[Spice-commits] 1031 commits - .gitignore MAINTAINERS Makefile Makefile.dis Makefile.hw Makefile.objs Makefile.target Makefile.user QMP/qmp-events.txt QMP/qmp-spec.txt VERSION arch_init.c arch_init.h audio/audio.c audio/winwaveaudio.c bitops.h block-migration.c block.c block.h block/blkdebug.c block/curl.c block/iscsi.c block/nbd.c block/qcow.c block/qcow2-cluster.c block/qcow2-refcount.c block/qcow2-snapshot.c block/qcow2.c block/qcow2.h block/qed-check.c block/qed.c block/qed.h block/raw-posix.c block/raw-win32.c block/raw.c block/rbd.c block/sheepdog.c block/vdi.c block/vmdk.c block/vpc.c block/vvfat.c block_int.h blockdev.c blockdev.h bsd-user/main.c compiler.h configure console.c coroutine-ucontext.c cpu-all.h cpu-common.h cpu-defs.h cpu-exec.c cpus.c cputlb.c cutils.c default-configs/arm-softmmu.mak default-configs/or32-linux-user.mak default-configs/or32-softmmu.mak default-configs/pci.mak default-configs/unicore32-softmmu.mak device_tree.c device_tree.h disas.c dma-helpers.c dma.h docs/bootindex.txt docs/qapi-code-gen.txt docs/specs docs/usb-storage.txt docs/writing-qmp-commands.txt docs/xbzrle.txt elf.h error.c error.h error_int.h event_notifier.c event_notifier.h exec-all.h exec-obsolete.h exec.c gdbstub.c hmp-commands.hx hmp.c hmp.h hw/9pfs hw/Makefile.objs hw/a15mpcore.c hw/a9mpcore.c hw/ac97.c hw/acpi.c hw/acpi_piix4.c hw/alpha_pci.c hw/alpha_typhoon.c hw/apic-msidef.h hw/apic.c hw/apic.h hw/apic_common.c hw/apic_internal.h hw/arm hw/arm-misc.h hw/arm11mpcore.c hw/arm_boot.c hw/arm_gic.c hw/arm_gic_common.c hw/arm_gic_internal.h hw/armv7m.c hw/armv7m_nvic.c hw/block-common.c hw/block-common.h hw/boards.h hw/bonito.c hw/bt-l2cap.c hw/cadence_gem.c hw/cadence_ttc.c hw/cirrus_vga.c hw/dec_pci.c hw/dec_pci.h hw/dp8393x.c hw/e1000.c hw/eepro100.c hw/es1370.c hw/escc.c hw/esp-pci.c hw/esp.c hw/esp.h hw/etraxfs_eth.c hw/exynos4210.c hw/exynos4210.h hw/exynos4210_gic.c hw/exynos4210_i2c.c hw/exynos4210_mct.c hw/exynos4210_pwm.c hw/exynos4210_rtc.c hw/exynos4_boards.c hw/fdc.c hw/fdc.h hw/framebuffer.c hw/grackle_pci.c hw/gt64xxx.c hw/hd-geometry.c hw/highbank.c hw/i386 hw/i82378.c hw/ide hw/ide.h hw/imx.h hw/imx_avic.c hw/imx_ccm.c hw/imx_serial.c hw/imx_timer.c hw/integratorcp.c hw/intel-hda.c hw/ioh3420.c hw/ivshmem.c hw/kvm hw/kzm.c hw/lan9118.c hw/lance.c hw/loader.c hw/lsi53c895a.c hw/mcf5208.c hw/mcf_fec.c hw/megasas.c hw/mfi.h hw/milkymist-minimac2.c hw/mips_jazz.c hw/mips_malta.c hw/mips_mipssim.c hw/mips_r4k.c hw/mipsnet.c hw/msi.c hw/msi.h hw/msix.c hw/msix.h hw/musicpal.c hw/ne2000-isa.c hw/ne2000.c hw/ne2000.h hw/null-machine.c hw/omap.h hw/opencores_eth.c hw/openpic.c hw/openrisc hw/openrisc_pic.c hw/openrisc_sim.c hw/openrisc_timer.c hw/pc.c hw/pc.h hw/pc_piix.c hw/pci.c hw/pci.h hw/pci_bridge.c hw/pci_bridge.h hw/pci_bridge_dev.c hw/pci_host.c hw/pci_host.h hw/pci_ids.h hw/pci_internals.h hw/pcnet-pci.c hw/pcnet.c hw/pcnet.h hw/petalogix_ml605_mmu.c hw/piix_pci.c hw/pl011.c hw/ppc hw/ppc440_bamboo.c hw /ppc4xx.h hw/ppc4xx_pci.c hw/ppc_mac.h hw/ppc_newworld.c hw/ppc_oldworld.c hw/ppc_prep.c hw/ppce500_mpc8544ds.c hw/ppce500_pci.c hw/ppce500_spin.c hw/prep_pci.c hw/puv3.c hw/puv3.h hw/puv3_dma.c hw/puv3_gpio.c hw/puv3_intc.c hw/puv3_ost.c hw/puv3_pm.c hw/pxa2xx.c hw/pxa2xx_pic.c hw/qdev-dma.h hw/qdev-monitor.c hw/qdev-properties.c hw/qdev.c hw/qdev.h hw/qxl.c hw/qxl.h hw/rtl8139.c hw/s390-virtio-bus.c hw/scsi-bus.c hw/scsi-defs.h hw/scsi-disk.c hw/scsi-generic.c hw/scsi.h hw/sd.c hw/sd.h hw/sh_serial.c hw/shpc.c hw/smc91c111.c hw/spapr.c hw/spapr.h hw/spapr_hcall.c hw/spapr_iommu.c hw/spapr_llan.c hw/spapr_pci.c hw/spapr_pci.h hw/spapr_vio.c hw/spapr_vio.h hw/spapr_vscsi.c hw/spapr_vty.c hw/ssd0323.c hw/stellaris_enet.c hw/stream.c hw/stream.h hw/sun4m.c hw/sun4u.c hw/unicore32 hw/unin_pci.c hw/usb hw/usb.h hw/versatilepb.c hw/vexpress.c hw/vga-isa-mm.c hw/vga-isa.c hw/vga-pci.c hw/vga-pci.h hw/vga.c hw/vga_int.h hw/vhost.c hw/vhost_net.c hw/vhost_net.h hw/virtio-balloon.c h w/virtio-blk.c hw/virtio-blk.h hw/virtio-net.c hw/virtio-pci.c hw/virtio-pci.h hw/virtio-scsi.c hw/virtio-scsi.h hw/virtio-serial-bus.c hw/virtio.c hw/virtio.h hw/vmware_vga.c hw/watchdog.c hw/wdt_i6300esb.c hw/xen-host-pci-device.c hw/xen-host-pci-device.h hw/xen_backend.c hw/xen_backend.h hw/xen_common.h hw/xen_console.c hw/xen_devconfig.c hw/xen_disk.c hw/xen_nic.c hw/xen_platform.c hw/xen_pt.c hw/xen_pt.h hw/xen_pt_config_init.c hw/xen_pt_msi.c hw/xenfb.c hw/xgmac.c hw/xics.c hw/xics.h hw/xilinx.h hw/xilinx_axidma.c hw/xilinx_axidma.h hw/xilinx_axienet.c hw/xilinx_ethlite.c hw/xio3130_downstream.c hw/xio3130_upstream.c hw/xtensa_lx60.c hw/xtensa_sim.c include/qemu iohandler.c iov.c iov.h json-parser.c kvm-all.c kvm-stub.c kvm.h linux-aio.c linux-headers/asm-s390 linux-headers/linux linux-user/alpha linux-user/cpu-uname.c linux-user/elfload.c linux-user/flatload.c linux-user/ioctls.h linux-user/main.c linux-user/mmap.c linux-user/openrisc linux-user/qemu.h linux-user/sign al.c linux-user/strace.c linux-user/strace.list linux-user/syscall.c linux-user/syscall_defs.h linux-user/syscall_types.h memory.c memory.h migration-tcp.c migration.c migration.h monitor.c monitor.h nbd.c net.c net.h net/Makefile.objs net/dump.c net/dump.h net/hub.c net/hub.h net/queue.c net/queue.h net/slirp.c net/slirp.h net/socket.c net/socket.h net/tap-aix.c net/tap-bsd.c net/tap-haiku.c net/tap-linux.c net/tap-solaris.c net/tap-win32.c net/tap.c net/tap.h net/vde.c net/vde.h os-posix.c osdep.c osdep.h oslib-posix.c page_cache.c pc-bios/README pc-bios/bios.bin pc-bios/keymaps pc-bios/mpc8544ds.dtb pc-bios/mpc8544ds.dts pc-bios/openbios-ppc pc-bios/openbios-sparc32 pc-bios/openbios-sparc64 pc-bios/slof.bin poison.h posix-aio-compat.c qapi-schema-guest.json qapi-schema.json qapi/Makefile.objs qapi/opts-visitor.c qapi/opts-visitor.h qapi/qapi-visit-core.c qapi/qapi-visit-core.h qapi/qmp-core.h qapi/qmp-dispatch.c qemu-bridge-helper.c qemu-char.c qemu-common.h qemu-config.c qemu-config.h qemu-coroutine-io.c qemu-doc.texi qemu-ga.c qemu-img.c qemu-img.texi qemu-io.c qemu-log.c qemu-log.h qemu-nbd.c qemu-option-internal.h qemu-option.c qemu-option.h qemu-options.hx qemu-seccomp.c qemu-seccomp.h qemu-sockets.c qemu-tech.texi qemu-thread-posix.c qemu-thread-win32.c qemu-thread.h qemu-timer.c qemu-tool.c qemu-user.c qemu_socket.h qerror.c qerror.h qga/Makefile.objs qga/commands-posix.c qga/commands-win32.c qlist.c qlist.h qmp-commands.hx qmp.c qom/object.c roms/Makefile roms/SLOF roms/config.vga.cirrus roms/config.vga.isavga roms/config.vga.qxl roms/config.vga.stdvga roms/config.vga.vmware roms/openbios roms/seabios rules.mak savevm.c scripts/checkpatch.pl scripts/kvm scripts/make-release scripts/qapi-commands.py scripts/qapi-types.py scripts/qapi-visit.py scripts/qapi.py scripts/simpletrace.py scripts/tracetool scripts/update-linux-headers.sh slirp/if.c slirp/libslirp.h slirp/main.h slirp/slirp.c slirp/tcp_subr.c softmmu-semi.h sysemu.h target-alp ha/cpu.h target-arm/arm-semi.c target-arm/cpu-qom.h target-arm/cpu.c target-arm/cpu.h target-arm/helper.c target-arm/helper.h target-arm/machine.c target-arm/neon_helper.c target-arm/op_helper.c target-arm/translate.c target-i386/Makefile.objs target-i386/cc_helper.c target-i386/cc_helper_template.h target-i386/cpu.c target-i386/cpu.h target-i386/excp_helper.c target-i386/fpu_helper.c target-i386/helper.c target-i386/helper.h target-i386/helper_template.h target-i386/int_helper.c target-i386/kvm-stub.c target-i386/kvm.c target-i386/kvm_i386.h target-i386/mem_helper.c target-i386/misc_helper.c target-i386/op_helper.c target-i386/ops_sse.h target-i386/ops_sse_header.h target-i386/seg_helper.c target-i386/shift_helper_template.h target-i386/smm_helper.c target-i386/svm_helper.c target-i386/translate.c target-mips/op_helper.c target-mips/translate.c target-openrisc/Makefile.objs target-openrisc/cpu.c target-openrisc/cpu.h target-openrisc/exception.c target-openrisc/exception.h t arget-openrisc/exception_helper.c target-openrisc/fpu_helper.c target-openrisc/helper.h target-openrisc/int_helper.c target-openrisc/interrupt.c target-openrisc/interrupt_helper.c target-openrisc/machine.c target-openrisc/mmu.c target-openrisc/mmu_helper.c target-openrisc/sys_helper.c target-openrisc/translate.c target-ppc/Makefile.objs target-ppc/cpu.h target-ppc/excp_helper.c target-ppc/fpu_helper.c target-ppc/helper.c target-ppc/helper.h target-ppc/int_helper.c target-ppc/kvm.c target-ppc/kvm_ppc.h target-ppc/mem_helper.c target-ppc/misc_helper.c target-ppc/mmu_helper.c target-ppc/mpic_helper.c target-ppc/op_helper.c target-ppc/timebase_helper.c target-ppc/translate.c target-ppc/translate_init.c target-s390x/Makefile.objs target-s390x/cpu.h target-s390x/interrupt.c target-s390x/kvm.c target-s390x/op_helper.c target-unicore32/Makefile.objs target-unicore32/cpu.c target-unicore32/cpu.h target-unicore32/helper.c target-unicore32/helper.h target-unicore32/machine.c target-uni core32/op_helper.c target-unicore32/softmmu.c target-unicore32/translate.c target-unicore32/ucf64_helper.c target-xtensa/cpu.h target-xtensa/helper.c target-xtensa/translate.c targphys.h tcg/arm tcg/ia64 tcg/mips tcg/ppc tcg/ppc64 tcg/tci tci.c tests/Makefile tests/check-qjson.c tests/fdc-test.c tests/hd-geo-test.c tests/libqtest.c tests/qemu-iotests tests/tcg tests/test-iov.c tests/test-qmp-commands.c tests/test-qmp-input-visitor.c trace-events trace/control.c trace/simple.c trace/simple.h ui/Makefile.objs ui/spice-display.c ui/vnc-auth-vencrypt.c ui/vnc-jobs-async.c ui/vnc-jobs-sync.c ui/vnc-jobs.c ui/vnc-jobs.h ui/vnc.c ui/vnc.h user-exec.c vl.c vmstate.h xen-all.c xen-mapcache.c

Gerd Hoffmann kraxel at kemper.freedesktop.org
Wed Aug 29 23:32:53 PDT 2012


 .gitignore                            |    6 
 MAINTAINERS                           |   41 
 Makefile                              |   85 
 Makefile.dis                          |    3 
 Makefile.hw                           |    7 
 Makefile.objs                         |   12 
 Makefile.target                       |    9 
 Makefile.user                         |    4 
 QMP/qmp-events.txt                    |  291 -
 QMP/qmp-spec.txt                      |   10 
 VERSION                               |    2 
 arch_init.c                           |  485 ++
 arch_init.h                           |    6 
 audio/audio.c                         |    1 
 audio/winwaveaudio.c                  |   12 
 bitops.h                              |  116 
 block-migration.c                     |  161 
 block.c                               |  475 --
 block.h                               |   77 
 block/blkdebug.c                      |  107 
 block/curl.c                          |    6 
 block/iscsi.c                         |  317 +
 block/nbd.c                           |   18 
 block/qcow.c                          |    4 
 block/qcow2-cluster.c                 |    5 
 block/qcow2-refcount.c                |    7 
 block/qcow2-snapshot.c                |    6 
 block/qcow2.c                         |  162 
 block/qcow2.h                         |   21 
 block/qed-check.c                     |   26 
 block/qed.c                           |   23 
 block/qed.h                           |    5 
 block/raw-posix.c                     |   55 
 block/raw-win32.c                     |    6 
 block/raw.c                           |    2 
 block/rbd.c                           |    4 
 block/sheepdog.c                      |  265 -
 block/vdi.c                           |    5 
 block/vmdk.c                          |   83 
 block/vpc.c                           |    4 
 block/vvfat.c                         |   74 
 block_int.h                           |   28 
 blockdev.c                            |   43 
 blockdev.h                            |    5 
 bsd-user/main.c                       |    4 
 compiler.h                            |    7 
 configure                             |  375 +-
 console.c                             |   26 
 coroutine-ucontext.c                  |   32 
 cpu-all.h                             |   32 
 cpu-common.h                          |    4 
 cpu-defs.h                            |   11 
 cpu-exec.c                            |   43 
 cpus.c                                |  112 
 cputlb.c                              |    4 
 cutils.c                              |  266 -
 default-configs/arm-softmmu.mak       |   18 
 default-configs/or32-linux-user.mak   |    1 
 default-configs/or32-softmmu.mak      |    4 
 default-configs/pci.mak               |    3 
 default-configs/unicore32-softmmu.mak |    4 
 dev/null                              |binary
 device_tree.c                         |  138 
 device_tree.h                         |   26 
 disas.c                               |   19 
 dma-helpers.c                         |  213 +
 dma.h                                 |  218 +
 docs/bootindex.txt                    |    2 
 docs/qapi-code-gen.txt                |    2 
 docs/specs/ppc-spapr-hcalls.txt       |   78 
 docs/specs/qcow2.txt                  |   14 
 docs/usb-storage.txt                  |   38 
 docs/writing-qmp-commands.txt         |   47 
 docs/xbzrle.txt                       |  128 
 elf.h                                 |    2 
 error.c                               |   96 
 error.h                               |   36 
 error_int.h                           |   29 
 event_notifier.c                      |   30 
 event_notifier.h                      |    8 
 exec-all.h                            |    2 
 exec-obsolete.h                       |   50 
 exec.c                                |  104 
 gdbstub.c                             |   64 
 hmp-commands.hx                       |   46 
 hmp.c                                 |  194 -
 hmp.h                                 |    7 
 hw/9pfs/virtio-9p.c                   |   23 
 hw/Makefile.objs                      |   34 
 hw/a15mpcore.c                        |    1 
 hw/a9mpcore.c                         |    2 
 hw/ac97.c                             |    3 
 hw/acpi.c                             |    2 
 hw/acpi_piix4.c                       |    1 
 hw/alpha_pci.c                        |    1 
 hw/alpha_typhoon.c                    |   26 
 hw/apic-msidef.h                      |   30 
 hw/apic.c                             |   38 
 hw/apic.h                             |    6 
 hw/apic_common.c                      |   20 
 hw/apic_internal.h                    |    1 
 hw/arm-misc.h                         |    6 
 hw/arm/Makefile.objs                  |   20 
 hw/arm11mpcore.c                      |    2 
 hw/arm_boot.c                         |   56 
 hw/arm_gic.c                          |  368 --
 hw/arm_gic_common.c                   |  184 +
 hw/arm_gic_internal.h                 |  136 
 hw/armv7m.c                           |    5 
 hw/armv7m_nvic.c                      |  157 
 hw/block-common.c                     |   64 
 hw/block-common.h                     |   79 
 hw/boards.h                           |    3 
 hw/bonito.c                           |  152 
 hw/bt-l2cap.c                         |   11 
 hw/cadence_gem.c                      |   16 
 hw/cadence_ttc.c                      |    2 
 hw/cirrus_vga.c                       |   10 
 hw/dec_pci.c                          |   31 
 hw/dec_pci.h                          |    2 
 hw/dp8393x.c                          |    9 
 hw/e1000.c                            |   15 
 hw/eepro100.c                         |   28 
 hw/es1370.c                           |    3 
 hw/escc.c                             |    1 
 hw/esp-pci.c                          |  518 ++
 hw/esp.c                              |  319 -
 hw/esp.h                              |  119 
 hw/etraxfs_eth.c                      |   10 
 hw/exynos4210.c                       |   69 
 hw/exynos4210.h                       |    5 
 hw/exynos4210_gic.c                   |   78 
 hw/exynos4210_i2c.c                   |  334 +
 hw/exynos4210_mct.c                   |    4 
 hw/exynos4210_pwm.c                   |    2 
 hw/exynos4210_rtc.c                   |  592 +++
 hw/exynos4_boards.c                   |    2 
 hw/fdc.c                              |  244 +
 hw/fdc.h                              |   10 
 hw/framebuffer.c                      |    2 
 hw/grackle_pci.c                      |   65 
 hw/gt64xxx.c                          |   67 
 hw/hd-geometry.c                      |  157 
 hw/highbank.c                         |    2 
 hw/i386/Makefile.objs                 |    2 
 hw/i82378.c                           |    1 
 hw/ide.h                              |    4 
 hw/ide/ahci.c                         |   75 
 hw/ide/ahci.h                         |    3 
 hw/ide/atapi.c                        |   31 
 hw/ide/cmd646.c                       |   10 
 hw/ide/core.c                         |   50 
 hw/ide/ich.c                          |    6 
 hw/ide/internal.h                     |    9 
 hw/ide/macio.c                        |    4 
 hw/ide/piix.c                         |    7 
 hw/ide/qdev.c                         |   42 
 hw/ide/via.c                          |    7 
 hw/imx.h                              |   34 
 hw/imx_avic.c                         |  408 ++
 hw/imx_ccm.c                          |  321 +
 hw/imx_serial.c                       |  467 ++
 hw/imx_timer.c                        |  689 +++
 hw/integratorcp.c                     |    2 
 hw/intel-hda.c                        |    3 
 hw/ioh3420.c                          |    8 
 hw/ivshmem.c                          |   88 
 hw/kvm/i8254.c                        |   52 
 hw/kvm/i8259.c                        |    2 
 hw/kvm/ioapic.c                       |    2 
 hw/kzm.c                              |  154 
 hw/lan9118.c                          |   16 
 hw/lance.c                            |    4 
 hw/loader.c                           |    4 
 hw/lsi53c895a.c                       |   55 
 hw/mcf5208.c                          |    2 
 hw/mcf_fec.c                          |    9 
 hw/megasas.c                          | 2209 ++++++++++++
 hw/mfi.h                              | 1249 +++++++
 hw/milkymist-minimac2.c               |    8 
 hw/mips_jazz.c                        |    2 
 hw/mips_malta.c                       |    1 
 hw/mips_mipssim.c                     |    2 
 hw/mips_r4k.c                         |    2 
 hw/mipsnet.c                          |    8 
 hw/msi.c                              |   17 
 hw/msi.h                              |    1 
 hw/msix.c                             |  286 -
 hw/msix.h                             |   19 
 hw/musicpal.c                         |    8 
 hw/ne2000-isa.c                       |    4 
 hw/ne2000.c                           |   21 
 hw/ne2000.h                           |    4 
 hw/null-machine.c                     |   40 
 hw/omap.h                             |  103 
 hw/opencores_eth.c                    |   10 
 hw/openpic.c                          |   17 
 hw/openrisc/Makefile.objs             |    3 
 hw/openrisc_pic.c                     |   60 
 hw/openrisc_sim.c                     |  150 
 hw/openrisc_timer.c                   |  101 
 hw/pc.c                               |  132 
 hw/pc.h                               |    4 
 hw/pc_piix.c                          |   48 
 hw/pci.c                              |   74 
 hw/pci.h                              |   67 
 hw/pci_bridge.c                       |    3 
 hw/pci_bridge.h                       |    2 
 hw/pci_bridge_dev.c                   |   13 
 hw/pci_host.c                         |   12 
 hw/pci_host.h                         |    5 
 hw/pci_ids.h                          |    4 
 hw/pci_internals.h                    |    3 
 hw/pcnet-pci.c                        |    9 
 hw/pcnet.c                            |    6 
 hw/pcnet.h                            |    6 
 hw/petalogix_ml605_mmu.c              |   24 
 hw/piix_pci.c                         |   42 
 hw/pl011.c                            |    4 
 hw/ppc/Makefile.objs                  |    6 
 hw/ppc/e500.c                         |  589 +++
 hw/ppc/e500.h                         |   21 
 hw/ppc/e500plat.c                     |   60 
 hw/ppc/mpc8544ds.c                    |   61 
 hw/ppc440_bamboo.c                    |    3 
 hw/ppc4xx.h                           |    2 
 hw/ppc4xx_pci.c                       |   27 
 hw/ppc_mac.h                          |    1 
 hw/ppc_newworld.c                     |    2 
 hw/ppc_oldworld.c                     |    2 
 hw/ppc_prep.c                         |    5 
 hw/ppce500_mpc8544ds.c                |  415 --
 hw/ppce500_pci.c                      |   24 
 hw/ppce500_spin.c                     |    2 
 hw/prep_pci.c                         |   33 
 hw/puv3.c                             |  131 
 hw/puv3.h                             |   49 
 hw/puv3_dma.c                         |  109 
 hw/puv3_gpio.c                        |  141 
 hw/puv3_intc.c                        |  135 
 hw/puv3_ost.c                         |  151 
 hw/puv3_pm.c                          |  149 
 hw/pxa2xx.c                           |  285 -
 hw/pxa2xx_pic.c                       |   53 
 hw/qdev-dma.h                         |   10 
 hw/qdev-monitor.c                     |   33 
 hw/qdev-properties.c                  |  323 +
 hw/qdev.c                             |    9 
 hw/qdev.h                             |   26 
 hw/qxl.c                              |  138 
 hw/qxl.h                              |    8 
 hw/rtl8139.c                          |   39 
 hw/s390-virtio-bus.c                  |    1 
 hw/scsi-bus.c                         |  294 +
 hw/scsi-defs.h                        |   19 
 hw/scsi-disk.c                        |  980 ++++-
 hw/scsi-generic.c                     |   13 
 hw/scsi.h                             |   15 
 hw/sd.c                               |   72 
 hw/sd.h                               |    6 
 hw/sh_serial.c                        |    6 
 hw/shpc.c                             |    1 
 hw/smc91c111.c                        |    8 
 hw/spapr.c                            |  161 
 hw/spapr.h                            |   36 
 hw/spapr_hcall.c                      |   68 
 hw/spapr_iommu.c                      |  262 +
 hw/spapr_llan.c                       |   71 
 hw/spapr_pci.c                        |  399 +-
 hw/spapr_pci.h                        |   42 
 hw/spapr_vio.c                        |  293 -
 hw/spapr_vio.h                        |   81 
 hw/spapr_vscsi.c                      |   30 
 hw/spapr_vty.c                        |    4 
 hw/ssd0323.c                          |    4 
 hw/stellaris_enet.c                   |    8 
 hw/stream.c                           |   23 
 hw/stream.h                           |   31 
 hw/sun4m.c                            |   18 
 hw/sun4u.c                            |    1 
 hw/unicore32/Makefile.objs            |    6 
 hw/unin_pci.c                         |  185 -
 hw/usb.h                              |    6 
 hw/usb/Makefile.objs                  |    1 
 hw/usb/bus.c                          |   13 
 hw/usb/core.c                         |   24 
 hw/usb/dev-network.c                  |   10 
 hw/usb/dev-storage.c                  |   21 
 hw/usb/dev-uas.c                      |  779 ++++
 hw/usb/hcd-ehci.c                     |  273 +
 hw/usb/hcd-ohci.c                     |   93 
 hw/usb/hcd-uhci.c                     |   21 
 hw/usb/host-linux.c                   |   95 
 hw/usb/libhw.c                        |   21 
 hw/usb/redirect.c                     |    2 
 hw/versatilepb.c                      |    2 
 hw/vexpress.c                         |   15 
 hw/vga-isa-mm.c                       |    5 
 hw/vga-isa.c                          |    8 
 hw/vga-pci.c                          |   10 
 hw/vga-pci.h                          |   12 
 hw/vga.c                              |   27 
 hw/vga_int.h                          |   10 
 hw/vhost.c                            |    4 
 hw/vhost_net.c                        |   26 
 hw/vhost_net.h                        |    2 
 hw/virtio-balloon.c                   |    4 
 hw/virtio-blk.c                       |   55 
 hw/virtio-blk.h                       |   10 
 hw/virtio-net.c                       |   26 
 hw/virtio-pci.c                       |  136 
 hw/virtio-pci.h                       |    1 
 hw/virtio-scsi.c                      |  116 
 hw/virtio-scsi.h                      |    9 
 hw/virtio-serial-bus.c                |   10 
 hw/virtio.c                           |   49 
 hw/virtio.h                           |    5 
 hw/vmware_vga.c                       |   22 
 hw/watchdog.c                         |    2 
 hw/wdt_i6300esb.c                     |    4 
 hw/xen-host-pci-device.c              |  396 ++
 hw/xen-host-pci-device.h              |   55 
 hw/xen_backend.c                      |    6 
 hw/xen_backend.h                      |    1 
 hw/xen_common.h                       |    9 
 hw/xen_console.c                      |    5 
 hw/xen_devconfig.c                    |   10 
 hw/xen_disk.c                         |    6 
 hw/xen_nic.c                          |   16 
 hw/xen_platform.c                     |   11 
 hw/xen_pt.c                           |  849 ++++
 hw/xen_pt.h                           |  301 +
 hw/xen_pt_config_init.c               | 1869 ++++++++++
 hw/xen_pt_msi.c                       |  620 +++
 hw/xenfb.c                            |   13 
 hw/xgmac.c                            |    8 
 hw/xics.c                             |   12 
 hw/xics.h                             |    5 
 hw/xilinx.h                           |   22 
 hw/xilinx_axidma.c                    |   74 
 hw/xilinx_axidma.h                    |   39 
 hw/xilinx_axienet.c                   |   41 
 hw/xilinx_ethlite.c                   |    8 
 hw/xio3130_downstream.c               |    8 
 hw/xio3130_upstream.c                 |    8 
 hw/xtensa_lx60.c                      |    8 
 hw/xtensa_sim.c                       |    5 
 include/qemu/cpu.h                    |    7 
 include/qemu/object.h                 |   46 
 include/qemu/page_cache.h             |   79 
 iohandler.c                           |    1 
 iov.c                                 |  200 -
 iov.h                                 |   77 
 json-parser.c                         |  230 -
 kvm-all.c                             |   92 
 kvm-stub.c                            |   19 
 kvm.h                                 |   64 
 linux-aio.c                           |    4 
 linux-headers/asm-s390/kvm.h          |    5 
 linux-headers/linux/kvm.h             |    1 
 linux-user/alpha/syscall_nr.h         |    2 
 linux-user/cpu-uname.c                |    5 
 linux-user/elfload.c                  |  202 -
 linux-user/flatload.c                 |    2 
 linux-user/ioctls.h                   |    4 
 linux-user/main.c                     |  160 
 linux-user/mmap.c                     |   30 
 linux-user/openrisc/syscall.h         |   24 
 linux-user/openrisc/syscall_nr.h      |  506 ++
 linux-user/openrisc/target_signal.h   |   26 
 linux-user/openrisc/termbits.h        |  294 +
 linux-user/qemu.h                     |   15 
 linux-user/signal.c                   |  245 +
 linux-user/strace.c                   |   12 
 linux-user/strace.list                |    3 
 linux-user/syscall.c                  |  175 -
 linux-user/syscall_defs.h             |  283 -
 linux-user/syscall_types.h            |    3 
 memory.c                              |   18 
 memory.h                              |    9 
 migration-tcp.c                       |   22 
 migration.c                           |  137 
 migration.h                           |   34 
 monitor.c                             |  473 +-
 monitor.h                             |    6 
 nbd.c                                 |    2 
 net.c                                 | 1069 +-----
 net.h                                 |  102 
 net/Makefile.objs                     |    2 
 net/dump.c                            |   49 
 net/dump.h                            |    5 
 net/hub.c                             |  339 +
 net/hub.h                             |   29 
 net/queue.c                           |   38 
 net/queue.h                           |   25 
 net/slirp.c                           |  196 -
 net/slirp.h                           |    4 
 net/socket.c                          |  246 -
 net/socket.h                          |    5 
 net/tap-aix.c                         |    2 
 net/tap-bsd.c                         |    2 
 net/tap-haiku.c                       |    2 
 net/tap-linux.c                       |    9 
 net/tap-solaris.c                     |    2 
 net/tap-win32.c                       |   36 
 net/tap.c                             |  192 -
 net/tap.h                             |   26 
 net/vde.c                             |   32 
 net/vde.h                             |    5 
 os-posix.c                            |    5 
 osdep.c                               |  151 
 osdep.h                               |   13 
 oslib-posix.c                         |    6 
 page_cache.c                          |  218 +
 pc-bios/README                        |    4 
 pc-bios/bios.bin                      |binary
 pc-bios/keymaps/fi                    |    2 
 pc-bios/mpc8544ds.dts                 |  119 
 pc-bios/openbios-ppc                  |binary
 pc-bios/openbios-sparc32              |binary
 pc-bios/openbios-sparc64              |binary
 pc-bios/slof.bin                      |binary
 poison.h                              |    1 
 posix-aio-compat.c                    |    8 
 qapi-schema-guest.json                |   20 
 qapi-schema.json                      |  833 ++++
 qapi/Makefile.objs                    |    2 
 qapi/opts-visitor.c                   |  427 ++
 qapi/opts-visitor.h                   |   31 
 qapi/qapi-visit-core.c                |   19 
 qapi/qapi-visit-core.h                |    3 
 qapi/qmp-core.h                       |    1 
 qapi/qmp-dispatch.c                   |   11 
 qemu-bridge-helper.c                  |   24 
 qemu-char.c                           |   21 
 qemu-common.h                         |  111 
 qemu-config.c                         |   30 
 qemu-config.h                         |    3 
 qemu-coroutine-io.c                   |   83 
 qemu-doc.texi                         |   17 
 qemu-ga.c                             |   10 
 qemu-img.c                            |   34 
 qemu-img.texi                         |   10 
 qemu-io.c                             |   16 
 qemu-log.c                            |   32 
 qemu-log.h                            |   19 
 qemu-nbd.c                            |   75 
 qemu-option-internal.h                |   53 
 qemu-option.c                         |   36 
 qemu-option.h                         |   12 
 qemu-options.hx                       |   90 
 qemu-seccomp.c                        |  141 
 qemu-seccomp.h                        |   22 
 qemu-sockets.c                        |   18 
 qemu-tech.texi                        |    2 
 qemu-thread-posix.c                   |    2 
 qemu-thread-win32.c                   |    2 
 qemu-thread.h                         |    3 
 qemu-timer.c                          |   12 
 qemu-tool.c                           |   25 
 qemu-user.c                           |   20 
 qemu_socket.h                         |    4 
 qerror.c                              |  516 --
 qerror.h                              |  168 
 qga/Makefile.objs                     |    2 
 qga/commands-posix.c                  |  114 
 qga/commands-win32.c                  |   11 
 qlist.c                               |   13 
 qlist.h                               |    1 
 qmp-commands.hx                       |  325 +
 qmp.c                                 |   62 
 qom/object.c                          |  225 -
 roms/Makefile                         |   17 
 roms/SLOF                             |    2 
 roms/config.vga.cirrus                |    3 
 roms/config.vga.isavga                |    3 
 roms/config.vga.qxl                   |    6 
 roms/config.vga.stdvga                |    3 
 roms/config.vga.vmware                |    6 
 roms/openbios                         |    2 
 roms/seabios                          |    2 
 rules.mak                             |    5 
 savevm.c                              |  262 +
 scripts/checkpatch.pl                 |    5 
 scripts/kvm/kvm_stat                  |   26 
 scripts/make-release                  |   24 
 scripts/qapi-commands.py              |    1 
 scripts/qapi-types.py                 |   17 
 scripts/qapi-visit.py                 |  150 
 scripts/qapi.py                       |   53 
 scripts/simpletrace.py                |  116 
 scripts/tracetool/backend/simple.py   |   90 
 scripts/update-linux-headers.sh       |    5 
 slirp/if.c                            |    5 
 slirp/libslirp.h                      |    1 
 slirp/main.h                          |    1 
 slirp/slirp.c                         |    3 
 slirp/tcp_subr.c                      |    7 
 softmmu-semi.h                        |    5 
 sysemu.h                              |    7 
 target-alpha/cpu.h                    |   15 
 target-arm/arm-semi.c                 |   15 
 target-arm/cpu-qom.h                  |    5 
 target-arm/cpu.c                      |  236 +
 target-arm/cpu.h                      |  263 +
 target-arm/helper.c                   | 2481 ++++++++------
 target-arm/helper.h                   |   11 
 target-arm/machine.c                  |   12 
 target-arm/neon_helper.c              |   26 
 target-arm/op_helper.c                |   44 
 target-arm/translate.c                |  488 --
 target-i386/Makefile.objs             |    7 
 target-i386/cc_helper.c               |  380 ++
 target-i386/cc_helper_template.h      |  277 +
 target-i386/cpu.c                     |   68 
 target-i386/cpu.h                     |   68 
 target-i386/excp_helper.c             |  129 
 target-i386/fpu_helper.c              | 1289 +++++++
 target-i386/helper.c                  |   21 
 target-i386/helper.h                  |  356 +-
 target-i386/helper_template.h         |  334 -
 target-i386/int_helper.c              |  500 ++
 target-i386/kvm-stub.c                |   18 
 target-i386/kvm.c                     |   26 
 target-i386/kvm_i386.h                |   16 
 target-i386/mem_helper.c              |  155 
 target-i386/misc_helper.c             |  602 +++
 target-i386/op_helper.c               | 5923 ----------------------------------
 target-i386/ops_sse.h                 | 1237 +++----
 target-i386/ops_sse_header.h          |  334 -
 target-i386/seg_helper.c              | 2471 ++++++++++++++
 target-i386/shift_helper_template.h   |  112 
 target-i386/smm_helper.c              |  301 +
 target-i386/svm_helper.c              |  715 ++++
 target-i386/translate.c               | 1048 +++---
 target-mips/op_helper.c               |   75 
 target-mips/translate.c               |   38 
 target-openrisc/Makefile.objs         |    4 
 target-openrisc/cpu.c                 |  220 +
 target-openrisc/cpu.h                 |  458 ++
 target-openrisc/exception.c           |   27 
 target-openrisc/exception.h           |   28 
 target-openrisc/exception_helper.c    |   29 
 target-openrisc/fpu_helper.c          |  300 +
 target-openrisc/helper.h              |   70 
 target-openrisc/int_helper.c          |   79 
 target-openrisc/interrupt.c           |   74 
 target-openrisc/interrupt_helper.c    |   57 
 target-openrisc/machine.c             |   47 
 target-openrisc/mmu.c                 |  243 +
 target-openrisc/mmu_helper.c          |   63 
 target-openrisc/sys_helper.c          |  287 +
 target-openrisc/translate.c           | 1835 ++++++++++
 target-ppc/Makefile.objs              |   14 
 target-ppc/cpu.h                      |   88 
 target-ppc/excp_helper.c              |  969 +++++
 target-ppc/fpu_helper.c               | 1740 +++++++++
 target-ppc/helper.c                   | 3168 ------------------
 target-ppc/helper.h                   |  573 +--
 target-ppc/int_helper.c               | 1564 ++++++++
 target-ppc/kvm.c                      |  214 +
 target-ppc/kvm_ppc.h                  |    5 
 target-ppc/mem_helper.c               |  295 +
 target-ppc/misc_helper.c              |  124 
 target-ppc/mmu_helper.c               | 3326 +++++++++++++++++++
 target-ppc/mpic_helper.c              |   35 
 target-ppc/op_helper.c                | 4568 --------------------------
 target-ppc/timebase_helper.c          |  159 
 target-ppc/translate.c                |  462 +-
 target-ppc/translate_init.c           |  275 +
 target-s390x/Makefile.objs            |    2 
 target-s390x/cpu.h                    |    3 
 target-s390x/interrupt.c              |   29 
 target-s390x/kvm.c                    |   41 
 target-s390x/op_helper.c              |   43 
 target-unicore32/Makefile.objs        |    4 
 target-unicore32/cpu.c                |   19 
 target-unicore32/cpu.h                |   18 
 target-unicore32/helper.c             |  511 --
 target-unicore32/helper.h             |   17 
 target-unicore32/machine.c            |   23 
 target-unicore32/op_helper.c          |   44 
 target-unicore32/softmmu.c            |  267 +
 target-unicore32/translate.c          |  159 
 target-unicore32/ucf64_helper.c       |  345 +
 target-xtensa/cpu.h                   |    6 
 target-xtensa/helper.c                |    8 
 target-xtensa/translate.c             |   16 
 targphys.h                            |   16 
 tcg/arm/tcg-target.c                  |  237 -
 tcg/ia64/tcg-target.c                 |   58 
 tcg/mips/tcg-target.c                 |  158 
 tcg/ppc/tcg-target.c                  |    2 
 tcg/ppc64/tcg-target.c                |    2 
 tcg/tci/tcg-target.c                  |    2 
 tci.c                                 |    1 
 tests/Makefile                        |    8 
 tests/check-qjson.c                   |   53 
 tests/fdc-test.c                      |  102 
 tests/hd-geo-test.c                   |  428 ++
 tests/libqtest.c                      |   35 
 tests/qemu-iotests/030                |    6 
 tests/qemu-iotests/031.out            |   20 
 tests/qemu-iotests/036.out            |    4 
 tests/qemu-iotests/039                |  137 
 tests/qemu-iotests/039.out            |   59 
 tests/qemu-iotests/common             |   11 
 tests/qemu-iotests/common.rc          |   43 
 tests/qemu-iotests/group              |    1 
 tests/qemu-iotests/qed.py             |  235 +
 tests/tcg/openrisc/Makefile           |   71 
 tests/tcg/openrisc/test_add.c         |   43 
 tests/tcg/openrisc/test_addc.c        |   38 
 tests/tcg/openrisc/test_addi.c        |   33 
 tests/tcg/openrisc/test_addic.c       |   33 
 tests/tcg/openrisc/test_and_or.c      |   65 
 tests/tcg/openrisc/test_bf.c          |   47 
 tests/tcg/openrisc/test_bnf.c         |   51 
 tests/tcg/openrisc/test_div.c         |   54 
 tests/tcg/openrisc/test_divu.c        |   34 
 tests/tcg/openrisc/test_extx.c        |   78 
 tests/tcg/openrisc/test_fx.c          |   57 
 tests/tcg/openrisc/test_j.c           |   26 
 tests/tcg/openrisc/test_jal.c         |   26 
 tests/tcg/openrisc/test_lf_add.c      |   39 
 tests/tcg/openrisc/test_lf_div.c      |   37 
 tests/tcg/openrisc/test_lf_eqs.c      |   88 
 tests/tcg/openrisc/test_lf_ges.c      |   88 
 tests/tcg/openrisc/test_lf_gts.c      |   86 
 tests/tcg/openrisc/test_lf_les.c      |   88 
 tests/tcg/openrisc/test_lf_lts.c      |   92 
 tests/tcg/openrisc/test_lf_mul.c      |   22 
 tests/tcg/openrisc/test_lf_nes.c      |   89 
 tests/tcg/openrisc/test_lf_rem.c      |   32 
 tests/tcg/openrisc/test_lf_sub.c      |   35 
 tests/tcg/openrisc/test_logic.c       |  105 
 tests/tcg/openrisc/test_lx.c          |   84 
 tests/tcg/openrisc/test_movhi.c       |   31 
 tests/tcg/openrisc/test_mul.c         |   61 
 tests/tcg/openrisc/test_muli.c        |   48 
 tests/tcg/openrisc/test_mulu.c        |   48 
 tests/tcg/openrisc/test_sfeq.c        |   43 
 tests/tcg/openrisc/test_sfeqi.c       |   39 
 tests/tcg/openrisc/test_sfges.c       |   44 
 tests/tcg/openrisc/test_sfgesi.c      |   40 
 tests/tcg/openrisc/test_sfgeu.c       |   44 
 tests/tcg/openrisc/test_sfgeui.c      |   41 
 tests/tcg/openrisc/test_sfgts.c       |   45 
 tests/tcg/openrisc/test_sfgtsi.c      |   41 
 tests/tcg/openrisc/test_sfgtu.c       |   43 
 tests/tcg/openrisc/test_sfgtui.c      |   42 
 tests/tcg/openrisc/test_sfles.c       |   26 
 tests/tcg/openrisc/test_sflesi.c      |   39 
 tests/tcg/openrisc/test_sfleu.c       |   43 
 tests/tcg/openrisc/test_sfleui.c      |   39 
 tests/tcg/openrisc/test_sflts.c       |   43 
 tests/tcg/openrisc/test_sfltsi.c      |   39 
 tests/tcg/openrisc/test_sfltu.c       |   43 
 tests/tcg/openrisc/test_sfltui.c      |   39 
 tests/tcg/openrisc/test_sfne.c        |   43 
 tests/tcg/openrisc/test_sfnei.c       |   39 
 tests/tcg/openrisc/test_sub.c         |   35 
 tests/test-iov.c                      |  260 +
 tests/test-qmp-commands.c             |   42 
 tests/test-qmp-input-visitor.c        |   24 
 trace-events                          |  140 
 trace/control.c                       |    3 
 trace/simple.c                        |  282 -
 trace/simple.h                        |   39 
 ui/Makefile.objs                      |    6 
 ui/spice-display.c                    |    2 
 ui/vnc-auth-vencrypt.c                |    3 
 ui/vnc-jobs-async.c                   |  351 --
 ui/vnc-jobs-sync.c                    |   73 
 ui/vnc-jobs.c                         |  351 ++
 ui/vnc-jobs.h                         |   16 
 ui/vnc.c                              |   35 
 ui/vnc.h                              |   17 
 user-exec.c                           |   21 
 vl.c                                  |  200 -
 vmstate.h                             |   18 
 xen-all.c                             |   42 
 xen-mapcache.c                        |    9 
 683 files changed, 62046 insertions(+), 27771 deletions(-)

New commits:
commit 18fec301cd2a38f72a5eeba2656a0c5b4fa69fb7
Author: Aurelien Jarno <aurelien at aurel32.net>
Date:   Mon Aug 27 22:13:27 2012 +0200

    tcg/mips: fix broken CONFIG_TCG_PASS_AREG0 code
    
    The CONFIG_TCG_PASS_AREG0 code for calling ld/st helpers was
    broken in that it did not respect the ABI requirement that 64
    bit values were passed in even-odd register pairs. The simplest
    way to fix this is to implement some new utility functions
    for marshalling function arguments into the correct registers
    and stack, so that the code which sets up the address and
    data arguments does not need to care whether there has been
    a preceding env argument.
    
    Based on commit 9716ef3b for ARM by Peter Maydell.
    
    Signed-off-by: Aurelien Jarno <aurelien at aurel32.net>
    Reviewed-by: Peter Maydell <peter.maydell at linaro.org>

diff --git a/tcg/mips/tcg-target.c b/tcg/mips/tcg-target.c
index 393ba07..1006e28 100644
--- a/tcg/mips/tcg-target.c
+++ b/tcg/mips/tcg-target.c
@@ -217,6 +217,9 @@ static int target_parse_constraint(TCGArgConstraint *ct, const char **pct_str)
         tcg_regset_set(ct->u.regs, 0xffffffff);
 #if defined(CONFIG_SOFTMMU)
         tcg_regset_reset_reg(ct->u.regs, TCG_REG_A0);
+# if defined(CONFIG_TCG_PASS_AREG0) && (TARGET_LONG_BITS == 64)
+        tcg_regset_reset_reg(ct->u.regs, TCG_REG_A2);
+# endif
 #endif
         break;
     case 'S': /* qemu_st constraint */
@@ -224,10 +227,14 @@ static int target_parse_constraint(TCGArgConstraint *ct, const char **pct_str)
         tcg_regset_set(ct->u.regs, 0xffffffff);
         tcg_regset_reset_reg(ct->u.regs, TCG_REG_A0);
 #if defined(CONFIG_SOFTMMU)
-# if TARGET_LONG_BITS == 64
+# if (defined(CONFIG_TCG_PASS_AREG0) && TARGET_LONG_BITS == 32) || \
+     (!defined(CONFIG_TCG_PASS_AREG0) && TARGET_LONG_BITS == 64)
         tcg_regset_reset_reg(ct->u.regs, TCG_REG_A1);
 # endif
         tcg_regset_reset_reg(ct->u.regs, TCG_REG_A2);
+# if defined(CONFIG_TCG_PASS_AREG0) && TARGET_LONG_BITS == 64
+        tcg_regset_reset_reg(ct->u.regs, TCG_REG_A3);
+# endif
 #endif
         break;
     case 'I':
@@ -382,7 +389,10 @@ static inline void tcg_out_nop(TCGContext *s)
 static inline void tcg_out_mov(TCGContext *s, TCGType type,
                                TCGReg ret, TCGReg arg)
 {
-    tcg_out_opc_reg(s, OPC_ADDU, ret, arg, TCG_REG_ZERO);
+    /* Simple reg-reg move, optimising out the 'do nothing' case */
+    if (ret != arg) {
+        tcg_out_opc_reg(s, OPC_ADDU, ret, arg, TCG_REG_ZERO);
+    }
 }
 
 static inline void tcg_out_movi(TCGContext *s, TCGType type,
@@ -503,6 +513,67 @@ static inline void tcg_out_addi(TCGContext *s, int reg, tcg_target_long val)
     }
 }
 
+/* Helper routines for marshalling helper function arguments into
+ * the correct registers and stack.
+ * arg_num is where we want to put this argument, and is updated to be ready
+ * for the next call. arg is the argument itself. Note that arg_num 0..3 is
+ * real registers, 4+ on stack.
+ *
+ * We provide routines for arguments which are: immediate, 32 bit
+ * value in register, 16 and 8 bit values in register (which must be zero
+ * extended before use) and 64 bit value in a lo:hi register pair.
+ */
+#define DEFINE_TCG_OUT_CALL_IARG(NAME, ARGPARAM)                               \
+    static inline void NAME(TCGContext *s, int *arg_num, ARGPARAM)             \
+    {                                                                          \
+    if (*arg_num < 4) {                                                        \
+        DEFINE_TCG_OUT_CALL_IARG_GET_ARG(tcg_target_call_iarg_regs[*arg_num]); \
+    } else {                                                                   \
+        DEFINE_TCG_OUT_CALL_IARG_GET_ARG(TCG_REG_AT);                          \
+        tcg_out_st(s, TCG_TYPE_I32, TCG_REG_AT, TCG_REG_SP, 4 * (*arg_num));   \
+    }                                                                          \
+    (*arg_num)++;                                                              \
+}
+#define DEFINE_TCG_OUT_CALL_IARG_GET_ARG(A) \
+    tcg_out_opc_imm(s, OPC_ANDI, A, arg, 0xff);
+DEFINE_TCG_OUT_CALL_IARG(tcg_out_call_iarg_reg8, TCGReg arg)
+#undef DEFINE_TCG_OUT_CALL_IARG_GET_ARG
+#define DEFINE_TCG_OUT_CALL_IARG_GET_ARG(A) \
+    tcg_out_opc_imm(s, OPC_ANDI, A, arg, 0xffff);
+DEFINE_TCG_OUT_CALL_IARG(tcg_out_call_iarg_reg16, TCGReg arg)
+#undef DEFINE_TCG_OUT_CALL_IARG_GET_ARG
+#define DEFINE_TCG_OUT_CALL_IARG_GET_ARG(A) \
+    tcg_out_movi(s, TCG_TYPE_I32, A, arg);
+DEFINE_TCG_OUT_CALL_IARG(tcg_out_call_iarg_imm32, uint32_t arg)
+#undef DEFINE_TCG_OUT_CALL_IARG_GET_ARG
+
+/* We don't use the macro for this one to avoid an unnecessary reg-reg
+   move when storing to the stack. */
+static inline void tcg_out_call_iarg_reg32(TCGContext *s, int *arg_num,
+                                           TCGReg arg)
+{
+    if (*arg_num < 4) {
+        tcg_out_mov(s, TCG_TYPE_I32, tcg_target_call_iarg_regs[*arg_num], arg);
+    } else {
+        tcg_out_st(s, TCG_TYPE_I32, arg, TCG_REG_SP, 4 * (*arg_num));
+    }
+    (*arg_num)++;
+}
+
+static inline void tcg_out_call_iarg_reg64(TCGContext *s, int *arg_num,
+                                           TCGReg arg_low, TCGReg arg_high)
+{
+    (*arg_num) = (*arg_num + 1) & ~1;
+
+#if defined(TCG_TARGET_WORDS_BIGENDIAN)
+    tcg_out_call_iarg_reg32(s, arg_num, arg_high);
+    tcg_out_call_iarg_reg32(s, arg_num, arg_low);
+#else
+    tcg_out_call_iarg_reg32(s, arg_num, arg_low);
+    tcg_out_call_iarg_reg32(s, arg_num, arg_high);
+#endif
+}
+
 static void tcg_out_brcond(TCGContext *s, TCGCond cond, int arg1,
                            int arg2, int label_index)
 {
@@ -792,18 +863,18 @@ static void *qemu_st_helpers[4] = {
 static void tcg_out_qemu_ld(TCGContext *s, const TCGArg *args,
                             int opc)
 {
-    int addr_regl, addr_reg1, addr_meml;
+    int addr_regl, addr_meml;
     int data_regl, data_regh, data_reg1, data_reg2;
     int mem_index, s_bits;
 #if defined(CONFIG_SOFTMMU)
     void *label1_ptr, *label2_ptr;
-    int sp_args;
+    int arg_num;
 #endif
 #if TARGET_LONG_BITS == 64
 # if defined(CONFIG_SOFTMMU)
     uint8_t *label3_ptr;
 # endif
-    int addr_regh, addr_reg2, addr_memh;
+    int addr_regh, addr_memh;
 #endif
     data_regl = *args++;
     if (opc == 3)
@@ -831,18 +902,13 @@ static void tcg_out_qemu_ld(TCGContext *s, const TCGArg *args,
     }
 #if TARGET_LONG_BITS == 64
 # if defined(TCG_TARGET_WORDS_BIGENDIAN)
-    addr_reg1 = addr_regh;
-    addr_reg2 = addr_regl;
     addr_memh = 0;
     addr_meml = 4;
 # else
-    addr_reg1 = addr_regl;
-    addr_reg2 = addr_regh;
     addr_memh = 4;
     addr_meml = 0;
 # endif
 #else
-    addr_reg1 = addr_regl;
     addr_meml = 0;
 #endif
 
@@ -875,22 +941,17 @@ static void tcg_out_qemu_ld(TCGContext *s, const TCGArg *args,
 # endif
 
     /* slow path */
-    sp_args = TCG_REG_A0;
-    tcg_out_mov(s, TCG_TYPE_I32, sp_args++, addr_reg1);
+    arg_num = 0;
+# ifdef CONFIG_TCG_PASS_AREG0
+    tcg_out_call_iarg_reg32(s, &arg_num, TCG_AREG0);
+# endif
 # if TARGET_LONG_BITS == 64
-    tcg_out_mov(s, TCG_TYPE_I32, sp_args++, addr_reg2);
+    tcg_out_call_iarg_reg64(s, &arg_num, addr_regl, addr_regh);
+# else
+    tcg_out_call_iarg_reg32(s, &arg_num, addr_regl);
 # endif
-    tcg_out_movi(s, TCG_TYPE_I32, sp_args++, mem_index);
+    tcg_out_call_iarg_imm32(s, &arg_num, mem_index);
     tcg_out_movi(s, TCG_TYPE_I32, TCG_REG_T9, (tcg_target_long)qemu_ld_helpers[s_bits]);
-#ifdef CONFIG_TCG_PASS_AREG0
-    /* XXX/FIXME: suboptimal and incorrect for 64 on 32 bit */
-    tcg_out_mov(s, TCG_TYPE_I32, tcg_target_call_iarg_regs[2],
-                tcg_target_call_iarg_regs[1]);
-    tcg_out_mov(s, TCG_TYPE_TL, tcg_target_call_iarg_regs[1],
-                tcg_target_call_iarg_regs[0]);
-    tcg_out_mov(s, TCG_TYPE_PTR, tcg_target_call_iarg_regs[0],
-                TCG_AREG0);
-#endif
     tcg_out_opc_reg(s, OPC_JALR, TCG_REG_RA, TCG_REG_T9, 0);
     tcg_out_nop(s);
 
@@ -991,18 +1052,18 @@ static void tcg_out_qemu_ld(TCGContext *s, const TCGArg *args,
 static void tcg_out_qemu_st(TCGContext *s, const TCGArg *args,
                             int opc)
 {
-    int addr_regl, addr_reg1, addr_meml;
+    int addr_regl, addr_meml;
     int data_regl, data_regh, data_reg1, data_reg2;
     int mem_index, s_bits;
 #if defined(CONFIG_SOFTMMU)
     uint8_t *label1_ptr, *label2_ptr;
-    int sp_args;
+    int arg_num;
 #endif
 #if TARGET_LONG_BITS == 64
 # if defined(CONFIG_SOFTMMU)
     uint8_t *label3_ptr;
 # endif
-    int addr_regh, addr_reg2, addr_memh;
+    int addr_regh, addr_memh;
 #endif
 
     data_regl = *args++;
@@ -1024,18 +1085,13 @@ static void tcg_out_qemu_st(TCGContext *s, const TCGArg *args,
 #if TARGET_LONG_BITS == 64
     addr_regh = *args++;
 # if defined(TCG_TARGET_WORDS_BIGENDIAN)
-    addr_reg1 = addr_regh;
-    addr_reg2 = addr_regl;
     addr_memh = 0;
     addr_meml = 4;
 # else
-    addr_reg1 = addr_regl;
-    addr_reg2 = addr_regh;
     addr_memh = 4;
     addr_meml = 0;
 # endif
 #else
-    addr_reg1 = addr_regl;
     addr_meml = 0;
 #endif
     mem_index = *args;
@@ -1070,49 +1126,33 @@ static void tcg_out_qemu_st(TCGContext *s, const TCGArg *args,
 # endif
 
     /* slow path */
-    sp_args = TCG_REG_A0;
-    tcg_out_mov(s, TCG_TYPE_I32, sp_args++, addr_reg1);
+    arg_num = 0;
+# ifdef CONFIG_TCG_PASS_AREG0
+    tcg_out_call_iarg_reg32(s, &arg_num, TCG_AREG0);
+# endif
 # if TARGET_LONG_BITS == 64
-    tcg_out_mov(s, TCG_TYPE_I32, sp_args++, addr_reg2);
+    tcg_out_call_iarg_reg64(s, &arg_num, addr_regl, addr_regh);
+# else
+    tcg_out_call_iarg_reg32(s, &arg_num, addr_regl);
 # endif
     switch(opc) {
     case 0:
-        tcg_out_opc_imm(s, OPC_ANDI, sp_args++, data_reg1, 0xff);
+        tcg_out_call_iarg_reg8(s, &arg_num, data_regl);
         break;
     case 1:
-        tcg_out_opc_imm(s, OPC_ANDI, sp_args++, data_reg1, 0xffff);
+        tcg_out_call_iarg_reg16(s, &arg_num, data_regl);
         break;
     case 2:
-        tcg_out_mov(s, TCG_TYPE_I32, sp_args++, data_reg1);
+        tcg_out_call_iarg_reg32(s, &arg_num, data_regl);
         break;
     case 3:
-        sp_args = (sp_args + 1) & ~1;
-        tcg_out_mov(s, TCG_TYPE_I32, sp_args++, data_reg1);
-        tcg_out_mov(s, TCG_TYPE_I32, sp_args++, data_reg2);
+        tcg_out_call_iarg_reg64(s, &arg_num, data_regl, data_regh);
         break;
     default:
         tcg_abort();
     }
-    if (sp_args > TCG_REG_A3) {
-        /* Push mem_index on the stack */
-        tcg_out_movi(s, TCG_TYPE_I32, TCG_REG_AT, mem_index);
-        tcg_out_st(s, TCG_TYPE_I32, TCG_REG_AT, TCG_REG_SP, 16);
-    } else {
-        tcg_out_movi(s, TCG_TYPE_I32, sp_args, mem_index);
-    }
-
+    tcg_out_call_iarg_imm32(s, &arg_num, mem_index);
     tcg_out_movi(s, TCG_TYPE_I32, TCG_REG_T9, (tcg_target_long)qemu_st_helpers[s_bits]);
-#ifdef CONFIG_TCG_PASS_AREG0
-    /* XXX/FIXME: suboptimal and incorrect for 64 on 32 bit */
-    tcg_out_mov(s, TCG_TYPE_I32, tcg_target_call_iarg_regs[3],
-                tcg_target_call_iarg_regs[2]);
-    tcg_out_mov(s, TCG_TYPE_I64, tcg_target_call_iarg_regs[2],
-                tcg_target_call_iarg_regs[1]);
-    tcg_out_mov(s, TCG_TYPE_TL, tcg_target_call_iarg_regs[1],
-                tcg_target_call_iarg_regs[0]);
-    tcg_out_mov(s, TCG_TYPE_PTR, tcg_target_call_iarg_regs[0],
-                TCG_AREG0);
-#endif
     tcg_out_opc_reg(s, OPC_JALR, TCG_REG_RA, TCG_REG_T9, 0);
     tcg_out_nop(s);
 
commit ce6760404851f410d63519084329d54dc216ff93
Author: Aurelien Jarno <aurelien at aurel32.net>
Date:   Tue Aug 28 14:47:51 2012 +0200

    Update OpenBIOS PPC image
    
    Update OpenBIOS PPC image to SVN r1063 to fix issues introduced by
    commit 9e56edcf. The code change in this revision only affects PPC,
    so OpenBIOS SPARC images are not updated.
    
    Signed-off-by: Aurelien Jarno <aurelien at aurel32.net>

diff --git a/pc-bios/README b/pc-bios/README
index fc07ebc..3037130 100644
--- a/pc-bios/README
+++ b/pc-bios/README
@@ -12,7 +12,7 @@
   1275-1994 (referred to as Open Firmware) compliant firmware.
   The included images for PowerPC (for 32 and 64 bit PPC CPUs),
   Sparc32 and Sparc64 are built from OpenBIOS SVN revision
-  1062.
+  1063.
 
 - SLOF (Slimline Open Firmware) is a free IEEE 1275 Open Firmware
   implementation for certain IBM POWER hardware.  The sources are at
diff --git a/pc-bios/openbios-ppc b/pc-bios/openbios-ppc
index 1c3753d..5311eca 100644
Binary files a/pc-bios/openbios-ppc and b/pc-bios/openbios-ppc differ
diff --git a/roms/openbios b/roms/openbios
index d1d2787..f095c85 160000
--- a/roms/openbios
+++ b/roms/openbios
@@ -1 +1 @@
-Subproject commit d1d2787f87167edf487a60e61b9168514d5a7434
+Subproject commit f095c858136896d236931357b8d597f407286f71
commit 54cddd21b04013d5741a92d6828dea3bdb821482
Author: Aurelien Jarno <aurelien at aurel32.net>
Date:   Sun Aug 26 16:12:03 2012 +0200

    target-ppc: fix altivec instructions
    
    Altivec instructions are not working anymore in PowerPC emulation,
    following commit d15f74fb, which inverted two registers in the call
    to helper. Fix that.
    
    Reviewed-by: Peter Maydell <peter.maydell at linaro.org>
    Reviewed-by: Andreas Färber <afaerber at suse.de>
    Acked-by: Blue Swirl <blauwirbel at gmail.com>
    Signed-off-by: Aurelien Jarno <aurelien at aurel32.net>

diff --git a/target-ppc/translate.c b/target-ppc/translate.c
index 91eb7a0..ac915cc 100644
--- a/target-ppc/translate.c
+++ b/target-ppc/translate.c
@@ -6530,7 +6530,7 @@ static void glue(gen_, name)(DisasContext *ctx)                         \
     ra = gen_avr_ptr(rA(ctx->opcode));                                  \
     rb = gen_avr_ptr(rB(ctx->opcode));                                  \
     rd = gen_avr_ptr(rD(ctx->opcode));                                  \
-    gen_helper_##name(rd, cpu_env, ra, rb);                             \
+    gen_helper_##name(cpu_env, rd, ra, rb);                             \
     tcg_temp_free_ptr(ra);                                              \
     tcg_temp_free_ptr(rb);                                              \
     tcg_temp_free_ptr(rd);                                              \
commit 13ef70f64e9e4d7583fbd9918d8ea76194023d37
Author: munkyu.im <munkyu.im at samsung.com>
Date:   Tue Aug 28 16:42:06 2012 +0900

    audio/winwave: previous audio buffer should be flushed
    
    Winwave audio backend has problem with pausing and restart audio out.
    Unlike other backends, Winwave pausing API does not flush audio buffer.
    As a result, the previous audio data are played in front of
    user expected sound when user restart audio.
    So changes it to waveOutReset()
    
    Signed-off-by: Munkyu Im <munkyu.im at samsung.com>
    Signed-off-by: malc <av1474 at comtv.ru>

diff --git a/audio/winwaveaudio.c b/audio/winwaveaudio.c
index 663abb9..72babbf 100644
--- a/audio/winwaveaudio.c
+++ b/audio/winwaveaudio.c
@@ -349,21 +349,15 @@ static int winwave_ctl_out (HWVoiceOut *hw, int cmd, ...)
             else {
                 hw->poll_mode = 0;
             }
-            if (wave->paused) {
-                mr = waveOutRestart (wave->hwo);
-                if (mr != MMSYSERR_NOERROR) {
-                    winwave_logerr (mr, "waveOutRestart");
-                }
-                wave->paused = 0;
-            }
+            wave->paused = 0;
         }
         return 0;
 
     case VOICE_DISABLE:
         if (!wave->paused) {
-            mr = waveOutPause (wave->hwo);
+            mr = waveOutReset (wave->hwo);
             if (mr != MMSYSERR_NOERROR) {
-                winwave_logerr (mr, "waveOutPause");
+                winwave_logerr (mr, "waveOutReset");
             }
             else {
                 wave->paused = 1;
commit 36c6711bbe79642b0102416a9dd4243505e874a6
Author: Eric Johnson <ericj at mips.com>
Date:   Sat Sep 17 17:28:16 2011 -0700

    target-mips: allow microMIPS SWP and SDP to have RD equal to BASE
    
    The microMIPS SWP and SDP instructions do not modify GPRs.  So their
    behavior is well defined when RD equals BASE.  The MIPS Architecture
    Verification Programs (AVPs) check that they work as expected.  This
    is required for AVPs to pass.
    
    Signed-off-by: Eric Johnson <ericj at mips.com>
    Signed-off-by: Aurelien Jarno <aurelien at aurel32.net>

diff --git a/target-mips/translate.c b/target-mips/translate.c
index 0cff905..b293419 100644
--- a/target-mips/translate.c
+++ b/target-mips/translate.c
@@ -10031,7 +10031,7 @@ static void gen_ldst_pair (DisasContext *ctx, uint32_t opc, int rd,
     const char *opn = "ldst_pair";
     TCGv t0, t1;
 
-    if (ctx->hflags & MIPS_HFLAG_BMASK || rd == 31 || rd == base) {
+    if (ctx->hflags & MIPS_HFLAG_BMASK || rd == 31) {
         generate_exception(ctx, EXCP_RI);
         return;
     }
@@ -10043,6 +10043,10 @@ static void gen_ldst_pair (DisasContext *ctx, uint32_t opc, int rd,
 
     switch (opc) {
     case LWP:
+        if (rd == base) {
+            generate_exception(ctx, EXCP_RI);
+            return;
+        }
         save_cpu_state(ctx, 0);
         op_ld_lw(t1, t0, ctx);
         gen_store_gpr(t1, rd);
@@ -10064,6 +10068,10 @@ static void gen_ldst_pair (DisasContext *ctx, uint32_t opc, int rd,
         break;
 #ifdef TARGET_MIPS64
     case LDP:
+        if (rd == base) {
+            generate_exception(ctx, EXCP_RI);
+            return;
+        }
         save_cpu_state(ctx, 0);
         op_ld_ld(t1, t0, ctx);
         gen_store_gpr(t1, rd);
commit 2e15497c5b8d0d172dece0cf56e2d2e977a6b679
Author: Eric Johnson <ericj at mips.com>
Date:   Sat Sep 17 17:05:32 2011 -0700

    target-mips: add privilege level check to several Cop0 instructions
    
    The MIPS Architecture Verification Programs (AVPs) check privileged
    instructions for the required privilege level.  These changes are needed
    to pass the AVP suite.
    
    Signed-off-by: Eric Johnson <ericj at mips.com>
    Signed-off-by: Aurelien Jarno <aurelien at aurel32.net>

diff --git a/target-mips/translate.c b/target-mips/translate.c
index 35624e9..0cff905 100644
--- a/target-mips/translate.c
+++ b/target-mips/translate.c
@@ -5933,6 +5933,7 @@ static void gen_cp0 (CPUMIPSState *env, DisasContext *ctx, uint32_t opc, int rt,
 {
     const char *opn = "ldst";
 
+    check_cp0_enabled(ctx);
     switch (opc) {
     case OPC_MFC0:
         if (rt == 0) {
@@ -10121,6 +10122,7 @@ static void gen_pool32axf (CPUMIPSState *env, DisasContext *ctx, int rt, int rs,
 #ifndef CONFIG_USER_ONLY
     case MFC0:
     case MFC0 + 32:
+        check_cp0_enabled(ctx);
         if (rt == 0) {
             /* Treat as NOP. */
             break;
@@ -10129,6 +10131,7 @@ static void gen_pool32axf (CPUMIPSState *env, DisasContext *ctx, int rt, int rs,
         break;
     case MTC0:
     case MTC0 + 32:
+        check_cp0_enabled(ctx);
         {
             TCGv t0 = tcg_temp_new();
 
@@ -10225,10 +10228,12 @@ static void gen_pool32axf (CPUMIPSState *env, DisasContext *ctx, int rt, int rs,
     case 0x05:
         switch (minor) {
         case RDPGPR:
+            check_cp0_enabled(ctx);
             check_insn(env, ctx, ISA_MIPS32R2);
             gen_load_srsgpr(rt, rs);
             break;
         case WRPGPR:
+            check_cp0_enabled(ctx);
             check_insn(env, ctx, ISA_MIPS32R2);
             gen_store_srsgpr(rt, rs);
             break;
@@ -10269,6 +10274,7 @@ static void gen_pool32axf (CPUMIPSState *env, DisasContext *ctx, int rt, int rs,
     case 0x1d:
         switch (minor) {
         case DI:
+            check_cp0_enabled(ctx);
             {
                 TCGv t0 = tcg_temp_new();
 
@@ -10281,6 +10287,7 @@ static void gen_pool32axf (CPUMIPSState *env, DisasContext *ctx, int rt, int rs,
             }
             break;
         case EI:
+            check_cp0_enabled(ctx);
             {
                 TCGv t0 = tcg_temp_new();
 
@@ -10761,6 +10768,7 @@ static void decode_micromips32_opc (CPUMIPSState *env, DisasContext *ctx,
         minor = (ctx->opcode >> 12) & 0xf;
         switch (minor) {
         case CACHE:
+            check_cp0_enabled(ctx);
             /* Treat as no-op. */
             break;
         case LWC2:
@@ -12211,6 +12219,7 @@ static void decode_opc (CPUMIPSState *env, DisasContext *ctx, int *is_branch)
          gen_st_cond(ctx, op, rt, rs, imm);
          break;
     case OPC_CACHE:
+        check_cp0_enabled(ctx);
         check_insn(env, ctx, ISA_MIPS3 | ISA_MIPS32);
         /* Treat as NOP. */
         break;
commit 08406b035edc35fff4e3e14af3ec6f8f3a17a587
Author: malc <av1474 at comtv.ru>
Date:   Mon Aug 27 18:33:24 2012 +0400

    Revert "fix some debug printf format strings"
    
    This reverts commit 145c7c880ff520a9348cc2401ba291330b9606fe.
    
    Signed-off-by: malc <av1474 at comtv.ru>

diff --git a/hw/cirrus_vga.c b/hw/cirrus_vga.c
index 909899d..e8dcc6b 100644
--- a/hw/cirrus_vga.c
+++ b/hw/cirrus_vga.c
@@ -2055,8 +2055,8 @@ static void cirrus_vga_mem_write(void *opaque,
 	}
     } else {
 #ifdef DEBUG_CIRRUS
-        printf("cirrus: mem_writeb " TARGET_FMT_plx " value %" PRIx64 "\n",
-               addr, mem_value);
+        printf("cirrus: mem_writeb " TARGET_FMT_plx " value %02x\n", addr,
+               mem_value);
 #endif
     }
 }
diff --git a/hw/i8259.c b/hw/i8259.c
index 6587666..53daf78 100644
--- a/hw/i8259.c
+++ b/hw/i8259.c
@@ -355,8 +355,7 @@ static uint64_t pic_ioport_read(void *opaque, target_phys_addr_t addr,
             ret = s->imr;
         }
     }
-    DPRINTF("read: addr=0x%02" TARGET_PRIxPHYS " val=0x%02x\n",
-            addr, ret);
+    DPRINTF("read: addr=0x%02x val=0x%02x\n", addr, ret);
     return ret;
 }
 
diff --git a/hw/ide/cmd646.c b/hw/ide/cmd646.c
index dd2855e..e0b9443 100644
--- a/hw/ide/cmd646.c
+++ b/hw/ide/cmd646.c
@@ -154,7 +154,7 @@ static uint64_t bmdma_read(void *opaque, target_phys_addr_t addr,
         break;
     }
 #ifdef DEBUG_IDE
-    printf("bmdma: readb 0x%02" TARGET_PRIxPHYS " : 0x%02x\n", addr, val);
+    printf("bmdma: readb 0x%02x : 0x%02x\n", addr, val);
 #endif
     return val;
 }
@@ -170,8 +170,7 @@ static void bmdma_write(void *opaque, target_phys_addr_t addr,
     }
 
 #ifdef DEBUG_IDE
-    printf("bmdma: writeb 0x%02" TARGET_PRIxPHYS " : 0x%02" PRIx64 "\n",
-           addr, val);
+    printf("bmdma: writeb 0x%02x : 0x%02x\n", addr, val);
 #endif
     switch(addr & 3) {
     case 0:
diff --git a/hw/ide/via.c b/hw/ide/via.c
index 948a469..b20e4f0 100644
--- a/hw/ide/via.c
+++ b/hw/ide/via.c
@@ -55,7 +55,7 @@ static uint64_t bmdma_read(void *opaque, target_phys_addr_t addr,
         break;
     }
 #ifdef DEBUG_IDE
-    printf("bmdma: readb 0x%02" TARGET_PRIxPHYS " : 0x%02x\n", addr, val);
+    printf("bmdma: readb 0x%02x : 0x%02x\n", addr, val);
 #endif
     return val;
 }
@@ -70,8 +70,7 @@ static void bmdma_write(void *opaque, target_phys_addr_t addr,
     }
 
 #ifdef DEBUG_IDE
-    printf("bmdma: writeb 0x%02" TARGET_PRIxPHYS " : 0x%02" PRIx64 "\n",
-           addr, val);
+    printf("bmdma: writeb 0x%02x : 0x%02x\n", addr, val);
 #endif
     switch (addr & 3) {
     case 0:
commit 9f227bc3583ea082be7a79c14a5ffdade5844753
Author: malc <av1474 at comtv.ru>
Date:   Mon Aug 27 18:33:22 2012 +0400

    Revert "vl: fix -hdachs/-hda argument order parsing issues"
    
    This reverts commit 7764ae9671f1cd74227cf4404431dd5213799ef0.
    
    Signed-off-by: malc <av1474 at comtv.ru>

diff --git a/vl.c b/vl.c
index febfd62..7c577fa 100644
--- a/vl.c
+++ b/vl.c
@@ -2352,9 +2352,8 @@ int main(int argc, char **argv, char **envp)
     char boot_devices[33] = "cad"; /* default to HD->floppy->CD-ROM */
     DisplayState *ds;
     DisplayChangeListener *dcl;
-    char hdachs_params[512];  /* save -hdachs to apply to later -hda */
-    QemuOpts *hda_opts = NULL; /* save -hda to be modified by later -hdachs */
-    QemuOpts *opts, *machine_opts;
+    int cyls, heads, secs, translation;
+    QemuOpts *hda_opts = NULL, *opts, *machine_opts;
     QemuOptsList *olist;
     int optind;
     const char *optarg;
@@ -2409,7 +2408,8 @@ int main(int argc, char **argv, char **envp)
     cpu_model = NULL;
     ram_size = 0;
     snapshot = 0;
-    snprintf(hdachs_params, sizeof(hdachs_params), "%s", HD_OPTS);
+    cyls = heads = secs = 0;
+    translation = BIOS_ATA_TRANSLATION_AUTO;
 
     for (i = 0; i < MAX_NODES; i++) {
         node_mem[i] = 0;
@@ -2457,7 +2457,7 @@ int main(int argc, char **argv, char **envp)
         if (optind >= argc)
             break;
         if (argv[optind][0] != '-') {
-            hda_opts = drive_add(IF_DEFAULT, 0, argv[optind++], hdachs_params);
+	    hda_opts = drive_add(IF_DEFAULT, 0, argv[optind++], HD_OPTS);
         } else {
             const QEMUOption *popt;
 
@@ -2475,8 +2475,21 @@ int main(int argc, char **argv, char **envp)
                 cpu_model = optarg;
                 break;
             case QEMU_OPTION_hda:
-                hda_opts = drive_add(IF_DEFAULT, 0, optarg, hdachs_params);
-                break;
+                {
+                    char buf[256];
+                    if (cyls == 0)
+                        snprintf(buf, sizeof(buf), "%s", HD_OPTS);
+                    else
+                        snprintf(buf, sizeof(buf),
+                                 "%s,cyls=%d,heads=%d,secs=%d%s",
+                                 HD_OPTS , cyls, heads, secs,
+                                 translation == BIOS_ATA_TRANSLATION_LBA ?
+                                 ",trans=lba" :
+                                 translation == BIOS_ATA_TRANSLATION_NONE ?
+                                 ",trans=none" : "");
+                    drive_add(IF_DEFAULT, 0, optarg, buf);
+                    break;
+                }
             case QEMU_OPTION_hdb:
             case QEMU_OPTION_hdc:
             case QEMU_OPTION_hdd:
@@ -2510,10 +2523,7 @@ int main(int argc, char **argv, char **envp)
                 break;
             case QEMU_OPTION_hdachs:
                 {
-                    int cyls, heads, secs, translation;
                     const char *p;
-                    cyls = heads = secs = 0;
-                    translation = BIOS_ATA_TRANSLATION_AUTO;
                     p = optarg;
                     cyls = strtol(p, (char **)&p, 0);
                     if (cyls < 1 || cyls > 16383)
@@ -2545,14 +2555,7 @@ int main(int argc, char **argv, char **envp)
                         fprintf(stderr, "qemu: invalid physical CHS format\n");
                         exit(1);
                     }
-                    snprintf(hdachs_params, sizeof(hdachs_params),
-                             "%s,cyls=%d,heads=%d,secs=%d%s",
-                             HD_OPTS , cyls, heads, secs,
-                             translation == BIOS_ATA_TRANSLATION_LBA ?
-                             ",trans=lba" :
-                             translation == BIOS_ATA_TRANSLATION_NONE ?
-                             ",trans=none" : "");
-                    if (hda_opts != NULL) {
+		    if (hda_opts != NULL) {
                         char num[16];
                         snprintf(num, sizeof(num), "%d", cyls);
                         qemu_opt_set(hda_opts, "cyls", num);
commit e4558dcae8b9fcb2bcc312f1d04071b34adf0781
Author: malc <av1474 at comtv.ru>
Date:   Mon Aug 27 18:33:21 2012 +0400

    Revert "qemu-options.hx: mention retrace= VGA option"
    
    This reverts commit 39dda260628e5f2a3fd2ce2ec8a71f3d5ca309a9.
    
    Signed-off-by: malc <av1474 at comtv.ru>

diff --git a/qemu-options.hx b/qemu-options.hx
index 3e8085d..3c411c4 100644
--- a/qemu-options.hx
+++ b/qemu-options.hx
@@ -945,7 +945,7 @@ DEF("vga", HAS_ARG, QEMU_OPTION_vga,
     "-vga [std|cirrus|vmware|qxl|xenfb|none]\n"
     "                select video card type\n", QEMU_ARCH_ALL)
 STEXI
- at item -vga @var{type}[, at var{prop}=@var{value}[,...]]
+ at item -vga @var{type}
 @findex -vga
 Select type of VGA card to emulate. Valid values for @var{type} are
 @table @option
@@ -970,12 +970,6 @@ Recommended choice when using the spice protocol.
 @item none
 Disable VGA card.
 @end table
-Valid optional properties are
- at table @option
- at item retrace=dumb|precise
-Select dumb (default) or precise VGA retrace logic, useful for some
-DOS games/demos.
- at end table
 ETEXI
 
 DEF("full-screen", 0, QEMU_OPTION_full_screen,
commit df8002103c3e262dc40d7b5e0eb2171ba28b1d63
Author: malc <av1474 at comtv.ru>
Date:   Mon Aug 27 18:33:20 2012 +0400

    Revert "vga: add some optional CGA compatibility hacks"
    
    This reverts commit 482f7bf86b43af9f6903c52726fedf82b28bf953.
    
    Signed-off-by: malc <av1474 at comtv.ru>

diff --git a/hw/pc.h b/hw/pc.h
index 37e2f87..e4db071 100644
--- a/hw/pc.h
+++ b/hw/pc.h
@@ -176,10 +176,6 @@ enum vga_retrace_method {
 
 extern enum vga_retrace_method vga_retrace_method;
 
-#define VGA_CGA_HACK_PALETTE_BLANKING  (1<<0)
-#define VGA_CGA_HACK_FONT_HEIGHT       (1<<1)
-extern int vga_cga_hacks;
-
 static inline DeviceState *isa_vga_init(ISABus *bus)
 {
     ISADevice *dev;
diff --git a/hw/vga.c b/hw/vga.c
index a65fc26..f82ced8 100644
--- a/hw/vga.c
+++ b/hw/vga.c
@@ -547,31 +547,14 @@ void vga_ioport_write(void *opaque, uint32_t addr, uint32_t val)
         printf("vga: write CR%x = 0x%02x\n", s->cr_index, val);
 #endif
         /* handle CR0-7 protection */
-        if (s->cr[VGA_CRTC_V_SYNC_END] & VGA_CR11_LOCK_CR0_CR7) {
-            if (s->cr_index <= VGA_CRTC_OVERFLOW) {
-                /* can always write bit 4 of CR7 */
-                if (s->cr_index == VGA_CRTC_OVERFLOW) {
-                    s->cr[VGA_CRTC_OVERFLOW] =
-                        (s->cr[VGA_CRTC_OVERFLOW] & ~0x10) | (val & 0x10);
-                }
-                return;
-            } else if ((vga_cga_hacks & VGA_CGA_HACK_FONT_HEIGHT) &&
-                       !(s->sr[VGA_SEQ_CLOCK_MODE] & VGA_SR01_CHAR_CLK_8DOTS)) {
-                /* extra CGA compatibility hacks (not in standard VGA) */
-                if (s->cr_index == VGA_CRTC_MAX_SCAN &&
-                    val == 7 &&
-                    (s->cr[VGA_CRTC_MAX_SCAN] & 0xf) == 0xf) {
-                    return;
-                } else if (s->cr_index == VGA_CRTC_CURSOR_START &&
-                           val == 6 &&
-                           (s->cr[VGA_CRTC_MAX_SCAN] & 0xf) == 0xf) {
-                    val = 0xd;
-                } else if (s->cr_index == VGA_CRTC_CURSOR_END &&
-                           val == 7 &&
-                           (s->cr[VGA_CRTC_MAX_SCAN] & 0xf) == 0xf) {
-                    val = 0xe;
-                }
+        if ((s->cr[VGA_CRTC_V_SYNC_END] & VGA_CR11_LOCK_CR0_CR7) &&
+            s->cr_index <= VGA_CRTC_OVERFLOW) {
+            /* can always write bit 4 of CR7 */
+            if (s->cr_index == VGA_CRTC_OVERFLOW) {
+                s->cr[VGA_CRTC_OVERFLOW] = (s->cr[VGA_CRTC_OVERFLOW] & ~0x10) |
+                    (val & 0x10);
             }
+            return;
         }
         s->cr[s->cr_index] = val;
 
@@ -1903,10 +1886,7 @@ static void vga_update_display(void *opaque)
         /* nothing to do */
     } else {
         full_update = 0;
-        if (!(s->ar_index & 0x20) &&
-            /* extra CGA compatibility hacks (not in standard VGA */
-            (!(vga_cga_hacks & VGA_CGA_HACK_PALETTE_BLANKING) ||
-             (s->ar_index != 0 && s->ar_flip_flop))) {
+        if (!(s->ar_index & 0x20)) {
             graphic_mode = GMODE_BLANK;
         } else {
             graphic_mode = s->gr[VGA_GFX_MISC] & VGA_GR06_GRAPHICS_MODE;
diff --git a/qemu-options.hx b/qemu-options.hx
index 0682338..3e8085d 100644
--- a/qemu-options.hx
+++ b/qemu-options.hx
@@ -975,25 +975,6 @@ Valid optional properties are
 @item retrace=dumb|precise
 Select dumb (default) or precise VGA retrace logic, useful for some
 DOS games/demos.
- at item cga_hacks=@var{hack1}[+ at var{hack2},[...]]
-Enable various extra CGA compatibility hacks for programs that are
-trying to directly set CGA modes without BIOS assistance nor
-real knowledge of EGA/VGA.  These might only work with -vga std.
-Valid hacks are
- at table @option
- at item palette_blanking
-Wait to blank the screen until palette registers seem to actually be
-modified, instead of blanking it as soon as the palette address bit (0x10)
-of the attribute address register (0x3c0) is cleared.
- at item font_height
-Ignore attempts to change the VGA font height (index 9),
-cursor start (index 10), and cursor end (index 11) of the CRTC control
-registers (0x3d5) if trying to set them to the default for CGA fonts
-instead of VGA fonts.
- at item all
-Enable all CGA hacks.  More CGA hacks may be added in future versions
-of qemu.
- at end table
 @end table
 ETEXI
 
diff --git a/vl.c b/vl.c
index 16d04a2..febfd62 100644
--- a/vl.c
+++ b/vl.c
@@ -179,7 +179,6 @@ int main(int argc, char **argv)
 static const char *data_dir;
 const char *bios_name = NULL;
 enum vga_retrace_method vga_retrace_method = VGA_RETRACE_DUMB;
-int vga_cga_hacks = 0;
 DisplayType display_type = DT_DEFAULT;
 int display_remote = 0;
 const char* keyboard_layout = NULL;
@@ -1749,28 +1748,6 @@ static void select_vgahw (const char *p)
             else if (strstart(opts, "precise", &nextopt))
                 vga_retrace_method = VGA_RETRACE_PRECISE;
             else goto invalid_vga;
-        } else if (strstart(opts, ",cga_hacks=", &nextopt)) {
-            opts = nextopt;
-            while (*opts) {
-                if (strstart(opts, "all", &nextopt)) {
-                    opts = nextopt;
-                    vga_cga_hacks |= ~0;
-                } else if (strstart(opts, "palette_blanking", &nextopt)) {
-                    opts = nextopt;
-                    vga_cga_hacks |= VGA_CGA_HACK_PALETTE_BLANKING;
-                } else if (strstart(opts, "font_height", &nextopt)) {
-                    opts = nextopt;
-                    vga_cga_hacks |= VGA_CGA_HACK_FONT_HEIGHT;
-                } else {
-                    break;
-                }
-
-                if (*opts == '+') {
-                    opts++;
-                } else {
-                    break;
-                }
-            }
         } else goto invalid_vga;
         opts = nextopt;
     }
commit 4f213879f3cc695644cfd8bf603495e7316c78f6
Author: malc <av1474 at comtv.ru>
Date:   Mon Aug 27 18:33:12 2012 +0400

    Revert "i8259: add -no-spurious-interrupt-hack option"
    
    This reverts commit f278d4947fff814dcde2ef2acad36d172ff8be35.
    
    Signed-off-by: malc <av1474 at comtv.ru>

diff --git a/cpu-exec.c b/cpu-exec.c
index 625fbb0..134b3c4 100644
--- a/cpu-exec.c
+++ b/cpu-exec.c
@@ -329,15 +329,11 @@ int cpu_exec(CPUArchState *env)
                                                           0);
                             env->interrupt_request &= ~(CPU_INTERRUPT_HARD | CPU_INTERRUPT_VIRQ);
                             intno = cpu_get_pic_interrupt(env);
-                            if (intno >= 0) {
-                                qemu_log_mask(CPU_LOG_TB_IN_ASM,
-                                              "Servicing hardware INT=0x%02x\n",
-                                              intno);
-                                do_interrupt_x86_hardirq(env, intno, 1);
-                                /* ensure that no TB jump will be modified as
-                                   the program flow was changed */
-                                next_tb = 0;
-                            }
+                            qemu_log_mask(CPU_LOG_TB_IN_ASM, "Servicing hardware INT=0x%02x\n", intno);
+                            do_interrupt_x86_hardirq(env, intno, 1);
+                            /* ensure that no TB jump will be modified as
+                               the program flow was changed */
+                            next_tb = 0;
 #if !defined(CONFIG_USER_ONLY)
                         } else if ((interrupt_request & CPU_INTERRUPT_VIRQ) &&
                                    (env->eflags & IF_MASK) && 
diff --git a/hw/i8259.c b/hw/i8259.c
index 7ecb7e1..6587666 100644
--- a/hw/i8259.c
+++ b/hw/i8259.c
@@ -26,7 +26,6 @@
 #include "isa.h"
 #include "monitor.h"
 #include "qemu-timer.h"
-#include "sysemu.h"
 #include "i8259_internal.h"
 
 /* debug PIC */
@@ -194,20 +193,6 @@ int pic_read_irq(DeviceState *d)
                 pic_intack(slave_pic, irq2);
             } else {
                 /* spurious IRQ on slave controller */
-                if (no_spurious_interrupt_hack) {
-                    /* Pretend it was delivered and acknowledged.  If
-                     * it was spurious due to slave_pic->imr, then
-                     * as soon as the mask is cleared, the slave will
-                     * re-trigger IRQ2 on the master.  If it is spurious for
-                     * some other reason, make sure we don't keep trying
-                     * to half-process the same spurious interrupt over
-                     * and over again.
-                     */
-                    s->irr &= ~(1<<irq);
-                    s->last_irr &= ~(1<<irq);
-                    s->isr &= ~(1<<irq);
-                    return -1;
-                }
                 irq2 = 7;
             }
             intno = slave_pic->irq_base + irq2;
@@ -217,9 +202,6 @@ int pic_read_irq(DeviceState *d)
         pic_intack(s, irq);
     } else {
         /* spurious IRQ on host controller */
-        if (no_spurious_interrupt_hack) {
-            return -1;
-        }
         irq = 7;
         intno = s->irq_base + irq;
     }
diff --git a/qemu-options.hx b/qemu-options.hx
index 2a6d829..0682338 100644
--- a/qemu-options.hx
+++ b/qemu-options.hx
@@ -1189,18 +1189,6 @@ Windows 2000 is installed, you no longer need this option (this option
 slows down the IDE transfers).
 ETEXI
 
-DEF("no-spurious-interrupt-hack", 0, QEMU_OPTION_no_spurious_interrupt_hack,
-    "-no-spurious-interrupt-hack     disable delivery of spurious interrupts\n",
-    QEMU_ARCH_I386)
-STEXI
- at item -no-spurious-interrupt-hack
- at findex -no-spurious-interrupt-hack
-Use it as a workaround for operating systems that drive PICs in a way that
-can generate spurious interrupts, but the OS doesn't handle spurious
-interrupts gracefully.  (e.g. late 80s/early 90s versions of ATT UNIX
-and derivatives)
-ETEXI
-
 HXCOMM Deprecated by -rtc
 DEF("rtc-td-hack", 0, QEMU_OPTION_rtc_td_hack, "", QEMU_ARCH_I386)
 
diff --git a/sysemu.h b/sysemu.h
index 0170109..65552ac 100644
--- a/sysemu.h
+++ b/sysemu.h
@@ -117,7 +117,6 @@ extern int graphic_depth;
 extern DisplayType display_type;
 extern const char *keyboard_layout;
 extern int win2k_install_hack;
-extern int no_spurious_interrupt_hack;
 extern int alt_grab;
 extern int ctrl_grab;
 extern int usb_enabled;
diff --git a/vl.c b/vl.c
index 6de41c1..16d04a2 100644
--- a/vl.c
+++ b/vl.c
@@ -204,7 +204,6 @@ CharDriverState *serial_hds[MAX_SERIAL_PORTS];
 CharDriverState *parallel_hds[MAX_PARALLEL_PORTS];
 CharDriverState *virtcon_hds[MAX_VIRTIO_CONSOLES];
 int win2k_install_hack = 0;
-int no_spurious_interrupt_hack = 0;
 int usb_enabled = 0;
 int singlestep = 0;
 int smp_cpus = 1;
@@ -3047,9 +3046,6 @@ int main(int argc, char **argv, char **envp)
             case QEMU_OPTION_win2k_hack:
                 win2k_install_hack = 1;
                 break;
-            case QEMU_OPTION_no_spurious_interrupt_hack:
-                no_spurious_interrupt_hack = 1;
-                break;
             case QEMU_OPTION_rtc_td_hack: {
                 static GlobalProperty slew_lost_ticks[] = {
                     {
commit b3167288367f79754b74ad933146e37938ebff13
Author: Richard Henderson <rth at twiddle.net>
Date:   Fri Mar 30 13:16:37 2012 -0400

    mips-linux-user: Always support rdhwr.
    
    The kernel will emulate this instruction if it's not supported
    natively.  This insn is used for TLS, among other things, and
    so is required by modern glibc.
    
    Signed-off-by: Richard Henderson <rth at twiddle.net>
    Cc: Riku Voipio <riku.voipio at iki.fi>
    Signed-off-by: Aurelien Jarno <aurelien at aurel32.net>

diff --git a/target-mips/translate.c b/target-mips/translate.c
index f740a08..35624e9 100644
--- a/target-mips/translate.c
+++ b/target-mips/translate.c
@@ -8111,7 +8111,11 @@ gen_rdhwr (CPUMIPSState *env, DisasContext *ctx, int rt, int rd)
 {
     TCGv t0;
 
+#if !defined(CONFIG_USER_ONLY)
+    /* The Linux kernel will emulate rdhwr if it's not supported natively.
+       Therefore only check the ISA in system mode.  */
     check_insn(env, ctx, ISA_MIPS32R2);
+#endif
     t0 = tcg_temp_new();
 
     switch (rd) {
commit 05168674505153a641c7bfddb691d2eda11d13d1
Author: Richard Henderson <rth at twiddle.net>
Date:   Fri Mar 30 13:16:36 2012 -0400

    target-mips: Streamline indexed cp1 memory addressing.
    
    We've already eliminated both base and index being zero.
    
    Signed-off-by: Aurelien Jarno <aurelien at aurel32.net>

diff --git a/target-mips/translate.c b/target-mips/translate.c
index d812986..f740a08 100644
--- a/target-mips/translate.c
+++ b/target-mips/translate.c
@@ -7742,8 +7742,7 @@ static void gen_flt3_ldst (DisasContext *ctx, uint32_t opc,
     } else if (index == 0) {
         gen_load_gpr(t0, base);
     } else {
-        gen_load_gpr(t0, index);
-        gen_op_addr_add(ctx, t0, cpu_gpr[base], t0);
+        gen_op_addr_add(ctx, t0, cpu_gpr[base], cpu_gpr[index]);
     }
     /* Don't do NOP if destination is zero: we must perform the actual
        memory access. */
commit 13d24f49720a3e7b35a21222ef182c8513f139db
Author: Richard Sandiford <rdsandiford at googlemail.com>
Date:   Mon Aug 27 09:53:29 2012 +0100

    Fix order of CVT.PS.S operands
    
    The FS input to CVT.PS.S is the high half and FT is the low half.
    tcg_gen_concat_i32_i64 takes the low half first, so the operands
    were in the wrong order.
    
    Signed-off-by: Richard Sandiford <rdsandiford at googlemail.com>
    Signed-off-by: Aurelien Jarno <aurelien at aurel32.net>

diff --git a/target-mips/translate.c b/target-mips/translate.c
index 2589f63..d812986 100644
--- a/target-mips/translate.c
+++ b/target-mips/translate.c
@@ -6900,7 +6900,7 @@ static void gen_farith (DisasContext *ctx, enum fopcode op1,
 
             gen_load_fpr32(fp32_0, fs);
             gen_load_fpr32(fp32_1, ft);
-            tcg_gen_concat_i32_i64(fp64, fp32_0, fp32_1);
+            tcg_gen_concat_i32_i64(fp64, fp32_1, fp32_0);
             tcg_temp_free_i32(fp32_1);
             tcg_temp_free_i32(fp32_0);
             gen_store_fpr64(ctx, fp64, fd);
commit d22d7289877ecd3ef86570f6f6d0574da40711dc
Author: Richard Sandiford <rdsandiford at googlemail.com>
Date:   Mon Aug 27 09:50:38 2012 +0100

    Fix operands of RECIP2.S and RECIP2.PS
    
    Read the second input operand of RECIP2.S and RECIP2.PS from FT rather
    than FD.  RECIP2.D is already correct.
    
    Signed-off-by: Richard Sandiford <rdsandiford at googlemail.com>
    Signed-off-by: Aurelien Jarno <aurelien at aurel32.net>

diff --git a/target-mips/translate.c b/target-mips/translate.c
index d643676..2589f63 100644
--- a/target-mips/translate.c
+++ b/target-mips/translate.c
@@ -6805,7 +6805,7 @@ static void gen_farith (DisasContext *ctx, enum fopcode op1,
             TCGv_i32 fp1 = tcg_temp_new_i32();
 
             gen_load_fpr32(fp0, fs);
-            gen_load_fpr32(fp1, fd);
+            gen_load_fpr32(fp1, ft);
             gen_helper_float_recip2_s(fp0, fp0, fp1);
             tcg_temp_free_i32(fp1);
             gen_store_fpr32(fp0, fd);
@@ -7543,7 +7543,7 @@ static void gen_farith (DisasContext *ctx, enum fopcode op1,
             TCGv_i64 fp1 = tcg_temp_new_i64();
 
             gen_load_fpr64(ctx, fp0, fs);
-            gen_load_fpr64(ctx, fp1, fd);
+            gen_load_fpr64(ctx, fp1, ft);
             gen_helper_float_recip2_ps(fp0, fp0, fp1);
             tcg_temp_free_i64(fp1);
             gen_store_fpr64(ctx, fp0, fd);
commit d03c98d80ffb7c561d9e6874580f52fe7ecc8c6c
Author: Aurelien Jarno <aurelien at aurel32.net>
Date:   Sun Aug 26 00:45:27 2012 +0200

    tcg/ia64: fix and optimize ld/st slow path
    
    Store slow path has been broken in e141ab52d:
    - the arguments are shifted before the last one (mem_index) is written.
    - the shift is done for both slow and fast paths.
    
    Fix that. Also optimize a bit by bundling the move together. This still
    can be optimized, but it's better to wait for a decision to be taken on
    the arguments order.
    
    Signed-off-by: Aurelien Jarno <aurelien at aurel32.net>

diff --git a/tcg/ia64/tcg-target.c b/tcg/ia64/tcg-target.c
index b3c7db0..dc588db 100644
--- a/tcg/ia64/tcg-target.c
+++ b/tcg/ia64/tcg-target.c
@@ -1532,12 +1532,13 @@ static inline void tcg_out_qemu_ld(TCGContext *s, const TCGArg *args, int opc)
     }
 #ifdef CONFIG_TCG_PASS_AREG0
     /* XXX/FIXME: suboptimal */
-    tcg_out_mov(s, TCG_TYPE_I32, tcg_target_call_iarg_regs[2],
-                tcg_target_call_iarg_regs[1]);
-    tcg_out_mov(s, TCG_TYPE_TL, tcg_target_call_iarg_regs[1],
-                tcg_target_call_iarg_regs[0]);
-    tcg_out_mov(s, TCG_TYPE_PTR, tcg_target_call_iarg_regs[0],
-                TCG_AREG0);
+    tcg_out_bundle(s, mII,
+                   tcg_opc_a5 (TCG_REG_P7, OPC_ADDL_A5, TCG_REG_R58,
+                               mem_index, TCG_REG_R0),
+                   tcg_opc_a4 (TCG_REG_P7, OPC_ADDS_A4,
+                               TCG_REG_R57, 0, TCG_REG_R56),
+                   tcg_opc_a4 (TCG_REG_P7, OPC_ADDS_A4,
+                               TCG_REG_R56, 0, TCG_AREG0));
 #endif
     if (!bswap || s_bits == 0) {
         tcg_out_bundle(s, miB,
@@ -1659,15 +1660,21 @@ static inline void tcg_out_qemu_st(TCGContext *s, const TCGArg *args, int opc)
 
 #ifdef CONFIG_TCG_PASS_AREG0
     /* XXX/FIXME: suboptimal */
-    tcg_out_mov(s, TCG_TYPE_I32, tcg_target_call_iarg_regs[3],
-                tcg_target_call_iarg_regs[2]);
-    tcg_out_mov(s, TCG_TYPE_I64, tcg_target_call_iarg_regs[2],
-                tcg_target_call_iarg_regs[1]);
-    tcg_out_mov(s, TCG_TYPE_TL, tcg_target_call_iarg_regs[1],
-                tcg_target_call_iarg_regs[0]);
-    tcg_out_mov(s, TCG_TYPE_PTR, tcg_target_call_iarg_regs[0],
-                TCG_AREG0);
-#endif
+    tcg_out_bundle(s, mII,
+                   tcg_opc_a5 (TCG_REG_P7, OPC_ADDL_A5, TCG_REG_R59,
+                               mem_index, TCG_REG_R0),
+                   tcg_opc_a4 (TCG_REG_P7, OPC_ADDS_A4,
+                               TCG_REG_R58, 0, TCG_REG_R57),
+                   tcg_opc_a4 (TCG_REG_P7, OPC_ADDS_A4,
+                               TCG_REG_R57, 0, TCG_REG_R56));
+    tcg_out_bundle(s, miB,
+                   tcg_opc_m4 (TCG_REG_P6, opc_st_m4[opc],
+                               data_reg, TCG_REG_R3),
+                   tcg_opc_a4 (TCG_REG_P7, OPC_ADDS_A4,
+                               TCG_REG_R56, 0, TCG_AREG0),
+                   tcg_opc_b5 (TCG_REG_P7, OPC_BR_CALL_SPTK_MANY_B5,
+                               TCG_REG_B0, TCG_REG_B6));
+#else
     tcg_out_bundle(s, miB,
                    tcg_opc_m4 (TCG_REG_P6, opc_st_m4[opc],
                                data_reg, TCG_REG_R3),
@@ -1675,6 +1682,7 @@ static inline void tcg_out_qemu_st(TCGContext *s, const TCGArg *args, int opc)
                                mem_index, TCG_REG_R0),
                    tcg_opc_b5 (TCG_REG_P7, OPC_BR_CALL_SPTK_MANY_B5,
                                TCG_REG_B0, TCG_REG_B6));
+#endif
 }
 
 #else /* !CONFIG_SOFTMMU */
commit 18d445b443a5fa06a7c2819a170623b970afb3fb
Author: Aurelien Jarno <aurelien at aurel32.net>
Date:   Sat Aug 25 23:59:58 2012 +0200

    tcg/ia64: fix prologue/epilogue
    
    Prologue and epilogue code has been broken in cea5f9a28.
    
    Signed-off-by: Aurelien Jarno <aurelien at aurel32.net>

diff --git a/tcg/ia64/tcg-target.c b/tcg/ia64/tcg-target.c
index e02dacc..b3c7db0 100644
--- a/tcg/ia64/tcg-target.c
+++ b/tcg/ia64/tcg-target.c
@@ -107,7 +107,7 @@ enum {
 };
 
 static const int tcg_target_reg_alloc_order[] = {
-    TCG_REG_R34,
+    TCG_REG_R33,
     TCG_REG_R35,
     TCG_REG_R36,
     TCG_REG_R37,
@@ -2314,13 +2314,13 @@ static void tcg_target_qemu_prologue(TCGContext *s)
     s->code_ptr += 16; /* skip GP */
 
     /* prologue */
-    tcg_out_bundle(s, mII,
+    tcg_out_bundle(s, miI,
                    tcg_opc_m34(TCG_REG_P0, OPC_ALLOC_M34,
-                               TCG_REG_R33, 32, 24, 0),
+                               TCG_REG_R34, 32, 24, 0),
+                   tcg_opc_a4 (TCG_REG_P0, OPC_ADDS_A4,
+                               TCG_AREG0, 0, TCG_REG_R32),
                    tcg_opc_i21(TCG_REG_P0, OPC_MOV_I21,
-                               TCG_REG_B6, TCG_REG_R33, 0),
-                   tcg_opc_i22(TCG_REG_P0, OPC_MOV_I22,
-                               TCG_REG_R32, TCG_REG_B0));
+                               TCG_REG_B6, TCG_REG_R33, 0));
 
     /* ??? If GUEST_BASE < 0x200000, we could load the register via
        an ADDL in the M slot of the next bundle.  */
@@ -2335,9 +2335,9 @@ static void tcg_target_qemu_prologue(TCGContext *s)
 
     tcg_out_bundle(s, miB,
                    tcg_opc_a4 (TCG_REG_P0, OPC_ADDS_A4,
-                               TCG_AREG0, 0, TCG_REG_R32),
-                   tcg_opc_a4 (TCG_REG_P0, OPC_ADDS_A4,
                                TCG_REG_R12, -frame_size, TCG_REG_R12),
+                   tcg_opc_i22(TCG_REG_P0, OPC_MOV_I22,
+                               TCG_REG_R32, TCG_REG_B0),
                    tcg_opc_b4 (TCG_REG_P0, OPC_BR_SPTK_MANY_B4, TCG_REG_B6));
 
     /* epilogue */
@@ -2351,7 +2351,7 @@ static void tcg_target_qemu_prologue(TCGContext *s)
     tcg_out_bundle(s, miB,
                    tcg_opc_m48(TCG_REG_P0, OPC_NOP_M48, 0),
                    tcg_opc_i26(TCG_REG_P0, OPC_MOV_I_I26,
-                               TCG_REG_PFS, TCG_REG_R33),
+                               TCG_REG_PFS, TCG_REG_R34),
                    tcg_opc_b4 (TCG_REG_P0, OPC_BR_RET_SPTK_MANY_B4,
                                TCG_REG_B0));
 }
@@ -2403,7 +2403,7 @@ static void tcg_target_init(TCGContext *s)
     tcg_regset_set_reg(s->reserved_regs, TCG_REG_R12);  /* stack pointer */
     tcg_regset_set_reg(s->reserved_regs, TCG_REG_R13);  /* thread pointer */
     tcg_regset_set_reg(s->reserved_regs, TCG_REG_R32);  /* return address */
-    tcg_regset_set_reg(s->reserved_regs, TCG_REG_R33);  /* PFS */
+    tcg_regset_set_reg(s->reserved_regs, TCG_REG_R34);  /* PFS */
 
     /* The following 3 are not in use, are call-saved, but *not* saved
        by the prologue.  Therefore we cannot use them without modifying
commit 9716ef3b1b48ebbb4b6515fb4685a5db96ce41d9
Author: Peter Maydell <peter.maydell at linaro.org>
Date:   Sun Aug 26 14:40:02 2012 +0100

    tcg/arm: Fix broken CONFIG_TCG_PASS_AREG0 code
    
    The CONFIG_TCG_PASS_AREG0 code for calling ld/st helpers was
    broken in that it did not respect the ABI requirement that 64
    bit values were passed in even-odd register pairs. The simplest
    way to fix this is to implement some new utility functions
    for marshalling function arguments into the correct registers
    and stack, so that the code which sets up the address and
    data arguments does not need to care whether there has been
    a preceding env argument.
    
    Signed-off-by: Peter Maydell <peter.maydell at linaro.org>
    Signed-off-by: Blue Swirl <blauwirbel at gmail.com>

diff --git a/tcg/arm/tcg-target.c b/tcg/arm/tcg-target.c
index 4d59a63..cf0ca3d 100644
--- a/tcg/arm/tcg-target.c
+++ b/tcg/arm/tcg-target.c
@@ -176,6 +176,13 @@ static int target_parse_constraint(TCGArgConstraint *ct, const char **pct_str)
            so don't use these. */
         tcg_regset_reset_reg(ct->u.regs, TCG_REG_R0);
         tcg_regset_reset_reg(ct->u.regs, TCG_REG_R1);
+#if defined(CONFIG_TCG_PASS_AREG0) && (TARGET_LONG_BITS == 64)
+        /* If we're passing env to the helper as r0 and need a regpair
+         * for the address then r2 will be overwritten as we're setting
+         * up the args to the helper.
+         */
+        tcg_regset_reset_reg(ct->u.regs, TCG_REG_R2);
+#endif
 #endif
         break;
     case 'L':
@@ -197,6 +204,12 @@ static int target_parse_constraint(TCGArgConstraint *ct, const char **pct_str)
            use these. */
         tcg_regset_reset_reg(ct->u.regs, TCG_REG_R0);
         tcg_regset_reset_reg(ct->u.regs, TCG_REG_R1);
+#if defined(CONFIG_SOFTMMU) && \
+    defined(CONFIG_TCG_PASS_AREG0) && (TARGET_LONG_BITS == 64)
+        /* Avoid clashes with registers being used for helper args */
+        tcg_regset_reset_reg(ct->u.regs, TCG_REG_R2);
+        tcg_regset_reset_reg(ct->u.regs, TCG_REG_R3);
+#endif
         break;
     /* qemu_st64 data_reg2 */
     case 'S':
@@ -210,6 +223,10 @@ static int target_parse_constraint(TCGArgConstraint *ct, const char **pct_str)
 #ifdef CONFIG_SOFTMMU
         /* r2 is still needed to load data_reg, so don't use it. */
         tcg_regset_reset_reg(ct->u.regs, TCG_REG_R2);
+#if defined(CONFIG_TCG_PASS_AREG0) && (TARGET_LONG_BITS == 64)
+        /* Avoid clashes with registers being used for helper args */
+        tcg_regset_reset_reg(ct->u.regs, TCG_REG_R3);
+#endif
 #endif
         break;
 
@@ -388,6 +405,14 @@ static inline void tcg_out_dat_reg(TCGContext *s,
                     (rn << 16) | (rd << 12) | shift | rm);
 }
 
+static inline void tcg_out_mov_reg(TCGContext *s, int cond, int rd, int rm)
+{
+    /* Simple reg-reg move, optimising out the 'do nothing' case */
+    if (rd != rm) {
+        tcg_out_dat_reg(s, cond, ARITH_MOV, rd, 0, rm, SHIFT_IMM_LSL(0));
+    }
+}
+
 static inline void tcg_out_dat_reg2(TCGContext *s,
                 int cond, int opc0, int opc1, int rd0, int rd1,
                 int rn0, int rn1, int rm0, int rm1, int shift)
@@ -966,6 +991,90 @@ static void *qemu_st_helpers[4] = {
     __stq_mmu,
 };
 #endif
+
+/* Helper routines for marshalling helper function arguments into
+ * the correct registers and stack.
+ * argreg is where we want to put this argument, arg is the argument itself.
+ * Return value is the updated argreg ready for the next call.
+ * Note that argreg 0..3 is real registers, 4+ on stack.
+ * When we reach the first stacked argument, we allocate space for it
+ * and the following stacked arguments using "str r8, [sp, #-0x10]!".
+ * Following arguments are filled in with "str r8, [sp, #0xNN]".
+ * For more than 4 stacked arguments we'd need to know how much
+ * space to allocate when we pushed the first stacked argument.
+ * We don't need this, so don't implement it (and will assert if you try it.)
+ *
+ * We provide routines for arguments which are: immediate, 32 bit
+ * value in register, 16 and 8 bit values in register (which must be zero
+ * extended before use) and 64 bit value in a lo:hi register pair.
+ */
+#define DEFINE_TCG_OUT_ARG(NAME, ARGPARAM)                                 \
+    static TCGReg NAME(TCGContext *s, TCGReg argreg, ARGPARAM)             \
+    {                                                                      \
+        if (argreg < 4) {                                                  \
+            TCG_OUT_ARG_GET_ARG(argreg);                                   \
+        } else if (argreg == 4) {                                          \
+            TCG_OUT_ARG_GET_ARG(TCG_REG_R8);                               \
+            tcg_out32(s, (COND_AL << 28) | 0x052d8010);                    \
+        } else {                                                           \
+            assert(argreg < 8);                                            \
+            TCG_OUT_ARG_GET_ARG(TCG_REG_R8);                               \
+            tcg_out32(s, (COND_AL << 28) | 0x058d8000 | (argreg - 4) * 4); \
+        }                                                                  \
+        return argreg + 1;                                                 \
+    }
+
+#define TCG_OUT_ARG_GET_ARG(A) tcg_out_dat_imm(s, COND_AL, ARITH_MOV, A, 0, arg)
+DEFINE_TCG_OUT_ARG(tcg_out_arg_imm32, uint32_t arg)
+#undef TCG_OUT_ARG_GET_ARG
+#define TCG_OUT_ARG_GET_ARG(A) tcg_out_ext8u(s, COND_AL, A, arg)
+DEFINE_TCG_OUT_ARG(tcg_out_arg_reg8, TCGReg arg)
+#undef TCG_OUT_ARG_GET_ARG
+#define TCG_OUT_ARG_GET_ARG(A) tcg_out_ext16u(s, COND_AL, A, arg)
+DEFINE_TCG_OUT_ARG(tcg_out_arg_reg16, TCGReg arg)
+#undef TCG_OUT_ARG_GET_ARG
+
+/* We don't use the macro for this one to avoid an unnecessary reg-reg
+ * move when storing to the stack.
+ */
+static TCGReg tcg_out_arg_reg32(TCGContext *s, TCGReg argreg, TCGReg arg)
+{
+    if (argreg < 4) {
+        tcg_out_mov_reg(s, COND_AL, argreg, arg);
+    } else if (argreg == 4) {
+        /* str arg, [sp, #-0x10]! */
+        tcg_out32(s, (COND_AL << 28) | 0x052d0010 | (arg << 12));
+    } else {
+        assert(argreg < 8);
+        /* str arg, [sp, #0xNN] */
+        tcg_out32(s, (COND_AL << 28) | 0x058d0000 |
+                  (arg << 12) | (argreg - 4) * 4);
+    }
+    return argreg + 1;
+}
+
+static inline TCGReg tcg_out_arg_reg64(TCGContext *s, TCGReg argreg,
+                                       TCGReg arglo, TCGReg arghi)
+{
+    /* 64 bit arguments must go in even/odd register pairs
+     * and in 8-aligned stack slots.
+     */
+    if (argreg & 1) {
+        argreg++;
+    }
+    argreg = tcg_out_arg_reg32(s, argreg, arglo);
+    argreg = tcg_out_arg_reg32(s, argreg, arghi);
+    return argreg;
+}
+
+static inline void tcg_out_arg_stacktidy(TCGContext *s, TCGReg argreg)
+{
+    /* Output any necessary post-call cleanup of the stack */
+    if (argreg > 4) {
+        tcg_out_dat_imm(s, COND_AL, ARITH_ADD, TCG_REG_R13, TCG_REG_R13, 0x10);
+    }
+}
+
 #endif
 
 #define TLB_SHIFT	(CPU_TLB_ENTRY_BITS + CPU_TLB_BITS)
@@ -975,6 +1084,7 @@ static inline void tcg_out_qemu_ld(TCGContext *s, const TCGArg *args, int opc)
     int addr_reg, data_reg, data_reg2, bswap;
 #ifdef CONFIG_SOFTMMU
     int mem_index, s_bits;
+    TCGReg argreg;
 # if TARGET_LONG_BITS == 64
     int addr_reg2;
 # endif
@@ -1088,31 +1198,22 @@ static inline void tcg_out_qemu_ld(TCGContext *s, const TCGArg *args, int opc)
     tcg_out_b_noaddr(s, COND_EQ);
 
     /* TODO: move this code to where the constants pool will be */
-    if (addr_reg != TCG_REG_R0) {
-        tcg_out_dat_reg(s, COND_AL, ARITH_MOV,
-                        TCG_REG_R0, 0, addr_reg, SHIFT_IMM_LSL(0));
-    }
-# if TARGET_LONG_BITS == 32
-    tcg_out_dat_imm(s, COND_AL, ARITH_MOV, TCG_REG_R1, 0, mem_index);
-# else
-    tcg_out_dat_reg(s, COND_AL, ARITH_MOV,
-                    TCG_REG_R1, 0, addr_reg2, SHIFT_IMM_LSL(0));
-    tcg_out_dat_imm(s, COND_AL, ARITH_MOV, TCG_REG_R2, 0, mem_index);
-# endif
+    /* Note that this code relies on the constraints we set in arm_op_defs[]
+     * to ensure that later arguments are not passed to us in registers we
+     * trash by moving the earlier arguments into them.
+     */
+    argreg = TCG_REG_R0;
 #ifdef CONFIG_TCG_PASS_AREG0
-    /* XXX/FIXME: suboptimal and incorrect for 64 bit */
-    tcg_out_dat_reg(s, COND_AL, ARITH_MOV,
-                    tcg_target_call_iarg_regs[2], 0,
-                    tcg_target_call_iarg_regs[1], SHIFT_IMM_LSL(0));
-    tcg_out_dat_reg(s, COND_AL, ARITH_MOV,
-                    tcg_target_call_iarg_regs[1], 0,
-                    tcg_target_call_iarg_regs[0], SHIFT_IMM_LSL(0));
-
-    tcg_out_dat_reg(s, COND_AL, ARITH_MOV,
-                    tcg_target_call_iarg_regs[0], 0, TCG_AREG0,
-                    SHIFT_IMM_LSL(0));
+    argreg = tcg_out_arg_reg32(s, argreg, TCG_AREG0);
 #endif
+#if TARGET_LONG_BITS == 64
+    argreg = tcg_out_arg_reg64(s, argreg, addr_reg, addr_reg2);
+#else
+    argreg = tcg_out_arg_reg32(s, argreg, addr_reg);
+#endif
+    argreg = tcg_out_arg_imm32(s, argreg, mem_index);
     tcg_out_call(s, (tcg_target_long) qemu_ld_helpers[s_bits]);
+    tcg_out_arg_stacktidy(s, argreg);
 
     switch (opc) {
     case 0 | 4:
@@ -1211,6 +1312,7 @@ static inline void tcg_out_qemu_st(TCGContext *s, const TCGArg *args, int opc)
     int addr_reg, data_reg, data_reg2, bswap;
 #ifdef CONFIG_SOFTMMU
     int mem_index, s_bits;
+    TCGReg argreg;
 # if TARGET_LONG_BITS == 64
     int addr_reg2;
 # endif
@@ -1314,89 +1416,38 @@ static inline void tcg_out_qemu_st(TCGContext *s, const TCGArg *args, int opc)
     tcg_out_b_noaddr(s, COND_EQ);
 
     /* TODO: move this code to where the constants pool will be */
-    tcg_out_dat_reg(s, COND_AL, ARITH_MOV,
-                    TCG_REG_R0, 0, addr_reg, SHIFT_IMM_LSL(0));
-# if TARGET_LONG_BITS == 32
-    switch (opc) {
-    case 0:
-        tcg_out_ext8u(s, COND_AL, TCG_REG_R1, data_reg);
-        tcg_out_dat_imm(s, COND_AL, ARITH_MOV, TCG_REG_R2, 0, mem_index);
-        break;
-    case 1:
-        tcg_out_ext16u(s, COND_AL, TCG_REG_R1, data_reg);
-        tcg_out_dat_imm(s, COND_AL, ARITH_MOV, TCG_REG_R2, 0, mem_index);
-        break;
-    case 2:
-        tcg_out_dat_reg(s, COND_AL, ARITH_MOV,
-                        TCG_REG_R1, 0, data_reg, SHIFT_IMM_LSL(0));
-        tcg_out_dat_imm(s, COND_AL, ARITH_MOV, TCG_REG_R2, 0, mem_index);
-        break;
-    case 3:
-        tcg_out_dat_imm(s, COND_AL, ARITH_MOV, TCG_REG_R8, 0, mem_index);
-        tcg_out32(s, (COND_AL << 28) | 0x052d8010); /* str r8, [sp, #-0x10]! */
-        if (data_reg != TCG_REG_R2) {
-            tcg_out_dat_reg(s, COND_AL, ARITH_MOV,
-                            TCG_REG_R2, 0, data_reg, SHIFT_IMM_LSL(0));
-        }
-        if (data_reg2 != TCG_REG_R3) {
-            tcg_out_dat_reg(s, COND_AL, ARITH_MOV,
-                            TCG_REG_R3, 0, data_reg2, SHIFT_IMM_LSL(0));
-        }
-        break;
-    }
-# else
-    tcg_out_dat_reg(s, COND_AL, ARITH_MOV,
-                    TCG_REG_R1, 0, addr_reg2, SHIFT_IMM_LSL(0));
+    /* Note that this code relies on the constraints we set in arm_op_defs[]
+     * to ensure that later arguments are not passed to us in registers we
+     * trash by moving the earlier arguments into them.
+     */
+    argreg = TCG_REG_R0;
+#ifdef CONFIG_TCG_PASS_AREG0
+    argreg = tcg_out_arg_reg32(s, argreg, TCG_AREG0);
+#endif
+#if TARGET_LONG_BITS == 64
+    argreg = tcg_out_arg_reg64(s, argreg, addr_reg, addr_reg2);
+#else
+    argreg = tcg_out_arg_reg32(s, argreg, addr_reg);
+#endif
+
     switch (opc) {
     case 0:
-        tcg_out_ext8u(s, COND_AL, TCG_REG_R2, data_reg);
-        tcg_out_dat_imm(s, COND_AL, ARITH_MOV, TCG_REG_R3, 0, mem_index);
+        argreg = tcg_out_arg_reg8(s, argreg, data_reg);
         break;
     case 1:
-        tcg_out_ext16u(s, COND_AL, TCG_REG_R2, data_reg);
-        tcg_out_dat_imm(s, COND_AL, ARITH_MOV, TCG_REG_R3, 0, mem_index);
+        argreg = tcg_out_arg_reg16(s, argreg, data_reg);
         break;
     case 2:
-        if (data_reg != TCG_REG_R2) {
-            tcg_out_dat_reg(s, COND_AL, ARITH_MOV,
-                            TCG_REG_R2, 0, data_reg, SHIFT_IMM_LSL(0));
-        }
-        tcg_out_dat_imm(s, COND_AL, ARITH_MOV, TCG_REG_R3, 0, mem_index);
+        argreg = tcg_out_arg_reg32(s, argreg, data_reg);
         break;
     case 3:
-        tcg_out_dat_imm(s, COND_AL, ARITH_MOV, TCG_REG_R8, 0, mem_index);
-        tcg_out32(s, (COND_AL << 28) | 0x052d8010); /* str r8, [sp, #-0x10]! */
-        if (data_reg != TCG_REG_R2) {
-            tcg_out_dat_reg(s, COND_AL, ARITH_MOV,
-                            TCG_REG_R2, 0, data_reg, SHIFT_IMM_LSL(0));
-        }
-        if (data_reg2 != TCG_REG_R3) {
-            tcg_out_dat_reg(s, COND_AL, ARITH_MOV,
-                            TCG_REG_R3, 0, data_reg2, SHIFT_IMM_LSL(0));
-        }
+        argreg = tcg_out_arg_reg64(s, argreg, data_reg, data_reg2);
         break;
     }
-# endif
-
-#ifdef CONFIG_TCG_PASS_AREG0
-    /* XXX/FIXME: suboptimal and incorrect for 64 bit */
-    tcg_out_dat_reg(s, COND_AL, ARITH_MOV,
-                    tcg_target_call_iarg_regs[3], 0,
-                    tcg_target_call_iarg_regs[2], SHIFT_IMM_LSL(0));
-    tcg_out_dat_reg(s, COND_AL, ARITH_MOV,
-                    tcg_target_call_iarg_regs[2], 0,
-                    tcg_target_call_iarg_regs[1], SHIFT_IMM_LSL(0));
-    tcg_out_dat_reg(s, COND_AL, ARITH_MOV,
-                    tcg_target_call_iarg_regs[1], 0,
-                    tcg_target_call_iarg_regs[0], SHIFT_IMM_LSL(0));
 
-    tcg_out_dat_reg(s, COND_AL, ARITH_MOV,
-                    tcg_target_call_iarg_regs[0], 0, TCG_AREG0,
-                    SHIFT_IMM_LSL(0));
-#endif
+    argreg = tcg_out_arg_imm32(s, argreg, mem_index);
     tcg_out_call(s, (tcg_target_long) qemu_st_helpers[s_bits]);
-    if (opc == 3)
-        tcg_out_dat_imm(s, COND_AL, ARITH_ADD, TCG_REG_R13, TCG_REG_R13, 0x10);
+    tcg_out_arg_stacktidy(s, argreg);
 
     reloc_pc24(label_ptr, (tcg_target_long)s->code_ptr);
 #else /* !CONFIG_SOFTMMU */
commit f278d4947fff814dcde2ef2acad36d172ff8be35
Author: Matthew Ogilvie <mmogilvi_qemu at miniinfo.net>
Date:   Thu Aug 23 00:24:43 2012 -0600

    i8259: add -no-spurious-interrupt-hack option
    
    This patch provides a way to optionally suppress spurious interrupts,
    as a workaround for systems described below:
    
    Some old operating systems do not handle spurious interrupts well,
    and qemu tends to generate them significantly more often than
    real hardware.
    
    Examples:
      - Microport UNIX System V/386 v 2.1 (ca 1987)
        (The main problem I'm fixing: Without this patch, it panics
        sporadically when accessing the hard disk.)
      - AT&T UNIX System V/386 Release 4.0 Version 2.1a (ca 1991)
        See screenshot in "QEMU Official OS Support List":
        http://www.claunia.com/qemu/objectManager.php?sClass=application&iId=9
        (I don't have this system to test.)
      - A report about OS/2 boot lockup from 2004 by Hampa Hug:
        http://lists.nongnu.org/archive/html/qemu-devel/2004-09/msg00367.html
        (My patch was partially inspired by his.)
        Also: http://lists.nongnu.org/archive/html/qemu-devel/2005-06/msg00243.html
        (I don't have this system to test.)
    
    Signed-off-by: Matthew Ogilvie <mmogilvi_qemu at miniinfo.net>
    Signed-off-by: malc <av1474 at comtv.ru>

diff --git a/cpu-exec.c b/cpu-exec.c
index 134b3c4..625fbb0 100644
--- a/cpu-exec.c
+++ b/cpu-exec.c
@@ -329,11 +329,15 @@ int cpu_exec(CPUArchState *env)
                                                           0);
                             env->interrupt_request &= ~(CPU_INTERRUPT_HARD | CPU_INTERRUPT_VIRQ);
                             intno = cpu_get_pic_interrupt(env);
-                            qemu_log_mask(CPU_LOG_TB_IN_ASM, "Servicing hardware INT=0x%02x\n", intno);
-                            do_interrupt_x86_hardirq(env, intno, 1);
-                            /* ensure that no TB jump will be modified as
-                               the program flow was changed */
-                            next_tb = 0;
+                            if (intno >= 0) {
+                                qemu_log_mask(CPU_LOG_TB_IN_ASM,
+                                              "Servicing hardware INT=0x%02x\n",
+                                              intno);
+                                do_interrupt_x86_hardirq(env, intno, 1);
+                                /* ensure that no TB jump will be modified as
+                                   the program flow was changed */
+                                next_tb = 0;
+                            }
 #if !defined(CONFIG_USER_ONLY)
                         } else if ((interrupt_request & CPU_INTERRUPT_VIRQ) &&
                                    (env->eflags & IF_MASK) && 
diff --git a/hw/i8259.c b/hw/i8259.c
index 6587666..7ecb7e1 100644
--- a/hw/i8259.c
+++ b/hw/i8259.c
@@ -26,6 +26,7 @@
 #include "isa.h"
 #include "monitor.h"
 #include "qemu-timer.h"
+#include "sysemu.h"
 #include "i8259_internal.h"
 
 /* debug PIC */
@@ -193,6 +194,20 @@ int pic_read_irq(DeviceState *d)
                 pic_intack(slave_pic, irq2);
             } else {
                 /* spurious IRQ on slave controller */
+                if (no_spurious_interrupt_hack) {
+                    /* Pretend it was delivered and acknowledged.  If
+                     * it was spurious due to slave_pic->imr, then
+                     * as soon as the mask is cleared, the slave will
+                     * re-trigger IRQ2 on the master.  If it is spurious for
+                     * some other reason, make sure we don't keep trying
+                     * to half-process the same spurious interrupt over
+                     * and over again.
+                     */
+                    s->irr &= ~(1<<irq);
+                    s->last_irr &= ~(1<<irq);
+                    s->isr &= ~(1<<irq);
+                    return -1;
+                }
                 irq2 = 7;
             }
             intno = slave_pic->irq_base + irq2;
@@ -202,6 +217,9 @@ int pic_read_irq(DeviceState *d)
         pic_intack(s, irq);
     } else {
         /* spurious IRQ on host controller */
+        if (no_spurious_interrupt_hack) {
+            return -1;
+        }
         irq = 7;
         intno = s->irq_base + irq;
     }
diff --git a/qemu-options.hx b/qemu-options.hx
index 0682338..2a6d829 100644
--- a/qemu-options.hx
+++ b/qemu-options.hx
@@ -1189,6 +1189,18 @@ Windows 2000 is installed, you no longer need this option (this option
 slows down the IDE transfers).
 ETEXI
 
+DEF("no-spurious-interrupt-hack", 0, QEMU_OPTION_no_spurious_interrupt_hack,
+    "-no-spurious-interrupt-hack     disable delivery of spurious interrupts\n",
+    QEMU_ARCH_I386)
+STEXI
+ at item -no-spurious-interrupt-hack
+ at findex -no-spurious-interrupt-hack
+Use it as a workaround for operating systems that drive PICs in a way that
+can generate spurious interrupts, but the OS doesn't handle spurious
+interrupts gracefully.  (e.g. late 80s/early 90s versions of ATT UNIX
+and derivatives)
+ETEXI
+
 HXCOMM Deprecated by -rtc
 DEF("rtc-td-hack", 0, QEMU_OPTION_rtc_td_hack, "", QEMU_ARCH_I386)
 
diff --git a/sysemu.h b/sysemu.h
index 65552ac..0170109 100644
--- a/sysemu.h
+++ b/sysemu.h
@@ -117,6 +117,7 @@ extern int graphic_depth;
 extern DisplayType display_type;
 extern const char *keyboard_layout;
 extern int win2k_install_hack;
+extern int no_spurious_interrupt_hack;
 extern int alt_grab;
 extern int ctrl_grab;
 extern int usb_enabled;
diff --git a/vl.c b/vl.c
index 16d04a2..6de41c1 100644
--- a/vl.c
+++ b/vl.c
@@ -204,6 +204,7 @@ CharDriverState *serial_hds[MAX_SERIAL_PORTS];
 CharDriverState *parallel_hds[MAX_PARALLEL_PORTS];
 CharDriverState *virtcon_hds[MAX_VIRTIO_CONSOLES];
 int win2k_install_hack = 0;
+int no_spurious_interrupt_hack = 0;
 int usb_enabled = 0;
 int singlestep = 0;
 int smp_cpus = 1;
@@ -3046,6 +3047,9 @@ int main(int argc, char **argv, char **envp)
             case QEMU_OPTION_win2k_hack:
                 win2k_install_hack = 1;
                 break;
+            case QEMU_OPTION_no_spurious_interrupt_hack:
+                no_spurious_interrupt_hack = 1;
+                break;
             case QEMU_OPTION_rtc_td_hack: {
                 static GlobalProperty slew_lost_ticks[] = {
                     {
commit 482f7bf86b43af9f6903c52726fedf82b28bf953
Author: Matthew Ogilvie <mmogilvi_qemu at miniinfo.net>
Date:   Thu Aug 23 00:24:42 2012 -0600

    vga: add some optional CGA compatibility hacks
    
    This patch adds some optional compatibility hacks (default
    disabled) to allow Microport UNIX to function under qemu.
    
    I've tried to structure it to be easy to add more hacks for other
    old CGA programs, if anyone ever needs them.
    
    Microport UNIX System V/386 v 2.1 (ca 1987) tries to program
    the CGA registers directly with neither the assistance of BIOS, nor
    with proper handling of EGA/VGA-only registers.  Note that it didn't
    work on real VGA hardware, either (although in that case, the most
    obvious problems seemed to be out-of-range hsync and/or vsync
    signalling, rather than the issues in this patch).
    
    Eventually real MDA and/or CGA support might provide an alternative to
    this patch, although a hybrid approach like this patch might still
    be useful in marginal cases.
    
    Signed-off-by: Matthew Ogilvie <mmogilvi_qemu at miniinfo.net>
    Signed-off-by: malc <av1474 at comtv.ru>

diff --git a/hw/pc.h b/hw/pc.h
index e4db071..37e2f87 100644
--- a/hw/pc.h
+++ b/hw/pc.h
@@ -176,6 +176,10 @@ enum vga_retrace_method {
 
 extern enum vga_retrace_method vga_retrace_method;
 
+#define VGA_CGA_HACK_PALETTE_BLANKING  (1<<0)
+#define VGA_CGA_HACK_FONT_HEIGHT       (1<<1)
+extern int vga_cga_hacks;
+
 static inline DeviceState *isa_vga_init(ISABus *bus)
 {
     ISADevice *dev;
diff --git a/hw/vga.c b/hw/vga.c
index f82ced8..a65fc26 100644
--- a/hw/vga.c
+++ b/hw/vga.c
@@ -547,14 +547,31 @@ void vga_ioport_write(void *opaque, uint32_t addr, uint32_t val)
         printf("vga: write CR%x = 0x%02x\n", s->cr_index, val);
 #endif
         /* handle CR0-7 protection */
-        if ((s->cr[VGA_CRTC_V_SYNC_END] & VGA_CR11_LOCK_CR0_CR7) &&
-            s->cr_index <= VGA_CRTC_OVERFLOW) {
-            /* can always write bit 4 of CR7 */
-            if (s->cr_index == VGA_CRTC_OVERFLOW) {
-                s->cr[VGA_CRTC_OVERFLOW] = (s->cr[VGA_CRTC_OVERFLOW] & ~0x10) |
-                    (val & 0x10);
+        if (s->cr[VGA_CRTC_V_SYNC_END] & VGA_CR11_LOCK_CR0_CR7) {
+            if (s->cr_index <= VGA_CRTC_OVERFLOW) {
+                /* can always write bit 4 of CR7 */
+                if (s->cr_index == VGA_CRTC_OVERFLOW) {
+                    s->cr[VGA_CRTC_OVERFLOW] =
+                        (s->cr[VGA_CRTC_OVERFLOW] & ~0x10) | (val & 0x10);
+                }
+                return;
+            } else if ((vga_cga_hacks & VGA_CGA_HACK_FONT_HEIGHT) &&
+                       !(s->sr[VGA_SEQ_CLOCK_MODE] & VGA_SR01_CHAR_CLK_8DOTS)) {
+                /* extra CGA compatibility hacks (not in standard VGA) */
+                if (s->cr_index == VGA_CRTC_MAX_SCAN &&
+                    val == 7 &&
+                    (s->cr[VGA_CRTC_MAX_SCAN] & 0xf) == 0xf) {
+                    return;
+                } else if (s->cr_index == VGA_CRTC_CURSOR_START &&
+                           val == 6 &&
+                           (s->cr[VGA_CRTC_MAX_SCAN] & 0xf) == 0xf) {
+                    val = 0xd;
+                } else if (s->cr_index == VGA_CRTC_CURSOR_END &&
+                           val == 7 &&
+                           (s->cr[VGA_CRTC_MAX_SCAN] & 0xf) == 0xf) {
+                    val = 0xe;
+                }
             }
-            return;
         }
         s->cr[s->cr_index] = val;
 
@@ -1886,7 +1903,10 @@ static void vga_update_display(void *opaque)
         /* nothing to do */
     } else {
         full_update = 0;
-        if (!(s->ar_index & 0x20)) {
+        if (!(s->ar_index & 0x20) &&
+            /* extra CGA compatibility hacks (not in standard VGA */
+            (!(vga_cga_hacks & VGA_CGA_HACK_PALETTE_BLANKING) ||
+             (s->ar_index != 0 && s->ar_flip_flop))) {
             graphic_mode = GMODE_BLANK;
         } else {
             graphic_mode = s->gr[VGA_GFX_MISC] & VGA_GR06_GRAPHICS_MODE;
diff --git a/qemu-options.hx b/qemu-options.hx
index 3e8085d..0682338 100644
--- a/qemu-options.hx
+++ b/qemu-options.hx
@@ -975,6 +975,25 @@ Valid optional properties are
 @item retrace=dumb|precise
 Select dumb (default) or precise VGA retrace logic, useful for some
 DOS games/demos.
+ at item cga_hacks=@var{hack1}[+ at var{hack2},[...]]
+Enable various extra CGA compatibility hacks for programs that are
+trying to directly set CGA modes without BIOS assistance nor
+real knowledge of EGA/VGA.  These might only work with -vga std.
+Valid hacks are
+ at table @option
+ at item palette_blanking
+Wait to blank the screen until palette registers seem to actually be
+modified, instead of blanking it as soon as the palette address bit (0x10)
+of the attribute address register (0x3c0) is cleared.
+ at item font_height
+Ignore attempts to change the VGA font height (index 9),
+cursor start (index 10), and cursor end (index 11) of the CRTC control
+registers (0x3d5) if trying to set them to the default for CGA fonts
+instead of VGA fonts.
+ at item all
+Enable all CGA hacks.  More CGA hacks may be added in future versions
+of qemu.
+ at end table
 @end table
 ETEXI
 
diff --git a/vl.c b/vl.c
index febfd62..16d04a2 100644
--- a/vl.c
+++ b/vl.c
@@ -179,6 +179,7 @@ int main(int argc, char **argv)
 static const char *data_dir;
 const char *bios_name = NULL;
 enum vga_retrace_method vga_retrace_method = VGA_RETRACE_DUMB;
+int vga_cga_hacks = 0;
 DisplayType display_type = DT_DEFAULT;
 int display_remote = 0;
 const char* keyboard_layout = NULL;
@@ -1748,6 +1749,28 @@ static void select_vgahw (const char *p)
             else if (strstart(opts, "precise", &nextopt))
                 vga_retrace_method = VGA_RETRACE_PRECISE;
             else goto invalid_vga;
+        } else if (strstart(opts, ",cga_hacks=", &nextopt)) {
+            opts = nextopt;
+            while (*opts) {
+                if (strstart(opts, "all", &nextopt)) {
+                    opts = nextopt;
+                    vga_cga_hacks |= ~0;
+                } else if (strstart(opts, "palette_blanking", &nextopt)) {
+                    opts = nextopt;
+                    vga_cga_hacks |= VGA_CGA_HACK_PALETTE_BLANKING;
+                } else if (strstart(opts, "font_height", &nextopt)) {
+                    opts = nextopt;
+                    vga_cga_hacks |= VGA_CGA_HACK_FONT_HEIGHT;
+                } else {
+                    break;
+                }
+
+                if (*opts == '+') {
+                    opts++;
+                } else {
+                    break;
+                }
+            }
         } else goto invalid_vga;
         opts = nextopt;
     }
commit 39dda260628e5f2a3fd2ce2ec8a71f3d5ca309a9
Author: Matthew Ogilvie <mmogilvi_qemu at miniinfo.net>
Date:   Thu Aug 23 00:24:41 2012 -0600

    qemu-options.hx: mention retrace= VGA option
    
    The feature was added in commit cb5a7aa8c32141bb Sep 2008.
    My description is based on "Better VGA retrace emulation (needed
    for some DOS games/demos)" from
    http://www.boblycat.org/~malc/code/patches/qemu/index.html
    
    Signed-off-by: Matthew Ogilvie <mmogilvi_qemu at miniinfo.net>
    Signed-off-by: malc <av1474 at comtv.ru>

diff --git a/qemu-options.hx b/qemu-options.hx
index 3c411c4..3e8085d 100644
--- a/qemu-options.hx
+++ b/qemu-options.hx
@@ -945,7 +945,7 @@ DEF("vga", HAS_ARG, QEMU_OPTION_vga,
     "-vga [std|cirrus|vmware|qxl|xenfb|none]\n"
     "                select video card type\n", QEMU_ARCH_ALL)
 STEXI
- at item -vga @var{type}
+ at item -vga @var{type}[, at var{prop}=@var{value}[,...]]
 @findex -vga
 Select type of VGA card to emulate. Valid values for @var{type} are
 @table @option
@@ -970,6 +970,12 @@ Recommended choice when using the spice protocol.
 @item none
 Disable VGA card.
 @end table
+Valid optional properties are
+ at table @option
+ at item retrace=dumb|precise
+Select dumb (default) or precise VGA retrace logic, useful for some
+DOS games/demos.
+ at end table
 ETEXI
 
 DEF("full-screen", 0, QEMU_OPTION_full_screen,
commit 7764ae9671f1cd74227cf4404431dd5213799ef0
Author: Matthew Ogilvie <mmogilvi_qemu at miniinfo.net>
Date:   Thu Aug 23 00:24:40 2012 -0600

    vl: fix -hdachs/-hda argument order parsing issues
    
    Without this patch, the -hdachs argument had to occur either
    BEFORE the corresponding "-hda" option, or AFTER the plain
    disk image name (if neither -hda nor -drive is used).  Otherwise
    it would effectively be ignored.
    
    Option -hdachs still has no effect on -drive, but that seems best.
    
    Signed-off-by: Matthew Ogilvie <mmogilvi_qemu at miniinfo.net>
    Signed-off-by: malc <av1474 at comtv.ru>

diff --git a/vl.c b/vl.c
index 7c577fa..febfd62 100644
--- a/vl.c
+++ b/vl.c
@@ -2352,8 +2352,9 @@ int main(int argc, char **argv, char **envp)
     char boot_devices[33] = "cad"; /* default to HD->floppy->CD-ROM */
     DisplayState *ds;
     DisplayChangeListener *dcl;
-    int cyls, heads, secs, translation;
-    QemuOpts *hda_opts = NULL, *opts, *machine_opts;
+    char hdachs_params[512];  /* save -hdachs to apply to later -hda */
+    QemuOpts *hda_opts = NULL; /* save -hda to be modified by later -hdachs */
+    QemuOpts *opts, *machine_opts;
     QemuOptsList *olist;
     int optind;
     const char *optarg;
@@ -2408,8 +2409,7 @@ int main(int argc, char **argv, char **envp)
     cpu_model = NULL;
     ram_size = 0;
     snapshot = 0;
-    cyls = heads = secs = 0;
-    translation = BIOS_ATA_TRANSLATION_AUTO;
+    snprintf(hdachs_params, sizeof(hdachs_params), "%s", HD_OPTS);
 
     for (i = 0; i < MAX_NODES; i++) {
         node_mem[i] = 0;
@@ -2457,7 +2457,7 @@ int main(int argc, char **argv, char **envp)
         if (optind >= argc)
             break;
         if (argv[optind][0] != '-') {
-	    hda_opts = drive_add(IF_DEFAULT, 0, argv[optind++], HD_OPTS);
+            hda_opts = drive_add(IF_DEFAULT, 0, argv[optind++], hdachs_params);
         } else {
             const QEMUOption *popt;
 
@@ -2475,21 +2475,8 @@ int main(int argc, char **argv, char **envp)
                 cpu_model = optarg;
                 break;
             case QEMU_OPTION_hda:
-                {
-                    char buf[256];
-                    if (cyls == 0)
-                        snprintf(buf, sizeof(buf), "%s", HD_OPTS);
-                    else
-                        snprintf(buf, sizeof(buf),
-                                 "%s,cyls=%d,heads=%d,secs=%d%s",
-                                 HD_OPTS , cyls, heads, secs,
-                                 translation == BIOS_ATA_TRANSLATION_LBA ?
-                                 ",trans=lba" :
-                                 translation == BIOS_ATA_TRANSLATION_NONE ?
-                                 ",trans=none" : "");
-                    drive_add(IF_DEFAULT, 0, optarg, buf);
-                    break;
-                }
+                hda_opts = drive_add(IF_DEFAULT, 0, optarg, hdachs_params);
+                break;
             case QEMU_OPTION_hdb:
             case QEMU_OPTION_hdc:
             case QEMU_OPTION_hdd:
@@ -2523,7 +2510,10 @@ int main(int argc, char **argv, char **envp)
                 break;
             case QEMU_OPTION_hdachs:
                 {
+                    int cyls, heads, secs, translation;
                     const char *p;
+                    cyls = heads = secs = 0;
+                    translation = BIOS_ATA_TRANSLATION_AUTO;
                     p = optarg;
                     cyls = strtol(p, (char **)&p, 0);
                     if (cyls < 1 || cyls > 16383)
@@ -2555,7 +2545,14 @@ int main(int argc, char **argv, char **envp)
                         fprintf(stderr, "qemu: invalid physical CHS format\n");
                         exit(1);
                     }
-		    if (hda_opts != NULL) {
+                    snprintf(hdachs_params, sizeof(hdachs_params),
+                             "%s,cyls=%d,heads=%d,secs=%d%s",
+                             HD_OPTS , cyls, heads, secs,
+                             translation == BIOS_ATA_TRANSLATION_LBA ?
+                             ",trans=lba" :
+                             translation == BIOS_ATA_TRANSLATION_NONE ?
+                             ",trans=none" : "");
+                    if (hda_opts != NULL) {
                         char num[16];
                         snprintf(num, sizeof(num), "%d", cyls);
                         qemu_opt_set(hda_opts, "cyls", num);
commit 5c73b757e3aa80dc84352b2ede0d8bdea5419f6d
Author: Matthew Ogilvie <mmogilvi_qemu at miniinfo.net>
Date:   Thu Aug 23 00:24:39 2012 -0600

    target-i386/translate.c: mov to/from crN/drN: ignore mod bits
    
    > This instruction is always treated as a register-to-register (MOD = 11)
    > instruction, regardless of the encoding of the MOD field in the MODR/M
    > byte.
    
    Also, Microport UNIX System V/386 v 2.1 (ca 1987) runs fine on
    real Intel 386 and 486 CPU's (at least), but does not run in qemu without
    this patch.
    
    Signed-off-by: Matthew Ogilvie <mmogilvi_qemu at miniinfo.net>
    Signed-off-by: malc <av1474 at comtv.ru>

diff --git a/target-i386/translate.c b/target-i386/translate.c
index 7ab2ccb..eb0cabc 100644
--- a/target-i386/translate.c
+++ b/target-i386/translate.c
@@ -7551,8 +7551,11 @@ static target_ulong disas_insn(DisasContext *s, target_ulong pc_start)
             gen_exception(s, EXCP0D_GPF, pc_start - s->cs_base);
         } else {
             modrm = cpu_ldub_code(cpu_single_env, s->pc++);
-            if ((modrm & 0xc0) != 0xc0)
-                goto illegal_op;
+            /* Ignore the mod bits (assume (modrm&0xc0)==0xc0).
+             * AMD documentation (24594.pdf) and testing of
+             * intel 386 and 486 processors all show that the mod bits
+             * are assumed to be 1's, regardless of actual values.
+             */
             rm = (modrm & 7) | REX_B(s);
             reg = ((modrm >> 3) & 7) | rex_r;
             if (CODE64(s))
@@ -7594,8 +7597,11 @@ static target_ulong disas_insn(DisasContext *s, target_ulong pc_start)
             gen_exception(s, EXCP0D_GPF, pc_start - s->cs_base);
         } else {
             modrm = cpu_ldub_code(cpu_single_env, s->pc++);
-            if ((modrm & 0xc0) != 0xc0)
-                goto illegal_op;
+            /* Ignore the mod bits (assume (modrm&0xc0)==0xc0).
+             * AMD documentation (24594.pdf) and testing of
+             * intel 386 and 486 processors all show that the mod bits
+             * are assumed to be 1's, regardless of actual values.
+             */
             rm = (modrm & 7) | REX_B(s);
             reg = ((modrm >> 3) & 7) | rex_r;
             if (CODE64(s))
commit 145c7c880ff520a9348cc2401ba291330b9606fe
Author: Matthew Ogilvie <mmogilvi_qemu at miniinfo.net>
Date:   Thu Aug 23 00:24:38 2012 -0600

    fix some debug printf format strings
    
    These are normally ifdefed out and don't matter.  But if you enable
    them, they ought to be correct.
    
    Signed-off-by: Matthew Ogilvie <mmogilvi_qemu at miniinfo.net>
    Signed-off-by: malc <av1474 at comtv.ru>

diff --git a/hw/cirrus_vga.c b/hw/cirrus_vga.c
index e8dcc6b..909899d 100644
--- a/hw/cirrus_vga.c
+++ b/hw/cirrus_vga.c
@@ -2055,8 +2055,8 @@ static void cirrus_vga_mem_write(void *opaque,
 	}
     } else {
 #ifdef DEBUG_CIRRUS
-        printf("cirrus: mem_writeb " TARGET_FMT_plx " value %02x\n", addr,
-               mem_value);
+        printf("cirrus: mem_writeb " TARGET_FMT_plx " value %" PRIx64 "\n",
+               addr, mem_value);
 #endif
     }
 }
diff --git a/hw/i8259.c b/hw/i8259.c
index 53daf78..6587666 100644
--- a/hw/i8259.c
+++ b/hw/i8259.c
@@ -355,7 +355,8 @@ static uint64_t pic_ioport_read(void *opaque, target_phys_addr_t addr,
             ret = s->imr;
         }
     }
-    DPRINTF("read: addr=0x%02x val=0x%02x\n", addr, ret);
+    DPRINTF("read: addr=0x%02" TARGET_PRIxPHYS " val=0x%02x\n",
+            addr, ret);
     return ret;
 }
 
diff --git a/hw/ide/cmd646.c b/hw/ide/cmd646.c
index e0b9443..dd2855e 100644
--- a/hw/ide/cmd646.c
+++ b/hw/ide/cmd646.c
@@ -154,7 +154,7 @@ static uint64_t bmdma_read(void *opaque, target_phys_addr_t addr,
         break;
     }
 #ifdef DEBUG_IDE
-    printf("bmdma: readb 0x%02x : 0x%02x\n", addr, val);
+    printf("bmdma: readb 0x%02" TARGET_PRIxPHYS " : 0x%02x\n", addr, val);
 #endif
     return val;
 }
@@ -170,7 +170,8 @@ static void bmdma_write(void *opaque, target_phys_addr_t addr,
     }
 
 #ifdef DEBUG_IDE
-    printf("bmdma: writeb 0x%02x : 0x%02x\n", addr, val);
+    printf("bmdma: writeb 0x%02" TARGET_PRIxPHYS " : 0x%02" PRIx64 "\n",
+           addr, val);
 #endif
     switch(addr & 3) {
     case 0:
diff --git a/hw/ide/via.c b/hw/ide/via.c
index b20e4f0..948a469 100644
--- a/hw/ide/via.c
+++ b/hw/ide/via.c
@@ -55,7 +55,7 @@ static uint64_t bmdma_read(void *opaque, target_phys_addr_t addr,
         break;
     }
 #ifdef DEBUG_IDE
-    printf("bmdma: readb 0x%02x : 0x%02x\n", addr, val);
+    printf("bmdma: readb 0x%02" TARGET_PRIxPHYS " : 0x%02x\n", addr, val);
 #endif
     return val;
 }
@@ -70,7 +70,8 @@ static void bmdma_write(void *opaque, target_phys_addr_t addr,
     }
 
 #ifdef DEBUG_IDE
-    printf("bmdma: writeb 0x%02x : 0x%02x\n", addr, val);
+    printf("bmdma: writeb 0x%02" TARGET_PRIxPHYS " : 0x%02" PRIx64 "\n",
+           addr, val);
 #endif
     switch (addr & 3) {
     case 0:
commit 98609cd8fcf755c0ba7049d751353b8b2e243b65
Author: Paolo Bonzini <pbonzini at redhat.com>
Date:   Wed Aug 22 23:09:47 2012 +0200

    ivshmem: fix memory_region_del_eventfd assertion failure
    
    We do not register ioeventfds unless the IVSHMEM_IOEVENTFD feature
    is set.  The same feature must be checked before releasing the eventfds.
    Regression introduced by commit 563027c (ivshmem: use EventNotifier and
    memory API, 2012-07-05).
    
    Reported-by: Cam Macdonnell <cam at cs.ualberta.ca>
    Tested-by: Cam Macdonnell <cam at cs.ualberta.ca>
    Signed-off-by: Paolo Bonzini <pbonzini at redhat.com>
    Signed-off-by: Anthony Liguori <aliguori at us.ibm.com>

diff --git a/hw/ivshmem.c b/hw/ivshmem.c
index b4d65a6..47f2a16 100644
--- a/hw/ivshmem.c
+++ b/hw/ivshmem.c
@@ -366,6 +366,10 @@ static void close_guest_eventfds(IVShmemState *s, int posn)
 {
     int i, guest_curr_max;
 
+    if (!ivshmem_has_feature(s, IVSHMEM_IOEVENTFD)) {
+        return;
+    }
+
     guest_curr_max = s->peers[posn].nb_eventfds;
 
     memory_region_transaction_begin();
commit da5a44e8b0b727681fc33e8d94832d1cae48a788
Author: Paolo Bonzini <pbonzini at redhat.com>
Date:   Wed Aug 22 23:09:46 2012 +0200

    qom: object_delete should unparent the object first
    
    object_deinit is only called when the reference count goes to zero,
    and yet tries to do an object_unparent.  Now, object_unparent
    either does nothing or it will decrease the reference count.
    Because we know the reference count is zero, the object_unparent
    call in object_deinit is useless.
    
    Instead, we need to disconnect the object from its parent just
    before we remove the last reference apart from the parent's.  This
    happens in object_delete.  Once we do this, all calls to
    object_unparent peppered through QEMU can go away.
    
    Signed-off-by: Paolo Bonzini <pbonzini at redhat.com>
    Signed-off-by: Anthony Liguori <aliguori at us.ibm.com>

diff --git a/hw/acpi_piix4.c b/hw/acpi_piix4.c
index 0aace60..72d6e5c 100644
--- a/hw/acpi_piix4.c
+++ b/hw/acpi_piix4.c
@@ -305,7 +305,6 @@ static void acpi_piix_eject_slot(PIIX4PMState *s, unsigned slots)
             if (pc->no_hotplug) {
                 slot_free = false;
             } else {
-                object_unparent(OBJECT(dev));
                 qdev_free(qdev);
             }
         }
diff --git a/hw/qdev.c b/hw/qdev.c
index b5b74b9..b5a52ac 100644
--- a/hw/qdev.c
+++ b/hw/qdev.c
@@ -159,7 +159,6 @@ int qdev_init(DeviceState *dev)
 
     rc = dc->init(dev);
     if (rc < 0) {
-        object_unparent(OBJECT(dev));
         qdev_free(dev);
         return rc;
     }
@@ -243,7 +242,6 @@ void qbus_reset_all_fn(void *opaque)
 int qdev_simple_unplug_cb(DeviceState *dev)
 {
     /* just zap it */
-    object_unparent(OBJECT(dev));
     qdev_free(dev);
     return 0;
 }
diff --git a/hw/shpc.c b/hw/shpc.c
index 6b9884d..a5baf24 100644
--- a/hw/shpc.c
+++ b/hw/shpc.c
@@ -253,7 +253,6 @@ static void shpc_free_devices_in_slot(SHPCDevice *shpc, int slot)
          ++devfn) {
         PCIDevice *affected_dev = shpc->sec_bus->devices[devfn];
         if (affected_dev) {
-            object_unparent(OBJECT(affected_dev));
             qdev_free(&affected_dev->qdev);
         }
     }
diff --git a/hw/xen_platform.c b/hw/xen_platform.c
index c1fe984..0d6c2ff 100644
--- a/hw/xen_platform.c
+++ b/hw/xen_platform.c
@@ -87,9 +87,6 @@ static void unplug_nic(PCIBus *b, PCIDevice *d, void *o)
 {
     if (pci_get_word(d->config + PCI_CLASS_DEVICE) ==
             PCI_CLASS_NETWORK_ETHERNET) {
-        /* Until qdev_free includes a call to object_unparent, we call it here
-         */
-        object_unparent(&d->qdev.parent_obj);
         qdev_free(&d->qdev);
     }
 }
diff --git a/qom/object.c b/qom/object.c
index a552be2..e3e9242 100644
--- a/qom/object.c
+++ b/qom/object.c
@@ -373,8 +373,6 @@ static void object_deinit(Object *obj, TypeImpl *type)
     if (type_has_parent(type)) {
         object_deinit(obj, type_get_parent(type));
     }
-
-    object_unparent(obj);
 }
 
 void object_finalize(void *data)
@@ -411,8 +409,9 @@ Object *object_new(const char *typename)
 
 void object_delete(Object *obj)
 {
+    object_unparent(obj);
+    g_assert(obj->ref == 1);
     object_unref(obj);
-    g_assert(obj->ref == 0);
     g_free(obj);
 }
 
commit 26efaca377e004b79ff50a6e936d029a0c095b8b
Author: Anthony Liguori <aliguori at us.ibm.com>
Date:   Thu Aug 23 13:49:02 2012 -0500

    monitor: don't try to initialize json parser when monitor is HMP
    
    Reported-by: Michael Roth <mdroth at linux.vnet.ibm.com>
    Signed-off-by: Anthony Liguori <aliguori at us.ibm.com>

diff --git a/monitor.c b/monitor.c
index b188582..b17b1bb 100644
--- a/monitor.c
+++ b/monitor.c
@@ -4946,13 +4946,13 @@ void monitor_init(CharDriverState *chr, int flags)
         qemu_chr_add_handlers(chr, monitor_can_read, monitor_control_read,
                               monitor_control_event, mon);
         qemu_chr_fe_set_echo(chr, true);
+
+        json_message_parser_init(&mon->mc->parser, handle_qmp_command);
     } else {
         qemu_chr_add_handlers(chr, monitor_can_read, monitor_read,
                               monitor_event, mon);
     }
 
-    json_message_parser_init(&mon->mc->parser, handle_qmp_command);
-
     QLIST_INSERT_HEAD(&mon_list, mon, entry);
     if (!default_mon || (flags & MONITOR_IS_DEFAULT))
         default_mon = mon;
commit 6fc97fafce05eee76479ca6d289241772d21b370
Author: Stefan Weil <sw at weilnetz.de>
Date:   Sun Mar 4 08:21:39 2012 +0100

    target-mips: Fix some helper functions (VR54xx multiplication)
    
    Commits b5dc7732e1cc2fb549e48b7b5d664f2c79628e2e and
    be24bb4f3007c3e07cbf1934f7e781493d876ab7 optimized the code
    and removed the correct setting of t0. Fix this.
    
    gcc-4.7 detected this bug because parameter arg1 was unused
    but set in set_HIT0_LO and set_HI_LOT0.
    
    Cc: Aurelien Jarno <aurelien at aurel32.net>
    Signed-off-by: Stefan Weil <sw at weilnetz.de>
    Signed-off-by: Aurelien Jarno <aurelien at aurel32.net>

diff --git a/target-mips/op_helper.c b/target-mips/op_helper.c
index 66037ac..e5bc93e 100644
--- a/target-mips/op_helper.c
+++ b/target-mips/op_helper.c
@@ -192,115 +192,98 @@ static inline uint64_t get_HILO (void)
     return ((uint64_t)(env->active_tc.HI[0]) << 32) | (uint32_t)env->active_tc.LO[0];
 }
 
-static inline void set_HIT0_LO (target_ulong arg1, uint64_t HILO)
+static inline target_ulong set_HIT0_LO(uint64_t HILO)
 {
+    target_ulong tmp;
     env->active_tc.LO[0] = (int32_t)(HILO & 0xFFFFFFFF);
-    arg1 = env->active_tc.HI[0] = (int32_t)(HILO >> 32);
+    tmp = env->active_tc.HI[0] = (int32_t)(HILO >> 32);
+    return tmp;
 }
 
-static inline void set_HI_LOT0 (target_ulong arg1, uint64_t HILO)
+static inline target_ulong set_HI_LOT0(uint64_t HILO)
 {
-    arg1 = env->active_tc.LO[0] = (int32_t)(HILO & 0xFFFFFFFF);
+    target_ulong tmp = env->active_tc.LO[0] = (int32_t)(HILO & 0xFFFFFFFF);
     env->active_tc.HI[0] = (int32_t)(HILO >> 32);
+    return tmp;
 }
 
 /* Multiplication variants of the vr54xx. */
 target_ulong helper_muls (target_ulong arg1, target_ulong arg2)
 {
-    set_HI_LOT0(arg1, 0 - ((int64_t)(int32_t)arg1 * (int64_t)(int32_t)arg2));
-
-    return arg1;
+    return set_HI_LOT0(0 - ((int64_t)(int32_t)arg1 * (int64_t)(int32_t)arg2));
 }
 
 target_ulong helper_mulsu (target_ulong arg1, target_ulong arg2)
 {
-    set_HI_LOT0(arg1, 0 - ((uint64_t)(uint32_t)arg1 * (uint64_t)(uint32_t)arg2));
-
-    return arg1;
+    return set_HI_LOT0(0 - (uint64_t)(uint32_t)arg1 * (uint64_t)(uint32_t)arg2);
 }
 
 target_ulong helper_macc (target_ulong arg1, target_ulong arg2)
 {
-    set_HI_LOT0(arg1, ((int64_t)get_HILO()) + ((int64_t)(int32_t)arg1 * (int64_t)(int32_t)arg2));
-
-    return arg1;
+    return set_HI_LOT0((int64_t)get_HILO() + (int64_t)(int32_t)arg1 *
+                                             (int64_t)(int32_t)arg2);
 }
 
 target_ulong helper_macchi (target_ulong arg1, target_ulong arg2)
 {
-    set_HIT0_LO(arg1, ((int64_t)get_HILO()) + ((int64_t)(int32_t)arg1 * (int64_t)(int32_t)arg2));
-
-    return arg1;
+    return set_HIT0_LO((int64_t)get_HILO() + (int64_t)(int32_t)arg1 *
+                                             (int64_t)(int32_t)arg2);
 }
 
 target_ulong helper_maccu (target_ulong arg1, target_ulong arg2)
 {
-    set_HI_LOT0(arg1, ((uint64_t)get_HILO()) + ((uint64_t)(uint32_t)arg1 * (uint64_t)(uint32_t)arg2));
-
-    return arg1;
+    return set_HI_LOT0((uint64_t)get_HILO() + (uint64_t)(uint32_t)arg1 *
+                                              (uint64_t)(uint32_t)arg2);
 }
 
 target_ulong helper_macchiu (target_ulong arg1, target_ulong arg2)
 {
-    set_HIT0_LO(arg1, ((uint64_t)get_HILO()) + ((uint64_t)(uint32_t)arg1 * (uint64_t)(uint32_t)arg2));
-
-    return arg1;
+    return set_HIT0_LO((uint64_t)get_HILO() + (uint64_t)(uint32_t)arg1 *
+                                              (uint64_t)(uint32_t)arg2);
 }
 
 target_ulong helper_msac (target_ulong arg1, target_ulong arg2)
 {
-    set_HI_LOT0(arg1, ((int64_t)get_HILO()) - ((int64_t)(int32_t)arg1 * (int64_t)(int32_t)arg2));
-
-    return arg1;
+    return set_HI_LOT0((int64_t)get_HILO() - (int64_t)(int32_t)arg1 *
+                                             (int64_t)(int32_t)arg2);
 }
 
 target_ulong helper_msachi (target_ulong arg1, target_ulong arg2)
 {
-    set_HIT0_LO(arg1, ((int64_t)get_HILO()) - ((int64_t)(int32_t)arg1 * (int64_t)(int32_t)arg2));
-
-    return arg1;
+    return set_HIT0_LO((int64_t)get_HILO() - (int64_t)(int32_t)arg1 *
+                                             (int64_t)(int32_t)arg2);
 }
 
 target_ulong helper_msacu (target_ulong arg1, target_ulong arg2)
 {
-    set_HI_LOT0(arg1, ((uint64_t)get_HILO()) - ((uint64_t)(uint32_t)arg1 * (uint64_t)(uint32_t)arg2));
-
-    return arg1;
+    return set_HI_LOT0((uint64_t)get_HILO() - (uint64_t)(uint32_t)arg1 *
+                                              (uint64_t)(uint32_t)arg2);
 }
 
 target_ulong helper_msachiu (target_ulong arg1, target_ulong arg2)
 {
-    set_HIT0_LO(arg1, ((uint64_t)get_HILO()) - ((uint64_t)(uint32_t)arg1 * (uint64_t)(uint32_t)arg2));
-
-    return arg1;
+    return set_HIT0_LO((uint64_t)get_HILO() - (uint64_t)(uint32_t)arg1 *
+                                              (uint64_t)(uint32_t)arg2);
 }
 
 target_ulong helper_mulhi (target_ulong arg1, target_ulong arg2)
 {
-    set_HIT0_LO(arg1, (int64_t)(int32_t)arg1 * (int64_t)(int32_t)arg2);
-
-    return arg1;
+    return set_HIT0_LO((int64_t)(int32_t)arg1 * (int64_t)(int32_t)arg2);
 }
 
 target_ulong helper_mulhiu (target_ulong arg1, target_ulong arg2)
 {
-    set_HIT0_LO(arg1, (uint64_t)(uint32_t)arg1 * (uint64_t)(uint32_t)arg2);
-
-    return arg1;
+    return set_HIT0_LO((uint64_t)(uint32_t)arg1 * (uint64_t)(uint32_t)arg2);
 }
 
 target_ulong helper_mulshi (target_ulong arg1, target_ulong arg2)
 {
-    set_HIT0_LO(arg1, 0 - ((int64_t)(int32_t)arg1 * (int64_t)(int32_t)arg2));
-
-    return arg1;
+    return set_HIT0_LO(0 - (int64_t)(int32_t)arg1 * (int64_t)(int32_t)arg2);
 }
 
 target_ulong helper_mulshiu (target_ulong arg1, target_ulong arg2)
 {
-    set_HIT0_LO(arg1, 0 - ((uint64_t)(uint32_t)arg1 * (uint64_t)(uint32_t)arg2));
-
-    return arg1;
+    return set_HIT0_LO(0 - (uint64_t)(uint32_t)arg1 * (uint64_t)(uint32_t)arg2);
 }
 
 #ifdef TARGET_MIPS64
commit 94159135cb59684853dcd45ff70d6dbc54a29209
Author: Meador Inge <meadori at codesourcery.com>
Date:   Tue Aug 21 12:31:37 2012 -0500

    target-mips: Enable access to required RDHWR hardware registers
    
    While running in the usermode emulator all of the required*
    MIPS32r2 RDHWR hardware registers should be accessible (the
    Linux kernel enables access to these same registers).  Note
    that these registers are still enabled when the MIPS ISA is
    not release 2.  This is OK since the Linux kernel emulates
    access to them when they are not available in hardware.
    
    * There is also the ULR register which is only recommended
      for full release 2 compliance.  Incidentally, accessing
      this register in the current implementation works fine
      without flipping its access bit.
    
    Signed-off-by: Meador Inge <meadori at codesourcery.com>
    Signed-off-by: Aurelien Jarno <aurelien at aurel32.net>

diff --git a/target-mips/translate.c b/target-mips/translate.c
index 47daf85..d643676 100644
--- a/target-mips/translate.c
+++ b/target-mips/translate.c
@@ -12768,8 +12768,9 @@ void cpu_state_reset(CPUMIPSState *env)
 
 #if defined(CONFIG_USER_ONLY)
     env->hflags = MIPS_HFLAG_UM;
-    /* Enable access to the SYNCI_Step register.  */
-    env->CP0_HWREna |= (1 << 1);
+    /* Enable access to the CPUNum, SYNCI_Step, CC, and CCRes RDHWR
+       hardware registers.  */
+    env->CP0_HWREna |= 0x0000000F;
     if (env->CP0_Config1 & (1 << CP0C1_FP)) {
         env->hflags |= MIPS_HFLAG_FPU;
     }
commit 58617a795c8067b2f9800cffce60f38707d3aa31
Author: Anthony Liguori <aliguori at us.ibm.com>
Date:   Thu Aug 23 08:03:21 2012 -0500

    monitor: move json init from OPEN event to init
    
    At some point in the past, the OPEN event was changed to be issued from a
    bottom half.  This creates a small window whereas a data callback registered in
    init may be invoked before the OPEN event has been issued.
    
    This is reproducible with:
    
     echo "{'execute': 'qmp_capabilities'}" | qemu-system-x86_64 -M none -qmp stdio
    
    We can fix this for the monitor by moving the parser initialization to init.
    
    The remaining state that is set in OPEN appears harmless.
    
    Reported-by: Daniel Berrange <berrange at redhat.com>
    Signed-off-by: Anthony Liguori <aliguori at us.ibm.com>

diff --git a/monitor.c b/monitor.c
index 480f583..b188582 100644
--- a/monitor.c
+++ b/monitor.c
@@ -4832,7 +4832,6 @@ static void monitor_control_event(void *opaque, int event)
     switch (event) {
     case CHR_EVENT_OPENED:
         mon->mc->command_mode = 0;
-        json_message_parser_init(&mon->mc->parser, handle_qmp_command);
         data = get_qmp_greeting();
         monitor_json_emitter(mon, data);
         qobject_decref(data);
@@ -4840,6 +4839,7 @@ static void monitor_control_event(void *opaque, int event)
         break;
     case CHR_EVENT_CLOSED:
         json_message_parser_destroy(&mon->mc->parser);
+        json_message_parser_init(&mon->mc->parser, handle_qmp_command);
         mon_refcount--;
         monitor_fdsets_cleanup();
         break;
@@ -4951,6 +4951,8 @@ void monitor_init(CharDriverState *chr, int flags)
                               monitor_event, mon);
     }
 
+    json_message_parser_init(&mon->mc->parser, handle_qmp_command);
+
     QLIST_INSERT_HEAD(&mon_list, mon, entry);
     if (!default_mon || (flags & MONITOR_IS_DEFAULT))
         default_mon = mon;
commit b4a738bf93c3137b92d532e59d60edccc4e1ea96
Author: Anthony Liguori <aliguori at us.ibm.com>
Date:   Wed Aug 22 15:22:05 2012 -0500

    boards: add a 'none' machine type to all platforms
    
    This allows any QEMU binary to be executed with:
    
      $QEMU_BINARY -M none -qmp stdio
    
    Without errors from missing options that are required by various boards.  This
    also provides a mode that we can use in the future to construct machines
    entirely through QMP commands.
    
    Cc: Daniel Berrange <berrange at redhat.com>
    Cc: Markus Armbruster <armbru at redhat.com>
    Signed-off-by: Anthony Liguori <aliguori at us.ibm.com>

diff --git a/hw/Makefile.objs b/hw/Makefile.objs
index 7f57ed5..6dfebd2 100644
--- a/hw/Makefile.objs
+++ b/hw/Makefile.objs
@@ -134,6 +134,8 @@ hw-obj-$(CONFIG_DP8393X) += dp8393x.o
 hw-obj-$(CONFIG_DS1225Y) += ds1225y.o
 hw-obj-$(CONFIG_MIPSNET) += mipsnet.o
 
+hw-obj-y += null-machine.o
+
 # Sound
 sound-obj-y =
 sound-obj-$(CONFIG_SB16) += sb16.o
diff --git a/hw/null-machine.c b/hw/null-machine.c
new file mode 100644
index 0000000..69910d3
--- /dev/null
+++ b/hw/null-machine.c
@@ -0,0 +1,40 @@
+/*
+ * Empty machine
+ *
+ * Copyright IBM, Corp. 2012
+ *
+ * Authors:
+ *  Anthony Liguori   <aliguori at us.ibm.com>
+ *
+ * This work is licensed under the terms of the GNU GPL, version 2 or later.
+ * See the COPYING file in the top-level directory.
+ *
+ */
+
+#include "qemu-common.h"
+#include "hw/hw.h"
+#include "hw/boards.h"
+
+static void machine_none_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)
+{
+}
+
+static QEMUMachine machine_none = {
+    .name = "none",
+    .desc = "empty machine",
+    .init = machine_none_init,
+    .max_cpus = 0,
+};
+
+static void register_machines(void)
+{
+    qemu_register_machine(&machine_none);
+}
+
+machine_init(register_machines);
+
commit af506c7036003a4a860e23e694034b9a914d1d2f
Author: Anthony Liguori <aliguori at us.ibm.com>
Date:   Wed Aug 22 15:44:38 2012 -0500

    Update version for 1.2.0-rc1 release
    
    Signed-off-by: Anthony Liguori <aliguori at us.ibm.com>

diff --git a/VERSION b/VERSION
index 69658cd..069199b 100644
--- a/VERSION
+++ b/VERSION
@@ -1 +1 @@
-1.1.90
+1.1.91
commit 86759aa89d1307d0dda2435cc25943bcd7026686
Merge: b100fcf... 7aa939a...
Author: Anthony Liguori <aliguori at us.ibm.com>
Date:   Wed Aug 22 13:33:15 2012 -0500

    Merge remote-tracking branch 'qmp/queue/qmp' into staging
    
    * qmp/queue/qmp:
      migration: move total_time from ram stats to migration info
      monitor: avoid declaring unused variables
      qapi: Fix memory leak

commit b100fcfe4966aa41d4d6908d0c4c510bcf8f82dd
Merge: a9b670b... 14d4018...
Author: Anthony Liguori <aliguori at us.ibm.com>
Date:   Wed Aug 22 13:31:39 2012 -0500

    Merge remote-tracking branch 'sstabellini/xen-fixes-20120822' into staging
    
    * sstabellini/xen-fixes-20120822:
      xen-all.c: fix multiply issue for int and uint types
      Fix invalidate if memory requested was not bucket aligned

commit a9b670b139ed381bd07df08bdfdcb515dff3ca8c
Merge: 7b2f89c... 07a5298...
Author: Anthony Liguori <aliguori at us.ibm.com>
Date:   Wed Aug 22 13:31:17 2012 -0500

    Merge remote-tracking branch 'bonzini/scsi-next' into staging
    
    * bonzini/scsi-next:
      virtio-scsi: add backwards-compatibility properties for 1.1 and earlier machines
      iscsi: fix races between task completion and abort
      iscsi: simplify iscsi_schedule_bh
      iscsi: move iscsi_schedule_bh and iscsi_readv_writev_bh_cb
      Revert "iscsi: Fix NULL dereferences / races between task completion and abort"

commit 7b2f89c435f895431d55b675dc412275c2069314
Merge: b6825cd... eec7f96...
Author: Anthony Liguori <aliguori at us.ibm.com>
Date:   Wed Aug 22 13:01:05 2012 -0500

    Merge remote-tracking branch 'kwolf/for-anthony' into staging
    
    * kwolf/for-anthony:
      virtio-blk: hide VIRTIO_BLK_F_CONFIG_WCE from old machine types
      Documentation: Warn against qemu-img on active image
      vmdk: Read footer for streamOptimized images
      vmdk: Fix header structure
    
    Conflicts:
    	hw/virtio-blk.c

commit b6825cd79cdf3e2006c22bb8cfe47a0d7c5209fa
Merge: 99afc91... 47d073c...
Author: Anthony Liguori <aliguori at us.ibm.com>
Date:   Wed Aug 22 12:53:18 2012 -0500

    Merge remote-tracking branch 'kraxel/usb.59' into staging
    
    * kraxel/usb.59:
      ehci: Fix setting of halt bit from usbcmd register updates
      ehci: fix Interrupt Threshold Control implementation
      usb: update uas product id
      usb: async control xfer fixup

commit 99afc91d6ccdbe45258cff66fd0ce0142820c366
Author: Daniel P. Berrange <berrange at redhat.com>
Date:   Mon Aug 20 15:31:38 2012 +0100

    qapi: add 'query-target' command to return target arch
    
    Add a 'query-target' QAPI command to allow management applications
    to determine what target architecture a QEMU binary is emulating
    without having to parse the binary name or -help output
    
      $ qmp-shell -p /tmp/qemu
      (QEMU) query-target
      {   u'return': {   u'arch': u'x86_64' }}
    
    Signed-off-by: Daniel P. Berrange <berrange at redhat.com>
    Signed-off-by: Anthony Liguori <aliguori at us.ibm.com>

diff --git a/arch_init.c b/arch_init.c
index 9b46bfc..5a1173e 100644
--- a/arch_init.c
+++ b/arch_init.c
@@ -44,6 +44,7 @@
 #include "exec-memory.h"
 #include "hw/pcspk.h"
 #include "qemu/page_cache.h"
+#include "qmp-commands.h"
 
 #ifdef DEBUG_ARCH_INIT
 #define DPRINTF(fmt, ...) \
@@ -1080,3 +1081,13 @@ int xen_available(void)
     return 0;
 #endif
 }
+
+
+TargetInfo *qmp_query_target(Error **errp)
+{
+    TargetInfo *info = g_malloc0(sizeof(*info));
+
+    info->arch = TARGET_TYPE;
+
+    return info;
+}
diff --git a/configure b/configure
index 60d266f..d97fd81 100755
--- a/configure
+++ b/configure
@@ -3834,14 +3834,19 @@ case "$target_arch2" in
   ;;
 esac
 
+upper() {
+    echo "$@"| LC_ALL=C tr '[a-z]' '[A-Z]'
+}
+
 echo "TARGET_SHORT_ALIGNMENT=$target_short_alignment" >> $config_target_mak
 echo "TARGET_INT_ALIGNMENT=$target_int_alignment" >> $config_target_mak
 echo "TARGET_LONG_ALIGNMENT=$target_long_alignment" >> $config_target_mak
 echo "TARGET_LLONG_ALIGNMENT=$target_llong_alignment" >> $config_target_mak
 echo "TARGET_ARCH=$TARGET_ARCH" >> $config_target_mak
-target_arch_name="`echo $TARGET_ARCH | LC_ALL=C tr '[a-z]' '[A-Z]'`"
+target_arch_name="`upper $TARGET_ARCH`"
 echo "TARGET_$target_arch_name=y" >> $config_target_mak
 echo "TARGET_ARCH2=$target_arch2" >> $config_target_mak
+echo "TARGET_TYPE=TARGET_TYPE_`upper $target_arch2`" >> $config_target_mak
 echo "TARGET_BASE_ARCH=$TARGET_BASE_ARCH" >> $config_target_mak
 if [ "$TARGET_ABI_DIR" = "" ]; then
   TARGET_ABI_DIR=$TARGET_ARCH
diff --git a/qapi-schema.json b/qapi-schema.json
index 3d2b2d1..72b3c4d 100644
--- a/qapi-schema.json
+++ b/qapi-schema.json
@@ -2454,3 +2454,42 @@
 #
 ##
 { 'command': 'query-fdsets', 'returns': ['FdsetInfo'] }
+
+##
+# @TargetType
+#
+# Target CPU emulation type
+#
+# These parameters correspond to the softmmu binary CPU name that is currently
+# running.
+#
+# Since: 1.2.0
+##
+{ 'enum': 'TargetType',
+  'data': [ 'alpha', 'arm', 'cris', 'i386', 'lm32', 'm68k', 'microblazeel',
+            'microblaze', 'mips64el', 'mips64', 'mipsel', 'mips', 'or32',
+            'ppc64', 'ppcemb', 'ppc', 's390x', 'sh4eb', 'sh4', 'sparc64',
+            'sparc', 'unicore32', 'x86_64', 'xtensaeb', 'xtensa' ] }
+
+##
+# @TargetInfo:
+#
+# Information describing the QEMU target.
+#
+# @arch: the target architecture (eg "x86_64", "i386", etc)
+#
+# Since: 1.2.0
+##
+{ 'type': 'TargetInfo',
+  'data': { 'arch': 'TargetType' } }
+
+##
+# @query-target:
+#
+# Return information about the target for this QEMU
+#
+# Returns: TargetInfo
+#
+# Since: 1.2.0
+##
+{ 'command': 'query-target', 'returns': 'TargetInfo' }
diff --git a/qmp-commands.hx b/qmp-commands.hx
index 2ce4ce6..00d798f 100644
--- a/qmp-commands.hx
+++ b/qmp-commands.hx
@@ -2509,3 +2509,8 @@ EQMP
         .mhandler.cmd_new = qmp_marshal_input_query_cpu_definitions,
     },
 
+    {
+        .name       = "query-target",
+        .args_type  = "",
+        .mhandler.cmd_new = qmp_marshal_input_query_target,
+    },
commit 67c332fd12326a6ef572f07b9d71370ada6a287f
Author: Andreas Färber <afaerber at suse.de>
Date:   Mon Aug 20 19:08:09 2012 +0200

    pci: Tidy up PCI host bridges
    
    Adopt the QOM parent field name and enforce QOM-style access via casts.
    Don't just typedef PCIHostState, either use it directly or embed it.
    
    Signed-off-by: Andreas Färber <afaerber at suse.de>
    Signed-off-by: Anthony Liguori <aliguori at us.ibm.com>

diff --git a/hw/alpha_typhoon.c b/hw/alpha_typhoon.c
index 7667412..b7cf4e2 100644
--- a/hw/alpha_typhoon.c
+++ b/hw/alpha_typhoon.c
@@ -46,7 +46,7 @@ typedef struct TyphoonPchip {
     OBJECT_CHECK(TyphoonState, (obj), TYPE_TYPHOON_PCI_HOST_BRIDGE)
 
 typedef struct TyphoonState {
-    PCIHostState host;
+    PCIHostState parent_obj;
 
     TyphoonCchip cchip;
     TyphoonPchip pchip;
diff --git a/hw/dec_pci.c b/hw/dec_pci.c
index de16361..c30ade3 100644
--- a/hw/dec_pci.c
+++ b/hw/dec_pci.c
@@ -43,7 +43,7 @@
 #define DEC_21154(obj) OBJECT_CHECK(DECState, (obj), TYPE_DEC_21154)
 
 typedef struct DECState {
-    PCIHostState host_state;
+    PCIHostState parent_obj;
 } DECState;
 
 static int dec_map_irq(PCIDevice *pci_dev, int irq_num)
diff --git a/hw/grackle_pci.c b/hw/grackle_pci.c
index 066f6e1..67da307 100644
--- a/hw/grackle_pci.c
+++ b/hw/grackle_pci.c
@@ -41,7 +41,7 @@
     OBJECT_CHECK(GrackleState, (obj), TYPE_GRACKLE_PCI_HOST_BRIDGE)
 
 typedef struct GrackleState {
-    PCIHostState host_state;
+    PCIHostState parent_obj;
 
     MemoryRegion pci_mmio;
     MemoryRegion pci_hole;
diff --git a/hw/gt64xxx.c b/hw/gt64xxx.c
index 857758e..e95e664 100644
--- a/hw/gt64xxx.c
+++ b/hw/gt64xxx.c
@@ -235,7 +235,7 @@
     OBJECT_CHECK(GT64120State, (obj), TYPE_GT64120_PCI_HOST_BRIDGE)
 
 typedef struct GT64120State {
-    PCIHostState pci;
+    PCIHostState parent_obj;
 
     uint32_t regs[GT_REGS];
     PCI_MAPPING_ENTRY(PCI0IO);
@@ -315,6 +315,7 @@ static void gt64120_writel (void *opaque, target_phys_addr_t addr,
                             uint64_t val, unsigned size)
 {
     GT64120State *s = opaque;
+    PCIHostState *phb = PCI_HOST_BRIDGE(s);
     uint32_t saddr;
 
     if (!(s->regs[GT_CPU] & 0x00001000))
@@ -535,13 +536,15 @@ static void gt64120_writel (void *opaque, target_phys_addr_t addr,
         /* not implemented */
         break;
     case GT_PCI0_CFGADDR:
-        s->pci.config_reg = val & 0x80fffffc;
+        phb->config_reg = val & 0x80fffffc;
         break;
     case GT_PCI0_CFGDATA:
-        if (!(s->regs[GT_PCI0_CMD] & 1) && (s->pci.config_reg & 0x00fff800))
+        if (!(s->regs[GT_PCI0_CMD] & 1) && (phb->config_reg & 0x00fff800)) {
             val = bswap32(val);
-        if (s->pci.config_reg & (1u << 31))
-            pci_data_write(s->pci.bus, s->pci.config_reg, val, 4);
+        }
+        if (phb->config_reg & (1u << 31)) {
+            pci_data_write(phb->bus, phb->config_reg, val, 4);
+        }
         break;
 
     /* Interrupts */
@@ -594,6 +597,7 @@ static uint64_t gt64120_readl (void *opaque,
                                target_phys_addr_t addr, unsigned size)
 {
     GT64120State *s = opaque;
+    PCIHostState *phb = PCI_HOST_BRIDGE(s);
     uint32_t val;
     uint32_t saddr;
 
@@ -775,15 +779,17 @@ static uint64_t gt64120_readl (void *opaque,
 
     /* PCI Internal */
     case GT_PCI0_CFGADDR:
-        val = s->pci.config_reg;
+        val = phb->config_reg;
         break;
     case GT_PCI0_CFGDATA:
-        if (!(s->pci.config_reg & (1 << 31)))
+        if (!(phb->config_reg & (1 << 31))) {
             val = 0xffffffff;
-        else
-            val = pci_data_read(s->pci.bus, s->pci.config_reg, 4);
-        if (!(s->regs[GT_PCI0_CMD] & 1) && (s->pci.config_reg & 0x00fff800))
+        } else {
+            val = pci_data_read(phb->bus, phb->config_reg, 4);
+        }
+        if (!(s->regs[GT_PCI0_CMD] & 1) && (phb->config_reg & 0x00fff800)) {
             val = bswap32(val);
+        }
         break;
 
     case GT_PCI0_CMD:
diff --git a/hw/piix_pci.c b/hw/piix_pci.c
index 04ceccf..537fc19 100644
--- a/hw/piix_pci.c
+++ b/hw/piix_pci.c
@@ -36,7 +36,9 @@
  * http://download.intel.com/design/chipsets/datashts/29054901.pdf
  */
 
-typedef PCIHostState I440FXState;
+typedef struct I440FXState {
+    PCIHostState parent_obj;
+} I440FXState;
 
 #define PIIX_NUM_PIC_IRQS       16      /* i8259 * 2 */
 #define PIIX_NUM_PIRQS          4ULL    /* PIRQ[A-D] */
@@ -274,7 +276,7 @@ static PCIBus *i440fx_common_init(const char *device_name,
     dev = qdev_create(NULL, "i440FX-pcihost");
     s = PCI_HOST_BRIDGE(dev);
     s->address_space = address_space_mem;
-    b = pci_bus_new(&s->busdev.qdev, NULL, pci_address_space,
+    b = pci_bus_new(dev, NULL, pci_address_space,
                     address_space_io, 0);
     s->bus = b;
     object_property_add_child(qdev_get_machine(), "i440fx", OBJECT(dev), NULL);
diff --git a/hw/ppc4xx_pci.c b/hw/ppc4xx_pci.c
index 5583321..a14fd42 100644
--- a/hw/ppc4xx_pci.c
+++ b/hw/ppc4xx_pci.c
@@ -52,7 +52,7 @@ struct PCITargetMap {
 #define PPC4xx_PCI_NR_PTMS 2
 
 struct PPC4xxPCIState {
-    PCIHostState pci_state;
+    PCIHostState parent_obj;
 
     struct PCIMasterMap pmm[PPC4xx_PCI_NR_PMMS];
     struct PCITargetMap ptm[PPC4xx_PCI_NR_PTMS];
@@ -96,16 +96,18 @@ static uint64_t pci4xx_cfgaddr_read(void *opaque, target_phys_addr_t addr,
                                     unsigned size)
 {
     PPC4xxPCIState *ppc4xx_pci = opaque;
+    PCIHostState *phb = PCI_HOST_BRIDGE(ppc4xx_pci);
 
-    return ppc4xx_pci->pci_state.config_reg;
+    return phb->config_reg;
 }
 
 static void pci4xx_cfgaddr_write(void *opaque, target_phys_addr_t addr,
                                   uint64_t value, unsigned size)
 {
     PPC4xxPCIState *ppc4xx_pci = opaque;
+    PCIHostState *phb = PCI_HOST_BRIDGE(ppc4xx_pci);
 
-    ppc4xx_pci->pci_state.config_reg = value & ~0x3;
+    phb->config_reg = value & ~0x3;
 }
 
 static const MemoryRegionOps pci4xx_cfgaddr_ops = {
diff --git a/hw/ppce500_pci.c b/hw/ppce500_pci.c
index 3333967..92b1dc0 100644
--- a/hw/ppce500_pci.c
+++ b/hw/ppce500_pci.c
@@ -78,7 +78,7 @@ struct pci_inbound {
     OBJECT_CHECK(PPCE500PCIState, (obj), TYPE_PPC_E500_PCI_HOST_BRIDGE)
 
 struct PPCE500PCIState {
-    PCIHostState pci_state;
+    PCIHostState parent_obj;
 
     struct pci_outbound pob[PPCE500_PCI_NR_POBS];
     struct pci_inbound pib[PPCE500_PCI_NR_PIBS];
diff --git a/hw/prep_pci.c b/hw/prep_pci.c
index 35cb9b2..cc44e61 100644
--- a/hw/prep_pci.c
+++ b/hw/prep_pci.c
@@ -34,7 +34,7 @@
     OBJECT_CHECK(PREPPCIState, (obj), TYPE_RAVEN_PCI_HOST_BRIDGE)
 
 typedef struct PRePPCIState {
-    PCIHostState host_state;
+    PCIHostState parent_obj;
 
     MemoryRegion intack;
     qemu_irq irq[4];
@@ -60,14 +60,16 @@ static void ppc_pci_io_write(void *opaque, target_phys_addr_t addr,
                              uint64_t val, unsigned int size)
 {
     PREPPCIState *s = opaque;
-    pci_data_write(s->host_state.bus, PPC_PCIIO_config(addr), val, size);
+    PCIHostState *phb = PCI_HOST_BRIDGE(s);
+    pci_data_write(phb->bus, PPC_PCIIO_config(addr), val, size);
 }
 
 static uint64_t ppc_pci_io_read(void *opaque, target_phys_addr_t addr,
                                 unsigned int size)
 {
     PREPPCIState *s = opaque;
-    return pci_data_read(s->host_state.bus, PPC_PCIIO_config(addr), size);
+    PCIHostState *phb = PCI_HOST_BRIDGE(s);
+    return pci_data_read(phb->bus, PPC_PCIIO_config(addr), size);
 }
 
 static const MemoryRegionOps PPC_PCIIO_ops = {
diff --git a/hw/spapr_pci.h b/hw/spapr_pci.h
index 4140ee6..670dc62 100644
--- a/hw/spapr_pci.h
+++ b/hw/spapr_pci.h
@@ -35,7 +35,7 @@
     OBJECT_CHECK(sPAPRPHBState, (obj), TYPE_SPAPR_PCI_HOST_BRIDGE)
 
 typedef struct sPAPRPHBState {
-    PCIHostState host_state;
+    PCIHostState parent_obj;
 
     uint64_t buid;
     char *busname;
diff --git a/hw/unin_pci.c b/hw/unin_pci.c
index 0db7c1f..d1cc680 100644
--- a/hw/unin_pci.c
+++ b/hw/unin_pci.c
@@ -53,7 +53,7 @@ static const int unin_irq_line[] = { 0x1b, 0x1c, 0x1d, 0x1e };
     OBJECT_CHECK(UNINState, (obj), TYPE_U3_AGP_HOST_BRIDGE)
 
 typedef struct UNINState {
-    PCIHostState host_state;
+    PCIHostState parent_obj;
 
     MemoryRegion pci_mmio;
     MemoryRegion pci_hole;
@@ -115,10 +115,11 @@ static void unin_data_write(void *opaque, target_phys_addr_t addr,
                             uint64_t val, unsigned len)
 {
     UNINState *s = opaque;
+    PCIHostState *phb = PCI_HOST_BRIDGE(s);
     UNIN_DPRINTF("write addr %" TARGET_FMT_plx " len %d val %"PRIx64"\n",
                  addr, len, val);
-    pci_data_write(s->host_state.bus,
-                   unin_get_config_reg(s->host_state.config_reg, addr),
+    pci_data_write(phb->bus,
+                   unin_get_config_reg(phb->config_reg, addr),
                    val, len);
 }
 
@@ -126,10 +127,11 @@ static uint64_t unin_data_read(void *opaque, target_phys_addr_t addr,
                                unsigned len)
 {
     UNINState *s = opaque;
+    PCIHostState *phb = PCI_HOST_BRIDGE(s);
     uint32_t val;
 
-    val = pci_data_read(s->host_state.bus,
-                        unin_get_config_reg(s->host_state.config_reg, addr),
+    val = pci_data_read(phb->bus,
+                        unin_get_config_reg(phb->config_reg, addr),
                         len);
     UNIN_DPRINTF("read addr %" TARGET_FMT_plx " len %d val %x\n",
                  addr, len, val);
commit 8558d942b665a9ff0847851615e107308f6386a5
Author: Andreas Färber <afaerber at suse.de>
Date:   Mon Aug 20 19:08:08 2012 +0200

    pci: Derive PCI host bridges from TYPE_PCI_HOST_BRIDGE
    
    Use PCIHostState and PCI_HOST_BRIDGE() where appropriate.
    
    Signed-off-by: Andreas Färber <afaerber at suse.de>
    Signed-off-by: Anthony Liguori <aliguori at us.ibm.com>

diff --git a/hw/alpha_typhoon.c b/hw/alpha_typhoon.c
index 10e588a..7667412 100644
--- a/hw/alpha_typhoon.c
+++ b/hw/alpha_typhoon.c
@@ -715,7 +715,7 @@ PCIBus *typhoon_init(ram_addr_t ram_size, ISABus **isa_bus,
     qdev_init_nofail(dev);
 
     s = TYPHOON_PCI_HOST_BRIDGE(dev);
-    phb = FROM_SYSBUS(PCIHostState, SYS_BUS_DEVICE(dev));
+    phb = PCI_HOST_BRIDGE(dev);
 
     /* Remember the CPUs so that we can deliver interrupts to them.  */
     for (i = 0; i < 4; i++) {
@@ -825,7 +825,7 @@ static void typhoon_pcihost_class_init(ObjectClass *klass, void *data)
 
 static const TypeInfo typhoon_pcihost_info = {
     .name          = TYPE_TYPHOON_PCI_HOST_BRIDGE,
-    .parent        = TYPE_SYS_BUS_DEVICE,
+    .parent        = TYPE_PCI_HOST_BRIDGE,
     .instance_size = sizeof(TyphoonState),
     .class_init    = typhoon_pcihost_class_init,
 };
diff --git a/hw/bonito.c b/hw/bonito.c
index 062c701..6084ac4 100644
--- a/hw/bonito.c
+++ b/hw/bonito.c
@@ -416,7 +416,7 @@ static const MemoryRegionOps bonito_cop_ops = {
 static uint32_t bonito_sbridge_pciaddr(void *opaque, target_phys_addr_t addr)
 {
     PCIBonitoState *s = opaque;
-    PCIHostState *phb = FROM_SYSBUS(PCIHostState, SYS_BUS_DEVICE(s->pcihost));
+    PCIHostState *phb = PCI_HOST_BRIDGE(s->pcihost);
     uint32_t cfgaddr;
     uint32_t idsel;
     uint32_t devno;
@@ -454,7 +454,7 @@ static void bonito_spciconf_writeb(void *opaque, target_phys_addr_t addr,
 {
     PCIBonitoState *s = opaque;
     PCIDevice *d = PCI_DEVICE(s);
-    PCIHostState *phb = FROM_SYSBUS(PCIHostState, SYS_BUS_DEVICE(s->pcihost));
+    PCIHostState *phb = PCI_HOST_BRIDGE(s->pcihost);
     uint32_t pciaddr;
     uint16_t status;
 
@@ -480,7 +480,7 @@ static void bonito_spciconf_writew(void *opaque, target_phys_addr_t addr,
 {
     PCIBonitoState *s = opaque;
     PCIDevice *d = PCI_DEVICE(s);
-    PCIHostState *phb = FROM_SYSBUS(PCIHostState, SYS_BUS_DEVICE(s->pcihost));
+    PCIHostState *phb = PCI_HOST_BRIDGE(s->pcihost);
     uint32_t pciaddr;
     uint16_t status;
 
@@ -508,7 +508,7 @@ static void bonito_spciconf_writel(void *opaque, target_phys_addr_t addr,
 {
     PCIBonitoState *s = opaque;
     PCIDevice *d = PCI_DEVICE(s);
-    PCIHostState *phb = FROM_SYSBUS(PCIHostState, SYS_BUS_DEVICE(s->pcihost));
+    PCIHostState *phb = PCI_HOST_BRIDGE(s->pcihost);
     uint32_t pciaddr;
     uint16_t status;
 
@@ -535,7 +535,7 @@ static uint32_t bonito_spciconf_readb(void *opaque, target_phys_addr_t addr)
 {
     PCIBonitoState *s = opaque;
     PCIDevice *d = PCI_DEVICE(s);
-    PCIHostState *phb = FROM_SYSBUS(PCIHostState, SYS_BUS_DEVICE(s->pcihost));
+    PCIHostState *phb = PCI_HOST_BRIDGE(s->pcihost);
     uint32_t pciaddr;
     uint16_t status;
 
@@ -561,7 +561,7 @@ static uint32_t bonito_spciconf_readw(void *opaque, target_phys_addr_t addr)
 {
     PCIBonitoState *s = opaque;
     PCIDevice *d = PCI_DEVICE(s);
-    PCIHostState *phb = FROM_SYSBUS(PCIHostState, SYS_BUS_DEVICE(s->pcihost));
+    PCIHostState *phb = PCI_HOST_BRIDGE(s->pcihost);
     uint32_t pciaddr;
     uint16_t status;
 
@@ -589,7 +589,7 @@ static uint32_t bonito_spciconf_readl(void *opaque, target_phys_addr_t addr)
 {
     PCIBonitoState *s = opaque;
     PCIDevice *d = PCI_DEVICE(s);
-    PCIHostState *phb = FROM_SYSBUS(PCIHostState, SYS_BUS_DEVICE(s->pcihost));
+    PCIHostState *phb = PCI_HOST_BRIDGE(s->pcihost);
     uint32_t pciaddr;
     uint16_t status;
 
@@ -702,7 +702,7 @@ static const VMStateDescription vmstate_bonito = {
 
 static int bonito_pcihost_initfn(SysBusDevice *dev)
 {
-    PCIHostState *phb = FROM_SYSBUS(PCIHostState, dev);
+    PCIHostState *phb = PCI_HOST_BRIDGE(dev);
 
     phb->bus = pci_register_bus(DEVICE(dev), "pci",
                                 pci_bonito_set_irq, pci_bonito_map_irq, dev,
@@ -716,7 +716,7 @@ static int bonito_initfn(PCIDevice *dev)
 {
     PCIBonitoState *s = DO_UPCAST(PCIBonitoState, dev, dev);
     SysBusDevice *sysbus = SYS_BUS_DEVICE(s->pcihost);
-    PCIHostState *phb = FROM_SYSBUS(PCIHostState, sysbus);
+    PCIHostState *phb = PCI_HOST_BRIDGE(s->pcihost);
 
     /* Bonito North Bridge, built on FPGA, VENDOR_ID/DEVICE_ID are "undefined" */
     pci_config_set_prog_interface(dev->config, 0x00);
@@ -785,7 +785,7 @@ PCIBus *bonito_init(qemu_irq *pic)
     PCIDevice *d;
 
     dev = qdev_create(NULL, TYPE_BONITO_PCI_HOST_BRIDGE);
-    phb = FROM_SYSBUS(PCIHostState, sysbus_from_qdev(dev));
+    phb = PCI_HOST_BRIDGE(dev);
     pcihost = BONITO_PCI_HOST_BRIDGE(dev);
     pcihost->pic = pic;
     qdev_init_nofail(dev);
@@ -833,7 +833,7 @@ static void bonito_pcihost_class_init(ObjectClass *klass, void *data)
 
 static const TypeInfo bonito_pcihost_info = {
     .name          = TYPE_BONITO_PCI_HOST_BRIDGE,
-    .parent        = TYPE_SYS_BUS_DEVICE,
+    .parent        = TYPE_PCI_HOST_BRIDGE,
     .instance_size = sizeof(BonitoState),
     .class_init    = bonito_pcihost_class_init,
 };
diff --git a/hw/dec_pci.c b/hw/dec_pci.c
index 19aed1b..de16361 100644
--- a/hw/dec_pci.c
+++ b/hw/dec_pci.c
@@ -91,7 +91,7 @@ static int pci_dec_21154_device_init(SysBusDevice *dev)
 {
     PCIHostState *phb;
 
-    phb = FROM_SYSBUS(PCIHostState, dev);
+    phb = PCI_HOST_BRIDGE(dev);
 
     memory_region_init_io(&phb->conf_mem, &pci_host_conf_le_ops,
                           dev, "pci-conf-idx", 0x1000);
@@ -136,7 +136,7 @@ static void pci_dec_21154_device_class_init(ObjectClass *klass, void *data)
 
 static const TypeInfo pci_dec_21154_device_info = {
     .name          = TYPE_DEC_21154,
-    .parent        = TYPE_SYS_BUS_DEVICE,
+    .parent        = TYPE_PCI_HOST_BRIDGE,
     .instance_size = sizeof(DECState),
     .class_init    = pci_dec_21154_device_class_init,
 };
diff --git a/hw/grackle_pci.c b/hw/grackle_pci.c
index d814270..066f6e1 100644
--- a/hw/grackle_pci.c
+++ b/hw/grackle_pci.c
@@ -73,7 +73,7 @@ PCIBus *pci_grackle_init(uint32_t base, qemu_irq *pic,
     dev = qdev_create(NULL, TYPE_GRACKLE_PCI_HOST_BRIDGE);
     qdev_init_nofail(dev);
     s = SYS_BUS_DEVICE(dev);
-    phb = FROM_SYSBUS(PCIHostState, s);
+    phb = PCI_HOST_BRIDGE(dev);
     d = GRACKLE_PCI_HOST_BRIDGE(dev);
 
     memory_region_init(&d->pci_mmio, "pci-mmio", 0x100000000ULL);
@@ -102,7 +102,7 @@ static int pci_grackle_init_device(SysBusDevice *dev)
 {
     PCIHostState *phb;
 
-    phb = FROM_SYSBUS(PCIHostState, dev);
+    phb = PCI_HOST_BRIDGE(dev);
 
     memory_region_init_io(&phb->conf_mem, &pci_host_conf_le_ops,
                           dev, "pci-conf-idx", 0x1000);
@@ -151,7 +151,7 @@ static void pci_grackle_class_init(ObjectClass *klass, void *data)
 
 static const TypeInfo grackle_pci_host_info = {
     .name          = TYPE_GRACKLE_PCI_HOST_BRIDGE,
-    .parent        = TYPE_SYS_BUS_DEVICE,
+    .parent        = TYPE_PCI_HOST_BRIDGE,
     .instance_size = sizeof(GrackleState),
     .class_init    = pci_grackle_class_init,
 };
diff --git a/hw/gt64xxx.c b/hw/gt64xxx.c
index 0677299..857758e 100644
--- a/hw/gt64xxx.c
+++ b/hw/gt64xxx.c
@@ -1095,7 +1095,7 @@ PCIBus *gt64120_register(qemu_irq *pic)
     dev = qdev_create(NULL, TYPE_GT64120_PCI_HOST_BRIDGE);
     qdev_init_nofail(dev);
     d = GT64120_PCI_HOST_BRIDGE(dev);
-    phb = &d->pci;
+    phb = PCI_HOST_BRIDGE(dev);
     phb->bus = pci_register_bus(dev, "pci",
                                 gt64120_pci_set_irq, gt64120_pci_map_irq,
                                 pic,
@@ -1168,7 +1168,7 @@ static void gt64120_class_init(ObjectClass *klass, void *data)
 
 static const TypeInfo gt64120_info = {
     .name          = TYPE_GT64120_PCI_HOST_BRIDGE,
-    .parent        = TYPE_SYS_BUS_DEVICE,
+    .parent        = TYPE_PCI_HOST_BRIDGE,
     .instance_size = sizeof(GT64120State),
     .class_init    = gt64120_class_init,
 };
diff --git a/hw/piix_pci.c b/hw/piix_pci.c
index 0b06a75..04ceccf 100644
--- a/hw/piix_pci.c
+++ b/hw/piix_pci.c
@@ -225,7 +225,7 @@ static const VMStateDescription vmstate_i440fx = {
 
 static int i440fx_pcihost_initfn(SysBusDevice *dev)
 {
-    I440FXState *s = FROM_SYSBUS(I440FXState, dev);
+    PCIHostState *s = PCI_HOST_BRIDGE(dev);
 
     memory_region_init_io(&s->conf_mem, &pci_host_conf_le_ops, s,
                           "pci-conf-idx", 4);
@@ -267,12 +267,12 @@ static PCIBus *i440fx_common_init(const char *device_name,
     DeviceState *dev;
     PCIBus *b;
     PCIDevice *d;
-    I440FXState *s;
+    PCIHostState *s;
     PIIX3State *piix3;
     PCII440FXState *f;
 
     dev = qdev_create(NULL, "i440FX-pcihost");
-    s = FROM_SYSBUS(I440FXState, sysbus_from_qdev(dev));
+    s = PCI_HOST_BRIDGE(dev);
     s->address_space = address_space_mem;
     b = pci_bus_new(&s->busdev.qdev, NULL, pci_address_space,
                     address_space_io, 0);
@@ -603,7 +603,7 @@ static void i440fx_pcihost_class_init(ObjectClass *klass, void *data)
 
 static const TypeInfo i440fx_pcihost_info = {
     .name          = "i440FX-pcihost",
-    .parent        = TYPE_SYS_BUS_DEVICE,
+    .parent        = TYPE_PCI_HOST_BRIDGE,
     .instance_size = sizeof(I440FXState),
     .class_init    = i440fx_pcihost_class_init,
 };
diff --git a/hw/ppc4xx_pci.c b/hw/ppc4xx_pci.c
index 599a75a..5583321 100644
--- a/hw/ppc4xx_pci.c
+++ b/hw/ppc4xx_pci.c
@@ -338,7 +338,7 @@ static int ppc4xx_pcihost_initfn(SysBusDevice *dev)
     PCIBus *b;
     int i;
 
-    h = FROM_SYSBUS(PCIHostState, dev);
+    h = PCI_HOST_BRIDGE(dev);
     s = PPC4xx_PCI_HOST_BRIDGE(dev);
 
     for (i = 0; i < ARRAY_SIZE(s->irq); i++) {
@@ -398,7 +398,7 @@ static void ppc4xx_pcihost_class_init(ObjectClass *klass, void *data)
 
 static const TypeInfo ppc4xx_pcihost_info = {
     .name          = TYPE_PPC4xx_PCI_HOST_BRIDGE,
-    .parent        = TYPE_SYS_BUS_DEVICE,
+    .parent        = TYPE_PCI_HOST_BRIDGE,
     .instance_size = sizeof(PPC4xxPCIState),
     .class_init    = ppc4xx_pcihost_class_init,
 };
diff --git a/hw/ppc_prep.c b/hw/ppc_prep.c
index 7a87616..592b7b2 100644
--- a/hw/ppc_prep.c
+++ b/hw/ppc_prep.c
@@ -471,7 +471,6 @@ static void ppc_prep_init (ram_addr_t ram_size,
     uint32_t kernel_base, initrd_base;
     long kernel_size, initrd_size;
     DeviceState *dev;
-    SysBusDevice *sys;
     PCIHostState *pcihost;
     PCIBus *pci_bus;
     PCIDevice *pci;
@@ -584,8 +583,7 @@ static void ppc_prep_init (ram_addr_t ram_size,
     }
 
     dev = qdev_create(NULL, "raven-pcihost");
-    sys = sysbus_from_qdev(dev);
-    pcihost = DO_UPCAST(PCIHostState, busdev, sys);
+    pcihost = PCI_HOST_BRIDGE(dev);
     pcihost->address_space = get_system_memory();
     object_property_add_child(qdev_get_machine(), "raven", OBJECT(dev), NULL);
     qdev_init_nofail(dev);
diff --git a/hw/ppce500_pci.c b/hw/ppce500_pci.c
index e4f065a..3333967 100644
--- a/hw/ppce500_pci.c
+++ b/hw/ppce500_pci.c
@@ -316,7 +316,7 @@ static int e500_pcihost_initfn(SysBusDevice *dev)
     MemoryRegion *address_space_mem = get_system_memory();
     MemoryRegion *address_space_io = get_system_io();
 
-    h = FROM_SYSBUS(PCIHostState, dev);
+    h = PCI_HOST_BRIDGE(dev);
     s = PPC_E500_PCI_HOST_BRIDGE(dev);
 
     for (i = 0; i < ARRAY_SIZE(s->irq); i++) {
@@ -374,7 +374,7 @@ static void e500_pcihost_class_init(ObjectClass *klass, void *data)
 
 static const TypeInfo e500_pcihost_info = {
     .name          = TYPE_PPC_E500_PCI_HOST_BRIDGE,
-    .parent        = TYPE_SYS_BUS_DEVICE,
+    .parent        = TYPE_PCI_HOST_BRIDGE,
     .instance_size = sizeof(PPCE500PCIState),
     .class_init    = e500_pcihost_class_init,
 };
diff --git a/hw/prep_pci.c b/hw/prep_pci.c
index 69c19df..35cb9b2 100644
--- a/hw/prep_pci.c
+++ b/hw/prep_pci.c
@@ -103,7 +103,7 @@ static void prep_set_irq(void *opaque, int irq_num, int level)
 
 static int raven_pcihost_init(SysBusDevice *dev)
 {
-    PCIHostState *h = FROM_SYSBUS(PCIHostState, dev);
+    PCIHostState *h = PCI_HOST_BRIDGE(dev);
     PREPPCIState *s = RAVEN_PCI_HOST_BRIDGE(dev);
     MemoryRegion *address_space_mem = get_system_memory();
     MemoryRegion *address_space_io = get_system_io();
@@ -192,7 +192,7 @@ static void raven_pcihost_class_init(ObjectClass *klass, void *data)
 
 static const TypeInfo raven_pcihost_info = {
     .name = TYPE_RAVEN_PCI_HOST_BRIDGE,
-    .parent = TYPE_SYS_BUS_DEVICE,
+    .parent = TYPE_PCI_HOST_BRIDGE,
     .instance_size = sizeof(PREPPCIState),
     .class_init = raven_pcihost_class_init,
 };
diff --git a/hw/spapr.c b/hw/spapr.c
index f8b53e9..c34b767 100644
--- a/hw/spapr.c
+++ b/hw/spapr.c
@@ -743,7 +743,7 @@ static void ppc_spapr_init(ram_addr_t ram_size,
                      SPAPR_PCI_MEM_WIN_SIZE,
                      SPAPR_PCI_IO_WIN_ADDR,
                      SPAPR_PCI_MSI_WIN_ADDR);
-    phb = &QLIST_FIRST(&spapr->phbs)->host_state;
+    phb = PCI_HOST_BRIDGE(QLIST_FIRST(&spapr->phbs));
 
     for (i = 0; i < nb_nics; i++) {
         NICInfo *nd = &nd_table[i];
diff --git a/hw/spapr_pci.c b/hw/spapr_pci.c
index f9dd2a8..661c05b 100644
--- a/hw/spapr_pci.c
+++ b/hw/spapr_pci.c
@@ -64,7 +64,7 @@ static PCIDevice *find_dev(sPAPREnvironment *spapr, uint64_t buid,
                            uint32_t config_addr)
 {
     sPAPRPHBState *sphb = find_phb(spapr, buid);
-    PCIHostState *phb = &sphb->host_state;
+    PCIHostState *phb = PCI_HOST_BRIDGE(sphb);
     BusState *bus = BUS(phb->bus);
     BusChild *kid;
     int devfn = (config_addr >> 8) & 0xFF;
@@ -517,7 +517,7 @@ static DMAContext *spapr_pci_dma_context_fn(PCIBus *bus, void *opaque,
 static int spapr_phb_init(SysBusDevice *s)
 {
     sPAPRPHBState *sphb = SPAPR_PCI_HOST_BRIDGE(s);
-    PCIHostState *phb = FROM_SYSBUS(PCIHostState, s);
+    PCIHostState *phb = PCI_HOST_BRIDGE(s);
     char *namebuf;
     int i;
     PCIBus *bus;
@@ -617,7 +617,7 @@ static void spapr_phb_class_init(ObjectClass *klass, void *data)
 
 static const TypeInfo spapr_phb_info = {
     .name          = TYPE_SPAPR_PCI_HOST_BRIDGE,
-    .parent        = TYPE_SYS_BUS_DEVICE,
+    .parent        = TYPE_PCI_HOST_BRIDGE,
     .instance_size = sizeof(sPAPRPHBState),
     .class_init    = spapr_phb_class_init,
 };
diff --git a/hw/unin_pci.c b/hw/unin_pci.c
index 1fc8920..0db7c1f 100644
--- a/hw/unin_pci.c
+++ b/hw/unin_pci.c
@@ -148,7 +148,7 @@ static int pci_unin_main_init_device(SysBusDevice *dev)
 
     /* Use values found on a real PowerMac */
     /* Uninorth main bus */
-    h = FROM_SYSBUS(PCIHostState, dev);
+    h = PCI_HOST_BRIDGE(dev);
 
     memory_region_init_io(&h->conf_mem, &pci_host_conf_le_ops,
                           dev, "pci-conf-idx", 0x1000);
@@ -166,7 +166,7 @@ static int pci_u3_agp_init_device(SysBusDevice *dev)
     PCIHostState *h;
 
     /* Uninorth U3 AGP bus */
-    h = FROM_SYSBUS(PCIHostState, dev);
+    h = PCI_HOST_BRIDGE(dev);
 
     memory_region_init_io(&h->conf_mem, &pci_host_conf_le_ops,
                           dev, "pci-conf-idx", 0x1000);
@@ -183,7 +183,7 @@ static int pci_unin_agp_init_device(SysBusDevice *dev)
     PCIHostState *h;
 
     /* Uninorth AGP bus */
-    h = FROM_SYSBUS(PCIHostState, dev);
+    h = PCI_HOST_BRIDGE(dev);
 
     memory_region_init_io(&h->conf_mem, &pci_host_conf_le_ops,
                           dev, "pci-conf-idx", 0x1000);
@@ -199,7 +199,7 @@ static int pci_unin_internal_init_device(SysBusDevice *dev)
     PCIHostState *h;
 
     /* Uninorth internal bus */
-    h = FROM_SYSBUS(PCIHostState, dev);
+    h = PCI_HOST_BRIDGE(dev);
 
     memory_region_init_io(&h->conf_mem, &pci_host_conf_le_ops,
                           dev, "pci-conf-idx", 0x1000);
@@ -224,7 +224,7 @@ PCIBus *pci_pmac_init(qemu_irq *pic,
     dev = qdev_create(NULL, TYPE_UNI_NORTH_PCI_HOST_BRIDGE);
     qdev_init_nofail(dev);
     s = SYS_BUS_DEVICE(dev);
-    h = FROM_SYSBUS(PCIHostState, s);
+    h = PCI_HOST_BRIDGE(s);
     d = UNI_NORTH_PCI_HOST_BRIDGE(dev);
     memory_region_init(&d->pci_mmio, "pci-mmio", 0x100000000ULL);
     memory_region_init_alias(&d->pci_hole, "pci-hole", &d->pci_mmio,
@@ -289,7 +289,7 @@ PCIBus *pci_pmac_u3_init(qemu_irq *pic,
     dev = qdev_create(NULL, TYPE_U3_AGP_HOST_BRIDGE);
     qdev_init_nofail(dev);
     s = SYS_BUS_DEVICE(dev);
-    h = FROM_SYSBUS(PCIHostState, s);
+    h = PCI_HOST_BRIDGE(dev);
     d = U3_AGP_HOST_BRIDGE(dev);
 
     memory_region_init(&d->pci_mmio, "pci-mmio", 0x100000000ULL);
@@ -427,7 +427,7 @@ static void pci_unin_main_class_init(ObjectClass *klass, void *data)
 
 static const TypeInfo pci_unin_main_info = {
     .name          = TYPE_UNI_NORTH_PCI_HOST_BRIDGE,
-    .parent        = TYPE_SYS_BUS_DEVICE,
+    .parent        = TYPE_PCI_HOST_BRIDGE,
     .instance_size = sizeof(UNINState),
     .class_init    = pci_unin_main_class_init,
 };
@@ -441,7 +441,7 @@ static void pci_u3_agp_class_init(ObjectClass *klass, void *data)
 
 static const TypeInfo pci_u3_agp_info = {
     .name          = TYPE_U3_AGP_HOST_BRIDGE,
-    .parent        = TYPE_SYS_BUS_DEVICE,
+    .parent        = TYPE_PCI_HOST_BRIDGE,
     .instance_size = sizeof(UNINState),
     .class_init    = pci_u3_agp_class_init,
 };
@@ -455,7 +455,7 @@ static void pci_unin_agp_class_init(ObjectClass *klass, void *data)
 
 static const TypeInfo pci_unin_agp_info = {
     .name          = TYPE_UNI_NORTH_AGP_HOST_BRIDGE,
-    .parent        = TYPE_SYS_BUS_DEVICE,
+    .parent        = TYPE_PCI_HOST_BRIDGE,
     .instance_size = sizeof(UNINState),
     .class_init    = pci_unin_agp_class_init,
 };
@@ -469,7 +469,7 @@ static void pci_unin_internal_class_init(ObjectClass *klass, void *data)
 
 static const TypeInfo pci_unin_internal_info = {
     .name          = TYPE_UNI_NORTH_INTERNAL_PCI_HOST_BRIDGE,
-    .parent        = TYPE_SYS_BUS_DEVICE,
+    .parent        = TYPE_PCI_HOST_BRIDGE,
     .instance_size = sizeof(UNINState),
     .class_init    = pci_unin_internal_class_init,
 };
commit b44ff9d430c5f2b51872f542d9562a15f0061a82
Author: Andreas Färber <andreas.faerber at web.de>
Date:   Mon Aug 20 19:08:07 2012 +0200

    pci_host: Turn into SysBus-derived QOM type
    
    The preceding commits fixed misuses of FROM_SYSBUS() that led people to
    add a bogus busdev field. For qdev the field order was less relevant but
    for QOM the PCIHostState field (including the SysBusDevice actually
    initialized with a value) must be placed first within the state struct.
    
    To facilitate accessing the PCIHostState fields, derive all PCI host
    bridges from TYPE_PCI_HOST_BRIDGE rather than TYPE_SYS_BUS_DEVICE.
    
    We can now access PCIHostState QOM-style, with PCI_HOST_BRIDGE() macro.
    
    Signed-off-by: Anthony Liguori <aliguori at us.ibm.com>
    Signed-off-by: Wanpeng Li <liwanp at linux.vnet.ibm.com>
    Signed-off-by: Andreas Färber <andreas.faerber at web.de>
    Signed-off-by: Andreas Färber <afaerber at suse.de>
    Acked-by: Michael S. Tsirkin <mst at redhat.com>
    Signed-off-by: Anthony Liguori <aliguori at us.ibm.com>

diff --git a/hw/pci_host.c b/hw/pci_host.c
index 8041778..3950e94 100644
--- a/hw/pci_host.c
+++ b/hw/pci_host.c
@@ -165,4 +165,16 @@ const MemoryRegionOps pci_host_data_be_ops = {
     .endianness = DEVICE_BIG_ENDIAN,
 };
 
+static const TypeInfo pci_host_type_info = {
+    .name = TYPE_PCI_HOST_BRIDGE,
+    .parent = TYPE_SYS_BUS_DEVICE,
+    .abstract = true,
+    .instance_size = sizeof(PCIHostState),
+};
+
+static void pci_host_register_types(void)
+{
+    type_register_static(&pci_host_type_info);
+}
 
+type_init(pci_host_register_types)
diff --git a/hw/pci_host.h b/hw/pci_host.h
index 359e38f..4b9c300 100644
--- a/hw/pci_host.h
+++ b/hw/pci_host.h
@@ -30,8 +30,13 @@
 
 #include "sysbus.h"
 
+#define TYPE_PCI_HOST_BRIDGE "pci-host-bridge"
+#define PCI_HOST_BRIDGE(obj) \
+    OBJECT_CHECK(PCIHostState, (obj), TYPE_PCI_HOST_BRIDGE)
+
 struct PCIHostState {
     SysBusDevice busdev;
+
     MemoryRegion conf_mem;
     MemoryRegion data_mem;
     MemoryRegion mmcfg;
commit 57fd7b7fce9098cdac58a8442033cb91412400b9
Author: Andreas Färber <afaerber at suse.de>
Date:   Mon Aug 20 19:08:06 2012 +0200

    unin_pci: QOM'ify UniNorth PCI host bridges
    
    Introduce type constants and cast macros.
    Avoid accessing parent fields directly.
    
    Signed-off-by: Andreas Färber <afaerber at suse.de>
    Acked-by: Michael S. Tsirkin <mst at redhat.com>
    Signed-off-by: Anthony Liguori <aliguori at us.ibm.com>

diff --git a/hw/unin_pci.c b/hw/unin_pci.c
index 2b309df..1fc8920 100644
--- a/hw/unin_pci.c
+++ b/hw/unin_pci.c
@@ -38,8 +38,23 @@
 
 static const int unin_irq_line[] = { 0x1b, 0x1c, 0x1d, 0x1e };
 
+#define TYPE_UNI_NORTH_PCI_HOST_BRIDGE "uni-north-pci-pcihost"
+#define TYPE_UNI_NORTH_AGP_HOST_BRIDGE "uni-north-agp-pcihost"
+#define TYPE_UNI_NORTH_INTERNAL_PCI_HOST_BRIDGE "uni-north-internal-pci-pcihost"
+#define TYPE_U3_AGP_HOST_BRIDGE "u3-agp-pcihost"
+
+#define UNI_NORTH_PCI_HOST_BRIDGE(obj) \
+    OBJECT_CHECK(UNINState, (obj), TYPE_UNI_NORTH_PCI_HOST_BRIDGE)
+#define UNI_NORTH_AGP_HOST_BRIDGE(obj) \
+    OBJECT_CHECK(UNINState, (obj), TYPE_UNI_NORTH_AGP_HOST_BRIDGE)
+#define UNI_NORTH_INTERNAL_PCI_HOST_BRIDGE(obj) \
+    OBJECT_CHECK(UNINState, (obj), TYPE_UNI_NORTH_INTERNAL_PCI_HOST_BRIDGE)
+#define U3_AGP_HOST_BRIDGE(obj) \
+    OBJECT_CHECK(UNINState, (obj), TYPE_U3_AGP_HOST_BRIDGE)
+
 typedef struct UNINState {
     PCIHostState host_state;
+
     MemoryRegion pci_mmio;
     MemoryRegion pci_hole;
 } UNINState;
@@ -130,19 +145,17 @@ static const MemoryRegionOps unin_data_ops = {
 static int pci_unin_main_init_device(SysBusDevice *dev)
 {
     PCIHostState *h;
-    UNINState *s;
 
     /* Use values found on a real PowerMac */
     /* Uninorth main bus */
     h = FROM_SYSBUS(PCIHostState, dev);
-    s = DO_UPCAST(UNINState, host_state, h);
 
-    memory_region_init_io(&s->host_state.conf_mem, &pci_host_conf_le_ops,
-                          &s->host_state, "pci-conf-idx", 0x1000);
-    memory_region_init_io(&s->host_state.data_mem, &unin_data_ops, s,
+    memory_region_init_io(&h->conf_mem, &pci_host_conf_le_ops,
+                          dev, "pci-conf-idx", 0x1000);
+    memory_region_init_io(&h->data_mem, &unin_data_ops, dev,
                           "pci-conf-data", 0x1000);
-    sysbus_init_mmio(dev, &s->host_state.conf_mem);
-    sysbus_init_mmio(dev, &s->host_state.data_mem);
+    sysbus_init_mmio(dev, &h->conf_mem);
+    sysbus_init_mmio(dev, &h->data_mem);
 
     return 0;
 }
@@ -151,18 +164,16 @@ static int pci_unin_main_init_device(SysBusDevice *dev)
 static int pci_u3_agp_init_device(SysBusDevice *dev)
 {
     PCIHostState *h;
-    UNINState *s;
 
     /* Uninorth U3 AGP bus */
     h = FROM_SYSBUS(PCIHostState, dev);
-    s = DO_UPCAST(UNINState, host_state, h);
 
-    memory_region_init_io(&s->host_state.conf_mem, &pci_host_conf_le_ops,
-                          &s->host_state, "pci-conf-idx", 0x1000);
-    memory_region_init_io(&s->host_state.data_mem, &unin_data_ops, s,
+    memory_region_init_io(&h->conf_mem, &pci_host_conf_le_ops,
+                          dev, "pci-conf-idx", 0x1000);
+    memory_region_init_io(&h->data_mem, &unin_data_ops, dev,
                           "pci-conf-data", 0x1000);
-    sysbus_init_mmio(dev, &s->host_state.conf_mem);
-    sysbus_init_mmio(dev, &s->host_state.data_mem);
+    sysbus_init_mmio(dev, &h->conf_mem);
+    sysbus_init_mmio(dev, &h->data_mem);
 
     return 0;
 }
@@ -170,36 +181,32 @@ static int pci_u3_agp_init_device(SysBusDevice *dev)
 static int pci_unin_agp_init_device(SysBusDevice *dev)
 {
     PCIHostState *h;
-    UNINState *s;
 
     /* Uninorth AGP bus */
     h = FROM_SYSBUS(PCIHostState, dev);
-    s = DO_UPCAST(UNINState, host_state, h);
-
-    memory_region_init_io(&s->host_state.conf_mem, &pci_host_conf_le_ops,
-                          &s->host_state, "pci-conf-idx", 0x1000);
-    memory_region_init_io(&s->host_state.data_mem, &pci_host_data_le_ops,
-                          &s->host_state, "pci-conf-data", 0x1000);
-    sysbus_init_mmio(dev, &s->host_state.conf_mem);
-    sysbus_init_mmio(dev, &s->host_state.data_mem);
+
+    memory_region_init_io(&h->conf_mem, &pci_host_conf_le_ops,
+                          dev, "pci-conf-idx", 0x1000);
+    memory_region_init_io(&h->data_mem, &pci_host_data_le_ops,
+                          dev, "pci-conf-data", 0x1000);
+    sysbus_init_mmio(dev, &h->conf_mem);
+    sysbus_init_mmio(dev, &h->data_mem);
     return 0;
 }
 
 static int pci_unin_internal_init_device(SysBusDevice *dev)
 {
     PCIHostState *h;
-    UNINState *s;
 
     /* Uninorth internal bus */
     h = FROM_SYSBUS(PCIHostState, dev);
-    s = DO_UPCAST(UNINState, host_state, h);
-
-    memory_region_init_io(&s->host_state.conf_mem, &pci_host_conf_le_ops,
-                          &s->host_state, "pci-conf-idx", 0x1000);
-    memory_region_init_io(&s->host_state.data_mem, &pci_host_data_le_ops,
-                          &s->host_state, "pci-conf-data", 0x1000);
-    sysbus_init_mmio(dev, &s->host_state.conf_mem);
-    sysbus_init_mmio(dev, &s->host_state.data_mem);
+
+    memory_region_init_io(&h->conf_mem, &pci_host_conf_le_ops,
+                          dev, "pci-conf-idx", 0x1000);
+    memory_region_init_io(&h->data_mem, &pci_host_data_le_ops,
+                          dev, "pci-conf-data", 0x1000);
+    sysbus_init_mmio(dev, &h->conf_mem);
+    sysbus_init_mmio(dev, &h->data_mem);
     return 0;
 }
 
@@ -214,26 +221,26 @@ PCIBus *pci_pmac_init(qemu_irq *pic,
 
     /* Use values found on a real PowerMac */
     /* Uninorth main bus */
-    dev = qdev_create(NULL, "uni-north-pci-pcihost");
+    dev = qdev_create(NULL, TYPE_UNI_NORTH_PCI_HOST_BRIDGE);
     qdev_init_nofail(dev);
-    s = sysbus_from_qdev(dev);
+    s = SYS_BUS_DEVICE(dev);
     h = FROM_SYSBUS(PCIHostState, s);
-    d = DO_UPCAST(UNINState, host_state, h);
+    d = UNI_NORTH_PCI_HOST_BRIDGE(dev);
     memory_region_init(&d->pci_mmio, "pci-mmio", 0x100000000ULL);
     memory_region_init_alias(&d->pci_hole, "pci-hole", &d->pci_mmio,
                              0x80000000ULL, 0x70000000ULL);
     memory_region_add_subregion(address_space_mem, 0x80000000ULL,
                                 &d->pci_hole);
 
-    d->host_state.bus = pci_register_bus(dev, "pci",
-                                         pci_unin_set_irq, pci_unin_map_irq,
-                                         pic,
-                                         &d->pci_mmio,
-                                         address_space_io,
-                                         PCI_DEVFN(11, 0), 4);
+    h->bus = pci_register_bus(dev, "pci",
+                              pci_unin_set_irq, pci_unin_map_irq,
+                              pic,
+                              &d->pci_mmio,
+                              address_space_io,
+                              PCI_DEVFN(11, 0), 4);
 
 #if 0
-    pci_create_simple(d->host_state.bus, PCI_DEVFN(11, 0), "uni-north");
+    pci_create_simple(h->bus, PCI_DEVFN(11, 0), "uni-north");
 #endif
 
     sysbus_mmio_map(s, 0, 0xf2800000);
@@ -242,30 +249,30 @@ PCIBus *pci_pmac_init(qemu_irq *pic,
     /* DEC 21154 bridge */
 #if 0
     /* XXX: not activated as PPC BIOS doesn't handle multiple buses properly */
-    pci_create_simple(d->host_state.bus, PCI_DEVFN(12, 0), "dec-21154");
+    pci_create_simple(h->bus, PCI_DEVFN(12, 0), "dec-21154");
 #endif
 
     /* Uninorth AGP bus */
-    pci_create_simple(d->host_state.bus, PCI_DEVFN(11, 0), "uni-north-agp");
-    dev = qdev_create(NULL, "uni-north-agp-pcihost");
+    pci_create_simple(h->bus, PCI_DEVFN(11, 0), "uni-north-agp");
+    dev = qdev_create(NULL, TYPE_UNI_NORTH_AGP_HOST_BRIDGE);
     qdev_init_nofail(dev);
-    s = sysbus_from_qdev(dev);
+    s = SYS_BUS_DEVICE(dev);
     sysbus_mmio_map(s, 0, 0xf0800000);
     sysbus_mmio_map(s, 1, 0xf0c00000);
 
     /* Uninorth internal bus */
 #if 0
     /* XXX: not needed for now */
-    pci_create_simple(d->host_state.bus, PCI_DEVFN(14, 0),
+    pci_create_simple(h->bus, PCI_DEVFN(14, 0),
                       "uni-north-internal-pci");
-    dev = qdev_create(NULL, "uni-north-internal-pci-pcihost");
+    dev = qdev_create(NULL, TYPE_UNI_NORTH_INTERNAL_PCI_HOST_BRIDGE);
     qdev_init_nofail(dev);
-    s = sysbus_from_qdev(dev);
+    s = SYS_BUS_DEVICE(dev);
     sysbus_mmio_map(s, 0, 0xf4800000);
     sysbus_mmio_map(s, 1, 0xf4c00000);
 #endif
 
-    return d->host_state.bus;
+    return h->bus;
 }
 
 PCIBus *pci_pmac_u3_init(qemu_irq *pic,
@@ -279,11 +286,11 @@ PCIBus *pci_pmac_u3_init(qemu_irq *pic,
 
     /* Uninorth AGP bus */
 
-    dev = qdev_create(NULL, "u3-agp-pcihost");
+    dev = qdev_create(NULL, TYPE_U3_AGP_HOST_BRIDGE);
     qdev_init_nofail(dev);
-    s = sysbus_from_qdev(dev);
+    s = SYS_BUS_DEVICE(dev);
     h = FROM_SYSBUS(PCIHostState, s);
-    d = DO_UPCAST(UNINState, host_state, h);
+    d = U3_AGP_HOST_BRIDGE(dev);
 
     memory_region_init(&d->pci_mmio, "pci-mmio", 0x100000000ULL);
     memory_region_init_alias(&d->pci_hole, "pci-hole", &d->pci_mmio,
@@ -291,19 +298,19 @@ PCIBus *pci_pmac_u3_init(qemu_irq *pic,
     memory_region_add_subregion(address_space_mem, 0x80000000ULL,
                                 &d->pci_hole);
 
-    d->host_state.bus = pci_register_bus(dev, "pci",
-                                         pci_unin_set_irq, pci_unin_map_irq,
-                                         pic,
-                                         &d->pci_mmio,
-                                         address_space_io,
-                                         PCI_DEVFN(11, 0), 4);
+    h->bus = pci_register_bus(dev, "pci",
+                              pci_unin_set_irq, pci_unin_map_irq,
+                              pic,
+                              &d->pci_mmio,
+                              address_space_io,
+                              PCI_DEVFN(11, 0), 4);
 
     sysbus_mmio_map(s, 0, 0xf0800000);
     sysbus_mmio_map(s, 1, 0xf0c00000);
 
-    pci_create_simple(d->host_state.bus, 11 << 3, "u3-agp");
+    pci_create_simple(h->bus, 11 << 3, "u3-agp");
 
-    return d->host_state.bus;
+    return h->bus;
 }
 
 static int unin_main_pci_host_init(PCIDevice *d)
@@ -419,7 +426,7 @@ static void pci_unin_main_class_init(ObjectClass *klass, void *data)
 }
 
 static const TypeInfo pci_unin_main_info = {
-    .name          = "uni-north-pci-pcihost",
+    .name          = TYPE_UNI_NORTH_PCI_HOST_BRIDGE,
     .parent        = TYPE_SYS_BUS_DEVICE,
     .instance_size = sizeof(UNINState),
     .class_init    = pci_unin_main_class_init,
@@ -433,7 +440,7 @@ static void pci_u3_agp_class_init(ObjectClass *klass, void *data)
 }
 
 static const TypeInfo pci_u3_agp_info = {
-    .name          = "u3-agp-pcihost",
+    .name          = TYPE_U3_AGP_HOST_BRIDGE,
     .parent        = TYPE_SYS_BUS_DEVICE,
     .instance_size = sizeof(UNINState),
     .class_init    = pci_u3_agp_class_init,
@@ -447,7 +454,7 @@ static void pci_unin_agp_class_init(ObjectClass *klass, void *data)
 }
 
 static const TypeInfo pci_unin_agp_info = {
-    .name          = "uni-north-agp-pcihost",
+    .name          = TYPE_UNI_NORTH_AGP_HOST_BRIDGE,
     .parent        = TYPE_SYS_BUS_DEVICE,
     .instance_size = sizeof(UNINState),
     .class_init    = pci_unin_agp_class_init,
@@ -461,7 +468,7 @@ static void pci_unin_internal_class_init(ObjectClass *klass, void *data)
 }
 
 static const TypeInfo pci_unin_internal_info = {
-    .name          = "uni-north-internal-pci-pcihost",
+    .name          = TYPE_UNI_NORTH_INTERNAL_PCI_HOST_BRIDGE,
     .parent        = TYPE_SYS_BUS_DEVICE,
     .instance_size = sizeof(UNINState),
     .class_init    = pci_unin_internal_class_init,
commit 8c9f64df3dd76c253e4961c5d2f075bffcc29e1d
Author: Andreas Färber <afaerber at suse.de>
Date:   Mon Aug 20 19:08:05 2012 +0200

    spapr_pci: QOM'ify sPAPR PCI host bridge
    
    Introduce type constant. Introduce cast macro to drop bogus busdev field
    that would've broken SYS_BUS_DEVICE(). Avoid accessing parent fields
    directly.
    
    Free the identifier phb as acronym for PCI_HOST_BRIDGE.
    
    Updated against conflicting merge from branch 'agraf/ppc-for-upstream'
    (0d16fdd732d1b211842fa96b7c90ddf9e6bde0e4), which removed busdev field
    differently, moved some code around and added new occurrences of 'phb'.
    
    Signed-off-by: Andreas Färber <afaerber at suse.de>
    Signed-off-by: Anthony Liguori <aliguori at us.ibm.com>

diff --git a/hw/spapr.c b/hw/spapr.c
index be533ee..f8b53e9 100644
--- a/hw/spapr.c
+++ b/hw/spapr.c
@@ -612,6 +612,7 @@ static void ppc_spapr_init(ram_addr_t ram_size,
 {
     PowerPCCPU *cpu;
     CPUPPCState *env;
+    PCIHostState *phb;
     int i;
     MemoryRegion *sysmem = get_system_memory();
     MemoryRegion *ram = g_new(MemoryRegion, 1);
@@ -742,6 +743,7 @@ static void ppc_spapr_init(ram_addr_t ram_size,
                      SPAPR_PCI_MEM_WIN_SIZE,
                      SPAPR_PCI_IO_WIN_ADDR,
                      SPAPR_PCI_MSI_WIN_ADDR);
+    phb = &QLIST_FIRST(&spapr->phbs)->host_state;
 
     for (i = 0; i < nb_nics; i++) {
         NICInfo *nd = &nd_table[i];
@@ -762,13 +764,12 @@ static void ppc_spapr_init(ram_addr_t ram_size,
     }
 
     /* Graphics */
-    if (spapr_vga_init(QLIST_FIRST(&spapr->phbs)->host_state.bus)) {
+    if (spapr_vga_init(phb->bus)) {
         spapr->has_graphics = true;
     }
 
     if (usb_enabled) {
-        pci_create_simple(QLIST_FIRST(&spapr->phbs)->host_state.bus,
-                          -1, "pci-ohci");
+        pci_create_simple(phb->bus, -1, "pci-ohci");
         if (spapr->has_graphics) {
             usbdevice_create("keyboard");
             usbdevice_create("mouse");
diff --git a/hw/spapr_pci.c b/hw/spapr_pci.c
index c57ab1e..f9dd2a8 100644
--- a/hw/spapr_pci.c
+++ b/hw/spapr_pci.c
@@ -48,13 +48,13 @@
 
 static sPAPRPHBState *find_phb(sPAPREnvironment *spapr, uint64_t buid)
 {
-    sPAPRPHBState *phb;
+    sPAPRPHBState *sphb;
 
-    QLIST_FOREACH(phb, &spapr->phbs, list) {
-        if (phb->buid != buid) {
+    QLIST_FOREACH(sphb, &spapr->phbs, list) {
+        if (sphb->buid != buid) {
             continue;
         }
-        return phb;
+        return sphb;
     }
 
     return NULL;
@@ -63,7 +63,9 @@ static sPAPRPHBState *find_phb(sPAPREnvironment *spapr, uint64_t buid)
 static PCIDevice *find_dev(sPAPREnvironment *spapr, uint64_t buid,
                            uint32_t config_addr)
 {
-    sPAPRPHBState *phb = find_phb(spapr, buid);
+    sPAPRPHBState *sphb = find_phb(spapr, buid);
+    PCIHostState *phb = &sphb->host_state;
+    BusState *bus = BUS(phb->bus);
     BusChild *kid;
     int devfn = (config_addr >> 8) & 0xFF;
 
@@ -71,7 +73,7 @@ static PCIDevice *find_dev(sPAPREnvironment *spapr, uint64_t buid,
         return NULL;
     }
 
-    QTAILQ_FOREACH(kid, &phb->host_state.bus->qbus.children, sibling) {
+    QTAILQ_FOREACH(kid, &bus->children, sibling) {
         PCIDevice *dev = (PCIDevice *)kid->child;
         if (dev->devfn == devfn) {
             return dev;
@@ -514,23 +516,24 @@ static DMAContext *spapr_pci_dma_context_fn(PCIBus *bus, void *opaque,
 
 static int spapr_phb_init(SysBusDevice *s)
 {
-    sPAPRPHBState *phb = DO_UPCAST(sPAPRPHBState, host_state.busdev, s);
+    sPAPRPHBState *sphb = SPAPR_PCI_HOST_BRIDGE(s);
+    PCIHostState *phb = FROM_SYSBUS(PCIHostState, s);
     char *namebuf;
     int i;
     PCIBus *bus;
 
-    phb->dtbusname = g_strdup_printf("pci@%" PRIx64, phb->buid);
-    namebuf = alloca(strlen(phb->dtbusname) + 32);
+    sphb->dtbusname = g_strdup_printf("pci@%" PRIx64, sphb->buid);
+    namebuf = alloca(strlen(sphb->dtbusname) + 32);
 
     /* Initialize memory regions */
-    sprintf(namebuf, "%s.mmio", phb->dtbusname);
-    memory_region_init(&phb->memspace, namebuf, INT64_MAX);
+    sprintf(namebuf, "%s.mmio", sphb->dtbusname);
+    memory_region_init(&sphb->memspace, namebuf, INT64_MAX);
 
-    sprintf(namebuf, "%s.mmio-alias", phb->dtbusname);
-    memory_region_init_alias(&phb->memwindow, namebuf, &phb->memspace,
-                             SPAPR_PCI_MEM_WIN_BUS_OFFSET, phb->mem_win_size);
-    memory_region_add_subregion(get_system_memory(), phb->mem_win_addr,
-                                &phb->memwindow);
+    sprintf(namebuf, "%s.mmio-alias", sphb->dtbusname);
+    memory_region_init_alias(&sphb->memwindow, namebuf, &sphb->memspace,
+                             SPAPR_PCI_MEM_WIN_BUS_OFFSET, sphb->mem_win_size);
+    memory_region_add_subregion(get_system_memory(), sphb->mem_win_addr,
+                                &sphb->memwindow);
 
     /* On ppc, we only have MMIO no specific IO space from the CPU
      * perspective.  In theory we ought to be able to embed the PCI IO
@@ -540,42 +543,42 @@ static int spapr_phb_init(SysBusDevice *s)
      * system io address space.  This hack to bounce things via
      * system_io works around the problem until all the users of
      * old_portion are updated */
-    sprintf(namebuf, "%s.io", phb->dtbusname);
-    memory_region_init(&phb->iospace, namebuf, SPAPR_PCI_IO_WIN_SIZE);
+    sprintf(namebuf, "%s.io", sphb->dtbusname);
+    memory_region_init(&sphb->iospace, namebuf, SPAPR_PCI_IO_WIN_SIZE);
     /* FIXME: fix to support multiple PHBs */
-    memory_region_add_subregion(get_system_io(), 0, &phb->iospace);
+    memory_region_add_subregion(get_system_io(), 0, &sphb->iospace);
 
-    sprintf(namebuf, "%s.io-alias", phb->dtbusname);
-    memory_region_init_io(&phb->iowindow, &spapr_io_ops, phb,
+    sprintf(namebuf, "%s.io-alias", sphb->dtbusname);
+    memory_region_init_io(&sphb->iowindow, &spapr_io_ops, sphb,
                           namebuf, SPAPR_PCI_IO_WIN_SIZE);
-    memory_region_add_subregion(get_system_memory(), phb->io_win_addr,
-                                &phb->iowindow);
+    memory_region_add_subregion(get_system_memory(), sphb->io_win_addr,
+                                &sphb->iowindow);
 
     /* As MSI/MSIX interrupts trigger by writing at MSI/MSIX vectors,
      * we need to allocate some memory to catch those writes coming
      * from msi_notify()/msix_notify() */
     if (msi_supported) {
-        sprintf(namebuf, "%s.msi", phb->dtbusname);
-        memory_region_init_io(&phb->msiwindow, &spapr_msi_ops, phb,
+        sprintf(namebuf, "%s.msi", sphb->dtbusname);
+        memory_region_init_io(&sphb->msiwindow, &spapr_msi_ops, sphb,
                               namebuf, SPAPR_MSIX_MAX_DEVS * 0x10000);
-        memory_region_add_subregion(get_system_memory(), phb->msi_win_addr,
-                                    &phb->msiwindow);
+        memory_region_add_subregion(get_system_memory(), sphb->msi_win_addr,
+                                    &sphb->msiwindow);
     }
 
-    bus = pci_register_bus(&phb->host_state.busdev.qdev,
-                           phb->busname ? phb->busname : phb->dtbusname,
-                           pci_spapr_set_irq, pci_spapr_map_irq, phb,
-                           &phb->memspace, &phb->iospace,
+    bus = pci_register_bus(DEVICE(s),
+                           sphb->busname ? sphb->busname : sphb->dtbusname,
+                           pci_spapr_set_irq, pci_spapr_map_irq, sphb,
+                           &sphb->memspace, &sphb->iospace,
                            PCI_DEVFN(0, 0), PCI_NUM_PINS);
-    phb->host_state.bus = bus;
+    phb->bus = bus;
 
-    phb->dma_liobn = SPAPR_PCI_BASE_LIOBN | (pci_find_domain(bus) << 16);
-    phb->dma_window_start = 0;
-    phb->dma_window_size = 0x40000000;
-    phb->dma = spapr_tce_new_dma_context(phb->dma_liobn, phb->dma_window_size);
-    pci_setup_iommu(bus, spapr_pci_dma_context_fn, phb);
+    sphb->dma_liobn = SPAPR_PCI_BASE_LIOBN | (pci_find_domain(bus) << 16);
+    sphb->dma_window_start = 0;
+    sphb->dma_window_size = 0x40000000;
+    sphb->dma = spapr_tce_new_dma_context(sphb->dma_liobn, sphb->dma_window_size);
+    pci_setup_iommu(bus, spapr_pci_dma_context_fn, sphb);
 
-    QLIST_INSERT_HEAD(&spapr->phbs, phb, list);
+    QLIST_INSERT_HEAD(&spapr->phbs, sphb, list);
 
     /* Initialize the LSI table */
     for (i = 0; i < PCI_NUM_PINS; i++) {
@@ -586,7 +589,7 @@ static int spapr_phb_init(SysBusDevice *s)
             return -1;
         }
 
-        phb->lsi_table[i].irq = irq;
+        sphb->lsi_table[i].irq = irq;
     }
 
     return 0;
@@ -613,7 +616,7 @@ static void spapr_phb_class_init(ObjectClass *klass, void *data)
 }
 
 static const TypeInfo spapr_phb_info = {
-    .name          = "spapr-pci-host-bridge",
+    .name          = TYPE_SPAPR_PCI_HOST_BRIDGE,
     .parent        = TYPE_SYS_BUS_DEVICE,
     .instance_size = sizeof(sPAPRPHBState),
     .class_init    = spapr_phb_class_init,
@@ -626,7 +629,7 @@ void spapr_create_phb(sPAPREnvironment *spapr,
 {
     DeviceState *dev;
 
-    dev = qdev_create(NULL, spapr_phb_info.name);
+    dev = qdev_create(NULL, TYPE_SPAPR_PCI_HOST_BRIDGE);
 
     if (busname) {
         qdev_prop_set_string(dev, "busname", g_strdup(busname));
@@ -750,8 +753,9 @@ void spapr_pci_rtas_init(void)
     }
 }
 
-static void register_types(void)
+static void spapr_pci_register_types(void)
 {
     type_register_static(&spapr_phb_info);
 }
-type_init(register_types)
+
+type_init(spapr_pci_register_types)
diff --git a/hw/spapr_pci.h b/hw/spapr_pci.h
index 7518899..4140ee6 100644
--- a/hw/spapr_pci.h
+++ b/hw/spapr_pci.h
@@ -29,6 +29,11 @@
 
 #define SPAPR_MSIX_MAX_DEVS 32
 
+#define TYPE_SPAPR_PCI_HOST_BRIDGE "spapr-pci-host-bridge"
+
+#define SPAPR_PCI_HOST_BRIDGE(obj) \
+    OBJECT_CHECK(sPAPRPHBState, (obj), TYPE_SPAPR_PCI_HOST_BRIDGE)
+
 typedef struct sPAPRPHBState {
     PCIHostState host_state;
 
commit 03a6b667702b0af0e7b36754489aed6aa82d30a1
Author: Andreas Färber <afaerber at suse.de>
Date:   Mon Aug 20 19:08:04 2012 +0200

    prep_pci: QOM'ify Raven PCI host bridge
    
    Introduce type constant and cast macro. Avoid accessing parent fields
    directly.
    
    Also add missing space and braces.
    
    Signed-off-by: Andreas Färber <afaerber at suse.de>
    Acked-by: Michael S. Tsirkin <mst at redhat.com>
    Signed-off-by: Anthony Liguori <aliguori at us.ibm.com>

diff --git a/hw/prep_pci.c b/hw/prep_pci.c
index a8cdc21..69c19df 100644
--- a/hw/prep_pci.c
+++ b/hw/prep_pci.c
@@ -28,8 +28,14 @@
 #include "pc.h"
 #include "exec-memory.h"
 
+#define TYPE_RAVEN_PCI_HOST_BRIDGE "raven-pcihost"
+
+#define RAVEN_PCI_HOST_BRIDGE(obj) \
+    OBJECT_CHECK(PREPPCIState, (obj), TYPE_RAVEN_PCI_HOST_BRIDGE)
+
 typedef struct PRePPCIState {
     PCIHostState host_state;
+
     MemoryRegion intack;
     qemu_irq irq[4];
 } PREPPCIState;
@@ -42,9 +48,10 @@ static inline uint32_t PPC_PCIIO_config(target_phys_addr_t addr)
 {
     int i;
 
-    for(i = 0; i < 11; i++) {
-        if ((addr & (1 << (11 + i))) != 0)
+    for (i = 0; i < 11; i++) {
+        if ((addr & (1 << (11 + i))) != 0) {
             break;
+        }
     }
     return (addr & 0x7ff) |  (i << 11);
 }
@@ -97,7 +104,7 @@ static void prep_set_irq(void *opaque, int irq_num, int level)
 static int raven_pcihost_init(SysBusDevice *dev)
 {
     PCIHostState *h = FROM_SYSBUS(PCIHostState, dev);
-    PREPPCIState *s = DO_UPCAST(PREPPCIState, host_state, h);
+    PREPPCIState *s = RAVEN_PCI_HOST_BRIDGE(dev);
     MemoryRegion *address_space_mem = get_system_memory();
     MemoryRegion *address_space_io = get_system_io();
     PCIBus *bus;
@@ -107,7 +114,7 @@ static int raven_pcihost_init(SysBusDevice *dev)
         sysbus_init_irq(dev, &s->irq[i]);
     }
 
-    bus = pci_register_bus(&h->busdev.qdev, NULL,
+    bus = pci_register_bus(DEVICE(dev), NULL,
                            prep_set_irq, prep_map_irq, s->irq,
                            address_space_mem, address_space_io, 0, 4);
     h->bus = bus;
@@ -184,7 +191,7 @@ static void raven_pcihost_class_init(ObjectClass *klass, void *data)
 }
 
 static const TypeInfo raven_pcihost_info = {
-    .name = "raven-pcihost",
+    .name = TYPE_RAVEN_PCI_HOST_BRIDGE,
     .parent = TYPE_SYS_BUS_DEVICE,
     .instance_size = sizeof(PREPPCIState),
     .class_init = raven_pcihost_class_init,
commit 9c1a61f0e583a0ae3f601465ffa22da5954c9bfc
Author: Andreas Färber <afaerber at suse.de>
Date:   Mon Aug 20 19:08:03 2012 +0200

    ppce500_pci: QOM'ify e500 PCI host bridge
    
    Introduce type constant and cast macro. Avoid accessing parent fields
    directly.
    
    Signed-off-by: Andreas Färber <afaerber at suse.de>
    Acked-by: Michael S. Tsirkin <mst at redhat.com>
    Signed-off-by: Anthony Liguori <aliguori at us.ibm.com>

diff --git a/hw/ppce500_pci.c b/hw/ppce500_pci.c
index 99748b3..e4f065a 100644
--- a/hw/ppce500_pci.c
+++ b/hw/ppce500_pci.c
@@ -72,8 +72,14 @@ struct pci_inbound {
     uint32_t piwar;
 };
 
+#define TYPE_PPC_E500_PCI_HOST_BRIDGE "e500-pcihost"
+
+#define PPC_E500_PCI_HOST_BRIDGE(obj) \
+    OBJECT_CHECK(PPCE500PCIState, (obj), TYPE_PPC_E500_PCI_HOST_BRIDGE)
+
 struct PPCE500PCIState {
     PCIHostState pci_state;
+
     struct pci_outbound pob[PPCE500_PCI_NR_POBS];
     struct pci_inbound pib[PPCE500_PCI_NR_PIBS];
     uint32_t gasket_time;
@@ -310,17 +316,17 @@ static int e500_pcihost_initfn(SysBusDevice *dev)
     MemoryRegion *address_space_mem = get_system_memory();
     MemoryRegion *address_space_io = get_system_io();
 
-    h = FROM_SYSBUS(PCIHostState, sysbus_from_qdev(dev));
-    s = DO_UPCAST(PPCE500PCIState, pci_state, h);
+    h = FROM_SYSBUS(PCIHostState, dev);
+    s = PPC_E500_PCI_HOST_BRIDGE(dev);
 
     for (i = 0; i < ARRAY_SIZE(s->irq); i++) {
         sysbus_init_irq(dev, &s->irq[i]);
     }
 
-    b = pci_register_bus(&s->pci_state.busdev.qdev, NULL, mpc85xx_pci_set_irq,
+    b = pci_register_bus(DEVICE(dev), NULL, mpc85xx_pci_set_irq,
                          mpc85xx_pci_map_irq, s->irq, address_space_mem,
                          address_space_io, PCI_DEVFN(0x11, 0), 4);
-    s->pci_state.bus = b;
+    h->bus = b;
 
     pci_create_simple(b, 0, "e500-host-bridge");
 
@@ -367,7 +373,7 @@ static void e500_pcihost_class_init(ObjectClass *klass, void *data)
 }
 
 static const TypeInfo e500_pcihost_info = {
-    .name          = "e500-pcihost",
+    .name          = TYPE_PPC_E500_PCI_HOST_BRIDGE,
     .parent        = TYPE_SYS_BUS_DEVICE,
     .instance_size = sizeof(PPCE500PCIState),
     .class_init    = e500_pcihost_class_init,
commit 42c281a2832a67ee1d0cc08744c5b9ebb4f6b802
Author: Andreas Färber <afaerber at suse.de>
Date:   Mon Aug 20 19:08:02 2012 +0200

    ppc4xx_pci: QOM'ify ppc4xx PCI host bridge
    
    Introduce type constant and cast macro. Avoid accessing its parent field
    directly.
    
    Signed-off-by: Andreas Färber <afaerber at suse.de>
    Acked-by: Michael S. Tsirkin <mst at redhat.com>
    Signed-off-by: Anthony Liguori <aliguori at us.ibm.com>

diff --git a/hw/ppc440_bamboo.c b/hw/ppc440_bamboo.c
index 0dd4dab..c198071 100644
--- a/hw/ppc440_bamboo.c
+++ b/hw/ppc440_bamboo.c
@@ -216,7 +216,8 @@ static void bamboo_init(ram_addr_t ram_size,
                       ram_bases, ram_sizes, 1);
 
     /* PCI */
-    dev = sysbus_create_varargs("ppc4xx-pcihost", PPC440EP_PCI_CONFIG,
+    dev = sysbus_create_varargs(TYPE_PPC4xx_PCI_HOST_BRIDGE,
+                                PPC440EP_PCI_CONFIG,
                                 pic[pci_irq_nrs[0]], pic[pci_irq_nrs[1]],
                                 pic[pci_irq_nrs[2]], pic[pci_irq_nrs[3]],
                                 NULL);
diff --git a/hw/ppc4xx.h b/hw/ppc4xx.h
index b511020..5cd78b6 100644
--- a/hw/ppc4xx.h
+++ b/hw/ppc4xx.h
@@ -53,6 +53,8 @@ void ppc4xx_sdram_init (CPUPPCState *env, qemu_irq irq, int nbanks,
                         target_phys_addr_t *ram_sizes,
                         int do_init);
 
+#define TYPE_PPC4xx_PCI_HOST_BRIDGE "ppc4xx-pcihost"
+
 PCIBus *ppc4xx_pci_init(CPUPPCState *env, qemu_irq pci_irqs[4],
                         target_phys_addr_t config_space,
                         target_phys_addr_t int_ack,
diff --git a/hw/ppc4xx_pci.c b/hw/ppc4xx_pci.c
index 104ed98..599a75a 100644
--- a/hw/ppc4xx_pci.c
+++ b/hw/ppc4xx_pci.c
@@ -45,6 +45,9 @@ struct PCITargetMap {
     uint32_t la;
 };
 
+#define PPC4xx_PCI_HOST_BRIDGE(obj) \
+    OBJECT_CHECK(PPC4xxPCIState, (obj), TYPE_PPC4xx_PCI_HOST_BRIDGE)
+
 #define PPC4xx_PCI_NR_PMMS 3
 #define PPC4xx_PCI_NR_PTMS 2
 
@@ -335,17 +338,17 @@ static int ppc4xx_pcihost_initfn(SysBusDevice *dev)
     PCIBus *b;
     int i;
 
-    h = FROM_SYSBUS(PCIHostState, sysbus_from_qdev(dev));
-    s = DO_UPCAST(PPC4xxPCIState, pci_state, h);
+    h = FROM_SYSBUS(PCIHostState, dev);
+    s = PPC4xx_PCI_HOST_BRIDGE(dev);
 
     for (i = 0; i < ARRAY_SIZE(s->irq); i++) {
         sysbus_init_irq(dev, &s->irq[i]);
     }
 
-    b = pci_register_bus(&s->pci_state.busdev.qdev, NULL, ppc4xx_pci_set_irq,
+    b = pci_register_bus(DEVICE(dev), NULL, ppc4xx_pci_set_irq,
                          ppc4xx_pci_map_irq, s->irq, get_system_memory(),
                          get_system_io(), 0, 4);
-    s->pci_state.bus = b;
+    h->bus = b;
 
     pci_create_simple(b, 0, "ppc4xx-host-bridge");
 
@@ -394,7 +397,7 @@ static void ppc4xx_pcihost_class_init(ObjectClass *klass, void *data)
 }
 
 static const TypeInfo ppc4xx_pcihost_info = {
-    .name          = "ppc4xx-pcihost",
+    .name          = TYPE_PPC4xx_PCI_HOST_BRIDGE,
     .parent        = TYPE_SYS_BUS_DEVICE,
     .instance_size = sizeof(PPC4xxPCIState),
     .class_init    = ppc4xx_pcihost_class_init,
commit 8d43d7e591c2078cc64534b867365d46ad394d04
Author: Andreas Färber <afaerber at suse.de>
Date:   Mon Aug 20 19:08:01 2012 +0200

    gt64xxx: QOM'ify GT64120 PCI host bridge
    
    Introduce type constant. Introduce cast macro to drop dummy busdev field
    used with FROM_SYSBUS() macro that would've broken SYS_BUS_DEVICE().
    Avoid accessing DeviceState indirectly through PCIHostState.
    
    Signed-off-by: Andreas Färber <afaerber at suse.de>
    Acked-by: Michael S. Tsirkin <mst at redhat.com>
    Signed-off-by: Anthony Liguori <aliguori at us.ibm.com>

diff --git a/hw/gt64xxx.c b/hw/gt64xxx.c
index 04831bb..0677299 100644
--- a/hw/gt64xxx.c
+++ b/hw/gt64xxx.c
@@ -229,9 +229,14 @@
     target_phys_addr_t regname ##_length;     \
     MemoryRegion regname ##_mem
 
+#define TYPE_GT64120_PCI_HOST_BRIDGE "gt64120"
+
+#define GT64120_PCI_HOST_BRIDGE(obj) \
+    OBJECT_CHECK(GT64120State, (obj), TYPE_GT64120_PCI_HOST_BRIDGE)
+
 typedef struct GT64120State {
-    SysBusDevice busdev;
     PCIHostState pci;
+
     uint32_t regs[GT_REGS];
     PCI_MAPPING_ENTRY(PCI0IO);
     PCI_MAPPING_ENTRY(ISD);
@@ -1083,31 +1088,31 @@ static void gt64120_reset(void *opaque)
 
 PCIBus *gt64120_register(qemu_irq *pic)
 {
-    SysBusDevice *s;
     GT64120State *d;
+    PCIHostState *phb;
     DeviceState *dev;
 
-    dev = qdev_create(NULL, "gt64120");
+    dev = qdev_create(NULL, TYPE_GT64120_PCI_HOST_BRIDGE);
     qdev_init_nofail(dev);
-    s = sysbus_from_qdev(dev);
-    d = FROM_SYSBUS(GT64120State, s);
-    d->pci.bus = pci_register_bus(&d->busdev.qdev, "pci",
-                                  gt64120_pci_set_irq, gt64120_pci_map_irq,
-                                  pic,
-                                  get_system_memory(),
-                                  get_system_io(),
-                                  PCI_DEVFN(18, 0), 4);
+    d = GT64120_PCI_HOST_BRIDGE(dev);
+    phb = &d->pci;
+    phb->bus = pci_register_bus(dev, "pci",
+                                gt64120_pci_set_irq, gt64120_pci_map_irq,
+                                pic,
+                                get_system_memory(),
+                                get_system_io(),
+                                PCI_DEVFN(18, 0), 4);
     memory_region_init_io(&d->ISD_mem, &isd_mem_ops, d, "isd-mem", 0x1000);
 
-    pci_create_simple(d->pci.bus, PCI_DEVFN(0, 0), "gt64120_pci");
-    return d->pci.bus;
+    pci_create_simple(phb->bus, PCI_DEVFN(0, 0), "gt64120_pci");
+    return phb->bus;
 }
 
 static int gt64120_init(SysBusDevice *dev)
 {
     GT64120State *s;
 
-    s = FROM_SYSBUS(GT64120State, dev);
+    s = GT64120_PCI_HOST_BRIDGE(dev);
 
     /* FIXME: This value is computed from registers during reset, but some
        devices (e.g. VGA card) need to know it when they are registered.
@@ -1162,7 +1167,7 @@ static void gt64120_class_init(ObjectClass *klass, void *data)
 }
 
 static const TypeInfo gt64120_info = {
-    .name          = "gt64120",
+    .name          = TYPE_GT64120_PCI_HOST_BRIDGE,
     .parent        = TYPE_SYS_BUS_DEVICE,
     .instance_size = sizeof(GT64120State),
     .class_init    = gt64120_class_init,
commit 0e655047c5b394b54ffec6dddf37641b2aa5df55
Author: Andreas Färber <afaerber at suse.de>
Date:   Mon Aug 20 19:08:00 2012 +0200

    grackle_pci: QOM'ify Grackle PCI host bridge
    
    Introduce type constant. Introduce cast macro to drop dummy busdev field
    used with FROM_SYSBUS() that would've broken SYS_BUS_DEVICE().
    Avoid accessing parent fields directly.
    
    Drop no-op reset function.
    
    Signed-off-by: Andreas Färber <afaerber at suse.de>
    Acked-by: Michael S. Tsirkin <mst at redhat.com>
    Signed-off-by: Anthony Liguori <aliguori at us.ibm.com>

diff --git a/hw/grackle_pci.c b/hw/grackle_pci.c
index 35667ad..d814270 100644
--- a/hw/grackle_pci.c
+++ b/hw/grackle_pci.c
@@ -23,10 +23,9 @@
  * THE SOFTWARE.
  */
 
-#include "sysbus.h"
+#include "pci_host.h"
 #include "ppc_mac.h"
 #include "pci.h"
-#include "pci_host.h"
 
 /* debug Grackle */
 //#define DEBUG_GRACKLE
@@ -38,9 +37,12 @@
 #define GRACKLE_DPRINTF(fmt, ...)
 #endif
 
+#define GRACKLE_PCI_HOST_BRIDGE(obj) \
+    OBJECT_CHECK(GrackleState, (obj), TYPE_GRACKLE_PCI_HOST_BRIDGE)
+
 typedef struct GrackleState {
-    SysBusDevice busdev;
     PCIHostState host_state;
+
     MemoryRegion pci_mmio;
     MemoryRegion pci_hole;
 } GrackleState;
@@ -59,22 +61,20 @@ static void pci_grackle_set_irq(void *opaque, int irq_num, int level)
     qemu_set_irq(pic[irq_num + 0x15], level);
 }
 
-static void pci_grackle_reset(void *opaque)
-{
-}
-
 PCIBus *pci_grackle_init(uint32_t base, qemu_irq *pic,
                          MemoryRegion *address_space_mem,
                          MemoryRegion *address_space_io)
 {
     DeviceState *dev;
     SysBusDevice *s;
+    PCIHostState *phb;
     GrackleState *d;
 
-    dev = qdev_create(NULL, "grackle-pcihost");
+    dev = qdev_create(NULL, TYPE_GRACKLE_PCI_HOST_BRIDGE);
     qdev_init_nofail(dev);
-    s = sysbus_from_qdev(dev);
-    d = FROM_SYSBUS(GrackleState, s);
+    s = SYS_BUS_DEVICE(dev);
+    phb = FROM_SYSBUS(PCIHostState, s);
+    d = GRACKLE_PCI_HOST_BRIDGE(dev);
 
     memory_region_init(&d->pci_mmio, "pci-mmio", 0x100000000ULL);
     memory_region_init_alias(&d->pci_hole, "pci-hole", &d->pci_mmio,
@@ -82,36 +82,35 @@ PCIBus *pci_grackle_init(uint32_t base, qemu_irq *pic,
     memory_region_add_subregion(address_space_mem, 0x80000000ULL,
                                 &d->pci_hole);
 
-    d->host_state.bus = pci_register_bus(&d->busdev.qdev, "pci",
-                                         pci_grackle_set_irq,
-                                         pci_grackle_map_irq,
-                                         pic,
-                                         &d->pci_mmio,
-                                         address_space_io,
-                                         0, 4);
+    phb->bus = pci_register_bus(dev, "pci",
+                                pci_grackle_set_irq,
+                                pci_grackle_map_irq,
+                                pic,
+                                &d->pci_mmio,
+                                address_space_io,
+                                0, 4);
 
-    pci_create_simple(d->host_state.bus, 0, "grackle");
+    pci_create_simple(phb->bus, 0, "grackle");
 
     sysbus_mmio_map(s, 0, base);
     sysbus_mmio_map(s, 1, base + 0x00200000);
 
-    return d->host_state.bus;
+    return phb->bus;
 }
 
 static int pci_grackle_init_device(SysBusDevice *dev)
 {
-    GrackleState *s;
+    PCIHostState *phb;
 
-    s = FROM_SYSBUS(GrackleState, dev);
+    phb = FROM_SYSBUS(PCIHostState, dev);
 
-    memory_region_init_io(&s->host_state.conf_mem, &pci_host_conf_le_ops,
-                          &s->host_state, "pci-conf-idx", 0x1000);
-    memory_region_init_io(&s->host_state.data_mem, &pci_host_data_le_ops,
-                          &s->host_state, "pci-data-idx", 0x1000);
-    sysbus_init_mmio(dev, &s->host_state.conf_mem);
-    sysbus_init_mmio(dev, &s->host_state.data_mem);
+    memory_region_init_io(&phb->conf_mem, &pci_host_conf_le_ops,
+                          dev, "pci-conf-idx", 0x1000);
+    memory_region_init_io(&phb->data_mem, &pci_host_data_le_ops,
+                          dev, "pci-data-idx", 0x1000);
+    sysbus_init_mmio(dev, &phb->conf_mem);
+    sysbus_init_mmio(dev, &phb->data_mem);
 
-    qemu_register_reset(pci_grackle_reset, &s->host_state);
     return 0;
 }
 
@@ -151,7 +150,7 @@ static void pci_grackle_class_init(ObjectClass *klass, void *data)
 }
 
 static const TypeInfo grackle_pci_host_info = {
-    .name          = "grackle-pcihost",
+    .name          = TYPE_GRACKLE_PCI_HOST_BRIDGE,
     .parent        = TYPE_SYS_BUS_DEVICE,
     .instance_size = sizeof(GrackleState),
     .class_init    = pci_grackle_class_init,
diff --git a/hw/ppc_mac.h b/hw/ppc_mac.h
index af75e45..7d08418 100644
--- a/hw/ppc_mac.h
+++ b/hw/ppc_mac.h
@@ -55,6 +55,7 @@ qemu_irq *heathrow_pic_init(MemoryRegion **pmem,
                             int nb_cpus, qemu_irq **irqs);
 
 /* Grackle PCI */
+#define TYPE_GRACKLE_PCI_HOST_BRIDGE "grackle-pcihost"
 PCIBus *pci_grackle_init(uint32_t base, qemu_irq *pic,
                          MemoryRegion *address_space_mem,
                          MemoryRegion *address_space_io);
commit ab6153673727cc1b88258675fa02113cf3271aa8
Author: Andreas Färber <afaerber at suse.de>
Date:   Mon Aug 20 19:07:59 2012 +0200

    dec_pci: QOM'ify DEC 21154 PCI-PCI bridge
    
    Introduce type constant. Introduce cast macro and drop dummy busdev
    field used with FROM_SYSBUS() that would've broken SYS_BUS_DEVICE().
    Avoid accessing parent fields directly.
    
    Signed-off-by: Andreas Färber <afaerber at suse.de>
    Acked-by: Michael S. Tsirkin <mst at redhat.com>
    Signed-off-by: Anthony Liguori <aliguori at us.ibm.com>

diff --git a/hw/dec_pci.c b/hw/dec_pci.c
index 5194a9f..19aed1b 100644
--- a/hw/dec_pci.c
+++ b/hw/dec_pci.c
@@ -40,8 +40,9 @@
 #define DEC_DPRINTF(fmt, ...)
 #endif
 
+#define DEC_21154(obj) OBJECT_CHECK(DECState, (obj), TYPE_DEC_21154)
+
 typedef struct DECState {
-    SysBusDevice busdev;
     PCIHostState host_state;
 } DECState;
 
@@ -88,16 +89,16 @@ PCIBus *pci_dec_21154_init(PCIBus *parent_bus, int devfn)
 
 static int pci_dec_21154_device_init(SysBusDevice *dev)
 {
-    DECState *s;
+    PCIHostState *phb;
 
-    s = FROM_SYSBUS(DECState, dev);
+    phb = FROM_SYSBUS(PCIHostState, dev);
 
-    memory_region_init_io(&s->host_state.conf_mem, &pci_host_conf_le_ops,
-                          &s->host_state, "pci-conf-idx", 0x1000);
-    memory_region_init_io(&s->host_state.data_mem, &pci_host_data_le_ops,
-                          &s->host_state, "pci-data-idx", 0x1000);
-    sysbus_init_mmio(dev, &s->host_state.conf_mem);
-    sysbus_init_mmio(dev, &s->host_state.data_mem);
+    memory_region_init_io(&phb->conf_mem, &pci_host_conf_le_ops,
+                          dev, "pci-conf-idx", 0x1000);
+    memory_region_init_io(&phb->data_mem, &pci_host_data_le_ops,
+                          dev, "pci-data-idx", 0x1000);
+    sysbus_init_mmio(dev, &phb->conf_mem);
+    sysbus_init_mmio(dev, &phb->data_mem);
     return 0;
 }
 
@@ -134,7 +135,7 @@ static void pci_dec_21154_device_class_init(ObjectClass *klass, void *data)
 }
 
 static const TypeInfo pci_dec_21154_device_info = {
-    .name          = "dec-21154-sysbus",
+    .name          = TYPE_DEC_21154,
     .parent        = TYPE_SYS_BUS_DEVICE,
     .instance_size = sizeof(DECState),
     .class_init    = pci_dec_21154_device_class_init,
diff --git a/hw/dec_pci.h b/hw/dec_pci.h
index 79264ba..17dc0c2 100644
--- a/hw/dec_pci.h
+++ b/hw/dec_pci.h
@@ -3,6 +3,8 @@
 
 #include "qemu-common.h"
 
+#define TYPE_DEC_21154 "dec-21154-sysbus"
+
 PCIBus *pci_dec_21154_init(PCIBus *parent_bus, int devfn);
 
 #endif
commit c5589ee9745319944886231935680fb8d110e6cb
Author: Andreas Färber <afaerber at suse.de>
Date:   Mon Aug 20 19:07:58 2012 +0200

    bonito: QOM'ify Bonito PCI host bridge
    
    Introduce type constant. Avoid accessing DeviceState or SysBusDevice
    indirectly through PCIHostState field.
    
    Drop global state by passing BonitoState as opaque and adding the IRQs
    and a pointer to PCIBonitoState to its state.
    
    Signed-off-by: Andreas Färber <afaerber at suse.de>
    Acked-by: Michael S. Tsirkin <mst at redhat.com>
    Signed-off-by: Anthony Liguori <aliguori at us.ibm.com>

diff --git a/hw/bonito.c b/hw/bonito.c
index b990875..062c701 100644
--- a/hw/bonito.c
+++ b/hw/bonito.c
@@ -180,11 +180,14 @@
 #define PCI_ADDR(busno,devno,funno,regno)  \
     ((((busno)<<16)&0xff0000) + (((devno)<<11)&0xf800) + (((funno)<<8)&0x700) + (regno))
 
-typedef PCIHostState BonitoState;
+#define TYPE_BONITO_PCI_HOST_BRIDGE "Bonito-pcihost"
+
+typedef struct BonitoState BonitoState;
 
 typedef struct PCIBonitoState
 {
     PCIDevice dev;
+
     BonitoState *pcihost;
     uint32_t regs[BONITO_REGS];
 
@@ -218,7 +221,16 @@ typedef struct PCIBonitoState
 
 } PCIBonitoState;
 
-PCIBonitoState * bonito_state;
+#define BONITO_PCI_HOST_BRIDGE(obj) \
+    OBJECT_CHECK(BonitoState, (obj), TYPE_BONITO_PCI_HOST_BRIDGE)
+
+struct BonitoState {
+    PCIHostState parent_obj;
+
+    qemu_irq *pic;
+
+    PCIBonitoState *pci_dev;
+};
 
 static void bonito_writel(void *opaque, target_phys_addr_t addr,
                           uint64_t val, unsigned size)
@@ -314,9 +326,10 @@ static void bonito_pciconf_writel(void *opaque, target_phys_addr_t addr,
                                   uint64_t val, unsigned size)
 {
     PCIBonitoState *s = opaque;
+    PCIDevice *d = PCI_DEVICE(s);
 
     DPRINTF("bonito_pciconf_writel "TARGET_FMT_plx" val %x\n", addr, val);
-    s->dev.config_write(&s->dev, addr, val, 4);
+    d->config_write(d, addr, val, 4);
 }
 
 static uint64_t bonito_pciconf_readl(void *opaque, target_phys_addr_t addr,
@@ -324,9 +337,10 @@ static uint64_t bonito_pciconf_readl(void *opaque, target_phys_addr_t addr,
 {
 
     PCIBonitoState *s = opaque;
+    PCIDevice *d = PCI_DEVICE(s);
 
     DPRINTF("bonito_pciconf_readl "TARGET_FMT_plx"\n", addr);
-    return s->dev.config_read(&s->dev, addr, 4);
+    return d->config_read(d, addr, 4);
 }
 
 /* north bridge PCI configure space. 0x1fe0 0000 - 0x1fe0 00ff */
@@ -402,6 +416,7 @@ static const MemoryRegionOps bonito_cop_ops = {
 static uint32_t bonito_sbridge_pciaddr(void *opaque, target_phys_addr_t addr)
 {
     PCIBonitoState *s = opaque;
+    PCIHostState *phb = FROM_SYSBUS(PCIHostState, SYS_BUS_DEVICE(s->pcihost));
     uint32_t cfgaddr;
     uint32_t idsel;
     uint32_t devno;
@@ -423,13 +438,13 @@ static uint32_t bonito_sbridge_pciaddr(void *opaque, target_phys_addr_t addr)
     regno = (cfgaddr & BONITO_PCICONF_REG_MASK) >> BONITO_PCICONF_REG_OFFSET;
 
     if (idsel == 0) {
-        fprintf(stderr, "error in bonito pci config address" TARGET_FMT_plx
+        fprintf(stderr, "error in bonito pci config address " TARGET_FMT_plx
             ",pcimap_cfg=%x\n", addr, s->regs[BONITO_PCIMAP_CFG]);
         exit(1);
     }
-    pciaddr = PCI_ADDR(pci_bus_num(s->pcihost->bus), devno, funno, regno);
+    pciaddr = PCI_ADDR(pci_bus_num(phb->bus), devno, funno, regno);
     DPRINTF("cfgaddr %x pciaddr %x busno %x devno %d funno %d regno %d\n",
-        cfgaddr, pciaddr, pci_bus_num(s->pcihost->bus), devno, funno, regno);
+        cfgaddr, pciaddr, pci_bus_num(phb->bus), devno, funno, regno);
 
     return pciaddr;
 }
@@ -438,6 +453,8 @@ static void bonito_spciconf_writeb(void *opaque, target_phys_addr_t addr,
                                    uint32_t val)
 {
     PCIBonitoState *s = opaque;
+    PCIDevice *d = PCI_DEVICE(s);
+    PCIHostState *phb = FROM_SYSBUS(PCIHostState, SYS_BUS_DEVICE(s->pcihost));
     uint32_t pciaddr;
     uint16_t status;
 
@@ -449,24 +466,26 @@ static void bonito_spciconf_writeb(void *opaque, target_phys_addr_t addr,
     }
 
     /* set the pci address in s->config_reg */
-    s->pcihost->config_reg = (pciaddr) | (1u << 31);
-    pci_data_write(s->pcihost->bus, s->pcihost->config_reg, val & 0xff, 1);
+    phb->config_reg = (pciaddr) | (1u << 31);
+    pci_data_write(phb->bus, phb->config_reg, val & 0xff, 1);
 
     /* clear PCI_STATUS_REC_MASTER_ABORT and PCI_STATUS_REC_TARGET_ABORT */
-    status = pci_get_word(s->dev.config + PCI_STATUS);
+    status = pci_get_word(d->config + PCI_STATUS);
     status &= ~(PCI_STATUS_REC_MASTER_ABORT | PCI_STATUS_REC_TARGET_ABORT);
-    pci_set_word(s->dev.config + PCI_STATUS, status);
+    pci_set_word(d->config + PCI_STATUS, status);
 }
 
 static void bonito_spciconf_writew(void *opaque, target_phys_addr_t addr,
                                    uint32_t val)
 {
     PCIBonitoState *s = opaque;
+    PCIDevice *d = PCI_DEVICE(s);
+    PCIHostState *phb = FROM_SYSBUS(PCIHostState, SYS_BUS_DEVICE(s->pcihost));
     uint32_t pciaddr;
     uint16_t status;
 
     DPRINTF("bonito_spciconf_writew "TARGET_FMT_plx" val %x\n", addr, val);
-    assert((addr&0x1)==0);
+    assert((addr & 0x1) == 0);
 
     pciaddr = bonito_sbridge_pciaddr(s, addr);
 
@@ -475,24 +494,26 @@ static void bonito_spciconf_writew(void *opaque, target_phys_addr_t addr,
     }
 
     /* set the pci address in s->config_reg */
-    s->pcihost->config_reg = (pciaddr) | (1u << 31);
-    pci_data_write(s->pcihost->bus, s->pcihost->config_reg, val, 2);
+    phb->config_reg = (pciaddr) | (1u << 31);
+    pci_data_write(phb->bus, phb->config_reg, val, 2);
 
     /* clear PCI_STATUS_REC_MASTER_ABORT and PCI_STATUS_REC_TARGET_ABORT */
-    status = pci_get_word(s->dev.config + PCI_STATUS);
+    status = pci_get_word(d->config + PCI_STATUS);
     status &= ~(PCI_STATUS_REC_MASTER_ABORT | PCI_STATUS_REC_TARGET_ABORT);
-    pci_set_word(s->dev.config + PCI_STATUS, status);
+    pci_set_word(d->config + PCI_STATUS, status);
 }
 
 static void bonito_spciconf_writel(void *opaque, target_phys_addr_t addr,
                                    uint32_t val)
 {
     PCIBonitoState *s = opaque;
+    PCIDevice *d = PCI_DEVICE(s);
+    PCIHostState *phb = FROM_SYSBUS(PCIHostState, SYS_BUS_DEVICE(s->pcihost));
     uint32_t pciaddr;
     uint16_t status;
 
     DPRINTF("bonito_spciconf_writel "TARGET_FMT_plx" val %x\n", addr, val);
-    assert((addr&0x3)==0);
+    assert((addr & 0x3) == 0);
 
     pciaddr = bonito_sbridge_pciaddr(s, addr);
 
@@ -501,18 +522,20 @@ static void bonito_spciconf_writel(void *opaque, target_phys_addr_t addr,
     }
 
     /* set the pci address in s->config_reg */
-    s->pcihost->config_reg = (pciaddr) | (1u << 31);
-    pci_data_write(s->pcihost->bus, s->pcihost->config_reg, val, 4);
+    phb->config_reg = (pciaddr) | (1u << 31);
+    pci_data_write(phb->bus, phb->config_reg, val, 4);
 
     /* clear PCI_STATUS_REC_MASTER_ABORT and PCI_STATUS_REC_TARGET_ABORT */
-    status = pci_get_word(s->dev.config + PCI_STATUS);
+    status = pci_get_word(d->config + PCI_STATUS);
     status &= ~(PCI_STATUS_REC_MASTER_ABORT | PCI_STATUS_REC_TARGET_ABORT);
-    pci_set_word(s->dev.config + PCI_STATUS, status);
+    pci_set_word(d->config + PCI_STATUS, status);
 }
 
 static uint32_t bonito_spciconf_readb(void *opaque, target_phys_addr_t addr)
 {
     PCIBonitoState *s = opaque;
+    PCIDevice *d = PCI_DEVICE(s);
+    PCIHostState *phb = FROM_SYSBUS(PCIHostState, SYS_BUS_DEVICE(s->pcihost));
     uint32_t pciaddr;
     uint16_t status;
 
@@ -524,24 +547,26 @@ static uint32_t bonito_spciconf_readb(void *opaque, target_phys_addr_t addr)
     }
 
     /* set the pci address in s->config_reg */
-    s->pcihost->config_reg = (pciaddr) | (1u << 31);
+    phb->config_reg = (pciaddr) | (1u << 31);
 
     /* clear PCI_STATUS_REC_MASTER_ABORT and PCI_STATUS_REC_TARGET_ABORT */
-    status = pci_get_word(s->dev.config + PCI_STATUS);
+    status = pci_get_word(d->config + PCI_STATUS);
     status &= ~(PCI_STATUS_REC_MASTER_ABORT | PCI_STATUS_REC_TARGET_ABORT);
-    pci_set_word(s->dev.config + PCI_STATUS, status);
+    pci_set_word(d->config + PCI_STATUS, status);
 
-    return pci_data_read(s->pcihost->bus, s->pcihost->config_reg, 1);
+    return pci_data_read(phb->bus, phb->config_reg, 1);
 }
 
 static uint32_t bonito_spciconf_readw(void *opaque, target_phys_addr_t addr)
 {
     PCIBonitoState *s = opaque;
+    PCIDevice *d = PCI_DEVICE(s);
+    PCIHostState *phb = FROM_SYSBUS(PCIHostState, SYS_BUS_DEVICE(s->pcihost));
     uint32_t pciaddr;
     uint16_t status;
 
     DPRINTF("bonito_spciconf_readw "TARGET_FMT_plx"\n", addr);
-    assert((addr&0x1)==0);
+    assert((addr & 0x1) == 0);
 
     pciaddr = bonito_sbridge_pciaddr(s, addr);
 
@@ -550,24 +575,26 @@ static uint32_t bonito_spciconf_readw(void *opaque, target_phys_addr_t addr)
     }
 
     /* set the pci address in s->config_reg */
-    s->pcihost->config_reg = (pciaddr) | (1u << 31);
+    phb->config_reg = (pciaddr) | (1u << 31);
 
     /* clear PCI_STATUS_REC_MASTER_ABORT and PCI_STATUS_REC_TARGET_ABORT */
-    status = pci_get_word(s->dev.config + PCI_STATUS);
+    status = pci_get_word(d->config + PCI_STATUS);
     status &= ~(PCI_STATUS_REC_MASTER_ABORT | PCI_STATUS_REC_TARGET_ABORT);
-    pci_set_word(s->dev.config + PCI_STATUS, status);
+    pci_set_word(d->config + PCI_STATUS, status);
 
-    return pci_data_read(s->pcihost->bus, s->pcihost->config_reg, 2);
+    return pci_data_read(phb->bus, phb->config_reg, 2);
 }
 
 static uint32_t bonito_spciconf_readl(void *opaque, target_phys_addr_t addr)
 {
     PCIBonitoState *s = opaque;
+    PCIDevice *d = PCI_DEVICE(s);
+    PCIHostState *phb = FROM_SYSBUS(PCIHostState, SYS_BUS_DEVICE(s->pcihost));
     uint32_t pciaddr;
     uint16_t status;
 
     DPRINTF("bonito_spciconf_readl "TARGET_FMT_plx"\n", addr);
-    assert((addr&0x3) == 0);
+    assert((addr & 0x3) == 0);
 
     pciaddr = bonito_sbridge_pciaddr(s, addr);
 
@@ -576,14 +603,14 @@ static uint32_t bonito_spciconf_readl(void *opaque, target_phys_addr_t addr)
     }
 
     /* set the pci address in s->config_reg */
-    s->pcihost->config_reg = (pciaddr) | (1u << 31);
+    phb->config_reg = (pciaddr) | (1u << 31);
 
     /* clear PCI_STATUS_REC_MASTER_ABORT and PCI_STATUS_REC_TARGET_ABORT */
-    status = pci_get_word(s->dev.config + PCI_STATUS);
+    status = pci_get_word(d->config + PCI_STATUS);
     status &= ~(PCI_STATUS_REC_MASTER_ABORT | PCI_STATUS_REC_TARGET_ABORT);
-    pci_set_word(s->dev.config + PCI_STATUS, status);
+    pci_set_word(d->config + PCI_STATUS, status);
 
-    return pci_data_read(s->pcihost->bus, s->pcihost->config_reg, 4);
+    return pci_data_read(phb->bus, phb->config_reg, 4);
 }
 
 /* south bridge PCI configure space. 0x1fe8 0000 - 0x1fef ffff */
@@ -607,13 +634,15 @@ static const MemoryRegionOps bonito_spciconf_ops = {
 
 static void pci_bonito_set_irq(void *opaque, int irq_num, int level)
 {
-    qemu_irq *pic = opaque;
+    BonitoState *s = opaque;
+    qemu_irq *pic = s->pic;
+    PCIBonitoState *bonito_state = s->pci_dev;
     int internal_irq = irq_num - BONITO_IRQ_BASE;
 
-    if (bonito_state->regs[BONITO_INTEDGE] & (1<<internal_irq)) {
+    if (bonito_state->regs[BONITO_INTEDGE] & (1 << internal_irq)) {
         qemu_irq_pulse(*pic);
     } else {   /* level triggered */
-        if (bonito_state->regs[BONITO_INTPOL] & (1<<internal_irq)) {
+        if (bonito_state->regs[BONITO_INTPOL] & (1 << internal_irq)) {
             qemu_irq_raise(*pic);
         } else {
             qemu_irq_lower(*pic);
@@ -673,13 +702,21 @@ static const VMStateDescription vmstate_bonito = {
 
 static int bonito_pcihost_initfn(SysBusDevice *dev)
 {
+    PCIHostState *phb = FROM_SYSBUS(PCIHostState, dev);
+
+    phb->bus = pci_register_bus(DEVICE(dev), "pci",
+                                pci_bonito_set_irq, pci_bonito_map_irq, dev,
+                                get_system_memory(), get_system_io(),
+                                0x28, 32);
+
     return 0;
 }
 
 static int bonito_initfn(PCIDevice *dev)
 {
     PCIBonitoState *s = DO_UPCAST(PCIBonitoState, dev, dev);
-    SysBusDevice *sysbus = &s->pcihost->busdev;
+    SysBusDevice *sysbus = SYS_BUS_DEVICE(s->pcihost);
+    PCIHostState *phb = FROM_SYSBUS(PCIHostState, sysbus);
 
     /* Bonito North Bridge, built on FPGA, VENDOR_ID/DEVICE_ID are "undefined" */
     pci_config_set_prog_interface(dev->config, 0x00);
@@ -691,15 +728,15 @@ static int bonito_initfn(PCIDevice *dev)
     sysbus_mmio_map(sysbus, 0, BONITO_INTERNAL_REG_BASE);
 
     /* set the north bridge pci configure  mapping */
-    memory_region_init_io(&s->pcihost->conf_mem, &bonito_pciconf_ops, s,
+    memory_region_init_io(&phb->conf_mem, &bonito_pciconf_ops, s,
                           "north-bridge-pci-config", BONITO_PCICONFIG_SIZE);
-    sysbus_init_mmio(sysbus, &s->pcihost->conf_mem);
+    sysbus_init_mmio(sysbus, &phb->conf_mem);
     sysbus_mmio_map(sysbus, 1, BONITO_PCICONFIG_BASE);
 
     /* set the south bridge pci configure  mapping */
-    memory_region_init_io(&s->pcihost->data_mem, &bonito_spciconf_ops, s,
+    memory_region_init_io(&phb->data_mem, &bonito_spciconf_ops, s,
                           "south-bridge-pci-config", BONITO_SPCICONFIG_SIZE);
-    sysbus_init_mmio(sysbus, &s->pcihost->data_mem);
+    sysbus_init_mmio(sysbus, &phb->data_mem);
     sysbus_mmio_map(sysbus, 2, BONITO_SPCICONFIG_BASE);
 
     memory_region_init_io(&s->iomem_ldma, &bonito_ldma_ops, s,
@@ -742,28 +779,25 @@ static int bonito_initfn(PCIDevice *dev)
 PCIBus *bonito_init(qemu_irq *pic)
 {
     DeviceState *dev;
-    PCIBus *b;
     BonitoState *pcihost;
+    PCIHostState *phb;
     PCIBonitoState *s;
     PCIDevice *d;
 
-    dev = qdev_create(NULL, "Bonito-pcihost");
-    pcihost = FROM_SYSBUS(BonitoState, sysbus_from_qdev(dev));
-    b = pci_register_bus(&pcihost->busdev.qdev, "pci", pci_bonito_set_irq,
-                         pci_bonito_map_irq, pic, get_system_memory(),
-                         get_system_io(),
-                         0x28, 32);
-    pcihost->bus = b;
+    dev = qdev_create(NULL, TYPE_BONITO_PCI_HOST_BRIDGE);
+    phb = FROM_SYSBUS(PCIHostState, sysbus_from_qdev(dev));
+    pcihost = BONITO_PCI_HOST_BRIDGE(dev);
+    pcihost->pic = pic;
     qdev_init_nofail(dev);
 
     /* set the pcihost pointer before bonito_initfn is called */
-    d = pci_create(b, PCI_DEVFN(0, 0), "Bonito");
+    d = pci_create(phb->bus, PCI_DEVFN(0, 0), "Bonito");
     s = DO_UPCAST(PCIBonitoState, dev, d);
     s->pcihost = pcihost;
-    bonito_state = s;
-    qdev_init_nofail(&d->qdev);
+    pcihost->pci_dev = s;
+    qdev_init_nofail(DEVICE(d));
 
-    return b;
+    return phb->bus;
 }
 
 static void bonito_class_init(ObjectClass *klass, void *data)
@@ -798,7 +832,7 @@ static void bonito_pcihost_class_init(ObjectClass *klass, void *data)
 }
 
 static const TypeInfo bonito_pcihost_info = {
-    .name          = "Bonito-pcihost",
+    .name          = TYPE_BONITO_PCI_HOST_BRIDGE,
     .parent        = TYPE_SYS_BUS_DEVICE,
     .instance_size = sizeof(BonitoState),
     .class_init    = bonito_pcihost_class_init,
commit 94dd91d651fe821971411280f8c64a6b72e8ca64
Author: Andreas Färber <afaerber at suse.de>
Date:   Mon Aug 20 19:07:57 2012 +0200

    alpha_typhoon: QOM'ify Typhoon PCI host bridge
    
    Introduce type constant and cast macro. Don't access DeviceState
    or PCIHostState indirectly through parent fields.
    
    Signed-off-by: Andreas Färber <afaerber at suse.de>
    Acked-by: Michael S. Tsirkin <mst at redhat.com>
    Signed-off-by: Anthony Liguori <aliguori at us.ibm.com>

diff --git a/hw/alpha_typhoon.c b/hw/alpha_typhoon.c
index cc63737..10e588a 100644
--- a/hw/alpha_typhoon.c
+++ b/hw/alpha_typhoon.c
@@ -15,6 +15,8 @@
 #include "exec-memory.h"
 
 
+#define TYPE_TYPHOON_PCI_HOST_BRIDGE "typhoon-pcihost"
+
 typedef struct TyphoonCchip {
     MemoryRegion region;
     uint64_t misc;
@@ -40,8 +42,12 @@ typedef struct TyphoonPchip {
     TyphoonWindow win[4];
 } TyphoonPchip;
 
+#define TYPHOON_PCI_HOST_BRIDGE(obj) \
+    OBJECT_CHECK(TyphoonState, (obj), TYPE_TYPHOON_PCI_HOST_BRIDGE)
+
 typedef struct TyphoonState {
     PCIHostState host;
+
     TyphoonCchip cchip;
     TyphoonPchip pchip;
     MemoryRegion dchip_region;
@@ -700,16 +706,16 @@ PCIBus *typhoon_init(ram_addr_t ram_size, ISABus **isa_bus,
     MemoryRegion *addr_space = get_system_memory();
     MemoryRegion *addr_space_io = get_system_io();
     DeviceState *dev;
-    PCIHostState *p;
     TyphoonState *s;
+    PCIHostState *phb;
     PCIBus *b;
     int i;
 
-    dev = qdev_create(NULL, "typhoon-pcihost");
+    dev = qdev_create(NULL, TYPE_TYPHOON_PCI_HOST_BRIDGE);
     qdev_init_nofail(dev);
 
-    p = FROM_SYSBUS(PCIHostState, sysbus_from_qdev(dev));
-    s = container_of(p, TyphoonState, host);
+    s = TYPHOON_PCI_HOST_BRIDGE(dev);
+    phb = FROM_SYSBUS(PCIHostState, SYS_BUS_DEVICE(dev));
 
     /* Remember the CPUs so that we can deliver interrupts to them.  */
     for (i = 0; i < 4; i++) {
@@ -763,10 +769,10 @@ PCIBus *typhoon_init(ram_addr_t ram_size, ISABus **isa_bus,
     memory_region_add_subregion(addr_space, 0x801fc000000ULL,
                                 &s->pchip.reg_io);
 
-    b = pci_register_bus(&s->host.busdev.qdev, "pci",
+    b = pci_register_bus(dev, "pci",
                          typhoon_set_irq, sys_map_irq, s,
                          &s->pchip.reg_mem, addr_space_io, 0, 64);
-    s->host.bus = b;
+    phb->bus = b;
 
     /* Pchip0 PCI special/interrupt acknowledge, 0x801.F800.0000, 64MB.  */
     memory_region_init_io(&s->pchip.reg_iack, &alpha_pci_iack_ops, b,
@@ -818,7 +824,7 @@ static void typhoon_pcihost_class_init(ObjectClass *klass, void *data)
 }
 
 static const TypeInfo typhoon_pcihost_info = {
-    .name          = "typhoon-pcihost",
+    .name          = TYPE_TYPHOON_PCI_HOST_BRIDGE,
     .parent        = TYPE_SYS_BUS_DEVICE,
     .instance_size = sizeof(TyphoonState),
     .class_init    = typhoon_pcihost_class_init,
commit 4240abff5a6fb5d88867b51f46c0235518dac564
Author: Andreas Färber <afaerber at suse.de>
Date:   Mon Aug 20 19:07:56 2012 +0200

    pci: Make host bridge TypeInfos const
    
    During the QOM migration they were amended with further info but this is
    no longer the case. All static TypeInfos can be const these days.
    
    Signed-off-by: Andreas Färber <afaerber at suse.de>
    Acked-by: Michael S. Tsirkin <mst at redhat.com>
    Signed-off-by: Anthony Liguori <aliguori at us.ibm.com>

diff --git a/hw/alpha_typhoon.c b/hw/alpha_typhoon.c
index 872e112..cc63737 100644
--- a/hw/alpha_typhoon.c
+++ b/hw/alpha_typhoon.c
@@ -817,7 +817,7 @@ static void typhoon_pcihost_class_init(ObjectClass *klass, void *data)
     dc->no_user = 1;
 }
 
-static TypeInfo typhoon_pcihost_info = {
+static const TypeInfo typhoon_pcihost_info = {
     .name          = "typhoon-pcihost",
     .parent        = TYPE_SYS_BUS_DEVICE,
     .instance_size = sizeof(TyphoonState),
diff --git a/hw/bonito.c b/hw/bonito.c
index 77786f8..b990875 100644
--- a/hw/bonito.c
+++ b/hw/bonito.c
@@ -781,7 +781,7 @@ static void bonito_class_init(ObjectClass *klass, void *data)
     dc->vmsd = &vmstate_bonito;
 }
 
-static TypeInfo bonito_info = {
+static const TypeInfo bonito_info = {
     .name          = "Bonito",
     .parent        = TYPE_PCI_DEVICE,
     .instance_size = sizeof(PCIBonitoState),
@@ -797,7 +797,7 @@ static void bonito_pcihost_class_init(ObjectClass *klass, void *data)
     dc->no_user = 1;
 }
 
-static TypeInfo bonito_pcihost_info = {
+static const TypeInfo bonito_pcihost_info = {
     .name          = "Bonito-pcihost",
     .parent        = TYPE_SYS_BUS_DEVICE,
     .instance_size = sizeof(BonitoState),
diff --git a/hw/dec_pci.c b/hw/dec_pci.c
index 37337bf..5194a9f 100644
--- a/hw/dec_pci.c
+++ b/hw/dec_pci.c
@@ -66,7 +66,7 @@ static void dec_21154_pci_bridge_class_init(ObjectClass *klass, void *data)
     dc->vmsd = &vmstate_pci_device;
 }
 
-static TypeInfo dec_21154_pci_bridge_info = {
+static const TypeInfo dec_21154_pci_bridge_info = {
     .name          = "dec-21154-p2p-bridge",
     .parent        = TYPE_PCI_DEVICE,
     .instance_size = sizeof(PCIBridge),
@@ -119,7 +119,7 @@ static void dec_21154_pci_host_class_init(ObjectClass *klass, void *data)
     k->is_bridge = 1;
 }
 
-static TypeInfo dec_21154_pci_host_info = {
+static const TypeInfo dec_21154_pci_host_info = {
     .name          = "dec-21154",
     .parent        = TYPE_PCI_DEVICE,
     .instance_size = sizeof(PCIDevice),
@@ -133,7 +133,7 @@ static void pci_dec_21154_device_class_init(ObjectClass *klass, void *data)
     sdc->init = pci_dec_21154_device_init;
 }
 
-static TypeInfo pci_dec_21154_device_info = {
+static const TypeInfo pci_dec_21154_device_info = {
     .name          = "dec-21154-sysbus",
     .parent        = TYPE_SYS_BUS_DEVICE,
     .instance_size = sizeof(DECState),
diff --git a/hw/grackle_pci.c b/hw/grackle_pci.c
index 81ff3a3..35667ad 100644
--- a/hw/grackle_pci.c
+++ b/hw/grackle_pci.c
@@ -134,7 +134,7 @@ static void grackle_pci_class_init(ObjectClass *klass, void *data)
     dc->no_user = 1;
 }
 
-static TypeInfo grackle_pci_info = {
+static const TypeInfo grackle_pci_info = {
     .name          = "grackle",
     .parent        = TYPE_PCI_DEVICE,
     .instance_size = sizeof(PCIDevice),
@@ -150,7 +150,7 @@ static void pci_grackle_class_init(ObjectClass *klass, void *data)
     dc->no_user = 1;
 }
 
-static TypeInfo grackle_pci_host_info = {
+static const TypeInfo grackle_pci_host_info = {
     .name          = "grackle-pcihost",
     .parent        = TYPE_SYS_BUS_DEVICE,
     .instance_size = sizeof(GrackleState),
diff --git a/hw/gt64xxx.c b/hw/gt64xxx.c
index a2d0e5a..04831bb 100644
--- a/hw/gt64xxx.c
+++ b/hw/gt64xxx.c
@@ -1147,7 +1147,7 @@ static void gt64120_pci_class_init(ObjectClass *klass, void *data)
     k->class_id = PCI_CLASS_BRIDGE_HOST;
 }
 
-static TypeInfo gt64120_pci_info = {
+static const TypeInfo gt64120_pci_info = {
     .name          = "gt64120_pci",
     .parent        = TYPE_PCI_DEVICE,
     .instance_size = sizeof(PCIDevice),
@@ -1161,7 +1161,7 @@ static void gt64120_class_init(ObjectClass *klass, void *data)
     sdc->init = gt64120_init;
 }
 
-static TypeInfo gt64120_info = {
+static const TypeInfo gt64120_info = {
     .name          = "gt64120",
     .parent        = TYPE_SYS_BUS_DEVICE,
     .instance_size = sizeof(GT64120State),
diff --git a/hw/piix_pci.c b/hw/piix_pci.c
index c497a01..0b06a75 100644
--- a/hw/piix_pci.c
+++ b/hw/piix_pci.c
@@ -537,7 +537,7 @@ static void piix3_class_init(ObjectClass *klass, void *data)
     k->class_id     = PCI_CLASS_BRIDGE_ISA;
 }
 
-static TypeInfo piix3_info = {
+static const TypeInfo piix3_info = {
     .name          = "PIIX3",
     .parent        = TYPE_PCI_DEVICE,
     .instance_size = sizeof(PIIX3State),
@@ -560,7 +560,7 @@ static void piix3_xen_class_init(ObjectClass *klass, void *data)
     k->class_id     = PCI_CLASS_BRIDGE_ISA;
 };
 
-static TypeInfo piix3_xen_info = {
+static const TypeInfo piix3_xen_info = {
     .name          = "PIIX3-xen",
     .parent        = TYPE_PCI_DEVICE,
     .instance_size = sizeof(PIIX3State),
@@ -584,7 +584,7 @@ static void i440fx_class_init(ObjectClass *klass, void *data)
     dc->vmsd = &vmstate_i440fx;
 }
 
-static TypeInfo i440fx_info = {
+static const TypeInfo i440fx_info = {
     .name          = "i440FX",
     .parent        = TYPE_PCI_DEVICE,
     .instance_size = sizeof(PCII440FXState),
@@ -601,7 +601,7 @@ static void i440fx_pcihost_class_init(ObjectClass *klass, void *data)
     dc->no_user = 1;
 }
 
-static TypeInfo i440fx_pcihost_info = {
+static const TypeInfo i440fx_pcihost_info = {
     .name          = "i440FX-pcihost",
     .parent        = TYPE_SYS_BUS_DEVICE,
     .instance_size = sizeof(I440FXState),
diff --git a/hw/ppc4xx_pci.c b/hw/ppc4xx_pci.c
index 203c3cd..104ed98 100644
--- a/hw/ppc4xx_pci.c
+++ b/hw/ppc4xx_pci.c
@@ -377,7 +377,7 @@ static void ppc4xx_host_bridge_class_init(ObjectClass *klass, void *data)
     k->class_id     = PCI_CLASS_BRIDGE_OTHER;
 }
 
-static TypeInfo ppc4xx_host_bridge_info = {
+static const TypeInfo ppc4xx_host_bridge_info = {
     .name          = "ppc4xx-host-bridge",
     .parent        = TYPE_PCI_DEVICE,
     .instance_size = sizeof(PCIDevice),
@@ -393,7 +393,7 @@ static void ppc4xx_pcihost_class_init(ObjectClass *klass, void *data)
     dc->vmsd = &vmstate_ppc4xx_pci;
 }
 
-static TypeInfo ppc4xx_pcihost_info = {
+static const TypeInfo ppc4xx_pcihost_info = {
     .name          = "ppc4xx-pcihost",
     .parent        = TYPE_SYS_BUS_DEVICE,
     .instance_size = sizeof(PPC4xxPCIState),
diff --git a/hw/ppce500_pci.c b/hw/ppce500_pci.c
index 0f60b24..99748b3 100644
--- a/hw/ppce500_pci.c
+++ b/hw/ppce500_pci.c
@@ -350,7 +350,7 @@ static void e500_host_bridge_class_init(ObjectClass *klass, void *data)
     dc->desc = "Host bridge";
 }
 
-static TypeInfo e500_host_bridge_info = {
+static const TypeInfo e500_host_bridge_info = {
     .name          = "e500-host-bridge",
     .parent        = TYPE_PCI_DEVICE,
     .instance_size = sizeof(PCIDevice),
@@ -366,7 +366,7 @@ static void e500_pcihost_class_init(ObjectClass *klass, void *data)
     dc->vmsd = &vmstate_ppce500_pci;
 }
 
-static TypeInfo e500_pcihost_info = {
+static const TypeInfo e500_pcihost_info = {
     .name          = "e500-pcihost",
     .parent        = TYPE_SYS_BUS_DEVICE,
     .instance_size = sizeof(PPCE500PCIState),
diff --git a/hw/prep_pci.c b/hw/prep_pci.c
index 38dbff4..a8cdc21 100644
--- a/hw/prep_pci.c
+++ b/hw/prep_pci.c
@@ -166,7 +166,7 @@ static void raven_class_init(ObjectClass *klass, void *data)
     dc->no_user = 1;
 }
 
-static TypeInfo raven_info = {
+static const TypeInfo raven_info = {
     .name = "raven",
     .parent = TYPE_PCI_DEVICE,
     .instance_size = sizeof(RavenPCIState),
@@ -183,7 +183,7 @@ static void raven_pcihost_class_init(ObjectClass *klass, void *data)
     dc->no_user = 1;
 }
 
-static TypeInfo raven_pcihost_info = {
+static const TypeInfo raven_pcihost_info = {
     .name = "raven-pcihost",
     .parent = TYPE_SYS_BUS_DEVICE,
     .instance_size = sizeof(PREPPCIState),
diff --git a/hw/spapr_pci.c b/hw/spapr_pci.c
index b92583a..c57ab1e 100644
--- a/hw/spapr_pci.c
+++ b/hw/spapr_pci.c
@@ -612,7 +612,7 @@ static void spapr_phb_class_init(ObjectClass *klass, void *data)
     dc->props = spapr_phb_properties;
 }
 
-static TypeInfo spapr_phb_info = {
+static const TypeInfo spapr_phb_info = {
     .name          = "spapr-pci-host-bridge",
     .parent        = TYPE_SYS_BUS_DEVICE,
     .instance_size = sizeof(sPAPRPHBState),
diff --git a/hw/unin_pci.c b/hw/unin_pci.c
index 409bcd4..2b309df 100644
--- a/hw/unin_pci.c
+++ b/hw/unin_pci.c
@@ -350,7 +350,7 @@ static void unin_main_pci_host_class_init(ObjectClass *klass, void *data)
     k->class_id  = PCI_CLASS_BRIDGE_HOST;
 }
 
-static TypeInfo unin_main_pci_host_info = {
+static const TypeInfo unin_main_pci_host_info = {
     .name = "uni-north-pci",
     .parent = TYPE_PCI_DEVICE,
     .instance_size = sizeof(PCIDevice),
@@ -368,7 +368,7 @@ static void u3_agp_pci_host_class_init(ObjectClass *klass, void *data)
     k->class_id  = PCI_CLASS_BRIDGE_HOST;
 }
 
-static TypeInfo u3_agp_pci_host_info = {
+static const TypeInfo u3_agp_pci_host_info = {
     .name = "u3-agp",
     .parent = TYPE_PCI_DEVICE,
     .instance_size = sizeof(PCIDevice),
@@ -386,7 +386,7 @@ static void unin_agp_pci_host_class_init(ObjectClass *klass, void *data)
     k->class_id  = PCI_CLASS_BRIDGE_HOST;
 }
 
-static TypeInfo unin_agp_pci_host_info = {
+static const TypeInfo unin_agp_pci_host_info = {
     .name = "uni-north-agp",
     .parent = TYPE_PCI_DEVICE,
     .instance_size = sizeof(PCIDevice),
@@ -404,7 +404,7 @@ static void unin_internal_pci_host_class_init(ObjectClass *klass, void *data)
     k->class_id  = PCI_CLASS_BRIDGE_HOST;
 }
 
-static TypeInfo unin_internal_pci_host_info = {
+static const TypeInfo unin_internal_pci_host_info = {
     .name = "uni-north-internal-pci",
     .parent = TYPE_PCI_DEVICE,
     .instance_size = sizeof(PCIDevice),
@@ -418,7 +418,7 @@ static void pci_unin_main_class_init(ObjectClass *klass, void *data)
     sbc->init = pci_unin_main_init_device;
 }
 
-static TypeInfo pci_unin_main_info = {
+static const TypeInfo pci_unin_main_info = {
     .name          = "uni-north-pci-pcihost",
     .parent        = TYPE_SYS_BUS_DEVICE,
     .instance_size = sizeof(UNINState),
@@ -432,7 +432,7 @@ static void pci_u3_agp_class_init(ObjectClass *klass, void *data)
     sbc->init = pci_u3_agp_init_device;
 }
 
-static TypeInfo pci_u3_agp_info = {
+static const TypeInfo pci_u3_agp_info = {
     .name          = "u3-agp-pcihost",
     .parent        = TYPE_SYS_BUS_DEVICE,
     .instance_size = sizeof(UNINState),
@@ -446,7 +446,7 @@ static void pci_unin_agp_class_init(ObjectClass *klass, void *data)
     sbc->init = pci_unin_agp_init_device;
 }
 
-static TypeInfo pci_unin_agp_info = {
+static const TypeInfo pci_unin_agp_info = {
     .name          = "uni-north-agp-pcihost",
     .parent        = TYPE_SYS_BUS_DEVICE,
     .instance_size = sizeof(UNINState),
@@ -460,7 +460,7 @@ static void pci_unin_internal_class_init(ObjectClass *klass, void *data)
     sbc->init = pci_unin_internal_init_device;
 }
 
-static TypeInfo pci_unin_internal_info = {
+static const TypeInfo pci_unin_internal_info = {
     .name          = "uni-north-internal-pci-pcihost",
     .parent        = TYPE_SYS_BUS_DEVICE,
     .instance_size = sizeof(UNINState),
commit ea776abca628d855e03c4929da3864985afd8aae
Author: Stefan Hajnoczi <stefanha at linux.vnet.ibm.com>
Date:   Tue Aug 21 14:40:49 2012 +0100

    virtio-blk: hide VIRTIO_BLK_F_CONFIG_WCE from old machine types
    
    QEMU has a policy of keeping a stable guest device ABI.  When new guest device
    features are introduced they must not change hardware info seen by existing
    guests.  This is important because operating systems or applications may
    "fingerprint" the hardware and refuse to run when the hardware changes.  To
    always get the latest guest device ABI, run with x86 machine type "pc".
    
    This patch hides the new VIRTIO_BLK_F_CONFIG_WCE virtio feature bit from
    existing machine types.  Only pc-1.2 and later will expose this feature
    by default.
    
    For more info on the VIRTIO_BLK_F_CONFIG_WCE feature bit, see:
    
      commit 13e3dce068773c971ff2f19d986378c55897c4a3
      Author: Paolo Bonzini <pbonzini at redhat.com>
      Date:   Thu Aug 9 16:07:19 2012 +0200
    
          virtio-blk: support VIRTIO_BLK_F_CONFIG_WCE
    
          Also rename VIRTIO_BLK_F_WCACHE to VIRTIO_BLK_F_WCE for consistency with
          the spec.
    
          Signed-off-by: Paolo Bonzini <pbonzini at redhat.com>
          Signed-off-by: Kevin Wolf <kwolf at redhat.com>
    
    Anthony Liguori <aliguori at us.ibm.com> reported:
    
      This broke qemu-test because it changed the pc-1.0 machine type:
    
      Setting guest RANDOM seed to 47167
      *** Running tests ***
      Running test /tests/finger-print.sh...		OK
      --- fingerprints/pc-1.0.x86_64	2011-12-18 13:08:40.000000000 -0600
      +++ fingerprint.txt	2012-08-12 13:30:48.000000000 -0500
      @@ -55,7 +55,7 @@
       /sys/bus/pci/devices/0000:00:06.0/subsystem_device=0x0002
       /sys/bus/pci/devices/0000:00:06.0/class=0x010000
       /sys/bus/pci/devices/0000:00:06.0/revision=0x00
      -/sys/bus/pci/devices/0000:00:06.0/virtio/host-features=0x710006d4
      +/sys/bus/pci/devices/0000:00:06.0/virtio/host-features=0x71000ed4
       /sys/class/dmi/id/bios_vendor=Bochs
       /sys/class/dmi/id/bios_date=01/01/2007
       /sys/class/dmi/id/bios_version=Bochs
      Guest fingerprint changed for pc-1.0!
    
    Reported-by: Anthony Liguori <aliguori at us.ibm.com>
    Signed-off-by: Stefan Hajnoczi <stefanha at linux.vnet.ibm.com>
    Signed-off-by: Anthony Liguori <aliguori at us.ibm.com>

diff --git a/hw/pc_piix.c b/hw/pc_piix.c
index 0c0096f..d68dbb2 100644
--- a/hw/pc_piix.c
+++ b/hw/pc_piix.c
@@ -375,6 +375,10 @@ static QEMUMachine pc_machine_v1_2 = {
             .driver   = "qxl",\
             .property = "vgamem_mb",\
             .value    = stringify(8),\
+        },{\
+            .driver   = "virtio-blk-pci",\
+            .property = "config-wce",\
+            .value    = "off",\
         }
 
 static QEMUMachine pc_machine_v1_1 = {
diff --git a/hw/virtio-blk.c b/hw/virtio-blk.c
index fd8fa90..6f6d172 100644
--- a/hw/virtio-blk.c
+++ b/hw/virtio-blk.c
@@ -533,7 +533,6 @@ static uint32_t virtio_blk_get_features(VirtIODevice *vdev, uint32_t features)
     features |= (1 << VIRTIO_BLK_F_BLK_SIZE);
     features |= (1 << VIRTIO_BLK_F_SCSI);
 
-    features |= (1 << VIRTIO_BLK_F_CONFIG_WCE);
     if (bdrv_enable_write_cache(s->bs))
         features |= (1 << VIRTIO_BLK_F_WCE);
 
diff --git a/hw/virtio-blk.h b/hw/virtio-blk.h
index 35834cf..651a000 100644
--- a/hw/virtio-blk.h
+++ b/hw/virtio-blk.h
@@ -107,6 +107,7 @@ struct VirtIOBlkConf
 };
 
 #define DEFINE_VIRTIO_BLK_FEATURES(_state, _field) \
-        DEFINE_VIRTIO_COMMON_FEATURES(_state, _field)
+        DEFINE_VIRTIO_COMMON_FEATURES(_state, _field), \
+        DEFINE_PROP_BIT("config-wce", _state, _field, VIRTIO_BLK_F_CONFIG_WCE, true)
 
 #endif
commit 15d9e3bc6af8a56af8c61911aab8453a54795db1
Author: Jim Meyering <meyering at redhat.com>
Date:   Wed Aug 22 13:55:56 2012 +0200

    softmmu-semi: fix lock_user* functions not to deref NULL upon OOM
    
    Return NULL upon malloc failure.
    
    Signed-off-by: Jim Meyering <meyering at redhat.com>
    Signed-off-by: Anthony Liguori <aliguori at us.ibm.com>

diff --git a/softmmu-semi.h b/softmmu-semi.h
index 648cb95..bcb979a 100644
--- a/softmmu-semi.h
+++ b/softmmu-semi.h
@@ -40,7 +40,7 @@ static void *softmmu_lock_user(CPUArchState *env, uint32_t addr, uint32_t len,
     uint8_t *p;
     /* TODO: Make this something that isn't fixed size.  */
     p = malloc(len);
-    if (copy)
+    if (p && copy)
         cpu_memory_rw_debug(env, addr, p, len, 0);
     return p;
 }
@@ -52,6 +52,9 @@ static char *softmmu_lock_user_string(CPUArchState *env, uint32_t addr)
     uint8_t c;
     /* TODO: Make this something that isn't fixed size.  */
     s = p = malloc(1024);
+    if (!s) {
+        return NULL;
+    }
     do {
         cpu_memory_rw_debug(env, addr, &c, 1, 0);
         addr++;
commit 396bef4b3846bf4e80a2bee38e9a2d8554d0f251
Author: Jim Meyering <meyering at redhat.com>
Date:   Wed Aug 22 13:55:55 2012 +0200

    arm-semi: don't leak 1KB user string lock buffer upon TARGET_SYS_OPEN
    
    Always call unlock_user before returning.
    
    Signed-off-by: Jim Meyering <meyering at redhat.com>
    Signed-off-by: Anthony Liguori <aliguori at us.ibm.com>

diff --git a/target-arm/arm-semi.c b/target-arm/arm-semi.c
index 2495206..73bde58 100644
--- a/target-arm/arm-semi.c
+++ b/target-arm/arm-semi.c
@@ -194,18 +194,19 @@ uint32_t do_arm_semihosting(CPUARMState *env)
         if (!(s = lock_user_string(ARG(0))))
             /* FIXME - should this error code be -TARGET_EFAULT ? */
             return (uint32_t)-1;
-        if (ARG(1) >= 12)
+        if (ARG(1) >= 12) {
+            unlock_user(s, ARG(0), 0);
             return (uint32_t)-1;
+        }
         if (strcmp(s, ":tt") == 0) {
-            if (ARG(1) < 4)
-                return STDIN_FILENO;
-            else
-                return STDOUT_FILENO;
+            int result_fileno = ARG(1) < 4 ? STDIN_FILENO : STDOUT_FILENO;
+            unlock_user(s, ARG(0), 0);
+            return result_fileno;
         }
         if (use_gdb_syscalls()) {
             gdb_do_syscall(arm_semi_cb, "open,%s,%x,1a4", ARG(0),
 			   (int)ARG(2)+1, gdb_open_modeflags[ARG(1)]);
-            return env->regs[0];
+            ret = env->regs[0];
         } else {
             ret = set_swi_errno(ts, open(s, open_modeflags[ARG(1)], 0644));
         }
commit a7e47d4bfcbf256fae06891a8599950ff8e1b61b
Author: Jim Meyering <meyering at redhat.com>
Date:   Wed Aug 22 13:55:54 2012 +0200

    sheepdog: don't leak socket file descriptor upon connection failure
    
    Signed-off-by: Jim Meyering <meyering at redhat.com>
    Signed-off-by: Anthony Liguori <aliguori at us.ibm.com>

diff --git a/block/sheepdog.c b/block/sheepdog.c
index a04ad99..df4f441 100644
--- a/block/sheepdog.c
+++ b/block/sheepdog.c
@@ -485,6 +485,7 @@ static int connect_to_sdog(const char *addr, const char *port)
             if (errno == EINTR) {
                 goto reconnect;
             }
+            close(fd);
             break;
         }
 
commit 0d07fe47d4986271a21ed4ff5237275ff55dd93f
Author: Jim Meyering <meyering at redhat.com>
Date:   Wed Aug 22 13:55:53 2012 +0200

    linux-user: do_msgrcv: don't leak host_mb upon TARGET_EFAULT failure
    
    Also, use g_malloc to avoid NULL-deref upon OOM.
    
    Signed-off-by: Jim Meyering <meyering at redhat.com>
    Signed-off-by: Anthony Liguori <aliguori at us.ibm.com>

diff --git a/linux-user/syscall.c b/linux-user/syscall.c
index 41c869b..1174306 100644
--- a/linux-user/syscall.c
+++ b/linux-user/syscall.c
@@ -2848,7 +2848,7 @@ static inline abi_long do_msgrcv(int msqid, abi_long msgp,
     if (!lock_user_struct(VERIFY_WRITE, target_mb, msgp, 0))
         return -TARGET_EFAULT;
 
-    host_mb = malloc(msgsz+sizeof(long));
+    host_mb = g_malloc(msgsz+sizeof(long));
     ret = get_errno(msgrcv(msqid, host_mb, msgsz, tswapal(msgtyp), msgflg));
 
     if (ret > 0) {
@@ -2863,11 +2863,11 @@ static inline abi_long do_msgrcv(int msqid, abi_long msgp,
     }
 
     target_mb->mtype = tswapal(host_mb->mtype);
-    free(host_mb);
 
 end:
     if (target_mb)
         unlock_user_struct(target_mb, msgp, 1);
+    g_free(host_mb);
     return ret;
 }
 
commit 4144f122b477164cf466ca69be24cf4ef5c218d3
Author: Jim Meyering <meyering at redhat.com>
Date:   Wed Aug 22 13:55:52 2012 +0200

    qemu-ga: don't leak a file descriptor upon failed lockf
    
    Signed-off-by: Jim Meyering <meyering at redhat.com>
    Signed-off-by: Anthony Liguori <aliguori at us.ibm.com>

diff --git a/qemu-ga.c b/qemu-ga.c
index 8f87621..26671fe 100644
--- a/qemu-ga.c
+++ b/qemu-ga.c
@@ -247,6 +247,9 @@ static bool ga_open_pidfile(const char *pidfile)
     pidfd = open(pidfile, O_CREAT|O_WRONLY, S_IRUSR|S_IWUSR);
     if (pidfd == -1 || lockf(pidfd, F_TLOCK, 0)) {
         g_critical("Cannot lock pid file, %s", strerror(errno));
+        if (pidfd != -1) {
+            close(pidfd);
+        }
         return false;
     }
 
commit 14d40183725361e6350166099556c7661063921b
Author: Dongxiao Xu <dongxiao.xu at intel.com>
Date:   Wed Aug 22 10:17:43 2012 +0000

    xen-all.c: fix multiply issue for int and uint types
    
    If the two multiply operands are int and uint types separately,
    the int type will be transformed to uint firstly, which is not the
    intent in our code piece. The fix is to add (int64_t) transform
    for the uint type before the multiply.
    
    Signed-off-by: Dongxiao Xu <dongxiao.xu at intel.com>
    Signed-off-by: Stefano Stabellini <stefano.stabellini at eu.citrix.com>

diff --git a/xen-all.c b/xen-all.c
index 61def2e..f76b051 100644
--- a/xen-all.c
+++ b/xen-all.c
@@ -712,7 +712,8 @@ static void cpu_ioreq_pio(ioreq_t *req)
 
             for (i = 0; i < req->count; i++) {
                 tmp = do_inp(req->addr, req->size);
-                cpu_physical_memory_write(req->data + (sign * i * req->size),
+                cpu_physical_memory_write(
+                        req->data + (sign * i * (int64_t)req->size),
                         (uint8_t *) &tmp, req->size);
             }
         }
@@ -723,7 +724,8 @@ static void cpu_ioreq_pio(ioreq_t *req)
             for (i = 0; i < req->count; i++) {
                 uint32_t tmp = 0;
 
-                cpu_physical_memory_read(req->data + (sign * i * req->size),
+                cpu_physical_memory_read(
+                        req->data + (sign * i * (int64_t)req->size),
                         (uint8_t*) &tmp, req->size);
                 do_outp(req->addr, req->size, tmp);
             }
@@ -740,12 +742,14 @@ static void cpu_ioreq_move(ioreq_t *req)
     if (!req->data_is_ptr) {
         if (req->dir == IOREQ_READ) {
             for (i = 0; i < req->count; i++) {
-                cpu_physical_memory_read(req->addr + (sign * i * req->size),
+                cpu_physical_memory_read(
+                        req->addr + (sign * i * (int64_t)req->size),
                         (uint8_t *) &req->data, req->size);
             }
         } else if (req->dir == IOREQ_WRITE) {
             for (i = 0; i < req->count; i++) {
-                cpu_physical_memory_write(req->addr + (sign * i * req->size),
+                cpu_physical_memory_write(
+                        req->addr + (sign * i * (int64_t)req->size),
                         (uint8_t *) &req->data, req->size);
             }
         }
@@ -754,16 +758,20 @@ static void cpu_ioreq_move(ioreq_t *req)
 
         if (req->dir == IOREQ_READ) {
             for (i = 0; i < req->count; i++) {
-                cpu_physical_memory_read(req->addr + (sign * i * req->size),
+                cpu_physical_memory_read(
+                        req->addr + (sign * i * (int64_t)req->size),
                         (uint8_t*) &tmp, req->size);
-                cpu_physical_memory_write(req->data + (sign * i * req->size),
+                cpu_physical_memory_write(
+                        req->data + (sign * i * (int64_t)req->size),
                         (uint8_t*) &tmp, req->size);
             }
         } else if (req->dir == IOREQ_WRITE) {
             for (i = 0; i < req->count; i++) {
-                cpu_physical_memory_read(req->data + (sign * i * req->size),
+                cpu_physical_memory_read(
+                        req->data + (sign * i * (int64_t)req->size),
                         (uint8_t*) &tmp, req->size);
-                cpu_physical_memory_write(req->addr + (sign * i * req->size),
+                cpu_physical_memory_write(
+                        req->addr + (sign * i * (int64_t)req->size),
                         (uint8_t*) &tmp, req->size);
             }
         }
commit 27b7652ef515bb4c694f79d657d2052c72b19536
Author: Frediano Ziglio <frediano.ziglio at citrix.com>
Date:   Wed Aug 22 10:17:04 2012 +0000

    Fix invalidate if memory requested was not bucket aligned
    
    When memory is mapped in qemu_map_cache with lock != 0 a reverse mapping
    is created pointing to the virtual address of location requested.
    The cached mapped entry is saved in last_address_vaddr with the memory
    location of the base virtual address (without bucket offset).
    However when this entry is invalidated the virtual address saved in the
    reverse mapping is used. This cause that the mapping is freed but the
    last_address_vaddr is not reset.
    
    Signed-off-by: Frediano Ziglio <frediano.ziglio at citrix.com>
    Signed-off-by: Stefano Stabellini <stefano.stabellini at eu.citrix.com>

diff --git a/xen-mapcache.c b/xen-mapcache.c
index 59ba085..9cd6db3 100644
--- a/xen-mapcache.c
+++ b/xen-mapcache.c
@@ -320,10 +320,6 @@ void xen_invalidate_map_cache_entry(uint8_t *buffer)
     target_phys_addr_t size;
     int found = 0;
 
-    if (mapcache->last_address_vaddr == buffer) {
-        mapcache->last_address_index = -1;
-    }
-
     QTAILQ_FOREACH(reventry, &mapcache->locked_entries, next) {
         if (reventry->vaddr_req == buffer) {
             paddr_index = reventry->paddr_index;
@@ -342,6 +338,11 @@ void xen_invalidate_map_cache_entry(uint8_t *buffer)
     QTAILQ_REMOVE(&mapcache->locked_entries, reventry, next);
     g_free(reventry);
 
+    if (mapcache->last_address_index == paddr_index) {
+        mapcache->last_address_index = -1;
+        mapcache->last_address_vaddr = NULL;
+    }
+
     entry = &mapcache->entry[paddr_index % mapcache->nr_buckets];
     while (entry && (entry->paddr_index != paddr_index || entry->size != size)) {
         pentry = entry;
commit 0ec64507a5e6366e6d8070a82c866b935f687ed9
Author: Jan Kiszka <jan.kiszka at siemens.com>
Date:   Fri Aug 17 12:56:44 2012 +0200

    i82378: Remove bogus MMIO coalescing
    
    This MMIO area is an entry gate to legacy PC ISA devices, addressed via
    PIO over there. Quite a few of the PIO ports have side effects on access
    like starting/stopping timers that must be executed properly ordered
    /wrt the CPU. So we have to remove the coalescing mark.
    
    Acked-by: Hervé Poussineau <hpoussin at reactos.org>
    Acked-by: Andreas Färber <andreas.faerber at web.de>
    Signed-off-by: Jan Kiszka <jan.kiszka at siemens.com>
    Signed-off-by: Anthony Liguori <aliguori at us.ibm.com>

diff --git a/hw/i82378.c b/hw/i82378.c
index 9b11d90..2123c14 100644
--- a/hw/i82378.c
+++ b/hw/i82378.c
@@ -225,7 +225,6 @@ static int pci_i82378_init(PCIDevice *dev)
     pci_register_bar(dev, 0, PCI_BASE_ADDRESS_SPACE_MEMORY, &s->io);
 
     memory_region_init_io(&s->mem, &i82378_mem_ops, s, "i82378-mem", 0x01000000);
-    memory_region_set_coalescing(&s->mem);
     pci_register_bar(dev, 1, PCI_BASE_ADDRESS_SPACE_MEMORY, &s->mem);
 
     /* Make I/O address read only */
commit 55ce75faf253d4369670f60409c608e665e8dde9
Author: Alexey Kardashevskiy <aik at ozlabs.ru>
Date:   Wed Jul 18 22:52:04 2012 +1000

    eventfd: making it thread safe
    
    QEMU uses IO handlers to run select() in the main loop.
    The handlers list is managed by qemu_set_fd_handler() helper
    which works fine when called from the main thread as it is
    called when select() is not waiting.
    
    However IO handlers list can be changed in the thread other than
    the main one doing os_host_main_loop_wait(), for example, as a result
    of a hypercall which changes PCI config space (VFIO on POWER is the case)
    and enables/disabled MSI/MSIX which closes/creates eventfd handles.
    As the main loop should be waiting on the newly created eventfds,
    it has to be restarted.
    
    The patch adds the qemu_notify_event() call to interrupt select()
    to make main_loop() restart select() with the updated IO handlers
    list.
    
    Signed-off-by: Alexey Kardashevskiy <aik at ozlabs.ru>
    Reviewed-by: Paolo Bonzini <pbonzini at redhat.com>
    Signed-off-by: Anthony Liguori <aliguori at us.ibm.com>

diff --git a/iohandler.c b/iohandler.c
index 3c74de6..dea4355 100644
--- a/iohandler.c
+++ b/iohandler.c
@@ -77,6 +77,7 @@ int qemu_set_fd_handler2(int fd,
         ioh->fd_write = fd_write;
         ioh->opaque = opaque;
         ioh->deleted = 0;
+        qemu_notify_event();
     }
     return 0;
 }
commit 7aa939af39e20eeca98fced59708a87c64267f54
Author: Juan Quintela <quintela at redhat.com>
Date:   Sat Aug 18 13:17:10 2012 +0200

    migration: move total_time from ram stats to migration info
    
    Signed-off-by: Juan Quintela <quintela at redhat.com>
    Signed-off-by: Luiz Capitulino <lcapitulino at redhat.com>

diff --git a/hmp.c b/hmp.c
index a9d5675..81c8acb 100644
--- a/hmp.c
+++ b/hmp.c
@@ -149,6 +149,8 @@ void hmp_info_migrate(Monitor *mon)
 
     if (info->has_status) {
         monitor_printf(mon, "Migration status: %s\n", info->status);
+        monitor_printf(mon, "total time: %" PRIu64 " milliseconds\n",
+                       info->total_time);
     }
 
     if (info->has_ram) {
@@ -158,8 +160,6 @@ void hmp_info_migrate(Monitor *mon)
                        info->ram->remaining >> 10);
         monitor_printf(mon, "total ram: %" PRIu64 " kbytes\n",
                        info->ram->total >> 10);
-        monitor_printf(mon, "total time: %" PRIu64 " milliseconds\n",
-                       info->ram->total_time);
         monitor_printf(mon, "duplicate: %" PRIu64 " pages\n",
                        info->ram->duplicate);
         monitor_printf(mon, "normal: %" PRIu64 " pages\n",
diff --git a/migration.c b/migration.c
index 653a3c1..1edeec5 100644
--- a/migration.c
+++ b/migration.c
@@ -166,14 +166,15 @@ MigrationInfo *qmp_query_migrate(Error **errp)
     case MIG_STATE_ACTIVE:
         info->has_status = true;
         info->status = g_strdup("active");
+        info->has_total_time = true;
+        info->total_time = qemu_get_clock_ms(rt_clock)
+            - s->total_time;
 
         info->has_ram = true;
         info->ram = g_malloc0(sizeof(*info->ram));
         info->ram->transferred = ram_bytes_transferred();
         info->ram->remaining = ram_bytes_remaining();
         info->ram->total = ram_bytes_total();
-        info->ram->total_time = qemu_get_clock_ms(rt_clock)
-            - s->total_time;
         info->ram->duplicate = dup_mig_pages_transferred();
         info->ram->normal = norm_mig_pages_transferred();
         info->ram->normal_bytes = norm_mig_bytes_transferred();
@@ -193,13 +194,13 @@ MigrationInfo *qmp_query_migrate(Error **errp)
 
         info->has_status = true;
         info->status = g_strdup("completed");
+        info->total_time = s->total_time;
 
         info->has_ram = true;
         info->ram = g_malloc0(sizeof(*info->ram));
         info->ram->transferred = ram_bytes_transferred();
         info->ram->remaining = 0;
         info->ram->total = ram_bytes_total();
-        info->ram->total_time = s->total_time;
         info->ram->duplicate = dup_mig_pages_transferred();
         info->ram->normal = norm_mig_pages_transferred();
         info->ram->normal_bytes = norm_mig_bytes_transferred();
diff --git a/qapi-schema.json b/qapi-schema.json
index 3d2b2d1..37f47e1 100644
--- a/qapi-schema.json
+++ b/qapi-schema.json
@@ -290,10 +290,6 @@
 #
 # @total: total amount of bytes involved in the migration process
 #
-# @total-time: total amount of ms since migration started.  If
-#        migration has ended, it returns the total migration
-#        time. (since 1.2)
-#
 # @duplicate: number of duplicate pages (since 1.2)
 #
 # @normal : number of normal pages (since 1.2)
@@ -304,8 +300,7 @@
 ##
 { 'type': 'MigrationStats',
   'data': {'transferred': 'int', 'remaining': 'int', 'total': 'int' ,
-           'total-time': 'int', 'duplicate': 'int', 'normal': 'int',
-           'normal-bytes': 'int' } }
+           'duplicate': 'int', 'normal': 'int', 'normal-bytes': 'int' } }
 
 ##
 # @XBZRLECacheStats
@@ -350,12 +345,17 @@
 #                migration statistics, only returned if XBZRLE feature is on and
 #                status is 'active' or 'completed' (since 1.2)
 #
+# @total-time: #optional total amount of milliseconds since migration started.
+#        If migration has ended, it returns the total migration
+#        time. (since 1.2)
+#
 # Since: 0.14.0
 ##
 { 'type': 'MigrationInfo',
   'data': {'*status': 'str', '*ram': 'MigrationStats',
            '*disk': 'MigrationStats',
-           '*xbzrle-cache': 'XBZRLECacheStats'} }
+           '*xbzrle-cache': 'XBZRLECacheStats',
+           '*total-time': 'int'} }
 
 ##
 # @query-migrate
diff --git a/qmp-commands.hx b/qmp-commands.hx
index 2ce4ce6..8671bf3 100644
--- a/qmp-commands.hx
+++ b/qmp-commands.hx
@@ -2239,14 +2239,14 @@ The main json-object contains the following:
 
 - "status": migration status (json-string)
      - Possible values: "active", "completed", "failed", "cancelled"
+- "total-time": total amount of ms since migration started.  If
+                migration has ended, it returns the total migration
+		 time (json-int)
 - "ram": only present if "status" is "active", it is a json-object with the
   following RAM information (in bytes):
          - "transferred": amount transferred (json-int)
          - "remaining": amount remaining (json-int)
          - "total": total (json-int)
-         - "total-time": total amount of ms since migration started.  If
-                         migration has ended, it returns the total migration time
-                         (json-int)
          - "duplicate": number of duplicated pages (json-int)
          - "normal" : number of normal pages transferred (json-int)
          - "normal-bytes" : number of normal bytes transferred (json-int)
commit b2dc64c391843f6499069f0ba77ad0a8c9560c86
Author: Blue Swirl <blauwirbel at gmail.com>
Date:   Sat Aug 18 20:14:54 2012 +0000

    monitor: avoid declaring unused variables
    
    Some variables are only used on !win32, declare
    them only when used.
    
    This avoids a warning in mingw32 build:
      CC    i386-softmmu/monitor.o
    /src/qemu/monitor.c: In function 'monitor_fdset_get_fd':
    /src/qemu/monitor.c:2575: warning: unused variable 'mon_fd_flags'
    /src/qemu/monitor.c:2574: warning: unused variable 'mon_fdset_fd'
    /src/qemu/monitor.c:2573: warning: unused variable 'mon_fdset'
    
    Signed-off-by: Blue Swirl <blauwirbel at gmail.com>
    Reviewed-by: Stefan Weil <sw at weilnetz.de>
    Signed-off-by: Luiz Capitulino <lcapitulino at redhat.com>

diff --git a/monitor.c b/monitor.c
index ce42466..480f583 100644
--- a/monitor.c
+++ b/monitor.c
@@ -2570,11 +2570,11 @@ FdsetInfoList *qmp_query_fdsets(Error **errp)
 
 int monitor_fdset_get_fd(int64_t fdset_id, int flags)
 {
+#ifndef _WIN32
     MonFdset *mon_fdset;
     MonFdsetFd *mon_fdset_fd;
     int mon_fd_flags;
 
-#ifndef _WIN32
     QLIST_FOREACH(mon_fdset, &mon_fdsets, next) {
         if (mon_fdset->id != fdset_id) {
             continue;
commit e36c87667aa2204a3f19efe7bbcb6eb41f098e40
Author: Stefan Weil <sw at weilnetz.de>
Date:   Sat Aug 18 22:51:29 2012 +0200

    qapi: Fix memory leak
    
    valgrind report:
    
    ==24534== 232 bytes in 2 blocks are definitely lost in loss record 1,245 of 1,601
    ==24534==    at 0x4824F20: malloc (vg_replace_malloc.c:236)
    ==24534==    by 0x293C88: malloc_and_trace (vl.c:2281)
    ==24534==    by 0x489AD99: ??? (in /lib/libglib-2.0.so.0.2400.1)
    ==24534==    by 0x489B23B: g_malloc0 (in /lib/libglib-2.0.so.0.2400.1)
    ==24534==    by 0x2B4EFC: opts_visitor_new (opts-visitor.c:376)
    ==24534==    by 0x29DEA5: net_client_init (net.c:708)
    ==24534==    by 0x29E6C7: net_init_client (net.c:966)
    ==24534==    by 0x2C2179: qemu_opts_foreach (qemu-option.c:1114)
    ==24534==    by 0x29E85B: net_init_clients (net.c:1008)
    ==24534==    by 0x296F40: main (vl.c:3463)
    
    Signed-off-by: Stefan Weil <sw at weilnetz.de>
    Reviewed-by: Laszlo Ersek <lersek at redhat.com>
    Signed-off-by: Luiz Capitulino <lcapitulino at redhat.com>

diff --git a/qapi/opts-visitor.c b/qapi/opts-visitor.c
index a59d306..e048b6c 100644
--- a/qapi/opts-visitor.c
+++ b/qapi/opts-visitor.c
@@ -416,7 +416,7 @@ opts_visitor_cleanup(OptsVisitor *ov)
         g_hash_table_destroy(ov->unprocessed_opts);
     }
     g_free(ov->fake_id_opt);
-    memset(ov, '\0', sizeof *ov);
+    g_free(ov);
 }
 
 
commit 07a5298c3067ed63f7d82d8c1a6f479146447289
Author: Paolo Bonzini <pbonzini at redhat.com>
Date:   Mon Aug 20 15:23:28 2012 +0200

    virtio-scsi: add backwards-compatibility properties for 1.1 and earlier machines
    
    Hotplug and parameter change are new in 1.2, disable them via compat
    properties for pc-1.1 and earlier.
    
    Signed-off-by: Paolo Bonzini <pbonzini at redhat.com>

diff --git a/hw/pc_piix.c b/hw/pc_piix.c
index 0c0096f..a960710 100644
--- a/hw/pc_piix.c
+++ b/hw/pc_piix.c
@@ -360,6 +360,14 @@ static QEMUMachine pc_machine_v1_2 = {
 
 #define PC_COMPAT_1_1 \
         {\
+            .driver   = "virtio-scsi-pci",\
+            .property = "hotplug",\
+            .value    = "off",\
+        },{\
+            .driver   = "virtio-scsi-pci",\
+            .property = "param_change",\
+            .value    = "off",\
+        },{\
             .driver   = "VGA",\
             .property = "vgamem_mb",\
             .value    = stringify(8),\
diff --git a/hw/virtio-scsi.c b/hw/virtio-scsi.c
index 5f737ac..c1b47a8 100644
--- a/hw/virtio-scsi.c
+++ b/hw/virtio-scsi.c
@@ -24,11 +24,6 @@
 #define VIRTIO_SCSI_MAX_TARGET  255
 #define VIRTIO_SCSI_MAX_LUN     16383
 
-/* Feature Bits */
-#define VIRTIO_SCSI_F_INOUT                    0
-#define VIRTIO_SCSI_F_HOTPLUG                  1
-#define VIRTIO_SCSI_F_CHANGE                   2
-
 /* Response codes */
 #define VIRTIO_SCSI_S_OK                       0
 #define VIRTIO_SCSI_S_OVERRUN                  1
@@ -561,8 +556,6 @@ static void virtio_scsi_set_config(VirtIODevice *vdev,
 static uint32_t virtio_scsi_get_features(VirtIODevice *vdev,
                                          uint32_t requested_features)
 {
-    requested_features |= (1UL << VIRTIO_SCSI_F_HOTPLUG);
-    requested_features |= (1UL << VIRTIO_SCSI_F_CHANGE);
     return requested_features;
 }
 
diff --git a/hw/virtio-scsi.h b/hw/virtio-scsi.h
index 4bc889d..91924f6 100644
--- a/hw/virtio-scsi.h
+++ b/hw/virtio-scsi.h
@@ -21,6 +21,11 @@
 /* The ID for virtio_scsi */
 #define VIRTIO_ID_SCSI  8
 
+/* Feature Bits */
+#define VIRTIO_SCSI_F_INOUT                    0
+#define VIRTIO_SCSI_F_HOTPLUG                  1
+#define VIRTIO_SCSI_F_CHANGE                   2
+
 struct VirtIOSCSIConf {
     uint32_t num_queues;
     uint32_t max_sectors;
@@ -31,6 +36,8 @@ struct VirtIOSCSIConf {
     DEFINE_VIRTIO_COMMON_FEATURES(_state, _features_field), \
     DEFINE_PROP_UINT32("num_queues", _state, _conf_field.num_queues, 1), \
     DEFINE_PROP_UINT32("max_sectors", _state, _conf_field.max_sectors, 0xFFFF), \
-    DEFINE_PROP_UINT32("cmd_per_lun", _state, _conf_field.cmd_per_lun, 128)
+    DEFINE_PROP_UINT32("cmd_per_lun", _state, _conf_field.cmd_per_lun, 128), \
+    DEFINE_PROP_BIT("hotplug", _state, _features_field, VIRTIO_SCSI_F_HOTPLUG, true), \
+    DEFINE_PROP_BIT("param_change", _state, _features_field, VIRTIO_SCSI_F_CHANGE, true)
 
 #endif /* _QEMU_VIRTIO_SCSI_H */
commit 1bd075f29ea6d11853475c7c42734595720c3ac6
Author: Paolo Bonzini <pbonzini at redhat.com>
Date:   Sat Aug 18 23:35:49 2012 +0200

    iscsi: fix races between task completion and abort
    
    This patch fixes two main issues with block/iscsi.c:
    
    1) iscsi_task_mgmt_abort_task_async calls iscsi_scsi_task_cancel which
    was also directly called in iscsi_aio_cancel
    
    2) a race between task completion and task abortion could happen cause
    the scsi_free_scsi_task were done before iscsi_schedule_bh has finished.
    To fix this, all the freeing of IscsiTasks and releasing of the AIOCBs
    is centralized in iscsi_bh_cb, independent of whether the SCSI command
    has completed or was cancelled.
    
    3) iscsi_aio_cancel was not synchronously waiting for the end of the
    command.
    
    Signed-off-by: Paolo Bonzini <pbonzini at redhat.com>

diff --git a/block/iscsi.c b/block/iscsi.c
index 7b09795..4828b83 100644
--- a/block/iscsi.c
+++ b/block/iscsi.c
@@ -83,12 +83,20 @@ iscsi_bh_cb(void *p)
         acb->common.cb(acb->common.opaque, acb->status);
     }
 
+    if (acb->task != NULL) {
+        scsi_free_scsi_task(acb->task);
+        acb->task = NULL;
+    }
+
     qemu_aio_release(acb);
 }
 
 static void
 iscsi_schedule_bh(IscsiAIOCB *acb)
 {
+    if (acb->bh) {
+        return;
+    }
     acb->bh = qemu_bh_new(iscsi_bh_cb, acb);
     qemu_bh_schedule(acb->bh);
 }
@@ -98,6 +106,10 @@ static void
 iscsi_abort_task_cb(struct iscsi_context *iscsi, int status, void *command_data,
                     void *private_data)
 {
+    IscsiAIOCB *acb = private_data;
+
+    acb->status = -ECANCELED;
+    iscsi_schedule_bh(acb);
 }
 
 static void
@@ -106,15 +118,19 @@ iscsi_aio_cancel(BlockDriverAIOCB *blockacb)
     IscsiAIOCB *acb = (IscsiAIOCB *)blockacb;
     IscsiLun *iscsilun = acb->iscsilun;
 
-    acb->common.cb(acb->common.opaque, -ECANCELED);
+    if (acb->status != -EINPROGRESS) {
+        return;
+    }
+
     acb->canceled = 1;
 
     /* send a task mgmt call to the target to cancel the task on the target */
     iscsi_task_mgmt_abort_task_async(iscsilun->iscsi, acb->task,
-                                     iscsi_abort_task_cb, NULL);
+                                     iscsi_abort_task_cb, acb);
 
-    /* then also cancel the task locally in libiscsi */
-    iscsi_scsi_task_cancel(iscsilun->iscsi, acb->task);
+    while (acb->status == -EINPROGRESS) {
+        qemu_aio_wait();
+    }
 }
 
 static AIOPool iscsi_aio_pool = {
@@ -192,9 +208,6 @@ iscsi_aio_write16_cb(struct iscsi_context *iscsi, int status,
     g_free(acb->buf);
 
     if (acb->canceled != 0) {
-        qemu_aio_release(acb);
-        scsi_free_scsi_task(acb->task);
-        acb->task = NULL;
         return;
     }
 
@@ -206,8 +219,6 @@ iscsi_aio_write16_cb(struct iscsi_context *iscsi, int status,
     }
 
     iscsi_schedule_bh(acb);
-    scsi_free_scsi_task(acb->task);
-    acb->task = NULL;
 }
 
 static int64_t sector_qemu2lun(int64_t sector, IscsiLun *iscsilun)
@@ -236,6 +247,8 @@ iscsi_aio_writev(BlockDriverState *bs, int64_t sector_num,
     acb->qiov     = qiov;
 
     acb->canceled   = 0;
+    acb->bh         = NULL;
+    acb->status     = -EINPROGRESS;
 
     /* XXX we should pass the iovec to write16 to avoid the extra copy */
     /* this will allow us to get rid of 'buf' completely */
@@ -293,9 +306,6 @@ iscsi_aio_read16_cb(struct iscsi_context *iscsi, int status,
     trace_iscsi_aio_read16_cb(iscsi, status, acb, acb->canceled);
 
     if (acb->canceled != 0) {
-        qemu_aio_release(acb);
-        scsi_free_scsi_task(acb->task);
-        acb->task = NULL;
         return;
     }
 
@@ -307,8 +317,6 @@ iscsi_aio_read16_cb(struct iscsi_context *iscsi, int status,
     }
 
     iscsi_schedule_bh(acb);
-    scsi_free_scsi_task(acb->task);
-    acb->task = NULL;
 }
 
 static BlockDriverAIOCB *
@@ -334,6 +342,8 @@ iscsi_aio_readv(BlockDriverState *bs, int64_t sector_num,
     acb->qiov     = qiov;
 
     acb->canceled    = 0;
+    acb->bh          = NULL;
+    acb->status      = -EINPROGRESS;
     acb->read_size   = qemu_read_size;
     acb->buf         = NULL;
 
@@ -409,9 +419,6 @@ iscsi_synccache10_cb(struct iscsi_context *iscsi, int status,
     IscsiAIOCB *acb = opaque;
 
     if (acb->canceled != 0) {
-        qemu_aio_release(acb);
-        scsi_free_scsi_task(acb->task);
-        acb->task = NULL;
         return;
     }
 
@@ -423,8 +430,6 @@ iscsi_synccache10_cb(struct iscsi_context *iscsi, int status,
     }
 
     iscsi_schedule_bh(acb);
-    scsi_free_scsi_task(acb->task);
-    acb->task = NULL;
 }
 
 static BlockDriverAIOCB *
@@ -439,6 +444,8 @@ iscsi_aio_flush(BlockDriverState *bs,
 
     acb->iscsilun = iscsilun;
     acb->canceled   = 0;
+    acb->bh         = NULL;
+    acb->status     = -EINPROGRESS;
 
     acb->task = iscsi_synchronizecache10_task(iscsi, iscsilun->lun,
                                          0, 0, 0, 0,
@@ -463,9 +470,6 @@ iscsi_unmap_cb(struct iscsi_context *iscsi, int status,
     IscsiAIOCB *acb = opaque;
 
     if (acb->canceled != 0) {
-        qemu_aio_release(acb);
-        scsi_free_scsi_task(acb->task);
-        acb->task = NULL;
         return;
     }
 
@@ -477,8 +481,6 @@ iscsi_unmap_cb(struct iscsi_context *iscsi, int status,
     }
 
     iscsi_schedule_bh(acb);
-    scsi_free_scsi_task(acb->task);
-    acb->task = NULL;
 }
 
 static BlockDriverAIOCB *
@@ -495,6 +497,8 @@ iscsi_aio_discard(BlockDriverState *bs,
 
     acb->iscsilun = iscsilun;
     acb->canceled   = 0;
+    acb->bh         = NULL;
+    acb->status     = -EINPROGRESS;
 
     list[0].lba = sector_qemu2lun(sector_num, iscsilun);
     list[0].num = nb_sectors * BDRV_SECTOR_SIZE / iscsilun->block_size;
@@ -523,9 +527,6 @@ iscsi_aio_ioctl_cb(struct iscsi_context *iscsi, int status,
     IscsiAIOCB *acb = opaque;
 
     if (acb->canceled != 0) {
-        qemu_aio_release(acb);
-        scsi_free_scsi_task(acb->task);
-        acb->task = NULL;
         return;
     }
 
@@ -554,8 +555,6 @@ iscsi_aio_ioctl_cb(struct iscsi_context *iscsi, int status,
     }
 
     iscsi_schedule_bh(acb);
-    scsi_free_scsi_task(acb->task);
-    acb->task = NULL;
 }
 
 static BlockDriverAIOCB *iscsi_aio_ioctl(BlockDriverState *bs,
@@ -573,6 +572,8 @@ static BlockDriverAIOCB *iscsi_aio_ioctl(BlockDriverState *bs,
 
     acb->iscsilun = iscsilun;
     acb->canceled    = 0;
+    acb->bh          = NULL;
+    acb->status      = -EINPROGRESS;
     acb->buf         = NULL;
     acb->ioh         = buf;
 
commit cfb3f5064af2d2e29c976e292c9472dfe9d61e31
Author: Paolo Bonzini <pbonzini at redhat.com>
Date:   Sat Aug 18 23:38:03 2012 +0200

    iscsi: simplify iscsi_schedule_bh
    
    It is always used with the same callback, remove the argument.  And
    its return value is never used, assume allocation succeeds.
    
    Signed-off-by: Paolo Bonzini <pbonzini at redhat.com>

diff --git a/block/iscsi.c b/block/iscsi.c
index 600e334..7b09795 100644
--- a/block/iscsi.c
+++ b/block/iscsi.c
@@ -73,7 +73,7 @@ struct IscsiTask {
 };
 
 static void
-iscsi_readv_writev_bh_cb(void *p)
+iscsi_bh_cb(void *p)
 {
     IscsiAIOCB *acb = p;
 
@@ -86,17 +86,11 @@ iscsi_readv_writev_bh_cb(void *p)
     qemu_aio_release(acb);
 }
 
-static int
-iscsi_schedule_bh(QEMUBHFunc *cb, IscsiAIOCB *acb)
+static void
+iscsi_schedule_bh(IscsiAIOCB *acb)
 {
-    acb->bh = qemu_bh_new(cb, acb);
-    if (!acb->bh) {
-        error_report("oom: could not create iscsi bh");
-        return -EIO;
-    }
-
+    acb->bh = qemu_bh_new(iscsi_bh_cb, acb);
     qemu_bh_schedule(acb->bh);
-    return 0;
 }
 
 
@@ -211,7 +205,7 @@ iscsi_aio_write16_cb(struct iscsi_context *iscsi, int status,
         acb->status = -EIO;
     }
 
-    iscsi_schedule_bh(iscsi_readv_writev_bh_cb, acb);
+    iscsi_schedule_bh(acb);
     scsi_free_scsi_task(acb->task);
     acb->task = NULL;
 }
@@ -312,7 +306,7 @@ iscsi_aio_read16_cb(struct iscsi_context *iscsi, int status,
         acb->status = -EIO;
     }
 
-    iscsi_schedule_bh(iscsi_readv_writev_bh_cb, acb);
+    iscsi_schedule_bh(acb);
     scsi_free_scsi_task(acb->task);
     acb->task = NULL;
 }
@@ -428,7 +422,7 @@ iscsi_synccache10_cb(struct iscsi_context *iscsi, int status,
         acb->status = -EIO;
     }
 
-    iscsi_schedule_bh(iscsi_readv_writev_bh_cb, acb);
+    iscsi_schedule_bh(acb);
     scsi_free_scsi_task(acb->task);
     acb->task = NULL;
 }
@@ -482,7 +476,7 @@ iscsi_unmap_cb(struct iscsi_context *iscsi, int status,
         acb->status = -EIO;
     }
 
-    iscsi_schedule_bh(iscsi_readv_writev_bh_cb, acb);
+    iscsi_schedule_bh(acb);
     scsi_free_scsi_task(acb->task);
     acb->task = NULL;
 }
@@ -559,7 +553,7 @@ iscsi_aio_ioctl_cb(struct iscsi_context *iscsi, int status,
         memcpy(acb->ioh->sbp, &acb->task->datain.data[2], ss);
     }
 
-    iscsi_schedule_bh(iscsi_readv_writev_bh_cb, acb);
+    iscsi_schedule_bh(acb);
     scsi_free_scsi_task(acb->task);
     acb->task = NULL;
 }
commit 27cbd828c617944c0f9603763fdf4fa87e7ad923
Author: Paolo Bonzini <pbonzini at redhat.com>
Date:   Sat Aug 18 23:37:31 2012 +0200

    iscsi: move iscsi_schedule_bh and iscsi_readv_writev_bh_cb
    
    Put these functions at the beginning, to avoid forward references
    in the next patches.
    
    Signed-off-by: Paolo Bonzini <pbonzini at redhat.com>

diff --git a/block/iscsi.c b/block/iscsi.c
index 219f927..600e334 100644
--- a/block/iscsi.c
+++ b/block/iscsi.c
@@ -73,6 +73,34 @@ struct IscsiTask {
 };
 
 static void
+iscsi_readv_writev_bh_cb(void *p)
+{
+    IscsiAIOCB *acb = p;
+
+    qemu_bh_delete(acb->bh);
+
+    if (acb->canceled == 0) {
+        acb->common.cb(acb->common.opaque, acb->status);
+    }
+
+    qemu_aio_release(acb);
+}
+
+static int
+iscsi_schedule_bh(QEMUBHFunc *cb, IscsiAIOCB *acb)
+{
+    acb->bh = qemu_bh_new(cb, acb);
+    if (!acb->bh) {
+        error_report("oom: could not create iscsi bh");
+        return -EIO;
+    }
+
+    qemu_bh_schedule(acb->bh);
+    return 0;
+}
+
+
+static void
 iscsi_abort_task_cb(struct iscsi_context *iscsi, int status, void *command_data,
                     void *private_data)
 {
@@ -159,34 +187,6 @@ iscsi_process_write(void *arg)
 }
 
 
-static int
-iscsi_schedule_bh(QEMUBHFunc *cb, IscsiAIOCB *acb)
-{
-    acb->bh = qemu_bh_new(cb, acb);
-    if (!acb->bh) {
-        error_report("oom: could not create iscsi bh");
-        return -EIO;
-    }
-
-    qemu_bh_schedule(acb->bh);
-    return 0;
-}
-
-static void
-iscsi_readv_writev_bh_cb(void *p)
-{
-    IscsiAIOCB *acb = p;
-
-    qemu_bh_delete(acb->bh);
-
-    if (acb->canceled == 0) {
-        acb->common.cb(acb->common.opaque, acb->status);
-    }
-
-    qemu_aio_release(acb);
-}
-
-
 static void
 iscsi_aio_write16_cb(struct iscsi_context *iscsi, int status,
                      void *command_data, void *opaque)
commit b20909195745c34a819aed14ae996b60ab0f591f
Author: Paolo Bonzini <pbonzini at redhat.com>
Date:   Sun Aug 19 00:12:39 2012 +0200

    Revert "iscsi: Fix NULL dereferences / races between task completion and abort"
    
    This reverts commit 64e69e80920d82df3fa679bc41b13770d2f99360.  The commit
    returned immediately from iscsi_aio_cancel, risking corruption in case the
    following happens:
    
        guest                  qemu                 target
      =========================================================================
        send write 1 -------->
                               send write 1 -------->
        cancel write 1 ------>
                               cancel write 1 ------>
           <------------------ cancellation processed
        send write 2 -------->
                               send write 2 -------->
                                   <---------------- completed write 2
           <------------------ completed write 2
                                   <---------------- completed write 1
                                   <---------------- cancellation not done
    
    Here, the guest would see write 2 superseding write 1, when in fact the
    outcome could have been the opposite.  The right behavior is to return
    only after the target says whether the cancellation was done or not, and
    it will be implemented by the next three patches.
    
    Signed-off-by: Paolo Bonzini <pbonzini at redhat.com>

diff --git a/block/iscsi.c b/block/iscsi.c
index bb9cf82..219f927 100644
--- a/block/iscsi.c
+++ b/block/iscsi.c
@@ -76,10 +76,6 @@ static void
 iscsi_abort_task_cb(struct iscsi_context *iscsi, int status, void *command_data,
                     void *private_data)
 {
-    IscsiAIOCB *acb = (IscsiAIOCB *)private_data;
-
-    scsi_free_scsi_task(acb->task);
-    acb->task = NULL;
 }
 
 static void
@@ -88,15 +84,15 @@ iscsi_aio_cancel(BlockDriverAIOCB *blockacb)
     IscsiAIOCB *acb = (IscsiAIOCB *)blockacb;
     IscsiLun *iscsilun = acb->iscsilun;
 
-    acb->canceled = 1;
-
     acb->common.cb(acb->common.opaque, -ECANCELED);
+    acb->canceled = 1;
 
-    /* send a task mgmt call to the target to cancel the task on the target
-     * this also cancels the task in libiscsi
-     */
+    /* send a task mgmt call to the target to cancel the task on the target */
     iscsi_task_mgmt_abort_task_async(iscsilun->iscsi, acb->task,
-                                     iscsi_abort_task_cb, &acb);
+                                     iscsi_abort_task_cb, NULL);
+
+    /* then also cancel the task locally in libiscsi */
+    iscsi_scsi_task_cancel(iscsilun->iscsi, acb->task);
 }
 
 static AIOPool iscsi_aio_pool = {
@@ -183,18 +179,11 @@ iscsi_readv_writev_bh_cb(void *p)
 
     qemu_bh_delete(acb->bh);
 
-    if (!acb->canceled) {
+    if (acb->canceled == 0) {
         acb->common.cb(acb->common.opaque, acb->status);
     }
 
     qemu_aio_release(acb);
-
-    if (acb->canceled) {
-        return;
-    }
-
-    scsi_free_scsi_task(acb->task);
-    acb->task = NULL;
 }
 
 
@@ -208,8 +197,10 @@ iscsi_aio_write16_cb(struct iscsi_context *iscsi, int status,
 
     g_free(acb->buf);
 
-    if (acb->canceled) {
+    if (acb->canceled != 0) {
         qemu_aio_release(acb);
+        scsi_free_scsi_task(acb->task);
+        acb->task = NULL;
         return;
     }
 
@@ -221,6 +212,8 @@ iscsi_aio_write16_cb(struct iscsi_context *iscsi, int status,
     }
 
     iscsi_schedule_bh(iscsi_readv_writev_bh_cb, acb);
+    scsi_free_scsi_task(acb->task);
+    acb->task = NULL;
 }
 
 static int64_t sector_qemu2lun(int64_t sector, IscsiLun *iscsilun)
@@ -305,8 +298,10 @@ iscsi_aio_read16_cb(struct iscsi_context *iscsi, int status,
 
     trace_iscsi_aio_read16_cb(iscsi, status, acb, acb->canceled);
 
-    if (acb->canceled) {
+    if (acb->canceled != 0) {
         qemu_aio_release(acb);
+        scsi_free_scsi_task(acb->task);
+        acb->task = NULL;
         return;
     }
 
@@ -318,6 +313,8 @@ iscsi_aio_read16_cb(struct iscsi_context *iscsi, int status,
     }
 
     iscsi_schedule_bh(iscsi_readv_writev_bh_cb, acb);
+    scsi_free_scsi_task(acb->task);
+    acb->task = NULL;
 }
 
 static BlockDriverAIOCB *
@@ -417,8 +414,10 @@ iscsi_synccache10_cb(struct iscsi_context *iscsi, int status,
 {
     IscsiAIOCB *acb = opaque;
 
-    if (acb->canceled) {
+    if (acb->canceled != 0) {
         qemu_aio_release(acb);
+        scsi_free_scsi_task(acb->task);
+        acb->task = NULL;
         return;
     }
 
@@ -430,6 +429,8 @@ iscsi_synccache10_cb(struct iscsi_context *iscsi, int status,
     }
 
     iscsi_schedule_bh(iscsi_readv_writev_bh_cb, acb);
+    scsi_free_scsi_task(acb->task);
+    acb->task = NULL;
 }
 
 static BlockDriverAIOCB *
@@ -467,8 +468,10 @@ iscsi_unmap_cb(struct iscsi_context *iscsi, int status,
 {
     IscsiAIOCB *acb = opaque;
 
-    if (acb->canceled) {
+    if (acb->canceled != 0) {
         qemu_aio_release(acb);
+        scsi_free_scsi_task(acb->task);
+        acb->task = NULL;
         return;
     }
 
@@ -480,6 +483,8 @@ iscsi_unmap_cb(struct iscsi_context *iscsi, int status,
     }
 
     iscsi_schedule_bh(iscsi_readv_writev_bh_cb, acb);
+    scsi_free_scsi_task(acb->task);
+    acb->task = NULL;
 }
 
 static BlockDriverAIOCB *
@@ -523,8 +528,10 @@ iscsi_aio_ioctl_cb(struct iscsi_context *iscsi, int status,
 {
     IscsiAIOCB *acb = opaque;
 
-    if (acb->canceled) {
+    if (acb->canceled != 0) {
         qemu_aio_release(acb);
+        scsi_free_scsi_task(acb->task);
+        acb->task = NULL;
         return;
     }
 
@@ -553,6 +560,8 @@ iscsi_aio_ioctl_cb(struct iscsi_context *iscsi, int status,
     }
 
     iscsi_schedule_bh(iscsi_readv_writev_bh_cb, acb);
+    scsi_free_scsi_task(acb->task);
+    acb->task = NULL;
 }
 
 static BlockDriverAIOCB *iscsi_aio_ioctl(BlockDriverState *bs,
commit 682527c00409d676c0d3b9fac99ca3b2fdfd6d2c
Author: Blue Swirl <blauwirbel at gmail.com>
Date:   Sun Aug 19 13:39:31 2012 +0000

    Update OpenBIOS images
    
    Update OpenBIOS images to SVN r1062. Build with GCC 4.6.0
    in order to avoid boot problems introduced by GCC 4.7.[01].
    
    Signed-off-by: Blue Swirl <blauwirbel at gmail.com>

diff --git a/pc-bios/README b/pc-bios/README
index f4b37d6..fc07ebc 100644
--- a/pc-bios/README
+++ b/pc-bios/README
@@ -12,7 +12,7 @@
   1275-1994 (referred to as Open Firmware) compliant firmware.
   The included images for PowerPC (for 32 and 64 bit PPC CPUs),
   Sparc32 and Sparc64 are built from OpenBIOS SVN revision
-  1060.
+  1062.
 
 - SLOF (Slimline Open Firmware) is a free IEEE 1275 Open Firmware
   implementation for certain IBM POWER hardware.  The sources are at
diff --git a/pc-bios/openbios-ppc b/pc-bios/openbios-ppc
index aeae265..1c3753d 100644
Binary files a/pc-bios/openbios-ppc and b/pc-bios/openbios-ppc differ
diff --git a/pc-bios/openbios-sparc32 b/pc-bios/openbios-sparc32
index d90c4e5..6bd8e45 100644
Binary files a/pc-bios/openbios-sparc32 and b/pc-bios/openbios-sparc32 differ
diff --git a/pc-bios/openbios-sparc64 b/pc-bios/openbios-sparc64
index 457d264..7c06fcc 100644
Binary files a/pc-bios/openbios-sparc64 and b/pc-bios/openbios-sparc64 differ
commit e89001f72edde37fb36fa7c964daa1bbeb2eca26
Author: Markus Armbruster <armbru at redhat.com>
Date:   Wed Aug 15 13:12:20 2012 +0200

    pc: Fix RTC CMOS info on RAM for ram_size < 1MiB
    
    pc_cmos_init() always claims 640KiB base memory, and ram_size - 1MiB
    extended memory.  The latter can underflow to "lots of extended
    memory".  Fix both, and clean up some.
    
    Note: SeaBIOS currently requires 1MiB of RAM, and doesn't check
    whether it got enough.
    
    Signed-off-by: Markus Armbruster <armbru at redhat.com>
    Signed-off-by: Blue Swirl <blauwirbel at gmail.com>

diff --git a/hw/pc.c b/hw/pc.c
index 3ed1a3c..112739a 100644
--- a/hw/pc.c
+++ b/hw/pc.c
@@ -338,32 +338,37 @@ void pc_cmos_init(ram_addr_t ram_size, ram_addr_t above_4g_mem_size,
     /* various important CMOS locations needed by PC/Bochs bios */
 
     /* memory size */
-    val = 640; /* base memory in K */
+    /* base memory (first MiB) */
+    val = MIN(ram_size / 1024, 640);
     rtc_set_memory(s, 0x15, val);
     rtc_set_memory(s, 0x16, val >> 8);
-
-    val = (ram_size / 1024) - 1024;
+    /* extended memory (next 64MiB) */
+    if (ram_size > 1024 * 1024) {
+        val = (ram_size - 1024 * 1024) / 1024;
+    } else {
+        val = 0;
+    }
     if (val > 65535)
         val = 65535;
     rtc_set_memory(s, 0x17, val);
     rtc_set_memory(s, 0x18, val >> 8);
     rtc_set_memory(s, 0x30, val);
     rtc_set_memory(s, 0x31, val >> 8);
-
-    if (above_4g_mem_size) {
-        rtc_set_memory(s, 0x5b, (unsigned int)above_4g_mem_size >> 16);
-        rtc_set_memory(s, 0x5c, (unsigned int)above_4g_mem_size >> 24);
-        rtc_set_memory(s, 0x5d, (uint64_t)above_4g_mem_size >> 32);
-    }
-
-    if (ram_size > (16 * 1024 * 1024))
-        val = (ram_size / 65536) - ((16 * 1024 * 1024) / 65536);
-    else
+    /* memory between 16MiB and 4GiB */
+    if (ram_size > 16 * 1024 * 1024) {
+        val = (ram_size - 16 * 1024 * 1024) / 65536;
+    } else {
         val = 0;
+    }
     if (val > 65535)
         val = 65535;
     rtc_set_memory(s, 0x34, val);
     rtc_set_memory(s, 0x35, val >> 8);
+    /* memory above 4GiB */
+    val = above_4g_mem_size / 65536;
+    rtc_set_memory(s, 0x5b, val);
+    rtc_set_memory(s, 0x5c, val >> 8);
+    rtc_set_memory(s, 0x5d, val >> 16);
 
     /* set the number of CPU */
     rtc_set_memory(s, 0x5f, smp_cpus - 1);
commit ff961015529437f4b83fca0a92069aebcf533c9c
Author: Markus Armbruster <armbru at redhat.com>
Date:   Wed Aug 15 13:12:19 2012 +0200

    vl: Round argument of -m up to multiple of 8KiB
    
    Partial pages make little sense and don't work.  Ensure the RAM size
    is a multiple of any possible target's page size.
    
    Fixes
    
        $ qemu-system-x86_64 -nodefaults -S -vnc :0 -m 0.8
        qemu-system-x86_64: /work/armbru/qemu/exec.c:2255: register_subpage: Assertion `existing->mr->subpage || existing->mr == &io_mem_unassigned' failed.
    
    Signed-off-by: Markus Armbruster <armbru at redhat.com>
    Signed-off-by: Blue Swirl <blauwirbel at gmail.com>

diff --git a/vl.c b/vl.c
index 67f5813..7c577fa 100644
--- a/vl.c
+++ b/vl.c
@@ -2735,6 +2735,7 @@ int main(int argc, char **argv, char **envp)
                 break;
             case QEMU_OPTION_m: {
                 int64_t value;
+                uint64_t sz;
                 char *end;
 
                 value = strtosz(optarg, &end);
@@ -2742,12 +2743,12 @@ int main(int argc, char **argv, char **envp)
                     fprintf(stderr, "qemu: invalid ram size: %s\n", optarg);
                     exit(1);
                 }
-
-                if (value != (uint64_t)(ram_addr_t)value) {
+                sz = QEMU_ALIGN_UP((uint64_t)value, 8192);
+                ram_size = sz;
+                if (ram_size != sz) {
                     fprintf(stderr, "qemu: ram size too large\n");
                     exit(1);
                 }
-                ram_size = value;
                 break;
             }
             case QEMU_OPTION_mempath:
commit d83c951cce14dd3c7600c386d3791c4993744622
Author: Gerd Hoffmann <kraxel at redhat.com>
Date:   Mon Aug 13 13:05:44 2012 +0200

    scsi: fix warning
    
    hw/scsi-bus.c:758: warning: ‘xfer’ may be used uninitialized in this
    function
    
    Isn't true, but older gcc versions (for example 4.1 as shipped in rhel5)
    are not clever enougth to figure, so sprinkle in a default: line to make
    them happy.
    
    Signed-off-by: Gerd Hoffmann <kraxel at redhat.com>
    Signed-off-by: Blue Swirl <blauwirbel at gmail.com>

diff --git a/hw/scsi-bus.c b/hw/scsi-bus.c
index b8a857d..4981a02 100644
--- a/hw/scsi-bus.c
+++ b/hw/scsi-bus.c
@@ -761,6 +761,7 @@ static int ata_passthrough_12_xfer_size(SCSIDevice *dev, uint8_t *buf)
     switch (length) {
     case 0:
     case 3: /* USB-specific.  */
+    default:
         xfer = 0;
         break;
     case 1:
@@ -784,6 +785,7 @@ static int ata_passthrough_16_xfer_size(SCSIDevice *dev, uint8_t *buf)
     switch (length) {
     case 0:
     case 3: /* USB-specific.  */
+    default:
         xfer = 0;
         break;
     case 1:
commit 5f893b4e9c207c5a38cf7b141d2c54fa30046afd
Author: Gerd Hoffmann <kraxel at redhat.com>
Date:   Mon Aug 13 13:05:43 2012 +0200

    Avoid asprintf() which is not available on mingw
    
    Use g_strdup_printf() instead.
    
    Signed-off-by: Gerd Hoffmann <kraxel at redhat.com>
    Reviewed-by: Stefan Weil <sw at weilnetz.de>
    Signed-off-by: Blue Swirl <blauwirbel at gmail.com>

diff --git a/hw/msix.c b/hw/msix.c
index 800fc32..aea340b 100644
--- a/hw/msix.c
+++ b/hw/msix.c
@@ -307,13 +307,9 @@ int msix_init_exclusive_bar(PCIDevice *dev, unsigned short nentries,
         return -EINVAL;
     }
 
-    if (asprintf(&name, "%s-msix", dev->name) == -1) {
-        return -ENOMEM;
-    }
-
+    name = g_strdup_printf("%s-msix", dev->name);
     memory_region_init(&dev->msix_exclusive_bar, name, MSIX_EXCLUSIVE_BAR_SIZE);
-
-    free(name);
+    g_free(name);
 
     ret = msix_init(dev, nentries, &dev->msix_exclusive_bar, bar_nr,
                     MSIX_EXCLUSIVE_BAR_TABLE_OFFSET, &dev->msix_exclusive_bar,
commit eec7f96c2cac88f59fd8c79b78a6e027df4abfb2
Author: Stefan Hajnoczi <stefanha at linux.vnet.ibm.com>
Date:   Thu Aug 16 09:57:49 2012 +0100

    virtio-blk: hide VIRTIO_BLK_F_CONFIG_WCE from old machine types
    
    QEMU has a policy of keeping a stable guest device ABI.  When new guest device
    features are introduced they must not change hardware info seen by existing
    guests.  This is important because operating systems or applications may
    "fingerprint" the hardware and refuse to run when the hardware changes.  To
    always get the latest guest device ABI, run with x86 machine type "pc".
    
    This patch hides the new VIRTIO_BLK_F_CONFIG_WCE virtio feature bit from
    existing machine types.  Only pc-1.2 and later will expose this feature
    by default.
    
    For more info on the VIRTIO_BLK_F_CONFIG_WCE feature bit, see:
    
      commit 13e3dce068773c971ff2f19d986378c55897c4a3
      Author: Paolo Bonzini <pbonzini at redhat.com>
      Date:   Thu Aug 9 16:07:19 2012 +0200
    
          virtio-blk: support VIRTIO_BLK_F_CONFIG_WCE
    
          Also rename VIRTIO_BLK_F_WCACHE to VIRTIO_BLK_F_WCE for consistency with
          the spec.
    
          Signed-off-by: Paolo Bonzini <pbonzini at redhat.com>
          Signed-off-by: Kevin Wolf <kwolf at redhat.com>
    
    Anthony Liguori <aliguori at us.ibm.com> reported:
    
      This broke qemu-test because it changed the pc-1.0 machine type:
    
      Setting guest RANDOM seed to 47167
      *** Running tests ***
      Running test /tests/finger-print.sh...		OK
      --- fingerprints/pc-1.0.x86_64	2011-12-18 13:08:40.000000000 -0600
      +++ fingerprint.txt	2012-08-12 13:30:48.000000000 -0500
      @@ -55,7 +55,7 @@
       /sys/bus/pci/devices/0000:00:06.0/subsystem_device=0x0002
       /sys/bus/pci/devices/0000:00:06.0/class=0x010000
       /sys/bus/pci/devices/0000:00:06.0/revision=0x00
      -/sys/bus/pci/devices/0000:00:06.0/virtio/host-features=0x710006d4
      +/sys/bus/pci/devices/0000:00:06.0/virtio/host-features=0x71000ed4
       /sys/class/dmi/id/bios_vendor=Bochs
       /sys/class/dmi/id/bios_date=01/01/2007
       /sys/class/dmi/id/bios_version=Bochs
      Guest fingerprint changed for pc-1.0!
    
    Reported-by: Anthony Liguori <aliguori at us.ibm.com>
    Signed-off-by: Stefan Hajnoczi <stefanha at linux.vnet.ibm.com>
    Signed-off-by: Kevin Wolf <kwolf at redhat.com>

diff --git a/hw/pc_piix.c b/hw/pc_piix.c
index 0c0096f..d68dbb2 100644
--- a/hw/pc_piix.c
+++ b/hw/pc_piix.c
@@ -375,6 +375,10 @@ static QEMUMachine pc_machine_v1_2 = {
             .driver   = "qxl",\
             .property = "vgamem_mb",\
             .value    = stringify(8),\
+        },{\
+            .driver   = "virtio-blk-pci",\
+            .property = "config-wce",\
+            .value    = "off",\
         }
 
 static QEMUMachine pc_machine_v1_1 = {
diff --git a/hw/virtio-blk.c b/hw/virtio-blk.c
index fd8fa90..0bc2b5e 100644
--- a/hw/virtio-blk.c
+++ b/hw/virtio-blk.c
@@ -533,7 +533,9 @@ static uint32_t virtio_blk_get_features(VirtIODevice *vdev, uint32_t features)
     features |= (1 << VIRTIO_BLK_F_BLK_SIZE);
     features |= (1 << VIRTIO_BLK_F_SCSI);
 
-    features |= (1 << VIRTIO_BLK_F_CONFIG_WCE);
+    if (s->blk->config_wce) {
+        features |= (1 << VIRTIO_BLK_F_CONFIG_WCE);
+    }
     if (bdrv_enable_write_cache(s->bs))
         features |= (1 << VIRTIO_BLK_F_WCE);
 
diff --git a/hw/virtio-blk.h b/hw/virtio-blk.h
index 35834cf..454f445 100644
--- a/hw/virtio-blk.h
+++ b/hw/virtio-blk.h
@@ -104,6 +104,7 @@ struct VirtIOBlkConf
     BlockConf conf;
     char *serial;
     uint32_t scsi;
+    uint32_t config_wce;
 };
 
 #define DEFINE_VIRTIO_BLK_FEATURES(_state, _field) \
diff --git a/hw/virtio-pci.c b/hw/virtio-pci.c
index 5e6e09e..2a3d86f 100644
--- a/hw/virtio-pci.c
+++ b/hw/virtio-pci.c
@@ -886,6 +886,7 @@ static Property virtio_blk_properties[] = {
 #ifdef __linux__
     DEFINE_PROP_BIT("scsi", VirtIOPCIProxy, blk.scsi, 0, true),
 #endif
+    DEFINE_PROP_BIT("config-wce", VirtIOPCIProxy, blk.config_wce, 0, true),
     DEFINE_PROP_BIT("ioeventfd", VirtIOPCIProxy, flags, VIRTIO_PCI_FLAG_USE_IOEVENTFD_BIT, true),
     DEFINE_PROP_UINT32("vectors", VirtIOPCIProxy, nvectors, 2),
     DEFINE_VIRTIO_BLK_FEATURES(VirtIOPCIProxy, host_features),
commit 48467328c6dccc9c7be6628ed0ef0810f83be2a9
Author: Kevin Wolf <kwolf at redhat.com>
Date:   Thu Aug 16 10:56:35 2012 +0200

    Documentation: Warn against qemu-img on active image
    
    People have repeatedly expected that you can do things like snapshotting
    an image with qemu-img while a qemu instance is running. Maybe we need
    to consider locking the files while they are in use, but having a
    warning in the qemu-img manpage is doable for 1.2 and can't hurt anyway.
    
    Signed-off-by: Kevin Wolf <kwolf at redhat.com>

diff --git a/qemu-img.texi b/qemu-img.texi
index 77c6d0b..6b42e35 100644
--- a/qemu-img.texi
+++ b/qemu-img.texi
@@ -4,6 +4,16 @@ usage: qemu-img command [command options]
 @c man end
 @end example
 
+ at c man begin DESCRIPTION
+qemu-img allows you to create, convert and modify images offline. It can handle
+all image formats supported by QEMU.
+
+ at b{Warning:} Never use qemu-img to modify images in use by a running virtual
+machine or any other process; this may destroy the image. Also, be aware that
+querying an image that is being modified by another process may encounter
+inconsistent state.
+ at c man end
+
 @c man begin OPTIONS
 
 The following commands are supported:
commit 65bd155c7356d448ffee7f89149c4d473076b0ba
Author: Kevin Wolf <kwolf at redhat.com>
Date:   Thu Aug 16 10:39:33 2012 +0200

    vmdk: Read footer for streamOptimized images
    
    The footer takes precedence over the header when it exists. It contains
    the real grain directory offset that is missing in the header. Without
    this patch, streamOptimized images with a footer cannot be read.
    
    Signed-off-by: Kevin Wolf <kwolf at redhat.com>
    Reviewed-by: Stefan Hajnoczi <stefanha at linux.vnet.ibm.com>
    Reviewed-by: Jeff Cody <jcody at redhat.com>

diff --git a/block/vmdk.c b/block/vmdk.c
index 9648398..bba4c61 100644
--- a/block/vmdk.c
+++ b/block/vmdk.c
@@ -35,6 +35,7 @@
 #define VMDK4_FLAG_RGD (1 << 1)
 #define VMDK4_FLAG_COMPRESS (1 << 16)
 #define VMDK4_FLAG_MARKER (1 << 17)
+#define VMDK4_GD_AT_END 0xffffffffffffffffULL
 
 typedef struct {
     uint32_t version;
@@ -115,6 +116,13 @@ typedef struct VmdkGrainMarker {
     uint8_t  data[0];
 } VmdkGrainMarker;
 
+enum {
+    MARKER_END_OF_STREAM    = 0,
+    MARKER_GRAIN_TABLE      = 1,
+    MARKER_GRAIN_DIRECTORY  = 2,
+    MARKER_FOOTER           = 3,
+};
+
 static int vmdk_probe(const uint8_t *buf, int buf_size, const char *filename)
 {
     uint32_t magic;
@@ -451,6 +459,54 @@ static int vmdk_open_vmdk4(BlockDriverState *bs,
     if (header.capacity == 0 && header.desc_offset) {
         return vmdk_open_desc_file(bs, flags, header.desc_offset << 9);
     }
+
+    if (le64_to_cpu(header.gd_offset) == VMDK4_GD_AT_END) {
+        /*
+         * The footer takes precedence over the header, so read it in. The
+         * footer starts at offset -1024 from the end: One sector for the
+         * footer, and another one for the end-of-stream marker.
+         */
+        struct {
+            struct {
+                uint64_t val;
+                uint32_t size;
+                uint32_t type;
+                uint8_t pad[512 - 16];
+            } QEMU_PACKED footer_marker;
+
+            uint32_t magic;
+            VMDK4Header header;
+            uint8_t pad[512 - 4 - sizeof(VMDK4Header)];
+
+            struct {
+                uint64_t val;
+                uint32_t size;
+                uint32_t type;
+                uint8_t pad[512 - 16];
+            } QEMU_PACKED eos_marker;
+        } QEMU_PACKED footer;
+
+        ret = bdrv_pread(file,
+            bs->file->total_sectors * 512 - 1536,
+            &footer, sizeof(footer));
+        if (ret < 0) {
+            return ret;
+        }
+
+        /* Some sanity checks for the footer */
+        if (be32_to_cpu(footer.magic) != VMDK4_MAGIC ||
+            le32_to_cpu(footer.footer_marker.size) != 0  ||
+            le32_to_cpu(footer.footer_marker.type) != MARKER_FOOTER ||
+            le64_to_cpu(footer.eos_marker.val) != 0  ||
+            le32_to_cpu(footer.eos_marker.size) != 0  ||
+            le32_to_cpu(footer.eos_marker.type) != MARKER_END_OF_STREAM)
+        {
+            return -EINVAL;
+        }
+
+        header = footer.header;
+    }
+
     l1_entry_sectors = le32_to_cpu(header.num_gtes_per_gte)
                         * le64_to_cpu(header.granularity);
     if (l1_entry_sectors == 0) {
commit 7a736bfa4e0a58087054cad68a1d4b3804bbb708
Author: Kevin Wolf <kwolf at redhat.com>
Date:   Thu Aug 16 10:34:10 2012 +0200

    vmdk: Fix header structure
    
    Commit bb45ded9 swapped gd_offset and rgd_offset. This is wrong.
    
    Signed-off-by: Kevin Wolf <kwolf at redhat.com>

diff --git a/block/vmdk.c b/block/vmdk.c
index daee426..9648398 100644
--- a/block/vmdk.c
+++ b/block/vmdk.c
@@ -57,8 +57,8 @@ typedef struct {
     int64_t desc_offset;
     int64_t desc_size;
     int32_t num_gtes_per_gte;
-    int64_t gd_offset;
     int64_t rgd_offset;
+    int64_t gd_offset;
     int64_t grain_offset;
     char filler[1];
     char check_bytes[4];
commit 731dc9ecd4f2c3041538f7eb2d10eee0cb82da1b
Author: Anthony Liguori <aliguori at us.ibm.com>
Date:   Thu Aug 16 13:56:34 2012 -0500

    Update version to 1.2.0-rc0
    
    Signed-off-by: Anthony Liguori <aliguori at us.ibm.com>

diff --git a/VERSION b/VERSION
index da44c7f..69658cd 100644
--- a/VERSION
+++ b/VERSION
@@ -1 +1 @@
-1.1.50
+1.1.90
commit c3767ed0eb5d0bb25fe409ae5dec06e3411ff1b6
Author: Lei Li <lilei at linux.vnet.ibm.com>
Date:   Thu Jul 19 22:09:22 2012 +0800

    qemu-char: (Re-)connect for tcp_chr_write() unconnected writing
    
    tcp_chr_write() did not deal with writing to an unconnected
    connection and return the original length of the data, it's
    not right and would cause false writing. So (re-)connect it
    and return 0 for this situation.
    
    Reviewed-by: Anthony Liguori <aliguori at us.ibm.com>
    Signed-off-by: Lei Li <lilei at linux.vnet.ibm.com>
    Signed-off-by: Anthony Liguori <aliguori at us.ibm.com>

diff --git a/qemu-char.c b/qemu-char.c
index 10d1504..398baf1 100644
--- a/qemu-char.c
+++ b/qemu-char.c
@@ -2141,14 +2141,17 @@ typedef struct {
 
 static void tcp_chr_accept(void *opaque);
 
+static void tcp_chr_connect(void *opaque);
+
 static int tcp_chr_write(CharDriverState *chr, const uint8_t *buf, int len)
 {
     TCPCharDriver *s = chr->opaque;
     if (s->connected) {
         return send_all(s->fd, buf, len);
     } else {
-        /* XXX: indicate an error ? */
-        return len;
+        /* (Re-)connect for unconnected writing */
+        tcp_chr_connect(chr);
+        return 0;
     }
 }
 
commit be52202902d166e914d426c8e3d8976b25121b4d
Author: David Gibson <david at gibson.dropbear.id.au>
Date:   Tue Aug 7 16:41:51 2012 +1000

    Allow QEMUMachine to override reset sequencing
    
    qemu_system_reset() function always performs the same basic actions on
    all machines.  This includes running all the reset handler hooks,
    however the order in which these will run is not always easily predictable.
    
    This patch splits the core of qemu_system_reset() - the invocation of
    the reset handlers - out into a new qemu_devices_reset() function.
    qemu_system_reset() will usually call qemu_devices_reset(), but that
    can be now overriden by a new reset method in the QEMUMachine
    structure.
    
    Individual machines can use this reset method, if necessary, to
    perform any extra, machine specific initializations which have to
    occur before or after the bulk of the reset handlers.  It's expected
    that the method will call qemu_devices_reset() at some point, but if
    the machine has really strange ordering requirements between devices
    resets it could even override that with it's own reset sequence (with
    great care, obviously).
    
    For a specific example of when this might be needed: a number of
    machines (but not PC) load images specified with -kernel or -initrd
    directly into the machine RAM before booting the guest.  This mostly
    works at the moment, but to make this actually safe requires that this
    load occurs after peripheral devices are reset - otherwise they could
    have active DMAs in progress which would clobber the in memory images.
    Some machines (notably pseries) also have other entry conditions which
    need to be set up as the last thing before executing in guest space -
    some of this could be considered "emulated firmware" in the sense that
    the actions of the firmware are emulated directly by qemu rather than
    by executing a firmware image within the guest.  When the platform's
    firmware to OS interface is sufficiently well specified, this saves
    time both in implementing the "firmware" and executing it.
    
    aliguori: don't unconditionally dereference current_machine
    
    Reviewed-by: Andreas Färber <afaerber at suse.de>
    Signed-off-by: David Gibson <david at gibson.dropbear.id.au>
    Signed-off-by: Anthony Liguori <aliguori at us.ibm.com>

diff --git a/hw/boards.h b/hw/boards.h
index 59c01d0..a2e0a54 100644
--- a/hw/boards.h
+++ b/hw/boards.h
@@ -12,11 +12,14 @@ typedef void QEMUMachineInitFunc(ram_addr_t ram_size,
                                  const char *initrd_filename,
                                  const char *cpu_model);
 
+typedef void QEMUMachineResetFunc(void);
+
 typedef struct QEMUMachine {
     const char *name;
     const char *alias;
     const char *desc;
     QEMUMachineInitFunc *init;
+    QEMUMachineResetFunc *reset;
     int use_scsi;
     int max_cpus;
     unsigned int no_serial:1,
diff --git a/sysemu.h b/sysemu.h
index 4669348..65552ac 100644
--- a/sysemu.h
+++ b/sysemu.h
@@ -62,6 +62,7 @@ int qemu_powerdown_requested(void);
 void qemu_system_killed(int signal, pid_t pid);
 void qemu_kill_report(void);
 extern qemu_irq qemu_system_powerdown;
+void qemu_devices_reset(void);
 void qemu_system_reset(bool report);
 
 void qemu_add_exit_notifier(Notifier *notify);
diff --git a/vl.c b/vl.c
index 124d30d..67f5813 100644
--- a/vl.c
+++ b/vl.c
@@ -1464,7 +1464,7 @@ void qemu_unregister_reset(QEMUResetHandler *func, void *opaque)
     }
 }
 
-void qemu_system_reset(bool report)
+void qemu_devices_reset(void)
 {
     QEMUResetEntry *re, *nre;
 
@@ -1472,6 +1472,15 @@ void qemu_system_reset(bool report)
     QTAILQ_FOREACH_SAFE(re, &reset_handlers, entry, nre) {
         re->func(re->opaque);
     }
+}
+
+void qemu_system_reset(bool report)
+{
+    if (current_machine && current_machine->reset) {
+        current_machine->reset();
+    } else {
+        qemu_devices_reset();
+    }
     if (report) {
         monitor_protocol_event(QEVENT_RESET, NULL);
     }
commit 35139a590c4e2f3086d069028bda77f1de1d46b0
Author: David Gibson <david at gibson.dropbear.id.au>
Date:   Thu Aug 16 12:03:56 2012 +1000

    pseries: Instantiate USB interface when required
    
    The pseries machine already supports the -vga std option, creating a
    graphics adapter.  However, this is not very useful without being able to
    add a keyboard and mouse as well.  This patch addresses this by adding
    a USB interface when requested, and automatically adding a USB keyboard
    and mouse when VGA is enabled.
    
    This is a stop gap measure to get usable graphics mode on pseries while
    waiting for Li Zhang's rework of USB options to go in after 1.2.
    
    Signed-off-by: David Gibson <david at gibson.dropbear.id.au>
    Signed-off-by: Anthony Liguori <aliguori at us.ibm.com>

diff --git a/hw/spapr.c b/hw/spapr.c
index 5178721..be533ee 100644
--- a/hw/spapr.c
+++ b/hw/spapr.c
@@ -49,6 +49,7 @@
 #include "vga-pci.h"
 
 #include "exec-memory.h"
+#include "hw/usb.h"
 
 #include <libfdt.h>
 
@@ -765,6 +766,15 @@ static void ppc_spapr_init(ram_addr_t ram_size,
         spapr->has_graphics = true;
     }
 
+    if (usb_enabled) {
+        pci_create_simple(QLIST_FIRST(&spapr->phbs)->host_state.bus,
+                          -1, "pci-ohci");
+        if (spapr->has_graphics) {
+            usbdevice_create("keyboard");
+            usbdevice_create("mouse");
+        }
+    }
+
     if (rma_size < (MIN_RMA_SLOF << 20)) {
         fprintf(stderr, "qemu: pSeries SLOF firmware requires >= "
                 "%ldM guest RMA (Real Mode Area memory)\n", MIN_RMA_SLOF);
commit d973ba18ced6e9440131c55b0f07e97bdbbc6703
Author: Peter Maydell <peter.maydell at linaro.org>
Date:   Thu Aug 16 12:15:18 2012 +0100

    osdep: Fix compilation failure on BSD systems
    
    Fix compilation failure on BSD systems (which don't have
    O_DIRECT or O_NOATIME:
    osdep.c:116: error: ‘O_DIRECT’ undeclared (first use in this function)
    osdep.c:116: error: (Each undeclared identifier is reported only once
    osdep.c:116: error: for each function it appears in.)
    osdep.c:116: error: ‘O_NOATIME’ undeclared (first use in this function)
    
    Reviewed-by: Stefan Weil <sw at weilnetz.de>
    Signed-off-by: Peter Maydell <peter.maydell at linaro.org>
    Signed-off-by: Anthony Liguori <aliguori at us.ibm.com>

diff --git a/osdep.c b/osdep.c
index 5b78cee..3b25297 100644
--- a/osdep.c
+++ b/osdep.c
@@ -113,7 +113,13 @@ static int qemu_dup_flags(int fd, int flags)
     }
 
     /* Set/unset flags that we can with fcntl */
-    setfl_flags = O_APPEND | O_ASYNC | O_DIRECT | O_NOATIME | O_NONBLOCK;
+    setfl_flags = O_APPEND | O_ASYNC | O_NONBLOCK;
+#ifdef O_NOATIME
+    setfl_flags |= O_NOATIME;
+#endif
+#ifdef O_DIRECT
+    setfl_flags |= O_DIRECT;
+#endif
     dup_flags &= ~setfl_flags;
     dup_flags |= (flags & setfl_flags);
     if (fcntl(ret, F_SETFL, dup_flags) == -1) {
commit 7d76ad4fa4405bb20c35fd24c3c848d2bc48f694
Author: Eduardo Otubo <otubo at linux.vnet.ibm.com>
Date:   Tue Aug 14 18:44:08 2012 -0300

    Command line support for seccomp with -sandbox (v8)
    
    Signed-off-by: Eduardo Otubo <otubo at linux.vnet.ibm.com>
    Signed-off-by: Anthony Liguori <aliguori at us.ibm.com>
    ---
    v7 -> v8
     - Parse options correctly (aliguori)

diff --git a/qemu-config.c b/qemu-config.c
index 6700de0..c05ffbc 100644
--- a/qemu-config.c
+++ b/qemu-config.c
@@ -362,6 +362,19 @@ static QemuOptsList qemu_global_opts = {
     },
 };
 
+QemuOptsList qemu_sandbox_opts = {
+    .name = "sandbox",
+    .implied_opt_name = "enable",
+    .head = QTAILQ_HEAD_INITIALIZER(qemu_sandbox_opts.head),
+    .desc = {
+        {
+            .name = "enable",
+            .type = QEMU_OPT_BOOL,
+        },
+        { /* end of list */ }
+    },
+};
+
 static QemuOptsList qemu_mon_opts = {
     .name = "mon",
     .implied_opt_name = "chardev",
@@ -645,6 +658,7 @@ static QemuOptsList *vm_config_groups[32] = {
     &qemu_machine_opts,
     &qemu_boot_opts,
     &qemu_iscsi_opts,
+    &qemu_sandbox_opts,
     NULL,
 };
 
diff --git a/qemu-config.h b/qemu-config.h
index 12ddf3e..5557562 100644
--- a/qemu-config.h
+++ b/qemu-config.h
@@ -6,6 +6,7 @@
 extern QemuOptsList qemu_fsdev_opts;
 extern QemuOptsList qemu_virtfs_opts;
 extern QemuOptsList qemu_spice_opts;
+extern QemuOptsList qemu_sandbox_opts;
 
 QemuOptsList *qemu_find_opts(const char *group);
 QemuOptsList *qemu_find_opts_err(const char *group, Error **errp);
diff --git a/qemu-options.hx b/qemu-options.hx
index 6aeef6a..3c411c4 100644
--- a/qemu-options.hx
+++ b/qemu-options.hx
@@ -2723,6 +2723,16 @@ STEXI
 Old param mode (ARM only).
 ETEXI
 
+DEF("sandbox", HAS_ARG, QEMU_OPTION_sandbox, \
+    "-sandbox <arg>  Enable seccomp mode 2 system call filter (default 'off').\n",
+    QEMU_ARCH_ALL)
+STEXI
+ at item -sandbox
+ at findex -sandbox
+Enable Seccomp mode 2 system call filter. 'on' will enable syscall filtering and 'off' will
+disable it.  The default is 'off'.
+ETEXI
+
 DEF("readconfig", HAS_ARG, QEMU_OPTION_readconfig,
     "-readconfig <file>\n", QEMU_ARCH_ALL)
 STEXI
diff --git a/vl.c b/vl.c
index 1010248..124d30d 100644
--- a/vl.c
+++ b/vl.c
@@ -770,6 +770,26 @@ static int bt_parse(const char *opt)
     return 1;
 }
 
+static int parse_sandbox(QemuOpts *opts, void *opaque)
+{
+    /* FIXME: change this to true for 1.3 */
+    if (qemu_opt_get_bool(opts, "enable", false)) {
+#ifdef CONFIG_SECCOMP
+        if (seccomp_start() < 0) {
+            qerror_report(ERROR_CLASS_GENERIC_ERROR,
+                          "failed to install seccomp syscall filter in the kernel");
+            return -1;
+        }
+#else
+        qerror_report(ERROR_CLASS_GENERIC_ERROR,
+                      "sandboxing request but seccomp is not compiled into this build");
+        return -1;
+#endif
+    }
+
+    return 0;
+}
+
 /***********************************************************/
 /* QEMU Block devices */
 
@@ -2349,14 +2369,6 @@ int main(int argc, char **argv, char **envp)
     const char *trace_events = NULL;
     const char *trace_file = NULL;
 
-#ifdef CONFIG_SECCOMP
-    if (seccomp_start() < 0) {
-        fprintf(stderr,
-                "seccomp: failed to install syscall filter in the kernel\n");
-        exit(1);
-    }
-#endif
-
     atexit(qemu_run_exit_notifiers);
     error_set_progname(argv[0]);
 
@@ -3260,6 +3272,12 @@ int main(int argc, char **argv, char **envp)
             case QEMU_OPTION_qtest_log:
                 qtest_log = optarg;
                 break;
+            case QEMU_OPTION_sandbox:
+                opts = qemu_opts_parse(qemu_find_opts("sandbox"), optarg, 1);
+                if (!opts) {
+                    exit(0);
+                }
+                break;
             default:
                 os_parse_cmd_args(popt->index, optarg);
             }
@@ -3267,6 +3285,10 @@ int main(int argc, char **argv, char **envp)
     }
     loc_set_none();
 
+    if (qemu_opts_foreach(qemu_find_opts("sandbox"), parse_sandbox, NULL, 0)) {
+        exit(1);
+    }
+
     if (machine == NULL) {
         fprintf(stderr, "No machine found.\n");
         exit(1);
commit 452dfbef600837c0e430564ea9e35138ef48f24c
Author: Eduardo Otubo <otubo at linux.vnet.ibm.com>
Date:   Tue Aug 14 18:44:07 2012 -0300

    Adding seccomp calls to vl.c (v8)
    
    Signed-off-by: Eduardo Otubo <otubo at linux.vnet.ibm.com>
    Signed-off-by: Anthony Liguori <aliguori at us.ibm.com>
    ---
    v1:
     - Full seccomp calls and data included in vl.c
    
    v1 -> v2:
     - Full seccomp calls and data removed from vl.c and put into separate
       qemu-seccomp.[ch] file.

diff --git a/vl.c b/vl.c
index d01256a..1010248 100644
--- a/vl.c
+++ b/vl.c
@@ -63,6 +63,11 @@
 #include <linux/ppdev.h>
 #include <linux/parport.h>
 #endif
+
+#ifdef CONFIG_SECCOMP
+#include "qemu-seccomp.h"
+#endif
+
 #ifdef __sun__
 #include <sys/stat.h>
 #include <sys/ethernet.h>
@@ -2344,6 +2349,14 @@ int main(int argc, char **argv, char **envp)
     const char *trace_events = NULL;
     const char *trace_file = NULL;
 
+#ifdef CONFIG_SECCOMP
+    if (seccomp_start() < 0) {
+        fprintf(stderr,
+                "seccomp: failed to install syscall filter in the kernel\n");
+        exit(1);
+    }
+#endif
+
     atexit(qemu_run_exit_notifiers);
     error_set_progname(argv[0]);
 
commit 2f668be77501c0232a84aafb6a066c9915987f0e
Author: Eduardo Otubo <otubo at linux.vnet.ibm.com>
Date:   Tue Aug 14 18:44:06 2012 -0300

    Adding qemu-seccomp.[ch] (v8)
    
    Signed-off-by: Eduardo Otubo <otubo at linux.vnet.ibm.com>
    Signed-off-by: Anthony Liguori <aliguori at us.ibm.com>
    ---
    v1:
     - I added a syscall struct using priority levels as described in the
       libseccomp man page. The priority numbers are based to the frequency
       they appear in a sample strace from a regular qemu guest run under
       libvirt.
    
       Libseccomp generates linear BPF code to filter system calls, those rules
       are read one after another. The priority system places the most common
       rules first in order to reduce the overhead when processing them.
    
    v1 -> v2:
     - Fixed some style issues
     - Removed code from vl.c and created qemu-seccomp.[ch]
     - Now using ARRAY_SIZE macro
     - Added more syscalls without priority/frequency set yet
    
    v2 -> v3:
     - Adding copyright and license information
     - Replacing seccomp_whitelist_count just by ARRAY_SIZE
     - Adding header protection to qemu-seccomp.h
     - Moving QemuSeccompSyscall definition to qemu-seccomp.c
     - Negative return from seccomp_start is fatal now.
     - Adding open() and execve() to the whitelis
    
    v3 -> v4:
     - Tests revealed a bigger set of syscalls.
     - seccomp_start() now has an argument to set the mode according to the
       configure option trap or kill.
    
    v4 -> v5:
     - Tests on x86_64 required a new specific set of system calls.
     - libseccomp release 1.0.0: part of the API have changed in this last
       release, had to adapt to the new function signatures.

diff --git a/qemu-seccomp.c b/qemu-seccomp.c
new file mode 100644
index 0000000..64329a3
--- /dev/null
+++ b/qemu-seccomp.c
@@ -0,0 +1,141 @@
+/*
+ * QEMU seccomp mode 2 support with libseccomp
+ *
+ * Copyright IBM, Corp. 2012
+ *
+ * Authors:
+ *  Eduardo Otubo    <eotubo at br.ibm.com>
+ *
+ * This work is licensed under the terms of the GNU GPL, version 2.  See
+ * the COPYING file in the top-level directory.
+ *
+ * Contributions after 2012-01-13 are licensed under the terms of the
+ * GNU GPL, version 2 or (at your option) any later version.
+ */
+#include <stdio.h>
+#include <seccomp.h>
+#include "qemu-seccomp.h"
+
+struct QemuSeccompSyscall {
+    int32_t num;
+    uint8_t priority;
+};
+
+static const struct QemuSeccompSyscall seccomp_whitelist[] = {
+    { SCMP_SYS(timer_settime), 255 },
+    { SCMP_SYS(timer_gettime), 254 },
+    { SCMP_SYS(futex), 253 },
+    { SCMP_SYS(select), 252 },
+    { SCMP_SYS(recvfrom), 251 },
+    { SCMP_SYS(sendto), 250 },
+    { SCMP_SYS(read), 249 },
+    { SCMP_SYS(brk), 248 },
+    { SCMP_SYS(clone), 247 },
+    { SCMP_SYS(mmap), 247 },
+    { SCMP_SYS(mprotect), 246 },
+    { SCMP_SYS(execve), 245 },
+    { SCMP_SYS(open), 245 },
+    { SCMP_SYS(ioctl), 245 },
+    { SCMP_SYS(recvmsg), 245 },
+    { SCMP_SYS(sendmsg), 245 },
+    { SCMP_SYS(accept), 245 },
+    { SCMP_SYS(connect), 245 },
+    { SCMP_SYS(gettimeofday), 245 },
+    { SCMP_SYS(readlink), 245 },
+    { SCMP_SYS(access), 245 },
+    { SCMP_SYS(prctl), 245 },
+    { SCMP_SYS(signalfd), 245 },
+#if defined(__i386__)
+    { SCMP_SYS(fcntl64), 245 },
+    { SCMP_SYS(fstat64), 245 },
+    { SCMP_SYS(stat64), 245 },
+    { SCMP_SYS(getgid32), 245 },
+    { SCMP_SYS(getegid32), 245 },
+    { SCMP_SYS(getuid32), 245 },
+    { SCMP_SYS(geteuid32), 245 },
+    { SCMP_SYS(sigreturn), 245 },
+    { SCMP_SYS(_newselect), 245 },
+    { SCMP_SYS(_llseek), 245 },
+    { SCMP_SYS(mmap2), 245},
+    { SCMP_SYS(sigprocmask), 245 },
+#elif defined(__x86_64__)
+    { SCMP_SYS(sched_getparam), 245},
+    { SCMP_SYS(sched_getscheduler), 245},
+    { SCMP_SYS(fstat), 245},
+    { SCMP_SYS(clock_getres), 245},
+    { SCMP_SYS(sched_get_priority_min), 245},
+    { SCMP_SYS(sched_get_priority_max), 245},
+    { SCMP_SYS(stat), 245},
+    { SCMP_SYS(socket), 245},
+    { SCMP_SYS(setsockopt), 245},
+    { SCMP_SYS(uname), 245},
+    { SCMP_SYS(semget), 245},
+#endif
+    { SCMP_SYS(eventfd2), 245 },
+    { SCMP_SYS(dup), 245 },
+    { SCMP_SYS(gettid), 245 },
+    { SCMP_SYS(timer_create), 245 },
+    { SCMP_SYS(exit), 245 },
+    { SCMP_SYS(clock_gettime), 245 },
+    { SCMP_SYS(time), 245 },
+    { SCMP_SYS(restart_syscall), 245 },
+    { SCMP_SYS(pwrite64), 245 },
+    { SCMP_SYS(chown), 245 },
+    { SCMP_SYS(openat), 245 },
+    { SCMP_SYS(getdents), 245 },
+    { SCMP_SYS(timer_delete), 245 },
+    { SCMP_SYS(exit_group), 245 },
+    { SCMP_SYS(rt_sigreturn), 245 },
+    { SCMP_SYS(sync), 245 },
+    { SCMP_SYS(pread64), 245 },
+    { SCMP_SYS(madvise), 245 },
+    { SCMP_SYS(set_robust_list), 245 },
+    { SCMP_SYS(lseek), 245 },
+    { SCMP_SYS(pselect6), 245 },
+    { SCMP_SYS(fork), 245 },
+    { SCMP_SYS(bind), 245 },
+    { SCMP_SYS(listen), 245 },
+    { SCMP_SYS(eventfd), 245 },
+    { SCMP_SYS(rt_sigprocmask), 245 },
+    { SCMP_SYS(write), 244 },
+    { SCMP_SYS(fcntl), 243 },
+    { SCMP_SYS(tgkill), 242 },
+    { SCMP_SYS(rt_sigaction), 242 },
+    { SCMP_SYS(pipe2), 242 },
+    { SCMP_SYS(munmap), 242 },
+    { SCMP_SYS(mremap), 242 },
+    { SCMP_SYS(getsockname), 242 },
+    { SCMP_SYS(getpeername), 242 },
+    { SCMP_SYS(fdatasync), 242 },
+    { SCMP_SYS(close), 242 }
+};
+
+int seccomp_start(void)
+{
+    int rc = 0;
+    unsigned int i = 0;
+    scmp_filter_ctx ctx;
+
+    ctx = seccomp_init(SCMP_ACT_KILL);
+    if (ctx == NULL) {
+        goto seccomp_return;
+    }
+
+    for (i = 0; i < ARRAY_SIZE(seccomp_whitelist); i++) {
+        rc = seccomp_rule_add(ctx, SCMP_ACT_ALLOW, seccomp_whitelist[i].num, 0);
+        if (rc < 0) {
+            goto seccomp_return;
+        }
+        rc = seccomp_syscall_priority(ctx, seccomp_whitelist[i].num,
+                                      seccomp_whitelist[i].priority);
+        if (rc < 0) {
+            goto seccomp_return;
+        }
+    }
+
+    rc = seccomp_load(ctx);
+
+  seccomp_return:
+    seccomp_release(ctx);
+    return rc;
+}
diff --git a/qemu-seccomp.h b/qemu-seccomp.h
new file mode 100644
index 0000000..b2fc3f8
--- /dev/null
+++ b/qemu-seccomp.h
@@ -0,0 +1,22 @@
+/*
+ * QEMU seccomp mode 2 support with libseccomp
+ *
+ * Copyright IBM, Corp. 2012
+ *
+ * Authors:
+ *  Eduardo Otubo    <eotubo at br.ibm.com>
+ *
+ * This work is licensed under the terms of the GNU GPL, version 2.  See
+ * the COPYING file in the top-level directory.
+ *
+ * Contributions after 2012-01-13 are licensed under the terms of the
+ * GNU GPL, version 2 or (at your option) any later version.
+ */
+#ifndef QEMU_SECCOMP_H
+#define QEMU_SECCOMP_H
+
+#include <seccomp.h>
+#include "osdep.h"
+
+int seccomp_start(void);
+#endif
commit f794573eab564548fa7aa463b5908b0042c0e6a4
Author: Eduardo Otubo <otubo at linux.vnet.ibm.com>
Date:   Tue Aug 14 18:44:05 2012 -0300

    Adding support for libseccomp in configure and Makefile (v8)
    
    Adding basic options to the configure script to use libseccomp or not.
    The default is set to 'no'. If the flag --enable-libseccomp is used, the
    script will check for its existence using pkg-config.
    
    Signed-off-by: Eduardo Otubo <otubo at linux.vnet.ibm.com>
    Signed-off-by: Anthony Liguori <aliguori at us.ibm.com>
    ---
    v1 -> v2:
     - As I removed all the code related to seccomp from vl.c, I created
       qemu-seccomp.[ch].
     - Also making the configure script to add the specific line to
       Makefile.obj in order to compile with appropriate support to seccomp.
    
    v2 -> v3:
     - Removing the line from Makefile.obj and adding it to Makefile.objs.
     - Marking libseccomp default option to 'yes' in the configure script.
    
    v3 -> v8:
     - fix configure probe if libseccomp isn't available (aliguori)

diff --git a/Makefile.objs b/Makefile.objs
index 309d066..4412757 100644
--- a/Makefile.objs
+++ b/Makefile.objs
@@ -97,6 +97,12 @@ common-obj-y += qemu-timer.o qemu-timer-common.o
 common-obj-$(CONFIG_SLIRP) += slirp/
 
 ######################################################################
+# libseccomp
+ifeq ($(CONFIG_SECCOMP),y)
+common-obj-y += qemu-seccomp.o
+endif
+
+######################################################################
 # libuser
 
 user-obj-y =
diff --git a/configure b/configure
index f54326d..60d266f 100755
--- a/configure
+++ b/configure
@@ -218,6 +218,7 @@ zlib="yes"
 guest_agent="yes"
 libiscsi=""
 coroutine=""
+seccomp=""
 
 # parse CC options first
 for opt do
@@ -864,6 +865,10 @@ for opt do
   ;;
   --disable-guest-agent) guest_agent="no"
   ;;
+  --enable-seccomp) seccomp="yes"
+  ;;
+  --disable-seccomp) seccomp="no"
+  ;;
   *) echo "ERROR: unknown option $opt"; show_help="yes"
   ;;
   esac
@@ -1152,6 +1157,8 @@ echo "  --disable-usb-redir      disable usb network redirection support"
 echo "  --enable-usb-redir       enable usb network redirection support"
 echo "  --disable-guest-agent    disable building of the QEMU Guest Agent"
 echo "  --enable-guest-agent     enable building of the QEMU Guest Agent"
+echo "  --disable-seccomp        disable seccomp support"
+echo "  --enable-seccomp         enables seccomp support"
 echo "  --with-coroutine=BACKEND coroutine backend. Supported options:"
 echo "                           gthread, ucontext, sigaltstack, windows"
 echo ""
@@ -1414,6 +1421,20 @@ EOF
 fi
 
 ##########################################
+# libseccomp check
+
+if test "$seccomp" != "no" ; then
+    if $pkg_config libseccomp --modversion >/dev/null 2>&1; then
+        LIBS=`$pkg_config --libs libseccomp`
+	seccomp="yes"
+    else
+	seccomp="no"
+	if test "$seccomp" = "yes"; then
+            feature_not_found "libseccomp"
+	fi
+    fi
+fi
+##########################################
 # xen probe
 
 if test "$xen" != "no" ; then
@@ -3143,6 +3164,7 @@ echo "usb net redir     $usb_redir"
 echo "OpenGL support    $opengl"
 echo "libiscsi support  $libiscsi"
 echo "build guest agent $guest_agent"
+echo "seccomp support   $seccomp"
 echo "coroutine backend $coroutine_backend"
 
 if test "$sdl_too_old" = "yes"; then
@@ -3438,6 +3460,10 @@ if test "$libiscsi" = "yes" ; then
   echo "CONFIG_LIBISCSI=y" >> $config_host_mak
 fi
 
+if test "$seccomp" = "yes"; then
+  echo "CONFIG_SECCOMP=y" >> $config_host_mak
+fi
+
 # XXX: suppress that
 if [ "$bsd" = "yes" ] ; then
   echo "CONFIG_BSD=y" >> $config_host_mak
commit bc9b78debf63c9be051abe51403736d386092d09
Author: Benjamin Herrenschmidt <benh at kernel.crashing.org>
Date:   Tue Aug 14 17:41:47 2012 +1000

    dma: Fix stupid typo/thinko
    
    Hi hard a brain fart when coding that function, it will
    fail to "set" the memory beyond the first 512 bytes. This
    is in turn causing guest crashes in ibmveth (spapr_llan.c
    on the qemu side) due to the receive queue not being
    properly initialized.
    
    Signed-off-by: Benjamin Herrenschmidt <benh at kernel.crashing.org>
    Signed-off-by: Anthony Liguori <aliguori at us.ibm.com>

diff --git a/dma-helpers.c b/dma-helpers.c
index 13593d1..433d8b2 100644
--- a/dma-helpers.c
+++ b/dma-helpers.c
@@ -24,8 +24,8 @@ static void do_dma_memory_set(dma_addr_t addr, uint8_t c, dma_addr_t len)
     while (len > 0) {
         l = len < FILLBUF_SIZE ? len : FILLBUF_SIZE;
         cpu_physical_memory_rw(addr, fillbuf, l, true);
-        len -= len;
-        addr += len;
+        len -= l;
+        addr += l;
     }
 }
 
commit ddb97f1debbb6be8d871f3b565f7b8befebf0f4f
Author: Jason Baron <jbaron at redhat.com>
Date:   Thu Aug 2 15:44:16 2012 -0400

    memory: add -machine dump-guest-core=on|off
    
    Add a new '[,dump-guest-core=on|off]' option to the '-machine' option. When
    'dump-guest-core=off' is specified, guest memory is omitted from the core dump.
    The default behavior continues to be to include guest memory when a core dump is
    triggered. In my testing, this brought the core dump size down from 384MB to 6MB
    on a 2GB guest.
    
    Is anything additional required to preserve this setting for migration or
    savevm? I don't believe so.
    
    Changelog:
    v3:
        Eliminate globals as per Anthony's suggestion
        set no dump from qemu_ram_remap() as well
    v2:
        move the option from -m to -machine, rename option dump -> dump-guest-core
    
    Signed-off-by: Jason Baron <jbaron at redhat.com>
    Signed-off-by: Anthony Liguori <aliguori at us.ibm.com>

diff --git a/exec.c b/exec.c
index 929db5c..5834766 100644
--- a/exec.c
+++ b/exec.c
@@ -2475,6 +2475,24 @@ static ram_addr_t last_ram_offset(void)
     return last;
 }
 
+static void qemu_ram_setup_dump(void *addr, ram_addr_t size)
+{
+    int ret;
+    QemuOpts *machine_opts;
+
+    /* Use MADV_DONTDUMP, if user doesn't want the guest memory in the core */
+    machine_opts = qemu_opts_find(qemu_find_opts("machine"), 0);
+    if (machine_opts &&
+        !qemu_opt_get_bool(machine_opts, "dump-guest-core", true)) {
+        ret = qemu_madvise(addr, size, QEMU_MADV_DONTDUMP);
+        if (ret) {
+            perror("qemu_madvise");
+            fprintf(stderr, "madvise doesn't support MADV_DONTDUMP, "
+                            "but dump_guest_core=off specified\n");
+        }
+    }
+}
+
 void qemu_ram_set_idstr(ram_addr_t addr, const char *name, DeviceState *dev)
 {
     RAMBlock *new_block, *block;
@@ -2554,6 +2572,8 @@ ram_addr_t qemu_ram_alloc_from_ptr(ram_addr_t size, void *host,
            0, size >> TARGET_PAGE_BITS);
     cpu_physical_memory_set_dirty_range(new_block->offset, size, 0xff);
 
+    qemu_ram_setup_dump(new_block->host, size);
+
     if (kvm_enabled())
         kvm_setup_guest_memory(new_block->host, size);
 
@@ -2670,6 +2690,7 @@ void qemu_ram_remap(ram_addr_t addr, ram_addr_t length)
                     exit(1);
                 }
                 qemu_madvise(vaddr, length, QEMU_MADV_MERGEABLE);
+                qemu_ram_setup_dump(vaddr, length);
             }
             return;
         }
diff --git a/osdep.h b/osdep.h
index d4b887d..cb213e0 100644
--- a/osdep.h
+++ b/osdep.h
@@ -103,6 +103,11 @@ void qemu_vfree(void *ptr);
 #else
 #define QEMU_MADV_MERGEABLE QEMU_MADV_INVALID
 #endif
+#ifdef MADV_DONTDUMP
+#define QEMU_MADV_DONTDUMP MADV_DONTDUMP
+#else
+#define QEMU_MADV_DONTDUMP QEMU_MADV_INVALID
+#endif
 
 #elif defined(CONFIG_POSIX_MADVISE)
 
@@ -110,6 +115,7 @@ void qemu_vfree(void *ptr);
 #define QEMU_MADV_DONTNEED  POSIX_MADV_DONTNEED
 #define QEMU_MADV_DONTFORK  QEMU_MADV_INVALID
 #define QEMU_MADV_MERGEABLE QEMU_MADV_INVALID
+#define QEMU_MADV_DONTDUMP QEMU_MADV_INVALID
 
 #else /* no-op */
 
@@ -117,6 +123,7 @@ void qemu_vfree(void *ptr);
 #define QEMU_MADV_DONTNEED  QEMU_MADV_INVALID
 #define QEMU_MADV_DONTFORK  QEMU_MADV_INVALID
 #define QEMU_MADV_MERGEABLE QEMU_MADV_INVALID
+#define QEMU_MADV_DONTDUMP QEMU_MADV_INVALID
 
 #endif
 
diff --git a/qemu-config.c b/qemu-config.c
index 5c3296b..6700de0 100644
--- a/qemu-config.c
+++ b/qemu-config.c
@@ -595,6 +595,10 @@ static QemuOptsList qemu_machine_opts = {
             .name = "dt_compatible",
             .type = QEMU_OPT_STRING,
             .help = "Overrides the \"compatible\" property of the dt root node",
+        }, {
+            .name = "dump-guest-core",
+            .type = QEMU_OPT_BOOL,
+            .help = "Include guest memory in  a core dump",
         },
         { /* End of list */ }
     },
diff --git a/qemu-options.hx b/qemu-options.hx
index 47cb5bd..6aeef6a 100644
--- a/qemu-options.hx
+++ b/qemu-options.hx
@@ -37,7 +37,8 @@ DEF("machine", HAS_ARG, QEMU_OPTION_machine, \
     "                property accel=accel1[:accel2[:...]] selects accelerator\n"
     "                supported accelerators are kvm, xen, tcg (default: tcg)\n"
     "                kernel_irqchip=on|off controls accelerated irqchip support\n"
-    "                kvm_shadow_mem=size of KVM shadow MMU\n",
+    "                kvm_shadow_mem=size of KVM shadow MMU\n"
+    "                dump-guest-core=on|off include guest memory in a core dump (default=on)\n",
     QEMU_ARCH_ALL)
 STEXI
 @item -machine [type=]@var{name}[,prop=@var{value}[,...]]
@@ -54,6 +55,8 @@ to initialize.
 Enables in-kernel irqchip support for the chosen accelerator when available.
 @item kvm_shadow_mem=size
 Defines the size of the KVM shadow MMU.
+ at item dump-guest-core=on|off
+Include guest memory in a core dump. The default is on.
 @end table
 ETEXI
 
commit 3c4a4d0dcbf4269e125f92df06816db1c1e86d20
Author: Peter Maydell <peter.maydell at linaro.org>
Date:   Sat Aug 11 22:34:40 2012 +0100

    Support using a different compiler for Objective-C files
    
    MacOSX 10.8 ("Mountain Lion") requires us to compile our one
    Objective-C source file with clang even if the rest of QEMU
    requires a real gcc, because the system headers we use make
    use of Apple's "Blocks" extension to C/ObjC, and mainline
    gcc doesn't support that. Since we only need to use a true
    gcc for the parts of QEMU that use the fixed-register
    env variable, we can simply use clang to build the ObjC
    file: it will link to the gcc-built objects with no problems.
    
    Add the necessary support for an OBJCC variable in the
    makefile and configure machinery; we default to clang
    if we have it, otherwise whatever CC is (since gcc
    might be the Apple gcc which does support Blocks).
    
    Signed-off-by: Peter Maydell <peter.maydell at linaro.org>
    Signed-off-by: Anthony Liguori <aliguori at us.ibm.com>

diff --git a/configure b/configure
index 6f6f8e0..f54326d 100755
--- a/configure
+++ b/configure
@@ -543,6 +543,13 @@ fi
 : ${python=${PYTHON-python}}
 : ${smbd=${SMBD-/usr/sbin/smbd}}
 
+# Default objcc to clang if available, otherwise use CC
+if has clang; then
+  objcc=clang
+else
+  objcc="$cc"
+fi
+
 if test "$mingw32" = "yes" ; then
   EXESUF=".exe"
   QEMU_CFLAGS="-DWIN32_LEAN_AND_MEAN -DWINVER=0x501 $QEMU_CFLAGS"
@@ -586,6 +593,8 @@ for opt do
   ;;
   --host-cc=*) host_cc="$optarg"
   ;;
+  --objcc=*) objcc="$optarg"
+  ;;
   --make=*) make="$optarg"
   ;;
   --install=*) install="$optarg"
@@ -1028,6 +1037,7 @@ echo "  --cross-prefix=PREFIX    use PREFIX for compile tools [$cross_prefix]"
 echo "  --cc=CC                  use C compiler CC [$cc]"
 echo "  --host-cc=CC             use C compiler CC [$host_cc] for code run at"
 echo "                           build time"
+echo "  --objcc=OBJCC            use Objective-C compiler OBJCC [$objcc]"
 echo "  --extra-cflags=CFLAGS    append extra C compiler flags QEMU_CFLAGS"
 echo "  --extra-ldflags=LDFLAGS  append extra linker flags LDFLAGS"
 echo "  --make=MAKE              use specified make [$make]"
@@ -3058,6 +3068,7 @@ fi
 echo "Source path       $source_path"
 echo "C compiler        $cc"
 echo "Host C compiler   $host_cc"
+echo "Objective-C compiler $objcc"
 echo "CFLAGS            $CFLAGS"
 echo "QEMU_CFLAGS       $QEMU_CFLAGS"
 echo "LDFLAGS           $LDFLAGS"
@@ -3521,6 +3532,7 @@ echo "PYTHON=$python" >> $config_host_mak
 echo "CC=$cc" >> $config_host_mak
 echo "CC_I386=$cc_i386" >> $config_host_mak
 echo "HOST_CC=$host_cc" >> $config_host_mak
+echo "OBJCC=$objcc" >> $config_host_mak
 echo "AR=$ar" >> $config_host_mak
 echo "OBJCOPY=$objcopy" >> $config_host_mak
 echo "LD=$ld" >> $config_host_mak
diff --git a/rules.mak b/rules.mak
index a284946..1b173aa 100644
--- a/rules.mak
+++ b/rules.mak
@@ -29,7 +29,7 @@ endif
 	$(call quiet-command,$(CC) $(QEMU_INCLUDES) $(QEMU_CFLAGS) $(QEMU_DGFLAGS) $(CFLAGS) -c -o $@ $<,"  AS    $(TARGET_DIR)$@")
 
 %.o: %.m
-	$(call quiet-command,$(CC) $(QEMU_INCLUDES) $(QEMU_CFLAGS) $(QEMU_DGFLAGS) $(CFLAGS) -c -o $@ $<,"  OBJC  $(TARGET_DIR)$@")
+	$(call quiet-command,$(OBJCC) $(QEMU_INCLUDES) $(QEMU_CFLAGS) $(QEMU_DGFLAGS) $(CFLAGS) -c -o $@ $<,"  OBJC  $(TARGET_DIR)$@")
 
 LINK = $(call quiet-command,$(CC) $(QEMU_CFLAGS) $(CFLAGS) $(LDFLAGS) -o $@ $(sort $(1)) $(LIBS),"  LINK  $(TARGET_DIR)$@")
 
commit a0b7cf6b6ecc91e730de5ac6a6f7f927d16f89ca
Author: Peter Maydell <peter.maydell at linaro.org>
Date:   Sat Aug 11 22:34:39 2012 +0100

    configure: Define OS_OBJECT_USE_OBJC=0 for MacOSX builds
    
    MacOSX 10.8 ("Mountain Lion") defaults to trying to use automated
    reference counting on certain objects.  This means that the system
    header files will use some Objective C syntax constructs even when
    compiling pure C, which confuses mainline gcc. Suppress this by
    setting OS_OBJECT_USE_OBJC=0. This avoids a compile error like this:
    
    In file included from
    /System/Library/Frameworks/Foundation.framework/Headers/NSObject.h:5:0,
                     from /usr/include/os/object.h:74,
                     from /usr/include/dispatch/dispatch.h:48,
                     from /System/Library/Frameworks/IOKit.framework/Headers/IOKitLib.h:56,
                     from block/raw-posix.c:35:
    /System/Library/Frameworks/Foundation.framework/Headers/NSObjCRuntime.h:409:1: error: stray ‘@’ in program
    [with a large number of further run-on errors]
    
    Signed-off-by: Peter Maydell <peter.maydell at linaro.org>
    Signed-off-by: Anthony Liguori <aliguori at us.ibm.com>

diff --git a/configure b/configure
index d08c0ce..6f6f8e0 100755
--- a/configure
+++ b/configure
@@ -467,6 +467,9 @@ Darwin)
   audio_possible_drivers="coreaudio sdl fmod"
   LDFLAGS="-framework CoreFoundation -framework IOKit $LDFLAGS"
   libs_softmmu="-F/System/Library/Frameworks -framework Cocoa -framework IOKit $libs_softmmu"
+  # Disable attempts to use ObjectiveC features in os/object.h since they
+  # won't work when we're compiling with gcc as a C compiler.
+  QEMU_CFLAGS="-DOS_OBJECT_USE_OBJC=0 $QEMU_CFLAGS"
 ;;
 SunOS)
   solaris="yes"
commit bbea4050802a2e7e0296a21823c0925782c02b93
Author: Peter Maydell <peter.maydell at linaro.org>
Date:   Tue Aug 14 15:35:34 2012 +0100

    configure: Don't override user's --cpu on MacOS and Solaris
    
    Both MacOS and Solaris have special case handling for the CPU
    type, because the check_define probes will return i386 even if
    the hardware is 64 bit and x86_64 would be preferable. Move
    these checks earlier in the configure probing so that we can
    do them only if the user didn't specify a CPU with --cpu. This
    fixes a bug where the user's command line argument was being
    ignored.
    
    Reviewed-by: Andreas F=E4rber <afaerber at suse.de>
    Signed-off-by: Peter Maydell <peter.maydell at linaro.org>
    Signed-off-by: Anthony Liguori <aliguori at us.ibm.com>

diff --git a/configure b/configure
index cc774b5..d08c0ce 100755
--- a/configure
+++ b/configure
@@ -298,6 +298,41 @@ EOF
   compile_object
 }
 
+if check_define __linux__ ; then
+  targetos="Linux"
+elif check_define _WIN32 ; then
+  targetos='MINGW32'
+elif check_define __OpenBSD__ ; then
+  targetos='OpenBSD'
+elif check_define __sun__ ; then
+  targetos='SunOS'
+elif check_define __HAIKU__ ; then
+  targetos='Haiku'
+else
+  targetos=`uname -s`
+fi
+
+# Some host OSes need non-standard checks for which CPU to use.
+# Note that these checks are broken for cross-compilation: if you're
+# cross-compiling to one of these OSes then you'll need to specify
+# the correct CPU with the --cpu option.
+case $targetos in
+Darwin)
+  # on Leopard most of the system is 32-bit, so we have to ask the kernel if we can
+  # run 64-bit userspace code.
+  # If the user didn't specify a CPU explicitly and the kernel says this is
+  # 64 bit hw, then assume x86_64. Otherwise fall through to the usual detection code.
+  if test -z "$cpu" && test "$(sysctl -n hw.optional.x86_64)" = "1"; then
+    cpu="x86_64"
+  fi
+  ;;
+SunOS)
+  # `uname -m` returns i86pc even on an x86_64 box, so default based on isainfo
+  if test -z "$cpu" && test "$(isainfo -k)" = "amd64"; then
+    cpu="x86_64"
+  fi
+esac
+
 if test ! -z "$cpu" ; then
   # command line argument
   :
@@ -372,19 +407,6 @@ if test -z "$ARCH"; then
 fi
 
 # OS specific
-if check_define __linux__ ; then
-  targetos="Linux"
-elif check_define _WIN32 ; then
-  targetos='MINGW32'
-elif check_define __OpenBSD__ ; then
-  targetos='OpenBSD'
-elif check_define __sun__ ; then
-  targetos='SunOS'
-elif check_define __HAIKU__ ; then
-  targetos='Haiku'
-else
-  targetos=`uname -s`
-fi
 
 case $targetos in
 CYGWIN*)
@@ -434,12 +456,6 @@ OpenBSD)
 Darwin)
   bsd="yes"
   darwin="yes"
-  # on Leopard most of the system is 32-bit, so we have to ask the kernel it if we can
-  # run 64-bit userspace code
-  if [ "$cpu" = "i386" ] ; then
-    is_x86_64=`sysctl -n hw.optional.x86_64`
-    [ "$is_x86_64" = "1" ] && cpu=x86_64
-  fi
   if [ "$cpu" = "x86_64" ] ; then
     QEMU_CFLAGS="-arch x86_64 $QEMU_CFLAGS"
     LDFLAGS="-arch x86_64 $LDFLAGS"
@@ -460,12 +476,6 @@ SunOS)
   smbd="${SMBD-/usr/sfw/sbin/smbd}"
   needs_libsunmath="no"
   solarisrev=`uname -r | cut -f2 -d.`
-  # have to select again, because `uname -m` returns i86pc
-  # even on an x86_64 box.
-  solariscpu=`isainfo -k`
-  if test "${solariscpu}" = "amd64" ; then
-    cpu="x86_64"
-  fi
   if [ "$cpu" = "i386" -o "$cpu" = "x86_64" ] ; then
     if test "$solarisrev" -le 9 ; then
       if test -f /opt/SUNWspro/prod/lib/libsunmath.so.1; then
commit 7109edfeb69c1d3c2164175837784dfcd210fed0
Author: Michael Roth <mdroth at linux.vnet.ibm.com>
Date:   Wed Aug 15 13:45:44 2012 -0500

    check-qjson: add test for large JSON objects
    
    Signed-off-by: Michael Roth <mdroth at linux.vnet.ibm.com>
    Signed-off-by: Anthony Liguori <aliguori at us.ibm.com>

diff --git a/tests/check-qjson.c b/tests/check-qjson.c
index 526e25e..3b896f5 100644
--- a/tests/check-qjson.c
+++ b/tests/check-qjson.c
@@ -466,6 +466,58 @@ static void simple_dict(void)
     }
 }
 
+/*
+ * this generates json of the form:
+ * a(0,m) = [0, 1, ..., m-1]
+ * a(n,m) = {
+ *            'key0': a(0,m),
+ *            'key1': a(1,m),
+ *            ...
+ *            'key(n-1)': a(n-1,m)
+ *          }
+ */
+static void gen_test_json(GString *gstr, int nest_level_max,
+                          int elem_count)
+{
+    int i;
+
+    g_assert(gstr);
+    if (nest_level_max == 0) {
+        g_string_append(gstr, "[");
+        for (i = 0; i < elem_count; i++) {
+            g_string_append_printf(gstr, "%d", i);
+            if (i < elem_count - 1) {
+                g_string_append_printf(gstr, ", ");
+            }
+        }
+        g_string_append(gstr, "]");
+        return;
+    }
+
+    g_string_append(gstr, "{");
+    for (i = 0; i < nest_level_max; i++) {
+        g_string_append_printf(gstr, "'key%d': ", i);
+        gen_test_json(gstr, i, elem_count);
+        if (i < nest_level_max - 1) {
+            g_string_append(gstr, ",");
+        }
+    }
+    g_string_append(gstr, "}");
+}
+
+static void large_dict(void)
+{
+    GString *gstr = g_string_new("");
+    QObject *obj;
+
+    gen_test_json(gstr, 10, 100);
+    obj = qobject_from_json(gstr->str);
+    g_assert(obj != NULL);
+
+    qobject_decref(obj);
+    g_string_free(gstr, true);
+}
+
 static void simple_list(void)
 {
     int i;
@@ -706,6 +758,7 @@ int main(int argc, char **argv)
     g_test_add_func("/literals/keyword", keyword_literal);
 
     g_test_add_func("/dicts/simple_dict", simple_dict);
+    g_test_add_func("/dicts/large_dict", large_dict);
     g_test_add_func("/lists/simple_list", simple_list);
 
     g_test_add_func("/whitespace/simple_whitespace", simple_whitespace);
commit 65c0f1e9558c7c762cdb333406243fff1d687117
Author: Michael Roth <mdroth at linux.vnet.ibm.com>
Date:   Wed Aug 15 13:45:43 2012 -0500

    json-parser: don't replicate tokens at each level of recursion
    
    Currently, when parsing a stream of tokens we make a copy of the token
    list at the beginning of each level of recursion so that we do not
    modify the original list in cases where we need to fall back to an
    earlier state.
    
    In the worst case, we will only read 1 or 2 tokens off the list before
    recursing again, which means an upper bound of roughly N^2 token allocations.
    
    For a "reasonably" sized QMP request (in this a QMP representation of
    cirrus_vga's device state, generated via QIDL, being passed in via
    qom-set), this caused my 16GB's of memory to be exhausted before any
    noticeable progress was made by the parser.
    
    This patch works around the issue by using single copy of the token list
    in the form of an indexable array so that we can save/restore state by
    manipulating indices.
    
    A subsequent commit adds a "large_dict" test case which exhibits the
    same behavior as above. With this patch applied the test case successfully
    completes in under a second.
    
    Tested with valgrind, make check, and QMP.
    
    Reviewed-by: Eric Blake <eblake at redhat.com>
    Signed-off-by: Michael Roth <mdroth at linux.vnet.ibm.com>
    Signed-off-by: Anthony Liguori <aliguori at us.ibm.com>

diff --git a/json-parser.c b/json-parser.c
index 849e215..457291b 100644
--- a/json-parser.c
+++ b/json-parser.c
@@ -27,6 +27,11 @@
 typedef struct JSONParserContext
 {
     Error *err;
+    struct {
+        QObject **buf;
+        size_t pos;
+        size_t count;
+    } tokens;
 } JSONParserContext;
 
 #define BUG_ON(cond) assert(!(cond))
@@ -40,7 +45,7 @@ typedef struct JSONParserContext
  * 4) deal with premature EOI
  */
 
-static QObject *parse_value(JSONParserContext *ctxt, QList **tokens, va_list *ap);
+static QObject *parse_value(JSONParserContext *ctxt, va_list *ap);
 
 /**
  * Token manipulators
@@ -270,27 +275,111 @@ out:
     return NULL;
 }
 
+static QObject *parser_context_pop_token(JSONParserContext *ctxt)
+{
+    QObject *token;
+    g_assert(ctxt->tokens.pos < ctxt->tokens.count);
+    token = ctxt->tokens.buf[ctxt->tokens.pos];
+    ctxt->tokens.pos++;
+    return token;
+}
+
+/* Note: parser_context_{peek|pop}_token do not increment the
+ * token object's refcount. In both cases the references will continue
+ * to be tracked and cleaned up in parser_context_free(), so do not
+ * attempt to free the token object.
+ */
+static QObject *parser_context_peek_token(JSONParserContext *ctxt)
+{
+    QObject *token;
+    g_assert(ctxt->tokens.pos < ctxt->tokens.count);
+    token = ctxt->tokens.buf[ctxt->tokens.pos];
+    return token;
+}
+
+static JSONParserContext parser_context_save(JSONParserContext *ctxt)
+{
+    JSONParserContext saved_ctxt = {0};
+    saved_ctxt.tokens.pos = ctxt->tokens.pos;
+    saved_ctxt.tokens.count = ctxt->tokens.count;
+    saved_ctxt.tokens.buf = ctxt->tokens.buf;
+    return saved_ctxt;
+}
+
+static void parser_context_restore(JSONParserContext *ctxt,
+                                   JSONParserContext saved_ctxt)
+{
+    ctxt->tokens.pos = saved_ctxt.tokens.pos;
+    ctxt->tokens.count = saved_ctxt.tokens.count;
+    ctxt->tokens.buf = saved_ctxt.tokens.buf;
+}
+
+static void tokens_append_from_iter(QObject *obj, void *opaque)
+{
+    JSONParserContext *ctxt = opaque;
+    g_assert(ctxt->tokens.pos < ctxt->tokens.count);
+    ctxt->tokens.buf[ctxt->tokens.pos++] = obj;
+    qobject_incref(obj);
+}
+
+static JSONParserContext *parser_context_new(QList *tokens)
+{
+    JSONParserContext *ctxt;
+    size_t count;
+
+    if (!tokens) {
+        return NULL;
+    }
+
+    count = qlist_size(tokens);
+    if (count == 0) {
+        return NULL;
+    }
+
+    ctxt = g_malloc0(sizeof(JSONParserContext));
+    ctxt->tokens.pos = 0;
+    ctxt->tokens.count = count;
+    ctxt->tokens.buf = g_malloc(count * sizeof(QObject *));
+    qlist_iter(tokens, tokens_append_from_iter, ctxt);
+    ctxt->tokens.pos = 0;
+
+    return ctxt;
+}
+
+/* to support error propagation, ctxt->err must be freed separately */
+static void parser_context_free(JSONParserContext *ctxt)
+{
+    int i;
+    if (ctxt) {
+        for (i = 0; i < ctxt->tokens.count; i++) {
+            qobject_decref(ctxt->tokens.buf[i]);
+        }
+        g_free(ctxt->tokens.buf);
+        g_free(ctxt);
+    }
+}
+
 /**
  * Parsing rules
  */
-static int parse_pair(JSONParserContext *ctxt, QDict *dict, QList **tokens, va_list *ap)
+static int parse_pair(JSONParserContext *ctxt, QDict *dict, va_list *ap)
 {
     QObject *key = NULL, *token = NULL, *value, *peek;
-    QList *working = qlist_copy(*tokens);
+    JSONParserContext saved_ctxt = parser_context_save(ctxt);
 
-    peek = qlist_peek(working);
+    peek = parser_context_peek_token(ctxt);
     if (peek == NULL) {
         parse_error(ctxt, NULL, "premature EOI");
         goto out;
     }
 
-    key = parse_value(ctxt, &working, ap);
+    key = parse_value(ctxt, ap);
     if (!key || qobject_type(key) != QTYPE_QSTRING) {
         parse_error(ctxt, peek, "key is not a string in object");
         goto out;
     }
 
-    token = qlist_pop(working);
+    token = parser_context_pop_token(ctxt);
     if (token == NULL) {
         parse_error(ctxt, NULL, "premature EOI");
         goto out;
@@ -301,7 +390,7 @@ static int parse_pair(JSONParserContext *ctxt, QDict *dict, QList **tokens, va_l
         goto out;
     }
 
-    value = parse_value(ctxt, &working, ap);
+    value = parse_value(ctxt, ap);
     if (value == NULL) {
         parse_error(ctxt, token, "Missing value in dict");
         goto out;
@@ -309,28 +398,24 @@ static int parse_pair(JSONParserContext *ctxt, QDict *dict, QList **tokens, va_l
 
     qdict_put_obj(dict, qstring_get_str(qobject_to_qstring(key)), value);
 
-    qobject_decref(token);
     qobject_decref(key);
-    QDECREF(*tokens);
-    *tokens = working;
 
     return 0;
 
 out:
-    qobject_decref(token);
+    parser_context_restore(ctxt, saved_ctxt);
     qobject_decref(key);
-    QDECREF(working);
 
     return -1;
 }
 
-static QObject *parse_object(JSONParserContext *ctxt, QList **tokens, va_list *ap)
+static QObject *parse_object(JSONParserContext *ctxt, va_list *ap)
 {
     QDict *dict = NULL;
     QObject *token, *peek;
-    QList *working = qlist_copy(*tokens);
+    JSONParserContext saved_ctxt = parser_context_save(ctxt);
 
-    token = qlist_pop(working);
+    token = parser_context_pop_token(ctxt);
     if (token == NULL) {
         goto out;
     }
@@ -338,23 +423,22 @@ static QObject *parse_object(JSONParserContext *ctxt, QList **tokens, va_list *a
     if (!token_is_operator(token, '{')) {
         goto out;
     }
-    qobject_decref(token);
     token = NULL;
 
     dict = qdict_new();
 
-    peek = qlist_peek(working);
+    peek = parser_context_peek_token(ctxt);
     if (peek == NULL) {
         parse_error(ctxt, NULL, "premature EOI");
         goto out;
     }
 
     if (!token_is_operator(peek, '}')) {
-        if (parse_pair(ctxt, dict, &working, ap) == -1) {
+        if (parse_pair(ctxt, dict, ap) == -1) {
             goto out;
         }
 
-        token = qlist_pop(working);
+        token = parser_context_pop_token(ctxt);
         if (token == NULL) {
             parse_error(ctxt, NULL, "premature EOI");
             goto out;
@@ -365,59 +449,52 @@ static QObject *parse_object(JSONParserContext *ctxt, QList **tokens, va_list *a
                 parse_error(ctxt, token, "expected separator in dict");
                 goto out;
             }
-            qobject_decref(token);
             token = NULL;
 
-            if (parse_pair(ctxt, dict, &working, ap) == -1) {
+            if (parse_pair(ctxt, dict, ap) == -1) {
                 goto out;
             }
 
-            token = qlist_pop(working);
+            token = parser_context_pop_token(ctxt);
             if (token == NULL) {
                 parse_error(ctxt, NULL, "premature EOI");
                 goto out;
             }
         }
-        qobject_decref(token);
         token = NULL;
     } else {
-        token = qlist_pop(working);
-        qobject_decref(token);
+        token = parser_context_pop_token(ctxt);
         token = NULL;
     }
 
-    QDECREF(*tokens);
-    *tokens = working;
-
     return QOBJECT(dict);
 
 out:
-    qobject_decref(token);
-    QDECREF(working);
+    parser_context_restore(ctxt, saved_ctxt);
     QDECREF(dict);
     return NULL;
 }
 
-static QObject *parse_array(JSONParserContext *ctxt, QList **tokens, va_list *ap)
+static QObject *parse_array(JSONParserContext *ctxt, va_list *ap)
 {
     QList *list = NULL;
     QObject *token, *peek;
-    QList *working = qlist_copy(*tokens);
+    JSONParserContext saved_ctxt = parser_context_save(ctxt);
 
-    token = qlist_pop(working);
+    token = parser_context_pop_token(ctxt);
     if (token == NULL) {
         goto out;
     }
 
     if (!token_is_operator(token, '[')) {
+        token = NULL;
         goto out;
     }
-    qobject_decref(token);
     token = NULL;
 
     list = qlist_new();
 
-    peek = qlist_peek(working);
+    peek = parser_context_peek_token(ctxt);
     if (peek == NULL) {
         parse_error(ctxt, NULL, "premature EOI");
         goto out;
@@ -426,7 +503,7 @@ static QObject *parse_array(JSONParserContext *ctxt, QList **tokens, va_list *ap
     if (!token_is_operator(peek, ']')) {
         QObject *obj;
 
-        obj = parse_value(ctxt, &working, ap);
+        obj = parse_value(ctxt, ap);
         if (obj == NULL) {
             parse_error(ctxt, token, "expecting value");
             goto out;
@@ -434,7 +511,7 @@ static QObject *parse_array(JSONParserContext *ctxt, QList **tokens, va_list *ap
 
         qlist_append_obj(list, obj);
 
-        token = qlist_pop(working);
+        token = parser_context_pop_token(ctxt);
         if (token == NULL) {
             parse_error(ctxt, NULL, "premature EOI");
             goto out;
@@ -446,10 +523,9 @@ static QObject *parse_array(JSONParserContext *ctxt, QList **tokens, va_list *ap
                 goto out;
             }
 
-            qobject_decref(token);
             token = NULL;
 
-            obj = parse_value(ctxt, &working, ap);
+            obj = parse_value(ctxt, ap);
             if (obj == NULL) {
                 parse_error(ctxt, token, "expecting value");
                 goto out;
@@ -457,39 +533,33 @@ static QObject *parse_array(JSONParserContext *ctxt, QList **tokens, va_list *ap
 
             qlist_append_obj(list, obj);
 
-            token = qlist_pop(working);
+            token = parser_context_pop_token(ctxt);
             if (token == NULL) {
                 parse_error(ctxt, NULL, "premature EOI");
                 goto out;
             }
         }
 
-        qobject_decref(token);
         token = NULL;
     } else {
-        token = qlist_pop(working);
-        qobject_decref(token);
+        token = parser_context_pop_token(ctxt);
         token = NULL;
     }
 
-    QDECREF(*tokens);
-    *tokens = working;
-
     return QOBJECT(list);
 
 out:
-    qobject_decref(token);
-    QDECREF(working);
+    parser_context_restore(ctxt, saved_ctxt);
     QDECREF(list);
     return NULL;
 }
 
-static QObject *parse_keyword(JSONParserContext *ctxt, QList **tokens)
+static QObject *parse_keyword(JSONParserContext *ctxt)
 {
     QObject *token, *ret;
-    QList *working = qlist_copy(*tokens);
+    JSONParserContext saved_ctxt = parser_context_save(ctxt);
 
-    token = qlist_pop(working);
+    token = parser_context_pop_token(ctxt);
     if (token == NULL) {
         goto out;
     }
@@ -507,29 +577,24 @@ static QObject *parse_keyword(JSONParserContext *ctxt, QList **tokens)
         goto out;
     }
 
-    qobject_decref(token);
-    QDECREF(*tokens);
-    *tokens = working;
-
     return ret;
 
 out: 
-    qobject_decref(token);
-    QDECREF(working);
+    parser_context_restore(ctxt, saved_ctxt);
 
     return NULL;
 }
 
-static QObject *parse_escape(JSONParserContext *ctxt, QList **tokens, va_list *ap)
+static QObject *parse_escape(JSONParserContext *ctxt, va_list *ap)
 {
     QObject *token = NULL, *obj;
-    QList *working = qlist_copy(*tokens);
+    JSONParserContext saved_ctxt = parser_context_save(ctxt);
 
     if (ap == NULL) {
         goto out;
     }
 
-    token = qlist_pop(working);
+    token = parser_context_pop_token(ctxt);
     if (token == NULL) {
         goto out;
     }
@@ -553,25 +618,20 @@ static QObject *parse_escape(JSONParserContext *ctxt, QList **tokens, va_list *a
         goto out;
     }
 
-    qobject_decref(token);
-    QDECREF(*tokens);
-    *tokens = working;
-
     return obj;
 
 out:
-    qobject_decref(token);
-    QDECREF(working);
+    parser_context_restore(ctxt, saved_ctxt);
 
     return NULL;
 }
 
-static QObject *parse_literal(JSONParserContext *ctxt, QList **tokens)
+static QObject *parse_literal(JSONParserContext *ctxt)
 {
     QObject *token, *obj;
-    QList *working = qlist_copy(*tokens);
+    JSONParserContext saved_ctxt = parser_context_save(ctxt);
 
-    token = qlist_pop(working);
+    token = parser_context_pop_token(ctxt);
     if (token == NULL) {
         goto out;
     }
@@ -591,35 +651,30 @@ static QObject *parse_literal(JSONParserContext *ctxt, QList **tokens)
         goto out;
     }
 
-    qobject_decref(token);
-    QDECREF(*tokens);
-    *tokens = working;
-
     return obj;
 
 out:
-    qobject_decref(token);
-    QDECREF(working);
+    parser_context_restore(ctxt, saved_ctxt);
 
     return NULL;
 }
 
-static QObject *parse_value(JSONParserContext *ctxt, QList **tokens, va_list *ap)
+static QObject *parse_value(JSONParserContext *ctxt, va_list *ap)
 {
     QObject *obj;
 
-    obj = parse_object(ctxt, tokens, ap);
+    obj = parse_object(ctxt, ap);
     if (obj == NULL) {
-        obj = parse_array(ctxt, tokens, ap);
+        obj = parse_array(ctxt, ap);
     }
     if (obj == NULL) {
-        obj = parse_escape(ctxt, tokens, ap);
+        obj = parse_escape(ctxt, ap);
     }
     if (obj == NULL) {
-        obj = parse_keyword(ctxt, tokens);
+        obj = parse_keyword(ctxt);
     } 
     if (obj == NULL) {
-        obj = parse_literal(ctxt, tokens);
+        obj = parse_literal(ctxt);
     }
 
     return obj;
@@ -632,19 +687,18 @@ QObject *json_parser_parse(QList *tokens, va_list *ap)
 
 QObject *json_parser_parse_err(QList *tokens, va_list *ap, Error **errp)
 {
-    JSONParserContext ctxt = {};
-    QList *working;
+    JSONParserContext *ctxt = parser_context_new(tokens);
     QObject *result;
 
-    if (!tokens) {
+    if (!ctxt) {
         return NULL;
     }
-    working = qlist_copy(tokens);
-    result = parse_value(&ctxt, &working, ap);
 
-    QDECREF(working);
+    result = parse_value(ctxt, ap);
+
+    error_propagate(errp, ctxt->err);
 
-    error_propagate(errp, ctxt.err);
+    parser_context_free(ctxt);
 
     return result;
 }
commit a86a4c2f7b7f0b72816ea1c219d8140699b6665b
Author: Michael Roth <mdroth at linux.vnet.ibm.com>
Date:   Wed Aug 15 13:45:42 2012 -0500

    qlist: add qlist_size()
    
    Signed-off-by: Michael Roth <mdroth at linux.vnet.ibm.com>
    Reviewed-by: Eric Blake <eblake at redhat.com>
    Signed-off-by: Michael Roth <mdroth at linux.vnet.ibm.com>
    Signed-off-by: Anthony Liguori <aliguori at us.ibm.com>

diff --git a/qlist.c b/qlist.c
index 88498b1..b48ec5b 100644
--- a/qlist.c
+++ b/qlist.c
@@ -124,6 +124,19 @@ int qlist_empty(const QList *qlist)
     return QTAILQ_EMPTY(&qlist->head);
 }
 
+static void qlist_size_iter(QObject *obj, void *opaque)
+{
+    size_t *count = opaque;
+    (*count)++;
+}
+
+size_t qlist_size(const QList *qlist)
+{
+    size_t count = 0;
+    qlist_iter(qlist, qlist_size_iter, &count);
+    return count;
+}
+
 /**
  * qobject_to_qlist(): Convert a QObject into a QList
  */
diff --git a/qlist.h b/qlist.h
index d426bd4..ae776f9 100644
--- a/qlist.h
+++ b/qlist.h
@@ -49,6 +49,7 @@ void qlist_iter(const QList *qlist,
 QObject *qlist_pop(QList *qlist);
 QObject *qlist_peek(QList *qlist);
 int qlist_empty(const QList *qlist);
+size_t qlist_size(const QList *qlist);
 QList *qobject_to_qlist(const QObject *obj);
 
 static inline const QListEntry *qlist_first(const QList *qlist)
commit 5a4d701acde890a5ca134236424ece45545f70c7
Author: Jan Kiszka <jan.kiszka at siemens.com>
Date:   Thu Aug 16 11:01:11 2012 +0200

    audio: Make pcspk card selectable again
    
        [ The following text is in the "ISO-8859-1" character set. ]
        [ Your display is set for the "KOI8-R" character set.  ]
        [ Some special characters may be displayed incorrectly. ]
    
    Since we moved pcspk into hwlib, CONFIG_PCSPK is no longer defined per
    target. Therefore, statically built soundhw array in arch_init.c stopped
    including this card.
    
    Work around this by re-adding this define to config-target.mak.
    Long-term, a dynamic creation of this soundhw list will be necessary.
    
    Signed-off-by: Jan Kiszka <jan.kiszka at siemens.com>
    Signed-off-by: malc <av1474 at comtv.ru>

diff --git a/configure b/configure
index edf9da4..cc774b5 100755
--- a/configure
+++ b/configure
@@ -3881,6 +3881,11 @@ if test "$target_bsd_user" = "yes" ; then
   echo "CONFIG_BSD_USER=y" >> $config_target_mak
 fi
 
+# the static way of configuring available audio cards requires this workaround
+if test "$target_user_only" != "yes" && grep -q CONFIG_PCSPK $source_path/default-configs/$target.mak; then
+  echo "CONFIG_PCSPK=y" >> $config_target_mak
+fi
+
 # generate QEMU_CFLAGS/LDFLAGS for targets
 
 cflags=""
commit 47d073cc3b8ad4a3ef1dba7055b35a87fa4091ff
Author: Hans de Goede <hdegoede at redhat.com>
Date:   Wed Aug 15 17:08:54 2012 +0200

    ehci: Fix setting of halt bit from usbcmd register updates
    
    This fixes linux guests started without any USB devices not seeing newly
    plugged devices until "lsusb" is done inside the guest.
    
    Signed-off-by: Hans de Goede <hdegoede at redhat.com>
    Signed-off-by: Gerd Hoffmann <kraxel at redhat.com>

diff --git a/hw/usb/hcd-ehci.c b/hw/usb/hcd-ehci.c
index e489509..8b94b17 100644
--- a/hw/usb/hcd-ehci.c
+++ b/hw/usb/hcd-ehci.c
@@ -1187,22 +1187,23 @@ static void ehci_mem_writel(void *ptr, target_phys_addr_t addr, uint32_t val)
             break;
         }
 
+        /* not supporting dynamic frame list size at the moment */
+        if ((val & USBCMD_FLS) && !(s->usbcmd & USBCMD_FLS)) {
+            fprintf(stderr, "attempt to set frame list size -- value %d\n",
+                    val & USBCMD_FLS);
+            val &= ~USBCMD_FLS;
+        }
+
         if (((USBCMD_RUNSTOP | USBCMD_PSE | USBCMD_ASE) & val) !=
             ((USBCMD_RUNSTOP | USBCMD_PSE | USBCMD_ASE) & s->usbcmd)) {
             if (s->pstate == EST_INACTIVE) {
                 SET_LAST_RUN_CLOCK(s);
             }
+            s->usbcmd = val; /* Set usbcmd for ehci_update_halt() */
             ehci_update_halt(s);
             s->async_stepdown = 0;
             qemu_mod_timer(s->frame_timer, qemu_get_clock_ns(vm_clock));
         }
-
-        /* not supporting dynamic frame list size at the moment */
-        if ((val & USBCMD_FLS) && !(s->usbcmd & USBCMD_FLS)) {
-            fprintf(stderr, "attempt to set frame list size -- value %d\n",
-                    val & USBCMD_FLS);
-            val &= ~USBCMD_FLS;
-        }
         break;
 
     case USBSTS:
commit 6d3b6d3d2deaf682def95e3e512ad0e17f02274f
Author: Gerd Hoffmann <kraxel at redhat.com>
Date:   Wed Aug 15 13:55:40 2012 +0200

    ehci: fix Interrupt Threshold Control implementation
    
    First, not all interrupts are subject to Interrupt Threshold Control,
    some of them must be delivered without delay.
    
    Second, Interrupt Threshold Control state must be part of vmstate,
    otherwise we might loose IRQs on migration.
    
    Signed-off-by: Gerd Hoffmann <kraxel at redhat.com>

diff --git a/hw/usb/hcd-ehci.c b/hw/usb/hcd-ehci.c
index 104c21d..e489509 100644
--- a/hw/usb/hcd-ehci.c
+++ b/hw/usb/hcd-ehci.c
@@ -575,7 +575,12 @@ static inline void ehci_update_irq(EHCIState *s)
 /* flag interrupt condition */
 static inline void ehci_raise_irq(EHCIState *s, int intr)
 {
-    s->usbsts_pending |= intr;
+    if (intr & (USBSTS_PCD | USBSTS_FLR | USBSTS_HSE)) {
+        s->usbsts |= intr;
+        ehci_update_irq(s);
+    } else {
+        s->usbsts_pending |= intr;
+    }
 }
 
 /*
@@ -2466,13 +2471,16 @@ static int usb_ehci_post_load(void *opaque, int version_id)
 
 static const VMStateDescription vmstate_ehci = {
     .name        = "ehci",
-    .version_id  = 1,
+    .version_id  = 2,
+    .minimum_version_id  = 1,
     .post_load   = usb_ehci_post_load,
     .fields      = (VMStateField[]) {
         VMSTATE_PCI_DEVICE(dev, EHCIState),
         /* mmio registers */
         VMSTATE_UINT32(usbcmd, EHCIState),
         VMSTATE_UINT32(usbsts, EHCIState),
+        VMSTATE_UINT32_V(usbsts_pending, EHCIState, 2),
+        VMSTATE_UINT32_V(usbsts_frindex, EHCIState, 2),
         VMSTATE_UINT32(usbintr, EHCIState),
         VMSTATE_UINT32(frindex, EHCIState),
         VMSTATE_UINT32(ctrldssegment, EHCIState),
commit 0daf53047da0b817e40c4931580e59e73b420f41
Author: Gerd Hoffmann <kraxel at redhat.com>
Date:   Fri Aug 10 13:06:05 2012 +0200

    usb: update uas product id
    
    Pick other product id to fix clash with audio.
    
    Current usage list (after applying this patch):
    
    46f4:0001 -- usb-storage
    46f4:0002 -- usb-audio
    46f4:0003 -- usb-uas
    
    Signed-off-by: Gerd Hoffmann <kraxel at redhat.com>

diff --git a/hw/usb/dev-uas.c b/hw/usb/dev-uas.c
index 9b02ff4..b13eeba 100644
--- a/hw/usb/dev-uas.c
+++ b/hw/usb/dev-uas.c
@@ -223,7 +223,7 @@ static const USBDescDevice desc_device_high = {
 static const USBDesc desc = {
     .id = {
         .idVendor          = 0x46f4, /* CRC16() of "QEMU" */
-        .idProduct         = 0x0002,
+        .idProduct         = 0x0003,
         .bcdDevice         = 0,
         .iManufacturer     = STR_MANUFACTURER,
         .iProduct          = STR_PRODUCT,
commit c19537a1143d493897850576394f082914f39ef1
Author: Gerd Hoffmann <kraxel at redhat.com>
Date:   Thu Aug 9 10:57:32 2012 +0200

    usb: async control xfer fixup
    
    Need to clear p->result after copying setup data using usb_packet_copy()
    because we'll reuse the USBPacket for the data transfer.
    
    Signed-off-by: Gerd Hoffmann <kraxel at redhat.com>

diff --git a/hw/usb/core.c b/hw/usb/core.c
index 01a7622..c7e5bc0 100644
--- a/hw/usb/core.c
+++ b/hw/usb/core.c
@@ -107,6 +107,7 @@ static int do_token_setup(USBDevice *s, USBPacket *p)
     }
 
     usb_packet_copy(p, s->setup_buf, p->iov.size);
+    p->result = 0;
     s->setup_len   = (s->setup_buf[7] << 8) | s->setup_buf[6];
     s->setup_index = 0;
 
diff --git a/hw/usb/host-linux.c b/hw/usb/host-linux.c
index d55be87..8df9207 100644
--- a/hw/usb/host-linux.c
+++ b/hw/usb/host-linux.c
@@ -1045,6 +1045,7 @@ static int usb_host_handle_control(USBDevice *dev, USBPacket *p,
 
     /* Note request is (bRequestType << 8) | bRequest */
     trace_usb_host_req_control(s->bus_num, s->addr, p, request, value, index);
+    assert(p->result == 0);
 
     switch (request) {
     case DeviceOutRequest | USB_REQ_SET_ADDRESS:
commit 2b97f88c927be3ff3722497980048bc1cb7cc571
Merge: 0d16fdd... 000a1a3...
Author: Anthony Liguori <aliguori at us.ibm.com>
Date:   Wed Aug 15 14:59:48 2012 -0500

    Merge remote-tracking branch 'agraf/s390-for-upstream' into staging
    
    * agraf/s390-for-upstream:
      s390: provide interface for service interrupt/introduce interrupt.c
      s390: Fix error handling and condition code of service call

commit 0d16fdd732d1b211842fa96b7c90ddf9e6bde0e4
Merge: 76b64a7... 3e77223...
Author: Anthony Liguori <aliguori at us.ibm.com>
Date:   Wed Aug 15 14:59:21 2012 -0500

    Merge remote-tracking branch 'agraf/ppc-for-upstream' into staging
    
    * agraf/ppc-for-upstream: (24 commits)
      openpic: Added BRR1 register
      pseries: Update SLOF firmware image
      pseries dma: DMA window params added to PHB and DT population changed
      pseries: Add PCI MSI/MSI-X support
      pseries: Add trace event for PCI irqs
      pseries: Export find_phb() utility function for PCI code
      pseries: added allocator for a block of IRQs
      pseries: Separate PCI RTAS setup from common from emulation specific PCI setup
      pseries: Rework irq assignment to avoid carrying qemu_irqs around
      pseries: Remove extraneous prints
      pseries: Update SLOF
      PPC: spapr: Remove global variable
      PPC: spapr: Rework VGA select logic
      xbzrle: fix compilation on ppc32
      spapr: Add support for -vga option
      Add one new file vga-pci.h and cleanup on all platforms
      Revert "PPC: e500: Use new MPIC dt format"
      ppc: Fix bug in handling of PAPR hypercall exits
      PPC: e500: add generic e500 platform
      PPC: e500: split mpc8544ds machine from generic e500 code
      ...

commit 76b64a7aa84965ee9c7594058a43b00c2a14c72e
Author: Anthony Liguori <aliguori at us.ibm.com>
Date:   Tue Aug 14 22:17:36 2012 -0500

    win32: provide separate macros for weak decls and definitions
    
    mingw32 seems to want the declaration to also carry the weak attribute.
    Strangely, gcc on Linux absolutely does not want the declaration to be marked
    as weak.  This may not be the right fix, but it seems to do the trick.
    
    Signed-off-by: Anthony Liguori <aliguori at us.ibm.com>

diff --git a/arch_init.h b/arch_init.h
index 547f93c..d9c572a 100644
--- a/arch_init.h
+++ b/arch_init.h
@@ -1,6 +1,8 @@
 #ifndef QEMU_ARCH_INIT_H
 #define QEMU_ARCH_INIT_H
 
+#include "qmp-commands.h"
+
 enum {
     QEMU_ARCH_ALL = -1,
     QEMU_ARCH_ALPHA = 1,
@@ -32,4 +34,6 @@ int tcg_available(void);
 int kvm_available(void);
 int xen_available(void);
 
+CpuDefinitionInfoList GCC_WEAK_DECL *arch_query_cpu_definitions(Error **errp);
+
 #endif
diff --git a/compiler.h b/compiler.h
index f76921e..07ba1f8 100644
--- a/compiler.h
+++ b/compiler.h
@@ -45,7 +45,13 @@
 #  define GCC_ATTR __attribute__((__unused__, format(gnu_printf, 1, 2)))
 #  define GCC_FMT_ATTR(n, m) __attribute__((format(gnu_printf, n, m)))
 # endif
+#if defined(_WIN32)
+#define GCC_WEAK __attribute__((weak))
+#define GCC_WEAK_DECL GCC_WEAK
+#else
 #define GCC_WEAK __attribute__((weak))
+#define GCC_WEAK_DECL
+#endif
 #else
 #define GCC_ATTR /**/
 #define GCC_FMT_ATTR(n, m)
diff --git a/qmp.c b/qmp.c
index 6c1e4e8..8463922 100644
--- a/qmp.c
+++ b/qmp.c
@@ -468,8 +468,14 @@ DevicePropertyInfoList *qmp_device_list_properties(const char *typename,
     return prop_list;
 }
 
-CpuDefinitionInfoList GCC_WEAK *qmp_query_cpu_definitions(Error **errp)
+CpuDefinitionInfoList GCC_WEAK *arch_query_cpu_definitions(Error **errp)
 {
     error_set(errp, QERR_NOT_SUPPORTED);
     return NULL;
 }
+
+CpuDefinitionInfoList *qmp_query_cpu_definitions(Error **errp)
+{
+    return arch_query_cpu_definitions(errp);
+}
+
diff --git a/target-i386/cpu.c b/target-i386/cpu.c
index 6d5d0d6..120a2e3 100644
--- a/target-i386/cpu.c
+++ b/target-i386/cpu.c
@@ -28,7 +28,7 @@
 #include "qemu-config.h"
 
 #include "qapi/qapi-visit-core.h"
-#include "qmp-commands.h"
+#include "arch_init.h"
 
 #include "hyperv.h"
 
@@ -1126,7 +1126,7 @@ void x86_cpu_list(FILE *f, fprintf_function cpu_fprintf, const char *optarg)
     }
 }
 
-CpuDefinitionInfoList *qmp_query_cpu_definitions(Error **errp)
+CpuDefinitionInfoList *arch_query_cpu_definitions(Error **errp)
 {
     CpuDefinitionInfoList *cpu_list = NULL;
     x86_def_t *def;
diff --git a/target-ppc/translate_init.c b/target-ppc/translate_init.c
index 6fe4168..fba2b42 100644
--- a/target-ppc/translate_init.c
+++ b/target-ppc/translate_init.c
@@ -27,7 +27,7 @@
 #include "gdbstub.h"
 #include <kvm.h>
 #include "kvm_ppc.h"
-#include "qmp-commands.h"
+#include "arch_init.h"
 
 //#define PPC_DUMP_CPU
 //#define PPC_DEBUG_SPR
@@ -10346,7 +10346,7 @@ void ppc_cpu_list (FILE *f, fprintf_function cpu_fprintf)
     }
 }
 
-CpuDefinitionInfoList *qmp_query_cpu_definitions(Error **errp)
+CpuDefinitionInfoList *arch_query_cpu_definitions(Error **errp)
 {
     CpuDefinitionInfoList *cpu_list = NULL;
     int i;
commit d1186a33efa74c91b01e1b5d9918c61d109f1b54
Merge: fdef621... c3594ed...
Author: Anthony Liguori <aliguori at us.ibm.com>
Date:   Wed Aug 15 13:25:54 2012 -0500

    Merge remote-tracking branch 'stefanha/trivial-patches' into staging
    
    * stefanha/trivial-patches:
      ivshmem, qdev-monitor: fix order of qerror parameters
      iov_send_recv(): Handle zero bytes case even if OS does not
      framebuffer: Fix spelling in comment (leight -> height)
      Spelling fix in comment (peripherans -> peripherals)
      docs: Fix spelling (propery -> property)
      trace: Fix "Qemu" -> "QEMU"
      cputlb.c: Fix out of date comment
      ehci: fix assertion typo
      Makefile: Avoid explicit list of directories in clean target

commit fdef621b5810cf8d6715e04d883a0f3523873014
Merge: cc92186... 58c8cce...
Author: Anthony Liguori <aliguori at us.ibm.com>
Date:   Wed Aug 15 13:25:47 2012 -0500

    Merge remote-tracking branch 'kwolf/for-anthony' into staging
    
    * kwolf/for-anthony:
      qemu-iotests: Fix 030 after switch to GenericError
      block: Flush parent to OS with cache=unsafe
      iscsi: Fix NULL dereferences / races between task completion and abort
      monitor: Clean up fd sets on monitor disconnect
      block: Enable qemu_open/close to work with fd sets
      block: Convert close calls to qemu_close
      block: Convert open calls to qemu_open
      block: Prevent detection of /dev/fdset/ as floppy
      qapi: Introduce add-fd, remove-fd, query-fdsets
      qemu-char: Add MSG_CMSG_CLOEXEC flag to recvmsg

commit 3e77223293bcb9277f7b760b88f694f097f29c33
Author: Bharat Bhushan <r65777 at freescale.com>
Date:   Tue Aug 14 04:30:55 2012 +0000

    openpic: Added BRR1 register
    
    Linux mpic driver uses (changes may be in pipeline to get upstreamed soon)
    BRR1. This patch adds the support to emulate readonly FSL BRR1 register.
    
    Currently QEMU does not fully emulate any version on MPIC, so the MPIC
    Major number and Minor number are set to 0.
    
    Signed-off-by: Bharat Bhushan <bharat.bhushan at freescale.com>
    Signed-off-by: Alexander Graf <agraf at suse.de>

diff --git a/hw/openpic.c b/hw/openpic.c
index 58ef871..b9d8568 100644
--- a/hw/openpic.c
+++ b/hw/openpic.c
@@ -130,6 +130,17 @@ enum {
 #define MPIC_CPU_REG_START        0x20000
 #define MPIC_CPU_REG_SIZE         0x100 + ((MAX_CPU - 1) * 0x1000)
 
+/*
+ * Block Revision Register1 (BRR1): QEMU does not fully emulate
+ * any version on MPIC. So to start with, set the IP version to 0.
+ *
+ * NOTE: This is Freescale MPIC specific register. Keep it here till
+ * this code is refactored for different variants of OPENPIC and MPIC.
+ */
+#define FSL_BRR1_IPID (0x0040 << 16) /* 16 bit IP-block ID */
+#define FSL_BRR1_IPMJ (0x00 << 8) /* 8 bit IP major number */
+#define FSL_BRR1_IPMN 0x00 /* 8 bit IP minor number */
+
 enum mpic_ide_bits {
     IDR_EP     = 31,
     IDR_CI0     = 30,
@@ -595,6 +606,8 @@ static void openpic_gbl_write (void *opaque, target_phys_addr_t addr, uint32_t v
     if (addr & 0xF)
         return;
     switch (addr) {
+    case 0x00: /* Block Revision Register1 (BRR1) is Readonly */
+        break;
     case 0x40:
     case 0x50:
     case 0x60:
@@ -671,6 +684,7 @@ static uint32_t openpic_gbl_read (void *opaque, target_phys_addr_t addr)
     case 0x1090: /* PINT */
         retval = 0x00000000;
         break;
+    case 0x00: /* Block Revision Register1 (BRR1) */
     case 0x40:
     case 0x50:
     case 0x60:
@@ -893,6 +907,9 @@ static uint32_t openpic_cpu_read_internal(void *opaque, target_phys_addr_t addr,
     dst = &opp->dst[idx];
     addr &= 0xFF0;
     switch (addr) {
+    case 0x00: /* Block Revision Register1 (BRR1) */
+        retval = FSL_BRR1_IPID | FSL_BRR1_IPMJ | FSL_BRR1_IPMN;
+        break;
     case 0x80: /* PCTP */
         retval = dst->pctp;
         break;
commit 4504068723bcf9a3b37f6683d87711b6c5e4c0c3
Author: David Gibson <david at gibson.dropbear.id.au>
Date:   Tue Aug 7 16:10:39 2012 +0000

    pseries: Update SLOF firmware image
    
    This updates SLOF to handle the necessary device tree properties for MSI
    and MSI-X.
    
    Signed-off-by: David Gibson <david at gibson.dropbear.id.au>
    Signed-off-by: Alexander Graf <agraf at suse.de>

diff --git a/pc-bios/README b/pc-bios/README
index e71bcd0..f4b37d6 100644
--- a/pc-bios/README
+++ b/pc-bios/README
@@ -17,7 +17,7 @@
 - SLOF (Slimline Open Firmware) is a free IEEE 1275 Open Firmware
   implementation for certain IBM POWER hardware.  The sources are at
   https://github.com/dgibson/SLOF, and the image currently in qemu is
-  built from git tag qemu-slof-20120719.
+  built from git tag qemu-slof-20120731.
 
 - sgabios (the Serial Graphics Adapter option ROM) provides a means for
   legacy x86 software to communicate with an attached serial console as
diff --git a/pc-bios/slof.bin b/pc-bios/slof.bin
index 320b8f0..84ba6b8 100644
Binary files a/pc-bios/slof.bin and b/pc-bios/slof.bin differ
diff --git a/roms/SLOF b/roms/SLOF
index 7279655..f21f7a3 160000
--- a/roms/SLOF
+++ b/roms/SLOF
@@ -1 +1 @@
-Subproject commit 7279655af2eba855bd2df61303d25abd1eeb2300
+Subproject commit f21f7a3f46b557eb5923f899ce8b4401b3cc6d91
commit 5c4cbcf26ca9465a36fc0661b4103d55897e1a19
Author: Alexey Kardashevskiy <aik at ozlabs.ru>
Date:   Tue Aug 7 16:10:38 2012 +0000

    pseries dma: DMA window params added to PHB and DT population changed
    
    Previously the only PCI bus supported was the emulated PCI bus with
    fixed DMA window with start at 0 and size 1GB. As we are going to support
    PCI pass through which DMA window properties are set by the host
    kernel, we have to support DMA windows with parameters other than default.
    
    This patch adds:
    
    1. DMA window properties to sPAPRPHBState: LIOBN (bus id), start,
    size of the window.
    
    2. An additional function spapr_dma_dt() to populate DMA window
    properties in the device tree which simply accepts all the parameters
    and does not try to guess what kind of IOMMU is given to it.
    The original spapr_dma_dt() is renamed to spapr_tcet_dma_dt().
    
    Signed-off-by: Alexey Kardashevskiy <aik at ozlabs.ru>
    Signed-off-by: David Gibson <david at gibson.dropbear.id.au>
    Signed-off-by: Alexander Graf <agraf at suse.de>

diff --git a/hw/spapr.h b/hw/spapr.h
index 6229769..ac34a17 100644
--- a/hw/spapr.h
+++ b/hw/spapr.h
@@ -337,6 +337,8 @@ void spapr_iommu_init(void);
 DMAContext *spapr_tce_new_dma_context(uint32_t liobn, size_t window_size);
 void spapr_tce_free(DMAContext *dma);
 int spapr_dma_dt(void *fdt, int node_off, const char *propname,
-                 DMAContext *dma);
+                 uint32_t liobn, uint64_t window, uint32_t size);
+int spapr_tcet_dma_dt(void *fdt, int node_off, const char *propname,
+                      DMAContext *dma);
 
 #endif /* !defined (__HW_SPAPR_H__) */
diff --git a/hw/spapr_iommu.c b/hw/spapr_iommu.c
index 388ffa4..53b7317 100644
--- a/hw/spapr_iommu.c
+++ b/hw/spapr_iommu.c
@@ -216,31 +216,47 @@ void spapr_iommu_init(void)
 }
 
 int spapr_dma_dt(void *fdt, int node_off, const char *propname,
-                 DMAContext *dma)
+                 uint32_t liobn, uint64_t window, uint32_t size)
 {
-    if (dma) {
-        sPAPRTCETable *tcet = DO_UPCAST(sPAPRTCETable, dma, dma);
-        uint32_t dma_prop[] = {cpu_to_be32(tcet->liobn),
-                               0, 0,
-                               0, cpu_to_be32(tcet->window_size)};
-        int ret;
-
-        ret = fdt_setprop_cell(fdt, node_off, "ibm,#dma-address-cells", 2);
-        if (ret < 0) {
-            return ret;
-        }
+    uint32_t dma_prop[5];
+    int ret;
+
+    dma_prop[0] = cpu_to_be32(liobn);
+    dma_prop[1] = cpu_to_be32(window >> 32);
+    dma_prop[2] = cpu_to_be32(window & 0xFFFFFFFF);
+    dma_prop[3] = 0; /* window size is 32 bits */
+    dma_prop[4] = cpu_to_be32(size);
+
+    ret = fdt_setprop_cell(fdt, node_off, "ibm,#dma-address-cells", 2);
+    if (ret < 0) {
+        return ret;
+    }
 
-        ret = fdt_setprop_cell(fdt, node_off, "ibm,#dma-size-cells", 2);
-        if (ret < 0) {
-            return ret;
-        }
+    ret = fdt_setprop_cell(fdt, node_off, "ibm,#dma-size-cells", 2);
+    if (ret < 0) {
+        return ret;
+    }
 
-        ret = fdt_setprop(fdt, node_off, propname, dma_prop,
-                          sizeof(dma_prop));
-        if (ret < 0) {
-            return ret;
-        }
+    ret = fdt_setprop(fdt, node_off, propname, dma_prop, sizeof(dma_prop));
+    if (ret < 0) {
+        return ret;
     }
 
     return 0;
 }
+
+int spapr_tcet_dma_dt(void *fdt, int node_off, const char *propname,
+                      DMAContext *iommu)
+{
+    if (!iommu) {
+        return 0;
+    }
+
+    if (iommu->translate == spapr_tce_translate) {
+        sPAPRTCETable *tcet = DO_UPCAST(sPAPRTCETable, dma, iommu);
+        return spapr_dma_dt(fdt, node_off, propname,
+                tcet->liobn, 0, tcet->window_size);
+    }
+
+    return -1;
+}
diff --git a/hw/spapr_pci.c b/hw/spapr_pci.c
index 780a4d6..b92583a 100644
--- a/hw/spapr_pci.c
+++ b/hw/spapr_pci.c
@@ -518,7 +518,6 @@ static int spapr_phb_init(SysBusDevice *s)
     char *namebuf;
     int i;
     PCIBus *bus;
-    uint32_t liobn;
 
     phb->dtbusname = g_strdup_printf("pci@%" PRIx64, phb->buid);
     namebuf = alloca(strlen(phb->dtbusname) + 32);
@@ -570,8 +569,10 @@ static int spapr_phb_init(SysBusDevice *s)
                            PCI_DEVFN(0, 0), PCI_NUM_PINS);
     phb->host_state.bus = bus;
 
-    liobn = SPAPR_PCI_BASE_LIOBN | (pci_find_domain(bus) << 16);
-    phb->dma = spapr_tce_new_dma_context(liobn, 0x40000000);
+    phb->dma_liobn = SPAPR_PCI_BASE_LIOBN | (pci_find_domain(bus) << 16);
+    phb->dma_window_start = 0;
+    phb->dma_window_size = 0x40000000;
+    phb->dma = spapr_tce_new_dma_context(phb->dma_liobn, phb->dma_window_size);
     pci_setup_iommu(bus, spapr_pci_dma_context_fn, phb);
 
     QLIST_INSERT_HEAD(&spapr->phbs, phb, list);
@@ -729,7 +730,9 @@ int spapr_populate_pci_dt(sPAPRPHBState *phb,
     _FDT(fdt_setprop(fdt, bus_off, "interrupt-map", &interrupt_map,
                      sizeof(interrupt_map)));
 
-    spapr_dma_dt(fdt, bus_off, "ibm,dma-window", phb->dma);
+    spapr_dma_dt(fdt, bus_off, "ibm,dma-window",
+                 phb->dma_liobn, phb->dma_window_start,
+                 phb->dma_window_size);
 
     return 0;
 }
diff --git a/hw/spapr_pci.h b/hw/spapr_pci.h
index 6892e4f..7518899 100644
--- a/hw/spapr_pci.h
+++ b/hw/spapr_pci.h
@@ -41,7 +41,9 @@ typedef struct sPAPRPHBState {
     target_phys_addr_t msi_win_addr;
     MemoryRegion memwindow, iowindow, msiwindow;
 
-
+    uint32_t dma_liobn;
+    uint64_t dma_window_start;
+    uint64_t dma_window_size;
     DMAContext *dma;
 
     struct {
diff --git a/hw/spapr_vio.c b/hw/spapr_vio.c
index 3abe853..7ca4452 100644
--- a/hw/spapr_vio.c
+++ b/hw/spapr_vio.c
@@ -142,7 +142,7 @@ static int vio_make_devnode(VIOsPAPRDevice *dev,
         }
     }
 
-    ret = spapr_dma_dt(fdt, node_off, "ibm,my-dma-window", dev->dma);
+    ret = spapr_tcet_dma_dt(fdt, node_off, "ibm,my-dma-window", dev->dma);
     if (ret < 0) {
         return ret;
     }
commit 0ee2c058a3fe485b8901186179102e251a33d082
Author: Alexey Kardashevskiy <aik at ozlabs.ru>
Date:   Tue Aug 7 16:10:37 2012 +0000

    pseries: Add PCI MSI/MSI-X support
    
    This patch implements MSI and MSI-X support for the pseries PCI host
    bridge.  To do this it adds:
    
     * A "config_space_address to msi_table" map, since the MSI RTAS calls
    take a PCI config space address as an identifier.
    
     * A MSIX memory region to catch msi_notify()/msix_notiry() from
    virtio-pci and pass them to the guest via qemu_irq_pulse().
    
     * RTAS call "ibm,change-msi" which sets up MSI vectors for a
    device. Note that this call may configure and return lesser number of
    vectors than requested.
    
     * RTAS call "ibm,query-interrupt-source-number" which translates MSI
    vector to interrupt controller (XICS) IRQ number.
    
    Signed-off-by: Alexey Kardashevskiy <aik at ozlabs.ru>
    Signed-off-by: David Gibson <david at gibson.dropbear.id.au>
    [agraf: fix error case ndev < 0]
    Signed-off-by: Alexander Graf <agraf at suse.de>

diff --git a/hw/spapr.c b/hw/spapr.c
index afbdbc5..5178721 100644
--- a/hw/spapr.c
+++ b/hw/spapr.c
@@ -41,6 +41,7 @@
 #include "hw/spapr_vio.h"
 #include "hw/spapr_pci.h"
 #include "hw/xics.h"
+#include "hw/msi.h"
 
 #include "kvm.h"
 #include "kvm_ppc.h"
@@ -79,6 +80,7 @@
 #define SPAPR_PCI_MEM_WIN_ADDR  (0x10000000000ULL + 0xA0000000)
 #define SPAPR_PCI_MEM_WIN_SIZE  0x20000000
 #define SPAPR_PCI_IO_WIN_ADDR   (0x10000000000ULL + 0x80000000)
+#define SPAPR_PCI_MSI_WIN_ADDR  (0x10000000000ULL + 0x90000000)
 
 #define PHANDLE_XICP            0x00001111
 
@@ -619,6 +621,8 @@ static void ppc_spapr_init(ram_addr_t ram_size,
     long pteg_shift = 17;
     char *filename;
 
+    msi_supported = true;
+
     spapr = g_malloc0(sizeof(*spapr));
     QLIST_INIT(&spapr->phbs);
 
@@ -735,7 +739,8 @@ static void ppc_spapr_init(ram_addr_t ram_size,
     spapr_create_phb(spapr, "pci", SPAPR_PCI_BUID,
                      SPAPR_PCI_MEM_WIN_ADDR,
                      SPAPR_PCI_MEM_WIN_SIZE,
-                     SPAPR_PCI_IO_WIN_ADDR);
+                     SPAPR_PCI_IO_WIN_ADDR,
+                     SPAPR_PCI_MSI_WIN_ADDR);
 
     for (i = 0; i < nb_nics; i++) {
         NICInfo *nd = &nd_table[i];
diff --git a/hw/spapr_pci.c b/hw/spapr_pci.c
index 1eb1a7e..780a4d6 100644
--- a/hw/spapr_pci.c
+++ b/hw/spapr_pci.c
@@ -24,6 +24,8 @@
  */
 #include "hw.h"
 #include "pci.h"
+#include "msi.h"
+#include "msix.h"
 #include "pci_host.h"
 #include "hw/spapr.h"
 #include "hw/spapr_pci.h"
@@ -33,6 +35,17 @@
 
 #include "hw/pci_internals.h"
 
+/* Copied from the kernel arch/powerpc/platforms/pseries/msi.c */
+#define RTAS_QUERY_FN           0
+#define RTAS_CHANGE_FN          1
+#define RTAS_RESET_FN           2
+#define RTAS_CHANGE_MSI_FN      3
+#define RTAS_CHANGE_MSIX_FN     4
+
+/* Interrupt types to return on RTAS_CHANGE_* */
+#define RTAS_TYPE_MSI           1
+#define RTAS_TYPE_MSIX          2
+
 static sPAPRPHBState *find_phb(sPAPREnvironment *spapr, uint64_t buid)
 {
     sPAPRPHBState *phb;
@@ -211,6 +224,191 @@ static void rtas_write_pci_config(sPAPREnvironment *spapr,
     finish_write_pci_config(spapr, 0, addr, size, val, rets);
 }
 
+/*
+ * Find an entry with config_addr or returns the empty one if not found AND
+ * alloc_new is set.
+ * At the moment the msi_table entries are never released so there is
+ * no point to look till the end of the list if we need to find the free entry.
+ */
+static int spapr_msicfg_find(sPAPRPHBState *phb, uint32_t config_addr,
+                             bool alloc_new)
+{
+    int i;
+
+    for (i = 0; i < SPAPR_MSIX_MAX_DEVS; ++i) {
+        if (!phb->msi_table[i].nvec) {
+            break;
+        }
+        if (phb->msi_table[i].config_addr == config_addr) {
+            return i;
+        }
+    }
+    if ((i < SPAPR_MSIX_MAX_DEVS) && alloc_new) {
+        trace_spapr_pci_msi("Allocating new MSI config", i, config_addr);
+        return i;
+    }
+
+    return -1;
+}
+
+/*
+ * Set MSI/MSIX message data.
+ * This is required for msi_notify()/msix_notify() which
+ * will write at the addresses via spapr_msi_write().
+ */
+static void spapr_msi_setmsg(PCIDevice *pdev, target_phys_addr_t addr,
+                             bool msix, unsigned req_num)
+{
+    unsigned i;
+    MSIMessage msg = { .address = addr, .data = 0 };
+
+    if (!msix) {
+        msi_set_message(pdev, msg);
+        trace_spapr_pci_msi_setup(pdev->name, 0, msg.address);
+        return;
+    }
+
+    for (i = 0; i < req_num; ++i) {
+        msg.address = addr | (i << 2);
+        msix_set_message(pdev, i, msg);
+        trace_spapr_pci_msi_setup(pdev->name, i, msg.address);
+    }
+}
+
+static void rtas_ibm_change_msi(sPAPREnvironment *spapr,
+                                uint32_t token, uint32_t nargs,
+                                target_ulong args, uint32_t nret,
+                                target_ulong rets)
+{
+    uint32_t config_addr = rtas_ld(args, 0);
+    uint64_t buid = ((uint64_t)rtas_ld(args, 1) << 32) | rtas_ld(args, 2);
+    unsigned int func = rtas_ld(args, 3);
+    unsigned int req_num = rtas_ld(args, 4); /* 0 == remove all */
+    unsigned int seq_num = rtas_ld(args, 5);
+    unsigned int ret_intr_type;
+    int ndev, irq;
+    sPAPRPHBState *phb = NULL;
+    PCIDevice *pdev = NULL;
+
+    switch (func) {
+    case RTAS_CHANGE_MSI_FN:
+    case RTAS_CHANGE_FN:
+        ret_intr_type = RTAS_TYPE_MSI;
+        break;
+    case RTAS_CHANGE_MSIX_FN:
+        ret_intr_type = RTAS_TYPE_MSIX;
+        break;
+    default:
+        fprintf(stderr, "rtas_ibm_change_msi(%u) is not implemented\n", func);
+        rtas_st(rets, 0, -3); /* Parameter error */
+        return;
+    }
+
+    /* Fins sPAPRPHBState */
+    phb = find_phb(spapr, buid);
+    if (phb) {
+        pdev = find_dev(spapr, buid, config_addr);
+    }
+    if (!phb || !pdev) {
+        rtas_st(rets, 0, -3); /* Parameter error */
+        return;
+    }
+
+    /* Releasing MSIs */
+    if (!req_num) {
+        ndev = spapr_msicfg_find(phb, config_addr, false);
+        if (ndev < 0) {
+            trace_spapr_pci_msi("MSI has not been enabled", -1, config_addr);
+            rtas_st(rets, 0, -1); /* Hardware error */
+            return;
+        }
+        trace_spapr_pci_msi("Released MSIs", ndev, config_addr);
+        rtas_st(rets, 0, 0);
+        rtas_st(rets, 1, 0);
+        return;
+    }
+
+    /* Enabling MSI */
+
+    /* Find a device number in the map to add or reuse the existing one */
+    ndev = spapr_msicfg_find(phb, config_addr, true);
+    if (ndev >= SPAPR_MSIX_MAX_DEVS || ndev < 0) {
+        fprintf(stderr, "No free entry for a new MSI device\n");
+        rtas_st(rets, 0, -1); /* Hardware error */
+        return;
+    }
+    trace_spapr_pci_msi("Configuring MSI", ndev, config_addr);
+
+    /* Check if there is an old config and MSI number has not changed */
+    if (phb->msi_table[ndev].nvec && (req_num != phb->msi_table[ndev].nvec)) {
+        /* Unexpected behaviour */
+        fprintf(stderr, "Cannot reuse MSI config for device#%d", ndev);
+        rtas_st(rets, 0, -1); /* Hardware error */
+        return;
+    }
+
+    /* There is no cached config, allocate MSIs */
+    if (!phb->msi_table[ndev].nvec) {
+        irq = spapr_allocate_irq_block(req_num, XICS_MSI);
+        if (irq < 0) {
+            fprintf(stderr, "Cannot allocate MSIs for device#%d", ndev);
+            rtas_st(rets, 0, -1); /* Hardware error */
+            return;
+        }
+        phb->msi_table[ndev].irq = irq;
+        phb->msi_table[ndev].nvec = req_num;
+        phb->msi_table[ndev].config_addr = config_addr;
+    }
+
+    /* Setup MSI/MSIX vectors in the device (via cfgspace or MSIX BAR) */
+    spapr_msi_setmsg(pdev, phb->msi_win_addr | (ndev << 16),
+                     ret_intr_type == RTAS_TYPE_MSIX, req_num);
+
+    rtas_st(rets, 0, 0);
+    rtas_st(rets, 1, req_num);
+    rtas_st(rets, 2, ++seq_num);
+    rtas_st(rets, 3, ret_intr_type);
+
+    trace_spapr_pci_rtas_ibm_change_msi(func, req_num);
+}
+
+static void rtas_ibm_query_interrupt_source_number(sPAPREnvironment *spapr,
+                                                   uint32_t token,
+                                                   uint32_t nargs,
+                                                   target_ulong args,
+                                                   uint32_t nret,
+                                                   target_ulong rets)
+{
+    uint32_t config_addr = rtas_ld(args, 0);
+    uint64_t buid = ((uint64_t)rtas_ld(args, 1) << 32) | rtas_ld(args, 2);
+    unsigned int intr_src_num = -1, ioa_intr_num = rtas_ld(args, 3);
+    int ndev;
+    sPAPRPHBState *phb = NULL;
+
+    /* Fins sPAPRPHBState */
+    phb = find_phb(spapr, buid);
+    if (!phb) {
+        rtas_st(rets, 0, -3); /* Parameter error */
+        return;
+    }
+
+    /* Find device descriptor and start IRQ */
+    ndev = spapr_msicfg_find(phb, config_addr, false);
+    if (ndev < 0) {
+        trace_spapr_pci_msi("MSI has not been enabled", -1, config_addr);
+        rtas_st(rets, 0, -1); /* Hardware error */
+        return;
+    }
+
+    intr_src_num = phb->msi_table[ndev].irq + ioa_intr_num;
+    trace_spapr_pci_rtas_ibm_query_interrupt_source_number(ioa_intr_num,
+                                                           intr_src_num);
+
+    rtas_st(rets, 0, 0);
+    rtas_st(rets, 1, intr_src_num);
+    rtas_st(rets, 2, 1);/* 0 == level; 1 == edge */
+}
+
 static int pci_spapr_swizzle(int slot, int pin)
 {
     return (slot + pin) % PCI_NUM_PINS;
@@ -277,6 +475,33 @@ static const MemoryRegionOps spapr_io_ops = {
 };
 
 /*
+ * MSI/MSIX memory region implementation.
+ * The handler handles both MSI and MSIX.
+ * For MSI-X, the vector number is encoded as a part of the address,
+ * data is set to 0.
+ * For MSI, the vector number is encoded in least bits in data.
+ */
+static void spapr_msi_write(void *opaque, target_phys_addr_t addr,
+                            uint64_t data, unsigned size)
+{
+    sPAPRPHBState *phb = opaque;
+    int ndev = addr >> 16;
+    int vec = ((addr & 0xFFFF) >> 2) | data;
+    uint32_t irq = phb->msi_table[ndev].irq + vec;
+
+    trace_spapr_pci_msi_write(addr, data, irq);
+
+    qemu_irq_pulse(xics_get_qirq(spapr->icp, irq));
+}
+
+static const MemoryRegionOps spapr_msi_ops = {
+    /* There is no .read as the read result is undefined by PCI spec */
+    .read = NULL,
+    .write = spapr_msi_write,
+    .endianness = DEVICE_LITTLE_ENDIAN
+};
+
+/*
  * PHB PCI device
  */
 static DMAContext *spapr_pci_dma_context_fn(PCIBus *bus, void *opaque,
@@ -327,6 +552,17 @@ static int spapr_phb_init(SysBusDevice *s)
     memory_region_add_subregion(get_system_memory(), phb->io_win_addr,
                                 &phb->iowindow);
 
+    /* As MSI/MSIX interrupts trigger by writing at MSI/MSIX vectors,
+     * we need to allocate some memory to catch those writes coming
+     * from msi_notify()/msix_notify() */
+    if (msi_supported) {
+        sprintf(namebuf, "%s.msi", phb->dtbusname);
+        memory_region_init_io(&phb->msiwindow, &spapr_msi_ops, phb,
+                              namebuf, SPAPR_MSIX_MAX_DEVS * 0x10000);
+        memory_region_add_subregion(get_system_memory(), phb->msi_win_addr,
+                                    &phb->msiwindow);
+    }
+
     bus = pci_register_bus(&phb->host_state.busdev.qdev,
                            phb->busname ? phb->busname : phb->dtbusname,
                            pci_spapr_set_irq, pci_spapr_map_irq, phb,
@@ -362,6 +598,7 @@ static Property spapr_phb_properties[] = {
     DEFINE_PROP_HEX64("mem_win_size", sPAPRPHBState, mem_win_size, 0x20000000),
     DEFINE_PROP_HEX64("io_win_addr", sPAPRPHBState, io_win_addr, 0),
     DEFINE_PROP_HEX64("io_win_size", sPAPRPHBState, io_win_size, 0x10000),
+    DEFINE_PROP_HEX64("msi_win_addr", sPAPRPHBState, msi_win_addr, 0),
     DEFINE_PROP_END_OF_LIST(),
 };
 
@@ -384,7 +621,7 @@ static TypeInfo spapr_phb_info = {
 void spapr_create_phb(sPAPREnvironment *spapr,
                       const char *busname, uint64_t buid,
                       uint64_t mem_win_addr, uint64_t mem_win_size,
-                      uint64_t io_win_addr)
+                      uint64_t io_win_addr, uint64_t msi_win_addr)
 {
     DeviceState *dev;
 
@@ -397,6 +634,7 @@ void spapr_create_phb(sPAPREnvironment *spapr,
     qdev_prop_set_uint64(dev, "mem_win_addr", mem_win_addr);
     qdev_prop_set_uint64(dev, "mem_win_size", mem_win_size);
     qdev_prop_set_uint64(dev, "io_win_addr", io_win_addr);
+    qdev_prop_set_uint64(dev, "msi_win_addr", msi_win_addr);
 
     qdev_init_nofail(dev);
 }
@@ -502,6 +740,11 @@ void spapr_pci_rtas_init(void)
     spapr_rtas_register("write-pci-config", rtas_write_pci_config);
     spapr_rtas_register("ibm,read-pci-config", rtas_ibm_read_pci_config);
     spapr_rtas_register("ibm,write-pci-config", rtas_ibm_write_pci_config);
+    if (msi_supported) {
+        spapr_rtas_register("ibm,query-interrupt-source-number",
+                            rtas_ibm_query_interrupt_source_number);
+        spapr_rtas_register("ibm,change-msi", rtas_ibm_change_msi);
+    }
 }
 
 static void register_types(void)
diff --git a/hw/spapr_pci.h b/hw/spapr_pci.h
index 2aee67f..6892e4f 100644
--- a/hw/spapr_pci.h
+++ b/hw/spapr_pci.h
@@ -27,6 +27,8 @@
 #include "hw/pci_host.h"
 #include "hw/xics.h"
 
+#define SPAPR_MSIX_MAX_DEVS 32
+
 typedef struct sPAPRPHBState {
     PCIHostState host_state;
 
@@ -36,13 +38,22 @@ typedef struct sPAPRPHBState {
 
     MemoryRegion memspace, iospace;
     target_phys_addr_t mem_win_addr, mem_win_size, io_win_addr, io_win_size;
-    MemoryRegion memwindow, iowindow;
+    target_phys_addr_t msi_win_addr;
+    MemoryRegion memwindow, iowindow, msiwindow;
+
+
     DMAContext *dma;
 
     struct {
         uint32_t irq;
     } lsi_table[PCI_NUM_PINS];
 
+    struct {
+        uint32_t config_addr;
+        uint32_t irq;
+        int nvec;
+    } msi_table[SPAPR_MSIX_MAX_DEVS];
+
     QLIST_ENTRY(sPAPRPHBState) list;
 } sPAPRPHBState;
 
@@ -57,7 +68,7 @@ static inline qemu_irq spapr_phb_lsi_qirq(struct sPAPRPHBState *phb, int pin)
 void spapr_create_phb(sPAPREnvironment *spapr,
                       const char *busname, uint64_t buid,
                       uint64_t mem_win_addr, uint64_t mem_win_size,
-                      uint64_t io_win_addr);
+                      uint64_t io_win_addr, uint64_t msi_win_addr);
 
 int spapr_populate_pci_dt(sPAPRPHBState *phb,
                           uint32_t xics_phandle,
diff --git a/trace-events b/trace-events
index 191b39e..04b0723 100644
--- a/trace-events
+++ b/trace-events
@@ -972,4 +972,9 @@ qxl_render_guest_primary_resized(int32_t width, int32_t height, int32_t stride,
 qxl_render_update_area_done(void *cookie) "%p"
 
 # hw/spapr_pci.c
+spapr_pci_msi(const char *msg, uint32_t n, uint32_t ca) "%s (device#%d, cfg=%x)"
+spapr_pci_msi_setup(const char *name, unsigned vector, uint64_t addr) "dev\"%s\" vector %u, addr=%"PRIx64
+spapr_pci_rtas_ibm_change_msi(unsigned func, unsigned req) "func %u, requested %u"
+spapr_pci_rtas_ibm_query_interrupt_source_number(unsigned ioa, unsigned intr) "queries for #%u, IRQ%u"
+spapr_pci_msi_write(uint64_t addr, uint64_t data, uint32_t dt_irq) "@%"PRIx64"<=%"PRIx64" IRQ %u"
 spapr_pci_lsi_set(const char *busname, int pin, uint32_t irq) "%s PIN%d IRQ %u"
commit a2950fb6e795e3e10fed35d347a7aa28a44be2ff
Author: Alexey Kardashevskiy <aik at ozlabs.ru>
Date:   Tue Aug 7 16:10:36 2012 +0000

    pseries: Add trace event for PCI irqs
    
    This adds a trace event in the pseries PCI specific set_irq() function to
    assist in debugging.
    
    Signed-off-by: Alexey Kardashevskiy <aik at ozlabs.ru>
    Signed-off-by: David Gibson <david at gibson.dropbear.id.au>
    [agraf: add trace.h include]
    Signed-off-by: Alexander Graf <agraf at suse.de>

diff --git a/hw/spapr_pci.c b/hw/spapr_pci.c
index 2e38fee..1eb1a7e 100644
--- a/hw/spapr_pci.c
+++ b/hw/spapr_pci.c
@@ -29,6 +29,7 @@
 #include "hw/spapr_pci.h"
 #include "exec-memory.h"
 #include <libfdt.h>
+#include "trace.h"
 
 #include "hw/pci_internals.h"
 
@@ -234,6 +235,7 @@ static void pci_spapr_set_irq(void *opaque, int irq_num, int level)
      */
     sPAPRPHBState *phb = opaque;
 
+    trace_spapr_pci_lsi_set(phb->busname, irq_num, phb->lsi_table[irq_num].irq);
     qemu_set_irq(spapr_phb_lsi_qirq(phb, irq_num), level);
 }
 
diff --git a/trace-events b/trace-events
index 6b12f83..191b39e 100644
--- a/trace-events
+++ b/trace-events
@@ -970,3 +970,6 @@ qxl_render_blit_guest_primary_initialized(void) ""
 qxl_render_blit(int32_t stride, int32_t left, int32_t right, int32_t top, int32_t bottom) "stride=%d [%d, %d, %d, %d]"
 qxl_render_guest_primary_resized(int32_t width, int32_t height, int32_t stride, int32_t bytes_pp, int32_t bits_pp) "%dx%d, stride %d, bpp %d, depth %d"
 qxl_render_update_area_done(void *cookie) "%p"
+
+# hw/spapr_pci.c
+spapr_pci_lsi_set(const char *busname, int pin, uint32_t irq) "%s PIN%d IRQ %u"
commit 9894c5d4b467d24e281c22f2f5e24822c9b55fb3
Author: Alexey Kardashevskiy <aik at ozlabs.ru>
Date:   Tue Aug 7 16:10:35 2012 +0000

    pseries: Export find_phb() utility function for PCI code
    
    The pseries PCI code makes use of an internal find_dev() function which
    locates a PCIDevice * given a (platform specific) bus ID and device
    address.  Internally this needs to first locate the host bridge on which
    the device resides based on the bus ID.  This patch exposes that host
    bridge lookup as a separate function, which we will need later in the MSI
    and VFIO code.
    
    Signed-off-by: Alexey Kardashevskiy <aik at ozlabs.ru>
    Signed-off-by: David Gibson <david at gibson.dropbear.id.au>
    [agraf: drop trace.h inclusion]
    Signed-off-by: Alexander Graf <agraf at suse.de>

diff --git a/hw/spapr_pci.c b/hw/spapr_pci.c
index fcc358e..2e38fee 100644
--- a/hw/spapr_pci.c
+++ b/hw/spapr_pci.c
@@ -32,24 +32,35 @@
 
 #include "hw/pci_internals.h"
 
-static PCIDevice *find_dev(sPAPREnvironment *spapr,
-                           uint64_t buid, uint32_t config_addr)
+static sPAPRPHBState *find_phb(sPAPREnvironment *spapr, uint64_t buid)
 {
-    int devfn = (config_addr >> 8) & 0xFF;
     sPAPRPHBState *phb;
 
     QLIST_FOREACH(phb, &spapr->phbs, list) {
-        BusChild *kid;
-
         if (phb->buid != buid) {
             continue;
         }
+        return phb;
+    }
+
+    return NULL;
+}
+
+static PCIDevice *find_dev(sPAPREnvironment *spapr, uint64_t buid,
+                           uint32_t config_addr)
+{
+    sPAPRPHBState *phb = find_phb(spapr, buid);
+    BusChild *kid;
+    int devfn = (config_addr >> 8) & 0xFF;
+
+    if (!phb) {
+        return NULL;
+    }
 
-        QTAILQ_FOREACH(kid, &phb->host_state.bus->qbus.children, sibling) {
-            PCIDevice *dev = (PCIDevice *)kid->child;
-            if (dev->devfn == devfn) {
-                return dev;
-            }
+    QTAILQ_FOREACH(kid, &phb->host_state.bus->qbus.children, sibling) {
+        PCIDevice *dev = (PCIDevice *)kid->child;
+        if (dev->devfn == devfn) {
+            return dev;
         }
     }
 
commit f4b9523ba6388f6f951933de3f9a76e2e9ea2ede
Author: Alexey Kardashevskiy <aik at ozlabs.ru>
Date:   Tue Aug 7 16:10:34 2012 +0000

    pseries: added allocator for a block of IRQs
    
    The patch adds a simple helper which allocates a consecutive sequence
    of IRQs calling spapr_allocate_irq for each and checks that allocated
    IRQs go consequently.
    
    The patch is required for upcoming support of MSI/MSIX on POWER.
    
    Signed-off-by: Alexey Kardashevskiy <aik at ozlabs.ru>
    Signed-off-by: David Gibson <david at gibson.dropbear.id.au>
    Signed-off-by: Alexander Graf <agraf at suse.de>

diff --git a/hw/spapr.c b/hw/spapr.c
index 8153c05..afbdbc5 100644
--- a/hw/spapr.c
+++ b/hw/spapr.c
@@ -105,6 +105,32 @@ int spapr_allocate_irq(int hint, enum xics_irq_type type)
     return irq;
 }
 
+/* Allocate block of consequtive IRQs, returns a number of the first */
+int spapr_allocate_irq_block(int num, enum xics_irq_type type)
+{
+    int first = -1;
+    int i;
+
+    for (i = 0; i < num; ++i) {
+        int irq;
+
+        irq = spapr_allocate_irq(0, type);
+        if (!irq) {
+            return -1;
+        }
+
+        if (0 == i) {
+            first = irq;
+        }
+
+        /* If the above doesn't create a consecutive block then that's
+         * an internal bug */
+        assert(irq == (first + i));
+    }
+
+    return first;
+}
+
 static int spapr_set_associativity(void *fdt, sPAPREnvironment *spapr)
 {
     int ret = 0, offset;
diff --git a/hw/spapr.h b/hw/spapr.h
index b5cf6af..6229769 100644
--- a/hw/spapr.h
+++ b/hw/spapr.h
@@ -290,6 +290,7 @@ target_ulong spapr_hypercall(CPUPPCState *env, target_ulong opcode,
                              target_ulong *args);
 
 int spapr_allocate_irq(int hint, enum xics_irq_type type);
+int spapr_allocate_irq_block(int num, enum xics_irq_type type);
 
 static inline int spapr_allocate_msi(int hint)
 {
commit fa28f71b4a88cdb796f1e0a308205c6be604d3f3
Author: Alexey Kardashevskiy <aik at ozlabs.ru>
Date:   Tue Aug 7 16:10:33 2012 +0000

    pseries: Separate PCI RTAS setup from common from emulation specific PCI setup
    
    Currently the RTAS functions for handling PCI are registered from the
    class init code for the PCI host bridge.  That sort of makes sense
    now, but will break in the future when vfio gives us multiple types of
    host bridge for pseries (emulated and pass-through, at least).  The
    RTAS functions will be common across all host bridge types (and will
    call out to different places internally depending on the type).
    
    So, this patch moves the RTAS registration into its own function
    called direct from the machine setup code.
    
    Signed-off-by: Alexey Kardashevskiy <aik at ozlabs.ru>
    Signed-off-by: David Gibson <david at gibson.dropbear.id.au>
    Signed-off-by: Alexander Graf <agraf at suse.de>

diff --git a/hw/spapr.c b/hw/spapr.c
index 40bb6d3..8153c05 100644
--- a/hw/spapr.c
+++ b/hw/spapr.c
@@ -704,6 +704,8 @@ static void ppc_spapr_init(ram_addr_t ram_size,
     }
 
     /* Set up PCI */
+    spapr_pci_rtas_init();
+
     spapr_create_phb(spapr, "pci", SPAPR_PCI_BUID,
                      SPAPR_PCI_MEM_WIN_ADDR,
                      SPAPR_PCI_MEM_WIN_SIZE,
diff --git a/hw/spapr_pci.c b/hw/spapr_pci.c
index 65ae8c4..fcc358e 100644
--- a/hw/spapr_pci.c
+++ b/hw/spapr_pci.c
@@ -359,11 +359,6 @@ static void spapr_phb_class_init(ObjectClass *klass, void *data)
 
     sdc->init = spapr_phb_init;
     dc->props = spapr_phb_properties;
-
-    spapr_rtas_register("read-pci-config", rtas_read_pci_config);
-    spapr_rtas_register("write-pci-config", rtas_write_pci_config);
-    spapr_rtas_register("ibm,read-pci-config", rtas_ibm_read_pci_config);
-    spapr_rtas_register("ibm,write-pci-config", rtas_ibm_write_pci_config);
 }
 
 static TypeInfo spapr_phb_info = {
@@ -488,6 +483,14 @@ int spapr_populate_pci_dt(sPAPRPHBState *phb,
     return 0;
 }
 
+void spapr_pci_rtas_init(void)
+{
+    spapr_rtas_register("read-pci-config", rtas_read_pci_config);
+    spapr_rtas_register("write-pci-config", rtas_write_pci_config);
+    spapr_rtas_register("ibm,read-pci-config", rtas_ibm_read_pci_config);
+    spapr_rtas_register("ibm,write-pci-config", rtas_ibm_write_pci_config);
+}
+
 static void register_types(void)
 {
     type_register_static(&spapr_phb_info);
diff --git a/hw/spapr_pci.h b/hw/spapr_pci.h
index 6bba885..2aee67f 100644
--- a/hw/spapr_pci.h
+++ b/hw/spapr_pci.h
@@ -63,4 +63,6 @@ int spapr_populate_pci_dt(sPAPRPHBState *phb,
                           uint32_t xics_phandle,
                           void *fdt);
 
+void spapr_pci_rtas_init(void);
+
 #endif /* __HW_SPAPR_PCI_H__ */
commit a307d59434ba78b97544b42b8cfd24a1b62e39a6
Author: Alexey Kardashevskiy <aik at ozlabs.ru>
Date:   Tue Aug 7 16:10:32 2012 +0000

    pseries: Rework irq assignment to avoid carrying qemu_irqs around
    
    Currently, the interfaces in the pseries machine code for assignment
    and setup of interrupts pass around qemu_irq objects.  That was done
    in an attempt not to be too closely linked to the specific XICS
    interrupt controller.  However interactions with the device tree setup
    made that attempt rather futile, and XICS is part of the PAPR spec
    anyway, so this really just meant we had to carry both the qemu_irq
    pointers and the XICS irq numbers around.
    
    This mess will just get worse when we add upcoming PCI MSI support,
    since that will require tracking a bunch more interrupt.  Therefore,
    this patch reworks the spapr code to just use XICS irq numbers
    (roughly equivalent to GSIs on x86) and only retrieve the qemu_irq
    pointers from the XICS code when we need them (a trivial lookup).
    
    This is a reworked and generalized version of an earlier spapr_pci
    specific patch from Alexey Kardashevskiy.
    
    Signed-off-by: Alexey Kardashevskiy <aik at ozlabs.ru>
    Signed-off-by: David Gibson <david at gibson.dropbear.id.au>
    [agraf: fix checkpath warning]
    Signed-off-by: Alexander Graf <agraf at suse.de>

diff --git a/hw/spapr.c b/hw/spapr.c
index 032d259..40bb6d3 100644
--- a/hw/spapr.c
+++ b/hw/spapr.c
@@ -84,11 +84,9 @@
 
 sPAPREnvironment *spapr;
 
-qemu_irq spapr_allocate_irq(uint32_t hint, uint32_t *irq_num,
-                            enum xics_irq_type type)
+int spapr_allocate_irq(int hint, enum xics_irq_type type)
 {
-    uint32_t irq;
-    qemu_irq qirq;
+    int irq;
 
     if (hint) {
         irq = hint;
@@ -97,16 +95,14 @@ qemu_irq spapr_allocate_irq(uint32_t hint, uint32_t *irq_num,
         irq = spapr->next_irq++;
     }
 
-    qirq = xics_assign_irq(spapr->icp, irq, type);
-    if (!qirq) {
-        return NULL;
+    /* Configure irq type */
+    if (!xics_get_qirq(spapr->icp, irq)) {
+        return 0;
     }
 
-    if (irq_num) {
-        *irq_num = irq;
-    }
+    xics_set_irq_type(spapr->icp, irq, type);
 
-    return qirq;
+    return irq;
 }
 
 static int spapr_set_associativity(void *fdt, sPAPREnvironment *spapr)
diff --git a/hw/spapr.h b/hw/spapr.h
index fe40e7d..b5cf6af 100644
--- a/hw/spapr.h
+++ b/hw/spapr.h
@@ -289,17 +289,16 @@ void spapr_register_hypercall(target_ulong opcode, spapr_hcall_fn fn);
 target_ulong spapr_hypercall(CPUPPCState *env, target_ulong opcode,
                              target_ulong *args);
 
-qemu_irq spapr_allocate_irq(uint32_t hint, uint32_t *irq_num,
-                            enum xics_irq_type type);
+int spapr_allocate_irq(int hint, enum xics_irq_type type);
 
-static inline qemu_irq spapr_allocate_msi(uint32_t hint, uint32_t *irq_num)
+static inline int spapr_allocate_msi(int hint)
 {
-    return spapr_allocate_irq(hint, irq_num, XICS_MSI);
+    return spapr_allocate_irq(hint, XICS_MSI);
 }
 
-static inline qemu_irq spapr_allocate_lsi(uint32_t hint, uint32_t *irq_num)
+static inline int spapr_allocate_lsi(int hint)
 {
-    return spapr_allocate_irq(hint, irq_num, XICS_LSI);
+    return spapr_allocate_irq(hint, XICS_LSI);
 }
 
 static inline uint32_t rtas_ld(target_ulong phys, int n)
diff --git a/hw/spapr_llan.c b/hw/spapr_llan.c
index 01e54f3..bd3f131 100644
--- a/hw/spapr_llan.c
+++ b/hw/spapr_llan.c
@@ -169,7 +169,7 @@ static ssize_t spapr_vlan_receive(NetClientState *nc, const uint8_t *buf,
     }
 
     if (sdev->signal_state & 1) {
-        qemu_irq_pulse(sdev->qirq);
+        qemu_irq_pulse(spapr_vio_qirq(sdev));
     }
 
     return size;
diff --git a/hw/spapr_pci.c b/hw/spapr_pci.c
index 2913540..65ae8c4 100644
--- a/hw/spapr_pci.c
+++ b/hw/spapr_pci.c
@@ -223,7 +223,7 @@ static void pci_spapr_set_irq(void *opaque, int irq_num, int level)
      */
     sPAPRPHBState *phb = opaque;
 
-    qemu_set_irq(phb->lsi_table[irq_num].qirq, level);
+    qemu_set_irq(spapr_phb_lsi_qirq(phb, irq_num), level);
 }
 
 static uint64_t spapr_io_read(void *opaque, target_phys_addr_t addr,
@@ -329,16 +329,14 @@ static int spapr_phb_init(SysBusDevice *s)
 
     /* Initialize the LSI table */
     for (i = 0; i < PCI_NUM_PINS; i++) {
-        qemu_irq qirq;
-        uint32_t num;
+        uint32_t irq;
 
-        qirq = spapr_allocate_lsi(0, &num);
-        if (!qirq) {
+        irq = spapr_allocate_lsi(0);
+        if (!irq) {
             return -1;
         }
 
-        phb->lsi_table[i].dt_irq = num;
-        phb->lsi_table[i].qirq = qirq;
+        phb->lsi_table[i].irq = irq;
     }
 
     return 0;
@@ -477,7 +475,7 @@ int spapr_populate_pci_dt(sPAPRPHBState *phb,
             irqmap[2] = 0;
             irqmap[3] = cpu_to_be32(j+1);
             irqmap[4] = cpu_to_be32(xics_phandle);
-            irqmap[5] = cpu_to_be32(phb->lsi_table[lsi_num].dt_irq);
+            irqmap[5] = cpu_to_be32(phb->lsi_table[lsi_num].irq);
             irqmap[6] = cpu_to_be32(0x8);
         }
     }
diff --git a/hw/spapr_pci.h b/hw/spapr_pci.h
index dd66f4b..6bba885 100644
--- a/hw/spapr_pci.h
+++ b/hw/spapr_pci.h
@@ -40,13 +40,17 @@ typedef struct sPAPRPHBState {
     DMAContext *dma;
 
     struct {
-        uint32_t dt_irq;
-        qemu_irq qirq;
+        uint32_t irq;
     } lsi_table[PCI_NUM_PINS];
 
     QLIST_ENTRY(sPAPRPHBState) list;
 } sPAPRPHBState;
 
+static inline qemu_irq spapr_phb_lsi_qirq(struct sPAPRPHBState *phb, int pin)
+{
+    return xics_get_qirq(spapr->icp, phb->lsi_table[pin].irq);
+}
+
 #define SPAPR_PCI_MEM_WIN_BUS_OFFSET 0x80000000ULL
 #define SPAPR_PCI_IO_WIN_SIZE        0x10000
 
diff --git a/hw/spapr_vio.c b/hw/spapr_vio.c
index 05b5503..3abe853 100644
--- a/hw/spapr_vio.c
+++ b/hw/spapr_vio.c
@@ -49,7 +49,7 @@
 #endif
 
 static Property spapr_vio_props[] = {
-    DEFINE_PROP_UINT32("irq", VIOsPAPRDevice, vio_irq_num, 0), \
+    DEFINE_PROP_UINT32("irq", VIOsPAPRDevice, irq, 0), \
     DEFINE_PROP_END_OF_LIST(),
 };
 
@@ -132,8 +132,8 @@ static int vio_make_devnode(VIOsPAPRDevice *dev,
         }
     }
 
-    if (dev->qirq) {
-        uint32_t ints_prop[] = {cpu_to_be32(dev->vio_irq_num), 0};
+    if (dev->irq) {
+        uint32_t ints_prop[] = {cpu_to_be32(dev->irq), 0};
 
         ret = fdt_setprop(fdt, node_off, "interrupts", ints_prop,
                           sizeof(ints_prop));
@@ -306,7 +306,7 @@ int spapr_vio_send_crq(VIOsPAPRDevice *dev, uint8_t *crq)
     dev->crq.qnext = (dev->crq.qnext + 16) % dev->crq.qsize;
 
     if (dev->signal_state & 1) {
-        qemu_irq_pulse(dev->qirq);
+        qemu_irq_pulse(spapr_vio_qirq(dev));
     }
 
     return 0;
@@ -459,8 +459,8 @@ static int spapr_vio_busdev_init(DeviceState *qdev)
         dev->qdev.id = id;
     }
 
-    dev->qirq = spapr_allocate_msi(dev->vio_irq_num, &dev->vio_irq_num);
-    if (!dev->qirq) {
+    dev->irq = spapr_allocate_msi(dev->irq);
+    if (!dev->irq) {
         return -1;
     }
 
diff --git a/hw/spapr_vio.h b/hw/spapr_vio.h
index 6f9a498..ea6aa43 100644
--- a/hw/spapr_vio.h
+++ b/hw/spapr_vio.h
@@ -61,8 +61,7 @@ struct VIOsPAPRDevice {
     DeviceState qdev;
     uint32_t reg;
     uint32_t flags;
-    qemu_irq qirq;
-    uint32_t vio_irq_num;
+    uint32_t irq;
     target_ulong signal_state;
     VIOsPAPR_CRQ crq;
     DMAContext *dma;
@@ -85,6 +84,11 @@ extern int spapr_populate_chosen_stdout(void *fdt, VIOsPAPRBus *bus);
 
 extern int spapr_vio_signal(VIOsPAPRDevice *dev, target_ulong mode);
 
+static inline qemu_irq spapr_vio_qirq(VIOsPAPRDevice *dev)
+{
+    return xics_get_qirq(spapr->icp, dev->irq);
+}
+
 static inline bool spapr_vio_dma_valid(VIOsPAPRDevice *dev, uint64_t taddr,
                                        uint32_t size, DMADirection dir)
 {
diff --git a/hw/spapr_vty.c b/hw/spapr_vty.c
index 99e52cc..5da17a3 100644
--- a/hw/spapr_vty.c
+++ b/hw/spapr_vty.c
@@ -26,7 +26,7 @@ static void vty_receive(void *opaque, const uint8_t *buf, int size)
 
     if ((dev->in == dev->out) && size) {
         /* toggle line to simulate edge interrupt */
-        qemu_irq_pulse(dev->sdev.qirq);
+        qemu_irq_pulse(spapr_vio_qirq(&dev->sdev));
     }
     for (i = 0; i < size; i++) {
         assert((dev->in - dev->out) < VTERM_BUFSIZE);
diff --git a/hw/xics.c b/hw/xics.c
index 668a0d6..b674771 100644
--- a/hw/xics.c
+++ b/hw/xics.c
@@ -315,18 +315,24 @@ static void ics_eoi(struct ics_state *ics, int nr)
  * Exported functions
  */
 
-qemu_irq xics_assign_irq(struct icp_state *icp, int irq,
-                         enum xics_irq_type type)
+qemu_irq xics_get_qirq(struct icp_state *icp, int irq)
 {
     if ((irq < icp->ics->offset)
         || (irq >= (icp->ics->offset + icp->ics->nr_irqs))) {
         return NULL;
     }
 
+    return icp->ics->qirqs[irq - icp->ics->offset];
+}
+
+void xics_set_irq_type(struct icp_state *icp, int irq,
+                       enum xics_irq_type type)
+{
+    assert((irq >= icp->ics->offset)
+           && (irq < (icp->ics->offset + icp->ics->nr_irqs)));
     assert((type == XICS_MSI) || (type == XICS_LSI));
 
     icp->ics->irqs[irq - icp->ics->offset].type = type;
-    return icp->ics->qirqs[irq - icp->ics->offset];
 }
 
 static target_ulong h_cppr(CPUPPCState *env, sPAPREnvironment *spapr,
diff --git a/hw/xics.h b/hw/xics.h
index 2080159..99b96ac 100644
--- a/hw/xics.h
+++ b/hw/xics.h
@@ -36,8 +36,9 @@ enum xics_irq_type {
     XICS_LSI,        /* Level-signalled interrupt */
 };
 
-qemu_irq xics_assign_irq(struct icp_state *icp, int irq,
-                         enum xics_irq_type type);
+qemu_irq xics_get_qirq(struct icp_state *icp, int irq);
+void xics_set_irq_type(struct icp_state *icp, int irq,
+                       enum xics_irq_type type);
 
 struct icp_state *xics_system_init(int nr_irqs);
 
commit c9f709d2e7d9dcc6e6ecbee8d499b4b14b11320b
Author: David Gibson <david at gibson.dropbear.id.au>
Date:   Tue Aug 7 16:10:31 2012 +0000

    pseries: Remove extraneous prints
    
    The pseries machine prints several messages to stderr whenever it starts up
    and another whenever the vm is reset.  It's not normal for qemu machines to
    do this though, so this patch removes them.  We can put them back
    conditional on a DEBUG symbol if we really need them in future.
    
    Signed-off-by: David Gibson <david at gibson.dropbear.id.au>
    Signed-off-by: Alexander Graf <agraf at suse.de>

diff --git a/hw/spapr.c b/hw/spapr.c
index aa39d2d..032d259 100644
--- a/hw/spapr.c
+++ b/hw/spapr.c
@@ -538,8 +538,6 @@ static void spapr_reset(void *opaque)
 {
     sPAPREnvironment *spapr = (sPAPREnvironment *)opaque;
 
-    fprintf(stderr, "sPAPR reset\n");
-
     /* flush out the hash table */
     memset(spapr->htab, 0, spapr->htab_size);
 
@@ -744,14 +742,6 @@ static void ppc_spapr_init(ram_addr_t ram_size,
         exit(1);
     }
 
-    fprintf(stderr, "sPAPR memory map:\n");
-    fprintf(stderr, "RTAS                 : 0x%08lx..%08lx\n",
-            (unsigned long)spapr->rtas_addr,
-            (unsigned long)(spapr->rtas_addr + spapr->rtas_size - 1));
-    fprintf(stderr, "FDT                  : 0x%08lx..%08lx\n",
-            (unsigned long)spapr->fdt_addr,
-            (unsigned long)(spapr->fdt_addr + FDT_MAX_SIZE - 1));
-
     if (kernel_filename) {
         uint64_t lowaddr = 0;
 
@@ -767,8 +757,6 @@ static void ppc_spapr_init(ram_addr_t ram_size,
                     kernel_filename);
             exit(1);
         }
-        fprintf(stderr, "Kernel               : 0x%08x..%08lx\n",
-                KERNEL_LOAD_ADDR, KERNEL_LOAD_ADDR + kernel_size - 1);
 
         /* load initrd */
         if (initrd_filename) {
@@ -783,8 +771,6 @@ static void ppc_spapr_init(ram_addr_t ram_size,
                         initrd_filename);
                 exit(1);
             }
-            fprintf(stderr, "Ramdisk              : 0x%08lx..%08lx\n",
-                    (long)initrd_base, (long)(initrd_base + initrd_size - 1));
         } else {
             initrd_base = 0;
             initrd_size = 0;
@@ -798,10 +784,6 @@ static void ppc_spapr_init(ram_addr_t ram_size,
         exit(1);
     }
     g_free(filename);
-    fprintf(stderr, "Firmware load        : 0x%08x..%08lx\n",
-            0, fw_size);
-    fprintf(stderr, "Firmware runtime     : 0x%08lx..%08lx\n",
-            load_limit, (unsigned long)spapr->fdt_addr);
 
     spapr->entry_point = 0x100;
 
commit 03332579b81ef7f2b0fcb41e45f7764a5bfc1ea4
Author: Benjamin Herrenschmidt <benh at kernel.crashing.org>
Date:   Mon Jul 30 20:09:01 2012 +0000

    pseries: Update SLOF
    
    This patch updates the SLOF version, introducing a number of fixes:
     * add proper graphics support
     * fix bugs with graphical terminal under grub2
     * fix bugs in handling of 64-bit unit addresses
     * fix VSCSI representation to be closer to PowerVM
     * fix bugs which caused grub2 to crash
    
    Signed-off-by: Benjamin Herrenschmidt <benh at kernel.crashing.org>
    Signed-off-by: David Gibson <david at gibson.dropbear.id.au>
    Signed-off-by: Alexander Graf <agraf at suse.de>

diff --git a/pc-bios/README b/pc-bios/README
index e56e9e5..e71bcd0 100644
--- a/pc-bios/README
+++ b/pc-bios/README
@@ -17,7 +17,7 @@
 - SLOF (Slimline Open Firmware) is a free IEEE 1275 Open Firmware
   implementation for certain IBM POWER hardware.  The sources are at
   https://github.com/dgibson/SLOF, and the image currently in qemu is
-  built from git tag qemu-slof-20120217.
+  built from git tag qemu-slof-20120719.
 
 - sgabios (the Serial Graphics Adapter option ROM) provides a means for
   legacy x86 software to communicate with an attached serial console as
diff --git a/pc-bios/slof.bin b/pc-bios/slof.bin
index 449a7bb..320b8f0 100644
Binary files a/pc-bios/slof.bin and b/pc-bios/slof.bin differ
diff --git a/roms/SLOF b/roms/SLOF
index d153364..7279655 160000
--- a/roms/SLOF
+++ b/roms/SLOF
@@ -1 +1 @@
-Subproject commit d153364253548d6cd91403711f84996e6a7dab31
+Subproject commit 7279655af2eba855bd2df61303d25abd1eeb2300
commit 3fc5acdeedfcea7c7d86040fa427ae785920b399
Author: Alexander Graf <agraf at suse.de>
Date:   Tue Aug 14 13:22:13 2012 +0200

    PPC: spapr: Remove global variable
    
    Global variables are bad. Let's move spapr_has_graphics into the
    machine state struct.
    
    Signed-off-by: Alexander Graf <agraf at suse.de>

diff --git a/hw/spapr.c b/hw/spapr.c
index 709673e..aa39d2d 100644
--- a/hw/spapr.c
+++ b/hw/spapr.c
@@ -83,7 +83,6 @@
 #define PHANDLE_XICP            0x00001111
 
 sPAPREnvironment *spapr;
-bool spapr_has_graphics;
 
 qemu_irq spapr_allocate_irq(uint32_t hint, uint32_t *irq_num,
                             enum xics_irq_type type)
@@ -508,7 +507,7 @@ static void spapr_finalize_fdt(sPAPREnvironment *spapr,
         }
     }
 
-    if (!spapr_has_graphics) {
+    if (!spapr->has_graphics) {
         spapr_populate_chosen_stdout(fdt, spapr->vio_bus);
     }
 
@@ -736,7 +735,7 @@ static void ppc_spapr_init(ram_addr_t ram_size,
 
     /* Graphics */
     if (spapr_vga_init(QLIST_FIRST(&spapr->phbs)->host_state.bus)) {
-        spapr_has_graphics = true;
+        spapr->has_graphics = true;
     }
 
     if (rma_size < (MIN_RMA_SLOF << 20)) {
diff --git a/hw/spapr.h b/hw/spapr.h
index 9153f29..fe40e7d 100644
--- a/hw/spapr.h
+++ b/hw/spapr.h
@@ -23,6 +23,7 @@ typedef struct sPAPREnvironment {
     int next_irq;
     int rtc_offset;
     char *cpu_model;
+    bool has_graphics;
 } sPAPREnvironment;
 
 #define H_SUCCESS         0
commit 8c57b867b5d18b0d916797dfbac465b8aaa5bf5a
Author: Alexander Graf <agraf at suse.de>
Date:   Tue Aug 14 13:11:49 2012 +0200

    PPC: spapr: Rework VGA select logic
    
    When selecting our VGA adapter, we want to:
    
      * fail completely when we can't satisfy the user's request
      * support -nographic where no VGA adapter should be spawned
    
    This patch reworks the logic so we fulfill the two conditions above.
    
    Signed-off-by: Alexander Graf <agraf at suse.de>

diff --git a/hw/spapr.c b/hw/spapr.c
index 494c412..709673e 100644
--- a/hw/spapr.c
+++ b/hw/spapr.c
@@ -563,16 +563,21 @@ static void spapr_cpu_reset(void *opaque)
     cpu_reset(CPU(cpu));
 }
 
+/* Returns whether we want to use VGA or not */
 static int spapr_vga_init(PCIBus *pci_bus)
 {
-    if (std_vga_enabled) {
+    switch (vga_interface_type) {
+    case VGA_STD:
         pci_vga_init(pci_bus);
-    } else {
+        return 1;
+    case VGA_NONE:
+        return 0;
+    default:
         fprintf(stderr, "This vga model is not supported,"
                 "currently it only supports -vga std\n");
-        return 0;
+        exit(0);
+        break;
     }
-    return 1;
 }
 
 /* pSeries LPAR / sPAPR hardware init */
commit a5b71725c7067f6805eb30ff8e03dce3b6bf7a53
Author: Alexander Graf <agraf at suse.de>
Date:   Tue Aug 14 12:53:18 2012 +0200

    xbzrle: fix compilation on ppc32
    
    When compiling the xbzrle code on my ppc32 user space, I hit the following
    gcc compiler warning (treated as an error):
    
      cc1: warnings being treated as errors
      savevm.c: In function ‘xbzrle_encode_buffer’:
      savevm.c:2476: error: overflow in implicit constant conversion
    
    Fix this by making the cast explicit, rather than implicit.
    
    Signed-off-by: Alexander Graf <agraf at suse.de>

diff --git a/savevm.c b/savevm.c
index 0ea10c9..9ab4d83 100644
--- a/savevm.c
+++ b/savevm.c
@@ -2473,7 +2473,7 @@ int xbzrle_encode_buffer(uint8_t *old_buf, uint8_t *new_buf, int slen,
         /* word at a time for speed, use of 32-bit long okay */
         if (!res) {
             /* truncation to 32-bit long okay */
-            long mask = 0x0101010101010101ULL;
+            long mask = (long)0x0101010101010101ULL;
             while (i < slen) {
                 xor = *(long *)(old_buf + i) ^ *(long *)(new_buf + i);
                 if ((xor - mask) & ~xor & (mask << 7)) {
commit f28359d8e8fc64192450a72164b89d06cc3f781d
Author: zhlcindy at gmail.com <zhlcindy at gmail.com>
Date:   Mon Aug 6 16:42:00 2012 +0000

    spapr: Add support for -vga option
    
    Also instanciate the USB keyboard and mouse when that option is used
    (you can still use -device to create individual devices without all
    the defaults)
    
    Signed-off-by: Benjamin Herrenschmidt <benh at kernel.crashing.org>
    Signed-off-by: Li Zhang <zhlcindy at linux.vnet.ibm.com>
    [agraf: remove USB bits]
    Signed-off-by: Alexander Graf <agraf at suse.de>

diff --git a/hw/spapr.c b/hw/spapr.c
index ab5a0c2..494c412 100644
--- a/hw/spapr.c
+++ b/hw/spapr.c
@@ -45,6 +45,7 @@
 #include "kvm.h"
 #include "kvm_ppc.h"
 #include "pci.h"
+#include "vga-pci.h"
 
 #include "exec-memory.h"
 
@@ -82,6 +83,7 @@
 #define PHANDLE_XICP            0x00001111
 
 sPAPREnvironment *spapr;
+bool spapr_has_graphics;
 
 qemu_irq spapr_allocate_irq(uint32_t hint, uint32_t *irq_num,
                             enum xics_irq_type type)
@@ -257,6 +259,9 @@ static void *spapr_create_fdt_skel(const char *cpu_model,
         _FDT((fdt_property(fdt, "qemu,boot-kernel", &kprop, sizeof(kprop))));
     }
     _FDT((fdt_property_string(fdt, "qemu,boot-device", boot_device)));
+    _FDT((fdt_property_cell(fdt, "qemu,graphic-width", graphic_width)));
+    _FDT((fdt_property_cell(fdt, "qemu,graphic-height", graphic_height)));
+    _FDT((fdt_property_cell(fdt, "qemu,graphic-depth", graphic_depth)));
 
     _FDT((fdt_end_node(fdt)));
 
@@ -503,7 +508,9 @@ static void spapr_finalize_fdt(sPAPREnvironment *spapr,
         }
     }
 
-    spapr_populate_chosen_stdout(fdt, spapr->vio_bus);
+    if (!spapr_has_graphics) {
+        spapr_populate_chosen_stdout(fdt, spapr->vio_bus);
+    }
 
     _FDT((fdt_pack(fdt)));
 
@@ -556,6 +563,18 @@ static void spapr_cpu_reset(void *opaque)
     cpu_reset(CPU(cpu));
 }
 
+static int spapr_vga_init(PCIBus *pci_bus)
+{
+    if (std_vga_enabled) {
+        pci_vga_init(pci_bus);
+    } else {
+        fprintf(stderr, "This vga model is not supported,"
+                "currently it only supports -vga std\n");
+        return 0;
+    }
+    return 1;
+}
+
 /* pSeries LPAR / sPAPR hardware init */
 static void ppc_spapr_init(ram_addr_t ram_size,
                            const char *boot_device,
@@ -710,6 +729,11 @@ static void ppc_spapr_init(ram_addr_t ram_size,
         spapr_vscsi_create(spapr->vio_bus);
     }
 
+    /* Graphics */
+    if (spapr_vga_init(QLIST_FIRST(&spapr->phbs)->host_state.bus)) {
+        spapr_has_graphics = true;
+    }
+
     if (rma_size < (MIN_RMA_SLOF << 20)) {
         fprintf(stderr, "qemu: pSeries SLOF firmware requires >= "
                 "%ldM guest RMA (Real Mode Area memory)\n", MIN_RMA_SLOF);
commit c1195d1677a41f42be712620674d42b39d83bdfe
Author: zhlcindy at gmail.com <zhlcindy at gmail.com>
Date:   Mon Aug 6 16:41:59 2012 +0000

    Add one new file vga-pci.h and cleanup on all platforms
    
    Functions pci_vga_init() and pci_cirrus_vga_init() are declared
    in pc.h. That prevents other platforms (e.g. sPAPR) to use them.
    
    This patch is to create one new file vga-pci.h and move the
    declarations to vga-pci.h, so that they can be shared by
    all platforms. This patch also cleans up on all platforms.
    
    Signed-off-by: Li Zhang <zhlcindy at linux.vnet.ibm.com>
    Signed-off-by: Alexander Graf <agraf at suse.de>

diff --git a/hw/alpha_pci.c b/hw/alpha_pci.c
index 6735577..ea546f8 100644
--- a/hw/alpha_pci.c
+++ b/hw/alpha_pci.c
@@ -11,6 +11,7 @@
 #include "qemu-log.h"
 #include "sysemu.h"
 #include "vmware_vga.h"
+#include "vga-pci.h"
 
 
 /* PCI IO reads/writes, to byte-word addressable memory.  */
diff --git a/hw/cirrus_vga.c b/hw/cirrus_vga.c
index 623dd68..e8dcc6b 100644
--- a/hw/cirrus_vga.c
+++ b/hw/cirrus_vga.c
@@ -27,8 +27,8 @@
  *   available at http://home.worldonline.dk/~finth/
  */
 #include "hw.h"
-#include "pc.h"
 #include "pci.h"
+#include "vga-pci.h"
 #include "console.h"
 #include "vga_int.h"
 #include "loader.h"
diff --git a/hw/mips_malta.c b/hw/mips_malta.c
index 351c88e..ad23f26 100644
--- a/hw/mips_malta.c
+++ b/hw/mips_malta.c
@@ -48,6 +48,7 @@
 #include "blockdev.h"
 #include "exec-memory.h"
 #include "sysbus.h"             /* SysBusDevice */
+#include "vga-pci.h"
 
 //#define DEBUG_BOARD_INIT
 
diff --git a/hw/pc.c b/hw/pc.c
index e8bcfc0..3ed1a3c 100644
--- a/hw/pc.c
+++ b/hw/pc.c
@@ -51,6 +51,7 @@
 #include "exec-memory.h"
 #include "arch_init.h"
 #include "bitmap.h"
+#include "vga-pci.h"
 
 /* output Bochs bios info messages */
 //#define DEBUG_BIOS
diff --git a/hw/pc.h b/hw/pc.h
index 31ccb6f..e4db071 100644
--- a/hw/pc.h
+++ b/hw/pc.h
@@ -189,14 +189,10 @@ static inline DeviceState *isa_vga_init(ISABus *bus)
     return &dev->qdev;
 }
 
-DeviceState *pci_vga_init(PCIBus *bus);
 int isa_vga_mm_init(target_phys_addr_t vram_base,
                     target_phys_addr_t ctrl_base, int it_shift,
                     MemoryRegion *address_space);
 
-/* cirrus_vga.c */
-DeviceState *pci_cirrus_vga_init(PCIBus *bus);
-
 /* ne2000.c */
 static inline bool isa_ne2000_init(ISABus *bus, int base, int irq, NICInfo *nd)
 {
diff --git a/hw/ppc_newworld.c b/hw/ppc_newworld.c
index 4e2a6e6..e95cfe8 100644
--- a/hw/ppc_newworld.c
+++ b/hw/ppc_newworld.c
@@ -52,7 +52,6 @@
 #include "adb.h"
 #include "mac_dbdma.h"
 #include "nvram.h"
-#include "pc.h"
 #include "pci.h"
 #include "net.h"
 #include "sysemu.h"
@@ -68,6 +67,7 @@
 #include "hw/usb.h"
 #include "blockdev.h"
 #include "exec-memory.h"
+#include "vga-pci.h"
 
 #define MAX_IDE_BUS 2
 #define CFG_ADDR 0xf0000510
diff --git a/hw/ppc_oldworld.c b/hw/ppc_oldworld.c
index f2c6908..1dcd8a6 100644
--- a/hw/ppc_oldworld.c
+++ b/hw/ppc_oldworld.c
@@ -29,7 +29,6 @@
 #include "adb.h"
 #include "mac_dbdma.h"
 #include "nvram.h"
-#include "pc.h"
 #include "sysemu.h"
 #include "net.h"
 #include "isa.h"
@@ -44,6 +43,7 @@
 #include "kvm_ppc.h"
 #include "blockdev.h"
 #include "exec-memory.h"
+#include "vga-pci.h"
 
 #define MAX_IDE_BUS 2
 #define CFG_ADDR 0xf0000510
diff --git a/hw/ppc_prep.c b/hw/ppc_prep.c
index be2b268..7a87616 100644
--- a/hw/ppc_prep.c
+++ b/hw/ppc_prep.c
@@ -39,6 +39,7 @@
 #include "blockdev.h"
 #include "arch_init.h"
 #include "exec-memory.h"
+#include "vga-pci.h"
 
 //#define HARD_DEBUG_PPC_IO
 //#define DEBUG_PPC_IO
diff --git a/hw/sun4u.c b/hw/sun4u.c
index 137a7c6..07cd042 100644
--- a/hw/sun4u.c
+++ b/hw/sun4u.c
@@ -39,6 +39,7 @@
 #include "elf.h"
 #include "blockdev.h"
 #include "exec-memory.h"
+#include "vga-pci.h"
 
 //#define DEBUG_IRQ
 //#define DEBUG_EBUS
diff --git a/hw/vga-pci.c b/hw/vga-pci.c
index 37dc019..9abbada 100644
--- a/hw/vga-pci.c
+++ b/hw/vga-pci.c
@@ -23,8 +23,8 @@
  */
 #include "hw.h"
 #include "console.h"
-#include "pc.h"
 #include "pci.h"
+#include "vga-pci.h"
 #include "vga_int.h"
 #include "pixel_ops.h"
 #include "qemu-timer.h"
diff --git a/hw/vga-pci.h b/hw/vga-pci.h
new file mode 100644
index 0000000..49abf13
--- /dev/null
+++ b/hw/vga-pci.h
@@ -0,0 +1,12 @@
+#ifndef VGA_PCI_H
+#define VGA_PCI_H
+
+#include "qemu-common.h"
+
+/* vga-pci.c */
+DeviceState *pci_vga_init(PCIBus *bus);
+
+/* cirrus_vga.c */
+DeviceState *pci_cirrus_vga_init(PCIBus *bus);
+
+#endif
commit 7e99826c350f21cb7d162e802efaa5d1b8689ad0
Author: Alexander Graf <agraf at suse.de>
Date:   Thu Aug 9 22:57:14 2012 +0200

    Revert "PPC: e500: Use new MPIC dt format"
    
    This reverts commit 518c7fb44f2182cde943dc64f88cb2fd4e4ff6b5. It breaks
    new Linux guests with SMP, because IPIs get mapped to large vectors which
    our MPIC emulation does not implement.
    
    Conflicts:
    
    	hw/ppc/e500.c

diff --git a/hw/ppc/e500.c b/hw/ppc/e500.c
index f07be08..6f0de6d 100644
--- a/hw/ppc/e500.c
+++ b/hw/ppc/e500.c
@@ -68,18 +68,18 @@ static void pci_map_create(void *fdt, uint32_t *pci_map, uint32_t mpic)
     int i;
     const uint32_t tmp[] = {
                              /* IDSEL 0x11 J17 Slot 1 */
-                             0x8800, 0x0, 0x0, 0x1, mpic, 0x2, 0x1, 0x0, 0x0,
-                             0x8800, 0x0, 0x0, 0x2, mpic, 0x3, 0x1, 0x0, 0x0,
-                             0x8800, 0x0, 0x0, 0x3, mpic, 0x4, 0x1, 0x0, 0x0,
-                             0x8800, 0x0, 0x0, 0x4, mpic, 0x1, 0x1, 0x0, 0x0,
+                             0x8800, 0x0, 0x0, 0x1, mpic, 0x2, 0x1,
+                             0x8800, 0x0, 0x0, 0x2, mpic, 0x3, 0x1,
+                             0x8800, 0x0, 0x0, 0x3, mpic, 0x4, 0x1,
+                             0x8800, 0x0, 0x0, 0x4, mpic, 0x1, 0x1,
 
                              /* IDSEL 0x12 J16 Slot 2 */
-                             0x9000, 0x0, 0x0, 0x1, mpic, 0x3, 0x1, 0x0, 0x0,
-                             0x9000, 0x0, 0x0, 0x2, mpic, 0x4, 0x1, 0x0, 0x0,
-                             0x9000, 0x0, 0x0, 0x3, mpic, 0x2, 0x1, 0x0, 0x0,
-                             0x9000, 0x0, 0x0, 0x4, mpic, 0x1, 0x1, 0x0, 0x0,
+                             0x9000, 0x0, 0x0, 0x1, mpic, 0x3, 0x1,
+                             0x9000, 0x0, 0x0, 0x2, mpic, 0x4, 0x1,
+                             0x9000, 0x0, 0x0, 0x3, mpic, 0x2, 0x1,
+                             0x9000, 0x0, 0x0, 0x4, mpic, 0x1, 0x1,
                            };
-    for (i = 0; i < ARRAY_SIZE(tmp); i++) {
+    for (i = 0; i < (7 * 8); i++) {
         pci_map[i] = cpu_to_be32(tmp[i]);
     }
 }
@@ -97,7 +97,7 @@ static void dt_serial_create(void *fdt, unsigned long long offset,
     qemu_devtree_setprop_cells(fdt, ser, "reg", offset, 0x100);
     qemu_devtree_setprop_cell(fdt, ser, "cell-index", idx);
     qemu_devtree_setprop_cell(fdt, ser, "clock-frequency", 0);
-    qemu_devtree_setprop_cells(fdt, ser, "interrupts", 42, 2, 0, 0);
+    qemu_devtree_setprop_cells(fdt, ser, "interrupts", 42, 2);
     qemu_devtree_setprop_phandle(fdt, ser, "interrupt-parent", mpic);
     qemu_devtree_setprop_string(fdt, "/aliases", alias, ser);
 
@@ -127,7 +127,7 @@ static int ppce500_load_device_tree(CPUPPCState *env,
     uint32_t mpic_ph;
     char gutil[128];
     char pci[128];
-    uint32_t pci_map[9 * 8];
+    uint32_t pci_map[7 * 8];
     uint32_t pci_ranges[14] =
         {
             0x2000000, 0x0, 0xc0000000,
@@ -274,18 +274,15 @@ static int ppce500_load_device_tree(CPUPPCState *env,
              MPC8544_MPIC_REGS_BASE - MPC8544_CCSRBAR_BASE);
     qemu_devtree_add_subnode(fdt, mpic);
     qemu_devtree_setprop_string(fdt, mpic, "device_type", "open-pic");
-    qemu_devtree_setprop_string(fdt, mpic, "compatible", "fsl,mpic");
+    qemu_devtree_setprop_string(fdt, mpic, "compatible", "chrp,open-pic");
     qemu_devtree_setprop_cells(fdt, mpic, "reg", MPC8544_MPIC_REGS_BASE -
                                MPC8544_CCSRBAR_BASE, 0x40000);
     qemu_devtree_setprop_cell(fdt, mpic, "#address-cells", 0);
-    qemu_devtree_setprop_cell(fdt, mpic, "#interrupt-cells", 4);
+    qemu_devtree_setprop_cell(fdt, mpic, "#interrupt-cells", 2);
     mpic_ph = qemu_devtree_alloc_phandle(fdt);
     qemu_devtree_setprop_cell(fdt, mpic, "phandle", mpic_ph);
     qemu_devtree_setprop_cell(fdt, mpic, "linux,phandle", mpic_ph);
     qemu_devtree_setprop(fdt, mpic, "interrupt-controller", NULL, 0);
-    qemu_devtree_setprop(fdt, mpic, "big-endian", NULL, 0);
-    qemu_devtree_setprop(fdt, mpic, "single-cpu-affinity", NULL, 0);
-    qemu_devtree_setprop_cell(fdt, mpic, "last-interrupt-source", 255);
 
     /*
      * We have to generate ser1 first, because Linux takes the first
@@ -315,7 +312,7 @@ static int ppce500_load_device_tree(CPUPPCState *env,
     pci_map_create(fdt, pci_map, qemu_devtree_get_phandle(fdt, mpic));
     qemu_devtree_setprop(fdt, pci, "interrupt-map", pci_map, sizeof(pci_map));
     qemu_devtree_setprop_phandle(fdt, pci, "interrupt-parent", mpic);
-    qemu_devtree_setprop_cells(fdt, pci, "interrupts", 24, 2, 0, 0);
+    qemu_devtree_setprop_cells(fdt, pci, "interrupts", 24, 2);
     qemu_devtree_setprop_cells(fdt, pci, "bus-range", 0, 255);
     for (i = 0; i < 14; i++) {
         pci_ranges[i] = cpu_to_be32(pci_ranges[i]);
commit 78e8fde26c032931ca2ae13bfc7c59e38afd17ee
Author: David Gibson <david at gibson.dropbear.id.au>
Date:   Mon Aug 6 18:44:45 2012 +0000

    ppc: Fix bug in handling of PAPR hypercall exits
    
    Currently for powerpc, kvm_arch_handle_exit() always returns 1, meaning
    that its caller - kvm_cpu_exec() - will always exit immediately afterwards
    to the loop in qemu_kvm_cpu_thread_fn().
    
    There's no need to do this.  Once we've handled the hypercall there's no
    reason we can't go straight around and KVM_RUN again, which is what ret = 0
    will signal.  The only exception might be for hypercalls which affect the
    state of cpu_can_run(), however the only one that might do this is H_CEDE
    and for kvm that is always handled in the kernel, not qemu.
    
    Furtherm setting ret = 0 means that when exit_requested is set from a
    hypercall, we will enter KVM_RUN once more with a signal which lets the
    the kernel do its internal logic to complete the hypercall with out
    actually executing any more guest code.  This is important if our hypercall
    also triggered a reset, which previously would re-initialize everything
    without completing the hypercall.  This caused the kernel to get confused
    because it thought the guest was still in the middle of a hypercall when
    it has actually been reset.
    
    This patch therefore changes to ret = 0, which is both a bugfix and a small
    optimization.
    
    Signed-off-by: David Gibson <david at gibson.dropbear.id.au>
    Signed-off-by: Alexander Graf <agraf at suse.de>

diff --git a/target-ppc/kvm.c b/target-ppc/kvm.c
index 829e180..a31d278 100644
--- a/target-ppc/kvm.c
+++ b/target-ppc/kvm.c
@@ -766,7 +766,7 @@ int kvm_arch_handle_exit(CPUPPCState *env, struct kvm_run *run)
         dprintf("handle PAPR hypercall\n");
         run->papr_hcall.ret = spapr_hypercall(env, run->papr_hcall.nr,
                                               run->papr_hcall.args);
-        ret = 1;
+        ret = 0;
         break;
 #endif
     default:
commit 4d5c29ca455ed6adb1fb9f8394e4d7badfd0c532
Author: Scott Wood <scottwood at freescale.com>
Date:   Mon Jul 2 13:03:21 2012 +0000

    PPC: e500: add generic e500 platform
    
    This gives the kernel a paravirtualized machine to target, without
    requiring both sides to pretend to be targeting a specific board
    that likely has little to do with the host in KVM scenarios.  This
    avoids the need to add new boards to QEMU, just to be able to
    run KVM on new CPUs.
    
    Signed-off-by: Scott Wood <scottwood at freescale.com>
    [agraf: conditionalize on CONFIG_FDT]
    Signed-off-by: Alexander Graf <agraf at suse.de>

diff --git a/hw/ppc/Makefile.objs b/hw/ppc/Makefile.objs
index 99fe837..951e407 100644
--- a/hw/ppc/Makefile.objs
+++ b/hw/ppc/Makefile.objs
@@ -27,4 +27,4 @@ obj-y += xilinx_ethlite.o
 
 obj-y := $(addprefix ../,$(obj-y))
 
-obj-$(CONFIG_FDT) += e500.o mpc8544ds.o
+obj-$(CONFIG_FDT) += e500.o mpc8544ds.o e500plat.o
diff --git a/hw/ppc/e500plat.c b/hw/ppc/e500plat.c
new file mode 100644
index 0000000..60a5cb3
--- /dev/null
+++ b/hw/ppc/e500plat.c
@@ -0,0 +1,60 @@
+/*
+ * Generic device-tree-driven paravirt PPC e500 platform
+ *
+ * Copyright 2012 Freescale Semiconductor, Inc.
+ *
+ * This is free software; you can redistribute it and/or modify
+ * it under the terms of  the GNU General  Public License as published by
+ * the Free Software Foundation;  either version 2 of the  License, or
+ * (at your option) any later version.
+ */
+
+#include "config.h"
+#include "qemu-common.h"
+#include "e500.h"
+#include "../boards.h"
+#include "device_tree.h"
+
+static void e500plat_fixup_devtree(PPCE500Params *params, void *fdt)
+{
+    const char model[] = "QEMU ppce500";
+    const char compatible[] = "fsl,qemu-e500";
+
+    qemu_devtree_setprop(fdt, "/", "model", model, sizeof(model));
+    qemu_devtree_setprop(fdt, "/", "compatible", compatible,
+                         sizeof(compatible));
+}
+
+static void e500plat_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)
+{
+    PPCE500Params params = {
+        .ram_size = ram_size,
+        .boot_device = boot_device,
+        .kernel_filename = kernel_filename,
+        .kernel_cmdline = kernel_cmdline,
+        .initrd_filename = initrd_filename,
+        .cpu_model = cpu_model,
+        .fixup_devtree = e500plat_fixup_devtree,
+    };
+
+    ppce500_init(&params);
+}
+
+static QEMUMachine e500plat_machine = {
+    .name = "ppce500",
+    .desc = "generic paravirt e500 platform",
+    .init = e500plat_init,
+    .max_cpus = 15,
+};
+
+static void e500plat_machine_init(void)
+{
+    qemu_register_machine(&e500plat_machine);
+}
+
+machine_init(e500plat_machine_init);
commit e6eaabeb8dfb026da51d178974bddf56f1f06ffe
Author: Scott Wood <scottwood at freescale.com>
Date:   Mon Jul 2 13:03:20 2012 +0000

    PPC: e500: split mpc8544ds machine from generic e500 code
    
    Currently the only mpc8544ds-ism that is factored out is
    toplevel compatible and model.  In the future the generic e500
    code is expected to become more generic.
    
    Signed-off-by: Scott Wood <scottwood at freescale.com>
    [agraf: conditionalize on CONFIG_FDT]
    Signed-off-by: Alexander Graf <agraf at suse.de>

diff --git a/hw/ppc/Makefile.objs b/hw/ppc/Makefile.objs
index e86c524..99fe837 100644
--- a/hw/ppc/Makefile.objs
+++ b/hw/ppc/Makefile.objs
@@ -27,4 +27,4 @@ obj-y += xilinx_ethlite.o
 
 obj-y := $(addprefix ../,$(obj-y))
 
-obj-$(CONFIG_FDT) += e500.o
+obj-$(CONFIG_FDT) += e500.o mpc8544ds.o
diff --git a/hw/ppc/e500.c b/hw/ppc/e500.c
index db5ca6e..f07be08 100644
--- a/hw/ppc/e500.c
+++ b/hw/ppc/e500.c
@@ -16,6 +16,7 @@
 
 #include "config.h"
 #include "qemu-common.h"
+#include "e500.h"
 #include "net.h"
 #include "hw/hw.h"
 #include "hw/pc.h"
@@ -106,24 +107,21 @@ static void dt_serial_create(void *fdt, unsigned long long offset,
 }
 
 static int ppce500_load_device_tree(CPUPPCState *env,
+                                    PPCE500Params *params,
                                     target_phys_addr_t addr,
-                                    target_phys_addr_t ramsize,
                                     target_phys_addr_t initrd_base,
-                                    target_phys_addr_t initrd_size,
-                                    const char *kernel_cmdline)
+                                    target_phys_addr_t initrd_size)
 {
     int ret = -1;
-    uint64_t mem_reg_property[] = { 0, cpu_to_be64(ramsize) };
+    uint64_t mem_reg_property[] = { 0, cpu_to_be64(params->ram_size) };
     int fdt_size;
     void *fdt;
     uint8_t hypercall[16];
     uint32_t clock_freq = 400000000;
     uint32_t tb_freq = 400000000;
     int i;
-    const char *compatible = "MPC8544DS\0MPC85xxDS";
-    int compatible_len = sizeof("MPC8544DS\0MPC85xxDS");
+    const char *toplevel_compat = NULL; /* user override */
     char compatible_sb[] = "fsl,mpc8544-immr\0simple-bus";
-    char model[] = "MPC8544DS";
     char soc[128];
     char mpic[128];
     uint32_t mpic_ph;
@@ -146,14 +144,9 @@ static int ppce500_load_device_tree(CPUPPCState *env,
 
     machine_opts = qemu_opts_find(qemu_find_opts("machine"), 0);
     if (machine_opts) {
-        const char *tmp;
         dumpdtb = qemu_opt_get(machine_opts, "dumpdtb");
         dtb_file = qemu_opt_get(machine_opts, "dtb");
-        tmp = qemu_opt_get(machine_opts, "dt_compatible");
-        if (tmp) {
-            compatible = tmp;
-            compatible_len = strlen(compatible) + 1;
-        }
+        toplevel_compat = qemu_opt_get(machine_opts, "dt_compatible");
     }
 
     if (dtb_file) {
@@ -176,8 +169,6 @@ static int ppce500_load_device_tree(CPUPPCState *env,
     }
 
     /* Manipulate device tree in memory. */
-    qemu_devtree_setprop_string(fdt, "/", "model", model);
-    qemu_devtree_setprop(fdt, "/", "compatible", compatible, compatible_len);
     qemu_devtree_setprop_cell(fdt, "/", "#address-cells", 2);
     qemu_devtree_setprop_cell(fdt, "/", "#size-cells", 2);
 
@@ -202,7 +193,7 @@ static int ppce500_load_device_tree(CPUPPCState *env,
     }
 
     ret = qemu_devtree_setprop_string(fdt, "/chosen", "bootargs",
-                                      kernel_cmdline);
+                                      params->kernel_cmdline);
     if (ret < 0)
         fprintf(stderr, "couldn't set /chosen/bootargs\n");
 
@@ -338,6 +329,13 @@ static int ppce500_load_device_tree(CPUPPCState *env,
     qemu_devtree_setprop_cell(fdt, pci, "#address-cells", 3);
     qemu_devtree_setprop_string(fdt, "/aliases", "pci0", pci);
 
+    params->fixup_devtree(params, fdt);
+
+    if (toplevel_compat) {
+        qemu_devtree_setprop(fdt, "/", "compatible", toplevel_compat,
+                             strlen(toplevel_compat) + 1);
+    }
+
 done:
     if (dumpdtb) {
         /* Dump the dtb to a file and quit */
@@ -418,12 +416,7 @@ static void ppce500_cpu_reset(void *opaque)
     mmubooke_create_initial_mapping(env);
 }
 
-static void ppce500_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)
+void ppce500_init(PPCE500Params *params)
 {
     MemoryRegion *address_space_mem = get_system_memory();
     MemoryRegion *ram = g_new(MemoryRegion, 1);
@@ -444,8 +437,8 @@ static void ppce500_init(ram_addr_t ram_size,
     CPUPPCState *firstenv = NULL;
 
     /* Setup CPUs */
-    if (cpu_model == NULL) {
-        cpu_model = "e500v2_v30";
+    if (params->cpu_model == NULL) {
+        params->cpu_model = "e500v2_v30";
     }
 
     irqs = g_malloc0(smp_cpus * sizeof(qemu_irq *));
@@ -454,7 +447,7 @@ static void ppce500_init(ram_addr_t ram_size,
         PowerPCCPU *cpu;
         qemu_irq *input;
 
-        cpu = cpu_ppc_init(cpu_model);
+        cpu = cpu_ppc_init(params->cpu_model);
         if (cpu == NULL) {
             fprintf(stderr, "Unable to initialize CPU!\n");
             exit(1);
@@ -543,43 +536,45 @@ static void ppce500_init(ram_addr_t ram_size,
     sysbus_create_simple("e500-spin", MPC8544_SPIN_BASE, NULL);
 
     /* Load kernel. */
-    if (kernel_filename) {
-        kernel_size = load_uimage(kernel_filename, &entry, &loadaddr, NULL);
+    if (params->kernel_filename) {
+        kernel_size = load_uimage(params->kernel_filename, &entry,
+                                  &loadaddr, NULL);
         if (kernel_size < 0) {
-            kernel_size = load_elf(kernel_filename, NULL, NULL, &elf_entry,
-                                   &elf_lowaddr, NULL, 1, ELF_MACHINE, 0);
+            kernel_size = load_elf(params->kernel_filename, NULL, NULL,
+                                   &elf_entry, &elf_lowaddr, NULL, 1,
+                                   ELF_MACHINE, 0);
             entry = elf_entry;
             loadaddr = elf_lowaddr;
         }
         /* XXX try again as binary */
         if (kernel_size < 0) {
             fprintf(stderr, "qemu: could not load kernel '%s'\n",
-                    kernel_filename);
+                    params->kernel_filename);
             exit(1);
         }
     }
 
     /* Load initrd. */
-    if (initrd_filename) {
+    if (params->initrd_filename) {
         initrd_base = (kernel_size + INITRD_LOAD_PAD) & ~INITRD_PAD_MASK;
-        initrd_size = load_image_targphys(initrd_filename, initrd_base,
+        initrd_size = load_image_targphys(params->initrd_filename, initrd_base,
                                           ram_size - initrd_base);
 
         if (initrd_size < 0) {
             fprintf(stderr, "qemu: could not load initial ram disk '%s'\n",
-                    initrd_filename);
+                    params->initrd_filename);
             exit(1);
         }
     }
 
     /* If we're loading a kernel directly, we must load the device tree too. */
-    if (kernel_filename) {
+    if (params->kernel_filename) {
         struct boot_info *boot_info;
         int dt_size;
 
         dt_base = (loadaddr + kernel_size + DTC_LOAD_PAD) & ~DTC_PAD_MASK;
-        dt_size = ppce500_load_device_tree(env, dt_base, ram_size, initrd_base,
-                                           initrd_size, kernel_cmdline);
+        dt_size = ppce500_load_device_tree(env, params, dt_base, initrd_base,
+                                           initrd_size);
         if (dt_size < 0) {
             fprintf(stderr, "couldn't load device tree\n");
             exit(1);
@@ -595,17 +590,3 @@ static void ppce500_init(ram_addr_t ram_size,
         kvmppc_init();
     }
 }
-
-static QEMUMachine ppce500_machine = {
-    .name = "mpc8544ds",
-    .desc = "mpc8544ds",
-    .init = ppce500_init,
-    .max_cpus = 15,
-};
-
-static void ppce500_machine_init(void)
-{
-    qemu_register_machine(&ppce500_machine);
-}
-
-machine_init(ppce500_machine_init);
diff --git a/hw/ppc/e500.h b/hw/ppc/e500.h
new file mode 100644
index 0000000..7ae87f4
--- /dev/null
+++ b/hw/ppc/e500.h
@@ -0,0 +1,21 @@
+#ifndef PPCE500_H
+#define PPCE500_H
+
+typedef struct PPCE500Params {
+    /* Standard QEMU machine init params */
+    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;
+
+    /* e500-specific params */
+
+    /* required -- must at least add toplevel board compatible */
+    void (*fixup_devtree)(struct PPCE500Params *params, void *fdt);
+} PPCE500Params;
+
+void ppce500_init(PPCE500Params *params);
+
+#endif
diff --git a/hw/ppc/mpc8544ds.c b/hw/ppc/mpc8544ds.c
new file mode 100644
index 0000000..984d21c
--- /dev/null
+++ b/hw/ppc/mpc8544ds.c
@@ -0,0 +1,61 @@
+/*
+ * Support for the PPC e500-based mpc8544ds board
+ *
+ * Copyright 2012 Freescale Semiconductor, Inc.
+ *
+ * This is free software; you can redistribute it and/or modify
+ * it under the terms of  the GNU General  Public License as published by
+ * the Free Software Foundation;  either version 2 of the  License, or
+ * (at your option) any later version.
+ */
+
+#include "config.h"
+#include "qemu-common.h"
+#include "e500.h"
+#include "../boards.h"
+#include "device_tree.h"
+
+static void mpc8544ds_fixup_devtree(PPCE500Params *params, void *fdt)
+{
+    const char model[] = "MPC8544DS";
+    const char compatible[] = "MPC8544DS\0MPC85xxDS";
+
+    qemu_devtree_setprop(fdt, "/", "model", model, sizeof(model));
+    qemu_devtree_setprop(fdt, "/", "compatible", compatible,
+                         sizeof(compatible));
+}
+
+static void mpc8544ds_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)
+{
+    PPCE500Params params = {
+        .ram_size = ram_size,
+        .boot_device = boot_device,
+        .kernel_filename = kernel_filename,
+        .kernel_cmdline = kernel_cmdline,
+        .initrd_filename = initrd_filename,
+        .cpu_model = cpu_model,
+        .fixup_devtree = mpc8544ds_fixup_devtree,
+    };
+
+    ppce500_init(&params);
+}
+
+
+static QEMUMachine ppce500_machine = {
+    .name = "mpc8544ds",
+    .desc = "mpc8544ds",
+    .init = mpc8544ds_init,
+    .max_cpus = 15,
+};
+
+static void ppce500_machine_init(void)
+{
+    qemu_register_machine(&ppce500_machine);
+}
+
+machine_init(ppce500_machine_init);
commit b330598137cad915f65562a524b30e32498e44be
Author: Scott Wood <scottwood at freescale.com>
Date:   Mon Jul 2 13:03:19 2012 +0000

    PPC: e500: change internal references away from mpc8544ds
    
    No functional changes -- machine is still outwardly mpc8544ds.
    
    The references that are not changed contain mpc8544 hardware details that
    need to be parameterized if/when a different e500 platform wants to
    change them.
    
    Signed-off-by: Scott Wood <scottwood at freescale.com>
    Signed-off-by: Alexander Graf <agraf at suse.de>

diff --git a/hw/ppc/e500.c b/hw/ppc/e500.c
index 0b383e6..db5ca6e 100644
--- a/hw/ppc/e500.c
+++ b/hw/ppc/e500.c
@@ -1,5 +1,5 @@
 /*
- * QEMU PowerPC MPC8544DS board emulation
+ * QEMU PowerPC e500-based platforms
  *
  * Copyright (C) 2009 Freescale Semiconductor, Inc. All rights reserved.
  *
@@ -42,6 +42,7 @@
 
 #define RAM_SIZES_ALIGN            (64UL << 20)
 
+/* TODO: parameterize */
 #define MPC8544_CCSRBAR_BASE       0xE0000000ULL
 #define MPC8544_CCSRBAR_SIZE       0x00100000ULL
 #define MPC8544_MPIC_REGS_BASE     (MPC8544_CCSRBAR_BASE + 0x40000ULL)
@@ -104,7 +105,7 @@ static void dt_serial_create(void *fdt, unsigned long long offset,
     }
 }
 
-static int mpc8544_load_device_tree(CPUPPCState *env,
+static int ppce500_load_device_tree(CPUPPCState *env,
                                     target_phys_addr_t addr,
                                     target_phys_addr_t ramsize,
                                     target_phys_addr_t initrd_base,
@@ -388,7 +389,7 @@ static void mmubooke_create_initial_mapping(CPUPPCState *env)
     env->tlb_dirty = true;
 }
 
-static void mpc8544ds_cpu_reset_sec(void *opaque)
+static void ppce500_cpu_reset_sec(void *opaque)
 {
     PowerPCCPU *cpu = opaque;
     CPUPPCState *env = &cpu->env;
@@ -401,7 +402,7 @@ static void mpc8544ds_cpu_reset_sec(void *opaque)
     env->exception_index = EXCP_HLT;
 }
 
-static void mpc8544ds_cpu_reset(void *opaque)
+static void ppce500_cpu_reset(void *opaque)
 {
     PowerPCCPU *cpu = opaque;
     CPUPPCState *env = &cpu->env;
@@ -417,7 +418,7 @@ static void mpc8544ds_cpu_reset(void *opaque)
     mmubooke_create_initial_mapping(env);
 }
 
-static void mpc8544ds_init(ram_addr_t ram_size,
+static void ppce500_init(ram_addr_t ram_size,
                          const char *boot_device,
                          const char *kernel_filename,
                          const char *kernel_cmdline,
@@ -478,11 +479,11 @@ static void mpc8544ds_init(ram_addr_t ram_size,
             /* Primary CPU */
             struct boot_info *boot_info;
             boot_info = g_malloc0(sizeof(struct boot_info));
-            qemu_register_reset(mpc8544ds_cpu_reset, cpu);
+            qemu_register_reset(ppce500_cpu_reset, cpu);
             env->load_info = boot_info;
         } else {
             /* Secondary CPUs */
-            qemu_register_reset(mpc8544ds_cpu_reset_sec, cpu);
+            qemu_register_reset(ppce500_cpu_reset_sec, cpu);
         }
     }
 
@@ -577,7 +578,7 @@ static void mpc8544ds_init(ram_addr_t ram_size,
         int dt_size;
 
         dt_base = (loadaddr + kernel_size + DTC_LOAD_PAD) & ~DTC_PAD_MASK;
-        dt_size = mpc8544_load_device_tree(env, dt_base, ram_size, initrd_base,
+        dt_size = ppce500_load_device_tree(env, dt_base, ram_size, initrd_base,
                                            initrd_size, kernel_cmdline);
         if (dt_size < 0) {
             fprintf(stderr, "couldn't load device tree\n");
@@ -595,16 +596,16 @@ static void mpc8544ds_init(ram_addr_t ram_size,
     }
 }
 
-static QEMUMachine mpc8544ds_machine = {
+static QEMUMachine ppce500_machine = {
     .name = "mpc8544ds",
     .desc = "mpc8544ds",
-    .init = mpc8544ds_init,
+    .init = ppce500_init,
     .max_cpus = 15,
 };
 
-static void mpc8544ds_machine_init(void)
+static void ppce500_machine_init(void)
 {
-    qemu_register_machine(&mpc8544ds_machine);
+    qemu_register_machine(&ppce500_machine);
 }
 
-machine_init(mpc8544ds_machine_init);
+machine_init(ppce500_machine_init);
commit 4a18e7c92a3c23ee742eda1e4442299b56198517
Author: Scott Wood <scottwood at freescale.com>
Date:   Mon Jul 2 13:03:18 2012 +0000

    PPC: e500: rename mpc8544ds into generic file
    
    Rename the file (with no changes other than fixing up the header paths)
    in preparation for refactoring into a generic e500 platform.  Also move
    it into the newly created ppc/ directory.
    
    Signed-off-by: Scott Wood <scottwood at freescale.com>
    Reviewed-by: Andreas Färber <afaerber at suse.de>
    [agraf: conditionalize on CONFIG_FDT]
    Signed-off-by: Alexander Graf <agraf at suse.de>

diff --git a/hw/ppc/Makefile.objs b/hw/ppc/Makefile.objs
index aa4bbeb..e86c524 100644
--- a/hw/ppc/Makefile.objs
+++ b/hw/ppc/Makefile.objs
@@ -15,7 +15,7 @@ obj-$(CONFIG_PSERIES) += spapr_pci.o pci-hotplug.o spapr_iommu.o
 obj-y += ppc4xx_devs.o ppc4xx_pci.o ppc405_uc.o ppc405_boards.o
 obj-y += ppc440_bamboo.o
 # PowerPC E500 boards
-obj-$(CONFIG_FDT) += ppce500_mpc8544ds.o mpc8544_guts.o ppce500_spin.o
+obj-$(CONFIG_FDT) += mpc8544_guts.o ppce500_spin.o
 # PowerPC 440 Xilinx ML507 reference board.
 obj-y += virtex_ml507.o
 # PowerPC OpenPIC
@@ -26,3 +26,5 @@ obj-$(CONFIG_FDT) += ../device_tree.o
 obj-y += xilinx_ethlite.o
 
 obj-y := $(addprefix ../,$(obj-y))
+
+obj-$(CONFIG_FDT) += e500.o
diff --git a/hw/ppc/e500.c b/hw/ppc/e500.c
new file mode 100644
index 0000000..0b383e6
--- /dev/null
+++ b/hw/ppc/e500.c
@@ -0,0 +1,610 @@
+/*
+ * QEMU PowerPC MPC8544DS board emulation
+ *
+ * Copyright (C) 2009 Freescale Semiconductor, Inc. All rights reserved.
+ *
+ * Author: Yu Liu,     <yu.liu at freescale.com>
+ *
+ * This file is derived from hw/ppc440_bamboo.c,
+ * the copyright for that material belongs to the original owners.
+ *
+ * This is free software; you can redistribute it and/or modify
+ * it under the terms of  the GNU General  Public License as published by
+ * the Free Software Foundation;  either version 2 of the  License, or
+ * (at your option) any later version.
+ */
+
+#include "config.h"
+#include "qemu-common.h"
+#include "net.h"
+#include "hw/hw.h"
+#include "hw/pc.h"
+#include "hw/pci.h"
+#include "hw/boards.h"
+#include "sysemu.h"
+#include "kvm.h"
+#include "kvm_ppc.h"
+#include "device_tree.h"
+#include "hw/openpic.h"
+#include "hw/ppc.h"
+#include "hw/loader.h"
+#include "elf.h"
+#include "hw/sysbus.h"
+#include "exec-memory.h"
+#include "host-utils.h"
+
+#define BINARY_DEVICE_TREE_FILE    "mpc8544ds.dtb"
+#define UIMAGE_LOAD_BASE           0
+#define DTC_LOAD_PAD               0x500000
+#define DTC_PAD_MASK               0xFFFFF
+#define INITRD_LOAD_PAD            0x2000000
+#define INITRD_PAD_MASK            0xFFFFFF
+
+#define RAM_SIZES_ALIGN            (64UL << 20)
+
+#define MPC8544_CCSRBAR_BASE       0xE0000000ULL
+#define MPC8544_CCSRBAR_SIZE       0x00100000ULL
+#define MPC8544_MPIC_REGS_BASE     (MPC8544_CCSRBAR_BASE + 0x40000ULL)
+#define MPC8544_SERIAL0_REGS_BASE  (MPC8544_CCSRBAR_BASE + 0x4500ULL)
+#define MPC8544_SERIAL1_REGS_BASE  (MPC8544_CCSRBAR_BASE + 0x4600ULL)
+#define MPC8544_PCI_REGS_BASE      (MPC8544_CCSRBAR_BASE + 0x8000ULL)
+#define MPC8544_PCI_REGS_SIZE      0x1000ULL
+#define MPC8544_PCI_IO             0xE1000000ULL
+#define MPC8544_PCI_IOLEN          0x10000ULL
+#define MPC8544_UTIL_BASE          (MPC8544_CCSRBAR_BASE + 0xe0000ULL)
+#define MPC8544_SPIN_BASE          0xEF000000ULL
+
+struct boot_info
+{
+    uint32_t dt_base;
+    uint32_t dt_size;
+    uint32_t entry;
+};
+
+static void pci_map_create(void *fdt, uint32_t *pci_map, uint32_t mpic)
+{
+    int i;
+    const uint32_t tmp[] = {
+                             /* IDSEL 0x11 J17 Slot 1 */
+                             0x8800, 0x0, 0x0, 0x1, mpic, 0x2, 0x1, 0x0, 0x0,
+                             0x8800, 0x0, 0x0, 0x2, mpic, 0x3, 0x1, 0x0, 0x0,
+                             0x8800, 0x0, 0x0, 0x3, mpic, 0x4, 0x1, 0x0, 0x0,
+                             0x8800, 0x0, 0x0, 0x4, mpic, 0x1, 0x1, 0x0, 0x0,
+
+                             /* IDSEL 0x12 J16 Slot 2 */
+                             0x9000, 0x0, 0x0, 0x1, mpic, 0x3, 0x1, 0x0, 0x0,
+                             0x9000, 0x0, 0x0, 0x2, mpic, 0x4, 0x1, 0x0, 0x0,
+                             0x9000, 0x0, 0x0, 0x3, mpic, 0x2, 0x1, 0x0, 0x0,
+                             0x9000, 0x0, 0x0, 0x4, mpic, 0x1, 0x1, 0x0, 0x0,
+                           };
+    for (i = 0; i < ARRAY_SIZE(tmp); i++) {
+        pci_map[i] = cpu_to_be32(tmp[i]);
+    }
+}
+
+static void dt_serial_create(void *fdt, unsigned long long offset,
+                             const char *soc, const char *mpic,
+                             const char *alias, int idx, bool defcon)
+{
+    char ser[128];
+
+    snprintf(ser, sizeof(ser), "%s/serial@%llx", soc, offset);
+    qemu_devtree_add_subnode(fdt, ser);
+    qemu_devtree_setprop_string(fdt, ser, "device_type", "serial");
+    qemu_devtree_setprop_string(fdt, ser, "compatible", "ns16550");
+    qemu_devtree_setprop_cells(fdt, ser, "reg", offset, 0x100);
+    qemu_devtree_setprop_cell(fdt, ser, "cell-index", idx);
+    qemu_devtree_setprop_cell(fdt, ser, "clock-frequency", 0);
+    qemu_devtree_setprop_cells(fdt, ser, "interrupts", 42, 2, 0, 0);
+    qemu_devtree_setprop_phandle(fdt, ser, "interrupt-parent", mpic);
+    qemu_devtree_setprop_string(fdt, "/aliases", alias, ser);
+
+    if (defcon) {
+        qemu_devtree_setprop_string(fdt, "/chosen", "linux,stdout-path", ser);
+    }
+}
+
+static int mpc8544_load_device_tree(CPUPPCState *env,
+                                    target_phys_addr_t addr,
+                                    target_phys_addr_t ramsize,
+                                    target_phys_addr_t initrd_base,
+                                    target_phys_addr_t initrd_size,
+                                    const char *kernel_cmdline)
+{
+    int ret = -1;
+    uint64_t mem_reg_property[] = { 0, cpu_to_be64(ramsize) };
+    int fdt_size;
+    void *fdt;
+    uint8_t hypercall[16];
+    uint32_t clock_freq = 400000000;
+    uint32_t tb_freq = 400000000;
+    int i;
+    const char *compatible = "MPC8544DS\0MPC85xxDS";
+    int compatible_len = sizeof("MPC8544DS\0MPC85xxDS");
+    char compatible_sb[] = "fsl,mpc8544-immr\0simple-bus";
+    char model[] = "MPC8544DS";
+    char soc[128];
+    char mpic[128];
+    uint32_t mpic_ph;
+    char gutil[128];
+    char pci[128];
+    uint32_t pci_map[9 * 8];
+    uint32_t pci_ranges[14] =
+        {
+            0x2000000, 0x0, 0xc0000000,
+            0x0, 0xc0000000,
+            0x0, 0x20000000,
+
+            0x1000000, 0x0, 0x0,
+            0x0, 0xe1000000,
+            0x0, 0x10000,
+        };
+    QemuOpts *machine_opts;
+    const char *dumpdtb = NULL;
+    const char *dtb_file = NULL;
+
+    machine_opts = qemu_opts_find(qemu_find_opts("machine"), 0);
+    if (machine_opts) {
+        const char *tmp;
+        dumpdtb = qemu_opt_get(machine_opts, "dumpdtb");
+        dtb_file = qemu_opt_get(machine_opts, "dtb");
+        tmp = qemu_opt_get(machine_opts, "dt_compatible");
+        if (tmp) {
+            compatible = tmp;
+            compatible_len = strlen(compatible) + 1;
+        }
+    }
+
+    if (dtb_file) {
+        char *filename;
+        filename = qemu_find_file(QEMU_FILE_TYPE_BIOS, dtb_file);
+        if (!filename) {
+            goto out;
+        }
+
+        fdt = load_device_tree(filename, &fdt_size);
+        if (!fdt) {
+            goto out;
+        }
+        goto done;
+    }
+
+    fdt = create_device_tree(&fdt_size);
+    if (fdt == NULL) {
+        goto out;
+    }
+
+    /* Manipulate device tree in memory. */
+    qemu_devtree_setprop_string(fdt, "/", "model", model);
+    qemu_devtree_setprop(fdt, "/", "compatible", compatible, compatible_len);
+    qemu_devtree_setprop_cell(fdt, "/", "#address-cells", 2);
+    qemu_devtree_setprop_cell(fdt, "/", "#size-cells", 2);
+
+    qemu_devtree_add_subnode(fdt, "/memory");
+    qemu_devtree_setprop_string(fdt, "/memory", "device_type", "memory");
+    qemu_devtree_setprop(fdt, "/memory", "reg", mem_reg_property,
+                         sizeof(mem_reg_property));
+
+    qemu_devtree_add_subnode(fdt, "/chosen");
+    if (initrd_size) {
+        ret = qemu_devtree_setprop_cell(fdt, "/chosen", "linux,initrd-start",
+                                        initrd_base);
+        if (ret < 0) {
+            fprintf(stderr, "couldn't set /chosen/linux,initrd-start\n");
+        }
+
+        ret = qemu_devtree_setprop_cell(fdt, "/chosen", "linux,initrd-end",
+                                        (initrd_base + initrd_size));
+        if (ret < 0) {
+            fprintf(stderr, "couldn't set /chosen/linux,initrd-end\n");
+        }
+    }
+
+    ret = qemu_devtree_setprop_string(fdt, "/chosen", "bootargs",
+                                      kernel_cmdline);
+    if (ret < 0)
+        fprintf(stderr, "couldn't set /chosen/bootargs\n");
+
+    if (kvm_enabled()) {
+        /* Read out host's frequencies */
+        clock_freq = kvmppc_get_clockfreq();
+        tb_freq = kvmppc_get_tbfreq();
+
+        /* indicate KVM hypercall interface */
+        qemu_devtree_add_subnode(fdt, "/hypervisor");
+        qemu_devtree_setprop_string(fdt, "/hypervisor", "compatible",
+                                    "linux,kvm");
+        kvmppc_get_hypercall(env, hypercall, sizeof(hypercall));
+        qemu_devtree_setprop(fdt, "/hypervisor", "hcall-instructions",
+                             hypercall, sizeof(hypercall));
+    }
+
+    /* Create CPU nodes */
+    qemu_devtree_add_subnode(fdt, "/cpus");
+    qemu_devtree_setprop_cell(fdt, "/cpus", "#address-cells", 1);
+    qemu_devtree_setprop_cell(fdt, "/cpus", "#size-cells", 0);
+
+    /* We need to generate the cpu nodes in reverse order, so Linux can pick
+       the first node as boot node and be happy */
+    for (i = smp_cpus - 1; i >= 0; i--) {
+        char cpu_name[128];
+        uint64_t cpu_release_addr = MPC8544_SPIN_BASE + (i * 0x20);
+
+        for (env = first_cpu; env != NULL; env = env->next_cpu) {
+            if (env->cpu_index == i) {
+                break;
+            }
+        }
+
+        if (!env) {
+            continue;
+        }
+
+        snprintf(cpu_name, sizeof(cpu_name), "/cpus/PowerPC,8544@%x", env->cpu_index);
+        qemu_devtree_add_subnode(fdt, cpu_name);
+        qemu_devtree_setprop_cell(fdt, cpu_name, "clock-frequency", clock_freq);
+        qemu_devtree_setprop_cell(fdt, cpu_name, "timebase-frequency", tb_freq);
+        qemu_devtree_setprop_string(fdt, cpu_name, "device_type", "cpu");
+        qemu_devtree_setprop_cell(fdt, cpu_name, "reg", env->cpu_index);
+        qemu_devtree_setprop_cell(fdt, cpu_name, "d-cache-line-size",
+                                  env->dcache_line_size);
+        qemu_devtree_setprop_cell(fdt, cpu_name, "i-cache-line-size",
+                                  env->icache_line_size);
+        qemu_devtree_setprop_cell(fdt, cpu_name, "d-cache-size", 0x8000);
+        qemu_devtree_setprop_cell(fdt, cpu_name, "i-cache-size", 0x8000);
+        qemu_devtree_setprop_cell(fdt, cpu_name, "bus-frequency", 0);
+        if (env->cpu_index) {
+            qemu_devtree_setprop_string(fdt, cpu_name, "status", "disabled");
+            qemu_devtree_setprop_string(fdt, cpu_name, "enable-method", "spin-table");
+            qemu_devtree_setprop_u64(fdt, cpu_name, "cpu-release-addr",
+                                     cpu_release_addr);
+        } else {
+            qemu_devtree_setprop_string(fdt, cpu_name, "status", "okay");
+        }
+    }
+
+    qemu_devtree_add_subnode(fdt, "/aliases");
+    /* XXX These should go into their respective devices' code */
+    snprintf(soc, sizeof(soc), "/soc@%llx", MPC8544_CCSRBAR_BASE);
+    qemu_devtree_add_subnode(fdt, soc);
+    qemu_devtree_setprop_string(fdt, soc, "device_type", "soc");
+    qemu_devtree_setprop(fdt, soc, "compatible", compatible_sb,
+                         sizeof(compatible_sb));
+    qemu_devtree_setprop_cell(fdt, soc, "#address-cells", 1);
+    qemu_devtree_setprop_cell(fdt, soc, "#size-cells", 1);
+    qemu_devtree_setprop_cells(fdt, soc, "ranges", 0x0,
+                               MPC8544_CCSRBAR_BASE >> 32, MPC8544_CCSRBAR_BASE,
+                               MPC8544_CCSRBAR_SIZE);
+    /* XXX should contain a reasonable value */
+    qemu_devtree_setprop_cell(fdt, soc, "bus-frequency", 0);
+
+    snprintf(mpic, sizeof(mpic), "%s/pic@%llx", soc,
+             MPC8544_MPIC_REGS_BASE - MPC8544_CCSRBAR_BASE);
+    qemu_devtree_add_subnode(fdt, mpic);
+    qemu_devtree_setprop_string(fdt, mpic, "device_type", "open-pic");
+    qemu_devtree_setprop_string(fdt, mpic, "compatible", "fsl,mpic");
+    qemu_devtree_setprop_cells(fdt, mpic, "reg", MPC8544_MPIC_REGS_BASE -
+                               MPC8544_CCSRBAR_BASE, 0x40000);
+    qemu_devtree_setprop_cell(fdt, mpic, "#address-cells", 0);
+    qemu_devtree_setprop_cell(fdt, mpic, "#interrupt-cells", 4);
+    mpic_ph = qemu_devtree_alloc_phandle(fdt);
+    qemu_devtree_setprop_cell(fdt, mpic, "phandle", mpic_ph);
+    qemu_devtree_setprop_cell(fdt, mpic, "linux,phandle", mpic_ph);
+    qemu_devtree_setprop(fdt, mpic, "interrupt-controller", NULL, 0);
+    qemu_devtree_setprop(fdt, mpic, "big-endian", NULL, 0);
+    qemu_devtree_setprop(fdt, mpic, "single-cpu-affinity", NULL, 0);
+    qemu_devtree_setprop_cell(fdt, mpic, "last-interrupt-source", 255);
+
+    /*
+     * We have to generate ser1 first, because Linux takes the first
+     * device it finds in the dt as serial output device. And we generate
+     * devices in reverse order to the dt.
+     */
+    dt_serial_create(fdt, MPC8544_SERIAL1_REGS_BASE - MPC8544_CCSRBAR_BASE,
+                     soc, mpic, "serial1", 1, false);
+    dt_serial_create(fdt, MPC8544_SERIAL0_REGS_BASE - MPC8544_CCSRBAR_BASE,
+                     soc, mpic, "serial0", 0, true);
+
+    snprintf(gutil, sizeof(gutil), "%s/global-utilities@%llx", soc,
+             MPC8544_UTIL_BASE - MPC8544_CCSRBAR_BASE);
+    qemu_devtree_add_subnode(fdt, gutil);
+    qemu_devtree_setprop_string(fdt, gutil, "compatible", "fsl,mpc8544-guts");
+    qemu_devtree_setprop_cells(fdt, gutil, "reg", MPC8544_UTIL_BASE -
+                               MPC8544_CCSRBAR_BASE, 0x1000);
+    qemu_devtree_setprop(fdt, gutil, "fsl,has-rstcr", NULL, 0);
+
+    snprintf(pci, sizeof(pci), "/pci@%llx", MPC8544_PCI_REGS_BASE);
+    qemu_devtree_add_subnode(fdt, pci);
+    qemu_devtree_setprop_cell(fdt, pci, "cell-index", 0);
+    qemu_devtree_setprop_string(fdt, pci, "compatible", "fsl,mpc8540-pci");
+    qemu_devtree_setprop_string(fdt, pci, "device_type", "pci");
+    qemu_devtree_setprop_cells(fdt, pci, "interrupt-map-mask", 0xf800, 0x0,
+                               0x0, 0x7);
+    pci_map_create(fdt, pci_map, qemu_devtree_get_phandle(fdt, mpic));
+    qemu_devtree_setprop(fdt, pci, "interrupt-map", pci_map, sizeof(pci_map));
+    qemu_devtree_setprop_phandle(fdt, pci, "interrupt-parent", mpic);
+    qemu_devtree_setprop_cells(fdt, pci, "interrupts", 24, 2, 0, 0);
+    qemu_devtree_setprop_cells(fdt, pci, "bus-range", 0, 255);
+    for (i = 0; i < 14; i++) {
+        pci_ranges[i] = cpu_to_be32(pci_ranges[i]);
+    }
+    qemu_devtree_setprop(fdt, pci, "ranges", pci_ranges, sizeof(pci_ranges));
+    qemu_devtree_setprop_cells(fdt, pci, "reg", MPC8544_PCI_REGS_BASE >> 32,
+                               MPC8544_PCI_REGS_BASE, 0, 0x1000);
+    qemu_devtree_setprop_cell(fdt, pci, "clock-frequency", 66666666);
+    qemu_devtree_setprop_cell(fdt, pci, "#interrupt-cells", 1);
+    qemu_devtree_setprop_cell(fdt, pci, "#size-cells", 2);
+    qemu_devtree_setprop_cell(fdt, pci, "#address-cells", 3);
+    qemu_devtree_setprop_string(fdt, "/aliases", "pci0", pci);
+
+done:
+    if (dumpdtb) {
+        /* Dump the dtb to a file and quit */
+        FILE *f = fopen(dumpdtb, "wb");
+        size_t len;
+        len = fwrite(fdt, fdt_size, 1, f);
+        fclose(f);
+        if (len != fdt_size) {
+            exit(1);
+        }
+        exit(0);
+    }
+
+    ret = rom_add_blob_fixed(BINARY_DEVICE_TREE_FILE, fdt, fdt_size, addr);
+    if (ret < 0) {
+        goto out;
+    }
+    g_free(fdt);
+    ret = fdt_size;
+
+out:
+
+    return ret;
+}
+
+/* Create -kernel TLB entries for BookE.  */
+static inline target_phys_addr_t booke206_page_size_to_tlb(uint64_t size)
+{
+    return 63 - clz64(size >> 10);
+}
+
+static void mmubooke_create_initial_mapping(CPUPPCState *env)
+{
+    struct boot_info *bi = env->load_info;
+    ppcmas_tlb_t *tlb = booke206_get_tlbm(env, 1, 0, 0);
+    target_phys_addr_t size, dt_end;
+    int ps;
+
+    /* Our initial TLB entry needs to cover everything from 0 to
+       the device tree top */
+    dt_end = bi->dt_base + bi->dt_size;
+    ps = booke206_page_size_to_tlb(dt_end) + 1;
+    size = (ps << MAS1_TSIZE_SHIFT);
+    tlb->mas1 = MAS1_VALID | size;
+    tlb->mas2 = 0;
+    tlb->mas7_3 = 0;
+    tlb->mas7_3 |= MAS3_UR | MAS3_UW | MAS3_UX | MAS3_SR | MAS3_SW | MAS3_SX;
+
+    env->tlb_dirty = true;
+}
+
+static void mpc8544ds_cpu_reset_sec(void *opaque)
+{
+    PowerPCCPU *cpu = opaque;
+    CPUPPCState *env = &cpu->env;
+
+    cpu_reset(CPU(cpu));
+
+    /* Secondary CPU starts in halted state for now. Needs to change when
+       implementing non-kernel boot. */
+    env->halted = 1;
+    env->exception_index = EXCP_HLT;
+}
+
+static void mpc8544ds_cpu_reset(void *opaque)
+{
+    PowerPCCPU *cpu = opaque;
+    CPUPPCState *env = &cpu->env;
+    struct boot_info *bi = env->load_info;
+
+    cpu_reset(CPU(cpu));
+
+    /* Set initial guest state. */
+    env->halted = 0;
+    env->gpr[1] = (16<<20) - 8;
+    env->gpr[3] = bi->dt_base;
+    env->nip = bi->entry;
+    mmubooke_create_initial_mapping(env);
+}
+
+static void mpc8544ds_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)
+{
+    MemoryRegion *address_space_mem = get_system_memory();
+    MemoryRegion *ram = g_new(MemoryRegion, 1);
+    PCIBus *pci_bus;
+    CPUPPCState *env = NULL;
+    uint64_t elf_entry;
+    uint64_t elf_lowaddr;
+    target_phys_addr_t entry=0;
+    target_phys_addr_t loadaddr=UIMAGE_LOAD_BASE;
+    target_long kernel_size=0;
+    target_ulong dt_base = 0;
+    target_ulong initrd_base = 0;
+    target_long initrd_size=0;
+    int i=0;
+    unsigned int pci_irq_nrs[4] = {1, 2, 3, 4};
+    qemu_irq **irqs, *mpic;
+    DeviceState *dev;
+    CPUPPCState *firstenv = NULL;
+
+    /* Setup CPUs */
+    if (cpu_model == NULL) {
+        cpu_model = "e500v2_v30";
+    }
+
+    irqs = g_malloc0(smp_cpus * sizeof(qemu_irq *));
+    irqs[0] = g_malloc0(smp_cpus * sizeof(qemu_irq) * OPENPIC_OUTPUT_NB);
+    for (i = 0; i < smp_cpus; i++) {
+        PowerPCCPU *cpu;
+        qemu_irq *input;
+
+        cpu = cpu_ppc_init(cpu_model);
+        if (cpu == NULL) {
+            fprintf(stderr, "Unable to initialize CPU!\n");
+            exit(1);
+        }
+        env = &cpu->env;
+
+        if (!firstenv) {
+            firstenv = env;
+        }
+
+        irqs[i] = irqs[0] + (i * OPENPIC_OUTPUT_NB);
+        input = (qemu_irq *)env->irq_inputs;
+        irqs[i][OPENPIC_OUTPUT_INT] = input[PPCE500_INPUT_INT];
+        irqs[i][OPENPIC_OUTPUT_CINT] = input[PPCE500_INPUT_CINT];
+        env->spr[SPR_BOOKE_PIR] = env->cpu_index = i;
+        env->mpic_cpu_base = MPC8544_MPIC_REGS_BASE + 0x20000;
+
+        ppc_booke_timers_init(env, 400000000, PPC_TIMER_E500);
+
+        /* Register reset handler */
+        if (!i) {
+            /* Primary CPU */
+            struct boot_info *boot_info;
+            boot_info = g_malloc0(sizeof(struct boot_info));
+            qemu_register_reset(mpc8544ds_cpu_reset, cpu);
+            env->load_info = boot_info;
+        } else {
+            /* Secondary CPUs */
+            qemu_register_reset(mpc8544ds_cpu_reset_sec, cpu);
+        }
+    }
+
+    env = firstenv;
+
+    /* Fixup Memory size on a alignment boundary */
+    ram_size &= ~(RAM_SIZES_ALIGN - 1);
+
+    /* Register Memory */
+    memory_region_init_ram(ram, "mpc8544ds.ram", ram_size);
+    vmstate_register_ram_global(ram);
+    memory_region_add_subregion(address_space_mem, 0, ram);
+
+    /* MPIC */
+    mpic = mpic_init(address_space_mem, MPC8544_MPIC_REGS_BASE,
+                     smp_cpus, irqs, NULL);
+
+    if (!mpic) {
+        cpu_abort(env, "MPIC failed to initialize\n");
+    }
+
+    /* Serial */
+    if (serial_hds[0]) {
+        serial_mm_init(address_space_mem, MPC8544_SERIAL0_REGS_BASE,
+                       0, mpic[12+26], 399193,
+                       serial_hds[0], DEVICE_BIG_ENDIAN);
+    }
+
+    if (serial_hds[1]) {
+        serial_mm_init(address_space_mem, MPC8544_SERIAL1_REGS_BASE,
+                       0, mpic[12+26], 399193,
+                       serial_hds[0], DEVICE_BIG_ENDIAN);
+    }
+
+    /* General Utility device */
+    sysbus_create_simple("mpc8544-guts", MPC8544_UTIL_BASE, NULL);
+
+    /* PCI */
+    dev = sysbus_create_varargs("e500-pcihost", MPC8544_PCI_REGS_BASE,
+                                mpic[pci_irq_nrs[0]], mpic[pci_irq_nrs[1]],
+                                mpic[pci_irq_nrs[2]], mpic[pci_irq_nrs[3]],
+                                NULL);
+    pci_bus = (PCIBus *)qdev_get_child_bus(dev, "pci.0");
+    if (!pci_bus)
+        printf("couldn't create PCI controller!\n");
+
+    isa_mmio_init(MPC8544_PCI_IO, MPC8544_PCI_IOLEN);
+
+    if (pci_bus) {
+        /* Register network interfaces. */
+        for (i = 0; i < nb_nics; i++) {
+            pci_nic_init_nofail(&nd_table[i], "virtio", NULL);
+        }
+    }
+
+    /* Register spinning region */
+    sysbus_create_simple("e500-spin", MPC8544_SPIN_BASE, NULL);
+
+    /* Load kernel. */
+    if (kernel_filename) {
+        kernel_size = load_uimage(kernel_filename, &entry, &loadaddr, NULL);
+        if (kernel_size < 0) {
+            kernel_size = load_elf(kernel_filename, NULL, NULL, &elf_entry,
+                                   &elf_lowaddr, NULL, 1, ELF_MACHINE, 0);
+            entry = elf_entry;
+            loadaddr = elf_lowaddr;
+        }
+        /* XXX try again as binary */
+        if (kernel_size < 0) {
+            fprintf(stderr, "qemu: could not load kernel '%s'\n",
+                    kernel_filename);
+            exit(1);
+        }
+    }
+
+    /* Load initrd. */
+    if (initrd_filename) {
+        initrd_base = (kernel_size + INITRD_LOAD_PAD) & ~INITRD_PAD_MASK;
+        initrd_size = load_image_targphys(initrd_filename, initrd_base,
+                                          ram_size - initrd_base);
+
+        if (initrd_size < 0) {
+            fprintf(stderr, "qemu: could not load initial ram disk '%s'\n",
+                    initrd_filename);
+            exit(1);
+        }
+    }
+
+    /* If we're loading a kernel directly, we must load the device tree too. */
+    if (kernel_filename) {
+        struct boot_info *boot_info;
+        int dt_size;
+
+        dt_base = (loadaddr + kernel_size + DTC_LOAD_PAD) & ~DTC_PAD_MASK;
+        dt_size = mpc8544_load_device_tree(env, dt_base, ram_size, initrd_base,
+                                           initrd_size, kernel_cmdline);
+        if (dt_size < 0) {
+            fprintf(stderr, "couldn't load device tree\n");
+            exit(1);
+        }
+
+        boot_info = env->load_info;
+        boot_info->entry = entry;
+        boot_info->dt_base = dt_base;
+        boot_info->dt_size = dt_size;
+    }
+
+    if (kvm_enabled()) {
+        kvmppc_init();
+    }
+}
+
+static QEMUMachine mpc8544ds_machine = {
+    .name = "mpc8544ds",
+    .desc = "mpc8544ds",
+    .init = mpc8544ds_init,
+    .max_cpus = 15,
+};
+
+static void mpc8544ds_machine_init(void)
+{
+    qemu_register_machine(&mpc8544ds_machine);
+}
+
+machine_init(mpc8544ds_machine_init);
diff --git a/hw/ppce500_mpc8544ds.c b/hw/ppce500_mpc8544ds.c
deleted file mode 100644
index 8b9fd83..0000000
--- a/hw/ppce500_mpc8544ds.c
+++ /dev/null
@@ -1,610 +0,0 @@
-/*
- * QEMU PowerPC MPC8544DS board emulation
- *
- * Copyright (C) 2009 Freescale Semiconductor, Inc. All rights reserved.
- *
- * Author: Yu Liu,     <yu.liu at freescale.com>
- *
- * This file is derived from hw/ppc440_bamboo.c,
- * the copyright for that material belongs to the original owners.
- *
- * This is free software; you can redistribute it and/or modify
- * it under the terms of  the GNU General  Public License as published by
- * the Free Software Foundation;  either version 2 of the  License, or
- * (at your option) any later version.
- */
-
-#include "config.h"
-#include "qemu-common.h"
-#include "net.h"
-#include "hw.h"
-#include "pc.h"
-#include "pci.h"
-#include "boards.h"
-#include "sysemu.h"
-#include "kvm.h"
-#include "kvm_ppc.h"
-#include "device_tree.h"
-#include "openpic.h"
-#include "ppc.h"
-#include "loader.h"
-#include "elf.h"
-#include "sysbus.h"
-#include "exec-memory.h"
-#include "host-utils.h"
-
-#define BINARY_DEVICE_TREE_FILE    "mpc8544ds.dtb"
-#define UIMAGE_LOAD_BASE           0
-#define DTC_LOAD_PAD               0x500000
-#define DTC_PAD_MASK               0xFFFFF
-#define INITRD_LOAD_PAD            0x2000000
-#define INITRD_PAD_MASK            0xFFFFFF
-
-#define RAM_SIZES_ALIGN            (64UL << 20)
-
-#define MPC8544_CCSRBAR_BASE       0xE0000000ULL
-#define MPC8544_CCSRBAR_SIZE       0x00100000ULL
-#define MPC8544_MPIC_REGS_BASE     (MPC8544_CCSRBAR_BASE + 0x40000ULL)
-#define MPC8544_SERIAL0_REGS_BASE  (MPC8544_CCSRBAR_BASE + 0x4500ULL)
-#define MPC8544_SERIAL1_REGS_BASE  (MPC8544_CCSRBAR_BASE + 0x4600ULL)
-#define MPC8544_PCI_REGS_BASE      (MPC8544_CCSRBAR_BASE + 0x8000ULL)
-#define MPC8544_PCI_REGS_SIZE      0x1000ULL
-#define MPC8544_PCI_IO             0xE1000000ULL
-#define MPC8544_PCI_IOLEN          0x10000ULL
-#define MPC8544_UTIL_BASE          (MPC8544_CCSRBAR_BASE + 0xe0000ULL)
-#define MPC8544_SPIN_BASE          0xEF000000ULL
-
-struct boot_info
-{
-    uint32_t dt_base;
-    uint32_t dt_size;
-    uint32_t entry;
-};
-
-static void pci_map_create(void *fdt, uint32_t *pci_map, uint32_t mpic)
-{
-    int i;
-    const uint32_t tmp[] = {
-                             /* IDSEL 0x11 J17 Slot 1 */
-                             0x8800, 0x0, 0x0, 0x1, mpic, 0x2, 0x1, 0x0, 0x0,
-                             0x8800, 0x0, 0x0, 0x2, mpic, 0x3, 0x1, 0x0, 0x0,
-                             0x8800, 0x0, 0x0, 0x3, mpic, 0x4, 0x1, 0x0, 0x0,
-                             0x8800, 0x0, 0x0, 0x4, mpic, 0x1, 0x1, 0x0, 0x0,
-
-                             /* IDSEL 0x12 J16 Slot 2 */
-                             0x9000, 0x0, 0x0, 0x1, mpic, 0x3, 0x1, 0x0, 0x0,
-                             0x9000, 0x0, 0x0, 0x2, mpic, 0x4, 0x1, 0x0, 0x0,
-                             0x9000, 0x0, 0x0, 0x3, mpic, 0x2, 0x1, 0x0, 0x0,
-                             0x9000, 0x0, 0x0, 0x4, mpic, 0x1, 0x1, 0x0, 0x0,
-                           };
-    for (i = 0; i < ARRAY_SIZE(tmp); i++) {
-        pci_map[i] = cpu_to_be32(tmp[i]);
-    }
-}
-
-static void dt_serial_create(void *fdt, unsigned long long offset,
-                             const char *soc, const char *mpic,
-                             const char *alias, int idx, bool defcon)
-{
-    char ser[128];
-
-    snprintf(ser, sizeof(ser), "%s/serial@%llx", soc, offset);
-    qemu_devtree_add_subnode(fdt, ser);
-    qemu_devtree_setprop_string(fdt, ser, "device_type", "serial");
-    qemu_devtree_setprop_string(fdt, ser, "compatible", "ns16550");
-    qemu_devtree_setprop_cells(fdt, ser, "reg", offset, 0x100);
-    qemu_devtree_setprop_cell(fdt, ser, "cell-index", idx);
-    qemu_devtree_setprop_cell(fdt, ser, "clock-frequency", 0);
-    qemu_devtree_setprop_cells(fdt, ser, "interrupts", 42, 2, 0, 0);
-    qemu_devtree_setprop_phandle(fdt, ser, "interrupt-parent", mpic);
-    qemu_devtree_setprop_string(fdt, "/aliases", alias, ser);
-
-    if (defcon) {
-        qemu_devtree_setprop_string(fdt, "/chosen", "linux,stdout-path", ser);
-    }
-}
-
-static int mpc8544_load_device_tree(CPUPPCState *env,
-                                    target_phys_addr_t addr,
-                                    target_phys_addr_t ramsize,
-                                    target_phys_addr_t initrd_base,
-                                    target_phys_addr_t initrd_size,
-                                    const char *kernel_cmdline)
-{
-    int ret = -1;
-    uint64_t mem_reg_property[] = { 0, cpu_to_be64(ramsize) };
-    int fdt_size;
-    void *fdt;
-    uint8_t hypercall[16];
-    uint32_t clock_freq = 400000000;
-    uint32_t tb_freq = 400000000;
-    int i;
-    const char *compatible = "MPC8544DS\0MPC85xxDS";
-    int compatible_len = sizeof("MPC8544DS\0MPC85xxDS");
-    char compatible_sb[] = "fsl,mpc8544-immr\0simple-bus";
-    char model[] = "MPC8544DS";
-    char soc[128];
-    char mpic[128];
-    uint32_t mpic_ph;
-    char gutil[128];
-    char pci[128];
-    uint32_t pci_map[9 * 8];
-    uint32_t pci_ranges[14] =
-        {
-            0x2000000, 0x0, 0xc0000000,
-            0x0, 0xc0000000,
-            0x0, 0x20000000,
-
-            0x1000000, 0x0, 0x0,
-            0x0, 0xe1000000,
-            0x0, 0x10000,
-        };
-    QemuOpts *machine_opts;
-    const char *dumpdtb = NULL;
-    const char *dtb_file = NULL;
-
-    machine_opts = qemu_opts_find(qemu_find_opts("machine"), 0);
-    if (machine_opts) {
-        const char *tmp;
-        dumpdtb = qemu_opt_get(machine_opts, "dumpdtb");
-        dtb_file = qemu_opt_get(machine_opts, "dtb");
-        tmp = qemu_opt_get(machine_opts, "dt_compatible");
-        if (tmp) {
-            compatible = tmp;
-            compatible_len = strlen(compatible) + 1;
-        }
-    }
-
-    if (dtb_file) {
-        char *filename;
-        filename = qemu_find_file(QEMU_FILE_TYPE_BIOS, dtb_file);
-        if (!filename) {
-            goto out;
-        }
-
-        fdt = load_device_tree(filename, &fdt_size);
-        if (!fdt) {
-            goto out;
-        }
-        goto done;
-    }
-
-    fdt = create_device_tree(&fdt_size);
-    if (fdt == NULL) {
-        goto out;
-    }
-
-    /* Manipulate device tree in memory. */
-    qemu_devtree_setprop_string(fdt, "/", "model", model);
-    qemu_devtree_setprop(fdt, "/", "compatible", compatible, compatible_len);
-    qemu_devtree_setprop_cell(fdt, "/", "#address-cells", 2);
-    qemu_devtree_setprop_cell(fdt, "/", "#size-cells", 2);
-
-    qemu_devtree_add_subnode(fdt, "/memory");
-    qemu_devtree_setprop_string(fdt, "/memory", "device_type", "memory");
-    qemu_devtree_setprop(fdt, "/memory", "reg", mem_reg_property,
-                         sizeof(mem_reg_property));
-
-    qemu_devtree_add_subnode(fdt, "/chosen");
-    if (initrd_size) {
-        ret = qemu_devtree_setprop_cell(fdt, "/chosen", "linux,initrd-start",
-                                        initrd_base);
-        if (ret < 0) {
-            fprintf(stderr, "couldn't set /chosen/linux,initrd-start\n");
-        }
-
-        ret = qemu_devtree_setprop_cell(fdt, "/chosen", "linux,initrd-end",
-                                        (initrd_base + initrd_size));
-        if (ret < 0) {
-            fprintf(stderr, "couldn't set /chosen/linux,initrd-end\n");
-        }
-    }
-
-    ret = qemu_devtree_setprop_string(fdt, "/chosen", "bootargs",
-                                      kernel_cmdline);
-    if (ret < 0)
-        fprintf(stderr, "couldn't set /chosen/bootargs\n");
-
-    if (kvm_enabled()) {
-        /* Read out host's frequencies */
-        clock_freq = kvmppc_get_clockfreq();
-        tb_freq = kvmppc_get_tbfreq();
-
-        /* indicate KVM hypercall interface */
-        qemu_devtree_add_subnode(fdt, "/hypervisor");
-        qemu_devtree_setprop_string(fdt, "/hypervisor", "compatible",
-                                    "linux,kvm");
-        kvmppc_get_hypercall(env, hypercall, sizeof(hypercall));
-        qemu_devtree_setprop(fdt, "/hypervisor", "hcall-instructions",
-                             hypercall, sizeof(hypercall));
-    }
-
-    /* Create CPU nodes */
-    qemu_devtree_add_subnode(fdt, "/cpus");
-    qemu_devtree_setprop_cell(fdt, "/cpus", "#address-cells", 1);
-    qemu_devtree_setprop_cell(fdt, "/cpus", "#size-cells", 0);
-
-    /* We need to generate the cpu nodes in reverse order, so Linux can pick
-       the first node as boot node and be happy */
-    for (i = smp_cpus - 1; i >= 0; i--) {
-        char cpu_name[128];
-        uint64_t cpu_release_addr = MPC8544_SPIN_BASE + (i * 0x20);
-
-        for (env = first_cpu; env != NULL; env = env->next_cpu) {
-            if (env->cpu_index == i) {
-                break;
-            }
-        }
-
-        if (!env) {
-            continue;
-        }
-
-        snprintf(cpu_name, sizeof(cpu_name), "/cpus/PowerPC,8544@%x", env->cpu_index);
-        qemu_devtree_add_subnode(fdt, cpu_name);
-        qemu_devtree_setprop_cell(fdt, cpu_name, "clock-frequency", clock_freq);
-        qemu_devtree_setprop_cell(fdt, cpu_name, "timebase-frequency", tb_freq);
-        qemu_devtree_setprop_string(fdt, cpu_name, "device_type", "cpu");
-        qemu_devtree_setprop_cell(fdt, cpu_name, "reg", env->cpu_index);
-        qemu_devtree_setprop_cell(fdt, cpu_name, "d-cache-line-size",
-                                  env->dcache_line_size);
-        qemu_devtree_setprop_cell(fdt, cpu_name, "i-cache-line-size",
-                                  env->icache_line_size);
-        qemu_devtree_setprop_cell(fdt, cpu_name, "d-cache-size", 0x8000);
-        qemu_devtree_setprop_cell(fdt, cpu_name, "i-cache-size", 0x8000);
-        qemu_devtree_setprop_cell(fdt, cpu_name, "bus-frequency", 0);
-        if (env->cpu_index) {
-            qemu_devtree_setprop_string(fdt, cpu_name, "status", "disabled");
-            qemu_devtree_setprop_string(fdt, cpu_name, "enable-method", "spin-table");
-            qemu_devtree_setprop_u64(fdt, cpu_name, "cpu-release-addr",
-                                     cpu_release_addr);
-        } else {
-            qemu_devtree_setprop_string(fdt, cpu_name, "status", "okay");
-        }
-    }
-
-    qemu_devtree_add_subnode(fdt, "/aliases");
-    /* XXX These should go into their respective devices' code */
-    snprintf(soc, sizeof(soc), "/soc@%llx", MPC8544_CCSRBAR_BASE);
-    qemu_devtree_add_subnode(fdt, soc);
-    qemu_devtree_setprop_string(fdt, soc, "device_type", "soc");
-    qemu_devtree_setprop(fdt, soc, "compatible", compatible_sb,
-                         sizeof(compatible_sb));
-    qemu_devtree_setprop_cell(fdt, soc, "#address-cells", 1);
-    qemu_devtree_setprop_cell(fdt, soc, "#size-cells", 1);
-    qemu_devtree_setprop_cells(fdt, soc, "ranges", 0x0,
-                               MPC8544_CCSRBAR_BASE >> 32, MPC8544_CCSRBAR_BASE,
-                               MPC8544_CCSRBAR_SIZE);
-    /* XXX should contain a reasonable value */
-    qemu_devtree_setprop_cell(fdt, soc, "bus-frequency", 0);
-
-    snprintf(mpic, sizeof(mpic), "%s/pic@%llx", soc,
-             MPC8544_MPIC_REGS_BASE - MPC8544_CCSRBAR_BASE);
-    qemu_devtree_add_subnode(fdt, mpic);
-    qemu_devtree_setprop_string(fdt, mpic, "device_type", "open-pic");
-    qemu_devtree_setprop_string(fdt, mpic, "compatible", "fsl,mpic");
-    qemu_devtree_setprop_cells(fdt, mpic, "reg", MPC8544_MPIC_REGS_BASE -
-                               MPC8544_CCSRBAR_BASE, 0x40000);
-    qemu_devtree_setprop_cell(fdt, mpic, "#address-cells", 0);
-    qemu_devtree_setprop_cell(fdt, mpic, "#interrupt-cells", 4);
-    mpic_ph = qemu_devtree_alloc_phandle(fdt);
-    qemu_devtree_setprop_cell(fdt, mpic, "phandle", mpic_ph);
-    qemu_devtree_setprop_cell(fdt, mpic, "linux,phandle", mpic_ph);
-    qemu_devtree_setprop(fdt, mpic, "interrupt-controller", NULL, 0);
-    qemu_devtree_setprop(fdt, mpic, "big-endian", NULL, 0);
-    qemu_devtree_setprop(fdt, mpic, "single-cpu-affinity", NULL, 0);
-    qemu_devtree_setprop_cell(fdt, mpic, "last-interrupt-source", 255);
-
-    /*
-     * We have to generate ser1 first, because Linux takes the first
-     * device it finds in the dt as serial output device. And we generate
-     * devices in reverse order to the dt.
-     */
-    dt_serial_create(fdt, MPC8544_SERIAL1_REGS_BASE - MPC8544_CCSRBAR_BASE,
-                     soc, mpic, "serial1", 1, false);
-    dt_serial_create(fdt, MPC8544_SERIAL0_REGS_BASE - MPC8544_CCSRBAR_BASE,
-                     soc, mpic, "serial0", 0, true);
-
-    snprintf(gutil, sizeof(gutil), "%s/global-utilities@%llx", soc,
-             MPC8544_UTIL_BASE - MPC8544_CCSRBAR_BASE);
-    qemu_devtree_add_subnode(fdt, gutil);
-    qemu_devtree_setprop_string(fdt, gutil, "compatible", "fsl,mpc8544-guts");
-    qemu_devtree_setprop_cells(fdt, gutil, "reg", MPC8544_UTIL_BASE -
-                               MPC8544_CCSRBAR_BASE, 0x1000);
-    qemu_devtree_setprop(fdt, gutil, "fsl,has-rstcr", NULL, 0);
-
-    snprintf(pci, sizeof(pci), "/pci@%llx", MPC8544_PCI_REGS_BASE);
-    qemu_devtree_add_subnode(fdt, pci);
-    qemu_devtree_setprop_cell(fdt, pci, "cell-index", 0);
-    qemu_devtree_setprop_string(fdt, pci, "compatible", "fsl,mpc8540-pci");
-    qemu_devtree_setprop_string(fdt, pci, "device_type", "pci");
-    qemu_devtree_setprop_cells(fdt, pci, "interrupt-map-mask", 0xf800, 0x0,
-                               0x0, 0x7);
-    pci_map_create(fdt, pci_map, qemu_devtree_get_phandle(fdt, mpic));
-    qemu_devtree_setprop(fdt, pci, "interrupt-map", pci_map, sizeof(pci_map));
-    qemu_devtree_setprop_phandle(fdt, pci, "interrupt-parent", mpic);
-    qemu_devtree_setprop_cells(fdt, pci, "interrupts", 24, 2, 0, 0);
-    qemu_devtree_setprop_cells(fdt, pci, "bus-range", 0, 255);
-    for (i = 0; i < 14; i++) {
-        pci_ranges[i] = cpu_to_be32(pci_ranges[i]);
-    }
-    qemu_devtree_setprop(fdt, pci, "ranges", pci_ranges, sizeof(pci_ranges));
-    qemu_devtree_setprop_cells(fdt, pci, "reg", MPC8544_PCI_REGS_BASE >> 32,
-                               MPC8544_PCI_REGS_BASE, 0, 0x1000);
-    qemu_devtree_setprop_cell(fdt, pci, "clock-frequency", 66666666);
-    qemu_devtree_setprop_cell(fdt, pci, "#interrupt-cells", 1);
-    qemu_devtree_setprop_cell(fdt, pci, "#size-cells", 2);
-    qemu_devtree_setprop_cell(fdt, pci, "#address-cells", 3);
-    qemu_devtree_setprop_string(fdt, "/aliases", "pci0", pci);
-
-done:
-    if (dumpdtb) {
-        /* Dump the dtb to a file and quit */
-        FILE *f = fopen(dumpdtb, "wb");
-        size_t len;
-        len = fwrite(fdt, fdt_size, 1, f);
-        fclose(f);
-        if (len != fdt_size) {
-            exit(1);
-        }
-        exit(0);
-    }
-
-    ret = rom_add_blob_fixed(BINARY_DEVICE_TREE_FILE, fdt, fdt_size, addr);
-    if (ret < 0) {
-        goto out;
-    }
-    g_free(fdt);
-    ret = fdt_size;
-
-out:
-
-    return ret;
-}
-
-/* Create -kernel TLB entries for BookE.  */
-static inline target_phys_addr_t booke206_page_size_to_tlb(uint64_t size)
-{
-    return 63 - clz64(size >> 10);
-}
-
-static void mmubooke_create_initial_mapping(CPUPPCState *env)
-{
-    struct boot_info *bi = env->load_info;
-    ppcmas_tlb_t *tlb = booke206_get_tlbm(env, 1, 0, 0);
-    target_phys_addr_t size, dt_end;
-    int ps;
-
-    /* Our initial TLB entry needs to cover everything from 0 to
-       the device tree top */
-    dt_end = bi->dt_base + bi->dt_size;
-    ps = booke206_page_size_to_tlb(dt_end) + 1;
-    size = (ps << MAS1_TSIZE_SHIFT);
-    tlb->mas1 = MAS1_VALID | size;
-    tlb->mas2 = 0;
-    tlb->mas7_3 = 0;
-    tlb->mas7_3 |= MAS3_UR | MAS3_UW | MAS3_UX | MAS3_SR | MAS3_SW | MAS3_SX;
-
-    env->tlb_dirty = true;
-}
-
-static void mpc8544ds_cpu_reset_sec(void *opaque)
-{
-    PowerPCCPU *cpu = opaque;
-    CPUPPCState *env = &cpu->env;
-
-    cpu_reset(CPU(cpu));
-
-    /* Secondary CPU starts in halted state for now. Needs to change when
-       implementing non-kernel boot. */
-    env->halted = 1;
-    env->exception_index = EXCP_HLT;
-}
-
-static void mpc8544ds_cpu_reset(void *opaque)
-{
-    PowerPCCPU *cpu = opaque;
-    CPUPPCState *env = &cpu->env;
-    struct boot_info *bi = env->load_info;
-
-    cpu_reset(CPU(cpu));
-
-    /* Set initial guest state. */
-    env->halted = 0;
-    env->gpr[1] = (16<<20) - 8;
-    env->gpr[3] = bi->dt_base;
-    env->nip = bi->entry;
-    mmubooke_create_initial_mapping(env);
-}
-
-static void mpc8544ds_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)
-{
-    MemoryRegion *address_space_mem = get_system_memory();
-    MemoryRegion *ram = g_new(MemoryRegion, 1);
-    PCIBus *pci_bus;
-    CPUPPCState *env = NULL;
-    uint64_t elf_entry;
-    uint64_t elf_lowaddr;
-    target_phys_addr_t entry=0;
-    target_phys_addr_t loadaddr=UIMAGE_LOAD_BASE;
-    target_long kernel_size=0;
-    target_ulong dt_base = 0;
-    target_ulong initrd_base = 0;
-    target_long initrd_size=0;
-    int i=0;
-    unsigned int pci_irq_nrs[4] = {1, 2, 3, 4};
-    qemu_irq **irqs, *mpic;
-    DeviceState *dev;
-    CPUPPCState *firstenv = NULL;
-
-    /* Setup CPUs */
-    if (cpu_model == NULL) {
-        cpu_model = "e500v2_v30";
-    }
-
-    irqs = g_malloc0(smp_cpus * sizeof(qemu_irq *));
-    irqs[0] = g_malloc0(smp_cpus * sizeof(qemu_irq) * OPENPIC_OUTPUT_NB);
-    for (i = 0; i < smp_cpus; i++) {
-        PowerPCCPU *cpu;
-        qemu_irq *input;
-
-        cpu = cpu_ppc_init(cpu_model);
-        if (cpu == NULL) {
-            fprintf(stderr, "Unable to initialize CPU!\n");
-            exit(1);
-        }
-        env = &cpu->env;
-
-        if (!firstenv) {
-            firstenv = env;
-        }
-
-        irqs[i] = irqs[0] + (i * OPENPIC_OUTPUT_NB);
-        input = (qemu_irq *)env->irq_inputs;
-        irqs[i][OPENPIC_OUTPUT_INT] = input[PPCE500_INPUT_INT];
-        irqs[i][OPENPIC_OUTPUT_CINT] = input[PPCE500_INPUT_CINT];
-        env->spr[SPR_BOOKE_PIR] = env->cpu_index = i;
-        env->mpic_cpu_base = MPC8544_MPIC_REGS_BASE + 0x20000;
-
-        ppc_booke_timers_init(env, 400000000, PPC_TIMER_E500);
-
-        /* Register reset handler */
-        if (!i) {
-            /* Primary CPU */
-            struct boot_info *boot_info;
-            boot_info = g_malloc0(sizeof(struct boot_info));
-            qemu_register_reset(mpc8544ds_cpu_reset, cpu);
-            env->load_info = boot_info;
-        } else {
-            /* Secondary CPUs */
-            qemu_register_reset(mpc8544ds_cpu_reset_sec, cpu);
-        }
-    }
-
-    env = firstenv;
-
-    /* Fixup Memory size on a alignment boundary */
-    ram_size &= ~(RAM_SIZES_ALIGN - 1);
-
-    /* Register Memory */
-    memory_region_init_ram(ram, "mpc8544ds.ram", ram_size);
-    vmstate_register_ram_global(ram);
-    memory_region_add_subregion(address_space_mem, 0, ram);
-
-    /* MPIC */
-    mpic = mpic_init(address_space_mem, MPC8544_MPIC_REGS_BASE,
-                     smp_cpus, irqs, NULL);
-
-    if (!mpic) {
-        cpu_abort(env, "MPIC failed to initialize\n");
-    }
-
-    /* Serial */
-    if (serial_hds[0]) {
-        serial_mm_init(address_space_mem, MPC8544_SERIAL0_REGS_BASE,
-                       0, mpic[12+26], 399193,
-                       serial_hds[0], DEVICE_BIG_ENDIAN);
-    }
-
-    if (serial_hds[1]) {
-        serial_mm_init(address_space_mem, MPC8544_SERIAL1_REGS_BASE,
-                       0, mpic[12+26], 399193,
-                       serial_hds[0], DEVICE_BIG_ENDIAN);
-    }
-
-    /* General Utility device */
-    sysbus_create_simple("mpc8544-guts", MPC8544_UTIL_BASE, NULL);
-
-    /* PCI */
-    dev = sysbus_create_varargs("e500-pcihost", MPC8544_PCI_REGS_BASE,
-                                mpic[pci_irq_nrs[0]], mpic[pci_irq_nrs[1]],
-                                mpic[pci_irq_nrs[2]], mpic[pci_irq_nrs[3]],
-                                NULL);
-    pci_bus = (PCIBus *)qdev_get_child_bus(dev, "pci.0");
-    if (!pci_bus)
-        printf("couldn't create PCI controller!\n");
-
-    isa_mmio_init(MPC8544_PCI_IO, MPC8544_PCI_IOLEN);
-
-    if (pci_bus) {
-        /* Register network interfaces. */
-        for (i = 0; i < nb_nics; i++) {
-            pci_nic_init_nofail(&nd_table[i], "virtio", NULL);
-        }
-    }
-
-    /* Register spinning region */
-    sysbus_create_simple("e500-spin", MPC8544_SPIN_BASE, NULL);
-
-    /* Load kernel. */
-    if (kernel_filename) {
-        kernel_size = load_uimage(kernel_filename, &entry, &loadaddr, NULL);
-        if (kernel_size < 0) {
-            kernel_size = load_elf(kernel_filename, NULL, NULL, &elf_entry,
-                                   &elf_lowaddr, NULL, 1, ELF_MACHINE, 0);
-            entry = elf_entry;
-            loadaddr = elf_lowaddr;
-        }
-        /* XXX try again as binary */
-        if (kernel_size < 0) {
-            fprintf(stderr, "qemu: could not load kernel '%s'\n",
-                    kernel_filename);
-            exit(1);
-        }
-    }
-
-    /* Load initrd. */
-    if (initrd_filename) {
-        initrd_base = (kernel_size + INITRD_LOAD_PAD) & ~INITRD_PAD_MASK;
-        initrd_size = load_image_targphys(initrd_filename, initrd_base,
-                                          ram_size - initrd_base);
-
-        if (initrd_size < 0) {
-            fprintf(stderr, "qemu: could not load initial ram disk '%s'\n",
-                    initrd_filename);
-            exit(1);
-        }
-    }
-
-    /* If we're loading a kernel directly, we must load the device tree too. */
-    if (kernel_filename) {
-        struct boot_info *boot_info;
-        int dt_size;
-
-        dt_base = (loadaddr + kernel_size + DTC_LOAD_PAD) & ~DTC_PAD_MASK;
-        dt_size = mpc8544_load_device_tree(env, dt_base, ram_size, initrd_base,
-                                           initrd_size, kernel_cmdline);
-        if (dt_size < 0) {
-            fprintf(stderr, "couldn't load device tree\n");
-            exit(1);
-        }
-
-        boot_info = env->load_info;
-        boot_info->entry = entry;
-        boot_info->dt_base = dt_base;
-        boot_info->dt_size = dt_size;
-    }
-
-    if (kvm_enabled()) {
-        kvmppc_init();
-    }
-}
-
-static QEMUMachine mpc8544ds_machine = {
-    .name = "mpc8544ds",
-    .desc = "mpc8544ds",
-    .init = mpc8544ds_init,
-    .max_cpus = 15,
-};
-
-static void mpc8544ds_machine_init(void)
-{
-    qemu_register_machine(&mpc8544ds_machine);
-}
-
-machine_init(mpc8544ds_machine_init);
commit e0fdbd7c1b45c1af034d4070a65067f6635f77b0
Author: Alexey Kardashevskiy <aik at ozlabs.ru>
Date:   Wed Jun 13 18:40:06 2012 +0000

    pseries pci: spapr_populate_pci_devices renamed to spapr_populate_pci_dt
    
    spapr_populate_pci_devices() populates the device tree only with bus
    properties and has nothing to do with the devices on it as PCI BAR
    allocation is done by the system firmware (SLOF).
    
    New name - spapr_populate_pci_dt() - describes the functionality better.
    
    Signed-off-by: Alexey Kardashevskiy <aik at ozlabs.ru>
    Signed-off-by: Alexander Graf <agraf at suse.de>

diff --git a/hw/spapr.c b/hw/spapr.c
index 81c9343..ab5a0c2 100644
--- a/hw/spapr.c
+++ b/hw/spapr.c
@@ -481,7 +481,7 @@ static void spapr_finalize_fdt(sPAPREnvironment *spapr,
     }
 
     QLIST_FOREACH(phb, &spapr->phbs, list) {
-        ret = spapr_populate_pci_devices(phb, PHANDLE_XICP, fdt);
+        ret = spapr_populate_pci_dt(phb, PHANDLE_XICP, fdt);
     }
 
     if (ret < 0) {
diff --git a/hw/spapr_pci.c b/hw/spapr_pci.c
index 5bee180..2913540 100644
--- a/hw/spapr_pci.c
+++ b/hw/spapr_pci.c
@@ -406,9 +406,9 @@ void spapr_create_phb(sPAPREnvironment *spapr,
 #define b_fff(x)        b_x((x), 8, 3)  /* function number */
 #define b_rrrrrrrr(x)   b_x((x), 0, 8)  /* register number */
 
-int spapr_populate_pci_devices(sPAPRPHBState *phb,
-                               uint32_t xics_phandle,
-                               void *fdt)
+int spapr_populate_pci_dt(sPAPRPHBState *phb,
+                          uint32_t xics_phandle,
+                          void *fdt)
 {
     int bus_off, i, j;
     char nodename[256];
diff --git a/hw/spapr_pci.h b/hw/spapr_pci.h
index a141764..dd66f4b 100644
--- a/hw/spapr_pci.h
+++ b/hw/spapr_pci.h
@@ -55,8 +55,8 @@ void spapr_create_phb(sPAPREnvironment *spapr,
                       uint64_t mem_win_addr, uint64_t mem_win_size,
                       uint64_t io_win_addr);
 
-int spapr_populate_pci_devices(sPAPRPHBState *phb,
-                               uint32_t xics_phandle,
-                               void *fdt);
+int spapr_populate_pci_dt(sPAPRPHBState *phb,
+                          uint32_t xics_phandle,
+                          void *fdt);
 
 #endif /* __HW_SPAPR_PCI_H__ */
commit 231903bf27c18ba6d4d905601eab368f324159eb
Author: Alexey Kardashevskiy <aik at ozlabs.ru>
Date:   Wed Jun 13 18:38:50 2012 +0000

    pseries pci: removed redundant busdev
    
    The PCIHostState struct already contains SysBusDevice so
    the one in sPAPRPHBState has to go.
    
    Signed-off-by: Alexey Kardashevskiy <aik at ozlabs.ru>
    Signed-off-by: Alexander Graf <agraf at suse.de>

diff --git a/hw/spapr_pci.c b/hw/spapr_pci.c
index b2e4f78..5bee180 100644
--- a/hw/spapr_pci.c
+++ b/hw/spapr_pci.c
@@ -276,7 +276,7 @@ static DMAContext *spapr_pci_dma_context_fn(PCIBus *bus, void *opaque,
 
 static int spapr_phb_init(SysBusDevice *s)
 {
-    sPAPRPHBState *phb = FROM_SYSBUS(sPAPRPHBState, s);
+    sPAPRPHBState *phb = DO_UPCAST(sPAPRPHBState, host_state.busdev, s);
     char *namebuf;
     int i;
     PCIBus *bus;
@@ -314,7 +314,7 @@ static int spapr_phb_init(SysBusDevice *s)
     memory_region_add_subregion(get_system_memory(), phb->io_win_addr,
                                 &phb->iowindow);
 
-    bus = pci_register_bus(&phb->busdev.qdev,
+    bus = pci_register_bus(&phb->host_state.busdev.qdev,
                            phb->busname ? phb->busname : phb->dtbusname,
                            pci_spapr_set_irq, pci_spapr_map_irq, phb,
                            &phb->memspace, &phb->iospace,
diff --git a/hw/spapr_pci.h b/hw/spapr_pci.h
index d9e46e2..a141764 100644
--- a/hw/spapr_pci.h
+++ b/hw/spapr_pci.h
@@ -28,7 +28,6 @@
 #include "hw/xics.h"
 
 typedef struct sPAPRPHBState {
-    SysBusDevice busdev;
     PCIHostState host_state;
 
     uint64_t buid;
commit cc92186773df8c9aae8f812fff85e7325e1d7583
Merge: 8fa27d2... 256d046...
Author: Anthony Liguori <aliguori at us.ibm.com>
Date:   Wed Aug 15 11:15:02 2012 -0500

    Merge remote-tracking branch 'qemu-kvm/uq/master' into staging
    
    * qemu-kvm/uq/master:
      update-linux-headers.sh: Pull in asm-generic/kvm_para.h
      kvmvapic: Disable if there is insufficient memory
      kvm: i8254: Finish time conversion fix
      kvm: i8254: Cache kernel clock offset in KVMPITState

commit 8fa27d21a993e261137d15def5475ba2c4d8985b
Merge: 03834e2... 4552e41...
Author: Anthony Liguori <aliguori at us.ibm.com>
Date:   Wed Aug 15 11:14:06 2012 -0500

    Merge remote-tracking branch 'stefanha/tracing' into staging
    
    * stefanha/tracing:
      trace/simple: Replace asprintf by g_strdup_printf
      trace/simple: Fix compiler warning for 32 bit hosts
      trace: avoid pointer aliasing in trace_record_finish()
      trace: drop unused TraceBufferRecord->next_tbuf_idx field
      trace: remove unnecessary write_to_buffer() typecasting
      trace: rename TraceRecordHeader to TraceLogHeader

commit 000a1a3800b532f97b939ebb777d5a14418f44a6
Author: Christian Borntraeger <borntraeger at de.ibm.com>
Date:   Mon Jul 23 21:37:05 2012 +0000

    s390: provide interface for service interrupt/introduce interrupt.c
    
    This patch creates interrupt.c. The first user is a callback for hw/*
    code to trigger an service interrupt for a given sccb value. Several
    interrupt types for s390 are floating (can be delivered to all CPUs).
    so this code does not belong to a specific CPU.
    Other interrupts (like the virtio one) are also floating and can be
    moved here later on.
    
    Signed-off-by: Christian Borntraeger <borntraeger at de.ibm.com>
    Signed-off-by: Alexander Graf <agraf at suse.de>

diff --git a/target-s390x/Makefile.objs b/target-s390x/Makefile.objs
index 262747f..80be3bb 100644
--- a/target-s390x/Makefile.objs
+++ b/target-s390x/Makefile.objs
@@ -1,4 +1,4 @@
-obj-y += translate.o op_helper.o helper.o cpu.o
+obj-y += translate.o op_helper.o helper.o cpu.o interrupt.o
 obj-$(CONFIG_SOFTMMU) += machine.o
 obj-$(CONFIG_KVM) += kvm.o
 
diff --git a/target-s390x/cpu.h b/target-s390x/cpu.h
index c30ac3a..18ac6e3 100644
--- a/target-s390x/cpu.h
+++ b/target-s390x/cpu.h
@@ -320,6 +320,9 @@ S390CPU *s390_cpu_addr2state(uint16_t cpu_addr);
 void s390_add_running_cpu(CPUS390XState *env);
 unsigned s390_del_running_cpu(CPUS390XState *env);
 
+/* service interrupts are floating therefore we must not pass an cpustate */
+void s390_sclp_extint(uint32_t parm);
+
 /* from s390-virtio-bus */
 extern const target_phys_addr_t virtio_size;
 
diff --git a/target-s390x/interrupt.c b/target-s390x/interrupt.c
new file mode 100644
index 0000000..c1b034f
--- /dev/null
+++ b/target-s390x/interrupt.c
@@ -0,0 +1,29 @@
+/*
+ * QEMU S/390 Interrupt support
+ *
+ * Copyright IBM, Corp. 2012
+ *
+ * This work is licensed under the terms of the GNU GPL, version 2 or (at your
+ * option) any later version.  See the COPYING file in the top-level directory.
+ */
+
+#include "cpu.h"
+#include "kvm.h"
+
+#if !defined(CONFIG_USER_ONLY)
+/* service interrupts are floating therefore we must not pass an cpustate */
+void s390_sclp_extint(uint32_t parm)
+{
+    S390CPU *dummy_cpu = s390_cpu_addr2state(0);
+    CPUS390XState *env = &dummy_cpu->env;
+
+    if (kvm_enabled()) {
+#ifdef CONFIG_KVM
+        kvm_s390_interrupt_internal(env, KVM_S390_INT_SERVICE, parm, 0, 1);
+#endif
+    } else {
+        env->psw.addr += 4;
+        cpu_inject_ext(env, EXT_SERVICE, parm, 0);
+    }
+}
+#endif
diff --git a/target-s390x/op_helper.c b/target-s390x/op_helper.c
index 91dd8dc..abc35dd 100644
--- a/target-s390x/op_helper.c
+++ b/target-s390x/op_helper.c
@@ -2362,12 +2362,6 @@ static void program_interrupt(CPUS390XState *env, uint32_t code, int ilc)
     }
 }
 
-static void ext_interrupt(CPUS390XState *env, int type, uint32_t param,
-                          uint64_t param64)
-{
-    cpu_inject_ext(env, type, param, param64);
-}
-
 /*
  * ret < 0 indicates program check, ret = 0,1,2,3 -> cc
  */
@@ -2398,15 +2392,7 @@ int sclp_service_call(CPUS390XState *env, uint32_t sccb, uint64_t code)
             stb_phys(sccb + SCP_INCREMENT, 1 << shift);
             stw_phys(sccb + SCP_RESPONSE_CODE, 0x10);
 
-            if (kvm_enabled()) {
-#ifdef CONFIG_KVM
-                kvm_s390_interrupt_internal(env, KVM_S390_INT_SERVICE,
-                                            sccb & ~3, 0, 1);
-#endif
-            } else {
-                env->psw.addr += 4;
-                ext_interrupt(env, EXT_SERVICE, sccb & ~3, 0);
-            }
+            s390_sclp_extint(sccb & ~3);
             break;
         default:
 #ifdef DEBUG_HELPER
commit 9abf567d95a4e840df868ca993219175fbef8c22
Author: Christian Borntraeger <borntraeger at de.ibm.com>
Date:   Mon Jul 23 21:37:04 2012 +0000

    s390: Fix error handling and condition code of service call
    
    Invalid sccb addresses will cause specification or addressing exception.
    Lets add those checks. Furthermore, the good case (cc=0) was incorrect
    for KVM, we did not set the CC at all. We now use return codes < 0
    as program checks and return codes > 0 as condition code values.
    
    Signed-off-by: Christian Borntraeger <borntraeger at de.ibm.com>
    Signed-off-by: Alexander Graf <agraf at suse.de>

diff --git a/target-s390x/kvm.c b/target-s390x/kvm.c
index 47008c2..07edf93 100644
--- a/target-s390x/kvm.c
+++ b/target-s390x/kvm.c
@@ -273,9 +273,10 @@ static int kvm_sclp_service_call(CPUS390XState *env, struct kvm_run *run,
     code = env->regs[(ipbh0 & 0xf0) >> 4];
 
     r = sclp_service_call(env, sccb, code);
-    if (r) {
-        setcc(env, 3);
+    if (r < 0) {
+        enter_pgmcheck(env, -r);
     }
+    setcc(env, r);
 
     return 0;
 }
diff --git a/target-s390x/op_helper.c b/target-s390x/op_helper.c
index 7b72473..91dd8dc 100644
--- a/target-s390x/op_helper.c
+++ b/target-s390x/op_helper.c
@@ -19,6 +19,8 @@
  */
 
 #include "cpu.h"
+#include "memory.h"
+#include "cputlb.h"
 #include "dyngen-exec.h"
 #include "host-utils.h"
 #include "helper.h"
@@ -2366,6 +2368,9 @@ static void ext_interrupt(CPUS390XState *env, int type, uint32_t param,
     cpu_inject_ext(env, type, param, param64);
 }
 
+/*
+ * ret < 0 indicates program check, ret = 0,1,2,3 -> cc
+ */
 int sclp_service_call(CPUS390XState *env, uint32_t sccb, uint64_t code)
 {
     int r = 0;
@@ -2375,10 +2380,12 @@ int sclp_service_call(CPUS390XState *env, uint32_t sccb, uint64_t code)
     printf("sclp(0x%x, 0x%" PRIx64 ")\n", sccb, code);
 #endif
 
+    /* basic checks */
+    if (!memory_region_is_ram(phys_page_find(sccb >> TARGET_PAGE_BITS)->mr)) {
+        return -PGM_ADDRESSING;
+    }
     if (sccb & ~0x7ffffff8ul) {
-        fprintf(stderr, "KVM: invalid sccb address 0x%x\n", sccb);
-        r = -1;
-        goto out;
+        return -PGM_SPECIFICATION;
     }
 
     switch(code) {
@@ -2405,22 +2412,24 @@ int sclp_service_call(CPUS390XState *env, uint32_t sccb, uint64_t code)
 #ifdef DEBUG_HELPER
             printf("KVM: invalid sclp call 0x%x / 0x%" PRIx64 "x\n", sccb, code);
 #endif
-            r = -1;
+            r = 3;
             break;
     }
 
-out:
     return r;
 }
 
 /* SCLP service call */
 uint32_t HELPER(servc)(uint32_t r1, uint64_t r2)
 {
-    if (sclp_service_call(env, r1, r2)) {
-        return 3;
-    }
+    int r;
 
-    return 0;
+    r = sclp_service_call(env, r1, r2);
+    if (r < 0) {
+        program_interrupt(env, -r, 4);
+        return 0;
+    }
+    return r;
 }
 
 /* DIAG */
commit c3594ed73e0a7e7feae309be79f0eb6bafcc02ab
Author: Alberto Garcia <agarcia at igalia.com>
Date:   Tue Aug 14 14:41:28 2012 +0300

    ivshmem, qdev-monitor: fix order of qerror parameters
    
    Now that the QERR_ macros no longer contain a json dictionary,
    the order of some parameters needs to be fixed for them to appear
    correctly.
    
    Signed-off-by: Alberto Garcia <agarcia at igalia.com>
    Reviewed-by: Luiz Capitulino <lcapitulino at redhat.com>
    Signed-off-by: Stefan Hajnoczi <stefanha at linux.vnet.ibm.com>

diff --git a/hw/ivshmem.c b/hw/ivshmem.c
index 0c58161..b4d65a6 100644
--- a/hw/ivshmem.c
+++ b/hw/ivshmem.c
@@ -677,7 +677,8 @@ static int pci_ivshmem_init(PCIDevice *dev)
     }
 
     if (s->role_val == IVSHMEM_PEER) {
-        error_set(&s->migration_blocker, QERR_DEVICE_FEATURE_BLOCKS_MIGRATION, "ivshmem", "peer mode");
+        error_set(&s->migration_blocker, QERR_DEVICE_FEATURE_BLOCKS_MIGRATION,
+                  "peer mode", "ivshmem");
         migrate_add_blocker(s->migration_blocker);
     }
 
diff --git a/hw/qdev-monitor.c b/hw/qdev-monitor.c
index b22a37a..018b386 100644
--- a/hw/qdev-monitor.c
+++ b/hw/qdev-monitor.c
@@ -443,7 +443,7 @@ DeviceState *qdev_device_add(QemuOpts *opts)
         bus = qbus_find_recursive(sysbus_get_default(), NULL, k->bus_type);
         if (!bus) {
             qerror_report(QERR_NO_BUS_FOR_DEVICE,
-                          driver, k->bus_type);
+                          k->bus_type, driver);
             return NULL;
         }
     }
commit bb9558679ffaae062ea26ef97d2273b148e9c515
Author: Peter Maydell <peter.maydell at linaro.org>
Date:   Sat Aug 11 22:24:35 2012 +0100

    iov_send_recv(): Handle zero bytes case even if OS does not
    
    POSIX allows sendmsg() and recvmsg() to fail EMSGSIZE if passed a zero
    msg.msg_iovlen (in particular the MacOS X implementation will do this).
    Handle the case where iov_send_recv() is passed a zero byte count
    explicitly, to avoid accidentally depending on the OS to treat zero
    msg_iovlen as a no-op.
    
    Signed-off-by: Peter Maydell <peter.maydell at linaro.org>
    Acked-by: Michael Tokarev <mjt at tls.msk.ru>
    Signed-off-by: Stefan Hajnoczi <stefanha at linux.vnet.ibm.com>

diff --git a/iov.c b/iov.c
index b333061..60705c7 100644
--- a/iov.c
+++ b/iov.c
@@ -146,6 +146,13 @@ ssize_t iov_send_recv(int sockfd, struct iovec *iov, unsigned iov_cnt,
 {
     ssize_t ret;
     unsigned si, ei;            /* start and end indexes */
+    if (bytes == 0) {
+        /* Catch the do-nothing case early, as otherwise we will pass an
+         * empty iovec to sendmsg/recvmsg(), and not all implementations
+         * accept this.
+         */
+        return 0;
+    }
 
     /* Find the start position, skipping `offset' bytes:
      * first, skip all full-sized vector elements, */
commit 9c6bb55b864d34d78aa617440fc055e1c61cd2a6
Author: Stefan Weil <sw at weilnetz.de>
Date:   Sat Aug 11 21:32:02 2012 +0200

    framebuffer: Fix spelling in comment (leight -> height)
    
    Signed-off-by: Stefan Weil <sw at weilnetz.de>
    Signed-off-by: Stefan Hajnoczi <stefanha at linux.vnet.ibm.com>

diff --git a/hw/framebuffer.c b/hw/framebuffer.c
index f4747cd..85a00a5 100644
--- a/hw/framebuffer.c
+++ b/hw/framebuffer.c
@@ -28,7 +28,7 @@ void framebuffer_update_display(
     MemoryRegion *address_space,
     target_phys_addr_t base,
     int cols, /* Width in pixels.  */
-    int rows, /* Leight in pixels.  */
+    int rows, /* Height in pixels.  */
     int src_width, /* Length of source line, in bytes.  */
     int dest_row_pitch, /* Bytes between adjacent horizontal output pixels.  */
     int dest_col_pitch, /* Bytes between adjacent vertical output pixels.  */
commit 370de0234cb2bff701248a07e8cf37fafc7e1043
Author: Stefan Weil <sw at weilnetz.de>
Date:   Fri Aug 10 21:56:46 2012 +0200

    Spelling fix in comment (peripherans -> peripherals)
    
    Signed-off-by: Stefan Weil <sw at weilnetz.de>
    Signed-off-by: Stefan Hajnoczi <stefanha at linux.vnet.ibm.com>

diff --git a/hw/versatilepb.c b/hw/versatilepb.c
index 4fd5d9b..7a92034 100644
--- a/hw/versatilepb.c
+++ b/hw/versatilepb.c
@@ -162,7 +162,7 @@ static int vpb_sic_init(SysBusDevice *dev)
 /* Board init.  */
 
 /* The AB and PB boards both use the same core, just with different
-   peripherans and expansion busses.  For now we emulate a subset of the
+   peripherals and expansion busses.  For now we emulate a subset of the
    PB peripherals and just change the board ID.  */
 
 static struct arm_boot_info versatile_binfo;
commit 280a66a6ab896252829d049c0a0331716497db7e
Author: Stefan Weil <sw at weilnetz.de>
Date:   Fri Aug 10 21:53:02 2012 +0200

    docs: Fix spelling (propery -> property)
    
    Signed-off-by: Stefan Weil <sw at weilnetz.de>
    Signed-off-by: Stefan Hajnoczi <stefanha at linux.vnet.ibm.com>

diff --git a/docs/bootindex.txt b/docs/bootindex.txt
index 16083b3..803ebfc 100644
--- a/docs/bootindex.txt
+++ b/docs/bootindex.txt
@@ -1,4 +1,4 @@
-= Bootindex propery =
+= Bootindex property =
 
 Block and net devices have bootindex property. This property is used to
 determine the order in which firmware will consider devices for booting
commit eda5edd12db3c172671f12f79d0676eeb78dae73
Author: Stefan Weil <sw at weilnetz.de>
Date:   Fri Aug 10 21:48:07 2012 +0200

    trace: Fix "Qemu" -> "QEMU"
    
    Signed-off-by: Stefan Weil <sw at weilnetz.de>
    Signed-off-by: Stefan Hajnoczi <stefanha at linux.vnet.ibm.com>

diff --git a/scripts/simpletrace.py b/scripts/simpletrace.py
index 9b4419f..8bbcb42 100755
--- a/scripts/simpletrace.py
+++ b/scripts/simpletrace.py
@@ -71,7 +71,7 @@ def read_trace_file(edict, fobj):
 
     log_version = header[2]
     if log_version == 0:
-        raise ValueError('Older log format, not supported with this Qemu release!')
+        raise ValueError('Older log format, not supported with this QEMU release!')
 
     while True:
         rec = read_record(edict, fobj)
commit 116aae36ae446cd97dd0010ae813194042732ccc
Author: Peter Maydell <peter.maydell at linaro.org>
Date:   Fri Aug 10 17:14:05 2012 +0100

    cputlb.c: Fix out of date comment
    
    The comment about the return address from get_page_addr_code() was
    well out of date as phys_ram_base has not existed for some time.
    
    Signed-off-by: Peter Maydell <peter.maydell at linaro.org>
    Signed-off-by: Stefan Hajnoczi <stefanha at linux.vnet.ibm.com>

diff --git a/cputlb.c b/cputlb.c
index 0d1e252..d3e7b25 100644
--- a/cputlb.c
+++ b/cputlb.c
@@ -312,7 +312,9 @@ void tlb_set_page(CPUArchState *env, target_ulong vaddr,
 
 /* NOTE: this function can trigger an exception */
 /* NOTE2: the returned address is not exactly the physical address: it
-   is the offset relative to phys_ram_base */
+ * is actually a ram_addr_t (in system mode; the user mode emulation
+ * version of this function returns a guest virtual address).
+ */
 tb_page_addr_t get_page_addr_code(CPUArchState *env1, target_ulong addr)
 {
     int mmu_idx, page_index, pd;
commit df6839c7f7f0afb208414234903a8f8202fc6770
Author: Alejandro Martinez Ruiz <alex at securiforest.com>
Date:   Tue Aug 14 16:13:02 2012 +0200

    ehci: fix assertion typo
    
    Signed-off-by: Alejandro Martinez Ruiz <alex at securiforest.com>
    Reviewed-by: Andreas Färber <afaerber at suse.de>
    Signed-off-by: Stefan Hajnoczi <stefanha at linux.vnet.ibm.com>

diff --git a/hw/usb/hcd-ehci.c b/hw/usb/hcd-ehci.c
index b043e7c..104c21d 100644
--- a/hw/usb/hcd-ehci.c
+++ b/hw/usb/hcd-ehci.c
@@ -2010,7 +2010,7 @@ static void ehci_fill_queue(EHCIPacket *p)
         p->qtdaddr = qtdaddr;
         p->qtd = qtd;
         p->usb_status = ehci_execute(p, "queue");
-        assert(p->usb_status = USB_RET_ASYNC);
+        assert(p->usb_status == USB_RET_ASYNC);
         p->async = EHCI_ASYNC_INFLIGHT;
     }
 }
commit e743ccecb1148485f0440db28f20f064bb89446e
Author: Peter Maydell <peter.maydell at linaro.org>
Date:   Wed Aug 15 12:29:24 2012 +0100

    Makefile: Avoid explicit list of directories in clean target
    
    Avoid having an explicit list of directories in the 'clean'
    target by using 'find' to remove all .o and .d files instead.
    
    Signed-off-by: Peter Maydell <peter.maydell at linaro.org>
    Reviewed-by: Eric Blake <eblake at redhat.com>
    Signed-off-by: Stefan Hajnoczi <stefanha at linux.vnet.ibm.com>

diff --git a/Makefile b/Makefile
index d736ea5..2964d5c 100644
--- a/Makefile
+++ b/Makefile
@@ -214,13 +214,10 @@ clean:
 # avoid old build problems by removing potentially incorrect old files
 	rm -f config.mak op-i386.h opc-i386.h gen-op-i386.h op-arm.h opc-arm.h gen-op-arm.h
 	rm -f qemu-options.def
-	rm -f *.o *.d *.a *.lo $(TOOLS) $(HELPERS-y) qemu-ga TAGS cscope.* *.pod *~ */*~
+	find . -name '*.[od]' -exec rm -f {} +
+	rm -f *.a *.lo $(TOOLS) $(HELPERS-y) qemu-ga TAGS cscope.* *.pod *~ */*~
 	rm -Rf .libs
-	rm -f slirp/*.o slirp/*.d audio/*.o audio/*.d block/*.o block/*.d net/*.o net/*.d fsdev/*.o fsdev/*.d ui/*.o ui/*.d qapi/*.o qapi/*.d qga/*.o qga/*.d
-	rm -f qom/*.o qom/*.d libuser/qom/*.o libuser/qom/*.d
-	rm -f hw/usb/*.o hw/usb/*.d hw/*.o hw/*.d
 	rm -f qemu-img-cmds.h
-	rm -f trace/*.o trace/*.d
 	rm -f trace-dtrace.dtrace trace-dtrace.dtrace-timestamp
 	@# May not be present in GENERATED_HEADERS
 	rm -f trace-dtrace.h trace-dtrace.h-timestamp
commit 58c8cce21c13bddd332590fb1fd9a5c369975d3f
Author: Kevin Wolf <kwolf at redhat.com>
Date:   Wed Aug 15 14:08:56 2012 +0200

    qemu-iotests: Fix 030 after switch to GenericError
    
    Signed-off-by: Kevin Wolf <kwolf at redhat.com>
    Reviewed-by: Stefan Hajnoczi <stefanha at linux.vnet.ibm.com>

diff --git a/tests/qemu-iotests/030 b/tests/qemu-iotests/030
index cc671dd..f71ab8d 100755
--- a/tests/qemu-iotests/030
+++ b/tests/qemu-iotests/030
@@ -225,8 +225,7 @@ class TestSetSpeed(ImageStreamingTestCase):
         self.assert_no_active_streams()
 
         result = self.vm.qmp('block-stream', device='drive0', speed=-1)
-        self.assert_qmp(result, 'error/class', 'InvalidParameter')
-        self.assert_qmp(result, 'error/data/name', 'speed')
+        self.assert_qmp(result, 'error/class', 'GenericError')
 
         self.assert_no_active_streams()
 
@@ -234,8 +233,7 @@ class TestSetSpeed(ImageStreamingTestCase):
         self.assert_qmp(result, 'return', {})
 
         result = self.vm.qmp('block-job-set-speed', device='drive0', speed=-1)
-        self.assert_qmp(result, 'error/class', 'InvalidParameter')
-        self.assert_qmp(result, 'error/data/name', 'speed')
+        self.assert_qmp(result, 'error/class', 'GenericError')
 
         self.cancel_and_wait()
 
commit d4c823292336598e2a0c79eb38a640d95748e2a2
Author: Kevin Wolf <kwolf at redhat.com>
Date:   Wed Aug 15 12:52:45 2012 +0200

    block: Flush parent to OS with cache=unsafe
    
    Commit 29cdb251 already added a comment that no unnecessary flushes to
    disk will occur, this patch makes the code even get to the point of the
    comment. This is mostly theoretical because in practice we only stack
    one format on top of one protocol, the former implementing flush_to_os
    and the latter only flush_to_disk. It starts to matter when drivers that
    are not on top implement flush_to_os.
    
    Signed-off-by: Kevin Wolf <kwolf at redhat.com>
    Reviewed-by: Stefan Hajnoczi <stefanha at linux.vnet.ibm.com>

diff --git a/block.c b/block.c
index 016858b..470bdcc 100644
--- a/block.c
+++ b/block.c
@@ -3534,7 +3534,7 @@ int coroutine_fn bdrv_co_flush(BlockDriverState *bs)
 
     /* But don't actually force it to the disk with cache=unsafe */
     if (bs->open_flags & BDRV_O_NO_FLUSH) {
-        return 0;
+        goto flush_parent;
     }
 
     if (bs->drv->bdrv_co_flush_to_disk) {
@@ -3573,6 +3573,7 @@ int coroutine_fn bdrv_co_flush(BlockDriverState *bs)
     /* Now flush the underlying protocol.  It will also have BDRV_O_NO_FLUSH
      * in the case of cache=unsafe, so there are no useless flushes.
      */
+flush_parent:
     return bdrv_co_flush(bs->file);
 }
 
commit 64e69e80920d82df3fa679bc41b13770d2f99360
Author: Stefan Priebe <s.priebe at profihost.ag>
Date:   Wed Aug 15 09:09:54 2012 +0200

    iscsi: Fix NULL dereferences / races between task completion and abort
    
    Signed-off-by: Stefan Priebe <s.priebe at profihost.ag>
    Acked-by: Ronnie Sahlberg <ronniesahlberg at gmail.com>
    Signed-off-by: Kevin Wolf <kwolf at redhat.com>

diff --git a/block/iscsi.c b/block/iscsi.c
index 219f927..bb9cf82 100644
--- a/block/iscsi.c
+++ b/block/iscsi.c
@@ -76,6 +76,10 @@ static void
 iscsi_abort_task_cb(struct iscsi_context *iscsi, int status, void *command_data,
                     void *private_data)
 {
+    IscsiAIOCB *acb = (IscsiAIOCB *)private_data;
+
+    scsi_free_scsi_task(acb->task);
+    acb->task = NULL;
 }
 
 static void
@@ -84,15 +88,15 @@ iscsi_aio_cancel(BlockDriverAIOCB *blockacb)
     IscsiAIOCB *acb = (IscsiAIOCB *)blockacb;
     IscsiLun *iscsilun = acb->iscsilun;
 
-    acb->common.cb(acb->common.opaque, -ECANCELED);
     acb->canceled = 1;
 
-    /* send a task mgmt call to the target to cancel the task on the target */
-    iscsi_task_mgmt_abort_task_async(iscsilun->iscsi, acb->task,
-                                     iscsi_abort_task_cb, NULL);
+    acb->common.cb(acb->common.opaque, -ECANCELED);
 
-    /* then also cancel the task locally in libiscsi */
-    iscsi_scsi_task_cancel(iscsilun->iscsi, acb->task);
+    /* send a task mgmt call to the target to cancel the task on the target
+     * this also cancels the task in libiscsi
+     */
+    iscsi_task_mgmt_abort_task_async(iscsilun->iscsi, acb->task,
+                                     iscsi_abort_task_cb, &acb);
 }
 
 static AIOPool iscsi_aio_pool = {
@@ -179,11 +183,18 @@ iscsi_readv_writev_bh_cb(void *p)
 
     qemu_bh_delete(acb->bh);
 
-    if (acb->canceled == 0) {
+    if (!acb->canceled) {
         acb->common.cb(acb->common.opaque, acb->status);
     }
 
     qemu_aio_release(acb);
+
+    if (acb->canceled) {
+        return;
+    }
+
+    scsi_free_scsi_task(acb->task);
+    acb->task = NULL;
 }
 
 
@@ -197,10 +208,8 @@ iscsi_aio_write16_cb(struct iscsi_context *iscsi, int status,
 
     g_free(acb->buf);
 
-    if (acb->canceled != 0) {
+    if (acb->canceled) {
         qemu_aio_release(acb);
-        scsi_free_scsi_task(acb->task);
-        acb->task = NULL;
         return;
     }
 
@@ -212,8 +221,6 @@ iscsi_aio_write16_cb(struct iscsi_context *iscsi, int status,
     }
 
     iscsi_schedule_bh(iscsi_readv_writev_bh_cb, acb);
-    scsi_free_scsi_task(acb->task);
-    acb->task = NULL;
 }
 
 static int64_t sector_qemu2lun(int64_t sector, IscsiLun *iscsilun)
@@ -298,10 +305,8 @@ iscsi_aio_read16_cb(struct iscsi_context *iscsi, int status,
 
     trace_iscsi_aio_read16_cb(iscsi, status, acb, acb->canceled);
 
-    if (acb->canceled != 0) {
+    if (acb->canceled) {
         qemu_aio_release(acb);
-        scsi_free_scsi_task(acb->task);
-        acb->task = NULL;
         return;
     }
 
@@ -313,8 +318,6 @@ iscsi_aio_read16_cb(struct iscsi_context *iscsi, int status,
     }
 
     iscsi_schedule_bh(iscsi_readv_writev_bh_cb, acb);
-    scsi_free_scsi_task(acb->task);
-    acb->task = NULL;
 }
 
 static BlockDriverAIOCB *
@@ -414,10 +417,8 @@ iscsi_synccache10_cb(struct iscsi_context *iscsi, int status,
 {
     IscsiAIOCB *acb = opaque;
 
-    if (acb->canceled != 0) {
+    if (acb->canceled) {
         qemu_aio_release(acb);
-        scsi_free_scsi_task(acb->task);
-        acb->task = NULL;
         return;
     }
 
@@ -429,8 +430,6 @@ iscsi_synccache10_cb(struct iscsi_context *iscsi, int status,
     }
 
     iscsi_schedule_bh(iscsi_readv_writev_bh_cb, acb);
-    scsi_free_scsi_task(acb->task);
-    acb->task = NULL;
 }
 
 static BlockDriverAIOCB *
@@ -468,10 +467,8 @@ iscsi_unmap_cb(struct iscsi_context *iscsi, int status,
 {
     IscsiAIOCB *acb = opaque;
 
-    if (acb->canceled != 0) {
+    if (acb->canceled) {
         qemu_aio_release(acb);
-        scsi_free_scsi_task(acb->task);
-        acb->task = NULL;
         return;
     }
 
@@ -483,8 +480,6 @@ iscsi_unmap_cb(struct iscsi_context *iscsi, int status,
     }
 
     iscsi_schedule_bh(iscsi_readv_writev_bh_cb, acb);
-    scsi_free_scsi_task(acb->task);
-    acb->task = NULL;
 }
 
 static BlockDriverAIOCB *
@@ -528,10 +523,8 @@ iscsi_aio_ioctl_cb(struct iscsi_context *iscsi, int status,
 {
     IscsiAIOCB *acb = opaque;
 
-    if (acb->canceled != 0) {
+    if (acb->canceled) {
         qemu_aio_release(acb);
-        scsi_free_scsi_task(acb->task);
-        acb->task = NULL;
         return;
     }
 
@@ -560,8 +553,6 @@ iscsi_aio_ioctl_cb(struct iscsi_context *iscsi, int status,
     }
 
     iscsi_schedule_bh(iscsi_readv_writev_bh_cb, acb);
-    scsi_free_scsi_task(acb->task);
-    acb->task = NULL;
 }
 
 static BlockDriverAIOCB *iscsi_aio_ioctl(BlockDriverState *bs,
commit efb87c169740e618ec548c45c819a43e0ade2bab
Author: Corey Bryant <coreyb at linux.vnet.ibm.com>
Date:   Tue Aug 14 16:43:48 2012 -0400

    monitor: Clean up fd sets on monitor disconnect
    
    Fd sets are shared by all monitor connections.  Fd sets are considered
    to be in use while at least one monitor is connected.  When the last
    monitor disconnects, all fds that are members of an fd set with no
    outstanding dup references are closed.  This prevents any fd leakage
    associated with a client disconnect prior to using a passed fd.
    
    Signed-off-by: Corey Bryant <coreyb at linux.vnet.ibm.com>
    Signed-off-by: Kevin Wolf <kwolf at redhat.com>

diff --git a/monitor.c b/monitor.c
index a4a29b9..ce42466 100644
--- a/monitor.c
+++ b/monitor.c
@@ -200,6 +200,7 @@ struct Monitor {
 
 static QLIST_HEAD(mon_list, Monitor) mon_list;
 static QLIST_HEAD(mon_fdsets, MonFdset) mon_fdsets;
+static int mon_refcount;
 
 static mon_cmd_t mon_cmds[];
 static mon_cmd_t info_cmds[];
@@ -2391,7 +2392,8 @@ static void monitor_fdset_cleanup(MonFdset *mon_fdset)
     MonFdsetFd *mon_fdset_fd_next;
 
     QLIST_FOREACH_SAFE(mon_fdset_fd, &mon_fdset->fds, next, mon_fdset_fd_next) {
-        if (mon_fdset_fd->removed) {
+        if (mon_fdset_fd->removed ||
+                (QLIST_EMPTY(&mon_fdset->dup_fds) && mon_refcount == 0)) {
             close(mon_fdset_fd->fd);
             g_free(mon_fdset_fd->opaque);
             QLIST_REMOVE(mon_fdset_fd, next);
@@ -2405,6 +2407,16 @@ static void monitor_fdset_cleanup(MonFdset *mon_fdset)
     }
 }
 
+static void monitor_fdsets_cleanup(void)
+{
+    MonFdset *mon_fdset;
+    MonFdset *mon_fdset_next;
+
+    QLIST_FOREACH_SAFE(mon_fdset, &mon_fdsets, next, mon_fdset_next) {
+        monitor_fdset_cleanup(mon_fdset);
+    }
+}
+
 AddfdInfo *qmp_add_fd(bool has_fdset_id, int64_t fdset_id, bool has_opaque,
                       const char *opaque, Error **errp)
 {
@@ -4824,9 +4836,12 @@ static void monitor_control_event(void *opaque, int event)
         data = get_qmp_greeting();
         monitor_json_emitter(mon, data);
         qobject_decref(data);
+        mon_refcount++;
         break;
     case CHR_EVENT_CLOSED:
         json_message_parser_destroy(&mon->mc->parser);
+        mon_refcount--;
+        monitor_fdsets_cleanup();
         break;
     }
 }
@@ -4867,6 +4882,12 @@ static void monitor_event(void *opaque, int event)
             readline_show_prompt(mon->rs);
         }
         mon->reset_seen = 1;
+        mon_refcount++;
+        break;
+
+    case CHR_EVENT_CLOSED:
+        mon_refcount--;
+        monitor_fdsets_cleanup();
         break;
     }
 }
commit adb696f3d8535119fe0f5363de79a29e6bda83ed
Author: Corey Bryant <coreyb at linux.vnet.ibm.com>
Date:   Tue Aug 14 16:43:47 2012 -0400

    block: Enable qemu_open/close to work with fd sets
    
    When qemu_open is passed a filename of the "/dev/fdset/nnn"
    format (where nnn is the fdset ID), an fd with matching access
    mode flags will be searched for within the specified monitor
    fd set.  If the fd is found, a dup of the fd will be returned
    from qemu_open.
    
    Signed-off-by: Corey Bryant <coreyb at linux.vnet.ibm.com>
    Signed-off-by: Kevin Wolf <kwolf at redhat.com>

diff --git a/Makefile b/Makefile
index d736ea5..6a65f8f 100644
--- a/Makefile
+++ b/Makefile
@@ -148,9 +148,6 @@ install-libcacard: libcacard.la
 	$(call quiet-command,$(MAKE) $(SUBDIR_MAKEFLAGS) -C libcacard V="$(V)" TARGET_DIR="$*/" install-libcacard,)
 endif
 
-vscclient$(EXESUF): $(libcacard-y) $(oslib-obj-y) $(trace-obj-y) qemu-timer-common.o libcacard/vscclient.o
-	$(call quiet-command,$(CC) $(LDFLAGS) -o $@ $^ $(libcacard_libs) $(LIBS),"  LINK  $@")
-
 ######################################################################
 
 qemu-img.o: qemu-img-cmds.h
@@ -166,6 +163,9 @@ qemu-io$(EXESUF): qemu-io.o cmd.o $(tools-obj-y) $(block-obj-y)
 
 qemu-bridge-helper$(EXESUF): qemu-bridge-helper.o
 
+vscclient$(EXESUF): $(libcacard-y) $(oslib-obj-y) $(trace-obj-y) $(tools-obj-y) qemu-timer-common.o libcacard/vscclient.o
+	$(call quiet-command,$(CC) $(LDFLAGS) -o $@ $^ $(libcacard_libs) $(LIBS),"  LINK  $@")
+
 fsdev/virtfs-proxy-helper$(EXESUF): fsdev/virtfs-proxy-helper.o fsdev/virtio-9p-marshal.o oslib-posix.o $(trace-obj-y)
 fsdev/virtfs-proxy-helper$(EXESUF): LIBS += -lcap
 
diff --git a/cutils.c b/cutils.c
index ee4614d..8ef648f 100644
--- a/cutils.c
+++ b/cutils.c
@@ -383,6 +383,11 @@ int qemu_parse_fd(const char *param)
     return fd;
 }
 
+int qemu_parse_fdset(const char *param)
+{
+    return qemu_parse_fd(param);
+}
+
 /* round down to the nearest power of 2*/
 int64_t pow2floor(int64_t value)
 {
diff --git a/monitor.c b/monitor.c
index 8d813d5..a4a29b9 100644
--- a/monitor.c
+++ b/monitor.c
@@ -154,6 +154,7 @@ typedef struct MonFdset MonFdset;
 struct MonFdset {
     int64_t id;
     QLIST_HEAD(, MonFdsetFd) fds;
+    QLIST_HEAD(, MonFdsetFd) dup_fds;
     QLIST_ENTRY(MonFdset) next;
 };
 
@@ -2398,7 +2399,7 @@ static void monitor_fdset_cleanup(MonFdset *mon_fdset)
         }
     }
 
-    if (QLIST_EMPTY(&mon_fdset->fds)) {
+    if (QLIST_EMPTY(&mon_fdset->fds) && QLIST_EMPTY(&mon_fdset->dup_fds)) {
         QLIST_REMOVE(mon_fdset, next);
         g_free(mon_fdset);
     }
@@ -2555,6 +2556,89 @@ FdsetInfoList *qmp_query_fdsets(Error **errp)
     return fdset_list;
 }
 
+int monitor_fdset_get_fd(int64_t fdset_id, int flags)
+{
+    MonFdset *mon_fdset;
+    MonFdsetFd *mon_fdset_fd;
+    int mon_fd_flags;
+
+#ifndef _WIN32
+    QLIST_FOREACH(mon_fdset, &mon_fdsets, next) {
+        if (mon_fdset->id != fdset_id) {
+            continue;
+        }
+        QLIST_FOREACH(mon_fdset_fd, &mon_fdset->fds, next) {
+            mon_fd_flags = fcntl(mon_fdset_fd->fd, F_GETFL);
+            if (mon_fd_flags == -1) {
+                return -1;
+            }
+
+            if ((flags & O_ACCMODE) == (mon_fd_flags & O_ACCMODE)) {
+                return mon_fdset_fd->fd;
+            }
+        }
+        errno = EACCES;
+        return -1;
+    }
+#endif
+
+    errno = ENOENT;
+    return -1;
+}
+
+int monitor_fdset_dup_fd_add(int64_t fdset_id, int dup_fd)
+{
+    MonFdset *mon_fdset;
+    MonFdsetFd *mon_fdset_fd_dup;
+
+    QLIST_FOREACH(mon_fdset, &mon_fdsets, next) {
+        if (mon_fdset->id != fdset_id) {
+            continue;
+        }
+        QLIST_FOREACH(mon_fdset_fd_dup, &mon_fdset->dup_fds, next) {
+            if (mon_fdset_fd_dup->fd == dup_fd) {
+                return -1;
+            }
+        }
+        mon_fdset_fd_dup = g_malloc0(sizeof(*mon_fdset_fd_dup));
+        mon_fdset_fd_dup->fd = dup_fd;
+        QLIST_INSERT_HEAD(&mon_fdset->dup_fds, mon_fdset_fd_dup, next);
+        return 0;
+    }
+    return -1;
+}
+
+static int monitor_fdset_dup_fd_find_remove(int dup_fd, bool remove)
+{
+    MonFdset *mon_fdset;
+    MonFdsetFd *mon_fdset_fd_dup;
+
+    QLIST_FOREACH(mon_fdset, &mon_fdsets, next) {
+        QLIST_FOREACH(mon_fdset_fd_dup, &mon_fdset->dup_fds, next) {
+            if (mon_fdset_fd_dup->fd == dup_fd) {
+                if (remove) {
+                    QLIST_REMOVE(mon_fdset_fd_dup, next);
+                    if (QLIST_EMPTY(&mon_fdset->dup_fds)) {
+                        monitor_fdset_cleanup(mon_fdset);
+                    }
+                }
+                return mon_fdset->id;
+            }
+        }
+    }
+    return -1;
+}
+
+int monitor_fdset_dup_fd_find(int dup_fd)
+{
+    return monitor_fdset_dup_fd_find_remove(dup_fd, false);
+}
+
+int monitor_fdset_dup_fd_remove(int dup_fd)
+{
+    return monitor_fdset_dup_fd_find_remove(dup_fd, true);
+}
+
 /* mon_cmds and info_cmds would be sorted at runtime */
 static mon_cmd_t mon_cmds[] = {
 #include "hmp-commands.h"
diff --git a/monitor.h b/monitor.h
index 4ef9a04..47d556b 100644
--- a/monitor.h
+++ b/monitor.h
@@ -87,4 +87,9 @@ int qmp_qom_set(Monitor *mon, const QDict *qdict, QObject **ret);
 
 int qmp_qom_get(Monitor *mon, const QDict *qdict, QObject **ret);
 
+int monitor_fdset_get_fd(int64_t fdset_id, int flags);
+int monitor_fdset_dup_fd_add(int64_t fdset_id, int dup_fd);
+int monitor_fdset_dup_fd_remove(int dup_fd);
+int monitor_fdset_dup_fd_find(int dup_fd);
+
 #endif /* !MONITOR_H */
diff --git a/osdep.c b/osdep.c
index 7f876ae..5b78cee 100644
--- a/osdep.c
+++ b/osdep.c
@@ -48,6 +48,7 @@ extern int madvise(caddr_t, size_t, int);
 #include "qemu-common.h"
 #include "trace.h"
 #include "qemu_socket.h"
+#include "monitor.h"
 
 static bool fips_enabled = false;
 
@@ -78,6 +79,66 @@ int qemu_madvise(void *addr, size_t len, int advice)
 #endif
 }
 
+#ifndef _WIN32
+/*
+ * Dups an fd and sets the flags
+ */
+static int qemu_dup_flags(int fd, int flags)
+{
+    int ret;
+    int serrno;
+    int dup_flags;
+    int setfl_flags;
+
+#ifdef F_DUPFD_CLOEXEC
+    ret = fcntl(fd, F_DUPFD_CLOEXEC, 0);
+#else
+    ret = dup(fd);
+    if (ret != -1) {
+        qemu_set_cloexec(ret);
+    }
+#endif
+    if (ret == -1) {
+        goto fail;
+    }
+
+    dup_flags = fcntl(ret, F_GETFL);
+    if (dup_flags == -1) {
+        goto fail;
+    }
+
+    if ((flags & O_SYNC) != (dup_flags & O_SYNC)) {
+        errno = EINVAL;
+        goto fail;
+    }
+
+    /* Set/unset flags that we can with fcntl */
+    setfl_flags = O_APPEND | O_ASYNC | O_DIRECT | O_NOATIME | O_NONBLOCK;
+    dup_flags &= ~setfl_flags;
+    dup_flags |= (flags & setfl_flags);
+    if (fcntl(ret, F_SETFL, dup_flags) == -1) {
+        goto fail;
+    }
+
+    /* Truncate the file in the cases that open() would truncate it */
+    if (flags & O_TRUNC ||
+            ((flags & (O_CREAT | O_EXCL)) == (O_CREAT | O_EXCL))) {
+        if (ftruncate(ret, 0) == -1) {
+            goto fail;
+        }
+    }
+
+    return ret;
+
+fail:
+    serrno = errno;
+    if (ret != -1) {
+        close(ret);
+    }
+    errno = serrno;
+    return -1;
+}
+#endif
 
 /*
  * Opens a file with FD_CLOEXEC set
@@ -87,6 +148,41 @@ int qemu_open(const char *name, int flags, ...)
     int ret;
     int mode = 0;
 
+#ifndef _WIN32
+    const char *fdset_id_str;
+
+    /* Attempt dup of fd from fd set */
+    if (strstart(name, "/dev/fdset/", &fdset_id_str)) {
+        int64_t fdset_id;
+        int fd, dupfd;
+
+        fdset_id = qemu_parse_fdset(fdset_id_str);
+        if (fdset_id == -1) {
+            errno = EINVAL;
+            return -1;
+        }
+
+        fd = monitor_fdset_get_fd(fdset_id, flags);
+        if (fd == -1) {
+            return -1;
+        }
+
+        dupfd = qemu_dup_flags(fd, flags);
+        if (dupfd == -1) {
+            return -1;
+        }
+
+        ret = monitor_fdset_dup_fd_add(fdset_id, dupfd);
+        if (ret == -1) {
+            close(dupfd);
+            errno = EINVAL;
+            return -1;
+        }
+
+        return dupfd;
+    }
+#endif
+
     if (flags & O_CREAT) {
         va_list ap;
 
@@ -109,6 +205,21 @@ int qemu_open(const char *name, int flags, ...)
 
 int qemu_close(int fd)
 {
+    int64_t fdset_id;
+
+    /* Close fd that was dup'd from an fdset */
+    fdset_id = monitor_fdset_dup_fd_find(fd);
+    if (fdset_id != -1) {
+        int ret;
+
+        ret = close(fd);
+        if (ret == 0) {
+            monitor_fdset_dup_fd_remove(fd);
+        }
+
+        return ret;
+    }
+
     return close(fd);
 }
 
diff --git a/qemu-common.h b/qemu-common.h
index b388c5c..e5c2bcd 100644
--- a/qemu-common.h
+++ b/qemu-common.h
@@ -167,6 +167,7 @@ int qemu_fls(int i);
 int qemu_fdatasync(int fd);
 int fcntl_setfl(int fd, int flag);
 int qemu_parse_fd(const char *param);
+int qemu_parse_fdset(const char *param);
 
 /*
  * strtosz() suffixes used to specify the default treatment of an
diff --git a/qemu-tool.c b/qemu-tool.c
index 64b5e88..18205ba 100644
--- a/qemu-tool.c
+++ b/qemu-tool.c
@@ -62,6 +62,26 @@ void monitor_protocol_event(MonitorEvent event, QObject *data)
 {
 }
 
+int monitor_fdset_get_fd(int64_t fdset_id, int flags)
+{
+    return -1;
+}
+
+int monitor_fdset_dup_fd_add(int64_t fdset_id, int dup_fd)
+{
+    return -1;
+}
+
+int monitor_fdset_dup_fd_remove(int dup_fd)
+{
+    return -1;
+}
+
+int monitor_fdset_dup_fd_find(int dup_fd)
+{
+    return -1;
+}
+
 int64_t cpu_get_clock(void)
 {
     return qemu_get_clock_ns(rt_clock);
diff --git a/qemu-user.c b/qemu-user.c
index 08ccb0f..13fb9ae 100644
--- a/qemu-user.c
+++ b/qemu-user.c
@@ -35,3 +35,23 @@ void monitor_vprintf(Monitor *mon, const char *fmt, va_list ap)
 void monitor_set_error(Monitor *mon, QError *qerror)
 {
 }
+
+int monitor_fdset_get_fd(int64_t fdset_id, int flags)
+{
+    return -1;
+}
+
+int monitor_fdset_dup_fd_add(int64_t fdset_id, int dup_fd)
+{
+    return -1;
+}
+
+int monitor_fdset_dup_fd_remove(int dup_fd)
+{
+    return -1;
+}
+
+int monitor_fdset_dup_fd_find(int dup_fd)
+{
+    return -1;
+}
diff --git a/tests/Makefile b/tests/Makefile
index f3f4159..26a67ce 100644
--- a/tests/Makefile
+++ b/tests/Makefile
@@ -81,7 +81,7 @@ TARGETS=$(patsubst %-softmmu,%, $(filter %-softmmu,$(TARGET_DIRS)))
 QTEST_TARGETS=$(foreach TARGET,$(TARGETS), $(if $(check-qtest-$(TARGET)-y), $(TARGET),))
 check-qtest-$(CONFIG_POSIX)=$(foreach TARGET,$(TARGETS), $(check-qtest-$(TARGET)-y))
 
-qtest-obj-y = tests/libqtest.o $(oslib-obj-y)
+qtest-obj-y = tests/libqtest.o $(oslib-obj-y) $(tools-obj-y)
 $(check-qtest-y): $(qtest-obj-y)
 
 .PHONY: check-help
commit 2e1e79dae7a7e0a3d698fbd359d75e3a0239bdaa
Author: Corey Bryant <coreyb at linux.vnet.ibm.com>
Date:   Tue Aug 14 16:43:46 2012 -0400

    block: Convert close calls to qemu_close
    
    This patch converts all block layer close calls, that correspond
    to qemu_open calls, to qemu_close.
    
    Signed-off-by: Corey Bryant <coreyb at linux.vnet.ibm.com>
    Signed-off-by: Kevin Wolf <kwolf at redhat.com>

diff --git a/block/raw-posix.c b/block/raw-posix.c
index 08b997e..6be20b1 100644
--- a/block/raw-posix.c
+++ b/block/raw-posix.c
@@ -271,7 +271,7 @@ static int raw_open_common(BlockDriverState *bs, const char *filename,
 out_free_buf:
     qemu_vfree(s->aligned_buf);
 out_close:
-    close(fd);
+    qemu_close(fd);
     return -errno;
 }
 
@@ -376,7 +376,7 @@ static void raw_close(BlockDriverState *bs)
 {
     BDRVRawState *s = bs->opaque;
     if (s->fd >= 0) {
-        close(s->fd);
+        qemu_close(s->fd);
         s->fd = -1;
         if (s->aligned_buf != NULL)
             qemu_vfree(s->aligned_buf);
@@ -580,7 +580,7 @@ static int raw_create(const char *filename, QEMUOptionParameter *options)
         if (ftruncate(fd, total_size * BDRV_SECTOR_SIZE) != 0) {
             result = -errno;
         }
-        if (close(fd) != 0) {
+        if (qemu_close(fd) != 0) {
             result = -errno;
         }
     }
@@ -850,7 +850,7 @@ static int hdev_open(BlockDriverState *bs, const char *filename, int flags)
             if (fd < 0) {
                 bsdPath[strlen(bsdPath)-1] = '1';
             } else {
-                close(fd);
+                qemu_close(fd);
             }
             filename = bsdPath;
         }
@@ -889,7 +889,7 @@ static int fd_open(BlockDriverState *bs)
     last_media_present = (s->fd >= 0);
     if (s->fd >= 0 &&
         (get_clock() - s->fd_open_time) >= FD_OPEN_TIMEOUT) {
-        close(s->fd);
+        qemu_close(s->fd);
         s->fd = -1;
 #ifdef DEBUG_FLOPPY
         printf("Floppy closed\n");
@@ -988,7 +988,7 @@ static int hdev_create(const char *filename, QEMUOptionParameter *options)
     else if (lseek(fd, 0, SEEK_END) < total_size * BDRV_SECTOR_SIZE)
         ret = -ENOSPC;
 
-    close(fd);
+    qemu_close(fd);
     return ret;
 }
 
@@ -1038,7 +1038,7 @@ static int floppy_open(BlockDriverState *bs, const char *filename, int flags)
         return ret;
 
     /* close fd so that we can reopen it as needed */
-    close(s->fd);
+    qemu_close(s->fd);
     s->fd = -1;
     s->fd_media_changed = 1;
 
@@ -1072,7 +1072,7 @@ static int floppy_probe_device(const char *filename)
         prio = 100;
 
 outc:
-    close(fd);
+    qemu_close(fd);
 out:
     return prio;
 }
@@ -1107,14 +1107,14 @@ static void floppy_eject(BlockDriverState *bs, bool eject_flag)
     int fd;
 
     if (s->fd >= 0) {
-        close(s->fd);
+        qemu_close(s->fd);
         s->fd = -1;
     }
     fd = qemu_open(bs->filename, s->open_flags | O_NONBLOCK);
     if (fd >= 0) {
         if (ioctl(fd, FDEJECT, 0) < 0)
             perror("FDEJECT");
-        close(fd);
+        qemu_close(fd);
     }
 }
 
@@ -1175,7 +1175,7 @@ static int cdrom_probe_device(const char *filename)
         prio = 100;
 
 outc:
-    close(fd);
+    qemu_close(fd);
 out:
     return prio;
 }
@@ -1283,7 +1283,7 @@ static int cdrom_reopen(BlockDriverState *bs)
      * FreeBSD seems to not notice sometimes...
      */
     if (s->fd >= 0)
-        close(s->fd);
+        qemu_close(s->fd);
     fd = qemu_open(bs->filename, s->open_flags, 0644);
     if (fd < 0) {
         s->fd = -1;
diff --git a/block/raw-win32.c b/block/raw-win32.c
index 8d7838d..c56bf83 100644
--- a/block/raw-win32.c
+++ b/block/raw-win32.c
@@ -261,7 +261,7 @@ static int raw_create(const char *filename, QEMUOptionParameter *options)
         return -EIO;
     set_sparse(fd);
     ftruncate(fd, total_size * 512);
-    close(fd);
+    qemu_close(fd);
     return 0;
 }
 
diff --git a/block/vmdk.c b/block/vmdk.c
index 557dc1b..daee426 100644
--- a/block/vmdk.c
+++ b/block/vmdk.c
@@ -1258,7 +1258,7 @@ static int vmdk_create_extent(const char *filename, int64_t filesize,
 
     ret = 0;
  exit:
-    close(fd);
+    qemu_close(fd);
     return ret;
 }
 
@@ -1506,7 +1506,7 @@ static int vmdk_create(const char *filename, QEMUOptionParameter *options)
     }
     ret = 0;
 exit:
-    close(fd);
+    qemu_close(fd);
     return ret;
 }
 
diff --git a/block/vpc.c b/block/vpc.c
index 60ebf5a..c0b82c4 100644
--- a/block/vpc.c
+++ b/block/vpc.c
@@ -744,7 +744,7 @@ static int vpc_create(const char *filename, QEMUOptionParameter *options)
     }
 
  fail:
-    close(fd);
+    qemu_close(fd);
     return ret;
 }
 
diff --git a/block/vvfat.c b/block/vvfat.c
index 22b586a..59d3c5b 100644
--- a/block/vvfat.c
+++ b/block/vvfat.c
@@ -1105,7 +1105,7 @@ static inline void vvfat_close_current_file(BDRVVVFATState *s)
     if(s->current_mapping) {
 	s->current_mapping = NULL;
 	if (s->current_fd) {
-		close(s->current_fd);
+		qemu_close(s->current_fd);
 		s->current_fd = 0;
 	}
     }
@@ -2230,7 +2230,7 @@ static int commit_one_file(BDRVVVFATState* s,
     }
     if (offset > 0) {
         if (lseek(fd, offset, SEEK_SET) != offset) {
-            close(fd);
+            qemu_close(fd);
             g_free(cluster);
             return -3;
         }
@@ -2251,13 +2251,13 @@ static int commit_one_file(BDRVVVFATState* s,
 	    (uint8_t*)cluster, (rest_size + 0x1ff) / 0x200);
 
         if (ret < 0) {
-            close(fd);
+            qemu_close(fd);
             g_free(cluster);
             return ret;
         }
 
         if (write(fd, cluster, rest_size) < 0) {
-            close(fd);
+            qemu_close(fd);
             g_free(cluster);
             return -2;
         }
@@ -2268,11 +2268,11 @@ static int commit_one_file(BDRVVVFATState* s,
 
     if (ftruncate(fd, size)) {
         perror("ftruncate()");
-        close(fd);
+        qemu_close(fd);
         g_free(cluster);
         return -4;
     }
-    close(fd);
+    qemu_close(fd);
     g_free(cluster);
 
     return commit_mappings(s, first_cluster, dir_index);
diff --git a/osdep.c b/osdep.c
index c07faf5..7f876ae 100644
--- a/osdep.c
+++ b/osdep.c
@@ -107,6 +107,11 @@ int qemu_open(const char *name, int flags, ...)
     return ret;
 }
 
+int qemu_close(int fd)
+{
+    return close(fd);
+}
+
 /*
  * A variant of write(2) which handles partial write.
  *
diff --git a/qemu-common.h b/qemu-common.h
index 095e28d..b388c5c 100644
--- a/qemu-common.h
+++ b/qemu-common.h
@@ -208,6 +208,7 @@ const char *path(const char *pathname);
 void *qemu_oom_check(void *ptr);
 
 int qemu_open(const char *name, int flags, ...);
+int qemu_close(int fd);
 ssize_t qemu_write_full(int fd, const void *buf, size_t count)
     QEMU_WARN_UNUSED_RESULT;
 ssize_t qemu_send_full(int fd, const void *buf, size_t count, int flags)
diff --git a/savevm.c b/savevm.c
index 0ea10c9..f002bfc 100644
--- a/savevm.c
+++ b/savevm.c
@@ -513,7 +513,7 @@ static void qemu_fill_buffer(QEMUFile *f)
  *
  * Returns f->close() return value, or 0 if close function is not set.
  */
-static int qemu_close(QEMUFile *f)
+static int qemu_fclose_internal(QEMUFile *f)
 {
     int ret = 0;
     if (f->close) {
@@ -535,7 +535,7 @@ int qemu_fclose(QEMUFile *f)
 {
     int ret;
     qemu_fflush(f);
-    ret = qemu_close(f);
+    ret = qemu_fclose_internal(f);
     /* If any error was spotted before closing, we should report it
      * instead of the close() return value.
      */
commit 6165f4d85d92e15b6aebdeeb2559dc687b0353c7
Author: Corey Bryant <coreyb at linux.vnet.ibm.com>
Date:   Tue Aug 14 16:43:45 2012 -0400

    block: Convert open calls to qemu_open
    
    This patch converts all block layer open calls to qemu_open.
    
    Note that this adds the O_CLOEXEC flag to the changed open paths
    when the O_CLOEXEC macro is defined.
    
    Signed-off-by: Corey Bryant <coreyb at linux.vnet.ibm.com>
    Signed-off-by: Kevin Wolf <kwolf at redhat.com>

diff --git a/block/raw-posix.c b/block/raw-posix.c
index f606211..08b997e 100644
--- a/block/raw-posix.c
+++ b/block/raw-posix.c
@@ -572,8 +572,8 @@ static int raw_create(const char *filename, QEMUOptionParameter *options)
         options++;
     }
 
-    fd = open(filename, O_WRONLY | O_CREAT | O_TRUNC | O_BINARY,
-              0644);
+    fd = qemu_open(filename, O_WRONLY | O_CREAT | O_TRUNC | O_BINARY,
+                   0644);
     if (fd < 0) {
         result = -errno;
     } else {
@@ -846,7 +846,7 @@ static int hdev_open(BlockDriverState *bs, const char *filename, int flags)
         if ( bsdPath[ 0 ] != '\0' ) {
             strcat(bsdPath,"s0");
             /* some CDs don't have a partition 0 */
-            fd = open(bsdPath, O_RDONLY | O_BINARY | O_LARGEFILE);
+            fd = qemu_open(bsdPath, O_RDONLY | O_BINARY | O_LARGEFILE);
             if (fd < 0) {
                 bsdPath[strlen(bsdPath)-1] = '1';
             } else {
@@ -903,7 +903,7 @@ static int fd_open(BlockDriverState *bs)
 #endif
             return -EIO;
         }
-        s->fd = open(bs->filename, s->open_flags & ~O_NONBLOCK);
+        s->fd = qemu_open(bs->filename, s->open_flags & ~O_NONBLOCK);
         if (s->fd < 0) {
             s->fd_error_time = get_clock();
             s->fd_got_error = 1;
@@ -977,7 +977,7 @@ static int hdev_create(const char *filename, QEMUOptionParameter *options)
         options++;
     }
 
-    fd = open(filename, O_WRONLY | O_BINARY);
+    fd = qemu_open(filename, O_WRONLY | O_BINARY);
     if (fd < 0)
         return -errno;
 
@@ -1057,7 +1057,7 @@ static int floppy_probe_device(const char *filename)
         prio = 50;
     }
 
-    fd = open(filename, O_RDONLY | O_NONBLOCK);
+    fd = qemu_open(filename, O_RDONLY | O_NONBLOCK);
     if (fd < 0) {
         goto out;
     }
@@ -1110,7 +1110,7 @@ static void floppy_eject(BlockDriverState *bs, bool eject_flag)
         close(s->fd);
         s->fd = -1;
     }
-    fd = open(bs->filename, s->open_flags | O_NONBLOCK);
+    fd = qemu_open(bs->filename, s->open_flags | O_NONBLOCK);
     if (fd >= 0) {
         if (ioctl(fd, FDEJECT, 0) < 0)
             perror("FDEJECT");
@@ -1160,7 +1160,7 @@ static int cdrom_probe_device(const char *filename)
     int prio = 0;
     struct stat st;
 
-    fd = open(filename, O_RDONLY | O_NONBLOCK);
+    fd = qemu_open(filename, O_RDONLY | O_NONBLOCK);
     if (fd < 0) {
         goto out;
     }
@@ -1284,7 +1284,7 @@ static int cdrom_reopen(BlockDriverState *bs)
      */
     if (s->fd >= 0)
         close(s->fd);
-    fd = open(bs->filename, s->open_flags, 0644);
+    fd = qemu_open(bs->filename, s->open_flags, 0644);
     if (fd < 0) {
         s->fd = -1;
         return -EIO;
diff --git a/block/raw-win32.c b/block/raw-win32.c
index e4b0b75..8d7838d 100644
--- a/block/raw-win32.c
+++ b/block/raw-win32.c
@@ -255,8 +255,8 @@ static int raw_create(const char *filename, QEMUOptionParameter *options)
         options++;
     }
 
-    fd = open(filename, O_WRONLY | O_CREAT | O_TRUNC | O_BINARY,
-              0644);
+    fd = qemu_open(filename, O_WRONLY | O_CREAT | O_TRUNC | O_BINARY,
+                   0644);
     if (fd < 0)
         return -EIO;
     set_sparse(fd);
diff --git a/block/vdi.c b/block/vdi.c
index 57325d6..c4f1529 100644
--- a/block/vdi.c
+++ b/block/vdi.c
@@ -653,8 +653,9 @@ static int vdi_create(const char *filename, QEMUOptionParameter *options)
         options++;
     }
 
-    fd = open(filename, O_WRONLY | O_CREAT | O_TRUNC | O_BINARY | O_LARGEFILE,
-              0644);
+    fd = qemu_open(filename,
+                   O_WRONLY | O_CREAT | O_TRUNC | O_BINARY | O_LARGEFILE,
+                   0644);
     if (fd < 0) {
         return -errno;
     }
diff --git a/block/vmdk.c b/block/vmdk.c
index 18e9b4c..557dc1b 100644
--- a/block/vmdk.c
+++ b/block/vmdk.c
@@ -1161,10 +1161,9 @@ static int vmdk_create_extent(const char *filename, int64_t filesize,
     VMDK4Header header;
     uint32_t tmp, magic, grains, gd_size, gt_size, gt_count;
 
-    fd = open(
-        filename,
-        O_WRONLY | O_CREAT | O_TRUNC | O_BINARY | O_LARGEFILE,
-        0644);
+    fd = qemu_open(filename,
+                   O_WRONLY | O_CREAT | O_TRUNC | O_BINARY | O_LARGEFILE,
+                   0644);
     if (fd < 0) {
         return -errno;
     }
@@ -1484,15 +1483,13 @@ static int vmdk_create(const char *filename, QEMUOptionParameter *options)
             (flags & BLOCK_FLAG_COMPAT6 ? 6 : 4),
             total_size / (int64_t)(63 * 16 * 512));
     if (split || flat) {
-        fd = open(
-                filename,
-                O_WRONLY | O_CREAT | O_TRUNC | O_BINARY | O_LARGEFILE,
-                0644);
+        fd = qemu_open(filename,
+                       O_WRONLY | O_CREAT | O_TRUNC | O_BINARY | O_LARGEFILE,
+                       0644);
     } else {
-        fd = open(
-                filename,
-                O_WRONLY | O_BINARY | O_LARGEFILE,
-                0644);
+        fd = qemu_open(filename,
+                       O_WRONLY | O_BINARY | O_LARGEFILE,
+                       0644);
     }
     if (fd < 0) {
         return -errno;
diff --git a/block/vpc.c b/block/vpc.c
index 5cd13d1..60ebf5a 100644
--- a/block/vpc.c
+++ b/block/vpc.c
@@ -678,7 +678,7 @@ static int vpc_create(const char *filename, QEMUOptionParameter *options)
     }
 
     /* Create the file */
-    fd = open(filename, O_WRONLY | O_CREAT | O_TRUNC | O_BINARY, 0644);
+    fd = qemu_open(filename, O_WRONLY | O_CREAT | O_TRUNC | O_BINARY, 0644);
     if (fd < 0) {
         return -EIO;
     }
diff --git a/block/vvfat.c b/block/vvfat.c
index 7b1dcee..22b586a 100644
--- a/block/vvfat.c
+++ b/block/vvfat.c
@@ -1162,7 +1162,7 @@ static int open_file(BDRVVVFATState* s,mapping_t* mapping)
     if(!s->current_mapping ||
 	    strcmp(s->current_mapping->path,mapping->path)) {
 	/* open file */
-	int fd = open(mapping->path, O_RDONLY | O_BINARY | O_LARGEFILE);
+	int fd = qemu_open(mapping->path, O_RDONLY | O_BINARY | O_LARGEFILE);
 	if(fd<0)
 	    return -1;
 	vvfat_close_current_file(s);
@@ -2221,7 +2221,7 @@ static int commit_one_file(BDRVVVFATState* s,
     for (i = s->cluster_size; i < offset; i += s->cluster_size)
 	c = modified_fat_get(s, c);
 
-    fd = open(mapping->path, O_RDWR | O_CREAT | O_BINARY, 0666);
+    fd = qemu_open(mapping->path, O_RDWR | O_CREAT | O_BINARY, 0666);
     if (fd < 0) {
 	fprintf(stderr, "Could not open %s... (%s, %d)\n", mapping->path,
 		strerror(errno), errno);
commit e17408283562be359f16a7e12ddfee7509d6fe11
Author: Corey Bryant <coreyb at linux.vnet.ibm.com>
Date:   Tue Aug 14 16:43:44 2012 -0400

    block: Prevent detection of /dev/fdset/ as floppy
    
    Signed-off-by: Corey Bryant <coreyb at linux.vnet.ibm.com>
    Signed-off-by: Kevin Wolf <kwolf at redhat.com>

diff --git a/block/raw-posix.c b/block/raw-posix.c
index 0dce089..f606211 100644
--- a/block/raw-posix.c
+++ b/block/raw-posix.c
@@ -1052,8 +1052,10 @@ static int floppy_probe_device(const char *filename)
     struct floppy_struct fdparam;
     struct stat st;
 
-    if (strstart(filename, "/dev/fd", NULL))
+    if (strstart(filename, "/dev/fd", NULL) &&
+        !strstart(filename, "/dev/fdset/", NULL)) {
         prio = 50;
+    }
 
     fd = open(filename, O_RDONLY | O_NONBLOCK);
     if (fd < 0) {
commit ba1c048a8f9c4a62812a8735ebd4fde0cfd086e8
Author: Corey Bryant <coreyb at linux.vnet.ibm.com>
Date:   Tue Aug 14 16:43:43 2012 -0400

    qapi: Introduce add-fd, remove-fd, query-fdsets
    
    This patch adds support that enables passing of file descriptors
    to the QEMU monitor where they will be stored in specified file
    descriptor sets.
    
    A file descriptor set can be used by a client like libvirt to
    store file descriptors for the same file.  This allows the
    client to open a file with different access modes (O_RDWR,
    O_WRONLY, O_RDONLY) and add/remove the passed fds to/from an fd
    set as needed.  This will allow QEMU to (in a later patch in this
    series) "open" and "reopen" the same file by dup()ing the fd in
    the fd set that corresponds to the file, where the fd has the
    matching access mode flag that QEMU requests.
    
    The new QMP commands are:
      add-fd: Add a file descriptor to an fd set
      remove-fd: Remove a file descriptor from an fd set
      query-fdsets: Return information describing all fd sets
    
    Note: These commands are not compatible with the existing getfd
    and closefd QMP commands.
    
    Signed-off-by: Corey Bryant <coreyb at linux.vnet.ibm.com>
    Signed-off-by: Kevin Wolf <kwolf at redhat.com>

diff --git a/monitor.c b/monitor.c
index dd63f1d..8d813d5 100644
--- a/monitor.c
+++ b/monitor.c
@@ -140,6 +140,23 @@ struct mon_fd_t {
     QLIST_ENTRY(mon_fd_t) next;
 };
 
+/* file descriptor associated with a file descriptor set */
+typedef struct MonFdsetFd MonFdsetFd;
+struct MonFdsetFd {
+    int fd;
+    bool removed;
+    char *opaque;
+    QLIST_ENTRY(MonFdsetFd) next;
+};
+
+/* file descriptor set containing fds passed via SCM_RIGHTS */
+typedef struct MonFdset MonFdset;
+struct MonFdset {
+    int64_t id;
+    QLIST_HEAD(, MonFdsetFd) fds;
+    QLIST_ENTRY(MonFdset) next;
+};
+
 typedef struct MonitorControl {
     QObject *id;
     JSONMessageParser parser;
@@ -181,6 +198,7 @@ struct Monitor {
 #define QMP_ACCEPT_UNKNOWNS 1
 
 static QLIST_HEAD(mon_list, Monitor) mon_list;
+static QLIST_HEAD(mon_fdsets, MonFdset) mon_fdsets;
 
 static mon_cmd_t mon_cmds[];
 static mon_cmd_t info_cmds[];
@@ -2366,6 +2384,177 @@ int monitor_get_fd(Monitor *mon, const char *fdname)
     return -1;
 }
 
+static void monitor_fdset_cleanup(MonFdset *mon_fdset)
+{
+    MonFdsetFd *mon_fdset_fd;
+    MonFdsetFd *mon_fdset_fd_next;
+
+    QLIST_FOREACH_SAFE(mon_fdset_fd, &mon_fdset->fds, next, mon_fdset_fd_next) {
+        if (mon_fdset_fd->removed) {
+            close(mon_fdset_fd->fd);
+            g_free(mon_fdset_fd->opaque);
+            QLIST_REMOVE(mon_fdset_fd, next);
+            g_free(mon_fdset_fd);
+        }
+    }
+
+    if (QLIST_EMPTY(&mon_fdset->fds)) {
+        QLIST_REMOVE(mon_fdset, next);
+        g_free(mon_fdset);
+    }
+}
+
+AddfdInfo *qmp_add_fd(bool has_fdset_id, int64_t fdset_id, bool has_opaque,
+                      const char *opaque, Error **errp)
+{
+    int fd;
+    Monitor *mon = cur_mon;
+    MonFdset *mon_fdset;
+    MonFdsetFd *mon_fdset_fd;
+    AddfdInfo *fdinfo;
+
+    fd = qemu_chr_fe_get_msgfd(mon->chr);
+    if (fd == -1) {
+        error_set(errp, QERR_FD_NOT_SUPPLIED);
+        goto error;
+    }
+
+    if (has_fdset_id) {
+        QLIST_FOREACH(mon_fdset, &mon_fdsets, next) {
+            if (mon_fdset->id == fdset_id) {
+                break;
+            }
+        }
+        if (mon_fdset == NULL) {
+            error_set(errp, QERR_INVALID_PARAMETER_VALUE, "fdset-id",
+                      "an existing fdset-id");
+            goto error;
+        }
+    } else {
+        int64_t fdset_id_prev = -1;
+        MonFdset *mon_fdset_cur = QLIST_FIRST(&mon_fdsets);
+
+        /* Use first available fdset ID */
+        QLIST_FOREACH(mon_fdset, &mon_fdsets, next) {
+            mon_fdset_cur = mon_fdset;
+            if (fdset_id_prev == mon_fdset_cur->id - 1) {
+                fdset_id_prev = mon_fdset_cur->id;
+                continue;
+            }
+            break;
+        }
+
+        mon_fdset = g_malloc0(sizeof(*mon_fdset));
+        mon_fdset->id = fdset_id_prev + 1;
+
+        /* The fdset list is ordered by fdset ID */
+        if (mon_fdset->id == 0) {
+            QLIST_INSERT_HEAD(&mon_fdsets, mon_fdset, next);
+        } else if (mon_fdset->id < mon_fdset_cur->id) {
+            QLIST_INSERT_BEFORE(mon_fdset_cur, mon_fdset, next);
+        } else {
+            QLIST_INSERT_AFTER(mon_fdset_cur, mon_fdset, next);
+        }
+    }
+
+    mon_fdset_fd = g_malloc0(sizeof(*mon_fdset_fd));
+    mon_fdset_fd->fd = fd;
+    mon_fdset_fd->removed = false;
+    if (has_opaque) {
+        mon_fdset_fd->opaque = g_strdup(opaque);
+    }
+    QLIST_INSERT_HEAD(&mon_fdset->fds, mon_fdset_fd, next);
+
+    fdinfo = g_malloc0(sizeof(*fdinfo));
+    fdinfo->fdset_id = mon_fdset->id;
+    fdinfo->fd = mon_fdset_fd->fd;
+
+    return fdinfo;
+
+error:
+    if (fd != -1) {
+        close(fd);
+    }
+    return NULL;
+}
+
+void qmp_remove_fd(int64_t fdset_id, bool has_fd, int64_t fd, Error **errp)
+{
+    MonFdset *mon_fdset;
+    MonFdsetFd *mon_fdset_fd;
+    char fd_str[60];
+
+    QLIST_FOREACH(mon_fdset, &mon_fdsets, next) {
+        if (mon_fdset->id != fdset_id) {
+            continue;
+        }
+        QLIST_FOREACH(mon_fdset_fd, &mon_fdset->fds, next) {
+            if (has_fd) {
+                if (mon_fdset_fd->fd != fd) {
+                    continue;
+                }
+                mon_fdset_fd->removed = true;
+                break;
+            } else {
+                mon_fdset_fd->removed = true;
+            }
+        }
+        if (has_fd && !mon_fdset_fd) {
+            goto error;
+        }
+        monitor_fdset_cleanup(mon_fdset);
+        return;
+    }
+
+error:
+    if (has_fd) {
+        snprintf(fd_str, sizeof(fd_str), "fdset-id:%" PRId64 ", fd:%" PRId64,
+                 fdset_id, fd);
+    } else {
+        snprintf(fd_str, sizeof(fd_str), "fdset-id:%" PRId64, fdset_id);
+    }
+    error_set(errp, QERR_FD_NOT_FOUND, fd_str);
+}
+
+FdsetInfoList *qmp_query_fdsets(Error **errp)
+{
+    MonFdset *mon_fdset;
+    MonFdsetFd *mon_fdset_fd;
+    FdsetInfoList *fdset_list = NULL;
+
+    QLIST_FOREACH(mon_fdset, &mon_fdsets, next) {
+        FdsetInfoList *fdset_info = g_malloc0(sizeof(*fdset_info));
+        FdsetFdInfoList *fdsetfd_list = NULL;
+
+        fdset_info->value = g_malloc0(sizeof(*fdset_info->value));
+        fdset_info->value->fdset_id = mon_fdset->id;
+
+        QLIST_FOREACH(mon_fdset_fd, &mon_fdset->fds, next) {
+            FdsetFdInfoList *fdsetfd_info;
+
+            fdsetfd_info = g_malloc0(sizeof(*fdsetfd_info));
+            fdsetfd_info->value = g_malloc0(sizeof(*fdsetfd_info->value));
+            fdsetfd_info->value->fd = mon_fdset_fd->fd;
+            if (mon_fdset_fd->opaque) {
+                fdsetfd_info->value->has_opaque = true;
+                fdsetfd_info->value->opaque = g_strdup(mon_fdset_fd->opaque);
+            } else {
+                fdsetfd_info->value->has_opaque = false;
+            }
+
+            fdsetfd_info->next = fdsetfd_list;
+            fdsetfd_list = fdsetfd_info;
+        }
+
+        fdset_info->value->fds = fdsetfd_list;
+
+        fdset_info->next = fdset_list;
+        fdset_list = fdset_info;
+    }
+
+    return fdset_list;
+}
+
 /* mon_cmds and info_cmds would be sorted at runtime */
 static mon_cmd_t mon_cmds[] = {
 #include "hmp-commands.h"
diff --git a/qapi-schema.json b/qapi-schema.json
index 53bbe46..3d2b2d1 100644
--- a/qapi-schema.json
+++ b/qapi-schema.json
@@ -2356,3 +2356,101 @@
 # Since: 1.2.0
 ##
 { 'command': 'query-cpu-definitions', 'returns': ['CpuDefinitionInfo'] }
+
+# @AddfdInfo:
+#
+# Information about a file descriptor that was added to an fd set.
+#
+# @fdset-id: The ID of the fd set that @fd was added to.
+#
+# @fd: The file descriptor that was received via SCM rights and
+#      added to the fd set.
+#
+# Since: 1.2.0
+##
+{ 'type': 'AddfdInfo', 'data': {'fdset-id': 'int', 'fd': 'int'} }
+
+##
+# @add-fd:
+#
+# Add a file descriptor, that was passed via SCM rights, to an fd set.
+#
+# @fdset-id: #optional The ID of the fd set to add the file descriptor to.
+#
+# @opaque: #optional A free-form string that can be used to describe the fd.
+#
+# Returns: @AddfdInfo on success
+#          If file descriptor was not received, FdNotSupplied
+#          If @fdset-id does not exist, InvalidParameterValue
+#
+# Notes: The list of fd sets is shared by all monitor connections.
+#
+#        If @fdset-id is not specified, a new fd set will be created.
+#
+# Since: 1.2.0
+##
+{ 'command': 'add-fd', 'data': {'*fdset-id': 'int', '*opaque': 'str'},
+  'returns': 'AddfdInfo' }
+
+##
+# @remove-fd:
+#
+# Remove a file descriptor from an fd set.
+#
+# @fdset-id: The ID of the fd set that the file descriptor belongs to.
+#
+# @fd: #optional The file descriptor that is to be removed.
+#
+# Returns: Nothing on success
+#          If @fdset-id or @fd is not found, FdNotFound
+#
+# Since: 1.2.0
+#
+# Notes: The list of fd sets is shared by all monitor connections.
+#
+#        If @fd is not specified, all file descriptors in @fdset-id
+#        will be removed.
+##
+{ 'command': 'remove-fd', 'data': {'fdset-id': 'int', '*fd': 'int'} }
+
+##
+# @FdsetFdInfo:
+#
+# Information about a file descriptor that belongs to an fd set.
+#
+# @fd: The file descriptor value.
+#
+# @opaque: #optional A free-form string that can be used to describe the fd.
+#
+# Since: 1.2.0
+##
+{ 'type': 'FdsetFdInfo',
+  'data': {'fd': 'int', '*opaque': 'str'} }
+
+##
+# @FdsetInfo:
+#
+# Information about an fd set.
+#
+# @fdset-id: The ID of the fd set.
+#
+# @fds: A list of file descriptors that belong to this fd set.
+#
+# Since: 1.2.0
+##
+{ 'type': 'FdsetInfo',
+  'data': {'fdset-id': 'int', 'fds': ['FdsetFdInfo']} }
+
+##
+# @query-fdsets:
+#
+# Return information describing all fd sets.
+#
+# Returns: A list of @FdsetInfo
+#
+# Since: 1.2.0
+#
+# Note: The list of fd sets is shared by all monitor connections.
+#
+##
+{ 'command': 'query-fdsets', 'returns': ['FdsetInfo'] }
diff --git a/qmp-commands.hx b/qmp-commands.hx
index 527b9f7..2ce4ce6 100644
--- a/qmp-commands.hx
+++ b/qmp-commands.hx
@@ -970,6 +970,128 @@ Example:
 
 EQMP
 
+     {
+        .name       = "add-fd",
+        .args_type  = "fdset-id:i?,opaque:s?",
+        .params     = "add-fd fdset-id opaque",
+        .help       = "Add a file descriptor, that was passed via SCM rights, to an fd set",
+        .mhandler.cmd_new = qmp_marshal_input_add_fd,
+    },
+
+SQMP
+add-fd
+-------
+
+Add a file descriptor, that was passed via SCM rights, to an fd set.
+
+Arguments:
+
+- "fdset-id": The ID of the fd set to add the file descriptor to.
+              (json-int, optional)
+- "opaque": A free-form string that can be used to describe the fd.
+            (json-string, optional)
+
+Return a json-object with the following information:
+
+- "fdset-id": The ID of the fd set that the fd was added to. (json-int)
+- "fd": The file descriptor that was received via SCM rights and added to the
+        fd set. (json-int)
+
+Example:
+
+-> { "execute": "add-fd", "arguments": { "fdset-id": 1 } }
+<- { "return": { "fdset-id": 1, "fd": 3 } }
+
+Notes:
+
+(1) The list of fd sets is shared by all monitor connections.
+(2) If "fdset-id" is not specified, a new fd set will be created.
+
+EQMP
+
+     {
+        .name       = "remove-fd",
+        .args_type  = "fdset-id:i,fd:i?",
+        .params     = "remove-fd fdset-id fd",
+        .help       = "Remove a file descriptor from an fd set",
+        .mhandler.cmd_new = qmp_marshal_input_remove_fd,
+    },
+
+SQMP
+remove-fd
+---------
+
+Remove a file descriptor from an fd set.
+
+Arguments:
+
+- "fdset-id": The ID of the fd set that the file descriptor belongs to.
+              (json-int)
+- "fd": The file descriptor that is to be removed. (json-int, optional)
+
+Example:
+
+-> { "execute": "remove-fd", "arguments": { "fdset-id": 1, "fd": 3 } }
+<- { "return": {} }
+
+Notes:
+
+(1) The list of fd sets is shared by all monitor connections.
+(2) If "fd" is not specified, all file descriptors in "fdset-id" will be
+    removed.
+
+EQMP
+
+    {
+        .name       = "query-fdsets",
+        .args_type  = "",
+        .help       = "Return information describing all fd sets",
+        .mhandler.cmd_new = qmp_marshal_input_query_fdsets,
+    },
+
+SQMP
+query-fdsets
+-------------
+
+Return information describing all fd sets.
+
+Arguments: None
+
+Example:
+
+-> { "execute": "query-fdsets" }
+<- { "return": [
+       {
+         "fds": [
+           {
+             "fd": 30,
+             "opaque": "rdonly:/path/to/file"
+           },
+           {
+             "fd": 24,
+             "opaque": "rdwr:/path/to/file"
+           }
+         ],
+         "fdset-id": 1
+       },
+       {
+         "fds": [
+           {
+             "fd": 28
+           },
+           {
+             "fd": 29
+           }
+         ],
+         "fdset-id": 0
+       }
+     ]
+   }
+
+Note: The list of fd sets is shared by all monitor connections.
+
+EQMP
+
     {
         .name       = "block_passwd",
         .args_type  = "device:B,password:s",
commit 06138651f3347a4ad7527d48b1ccbeae89f9e7f6
Author: Corey Bryant <coreyb at linux.vnet.ibm.com>
Date:   Tue Aug 14 16:43:42 2012 -0400

    qemu-char: Add MSG_CMSG_CLOEXEC flag to recvmsg
    
    Set the close-on-exec flag for the file descriptor received
    via SCM_RIGHTS.
    
    Signed-off-by: Corey Bryant <coreyb at linux.vnet.ibm.com>
    Signed-off-by: Kevin Wolf <kwolf at redhat.com>

diff --git a/qemu-char.c b/qemu-char.c
index 382c71e..10d1504 100644
--- a/qemu-char.c
+++ b/qemu-char.c
@@ -2238,6 +2238,9 @@ static void unix_process_msgfd(CharDriverState *chr, struct msghdr *msg)
         if (fd < 0)
             continue;
 
+#ifndef MSG_CMSG_CLOEXEC
+        qemu_set_cloexec(fd);
+#endif
         if (s->msgfd != -1)
             close(s->msgfd);
         s->msgfd = fd;
@@ -2253,6 +2256,7 @@ static ssize_t tcp_chr_recv(CharDriverState *chr, char *buf, size_t len)
         struct cmsghdr cmsg;
         char control[CMSG_SPACE(sizeof(int))];
     } msg_control;
+    int flags = 0;
     ssize_t ret;
 
     iov[0].iov_base = buf;
@@ -2263,9 +2267,13 @@ static ssize_t tcp_chr_recv(CharDriverState *chr, char *buf, size_t len)
     msg.msg_control = &msg_control;
     msg.msg_controllen = sizeof(msg_control);
 
-    ret = recvmsg(s->fd, &msg, 0);
-    if (ret > 0 && s->is_unix)
+#ifdef MSG_CMSG_CLOEXEC
+    flags |= MSG_CMSG_CLOEXEC;
+#endif
+    ret = recvmsg(s->fd, &msg, flags);
+    if (ret > 0 && s->is_unix) {
         unix_process_msgfd(chr, &msg);
+    }
 
     return ret;
 }
commit 256d046ca70788e4cb3aad56cda64ad81f19b7cd
Author: Peter Maydell <peter.maydell at linaro.org>
Date:   Wed Jul 25 16:29:07 2012 +0100

    update-linux-headers.sh: Pull in asm-generic/kvm_para.h
    
    Add asm-generic/kvm_para.h to the set of non-architecture specific
    KVM kernel headers we copy into QEMU. This header may be included
    by an architecture's kvm_para.h header.
    
    Reviewed-by: Jan Kiszka <jan.kiszka at siemens.com>
    Signed-off-by: Peter Maydell <peter.maydell at linaro.org>
    Signed-off-by: Marcelo Tosatti <mtosatti at redhat.com>

diff --git a/scripts/update-linux-headers.sh b/scripts/update-linux-headers.sh
index 9d2a4bc..a639c5b 100755
--- a/scripts/update-linux-headers.sh
+++ b/scripts/update-linux-headers.sh
@@ -46,6 +46,11 @@ mkdir -p "$output/linux-headers/linux"
 for header in kvm.h kvm_para.h vhost.h virtio_config.h virtio_ring.h; do
     cp "$tmpdir/include/linux/$header" "$output/linux-headers/linux"
 done
+rm -rf "$output/linux-headers/asm-generic"
+mkdir -p "$output/linux-headers/asm-generic"
+for header in kvm_para.h; do
+    cp "$tmpdir/include/asm-generic/$header" "$output/linux-headers/asm-generic"
+done
 if [ -L "$linux/source" ]; then
     cp "$linux/source/COPYING" "$output/linux-headers"
 else
commit a9605e0317c7a6d5e68f3a3b6708c8ef1096f4bc
Author: Jan Kiszka <jan.kiszka at siemens.com>
Date:   Tue Aug 14 13:43:12 2012 +0200

    kvmvapic: Disable if there is insufficient memory
    
    We need at least 1M of RAM to map the option ROM. Otherwise, we will
    corrupt host memory or even crash:
    
        $ qemu-system-x86_64 -nodefaults --enable-kvm -vnc :0 -m 640k
        Segmentation fault (core dumped)
    
    Reported-and-tested-by: Markus Armbruster <armbru at redhat.com>
    Signed-off-by: Jan Kiszka <jan.kiszka at siemens.com>
    Signed-off-by: Marcelo Tosatti <mtosatti at redhat.com>

diff --git a/hw/apic_common.c b/hw/apic_common.c
index 58e63b0..371f95d 100644
--- a/hw/apic_common.c
+++ b/hw/apic_common.c
@@ -299,7 +299,9 @@ static int apic_init_common(SysBusDevice *dev)
 
     sysbus_init_mmio(dev, &s->io_memory);
 
-    if (!vapic && s->vapic_control & VAPIC_ENABLE_MASK) {
+    /* Note: We need at least 1M to map the VAPIC option ROM */
+    if (!vapic && s->vapic_control & VAPIC_ENABLE_MASK &&
+        ram_size >= 1024 * 1024) {
         vapic = sysbus_create_simple("kvmvapic", -1, NULL);
     }
     s->vapic = vapic;
commit 050a46065de8e3d4ee5a04f5598d666f63d34800
Author: Jan Kiszka <jan.kiszka at siemens.com>
Date:   Tue Aug 14 10:24:47 2012 +0200

    kvm: i8254: Finish time conversion fix
    
    0cdd3d1444 fixed reading back the counter load time from the kernel
    while assuming the kernel would always update its load time on writing
    the state. That is only true for channel 1, and so pit_get_channel_info
    returned wrong output pin states for high counter values.
    
    Fix this by applying the offset also on kvm_pit_put. Now we also need to
    update the offset when we write the state while the VM is stopped as it
    keeps on changing in that state.
    
    Signed-off-by: Jan Kiszka <jan.kiszka at siemens.com>
    Signed-off-by: Marcelo Tosatti <mtosatti at redhat.com>

diff --git a/hw/kvm/i8254.c b/hw/kvm/i8254.c
index c235d80..53d13e3 100644
--- a/hw/kvm/i8254.c
+++ b/hw/kvm/i8254.c
@@ -122,17 +122,23 @@ static void kvm_pit_get(PITCommonState *pit)
         pit_get_next_transition_time(sc, sc->count_load_time);
 }
 
-static void kvm_pit_put(PITCommonState *s)
+static void kvm_pit_put(PITCommonState *pit)
 {
+    KVMPITState *s = DO_UPCAST(KVMPITState, pit, pit);
     struct kvm_pit_state2 kpit;
     struct kvm_pit_channel_state *kchan;
     struct PITChannelState *sc;
     int i, ret;
 
-    kpit.flags = s->channels[0].irq_disabled ? KVM_PIT_FLAGS_HPET_LEGACY : 0;
+    /* The offset keeps changing as long as the VM is stopped. */
+    if (s->vm_stopped) {
+        kvm_pit_update_clock_offset(s);
+    }
+
+    kpit.flags = pit->channels[0].irq_disabled ? KVM_PIT_FLAGS_HPET_LEGACY : 0;
     for (i = 0; i < 3; i++) {
         kchan = &kpit.channels[i];
-        sc = &s->channels[i];
+        sc = &pit->channels[i];
         kchan->count = sc->count;
         kchan->latched_count = sc->latched_count;
         kchan->count_latched = sc->count_latched;
@@ -145,7 +151,7 @@ static void kvm_pit_put(PITCommonState *s)
         kchan->mode = sc->mode;
         kchan->bcd = sc->bcd;
         kchan->gate = sc->gate;
-        kchan->count_load_time = sc->count_load_time;
+        kchan->count_load_time = sc->count_load_time - s->kernel_clock_offset;
     }
 
     ret = kvm_vm_ioctl(kvm_state,
commit 205df4d1a87cbb14a50655fb2c0a987467fb29d6
Author: Jan Kiszka <jan.kiszka at siemens.com>
Date:   Tue Aug 14 10:24:03 2012 +0200

    kvm: i8254: Cache kernel clock offset in KVMPITState
    
    To prepare the final fix for clock calibration issues with the in-kernel
    PIT, we want to cache the offset between vmclock and the clock used by
    the in-kernel PIT. So far, we only need to update it when the VM state
    changes between running and stopped because we only read the in-kernel
    PIT state while the VM is running.
    
    Signed-off-by: Jan Kiszka <jan.kiszka at siemens.com>
    Signed-off-by: Marcelo Tosatti <mtosatti at redhat.com>

diff --git a/hw/kvm/i8254.c b/hw/kvm/i8254.c
index c5d3711..c235d80 100644
--- a/hw/kvm/i8254.c
+++ b/hw/kvm/i8254.c
@@ -35,7 +35,8 @@
 typedef struct KVMPITState {
     PITCommonState pit;
     LostTickPolicy lost_tick_policy;
-    bool state_valid;
+    bool vm_stopped;
+    int64_t kernel_clock_offset;
 } KVMPITState;
 
 static int64_t abs64(int64_t v)
@@ -43,19 +44,11 @@ static int64_t abs64(int64_t v)
     return v < 0 ? -v : v;
 }
 
-static void kvm_pit_get(PITCommonState *pit)
+static void kvm_pit_update_clock_offset(KVMPITState *s)
 {
-    KVMPITState *s = DO_UPCAST(KVMPITState, pit, pit);
-    struct kvm_pit_state2 kpit;
-    struct kvm_pit_channel_state *kchan;
-    struct PITChannelState *sc;
     int64_t offset, clock_offset;
     struct timespec ts;
-    int i, ret;
-
-    if (s->state_valid) {
-        return;
-    }
+    int i;
 
     /*
      * Measure the delta between CLOCK_MONOTONIC, the base used for
@@ -72,6 +65,21 @@ static void kvm_pit_get(PITCommonState *pit)
             clock_offset = offset;
         }
     }
+    s->kernel_clock_offset = clock_offset;
+}
+
+static void kvm_pit_get(PITCommonState *pit)
+{
+    KVMPITState *s = DO_UPCAST(KVMPITState, pit, pit);
+    struct kvm_pit_state2 kpit;
+    struct kvm_pit_channel_state *kchan;
+    struct PITChannelState *sc;
+    int i, ret;
+
+    /* No need to re-read the state if VM is stopped. */
+    if (s->vm_stopped) {
+        return;
+    }
 
     if (kvm_has_pit_state2()) {
         ret = kvm_vm_ioctl(kvm_state, KVM_GET_PIT2, &kpit);
@@ -106,7 +114,7 @@ static void kvm_pit_get(PITCommonState *pit)
         sc->mode = kchan->mode;
         sc->bcd = kchan->bcd;
         sc->gate = kchan->gate;
-        sc->count_load_time = kchan->count_load_time + clock_offset;
+        sc->count_load_time = kchan->count_load_time + s->kernel_clock_offset;
     }
 
     sc = &pit->channels[0];
@@ -211,10 +219,12 @@ static void kvm_pit_vm_state_change(void *opaque, int running,
     KVMPITState *s = opaque;
 
     if (running) {
-        s->state_valid = false;
+        kvm_pit_update_clock_offset(s);
+        s->vm_stopped = false;
     } else {
+        kvm_pit_update_clock_offset(s);
         kvm_pit_get(&s->pit);
-        s->state_valid = true;
+        s->vm_stopped = true;
     }
 }
 
commit 03834e22abafbc8dc4052d46a5ccd6dd135a54a3
Merge: 28a9a00... 873359d...
Author: Anthony Liguori <aliguori at us.ibm.com>
Date:   Tue Aug 14 15:19:50 2012 -0500

    Merge remote-tracking branch 'origin/master' into staging
    
    * origin/master:
      linux-user: ARM: Ignore immediate value for svc in thumb mode
      linux-user: Use init_guest_space when -R and -B are specified
      linux-user: Factor out guest space probing into a function
      flatload: fix bss clearing
      linux-user: make host_to_target_cmsg support SO_TIMESTAMP cmsg_type
      linux-user: make do_setsockopt support SOL_RAW ICMP_FILTER socket option
      linux-user: pass sockaddr from host to target
      x86: switch to AREG0 free mode
      x86: avoid AREG0 in segmentation helpers
      x86: avoid AREG0 for misc helpers
      x86: use wrappers for memory access helpers
      x86: avoid AREG0 for SMM helpers
      x86: avoid AREG0 for SVM helpers
      x86: avoid AREG0 for integer helpers
      x86: avoid AREG0 for condition code helpers
      x86: avoid AREG0 for FPU helpers
      linux-user: Move target_to_host_errno_table[] setup out of ioctl loop
      linux-user: Fix SNDCTL_DSP_MAP{IN, OUT}BUF ioctl definitions
      linux-user: Fix incorrect TARGET_BLKBSZGET, TARGET_BLKBSZSET

commit 873359d411eeb380906761e46839a2b705dbcf75
Merge: 92fc4b5... 3a1363a...
Author: Blue Swirl <blauwirbel at gmail.com>
Date:   Tue Aug 14 19:50:22 2012 +0000

    Merge branch 'linux-user.next' of git://git.linaro.org/people/pmaydell/qemu-arm
    
    * 'linux-user.next' of git://git.linaro.org/people/pmaydell/qemu-arm:
      linux-user: ARM: Ignore immediate value for svc in thumb mode
      linux-user: Use init_guest_space when -R and -B are specified
      linux-user: Factor out guest space probing into a function
      flatload: fix bss clearing
      linux-user: make host_to_target_cmsg support SO_TIMESTAMP cmsg_type
      linux-user: make do_setsockopt support SOL_RAW ICMP_FILTER socket option
      linux-user: pass sockaddr from host to target
      linux-user: Move target_to_host_errno_table[] setup out of ioctl loop
      linux-user: Fix SNDCTL_DSP_MAP{IN, OUT}BUF ioctl definitions
      linux-user: Fix incorrect TARGET_BLKBSZGET, TARGET_BLKBSZSET

commit 3a1363acf9648bc26989b01b87c7c3c494df2138
Author: Alexander Graf <agraf at suse.de>
Date:   Tue May 29 05:30:26 2012 +0000

    linux-user: ARM: Ignore immediate value for svc in thumb mode
    
    When running in thumb mode, Linux doesn't evaluate the immediate value
    of the svc instruction, but instead just always assumes the syscall number
    to be in r7.
    
    This fixes executing go_bootstrap while building go for me.
    
    Signed-off-by: Alexander Graf <agraf at suse.de>
    Reviewed-by: Peter Maydell <peter.maydell at linaro.org>
    Signed-off-by: Peter Maydell <peter.maydell at linaro.org>

diff --git a/linux-user/main.c b/linux-user/main.c
index 63c1249..7dea084 100644
--- a/linux-user/main.c
+++ b/linux-user/main.c
@@ -822,8 +822,7 @@ void cpu_loop(CPUARMState *env)
                 } else if (n == ARM_NR_semihosting
                            || n == ARM_NR_thumb_semihosting) {
                     env->regs[0] = do_arm_semihosting (env);
-                } else if (n == 0 || n >= ARM_SYSCALL_BASE
-                           || (env->thumb && n == ARM_THUMB_SYSCALL)) {
+                } else if (n == 0 || n >= ARM_SYSCALL_BASE || env->thumb) {
                     /* linux syscall */
                     if (env->thumb || n == 0) {
                         n = env->regs[7];
commit 806d102141b99d4f1e55a97d68b7ea8c8ba3129f
Author: Meador Inge <meadori at codesourcery.com>
Date:   Thu Jul 26 16:50:02 2012 +0000

    linux-user: Use init_guest_space when -R and -B are specified
    
    Roll the code used to initialize the guest memory space when -R
    or -B is used into 'init_guest_space' and then call 'init_guest_space'
    from the driver.  This way the reserved guest memory space can
    be probed for.  Calling 'mmap' just once as is currently done is not
    guaranteed to succeed since the host address space validation might fail.
    
    Signed-off-by: Meador Inge <meadori at codesourcery.com>
    [PMM: Fixed minor whitespace errors.]
    Reviewed-by: Peter Maydell <peter.maydell at linaro.org>
    Signed-off-by: Peter Maydell <peter.maydell at linaro.org>

diff --git a/linux-user/elfload.c b/linux-user/elfload.c
index cbc7617..819fdd5 100644
--- a/linux-user/elfload.c
+++ b/linux-user/elfload.c
@@ -332,9 +332,17 @@ enum
     ARM_HWCAP_ARM_VFPv3D16  = 1 << 13,
 };
 
-#define TARGET_HAS_GUEST_VALIDATE_BASE
-/* We want the opportunity to check the suggested base */
-bool guest_validate_base(unsigned long guest_base)
+#define TARGET_HAS_VALIDATE_GUEST_SPACE
+/* Return 1 if the proposed guest space is suitable for the guest.
+ * Return 0 if the proposed guest space isn't suitable, but another
+ * address space should be tried.
+ * Return -1 if there is no way the proposed guest space can be
+ * valid regardless of the base.
+ * The guest code may leave a page mapped and populate it if the
+ * address is suitable.
+ */
+static int validate_guest_space(unsigned long guest_base,
+                                unsigned long guest_size)
 {
     unsigned long real_start, test_page_addr;
 
@@ -342,6 +350,15 @@ bool guest_validate_base(unsigned long guest_base)
      * commpage at 0xffff0fxx
      */
     test_page_addr = guest_base + (0xffff0f00 & qemu_host_page_mask);
+
+    /* If the commpage lies within the already allocated guest space,
+     * then there is no way we can allocate it.
+     */
+    if (test_page_addr >= guest_base
+        && test_page_addr <= (guest_base + guest_size)) {
+        return -1;
+    }
+
     /* Note it needs to be writeable to let us initialise it */
     real_start = (unsigned long)
                  mmap((void *)test_page_addr, qemu_host_page_size,
@@ -1418,9 +1435,10 @@ static abi_ulong create_elf_tables(abi_ulong p, int argc, int envc,
     return sp;
 }
 
-#ifndef TARGET_HAS_GUEST_VALIDATE_BASE
+#ifndef TARGET_HAS_VALIDATE_GUEST_SPACE
 /* If the guest doesn't have a validation function just agree */
-bool guest_validate_base(unsigned long guest_base)
+static int validate_guest_space(unsigned long guest_base,
+                                unsigned long guest_size)
 {
     return 1;
 }
@@ -1439,7 +1457,7 @@ unsigned long init_guest_space(unsigned long host_start,
     /* If just a starting address is given, then just verify that
      * address.  */
     if (host_start && !host_size) {
-        if (guest_validate_base(host_start)) {
+        if (validate_guest_space(host_start, host_size) == 1) {
             return host_start;
         } else {
             return (unsigned long)-1;
@@ -1456,6 +1474,8 @@ unsigned long init_guest_space(unsigned long host_start,
     /* Otherwise, a non-zero size region of memory needs to be mapped
      * and validated.  */
     while (1) {
+        unsigned long real_size = host_size;
+
         /* Do not use mmap_find_vma here because that is limited to the
          * guest address space.  We are going to make the
          * guest address space fit whatever we're given.
@@ -1466,9 +1486,28 @@ unsigned long init_guest_space(unsigned long host_start,
             return (unsigned long)-1;
         }
 
-        if ((real_start == current_start)
-            && guest_validate_base(real_start - guest_start)) {
-            break;
+        /* Ensure the address is properly aligned.  */
+        if (real_start & ~qemu_host_page_mask) {
+            munmap((void *)real_start, host_size);
+            real_size = host_size + qemu_host_page_size;
+            real_start = (unsigned long)
+                mmap((void *)real_start, real_size, PROT_NONE, flags, -1, 0);
+            if (real_start == (unsigned long)-1) {
+                return (unsigned long)-1;
+            }
+            real_start = HOST_PAGE_ALIGN(real_start);
+        }
+
+        /* Check to see if the address is valid.  */
+        if (!host_start || real_start == current_start) {
+            int valid = validate_guest_space(real_start - guest_start,
+                                             real_size);
+            if (valid == 1) {
+                break;
+            } else if (valid == -1) {
+                return (unsigned long)-1;
+            }
+            /* valid == 0, so try again. */
         }
 
         /* That address didn't work.  Unmap and try a different one.
@@ -1490,6 +1529,8 @@ unsigned long init_guest_space(unsigned long host_start,
         }
     }
 
+    qemu_log("Reserved 0x%lx bytes of guest address space\n", host_size);
+
     return real_start;
 }
 
diff --git a/linux-user/main.c b/linux-user/main.c
index 9d921aa..63c1249 100644
--- a/linux-user/main.c
+++ b/linux-user/main.c
@@ -3516,39 +3516,16 @@ int main(int argc, char **argv, char **envp)
      */
     guest_base = HOST_PAGE_ALIGN(guest_base);
 
-    if (reserved_va) {
-        void *p;
-        int flags;
-
-        flags = MAP_ANONYMOUS | MAP_PRIVATE | MAP_NORESERVE;
-        if (have_guest_base) {
-            flags |= MAP_FIXED;
-        }
-        p = mmap((void *)guest_base, reserved_va, PROT_NONE, flags, -1, 0);
-        if (p == MAP_FAILED) {
+    if (reserved_va || have_guest_base) {
+        guest_base = init_guest_space(guest_base, reserved_va, 0,
+                                      have_guest_base);
+        if (guest_base == (unsigned long)-1) {
             fprintf(stderr, "Unable to reserve guest address space\n");
             exit(1);
         }
-        guest_base = (unsigned long)p;
-        /* Make sure the address is properly aligned.  */
-        if (guest_base & ~qemu_host_page_mask) {
-            munmap(p, reserved_va);
-            p = mmap((void *)guest_base, reserved_va + qemu_host_page_size,
-                     PROT_NONE, flags, -1, 0);
-            if (p == MAP_FAILED) {
-                fprintf(stderr, "Unable to reserve guest address space\n");
-                exit(1);
-            }
-            guest_base = HOST_PAGE_ALIGN((unsigned long)p);
-        }
-        qemu_log("Reserved 0x%lx bytes of guest address space\n", reserved_va);
-        mmap_next_start = reserved_va;
-    }
 
-    if (reserved_va || have_guest_base) {
-        if (!guest_validate_base(guest_base)) {
-            fprintf(stderr, "Guest base/Reserved VA rejected by guest code\n");
-            exit(1);
+        if (reserved_va) {
+            mmap_next_start = reserved_va;
         }
     }
 #endif /* CONFIG_USE_GUEST_BASE */
diff --git a/linux-user/qemu.h b/linux-user/qemu.h
index 7d4e23e..69b27d7 100644
--- a/linux-user/qemu.h
+++ b/linux-user/qemu.h
@@ -204,12 +204,6 @@ int get_osversion(void);
 void fork_start(void);
 void fork_end(int child);
 
-/* Return true if the proposed guest_base is suitable for the guest.
- * The guest code may leave a page mapped and populate it if the
- * address is suitable.
- */
-bool guest_validate_base(unsigned long guest_base);
-
 /* Creates the initial guest address space in the host memory space using
  * the given host start address hint and size.  The guest_start parameter
  * specifies the start address of the guest space.  guest_base will be the
commit dce104013d1b393d39a89c4417d7771d928c08f3
Author: Meador Inge <meadori at codesourcery.com>
Date:   Thu Jul 26 16:50:01 2012 +0000

    linux-user: Factor out guest space probing into a function
    
    Signed-off-by: Meador Inge <meadori at codesourcery.com>
    Reviewed-by: Peter Maydell <peter.maydell at linaro.org>
    Signed-off-by: Peter Maydell <peter.maydell at linaro.org>

diff --git a/linux-user/elfload.c b/linux-user/elfload.c
index 6b622d4..cbc7617 100644
--- a/linux-user/elfload.c
+++ b/linux-user/elfload.c
@@ -1426,6 +1426,73 @@ bool guest_validate_base(unsigned long guest_base)
 }
 #endif
 
+unsigned long init_guest_space(unsigned long host_start,
+                               unsigned long host_size,
+                               unsigned long guest_start,
+                               bool fixed)
+{
+    unsigned long current_start, real_start;
+    int flags;
+
+    assert(host_start || host_size);
+
+    /* If just a starting address is given, then just verify that
+     * address.  */
+    if (host_start && !host_size) {
+        if (guest_validate_base(host_start)) {
+            return host_start;
+        } else {
+            return (unsigned long)-1;
+        }
+    }
+
+    /* Setup the initial flags and start address.  */
+    current_start = host_start & qemu_host_page_mask;
+    flags = MAP_ANONYMOUS | MAP_PRIVATE | MAP_NORESERVE;
+    if (fixed) {
+        flags |= MAP_FIXED;
+    }
+
+    /* Otherwise, a non-zero size region of memory needs to be mapped
+     * and validated.  */
+    while (1) {
+        /* Do not use mmap_find_vma here because that is limited to the
+         * guest address space.  We are going to make the
+         * guest address space fit whatever we're given.
+         */
+        real_start = (unsigned long)
+            mmap((void *)current_start, host_size, PROT_NONE, flags, -1, 0);
+        if (real_start == (unsigned long)-1) {
+            return (unsigned long)-1;
+        }
+
+        if ((real_start == current_start)
+            && guest_validate_base(real_start - guest_start)) {
+            break;
+        }
+
+        /* That address didn't work.  Unmap and try a different one.
+         * The address the host picked because is typically right at
+         * the top of the host address space and leaves the guest with
+         * no usable address space.  Resort to a linear search.  We
+         * already compensated for mmap_min_addr, so this should not
+         * happen often.  Probably means we got unlucky and host
+         * address space randomization put a shared library somewhere
+         * inconvenient.
+         */
+        munmap((void *)real_start, host_size);
+        current_start += qemu_host_page_size;
+        if (host_start == current_start) {
+            /* Theoretically possible if host doesn't have any suitably
+             * aligned areas.  Normally the first mmap will fail.
+             */
+            return (unsigned long)-1;
+        }
+    }
+
+    return real_start;
+}
+
 static void probe_guest_base(const char *image_name,
                              abi_ulong loaddr, abi_ulong hiaddr)
 {
@@ -1452,46 +1519,23 @@ static void probe_guest_base(const char *image_name,
             }
         }
         host_size = hiaddr - loaddr;
-        while (1) {
-            /* Do not use mmap_find_vma here because that is limited to the
-               guest address space.  We are going to make the
-               guest address space fit whatever we're given.  */
-            real_start = (unsigned long)
-                mmap((void *)host_start, host_size, PROT_NONE,
-                     MAP_ANONYMOUS | MAP_PRIVATE | MAP_NORESERVE, -1, 0);
-            if (real_start == (unsigned long)-1) {
-                goto exit_perror;
-            }
-            guest_base = real_start - loaddr;
-            if ((real_start == host_start) &&
-                guest_validate_base(guest_base)) {
-                break;
-            }
-            /* That address didn't work.  Unmap and try a different one.
-               The address the host picked because is typically right at
-               the top of the host address space and leaves the guest with
-               no usable address space.  Resort to a linear search.  We
-               already compensated for mmap_min_addr, so this should not
-               happen often.  Probably means we got unlucky and host
-               address space randomization put a shared library somewhere
-               inconvenient.  */
-            munmap((void *)real_start, host_size);
-            host_start += qemu_host_page_size;
-            if (host_start == loaddr) {
-                /* Theoretically possible if host doesn't have any suitably
-                   aligned areas.  Normally the first mmap will fail.  */
-                errmsg = "Unable to find space for application";
-                goto exit_errmsg;
-            }
+
+        /* Setup the initial guest memory space with ranges gleaned from
+         * the ELF image that is being loaded.
+         */
+        real_start = init_guest_space(host_start, host_size, loaddr, false);
+        if (real_start == (unsigned long)-1) {
+            errmsg = "Unable to find space for application";
+            goto exit_errmsg;
         }
+        guest_base = real_start - loaddr;
+
         qemu_log("Relocating guest address space from 0x"
                  TARGET_ABI_FMT_lx " to 0x%lx\n",
                  loaddr, real_start);
     }
     return;
 
-exit_perror:
-    errmsg = strerror(errno);
 exit_errmsg:
     fprintf(stderr, "%s: %s\n", image_name, errmsg);
     exit(-1);
diff --git a/linux-user/qemu.h b/linux-user/qemu.h
index 7b299b7..7d4e23e 100644
--- a/linux-user/qemu.h
+++ b/linux-user/qemu.h
@@ -210,6 +210,19 @@ void fork_end(int child);
  */
 bool guest_validate_base(unsigned long guest_base);
 
+/* Creates the initial guest address space in the host memory space using
+ * the given host start address hint and size.  The guest_start parameter
+ * specifies the start address of the guest space.  guest_base will be the
+ * difference between the host start address computed by this function and
+ * guest_start.  If fixed is specified, then the mapped address space must
+ * start at host_start.  The real start address of the mapped memory space is
+ * returned or -1 if there was an error.
+ */
+unsigned long init_guest_space(unsigned long host_start,
+                               unsigned long host_size,
+                               unsigned long guest_start,
+                               bool fixed);
+
 #include "qemu-log.h"
 
 /* strace.c */
commit cd8e407d24657569e0d6e323b2e8c274fafab590
Author: Mike Frysinger <vapier at gentoo.org>
Date:   Mon Jul 9 03:04:57 2012 +0000

    flatload: fix bss clearing
    
    The current bss clear logic assumes the target mmap address and host
    address are the same.  Use g2h to translate from the target address
    space to the host so we can call memset on it.
    
    Signed-off-by: Mike Frysinger <vapier at gentoo.org>
    Reviewed-by: Peter Maydell <peter.maydell at linaro.org>
    Signed-off-by: Peter Maydell <peter.maydell at linaro.org>

diff --git a/linux-user/flatload.c b/linux-user/flatload.c
index be79496..58f679e 100644
--- a/linux-user/flatload.c
+++ b/linux-user/flatload.c
@@ -660,7 +660,7 @@ static int load_flat_file(struct linux_binprm * bprm,
     }
 
     /* zero the BSS.  */
-    memset((void *)((unsigned long)datapos + data_len), 0, bss_len);
+    memset(g2h(datapos + data_len), 0, bss_len);
 
     return 0;
 }
commit aebf5bc727fa1837b3c5296c5325b560f19ed9ee
Author: Jing Huang <jing.huang.pku at gmail.com>
Date:   Tue Jul 24 14:01:42 2012 +0000

    linux-user: make host_to_target_cmsg support SO_TIMESTAMP cmsg_type
    
    Signed-off-by: Jing Huang <jing.huang.pku at gmail.com>
    Reviewed-by: Peter Maydell <peter.maydell at linaro.org>
    Signed-off-by: Peter Maydell <peter.maydell at linaro.org>

diff --git a/linux-user/syscall.c b/linux-user/syscall.c
index ae9c1d0..41c869b 100644
--- a/linux-user/syscall.c
+++ b/linux-user/syscall.c
@@ -1359,16 +1359,28 @@ static inline abi_long host_to_target_cmsg(struct target_msghdr *target_msgh,
         target_cmsg->cmsg_type = tswap32(cmsg->cmsg_type);
         target_cmsg->cmsg_len = tswapal(TARGET_CMSG_LEN(len));
 
-        if (cmsg->cmsg_level != TARGET_SOL_SOCKET || cmsg->cmsg_type != SCM_RIGHTS) {
-            gemu_log("Unsupported ancillary data: %d/%d\n", cmsg->cmsg_level, cmsg->cmsg_type);
-            memcpy(target_data, data, len);
-        } else {
+        if ((cmsg->cmsg_level == TARGET_SOL_SOCKET) &&
+                                (cmsg->cmsg_type == SCM_RIGHTS)) {
             int *fd = (int *)data;
             int *target_fd = (int *)target_data;
             int i, numfds = len / sizeof(int);
 
             for (i = 0; i < numfds; i++)
                 target_fd[i] = tswap32(fd[i]);
+        } else if ((cmsg->cmsg_level == TARGET_SOL_SOCKET) &&
+                                (cmsg->cmsg_type == SO_TIMESTAMP) &&
+                                (len == sizeof(struct timeval))) {
+            /* copy struct timeval to target */
+            struct timeval *tv = (struct timeval *)data;
+            struct target_timeval *target_tv =
+                                        (struct target_timeval *)target_data;
+
+            target_tv->tv_sec = tswapal(tv->tv_sec);
+            target_tv->tv_usec = tswapal(tv->tv_usec);
+        } else {
+            gemu_log("Unsupported ancillary data: %d/%d\n",
+                                        cmsg->cmsg_level, cmsg->cmsg_type);
+            memcpy(target_data, data, len);
         }
 
         cmsg = CMSG_NXTHDR(msgh, cmsg);
commit 920394db819e30fbbfa527f25e45360061d1a220
Author: Jing Huang <jing.huang.pku at gmail.com>
Date:   Tue Jul 24 13:59:23 2012 +0000

    linux-user: make do_setsockopt support SOL_RAW ICMP_FILTER socket option
    
    Signed-off-by: Jing Huang <jing.huang.pku at gmail.com>
    Reviewed-by: Peter Maydell <peter.maydell at linaro.org>
    Signed-off-by: Peter Maydell <peter.maydell at linaro.org>

diff --git a/linux-user/syscall.c b/linux-user/syscall.c
index 4bc11f1..ae9c1d0 100644
--- a/linux-user/syscall.c
+++ b/linux-user/syscall.c
@@ -60,6 +60,7 @@ int __clone2(int (*fn)(void *), void *child_stack_base,
 #include <netinet/ip.h>
 #include <netinet/tcp.h>
 #include <linux/wireless.h>
+#include <linux/icmp.h>
 #include "qemu-common.h"
 #ifdef TARGET_GPROF
 #include <sys/gmon.h>
@@ -1452,6 +1453,25 @@ static abi_long do_setsockopt(int sockfd, int level, int optname,
             goto unimplemented;
         }
         break;
+    case SOL_RAW:
+        switch (optname) {
+        case ICMP_FILTER:
+            /* struct icmp_filter takes an u32 value */
+            if (optlen < sizeof(uint32_t)) {
+                return -TARGET_EINVAL;
+            }
+
+            if (get_user_u32(val, optval_addr)) {
+                return -TARGET_EFAULT;
+            }
+            ret = get_errno(setsockopt(sockfd, level, optname,
+                                       &val, sizeof(val)));
+            break;
+
+        default:
+            goto unimplemented;
+        }
+        break;
     case TARGET_SOL_SOCKET:
         switch (optname) {
             /* Options with 'int' argument.  */
commit ca6190673c90e283897740b243f6508055c9de5a
Author: Jing Huang <jing.huang.pku at gmail.com>
Date:   Tue Jul 24 13:58:02 2012 +0000

    linux-user: pass sockaddr from host to target
    
    Signed-off-by: Jing Huang <jing.huang.pku at gmail.com>
    Reviewed-by: Peter Maydell <peter.maydell at linaro.org>
    Signed-off-by: Peter Maydell <peter.maydell at linaro.org>

diff --git a/linux-user/syscall.c b/linux-user/syscall.c
index 8a06131..4bc11f1 100644
--- a/linux-user/syscall.c
+++ b/linux-user/syscall.c
@@ -1268,7 +1268,6 @@ static inline abi_long host_to_target_sockaddr(abi_ulong target_addr,
     return 0;
 }
 
-/* ??? Should this also swap msgh->name?  */
 static inline abi_long target_to_host_cmsg(struct msghdr *msgh,
                                            struct target_msghdr *target_msgh)
 {
@@ -1325,7 +1324,6 @@ static inline abi_long target_to_host_cmsg(struct msghdr *msgh,
     return 0;
 }
 
-/* ??? Should this also swap msgh->name?  */
 static inline abi_long host_to_target_cmsg(struct target_msghdr *target_msgh,
                                            struct msghdr *msgh)
 {
@@ -1885,10 +1883,22 @@ static abi_long do_sendrecvmsg(int fd, abi_ulong target_msg,
         if (!is_error(ret)) {
             len = ret;
             ret = host_to_target_cmsg(msgp, &msg);
-            if (!is_error(ret))
+            if (!is_error(ret)) {
+                msgp->msg_namelen = tswap32(msg.msg_namelen);
+                if (msg.msg_name != NULL) {
+                    ret = host_to_target_sockaddr(tswapal(msgp->msg_name),
+                                    msg.msg_name, msg.msg_namelen);
+                    if (ret) {
+                        goto out;
+                    }
+                }
+
                 ret = len;
+            }
         }
     }
+
+out:
     unlock_iovec(vec, target_vec, count, !send);
     unlock_user_struct(msgp, target_msg, send ? 0 : 1);
     return ret;
commit 92fc4b586f8856ee9f2bad31fb6e9acd80fa8319
Author: Blue Swirl <blauwirbel at gmail.com>
Date:   Sun Apr 29 20:35:48 2012 +0000

    x86: switch to AREG0 free mode
    
    Add an explicit CPUX86State parameter instead of relying on AREG0.
    
    Remove temporary wrappers and switch to AREG0 free mode.
    
    Signed-off-by: Blue Swirl <blauwirbel at gmail.com>

diff --git a/configure b/configure
index fea62f1..edf9da4 100755
--- a/configure
+++ b/configure
@@ -3778,7 +3778,7 @@ symlink "$source_path/Makefile.target" "$target_dir/Makefile"
 
 
 case "$target_arch2" in
-  alpha | or32 | sparc* | xtensa* | ppc*)
+  alpha | i386 | or32 | sparc* | x86_64 | xtensa* | ppc*)
     echo "CONFIG_TCG_PASS_AREG0=y" >> $config_target_mak
   ;;
 esac
diff --git a/cpu-all.h b/cpu-all.h
index 82ba1d7..5e07d28 100644
--- a/cpu-all.h
+++ b/cpu-all.h
@@ -274,6 +274,28 @@ extern unsigned long reserved_va;
 #define cpu_ldsw_code(env1, p) ldsw_raw(p)
 #define cpu_ldl_code(env1, p) ldl_raw(p)
 #define cpu_ldq_code(env1, p) ldq_raw(p)
+
+#define cpu_ldub_data(env, addr) ldub_raw(addr)
+#define cpu_lduw_data(env, addr) lduw_raw(addr)
+#define cpu_ldsw_data(env, addr) ldsw_raw(addr)
+#define cpu_ldl_data(env, addr) ldl_raw(addr)
+#define cpu_ldq_data(env, addr) ldq_raw(addr)
+
+#define cpu_stb_data(env, addr, data) stb_raw(addr, data)
+#define cpu_stw_data(env, addr, data) stw_raw(addr, data)
+#define cpu_stl_data(env, addr, data) stl_raw(addr, data)
+#define cpu_stq_data(env, addr, data) stq_raw(addr, data)
+
+#define cpu_ldub_kernel(env, addr) ldub_raw(addr)
+#define cpu_lduw_kernel(env, addr) lduw_raw(addr)
+#define cpu_ldsw_kernel(env, addr) ldsw_raw(addr)
+#define cpu_ldl_kernel(env, addr) ldl_raw(addr)
+#define cpu_ldq_kernel(env, addr) ldq_raw(addr)
+
+#define cpu_stb_kernel(env, addr, data) stb_raw(addr, data)
+#define cpu_stw_kernel(env, addr, data) stw_raw(addr, data)
+#define cpu_stl_kernel(env, addr, data) stl_raw(addr, data)
+#define cpu_stq_kernel(env, addr, data) stq_raw(addr, data)
 #endif
 
 #define ldub_kernel(p) ldub_raw(p)
diff --git a/target-i386/Makefile.objs b/target-i386/Makefile.objs
index 71d7d3b..c1d4f05 100644
--- a/target-i386/Makefile.objs
+++ b/target-i386/Makefile.objs
@@ -6,5 +6,3 @@ obj-$(CONFIG_KVM) += kvm.o hyperv.o
 obj-$(CONFIG_NO_KVM) += kvm-stub.o
 obj-$(CONFIG_LINUX_USER) += ioport-user.o
 obj-$(CONFIG_BSD_USER) += ioport-user.o
-
-$(obj)/mem_helper.o: QEMU_CFLAGS += $(HELPER_CFLAGS)
diff --git a/target-i386/cpu.h b/target-i386/cpu.h
index f33be16..60f9e97 100644
--- a/target-i386/cpu.h
+++ b/target-i386/cpu.h
@@ -1138,25 +1138,4 @@ void do_smm_enter(CPUX86State *env1);
 
 void cpu_report_tpr_access(CPUX86State *env, TPRAccess access);
 
-/* temporary wrappers */
-uint32_t cpu_ldub_data(CPUX86State *env, target_ulong ptr);
-uint32_t cpu_lduw_data(CPUX86State *env, target_ulong ptr);
-uint32_t cpu_ldl_data(CPUX86State *env, target_ulong ptr);
-uint64_t cpu_ldq_data(CPUX86State *env, target_ulong ptr);
-
-void cpu_stb_data(CPUX86State *env, target_ulong ptr, uint32_t data);
-void cpu_stw_data(CPUX86State *env, target_ulong ptr, uint32_t data);
-void cpu_stl_data(CPUX86State *env, target_ulong ptr, uint32_t data);
-void cpu_stq_data(CPUX86State *env, target_ulong ptr, uint64_t data);
-
-uint32_t cpu_ldub_kernel(CPUX86State *env, target_ulong ptr);
-uint32_t cpu_lduw_kernel(CPUX86State *env, target_ulong ptr);
-uint32_t cpu_ldl_kernel(CPUX86State *env, target_ulong ptr);
-uint64_t cpu_ldq_kernel(CPUX86State *env, target_ulong ptr);
-
-void cpu_stb_kernel(CPUX86State *env, target_ulong ptr, uint32_t data);
-void cpu_stw_kernel(CPUX86State *env, target_ulong ptr, uint32_t data);
-void cpu_stl_kernel(CPUX86State *env, target_ulong ptr, uint32_t data);
-void cpu_stq_kernel(CPUX86State *env, target_ulong ptr, uint64_t data);
-
 #endif /* CPU_I386_H */
diff --git a/target-i386/fpu_helper.c b/target-i386/fpu_helper.c
index a1d7ef7..dfc34a6 100644
--- a/target-i386/fpu_helper.c
+++ b/target-i386/fpu_helper.c
@@ -21,6 +21,10 @@
 #include "cpu.h"
 #include "helper.h"
 
+#if !defined(CONFIG_USER_ONLY)
+#include "softmmu_exec.h"
+#endif /* !defined(CONFIG_USER_ONLY) */
+
 #define FPU_RC_MASK         0xc00
 #define FPU_RC_NEAR         0x000
 #define FPU_RC_DOWN         0x400
diff --git a/target-i386/helper.h b/target-i386/helper.h
index 0f02103..ab6af63 100644
--- a/target-i386/helper.h
+++ b/target-i386/helper.h
@@ -69,13 +69,13 @@ DEF_HELPER_1(cli, void, env)
 DEF_HELPER_1(sti, void, env)
 DEF_HELPER_1(set_inhibit_irq, void, env)
 DEF_HELPER_1(reset_inhibit_irq, void, env)
-DEF_HELPER_2(boundw, void, tl, int)
-DEF_HELPER_2(boundl, void, tl, int)
+DEF_HELPER_3(boundw, void, env, tl, int)
+DEF_HELPER_3(boundl, void, env, tl, int)
 DEF_HELPER_1(rsm, void, env)
 DEF_HELPER_2(into, void, env, int)
-DEF_HELPER_1(cmpxchg8b, void, tl)
+DEF_HELPER_2(cmpxchg8b, void, env, tl)
 #ifdef TARGET_X86_64
-DEF_HELPER_1(cmpxchg16b, void, tl)
+DEF_HELPER_2(cmpxchg16b, void, env, tl)
 #endif
 DEF_HELPER_1(single_step, void, env)
 DEF_HELPER_1(cpuid, void, env)
diff --git a/target-i386/mem_helper.c b/target-i386/mem_helper.c
index 3dd4406..7f99c7c 100644
--- a/target-i386/mem_helper.c
+++ b/target-i386/mem_helper.c
@@ -18,7 +18,6 @@
  */
 
 #include "cpu.h"
-#include "dyngen-exec.h"
 #include "helper.h"
 
 #if !defined(CONFIG_USER_ONLY)
@@ -39,19 +38,19 @@ void helper_unlock(void)
     spin_unlock(&global_cpu_lock);
 }
 
-void helper_cmpxchg8b(target_ulong a0)
+void helper_cmpxchg8b(CPUX86State *env, target_ulong a0)
 {
     uint64_t d;
     int eflags;
 
     eflags = cpu_cc_compute_all(env, CC_OP);
-    d = ldq(a0);
+    d = cpu_ldq_data(env, a0);
     if (d == (((uint64_t)EDX << 32) | (uint32_t)EAX)) {
-        stq(a0, ((uint64_t)ECX << 32) | (uint32_t)EBX);
+        cpu_stq_data(env, a0, ((uint64_t)ECX << 32) | (uint32_t)EBX);
         eflags |= CC_Z;
     } else {
         /* always do the store */
-        stq(a0, d);
+        cpu_stq_data(env, a0, d);
         EDX = (uint32_t)(d >> 32);
         EAX = (uint32_t)d;
         eflags &= ~CC_Z;
@@ -60,7 +59,7 @@ void helper_cmpxchg8b(target_ulong a0)
 }
 
 #ifdef TARGET_X86_64
-void helper_cmpxchg16b(target_ulong a0)
+void helper_cmpxchg16b(CPUX86State *env, target_ulong a0)
 {
     uint64_t d0, d1;
     int eflags;
@@ -69,16 +68,16 @@ void helper_cmpxchg16b(target_ulong a0)
         raise_exception(env, EXCP0D_GPF);
     }
     eflags = cpu_cc_compute_all(env, CC_OP);
-    d0 = ldq(a0);
-    d1 = ldq(a0 + 8);
+    d0 = cpu_ldq_data(env, a0);
+    d1 = cpu_ldq_data(env, a0 + 8);
     if (d0 == EAX && d1 == EDX) {
-        stq(a0, EBX);
-        stq(a0 + 8, ECX);
+        cpu_stq_data(env, a0, EBX);
+        cpu_stq_data(env, a0 + 8, ECX);
         eflags |= CC_Z;
     } else {
         /* always do the store */
-        stq(a0, d0);
-        stq(a0 + 8, d1);
+        cpu_stq_data(env, a0, d0);
+        cpu_stq_data(env, a0 + 8, d1);
         EDX = d1;
         EAX = d0;
         eflags &= ~CC_Z;
@@ -87,24 +86,24 @@ void helper_cmpxchg16b(target_ulong a0)
 }
 #endif
 
-void helper_boundw(target_ulong a0, int v)
+void helper_boundw(CPUX86State *env, target_ulong a0, int v)
 {
     int low, high;
 
-    low = ldsw(a0);
-    high = ldsw(a0 + 2);
+    low = cpu_ldsw_data(env, a0);
+    high = cpu_ldsw_data(env, a0 + 2);
     v = (int16_t)v;
     if (v < low || v > high) {
         raise_exception(env, EXCP05_BOUND);
     }
 }
 
-void helper_boundl(target_ulong a0, int v)
+void helper_boundl(CPUX86State *env, target_ulong a0, int v)
 {
     int low, high;
 
-    low = ldl(a0);
-    high = ldl(a0 + 4);
+    low = cpu_ldl_data(env, a0);
+    high = cpu_ldl_data(env, a0 + 4);
     if (v < low || v > high) {
         raise_exception(env, EXCP05_BOUND);
     }
@@ -133,15 +132,11 @@ void helper_boundl(target_ulong a0, int v)
    NULL, it means that the function was called in C code (i.e. not
    from generated code or from helper.c) */
 /* XXX: fix it to restore all registers */
-void tlb_fill(CPUX86State *env1, target_ulong addr, int is_write, int mmu_idx,
+void tlb_fill(CPUX86State *env, target_ulong addr, int is_write, int mmu_idx,
               uintptr_t retaddr)
 {
     TranslationBlock *tb;
     int ret;
-    CPUX86State *saved_env;
-
-    saved_env = env;
-    env = env1;
 
     ret = cpu_x86_handle_mmu_fault(env, addr, is_write, mmu_idx);
     if (ret) {
@@ -156,65 +151,5 @@ void tlb_fill(CPUX86State *env1, target_ulong addr, int is_write, int mmu_idx,
         }
         raise_exception_err(env, env->exception_index, env->error_code);
     }
-    env = saved_env;
 }
 #endif
-
-/* temporary wrappers */
-#if defined(CONFIG_USER_ONLY)
-#define ldub_data(addr) ldub_raw(addr)
-#define lduw_data(addr) lduw_raw(addr)
-#define ldl_data(addr) ldl_raw(addr)
-#define ldq_data(addr) ldq_raw(addr)
-
-#define stb_data(addr, data) stb_raw(addr, data)
-#define stw_data(addr, data) stw_raw(addr, data)
-#define stl_data(addr, data) stl_raw(addr, data)
-#define stq_data(addr, data) stq_raw(addr, data)
-#endif
-
-#define WRAP_LD(rettype, fn)                                    \
-    rettype cpu_ ## fn(CPUX86State *env1, target_ulong addr)    \
-    {                                                           \
-        CPUX86State *saved_env;                                 \
-        rettype ret;                                            \
-                                                                \
-        saved_env = env;                                        \
-        env = env1;                                             \
-        ret = fn(addr);                                         \
-        env = saved_env;                                        \
-        return ret;                                             \
-    }
-
-WRAP_LD(uint32_t, ldub_data)
-WRAP_LD(uint32_t, lduw_data)
-WRAP_LD(uint32_t, ldl_data)
-WRAP_LD(uint64_t, ldq_data)
-
-WRAP_LD(uint32_t, ldub_kernel)
-WRAP_LD(uint32_t, lduw_kernel)
-WRAP_LD(uint32_t, ldl_kernel)
-WRAP_LD(uint64_t, ldq_kernel)
-#undef WRAP_LD
-
-#define WRAP_ST(datatype, fn)                                           \
-    void cpu_ ## fn(CPUX86State *env1, target_ulong addr, datatype val) \
-    {                                                                   \
-        CPUX86State *saved_env;                                         \
-                                                                        \
-        saved_env = env;                                                \
-        env = env1;                                                     \
-        fn(addr, val);                                                  \
-        env = saved_env;                                                \
-    }
-
-WRAP_ST(uint32_t, stb_data)
-WRAP_ST(uint32_t, stw_data)
-WRAP_ST(uint32_t, stl_data)
-WRAP_ST(uint64_t, stq_data)
-
-WRAP_ST(uint32_t, stb_kernel)
-WRAP_ST(uint32_t, stw_kernel)
-WRAP_ST(uint32_t, stl_kernel)
-WRAP_ST(uint64_t, stq_kernel)
-#undef WRAP_ST
diff --git a/target-i386/misc_helper.c b/target-i386/misc_helper.c
index 154601b..a020379 100644
--- a/target-i386/misc_helper.c
+++ b/target-i386/misc_helper.c
@@ -21,6 +21,10 @@
 #include "ioport.h"
 #include "helper.h"
 
+#if !defined(CONFIG_USER_ONLY)
+#include "softmmu_exec.h"
+#endif /* !defined(CONFIG_USER_ONLY) */
+
 /* check if Port I/O is allowed in TSS */
 static inline void check_io(CPUX86State *env, int addr, int size)
 {
diff --git a/target-i386/seg_helper.c b/target-i386/seg_helper.c
index f136128..5fff8d5 100644
--- a/target-i386/seg_helper.c
+++ b/target-i386/seg_helper.c
@@ -24,6 +24,10 @@
 
 //#define DEBUG_PCALL
 
+#if !defined(CONFIG_USER_ONLY)
+#include "softmmu_exec.h"
+#endif /* !defined(CONFIG_USER_ONLY) */
+
 #ifdef DEBUG_PCALL
 # define LOG_PCALL(...) qemu_log_mask(CPU_LOG_PCALL, ## __VA_ARGS__)
 # define LOG_PCALL_STATE(env)                                  \
diff --git a/target-i386/svm_helper.c b/target-i386/svm_helper.c
index f370ac5..4943c37 100644
--- a/target-i386/svm_helper.c
+++ b/target-i386/svm_helper.c
@@ -21,6 +21,10 @@
 #include "cpu-all.h"
 #include "helper.h"
 
+#if !defined(CONFIG_USER_ONLY)
+#include "softmmu_exec.h"
+#endif /* !defined(CONFIG_USER_ONLY) */
+
 /* Secure Virtual Machine helpers */
 
 #if defined(CONFIG_USER_ONLY)
diff --git a/target-i386/translate.c b/target-i386/translate.c
index 26091f9..7ab2ccb 100644
--- a/target-i386/translate.c
+++ b/target-i386/translate.c
@@ -2043,7 +2043,7 @@ static void gen_lea_modrm(DisasContext *s, int modrm, int *reg_ptr, int *offset_
 
         if (base == 4) {
             havesib = 1;
-            code = ldub_code(s->pc++);
+            code = cpu_ldub_code(cpu_single_env, s->pc++);
             scale = (code >> 6) & 3;
             index = ((code >> 3) & 7) | REX_X(s);
             base = (code & 7);
@@ -2054,7 +2054,7 @@ static void gen_lea_modrm(DisasContext *s, int modrm, int *reg_ptr, int *offset_
         case 0:
             if ((base & 7) == 5) {
                 base = -1;
-                disp = (int32_t)ldl_code(s->pc);
+                disp = (int32_t)cpu_ldl_code(cpu_single_env, s->pc);
                 s->pc += 4;
                 if (CODE64(s) && !havesib) {
                     disp += s->pc + s->rip_offset;
@@ -2064,11 +2064,11 @@ static void gen_lea_modrm(DisasContext *s, int modrm, int *reg_ptr, int *offset_
             }
             break;
         case 1:
-            disp = (int8_t)ldub_code(s->pc++);
+            disp = (int8_t)cpu_ldub_code(cpu_single_env, s->pc++);
             break;
         default:
         case 2:
-            disp = (int32_t)ldl_code(s->pc);
+            disp = (int32_t)cpu_ldl_code(cpu_single_env, s->pc);
             s->pc += 4;
             break;
         }
@@ -2131,7 +2131,7 @@ static void gen_lea_modrm(DisasContext *s, int modrm, int *reg_ptr, int *offset_
         switch (mod) {
         case 0:
             if (rm == 6) {
-                disp = lduw_code(s->pc);
+                disp = cpu_lduw_code(cpu_single_env, s->pc);
                 s->pc += 2;
                 gen_op_movl_A0_im(disp);
                 rm = 0; /* avoid SS override */
@@ -2141,11 +2141,11 @@ static void gen_lea_modrm(DisasContext *s, int modrm, int *reg_ptr, int *offset_
             }
             break;
         case 1:
-            disp = (int8_t)ldub_code(s->pc++);
+            disp = (int8_t)cpu_ldub_code(cpu_single_env, s->pc++);
             break;
         default:
         case 2:
-            disp = lduw_code(s->pc);
+            disp = cpu_lduw_code(cpu_single_env, s->pc);
             s->pc += 2;
             break;
         }
@@ -2215,7 +2215,7 @@ static void gen_nop_modrm(DisasContext *s, int modrm)
         base = rm;
 
         if (base == 4) {
-            code = ldub_code(s->pc++);
+            code = cpu_ldub_code(cpu_single_env, s->pc++);
             base = (code & 7);
         }
 
@@ -2311,16 +2311,16 @@ static inline uint32_t insn_get(DisasContext *s, int ot)
 
     switch(ot) {
     case OT_BYTE:
-        ret = ldub_code(s->pc);
+        ret = cpu_ldub_code(cpu_single_env, s->pc);
         s->pc++;
         break;
     case OT_WORD:
-        ret = lduw_code(s->pc);
+        ret = cpu_lduw_code(cpu_single_env, s->pc);
         s->pc += 2;
         break;
     default:
     case OT_LONG:
-        ret = ldl_code(s->pc);
+        ret = cpu_ldl_code(cpu_single_env, s->pc);
         s->pc += 4;
         break;
     }
@@ -3229,7 +3229,7 @@ static void gen_sse(DisasContext *s, int b, target_ulong pc_start, int rex_r)
         gen_helper_enter_mmx(cpu_env);
     }
 
-    modrm = ldub_code(s->pc++);
+    modrm = cpu_ldub_code(cpu_single_env, s->pc++);
     reg = ((modrm >> 3) & 7);
     if (is_xmm)
         reg |= rex_r;
@@ -3433,8 +3433,8 @@ static void gen_sse(DisasContext *s, int b, target_ulong pc_start, int rex_r)
 
                 if (b1 == 1 && reg != 0)
                     goto illegal_op;
-                field_length = ldub_code(s->pc++) & 0x3F;
-                bit_index = ldub_code(s->pc++) & 0x3F;
+                field_length = cpu_ldub_code(cpu_single_env, s->pc++) & 0x3F;
+                bit_index = cpu_ldub_code(cpu_single_env, s->pc++) & 0x3F;
                 tcg_gen_addi_ptr(cpu_ptr0, cpu_env,
                     offsetof(CPUX86State,xmm_regs[reg]));
                 if (b1 == 1)
@@ -3559,7 +3559,7 @@ static void gen_sse(DisasContext *s, int b, target_ulong pc_start, int rex_r)
             if (b1 >= 2) {
 	        goto illegal_op;
             }
-            val = ldub_code(s->pc++);
+            val = cpu_ldub_code(cpu_single_env, s->pc++);
             if (is_xmm) {
                 gen_op_movl_T0_im(val);
                 tcg_gen_st32_tl(cpu_T[0], cpu_env, offsetof(CPUX86State,xmm_t0.XMM_L(0)));
@@ -3718,7 +3718,7 @@ static void gen_sse(DisasContext *s, int b, target_ulong pc_start, int rex_r)
         case 0x1c4:
             s->rip_offset = 1;
             gen_ldst_modrm(s, modrm, OT_WORD, OR_TMP0, 0);
-            val = ldub_code(s->pc++);
+            val = cpu_ldub_code(cpu_single_env, s->pc++);
             if (b1) {
                 val &= 7;
                 tcg_gen_st16_tl(cpu_T[0], cpu_env,
@@ -3734,7 +3734,7 @@ static void gen_sse(DisasContext *s, int b, target_ulong pc_start, int rex_r)
             if (mod != 3)
                 goto illegal_op;
             ot = (s->dflag == 2) ? OT_QUAD : OT_LONG;
-            val = ldub_code(s->pc++);
+            val = cpu_ldub_code(cpu_single_env, s->pc++);
             if (b1) {
                 val &= 7;
                 rm = (modrm & 7) | REX_B(s);
@@ -3795,7 +3795,7 @@ static void gen_sse(DisasContext *s, int b, target_ulong pc_start, int rex_r)
                 goto crc32;
         case 0x038:
             b = modrm;
-            modrm = ldub_code(s->pc++);
+            modrm = cpu_ldub_code(cpu_single_env, s->pc++);
             rm = modrm & 7;
             reg = ((modrm >> 3) & 7) | rex_r;
             mod = (modrm >> 6) & 3;
@@ -3869,7 +3869,7 @@ static void gen_sse(DisasContext *s, int b, target_ulong pc_start, int rex_r)
         case 0x338: /* crc32 */
         crc32:
             b = modrm;
-            modrm = ldub_code(s->pc++);
+            modrm = cpu_ldub_code(cpu_single_env, s->pc++);
             reg = ((modrm >> 3) & 7) | rex_r;
 
             if (b != 0xf0 && b != 0xf1)
@@ -3899,7 +3899,7 @@ static void gen_sse(DisasContext *s, int b, target_ulong pc_start, int rex_r)
         case 0x03a:
         case 0x13a:
             b = modrm;
-            modrm = ldub_code(s->pc++);
+            modrm = cpu_ldub_code(cpu_single_env, s->pc++);
             rm = modrm & 7;
             reg = ((modrm >> 3) & 7) | rex_r;
             mod = (modrm >> 6) & 3;
@@ -3920,7 +3920,7 @@ static void gen_sse(DisasContext *s, int b, target_ulong pc_start, int rex_r)
                 if (mod != 3)
                     gen_lea_modrm(s, modrm, &reg_addr, &offset_addr);
                 reg = ((modrm >> 3) & 7) | rex_r;
-                val = ldub_code(s->pc++);
+                val = cpu_ldub_code(cpu_single_env, s->pc++);
                 switch (b) {
                 case 0x14: /* pextrb */
                     tcg_gen_ld8u_tl(cpu_T[0], cpu_env, offsetof(CPUX86State,
@@ -4063,7 +4063,7 @@ static void gen_sse(DisasContext *s, int b, target_ulong pc_start, int rex_r)
                     gen_ldq_env_A0(s->mem_index, op2_offset);
                 }
             }
-            val = ldub_code(s->pc++);
+            val = cpu_ldub_code(cpu_single_env, s->pc++);
 
             if ((b & 0xfc) == 0x60) { /* pcmpXstrX */
                 s->cc_op = CC_OP_EFLAGS;
@@ -4129,7 +4129,7 @@ static void gen_sse(DisasContext *s, int b, target_ulong pc_start, int rex_r)
         case 0x0f: /* 3DNow! data insns */
             if (!(s->cpuid_ext2_features & CPUID_EXT2_3DNOW))
                 goto illegal_op;
-            val = ldub_code(s->pc++);
+            val = cpu_ldub_code(cpu_single_env, s->pc++);
             sse_fn_epp = sse_op_table5[val];
             if (!sse_fn_epp) {
                 goto illegal_op;
@@ -4140,7 +4140,7 @@ static void gen_sse(DisasContext *s, int b, target_ulong pc_start, int rex_r)
             break;
         case 0x70: /* pshufx insn */
         case 0xc6: /* pshufx insn */
-            val = ldub_code(s->pc++);
+            val = cpu_ldub_code(cpu_single_env, s->pc++);
             tcg_gen_addi_ptr(cpu_ptr0, cpu_env, op1_offset);
             tcg_gen_addi_ptr(cpu_ptr1, cpu_env, op2_offset);
             /* XXX: introduce a new table? */
@@ -4149,7 +4149,7 @@ static void gen_sse(DisasContext *s, int b, target_ulong pc_start, int rex_r)
             break;
         case 0xc2:
             /* compare insns */
-            val = ldub_code(s->pc++);
+            val = cpu_ldub_code(cpu_single_env, s->pc++);
             if (val >= 8)
                 goto illegal_op;
             sse_fn_epp = sse_op_table4[val][b1];
@@ -4218,7 +4218,7 @@ static target_ulong disas_insn(DisasContext *s, target_ulong pc_start)
 #endif
     s->rip_offset = 0; /* for relative ip address */
  next_byte:
-    b = ldub_code(s->pc);
+    b = cpu_ldub_code(cpu_single_env, s->pc);
     s->pc++;
     /* check prefixes */
 #ifdef TARGET_X86_64
@@ -4333,7 +4333,7 @@ static target_ulong disas_insn(DisasContext *s, target_ulong pc_start)
     case 0x0f:
         /**************************/
         /* extended op code */
-        b = ldub_code(s->pc++) | 0x100;
+        b = cpu_ldub_code(cpu_single_env, s->pc++) | 0x100;
         goto reswitch;
 
         /**************************/
@@ -4358,7 +4358,7 @@ static target_ulong disas_insn(DisasContext *s, target_ulong pc_start)
 
             switch(f) {
             case 0: /* OP Ev, Gv */
-                modrm = ldub_code(s->pc++);
+                modrm = cpu_ldub_code(cpu_single_env, s->pc++);
                 reg = ((modrm >> 3) & 7) | rex_r;
                 mod = (modrm >> 6) & 3;
                 rm = (modrm & 7) | REX_B(s);
@@ -4380,7 +4380,7 @@ static target_ulong disas_insn(DisasContext *s, target_ulong pc_start)
                 gen_op(s, op, ot, opreg);
                 break;
             case 1: /* OP Gv, Ev */
-                modrm = ldub_code(s->pc++);
+                modrm = cpu_ldub_code(cpu_single_env, s->pc++);
                 mod = (modrm >> 6) & 3;
                 reg = ((modrm >> 3) & 7) | rex_r;
                 rm = (modrm & 7) | REX_B(s);
@@ -4417,7 +4417,7 @@ static target_ulong disas_insn(DisasContext *s, target_ulong pc_start)
             else
                 ot = dflag + OT_WORD;
 
-            modrm = ldub_code(s->pc++);
+            modrm = cpu_ldub_code(cpu_single_env, s->pc++);
             mod = (modrm >> 6) & 3;
             rm = (modrm & 7) | REX_B(s);
             op = (modrm >> 3) & 7;
@@ -4466,7 +4466,7 @@ static target_ulong disas_insn(DisasContext *s, target_ulong pc_start)
         else
             ot = dflag + OT_WORD;
 
-        modrm = ldub_code(s->pc++);
+        modrm = cpu_ldub_code(cpu_single_env, s->pc++);
         mod = (modrm >> 6) & 3;
         rm = (modrm & 7) | REX_B(s);
         op = (modrm >> 3) & 7;
@@ -4698,7 +4698,7 @@ static target_ulong disas_insn(DisasContext *s, target_ulong pc_start)
         else
             ot = dflag + OT_WORD;
 
-        modrm = ldub_code(s->pc++);
+        modrm = cpu_ldub_code(cpu_single_env, s->pc++);
         mod = (modrm >> 6) & 3;
         rm = (modrm & 7) | REX_B(s);
         op = (modrm >> 3) & 7;
@@ -4810,7 +4810,7 @@ static target_ulong disas_insn(DisasContext *s, target_ulong pc_start)
         else
             ot = dflag + OT_WORD;
 
-        modrm = ldub_code(s->pc++);
+        modrm = cpu_ldub_code(cpu_single_env, s->pc++);
         reg = ((modrm >> 3) & 7) | rex_r;
 
         gen_ldst_modrm(s, modrm, ot, OR_TMP0, 0);
@@ -4875,7 +4875,7 @@ static target_ulong disas_insn(DisasContext *s, target_ulong pc_start)
     case 0x69: /* imul Gv, Ev, I */
     case 0x6b:
         ot = dflag + OT_WORD;
-        modrm = ldub_code(s->pc++);
+        modrm = cpu_ldub_code(cpu_single_env, s->pc++);
         reg = ((modrm >> 3) & 7) | rex_r;
         if (b == 0x69)
             s->rip_offset = insn_const_size(ot);
@@ -4939,7 +4939,7 @@ static target_ulong disas_insn(DisasContext *s, target_ulong pc_start)
             ot = OT_BYTE;
         else
             ot = dflag + OT_WORD;
-        modrm = ldub_code(s->pc++);
+        modrm = cpu_ldub_code(cpu_single_env, s->pc++);
         reg = ((modrm >> 3) & 7) | rex_r;
         mod = (modrm >> 6) & 3;
         if (mod == 3) {
@@ -4970,7 +4970,7 @@ static target_ulong disas_insn(DisasContext *s, target_ulong pc_start)
                 ot = OT_BYTE;
             else
                 ot = dflag + OT_WORD;
-            modrm = ldub_code(s->pc++);
+            modrm = cpu_ldub_code(cpu_single_env, s->pc++);
             reg = ((modrm >> 3) & 7) | rex_r;
             mod = (modrm >> 6) & 3;
             t0 = tcg_temp_local_new();
@@ -5018,7 +5018,7 @@ static target_ulong disas_insn(DisasContext *s, target_ulong pc_start)
         }
         break;
     case 0x1c7: /* cmpxchg8b */
-        modrm = ldub_code(s->pc++);
+        modrm = cpu_ldub_code(cpu_single_env, s->pc++);
         mod = (modrm >> 6) & 3;
         if ((mod == 3) || ((modrm & 0x38) != 0x8))
             goto illegal_op;
@@ -5030,7 +5030,7 @@ static target_ulong disas_insn(DisasContext *s, target_ulong pc_start)
             if (s->cc_op != CC_OP_DYNAMIC)
                 gen_op_set_cc_op(s->cc_op);
             gen_lea_modrm(s, modrm, &reg_addr, &offset_addr);
-            gen_helper_cmpxchg16b(cpu_A0);
+            gen_helper_cmpxchg16b(cpu_env, cpu_A0);
         } else
 #endif        
         {
@@ -5040,7 +5040,7 @@ static target_ulong disas_insn(DisasContext *s, target_ulong pc_start)
             if (s->cc_op != CC_OP_DYNAMIC)
                 gen_op_set_cc_op(s->cc_op);
             gen_lea_modrm(s, modrm, &reg_addr, &offset_addr);
-            gen_helper_cmpxchg8b(cpu_A0);
+            gen_helper_cmpxchg8b(cpu_env, cpu_A0);
         }
         s->cc_op = CC_OP_EFLAGS;
         break;
@@ -5092,7 +5092,7 @@ static target_ulong disas_insn(DisasContext *s, target_ulong pc_start)
         } else {
             ot = dflag + OT_WORD;
         }
-        modrm = ldub_code(s->pc++);
+        modrm = cpu_ldub_code(cpu_single_env, s->pc++);
         mod = (modrm >> 6) & 3;
         gen_pop_T0(s);
         if (mod == 3) {
@@ -5111,9 +5111,9 @@ static target_ulong disas_insn(DisasContext *s, target_ulong pc_start)
     case 0xc8: /* enter */
         {
             int level;
-            val = lduw_code(s->pc);
+            val = cpu_lduw_code(cpu_single_env, s->pc);
             s->pc += 2;
-            level = ldub_code(s->pc++);
+            level = cpu_ldub_code(cpu_single_env, s->pc++);
             gen_enter(s, val, level);
         }
         break;
@@ -5193,7 +5193,7 @@ static target_ulong disas_insn(DisasContext *s, target_ulong pc_start)
             ot = OT_BYTE;
         else
             ot = dflag + OT_WORD;
-        modrm = ldub_code(s->pc++);
+        modrm = cpu_ldub_code(cpu_single_env, s->pc++);
         reg = ((modrm >> 3) & 7) | rex_r;
 
         /* generate a generic store */
@@ -5205,7 +5205,7 @@ static target_ulong disas_insn(DisasContext *s, target_ulong pc_start)
             ot = OT_BYTE;
         else
             ot = dflag + OT_WORD;
-        modrm = ldub_code(s->pc++);
+        modrm = cpu_ldub_code(cpu_single_env, s->pc++);
         mod = (modrm >> 6) & 3;
         if (mod != 3) {
             s->rip_offset = insn_const_size(ot);
@@ -5224,14 +5224,14 @@ static target_ulong disas_insn(DisasContext *s, target_ulong pc_start)
             ot = OT_BYTE;
         else
             ot = OT_WORD + dflag;
-        modrm = ldub_code(s->pc++);
+        modrm = cpu_ldub_code(cpu_single_env, s->pc++);
         reg = ((modrm >> 3) & 7) | rex_r;
 
         gen_ldst_modrm(s, modrm, ot, OR_TMP0, 0);
         gen_op_mov_reg_T0(ot, reg);
         break;
     case 0x8e: /* mov seg, Gv */
-        modrm = ldub_code(s->pc++);
+        modrm = cpu_ldub_code(cpu_single_env, s->pc++);
         reg = (modrm >> 3) & 7;
         if (reg >= 6 || reg == R_CS)
             goto illegal_op;
@@ -5251,7 +5251,7 @@ static target_ulong disas_insn(DisasContext *s, target_ulong pc_start)
         }
         break;
     case 0x8c: /* mov Gv, seg */
-        modrm = ldub_code(s->pc++);
+        modrm = cpu_ldub_code(cpu_single_env, s->pc++);
         reg = (modrm >> 3) & 7;
         mod = (modrm >> 6) & 3;
         if (reg >= 6)
@@ -5274,7 +5274,7 @@ static target_ulong disas_insn(DisasContext *s, target_ulong pc_start)
             d_ot = dflag + OT_WORD;
             /* ot is the size of source */
             ot = (b & 1) + OT_BYTE;
-            modrm = ldub_code(s->pc++);
+            modrm = cpu_ldub_code(cpu_single_env, s->pc++);
             reg = ((modrm >> 3) & 7) | rex_r;
             mod = (modrm >> 6) & 3;
             rm = (modrm & 7) | REX_B(s);
@@ -5311,7 +5311,7 @@ static target_ulong disas_insn(DisasContext *s, target_ulong pc_start)
 
     case 0x8d: /* lea */
         ot = dflag + OT_WORD;
-        modrm = ldub_code(s->pc++);
+        modrm = cpu_ldub_code(cpu_single_env, s->pc++);
         mod = (modrm >> 6) & 3;
         if (mod == 3)
             goto illegal_op;
@@ -5338,7 +5338,7 @@ static target_ulong disas_insn(DisasContext *s, target_ulong pc_start)
                 ot = dflag + OT_WORD;
 #ifdef TARGET_X86_64
             if (s->aflag == 2) {
-                offset_addr = ldq_code(s->pc);
+                offset_addr = cpu_ldq_code(cpu_single_env, s->pc);
                 s->pc += 8;
                 gen_op_movq_A0_im(offset_addr);
             } else
@@ -5394,7 +5394,7 @@ static target_ulong disas_insn(DisasContext *s, target_ulong pc_start)
         if (dflag == 2) {
             uint64_t tmp;
             /* 64 bit case */
-            tmp = ldq_code(s->pc);
+            tmp = cpu_ldq_code(cpu_single_env, s->pc);
             s->pc += 8;
             reg = (b & 7) | REX_B(s);
             gen_movtl_T0_im(tmp);
@@ -5422,7 +5422,7 @@ static target_ulong disas_insn(DisasContext *s, target_ulong pc_start)
             ot = OT_BYTE;
         else
             ot = dflag + OT_WORD;
-        modrm = ldub_code(s->pc++);
+        modrm = cpu_ldub_code(cpu_single_env, s->pc++);
         reg = ((modrm >> 3) & 7) | rex_r;
         mod = (modrm >> 6) & 3;
         if (mod == 3) {
@@ -5465,7 +5465,7 @@ static target_ulong disas_insn(DisasContext *s, target_ulong pc_start)
         op = R_GS;
     do_lxx:
         ot = dflag ? OT_LONG : OT_WORD;
-        modrm = ldub_code(s->pc++);
+        modrm = cpu_ldub_code(cpu_single_env, s->pc++);
         reg = ((modrm >> 3) & 7) | rex_r;
         mod = (modrm >> 6) & 3;
         if (mod == 3)
@@ -5497,7 +5497,7 @@ static target_ulong disas_insn(DisasContext *s, target_ulong pc_start)
             else
                 ot = dflag + OT_WORD;
 
-            modrm = ldub_code(s->pc++);
+            modrm = cpu_ldub_code(cpu_single_env, s->pc++);
             mod = (modrm >> 6) & 3;
             op = (modrm >> 3) & 7;
 
@@ -5516,7 +5516,7 @@ static target_ulong disas_insn(DisasContext *s, target_ulong pc_start)
                 gen_shift(s, op, ot, opreg, OR_ECX);
             } else {
                 if (shift == 2) {
-                    shift = ldub_code(s->pc++);
+                    shift = cpu_ldub_code(cpu_single_env, s->pc++);
                 }
                 gen_shifti(s, op, ot, opreg, shift);
             }
@@ -5550,7 +5550,7 @@ static target_ulong disas_insn(DisasContext *s, target_ulong pc_start)
         shift = 0;
     do_shiftd:
         ot = dflag + OT_WORD;
-        modrm = ldub_code(s->pc++);
+        modrm = cpu_ldub_code(cpu_single_env, s->pc++);
         mod = (modrm >> 6) & 3;
         rm = (modrm & 7) | REX_B(s);
         reg = ((modrm >> 3) & 7) | rex_r;
@@ -5563,7 +5563,7 @@ static target_ulong disas_insn(DisasContext *s, target_ulong pc_start)
         gen_op_mov_TN_reg(ot, 1, reg);
 
         if (shift) {
-            val = ldub_code(s->pc++);
+            val = cpu_ldub_code(cpu_single_env, s->pc++);
             tcg_gen_movi_tl(cpu_T3, val);
         } else {
             tcg_gen_mov_tl(cpu_T3, cpu_regs[R_ECX]);
@@ -5580,7 +5580,7 @@ static target_ulong disas_insn(DisasContext *s, target_ulong pc_start)
             gen_exception(s, EXCP07_PREX, pc_start - s->cs_base);
             break;
         }
-        modrm = ldub_code(s->pc++);
+        modrm = cpu_ldub_code(cpu_single_env, s->pc++);
         mod = (modrm >> 6) & 3;
         rm = modrm & 7;
         op = ((b & 7) << 3) | ((modrm >> 3) & 7);
@@ -6211,7 +6211,7 @@ static target_ulong disas_insn(DisasContext *s, target_ulong pc_start)
             ot = OT_BYTE;
         else
             ot = dflag ? OT_LONG : OT_WORD;
-        val = ldub_code(s->pc++);
+        val = cpu_ldub_code(cpu_single_env, s->pc++);
         gen_op_movl_T0_im(val);
         gen_check_io(s, ot, pc_start - s->cs_base,
                      SVM_IOIO_TYPE_MASK | svm_is_rep(prefixes));
@@ -6231,7 +6231,7 @@ static target_ulong disas_insn(DisasContext *s, target_ulong pc_start)
             ot = OT_BYTE;
         else
             ot = dflag ? OT_LONG : OT_WORD;
-        val = ldub_code(s->pc++);
+        val = cpu_ldub_code(cpu_single_env, s->pc++);
         gen_op_movl_T0_im(val);
         gen_check_io(s, ot, pc_start - s->cs_base,
                      svm_is_rep(prefixes));
@@ -6293,7 +6293,7 @@ static target_ulong disas_insn(DisasContext *s, target_ulong pc_start)
         /************************/
         /* control */
     case 0xc2: /* ret im */
-        val = ldsw_code(s->pc);
+        val = cpu_ldsw_code(cpu_single_env, s->pc);
         s->pc += 2;
         gen_pop_T0(s);
         if (CODE64(s) && s->dflag)
@@ -6313,7 +6313,7 @@ static target_ulong disas_insn(DisasContext *s, target_ulong pc_start)
         gen_eob(s);
         break;
     case 0xca: /* lret im */
-        val = ldsw_code(s->pc);
+        val = cpu_ldsw_code(cpu_single_env, s->pc);
         s->pc += 2;
     do_lret:
         if (s->pe && !s->vm86) {
@@ -6448,7 +6448,7 @@ static target_ulong disas_insn(DisasContext *s, target_ulong pc_start)
         break;
 
     case 0x190 ... 0x19f: /* setcc Gv */
-        modrm = ldub_code(s->pc++);
+        modrm = cpu_ldub_code(cpu_single_env, s->pc++);
         gen_setcc(s, b);
         gen_ldst_modrm(s, modrm, OT_BYTE, OR_TMP0, 1);
         break;
@@ -6458,7 +6458,7 @@ static target_ulong disas_insn(DisasContext *s, target_ulong pc_start)
             TCGv t0;
 
             ot = dflag + OT_WORD;
-            modrm = ldub_code(s->pc++);
+            modrm = cpu_ldub_code(cpu_single_env, s->pc++);
             reg = ((modrm >> 3) & 7) | rex_r;
             mod = (modrm >> 6) & 3;
             t0 = tcg_temp_local_new();
@@ -6616,7 +6616,7 @@ static target_ulong disas_insn(DisasContext *s, target_ulong pc_start)
         /* bit operations */
     case 0x1ba: /* bt/bts/btr/btc Gv, im */
         ot = dflag + OT_WORD;
-        modrm = ldub_code(s->pc++);
+        modrm = cpu_ldub_code(cpu_single_env, s->pc++);
         op = (modrm >> 3) & 7;
         mod = (modrm >> 6) & 3;
         rm = (modrm & 7) | REX_B(s);
@@ -6628,7 +6628,7 @@ static target_ulong disas_insn(DisasContext *s, target_ulong pc_start)
             gen_op_mov_TN_reg(ot, 0, rm);
         }
         /* load shift */
-        val = ldub_code(s->pc++);
+        val = cpu_ldub_code(cpu_single_env, s->pc++);
         gen_op_movl_T1_im(val);
         if (op < 4)
             goto illegal_op;
@@ -6647,7 +6647,7 @@ static target_ulong disas_insn(DisasContext *s, target_ulong pc_start)
         op = 3;
     do_btx:
         ot = dflag + OT_WORD;
-        modrm = ldub_code(s->pc++);
+        modrm = cpu_ldub_code(cpu_single_env, s->pc++);
         reg = ((modrm >> 3) & 7) | rex_r;
         mod = (modrm >> 6) & 3;
         rm = (modrm & 7) | REX_B(s);
@@ -6708,7 +6708,7 @@ static target_ulong disas_insn(DisasContext *s, target_ulong pc_start)
             TCGv t0;
 
             ot = dflag + OT_WORD;
-            modrm = ldub_code(s->pc++);
+            modrm = cpu_ldub_code(cpu_single_env, s->pc++);
             reg = ((modrm >> 3) & 7) | rex_r;
             gen_ldst_modrm(s,modrm, ot, OR_TMP0, 0);
             gen_extu(ot, cpu_T[0]);
@@ -6780,7 +6780,7 @@ static target_ulong disas_insn(DisasContext *s, target_ulong pc_start)
     case 0xd4: /* aam */
         if (CODE64(s))
             goto illegal_op;
-        val = ldub_code(s->pc++);
+        val = cpu_ldub_code(cpu_single_env, s->pc++);
         if (val == 0) {
             gen_exception(s, EXCP00_DIVZ, pc_start - s->cs_base);
         } else {
@@ -6791,7 +6791,7 @@ static target_ulong disas_insn(DisasContext *s, target_ulong pc_start)
     case 0xd5: /* aad */
         if (CODE64(s))
             goto illegal_op;
-        val = ldub_code(s->pc++);
+        val = cpu_ldub_code(cpu_single_env, s->pc++);
         gen_helper_aad(cpu_env, tcg_const_i32(val));
         s->cc_op = CC_OP_LOGICB;
         break;
@@ -6825,7 +6825,7 @@ static target_ulong disas_insn(DisasContext *s, target_ulong pc_start)
         gen_interrupt(s, EXCP03_INT3, pc_start - s->cs_base, s->pc - s->cs_base);
         break;
     case 0xcd: /* int N */
-        val = ldub_code(s->pc++);
+        val = cpu_ldub_code(cpu_single_env, s->pc++);
         if (s->vm86 && s->iopl != 3) {
             gen_exception(s, EXCP0D_GPF, pc_start - s->cs_base);
         } else {
@@ -6895,7 +6895,7 @@ static target_ulong disas_insn(DisasContext *s, target_ulong pc_start)
         if (CODE64(s))
             goto illegal_op;
         ot = dflag ? OT_LONG : OT_WORD;
-        modrm = ldub_code(s->pc++);
+        modrm = cpu_ldub_code(cpu_single_env, s->pc++);
         reg = (modrm >> 3) & 7;
         mod = (modrm >> 6) & 3;
         if (mod == 3)
@@ -6904,10 +6904,11 @@ static target_ulong disas_insn(DisasContext *s, target_ulong pc_start)
         gen_lea_modrm(s, modrm, &reg_addr, &offset_addr);
         gen_jmp_im(pc_start - s->cs_base);
         tcg_gen_trunc_tl_i32(cpu_tmp2_i32, cpu_T[0]);
-        if (ot == OT_WORD)
-            gen_helper_boundw(cpu_A0, cpu_tmp2_i32);
-        else
-            gen_helper_boundl(cpu_A0, cpu_tmp2_i32);
+        if (ot == OT_WORD) {
+            gen_helper_boundw(cpu_env, cpu_A0, cpu_tmp2_i32);
+        } else {
+            gen_helper_boundl(cpu_env, cpu_A0, cpu_tmp2_i32);
+        }
         break;
     case 0x1c8 ... 0x1cf: /* bswap reg */
         reg = (b & 7) | REX_B(s);
@@ -7085,7 +7086,7 @@ static target_ulong disas_insn(DisasContext *s, target_ulong pc_start)
         }
         break;
     case 0x100:
-        modrm = ldub_code(s->pc++);
+        modrm = cpu_ldub_code(cpu_single_env, s->pc++);
         mod = (modrm >> 6) & 3;
         op = (modrm >> 3) & 7;
         switch(op) {
@@ -7154,7 +7155,7 @@ static target_ulong disas_insn(DisasContext *s, target_ulong pc_start)
         }
         break;
     case 0x101:
-        modrm = ldub_code(s->pc++);
+        modrm = cpu_ldub_code(cpu_single_env, s->pc++);
         mod = (modrm >> 6) & 3;
         op = (modrm >> 3) & 7;
         rm = modrm & 7;
@@ -7421,7 +7422,7 @@ static target_ulong disas_insn(DisasContext *s, target_ulong pc_start)
             /* d_ot is the size of destination */
             d_ot = dflag + OT_WORD;
 
-            modrm = ldub_code(s->pc++);
+            modrm = cpu_ldub_code(cpu_single_env, s->pc++);
             reg = ((modrm >> 3) & 7) | rex_r;
             mod = (modrm >> 6) & 3;
             rm = (modrm & 7) | REX_B(s);
@@ -7453,7 +7454,7 @@ static target_ulong disas_insn(DisasContext *s, target_ulong pc_start)
             t1 = tcg_temp_local_new();
             t2 = tcg_temp_local_new();
             ot = OT_WORD;
-            modrm = ldub_code(s->pc++);
+            modrm = cpu_ldub_code(cpu_single_env, s->pc++);
             reg = (modrm >> 3) & 7;
             mod = (modrm >> 6) & 3;
             rm = modrm & 7;
@@ -7501,7 +7502,7 @@ static target_ulong disas_insn(DisasContext *s, target_ulong pc_start)
             if (!s->pe || s->vm86)
                 goto illegal_op;
             ot = dflag ? OT_LONG : OT_WORD;
-            modrm = ldub_code(s->pc++);
+            modrm = cpu_ldub_code(cpu_single_env, s->pc++);
             reg = ((modrm >> 3) & 7) | rex_r;
             gen_ldst_modrm(s, modrm, OT_WORD, OR_TMP0, 0);
             t0 = tcg_temp_local_new();
@@ -7522,7 +7523,7 @@ static target_ulong disas_insn(DisasContext *s, target_ulong pc_start)
         }
         break;
     case 0x118:
-        modrm = ldub_code(s->pc++);
+        modrm = cpu_ldub_code(cpu_single_env, s->pc++);
         mod = (modrm >> 6) & 3;
         op = (modrm >> 3) & 7;
         switch(op) {
@@ -7541,7 +7542,7 @@ static target_ulong disas_insn(DisasContext *s, target_ulong pc_start)
         }
         break;
     case 0x119 ... 0x11f: /* nop (multi byte) */
-        modrm = ldub_code(s->pc++);
+        modrm = cpu_ldub_code(cpu_single_env, s->pc++);
         gen_nop_modrm(s, modrm);
         break;
     case 0x120: /* mov reg, crN */
@@ -7549,7 +7550,7 @@ static target_ulong disas_insn(DisasContext *s, target_ulong pc_start)
         if (s->cpl != 0) {
             gen_exception(s, EXCP0D_GPF, pc_start - s->cs_base);
         } else {
-            modrm = ldub_code(s->pc++);
+            modrm = cpu_ldub_code(cpu_single_env, s->pc++);
             if ((modrm & 0xc0) != 0xc0)
                 goto illegal_op;
             rm = (modrm & 7) | REX_B(s);
@@ -7592,7 +7593,7 @@ static target_ulong disas_insn(DisasContext *s, target_ulong pc_start)
         if (s->cpl != 0) {
             gen_exception(s, EXCP0D_GPF, pc_start - s->cs_base);
         } else {
-            modrm = ldub_code(s->pc++);
+            modrm = cpu_ldub_code(cpu_single_env, s->pc++);
             if ((modrm & 0xc0) != 0xc0)
                 goto illegal_op;
             rm = (modrm & 7) | REX_B(s);
@@ -7633,7 +7634,7 @@ static target_ulong disas_insn(DisasContext *s, target_ulong pc_start)
         if (!(s->cpuid_features & CPUID_SSE2))
             goto illegal_op;
         ot = s->dflag == 2 ? OT_QUAD : OT_LONG;
-        modrm = ldub_code(s->pc++);
+        modrm = cpu_ldub_code(cpu_single_env, s->pc++);
         mod = (modrm >> 6) & 3;
         if (mod == 3)
             goto illegal_op;
@@ -7642,7 +7643,7 @@ static target_ulong disas_insn(DisasContext *s, target_ulong pc_start)
         gen_ldst_modrm(s, modrm, ot, reg, 1);
         break;
     case 0x1ae:
-        modrm = ldub_code(s->pc++);
+        modrm = cpu_ldub_code(cpu_single_env, s->pc++);
         mod = (modrm >> 6) & 3;
         op = (modrm >> 3) & 7;
         switch(op) {
@@ -7717,7 +7718,7 @@ static target_ulong disas_insn(DisasContext *s, target_ulong pc_start)
         }
         break;
     case 0x10d: /* 3DNow! prefetch(w) */
-        modrm = ldub_code(s->pc++);
+        modrm = cpu_ldub_code(cpu_single_env, s->pc++);
         mod = (modrm >> 6) & 3;
         if (mod == 3)
             goto illegal_op;
@@ -7740,7 +7741,7 @@ static target_ulong disas_insn(DisasContext *s, target_ulong pc_start)
         if (!(s->cpuid_ext_features & CPUID_EXT_POPCNT))
             goto illegal_op;
 
-        modrm = ldub_code(s->pc++);
+        modrm = cpu_ldub_code(cpu_single_env, s->pc++);
         reg = ((modrm >> 3) & 7);
 
         if (s->prefix & PREFIX_DATA)
commit 2999a0b20074a7e4a58f56572bb1436749368f59
Author: Blue Swirl <blauwirbel at gmail.com>
Date:   Sun Apr 29 19:47:06 2012 +0000

    x86: avoid AREG0 in segmentation helpers
    
    Add an explicit CPUX86State parameter instead of relying on AREG0.
    
    Rename remains of op_helper.c to seg_helper.c.
    
    Signed-off-by: Blue Swirl <blauwirbel at gmail.com>

diff --git a/target-i386/Makefile.objs b/target-i386/Makefile.objs
index 13a7f6a..71d7d3b 100644
--- a/target-i386/Makefile.objs
+++ b/target-i386/Makefile.objs
@@ -8,4 +8,3 @@ obj-$(CONFIG_LINUX_USER) += ioport-user.o
 obj-$(CONFIG_BSD_USER) += ioport-user.o
 
 $(obj)/mem_helper.o: QEMU_CFLAGS += $(HELPER_CFLAGS)
-$(obj)/seg_helper.o: QEMU_CFLAGS += $(HELPER_CFLAGS)
diff --git a/target-i386/helper.h b/target-i386/helper.h
index 9a9c064..0f02103 100644
--- a/target-i386/helper.h
+++ b/target-i386/helper.h
@@ -28,19 +28,19 @@ DEF_HELPER_1(aas, void, env)
 DEF_HELPER_1(daa, void, env)
 DEF_HELPER_1(das, void, env)
 
-DEF_HELPER_1(lsl, tl, tl)
-DEF_HELPER_1(lar, tl, tl)
-DEF_HELPER_1(verr, void, tl)
-DEF_HELPER_1(verw, void, tl)
-DEF_HELPER_1(lldt, void, int)
-DEF_HELPER_1(ltr, void, int)
-DEF_HELPER_2(load_seg, void, int, int)
-DEF_HELPER_3(ljmp_protected, void, int, tl, int)
-DEF_HELPER_4(lcall_real, void, int, tl, int, int)
-DEF_HELPER_4(lcall_protected, void, int, tl, int, int)
-DEF_HELPER_1(iret_real, void, int)
-DEF_HELPER_2(iret_protected, void, int, int)
-DEF_HELPER_2(lret_protected, void, int, int)
+DEF_HELPER_2(lsl, tl, env, tl)
+DEF_HELPER_2(lar, tl, env, tl)
+DEF_HELPER_2(verr, void, env, tl)
+DEF_HELPER_2(verw, void, env, tl)
+DEF_HELPER_2(lldt, void, env, int)
+DEF_HELPER_2(ltr, void, env, int)
+DEF_HELPER_3(load_seg, void, env, int, int)
+DEF_HELPER_4(ljmp_protected, void, env, int, tl, int)
+DEF_HELPER_5(lcall_real, void, env, int, tl, int, int)
+DEF_HELPER_5(lcall_protected, void, env, int, tl, int, int)
+DEF_HELPER_2(iret_real, void, env, int)
+DEF_HELPER_3(iret_protected, void, env, int, int)
+DEF_HELPER_3(lret_protected, void, env, int, int)
 DEF_HELPER_2(read_crN, tl, env, int)
 DEF_HELPER_3(write_crN, void, env, int, tl)
 DEF_HELPER_2(lmsw, void, env, tl)
@@ -48,15 +48,15 @@ DEF_HELPER_1(clts, void, env)
 DEF_HELPER_3(movl_drN_T0, void, env, int, tl)
 DEF_HELPER_2(invlpg, void, env, tl)
 
-DEF_HELPER_3(enter_level, void, int, int, tl)
+DEF_HELPER_4(enter_level, void, env, int, int, tl)
 #ifdef TARGET_X86_64
-DEF_HELPER_3(enter64_level, void, int, int, tl)
+DEF_HELPER_4(enter64_level, void, env, int, int, tl)
 #endif
-DEF_HELPER_0(sysenter, void)
-DEF_HELPER_1(sysexit, void, int)
+DEF_HELPER_1(sysenter, void, env)
+DEF_HELPER_2(sysexit, void, env, int)
 #ifdef TARGET_X86_64
-DEF_HELPER_1(syscall, void, int)
-DEF_HELPER_1(sysret, void, int)
+DEF_HELPER_2(syscall, void, env, int)
+DEF_HELPER_2(sysret, void, env, int)
 #endif
 DEF_HELPER_2(hlt, void, env, int)
 DEF_HELPER_2(monitor, void, env, tl)
diff --git a/target-i386/seg_helper.c b/target-i386/seg_helper.c
index f5dcf01..f136128 100644
--- a/target-i386/seg_helper.c
+++ b/target-i386/seg_helper.c
@@ -19,7 +19,6 @@
  */
 
 #include "cpu.h"
-#include "dyngen-exec.h"
 #include "qemu-log.h"
 #include "helper.h"
 
@@ -35,8 +34,8 @@
 #endif
 
 /* return non zero if error */
-static inline int load_segment(uint32_t *e1_ptr, uint32_t *e2_ptr,
-                               int selector)
+static inline int load_segment(CPUX86State *env, uint32_t *e1_ptr,
+                               uint32_t *e2_ptr, int selector)
 {
     SegmentCache *dt;
     int index;
@@ -82,14 +81,14 @@ static inline void load_seg_cache_raw_dt(SegmentCache *sc, uint32_t e1,
 }
 
 /* init the segment cache in vm86 mode. */
-static inline void load_seg_vm(int seg, int selector)
+static inline void load_seg_vm(CPUX86State *env, int seg, int selector)
 {
     selector &= 0xffff;
     cpu_x86_load_seg_cache(env, seg, selector,
                            (selector << 4), 0xffff, 0);
 }
 
-static inline void get_ss_esp_from_tss(uint32_t *ss_ptr,
+static inline void get_ss_esp_from_tss(CPUX86State *env, uint32_t *ss_ptr,
                                        uint32_t *esp_ptr, int dpl)
 {
     int type, index, shift;
@@ -130,13 +129,13 @@ static inline void get_ss_esp_from_tss(uint32_t *ss_ptr,
 }
 
 /* XXX: merge with load_seg() */
-static void tss_load_seg(int seg_reg, int selector)
+static void tss_load_seg(CPUX86State *env, int seg_reg, int selector)
 {
     uint32_t e1, e2;
     int rpl, dpl, cpl;
 
     if ((selector & 0xfffc) != 0) {
-        if (load_segment(&e1, &e2, selector) != 0) {
+        if (load_segment(env, &e1, &e2, selector) != 0) {
             raise_exception_err(env, EXCP0A_TSS, selector & 0xfffc);
         }
         if (!(e2 & DESC_S_MASK)) {
@@ -195,7 +194,7 @@ static void tss_load_seg(int seg_reg, int selector)
 #define SWITCH_TSS_CALL 2
 
 /* XXX: restore CPU state in registers (PowerPC case) */
-static void switch_tss(int tss_selector,
+static void switch_tss(CPUX86State *env, int tss_selector,
                        uint32_t e1, uint32_t e2, int source,
                        uint32_t next_eip)
 {
@@ -221,7 +220,7 @@ static void switch_tss(int tss_selector,
         if (tss_selector & 4) {
             raise_exception_err(env, EXCP0A_TSS, tss_selector & 0xfffc);
         }
-        if (load_segment(&e1, &e2, tss_selector) != 0) {
+        if (load_segment(env, &e1, &e2, tss_selector) != 0) {
             raise_exception_err(env, EXCP0D_GPF, tss_selector & 0xfffc);
         }
         if (e2 & DESC_S_MASK) {
@@ -403,7 +402,7 @@ static void switch_tss(int tss_selector,
     EDI = new_regs[7];
     if (new_eflags & VM_MASK) {
         for (i = 0; i < 6; i++) {
-            load_seg_vm(i, new_segs[i]);
+            load_seg_vm(env, i, new_segs[i]);
         }
         /* in vm86, CPL is always 3 */
         cpu_x86_set_cpl(env, 3);
@@ -446,12 +445,12 @@ static void switch_tss(int tss_selector,
 
     /* load the segments */
     if (!(new_eflags & VM_MASK)) {
-        tss_load_seg(R_CS, new_segs[R_CS]);
-        tss_load_seg(R_SS, new_segs[R_SS]);
-        tss_load_seg(R_ES, new_segs[R_ES]);
-        tss_load_seg(R_DS, new_segs[R_DS]);
-        tss_load_seg(R_FS, new_segs[R_FS]);
-        tss_load_seg(R_GS, new_segs[R_GS]);
+        tss_load_seg(env, R_CS, new_segs[R_CS]);
+        tss_load_seg(env, R_SS, new_segs[R_SS]);
+        tss_load_seg(env, R_ES, new_segs[R_ES]);
+        tss_load_seg(env, R_DS, new_segs[R_DS]);
+        tss_load_seg(env, R_FS, new_segs[R_FS]);
+        tss_load_seg(env, R_GS, new_segs[R_GS]);
     }
 
     /* check that EIP is in the CS segment limits */
@@ -545,8 +544,9 @@ static int exception_has_error_code(int intno)
     }
 
 /* protected mode interrupt */
-static void do_interrupt_protected(int intno, int is_int, int error_code,
-                                   unsigned int next_eip, int is_hw)
+static void do_interrupt_protected(CPUX86State *env, int intno, int is_int,
+                                   int error_code, unsigned int next_eip,
+                                   int is_hw)
 {
     SegmentCache *dt;
     target_ulong ptr, ssp;
@@ -580,7 +580,7 @@ static void do_interrupt_protected(int intno, int is_int, int error_code,
         if (!(e2 & DESC_P_MASK)) {
             raise_exception_err(env, EXCP0B_NOSEG, intno * 8 + 2);
         }
-        switch_tss(intno * 8, e1, e2, SWITCH_TSS_CALL, old_eip);
+        switch_tss(env, intno * 8, e1, e2, SWITCH_TSS_CALL, old_eip);
         if (has_error_code) {
             int type;
             uint32_t mask;
@@ -627,7 +627,7 @@ static void do_interrupt_protected(int intno, int is_int, int error_code,
     if ((selector & 0xfffc) == 0) {
         raise_exception_err(env, EXCP0D_GPF, 0);
     }
-    if (load_segment(&e1, &e2, selector) != 0) {
+    if (load_segment(env, &e1, &e2, selector) != 0) {
         raise_exception_err(env, EXCP0D_GPF, selector & 0xfffc);
     }
     if (!(e2 & DESC_S_MASK) || !(e2 & (DESC_CS_MASK))) {
@@ -642,14 +642,14 @@ static void do_interrupt_protected(int intno, int is_int, int error_code,
     }
     if (!(e2 & DESC_C_MASK) && dpl < cpl) {
         /* to inner privilege */
-        get_ss_esp_from_tss(&ss, &esp, dpl);
+        get_ss_esp_from_tss(env, &ss, &esp, dpl);
         if ((ss & 0xfffc) == 0) {
             raise_exception_err(env, EXCP0A_TSS, ss & 0xfffc);
         }
         if ((ss & 3) != dpl) {
             raise_exception_err(env, EXCP0A_TSS, ss & 0xfffc);
         }
-        if (load_segment(&ss_e1, &ss_e2, ss) != 0) {
+        if (load_segment(env, &ss_e1, &ss_e2, ss) != 0) {
             raise_exception_err(env, EXCP0A_TSS, ss & 0xfffc);
         }
         ss_dpl = (ss_e2 >> DESC_DPL_SHIFT) & 3;
@@ -773,7 +773,7 @@ static void do_interrupt_protected(int intno, int is_int, int error_code,
         sp += 8;                                \
     }
 
-static inline target_ulong get_rsp_from_tss(int level)
+static inline target_ulong get_rsp_from_tss(CPUX86State *env, int level)
 {
     int index;
 
@@ -793,8 +793,8 @@ static inline target_ulong get_rsp_from_tss(int level)
 }
 
 /* 64 bit interrupt */
-static void do_interrupt64(int intno, int is_int, int error_code,
-                           target_ulong next_eip, int is_hw)
+static void do_interrupt64(CPUX86State *env, int intno, int is_int,
+                           int error_code, target_ulong next_eip, int is_hw)
 {
     SegmentCache *dt;
     target_ulong ptr;
@@ -848,7 +848,7 @@ static void do_interrupt64(int intno, int is_int, int error_code,
         raise_exception_err(env, EXCP0D_GPF, 0);
     }
 
-    if (load_segment(&e1, &e2, selector) != 0) {
+    if (load_segment(env, &e1, &e2, selector) != 0) {
         raise_exception_err(env, EXCP0D_GPF, selector & 0xfffc);
     }
     if (!(e2 & DESC_S_MASK) || !(e2 & (DESC_CS_MASK))) {
@@ -867,9 +867,9 @@ static void do_interrupt64(int intno, int is_int, int error_code,
     if ((!(e2 & DESC_C_MASK) && dpl < cpl) || ist != 0) {
         /* to inner privilege */
         if (ist != 0) {
-            esp = get_rsp_from_tss(ist + 3);
+            esp = get_rsp_from_tss(env, ist + 3);
         } else {
-            esp = get_rsp_from_tss(dpl);
+            esp = get_rsp_from_tss(env, dpl);
         }
         esp &= ~0xfLL; /* align stack */
         ss = 0;
@@ -881,7 +881,7 @@ static void do_interrupt64(int intno, int is_int, int error_code,
         }
         new_stack = 0;
         if (ist != 0) {
-            esp = get_rsp_from_tss(ist + 3);
+            esp = get_rsp_from_tss(env, ist + 3);
         } else {
             esp = ESP;
         }
@@ -926,14 +926,14 @@ static void do_interrupt64(int intno, int is_int, int error_code,
 
 #ifdef TARGET_X86_64
 #if defined(CONFIG_USER_ONLY)
-void helper_syscall(int next_eip_addend)
+void helper_syscall(CPUX86State *env, int next_eip_addend)
 {
     env->exception_index = EXCP_SYSCALL;
     env->exception_next_eip = env->eip + next_eip_addend;
     cpu_loop_exit(env);
 }
 #else
-void helper_syscall(int next_eip_addend)
+void helper_syscall(CPUX86State *env, int next_eip_addend)
 {
     int selector;
 
@@ -990,7 +990,7 @@ void helper_syscall(int next_eip_addend)
 #endif
 
 #ifdef TARGET_X86_64
-void helper_sysret(int dflag)
+void helper_sysret(CPUX86State *env, int dflag)
 {
     int cpl, selector;
 
@@ -1047,8 +1047,8 @@ void helper_sysret(int dflag)
 #endif
 
 /* real mode interrupt */
-static void do_interrupt_real(int intno, int is_int, int error_code,
-                              unsigned int next_eip)
+static void do_interrupt_real(CPUX86State *env, int intno, int is_int,
+                              int error_code, unsigned int next_eip)
 {
     SegmentCache *dt;
     target_ulong ptr, ssp;
@@ -1087,8 +1087,8 @@ static void do_interrupt_real(int intno, int is_int, int error_code,
 
 #if defined(CONFIG_USER_ONLY)
 /* fake user mode interrupt */
-static void do_interrupt_user(int intno, int is_int, int error_code,
-                              target_ulong next_eip)
+static void do_interrupt_user(CPUX86State *env, int intno, int is_int,
+                              int error_code, target_ulong next_eip)
 {
     SegmentCache *dt;
     target_ulong ptr;
@@ -1121,8 +1121,8 @@ static void do_interrupt_user(int intno, int is_int, int error_code,
 
 #else
 
-static void handle_even_inj(int intno, int is_int, int error_code,
-                            int is_hw, int rm)
+static void handle_even_inj(CPUX86State *env, int intno, int is_int,
+                            int error_code, int is_hw, int rm)
 {
     uint32_t event_inj = ldl_phys(env->vm_vmcb + offsetof(struct vmcb,
                                                           control.event_inj));
@@ -1153,8 +1153,8 @@ static void handle_even_inj(int intno, int is_int, int error_code,
  * the int instruction. next_eip is the EIP value AFTER the interrupt
  * instruction. It is only relevant if is_int is TRUE.
  */
-static void do_interrupt_all(int intno, int is_int, int error_code,
-                             target_ulong next_eip, int is_hw)
+static void do_interrupt_all(CPUX86State *env, int intno, int is_int,
+                             int error_code, target_ulong next_eip, int is_hw)
 {
     if (qemu_loglevel_mask(CPU_LOG_INT)) {
         if ((env->cr[0] & CR0_PE_MASK)) {
@@ -1193,24 +1193,25 @@ static void do_interrupt_all(int intno, int is_int, int error_code,
     if (env->cr[0] & CR0_PE_MASK) {
 #if !defined(CONFIG_USER_ONLY)
         if (env->hflags & HF_SVMI_MASK) {
-            handle_even_inj(intno, is_int, error_code, is_hw, 0);
+            handle_even_inj(env, intno, is_int, error_code, is_hw, 0);
         }
 #endif
 #ifdef TARGET_X86_64
         if (env->hflags & HF_LMA_MASK) {
-            do_interrupt64(intno, is_int, error_code, next_eip, is_hw);
+            do_interrupt64(env, intno, is_int, error_code, next_eip, is_hw);
         } else
 #endif
         {
-            do_interrupt_protected(intno, is_int, error_code, next_eip, is_hw);
+            do_interrupt_protected(env, intno, is_int, error_code, next_eip,
+                                   is_hw);
         }
     } else {
 #if !defined(CONFIG_USER_ONLY)
         if (env->hflags & HF_SVMI_MASK) {
-            handle_even_inj(intno, is_int, error_code, is_hw, 1);
+            handle_even_inj(env, intno, is_int, error_code, is_hw, 1);
         }
 #endif
-        do_interrupt_real(intno, is_int, error_code, next_eip);
+        do_interrupt_real(env, intno, is_int, error_code, next_eip);
     }
 
 #if !defined(CONFIG_USER_ONLY)
@@ -1225,17 +1226,13 @@ static void do_interrupt_all(int intno, int is_int, int error_code,
 #endif
 }
 
-void do_interrupt(CPUX86State *env1)
+void do_interrupt(CPUX86State *env)
 {
-    CPUX86State *saved_env;
-
-    saved_env = env;
-    env = env1;
 #if defined(CONFIG_USER_ONLY)
     /* if user mode only, we simulate a fake exception
        which will be handled outside the cpu execution
        loop */
-    do_interrupt_user(env->exception_index,
+    do_interrupt_user(env, env->exception_index,
                       env->exception_is_int,
                       env->error_code,
                       env->exception_next_eip);
@@ -1245,27 +1242,22 @@ void do_interrupt(CPUX86State *env1)
     /* simulate a real cpu exception. On i386, it can
        trigger new exceptions, but we do not handle
        double or triple faults yet. */
-    do_interrupt_all(env->exception_index,
+    do_interrupt_all(env, env->exception_index,
                      env->exception_is_int,
                      env->error_code,
                      env->exception_next_eip, 0);
     /* successfully delivered */
     env->old_exception = -1;
 #endif
-    env = saved_env;
 }
 
-void do_interrupt_x86_hardirq(CPUX86State *env1, int intno, int is_hw)
+void do_interrupt_x86_hardirq(CPUX86State *env, int intno, int is_hw)
 {
-    CPUX86State *saved_env;
-
-    saved_env = env;
-    env = env1;
-    do_interrupt_all(intno, 0, 0, 0, is_hw);
-    env = saved_env;
+    do_interrupt_all(env, intno, 0, 0, 0, is_hw);
 }
 
-void helper_enter_level(int level, int data32, target_ulong t1)
+void helper_enter_level(CPUX86State *env, int level, int data32,
+                        target_ulong t1)
 {
     target_ulong ssp;
     uint32_t esp_mask, esp, ebp;
@@ -1300,7 +1292,8 @@ void helper_enter_level(int level, int data32, target_ulong t1)
 }
 
 #ifdef TARGET_X86_64
-void helper_enter64_level(int level, int data64, target_ulong t1)
+void helper_enter64_level(CPUX86State *env, int level, int data64,
+                          target_ulong t1)
 {
     target_ulong esp, ebp;
 
@@ -1331,7 +1324,7 @@ void helper_enter64_level(int level, int data64, target_ulong t1)
 }
 #endif
 
-void helper_lldt(int selector)
+void helper_lldt(CPUX86State *env, int selector)
 {
     SegmentCache *dt;
     uint32_t e1, e2;
@@ -1385,7 +1378,7 @@ void helper_lldt(int selector)
     env->ldt.selector = selector;
 }
 
-void helper_ltr(int selector)
+void helper_ltr(CPUX86State *env, int selector)
 {
     SegmentCache *dt;
     uint32_t e1, e2;
@@ -1449,7 +1442,7 @@ void helper_ltr(int selector)
 }
 
 /* only works if protected mode and not VM86. seg_reg must be != R_CS */
-void helper_load_seg(int seg_reg, int selector)
+void helper_load_seg(CPUX86State *env, int seg_reg, int selector)
 {
     uint32_t e1, e2;
     int cpl, dpl, rpl;
@@ -1537,7 +1530,7 @@ void helper_load_seg(int seg_reg, int selector)
 }
 
 /* protected mode jump */
-void helper_ljmp_protected(int new_cs, target_ulong new_eip,
+void helper_ljmp_protected(CPUX86State *env, int new_cs, target_ulong new_eip,
                            int next_eip_addend)
 {
     int gate_cs, type;
@@ -1547,7 +1540,7 @@ void helper_ljmp_protected(int new_cs, target_ulong new_eip,
     if ((new_cs & 0xfffc) == 0) {
         raise_exception_err(env, EXCP0D_GPF, 0);
     }
-    if (load_segment(&e1, &e2, new_cs) != 0) {
+    if (load_segment(env, &e1, &e2, new_cs) != 0) {
         raise_exception_err(env, EXCP0D_GPF, new_cs & 0xfffc);
     }
     cpl = env->hflags & HF_CPL_MASK;
@@ -1596,7 +1589,7 @@ void helper_ljmp_protected(int new_cs, target_ulong new_eip,
                 raise_exception_err(env, EXCP0D_GPF, new_cs & 0xfffc);
             }
             next_eip = env->eip + next_eip_addend;
-            switch_tss(new_cs, e1, e2, SWITCH_TSS_JMP, next_eip);
+            switch_tss(env, new_cs, e1, e2, SWITCH_TSS_JMP, next_eip);
             CC_OP = CC_OP_EFLAGS;
             break;
         case 4: /* 286 call gate */
@@ -1612,7 +1605,7 @@ void helper_ljmp_protected(int new_cs, target_ulong new_eip,
             if (type == 12) {
                 new_eip |= (e2 & 0xffff0000);
             }
-            if (load_segment(&e1, &e2, gate_cs) != 0) {
+            if (load_segment(env, &e1, &e2, gate_cs) != 0) {
                 raise_exception_err(env, EXCP0D_GPF, gate_cs & 0xfffc);
             }
             dpl = (e2 >> DESC_DPL_SHIFT) & 3;
@@ -1644,7 +1637,7 @@ void helper_ljmp_protected(int new_cs, target_ulong new_eip,
 }
 
 /* real mode call */
-void helper_lcall_real(int new_cs, target_ulong new_eip1,
+void helper_lcall_real(CPUX86State *env, int new_cs, target_ulong new_eip1,
                        int shift, int next_eip)
 {
     int new_eip;
@@ -1670,7 +1663,7 @@ void helper_lcall_real(int new_cs, target_ulong new_eip1,
 }
 
 /* protected mode call */
-void helper_lcall_protected(int new_cs, target_ulong new_eip,
+void helper_lcall_protected(CPUX86State *env, int new_cs, target_ulong new_eip,
                             int shift, int next_eip_addend)
 {
     int new_stack, i;
@@ -1685,7 +1678,7 @@ void helper_lcall_protected(int new_cs, target_ulong new_eip,
     if ((new_cs & 0xfffc) == 0) {
         raise_exception_err(env, EXCP0D_GPF, 0);
     }
-    if (load_segment(&e1, &e2, new_cs) != 0) {
+    if (load_segment(env, &e1, &e2, new_cs) != 0) {
         raise_exception_err(env, EXCP0D_GPF, new_cs & 0xfffc);
     }
     cpl = env->hflags & HF_CPL_MASK;
@@ -1765,7 +1758,7 @@ void helper_lcall_protected(int new_cs, target_ulong new_eip,
             if (dpl < cpl || dpl < rpl) {
                 raise_exception_err(env, EXCP0D_GPF, new_cs & 0xfffc);
             }
-            switch_tss(new_cs, e1, e2, SWITCH_TSS_CALL, next_eip);
+            switch_tss(env, new_cs, e1, e2, SWITCH_TSS_CALL, next_eip);
             CC_OP = CC_OP_EFLAGS;
             return;
         case 4: /* 286 call gate */
@@ -1791,7 +1784,7 @@ void helper_lcall_protected(int new_cs, target_ulong new_eip,
             raise_exception_err(env, EXCP0D_GPF, 0);
         }
 
-        if (load_segment(&e1, &e2, selector) != 0) {
+        if (load_segment(env, &e1, &e2, selector) != 0) {
             raise_exception_err(env, EXCP0D_GPF, selector & 0xfffc);
         }
         if (!(e2 & DESC_S_MASK) || !(e2 & (DESC_CS_MASK))) {
@@ -1807,7 +1800,7 @@ void helper_lcall_protected(int new_cs, target_ulong new_eip,
 
         if (!(e2 & DESC_C_MASK) && dpl < cpl) {
             /* to inner privilege */
-            get_ss_esp_from_tss(&ss, &sp, dpl);
+            get_ss_esp_from_tss(env, &ss, &sp, dpl);
             LOG_PCALL("new ss:esp=%04x:%08x param_count=%d ESP=" TARGET_FMT_lx
                       "\n",
                       ss, sp, param_count, ESP);
@@ -1817,7 +1810,7 @@ void helper_lcall_protected(int new_cs, target_ulong new_eip,
             if ((ss & 3) != dpl) {
                 raise_exception_err(env, EXCP0A_TSS, ss & 0xfffc);
             }
-            if (load_segment(&ss_e1, &ss_e2, ss) != 0) {
+            if (load_segment(env, &ss_e1, &ss_e2, ss) != 0) {
                 raise_exception_err(env, EXCP0A_TSS, ss & 0xfffc);
             }
             ss_dpl = (ss_e2 >> DESC_DPL_SHIFT) & 3;
@@ -1897,7 +1890,7 @@ void helper_lcall_protected(int new_cs, target_ulong new_eip,
 }
 
 /* real and vm86 mode iret */
-void helper_iret_real(int shift)
+void helper_iret_real(CPUX86State *env, int shift)
 {
     uint32_t sp, new_cs, new_eip, new_eflags, sp_mask;
     target_ulong ssp;
@@ -1936,7 +1929,7 @@ void helper_iret_real(int shift)
     env->hflags2 &= ~HF2_NMI_MASK;
 }
 
-static inline void validate_seg(int seg_reg, int cpl)
+static inline void validate_seg(CPUX86State *env, int seg_reg, int cpl)
 {
     int dpl;
     uint32_t e2;
@@ -1960,7 +1953,8 @@ static inline void validate_seg(int seg_reg, int cpl)
 }
 
 /* protected mode iret */
-static inline void helper_ret_protected(int shift, int is_iret, int addend)
+static inline void helper_ret_protected(CPUX86State *env, int shift,
+                                        int is_iret, int addend)
 {
     uint32_t new_cs, new_eflags, new_ss;
     uint32_t new_es, new_ds, new_fs, new_gs;
@@ -2016,7 +2010,7 @@ static inline void helper_ret_protected(int shift, int is_iret, int addend)
     if ((new_cs & 0xfffc) == 0) {
         raise_exception_err(env, EXCP0D_GPF, new_cs & 0xfffc);
     }
-    if (load_segment(&e1, &e2, new_cs) != 0) {
+    if (load_segment(env, &e1, &e2, new_cs) != 0) {
         raise_exception_err(env, EXCP0D_GPF, new_cs & 0xfffc);
     }
     if (!(e2 & DESC_S_MASK) ||
@@ -2093,7 +2087,7 @@ static inline void helper_ret_protected(int shift, int is_iret, int addend)
             if ((new_ss & 3) != rpl) {
                 raise_exception_err(env, EXCP0D_GPF, new_ss & 0xfffc);
             }
-            if (load_segment(&ss_e1, &ss_e2, new_ss) != 0) {
+            if (load_segment(env, &ss_e1, &ss_e2, new_ss) != 0) {
                 raise_exception_err(env, EXCP0D_GPF, new_ss & 0xfffc);
             }
             if (!(ss_e2 & DESC_S_MASK) ||
@@ -2130,10 +2124,10 @@ static inline void helper_ret_protected(int shift, int is_iret, int addend)
         }
 
         /* validate data segments */
-        validate_seg(R_ES, rpl);
-        validate_seg(R_DS, rpl);
-        validate_seg(R_FS, rpl);
-        validate_seg(R_GS, rpl);
+        validate_seg(env, R_ES, rpl);
+        validate_seg(env, R_DS, rpl);
+        validate_seg(env, R_FS, rpl);
+        validate_seg(env, R_GS, rpl);
 
         sp += addend;
     }
@@ -2168,19 +2162,19 @@ static inline void helper_ret_protected(int shift, int is_iret, int addend)
     cpu_load_eflags(env, new_eflags, TF_MASK | AC_MASK | ID_MASK |
                     IF_MASK | IOPL_MASK | VM_MASK | NT_MASK | VIF_MASK |
                     VIP_MASK);
-    load_seg_vm(R_CS, new_cs & 0xffff);
+    load_seg_vm(env, R_CS, new_cs & 0xffff);
     cpu_x86_set_cpl(env, 3);
-    load_seg_vm(R_SS, new_ss & 0xffff);
-    load_seg_vm(R_ES, new_es & 0xffff);
-    load_seg_vm(R_DS, new_ds & 0xffff);
-    load_seg_vm(R_FS, new_fs & 0xffff);
-    load_seg_vm(R_GS, new_gs & 0xffff);
+    load_seg_vm(env, R_SS, new_ss & 0xffff);
+    load_seg_vm(env, R_ES, new_es & 0xffff);
+    load_seg_vm(env, R_DS, new_ds & 0xffff);
+    load_seg_vm(env, R_FS, new_fs & 0xffff);
+    load_seg_vm(env, R_GS, new_gs & 0xffff);
 
     env->eip = new_eip & 0xffff;
     ESP = new_esp;
 }
 
-void helper_iret_protected(int shift, int next_eip)
+void helper_iret_protected(CPUX86State *env, int shift, int next_eip)
 {
     int tss_selector, type;
     uint32_t e1, e2;
@@ -2196,7 +2190,7 @@ void helper_iret_protected(int shift, int next_eip)
         if (tss_selector & 4) {
             raise_exception_err(env, EXCP0A_TSS, tss_selector & 0xfffc);
         }
-        if (load_segment(&e1, &e2, tss_selector) != 0) {
+        if (load_segment(env, &e1, &e2, tss_selector) != 0) {
             raise_exception_err(env, EXCP0A_TSS, tss_selector & 0xfffc);
         }
         type = (e2 >> DESC_TYPE_SHIFT) & 0x17;
@@ -2204,19 +2198,19 @@ void helper_iret_protected(int shift, int next_eip)
         if (type != 3) {
             raise_exception_err(env, EXCP0A_TSS, tss_selector & 0xfffc);
         }
-        switch_tss(tss_selector, e1, e2, SWITCH_TSS_IRET, next_eip);
+        switch_tss(env, tss_selector, e1, e2, SWITCH_TSS_IRET, next_eip);
     } else {
-        helper_ret_protected(shift, 1, 0);
+        helper_ret_protected(env, shift, 1, 0);
     }
     env->hflags2 &= ~HF2_NMI_MASK;
 }
 
-void helper_lret_protected(int shift, int addend)
+void helper_lret_protected(CPUX86State *env, int shift, int addend)
 {
-    helper_ret_protected(shift, 0, addend);
+    helper_ret_protected(env, shift, 0, addend);
 }
 
-void helper_sysenter(void)
+void helper_sysenter(CPUX86State *env)
 {
     if (env->sysenter_cs == 0) {
         raise_exception_err(env, EXCP0D_GPF, 0);
@@ -2250,7 +2244,7 @@ void helper_sysenter(void)
     EIP = env->sysenter_eip;
 }
 
-void helper_sysexit(int dflag)
+void helper_sysexit(CPUX86State *env, int dflag)
 {
     int cpl;
 
@@ -2290,7 +2284,7 @@ void helper_sysexit(int dflag)
     EIP = EDX;
 }
 
-target_ulong helper_lsl(target_ulong selector1)
+target_ulong helper_lsl(CPUX86State *env, target_ulong selector1)
 {
     unsigned int limit;
     uint32_t e1, e2, eflags, selector;
@@ -2301,7 +2295,7 @@ target_ulong helper_lsl(target_ulong selector1)
     if ((selector & 0xfffc) == 0) {
         goto fail;
     }
-    if (load_segment(&e1, &e2, selector) != 0) {
+    if (load_segment(env, &e1, &e2, selector) != 0) {
         goto fail;
     }
     rpl = selector & 3;
@@ -2338,7 +2332,7 @@ target_ulong helper_lsl(target_ulong selector1)
     return limit;
 }
 
-target_ulong helper_lar(target_ulong selector1)
+target_ulong helper_lar(CPUX86State *env, target_ulong selector1)
 {
     uint32_t e1, e2, eflags, selector;
     int rpl, dpl, cpl, type;
@@ -2348,7 +2342,7 @@ target_ulong helper_lar(target_ulong selector1)
     if ((selector & 0xfffc) == 0) {
         goto fail;
     }
-    if (load_segment(&e1, &e2, selector) != 0) {
+    if (load_segment(env, &e1, &e2, selector) != 0) {
         goto fail;
     }
     rpl = selector & 3;
@@ -2387,7 +2381,7 @@ target_ulong helper_lar(target_ulong selector1)
     return e2 & 0x00f0ff00;
 }
 
-void helper_verr(target_ulong selector1)
+void helper_verr(CPUX86State *env, target_ulong selector1)
 {
     uint32_t e1, e2, eflags, selector;
     int rpl, dpl, cpl;
@@ -2397,7 +2391,7 @@ void helper_verr(target_ulong selector1)
     if ((selector & 0xfffc) == 0) {
         goto fail;
     }
-    if (load_segment(&e1, &e2, selector) != 0) {
+    if (load_segment(env, &e1, &e2, selector) != 0) {
         goto fail;
     }
     if (!(e2 & DESC_S_MASK)) {
@@ -2425,7 +2419,7 @@ void helper_verr(target_ulong selector1)
     CC_SRC = eflags | CC_Z;
 }
 
-void helper_verw(target_ulong selector1)
+void helper_verw(CPUX86State *env, target_ulong selector1)
 {
     uint32_t e1, e2, eflags, selector;
     int rpl, dpl, cpl;
@@ -2435,7 +2429,7 @@ void helper_verw(target_ulong selector1)
     if ((selector & 0xfffc) == 0) {
         goto fail;
     }
-    if (load_segment(&e1, &e2, selector) != 0) {
+    if (load_segment(env, &e1, &e2, selector) != 0) {
         goto fail;
     }
     if (!(e2 & DESC_S_MASK)) {
@@ -2460,19 +2454,14 @@ void helper_verw(target_ulong selector1)
 }
 
 #if defined(CONFIG_USER_ONLY)
-void cpu_x86_load_seg(CPUX86State *s, int seg_reg, int selector)
+void cpu_x86_load_seg(CPUX86State *env, int seg_reg, int selector)
 {
-    CPUX86State *saved_env;
-
-    saved_env = env;
-    env = s;
     if (!(env->cr[0] & CR0_PE_MASK) || (env->eflags & VM_MASK)) {
         selector &= 0xffff;
         cpu_x86_load_seg_cache(env, seg_reg, selector,
                                (selector << 4), 0xffff, 0);
     } else {
-        helper_load_seg(seg_reg, selector);
+        helper_load_seg(env, seg_reg, selector);
     }
-    env = saved_env;
 }
 #endif
diff --git a/target-i386/translate.c b/target-i386/translate.c
index a4c2ae0..26091f9 100644
--- a/target-i386/translate.c
+++ b/target-i386/translate.c
@@ -2443,7 +2443,7 @@ static void gen_movl_seg_T0(DisasContext *s, int seg_reg, target_ulong cur_eip)
             gen_op_set_cc_op(s->cc_op);
         gen_jmp_im(cur_eip);
         tcg_gen_trunc_tl_i32(cpu_tmp2_i32, cpu_T[0]);
-        gen_helper_load_seg(tcg_const_i32(seg_reg), cpu_tmp2_i32);
+        gen_helper_load_seg(cpu_env, tcg_const_i32(seg_reg), cpu_tmp2_i32);
         /* abort translation because the addseg value may change or
            because ss32 may change. For R_SS, translation must always
            stop as a special handling must be done to disable hardware
@@ -2680,7 +2680,7 @@ static void gen_enter(DisasContext *s, int esp_addend, int level)
         gen_op_st_T0_A0(ot + s->mem_index);
         if (level) {
             /* XXX: must save state */
-            gen_helper_enter64_level(tcg_const_i32(level),
+            gen_helper_enter64_level(cpu_env, tcg_const_i32(level),
                                      tcg_const_i32((ot == OT_QUAD)),
                                      cpu_T[1]);
         }
@@ -2705,7 +2705,7 @@ static void gen_enter(DisasContext *s, int esp_addend, int level)
         gen_op_st_T0_A0(ot + s->mem_index);
         if (level) {
             /* XXX: must save state */
-            gen_helper_enter_level(tcg_const_i32(level),
+            gen_helper_enter_level(cpu_env, tcg_const_i32(level),
                                    tcg_const_i32(s->dflag),
                                    cpu_T[1]);
         }
@@ -4759,13 +4759,13 @@ static target_ulong disas_insn(DisasContext *s, target_ulong pc_start)
                     gen_op_set_cc_op(s->cc_op);
                 gen_jmp_im(pc_start - s->cs_base);
                 tcg_gen_trunc_tl_i32(cpu_tmp2_i32, cpu_T[0]);
-                gen_helper_lcall_protected(cpu_tmp2_i32, cpu_T[1],
-                                           tcg_const_i32(dflag), 
+                gen_helper_lcall_protected(cpu_env, cpu_tmp2_i32, cpu_T[1],
+                                           tcg_const_i32(dflag),
                                            tcg_const_i32(s->pc - pc_start));
             } else {
                 tcg_gen_trunc_tl_i32(cpu_tmp2_i32, cpu_T[0]);
-                gen_helper_lcall_real(cpu_tmp2_i32, cpu_T[1],
-                                      tcg_const_i32(dflag), 
+                gen_helper_lcall_real(cpu_env, cpu_tmp2_i32, cpu_T[1],
+                                      tcg_const_i32(dflag),
                                       tcg_const_i32(s->pc - s->cs_base));
             }
             gen_eob(s);
@@ -4786,7 +4786,7 @@ static target_ulong disas_insn(DisasContext *s, target_ulong pc_start)
                     gen_op_set_cc_op(s->cc_op);
                 gen_jmp_im(pc_start - s->cs_base);
                 tcg_gen_trunc_tl_i32(cpu_tmp2_i32, cpu_T[0]);
-                gen_helper_ljmp_protected(cpu_tmp2_i32, cpu_T[1],
+                gen_helper_ljmp_protected(cpu_env, cpu_tmp2_i32, cpu_T[1],
                                           tcg_const_i32(s->pc - pc_start));
             } else {
                 gen_op_movl_seg_T0_vm(R_CS);
@@ -6320,7 +6320,7 @@ static target_ulong disas_insn(DisasContext *s, target_ulong pc_start)
             if (s->cc_op != CC_OP_DYNAMIC)
                 gen_op_set_cc_op(s->cc_op);
             gen_jmp_im(pc_start - s->cs_base);
-            gen_helper_lret_protected(tcg_const_i32(s->dflag),
+            gen_helper_lret_protected(cpu_env, tcg_const_i32(s->dflag),
                                       tcg_const_i32(val));
         } else {
             gen_stack_A0(s);
@@ -6347,20 +6347,20 @@ static target_ulong disas_insn(DisasContext *s, target_ulong pc_start)
         gen_svm_check_intercept(s, pc_start, SVM_EXIT_IRET);
         if (!s->pe) {
             /* real mode */
-            gen_helper_iret_real(tcg_const_i32(s->dflag));
+            gen_helper_iret_real(cpu_env, tcg_const_i32(s->dflag));
             s->cc_op = CC_OP_EFLAGS;
         } else if (s->vm86) {
             if (s->iopl != 3) {
                 gen_exception(s, EXCP0D_GPF, pc_start - s->cs_base);
             } else {
-                gen_helper_iret_real(tcg_const_i32(s->dflag));
+                gen_helper_iret_real(cpu_env, tcg_const_i32(s->dflag));
                 s->cc_op = CC_OP_EFLAGS;
             }
         } else {
             if (s->cc_op != CC_OP_DYNAMIC)
                 gen_op_set_cc_op(s->cc_op);
             gen_jmp_im(pc_start - s->cs_base);
-            gen_helper_iret_protected(tcg_const_i32(s->dflag), 
+            gen_helper_iret_protected(cpu_env, tcg_const_i32(s->dflag),
                                       tcg_const_i32(s->pc - s->cs_base));
             s->cc_op = CC_OP_EFLAGS;
         }
@@ -7028,7 +7028,7 @@ static target_ulong disas_insn(DisasContext *s, target_ulong pc_start)
         } else {
             gen_update_cc_op(s);
             gen_jmp_im(pc_start - s->cs_base);
-            gen_helper_sysenter();
+            gen_helper_sysenter(cpu_env);
             gen_eob(s);
         }
         break;
@@ -7041,7 +7041,7 @@ static target_ulong disas_insn(DisasContext *s, target_ulong pc_start)
         } else {
             gen_update_cc_op(s);
             gen_jmp_im(pc_start - s->cs_base);
-            gen_helper_sysexit(tcg_const_i32(dflag));
+            gen_helper_sysexit(cpu_env, tcg_const_i32(dflag));
             gen_eob(s);
         }
         break;
@@ -7050,7 +7050,7 @@ static target_ulong disas_insn(DisasContext *s, target_ulong pc_start)
         /* XXX: is it usable in real mode ? */
         gen_update_cc_op(s);
         gen_jmp_im(pc_start - s->cs_base);
-        gen_helper_syscall(tcg_const_i32(s->pc - pc_start));
+        gen_helper_syscall(cpu_env, tcg_const_i32(s->pc - pc_start));
         gen_eob(s);
         break;
     case 0x107: /* sysret */
@@ -7059,7 +7059,7 @@ static target_ulong disas_insn(DisasContext *s, target_ulong pc_start)
         } else {
             gen_update_cc_op(s);
             gen_jmp_im(pc_start - s->cs_base);
-            gen_helper_sysret(tcg_const_i32(s->dflag));
+            gen_helper_sysret(cpu_env, tcg_const_i32(s->dflag));
             /* condition codes are modified only in long mode */
             if (s->lma)
                 s->cc_op = CC_OP_EFLAGS;
@@ -7109,7 +7109,7 @@ static target_ulong disas_insn(DisasContext *s, target_ulong pc_start)
                 gen_ldst_modrm(s, modrm, OT_WORD, OR_TMP0, 0);
                 gen_jmp_im(pc_start - s->cs_base);
                 tcg_gen_trunc_tl_i32(cpu_tmp2_i32, cpu_T[0]);
-                gen_helper_lldt(cpu_tmp2_i32);
+                gen_helper_lldt(cpu_env, cpu_tmp2_i32);
             }
             break;
         case 1: /* str */
@@ -7132,7 +7132,7 @@ static target_ulong disas_insn(DisasContext *s, target_ulong pc_start)
                 gen_ldst_modrm(s, modrm, OT_WORD, OR_TMP0, 0);
                 gen_jmp_im(pc_start - s->cs_base);
                 tcg_gen_trunc_tl_i32(cpu_tmp2_i32, cpu_T[0]);
-                gen_helper_ltr(cpu_tmp2_i32);
+                gen_helper_ltr(cpu_env, cpu_tmp2_i32);
             }
             break;
         case 4: /* verr */
@@ -7142,10 +7142,11 @@ static target_ulong disas_insn(DisasContext *s, target_ulong pc_start)
             gen_ldst_modrm(s, modrm, OT_WORD, OR_TMP0, 0);
             if (s->cc_op != CC_OP_DYNAMIC)
                 gen_op_set_cc_op(s->cc_op);
-            if (op == 4)
-                gen_helper_verr(cpu_T[0]);
-            else
-                gen_helper_verw(cpu_T[0]);
+            if (op == 4) {
+                gen_helper_verr(cpu_env, cpu_T[0]);
+            } else {
+                gen_helper_verw(cpu_env, cpu_T[0]);
+            }
             s->cc_op = CC_OP_EFLAGS;
             break;
         default:
@@ -7506,10 +7507,11 @@ static target_ulong disas_insn(DisasContext *s, target_ulong pc_start)
             t0 = tcg_temp_local_new();
             if (s->cc_op != CC_OP_DYNAMIC)
                 gen_op_set_cc_op(s->cc_op);
-            if (b == 0x102)
-                gen_helper_lar(t0, cpu_T[0]);
-            else
-                gen_helper_lsl(t0, cpu_T[0]);
+            if (b == 0x102) {
+                gen_helper_lar(t0, cpu_env, cpu_T[0]);
+            } else {
+                gen_helper_lsl(t0, cpu_env, cpu_T[0]);
+            }
             tcg_gen_andi_tl(cpu_tmp0, cpu_cc_src, CC_Z);
             label1 = gen_new_label();
             tcg_gen_brcondi_tl(TCG_COND_EQ, cpu_tmp0, 0, label1);
commit 4a7443be520f5737009ea47f93e4aa0328eecbca
Author: Blue Swirl <blauwirbel at gmail.com>
Date:   Sun Apr 29 18:42:47 2012 +0000

    x86: avoid AREG0 for misc helpers
    
    Add an explicit CPUX86State parameter instead of relying on AREG0.
    
    Signed-off-by: Blue Swirl <blauwirbel at gmail.com>

diff --git a/target-i386/Makefile.objs b/target-i386/Makefile.objs
index 36b97bc..13a7f6a 100644
--- a/target-i386/Makefile.objs
+++ b/target-i386/Makefile.objs
@@ -7,6 +7,5 @@ obj-$(CONFIG_NO_KVM) += kvm-stub.o
 obj-$(CONFIG_LINUX_USER) += ioport-user.o
 obj-$(CONFIG_BSD_USER) += ioport-user.o
 
-$(obj)/misc_helper.o: QEMU_CFLAGS += $(HELPER_CFLAGS)
 $(obj)/mem_helper.o: QEMU_CFLAGS += $(HELPER_CFLAGS)
 $(obj)/seg_helper.o: QEMU_CFLAGS += $(HELPER_CFLAGS)
diff --git a/target-i386/helper.h b/target-i386/helper.h
index ec7edca..9a9c064 100644
--- a/target-i386/helper.h
+++ b/target-i386/helper.h
@@ -41,12 +41,12 @@ DEF_HELPER_4(lcall_protected, void, int, tl, int, int)
 DEF_HELPER_1(iret_real, void, int)
 DEF_HELPER_2(iret_protected, void, int, int)
 DEF_HELPER_2(lret_protected, void, int, int)
-DEF_HELPER_1(read_crN, tl, int)
-DEF_HELPER_2(write_crN, void, int, tl)
-DEF_HELPER_1(lmsw, void, tl)
+DEF_HELPER_2(read_crN, tl, env, int)
+DEF_HELPER_3(write_crN, void, env, int, tl)
+DEF_HELPER_2(lmsw, void, env, tl)
 DEF_HELPER_1(clts, void, env)
-DEF_HELPER_2(movl_drN_T0, void, int, tl)
-DEF_HELPER_1(invlpg, void, tl)
+DEF_HELPER_3(movl_drN_T0, void, env, int, tl)
+DEF_HELPER_2(invlpg, void, env, tl)
 
 DEF_HELPER_3(enter_level, void, int, int, tl)
 #ifdef TARGET_X86_64
@@ -58,10 +58,10 @@ DEF_HELPER_1(sysexit, void, int)
 DEF_HELPER_1(syscall, void, int)
 DEF_HELPER_1(sysret, void, int)
 #endif
-DEF_HELPER_1(hlt, void, int)
-DEF_HELPER_1(monitor, void, tl)
-DEF_HELPER_1(mwait, void, int)
-DEF_HELPER_0(debug, void)
+DEF_HELPER_2(hlt, void, env, int)
+DEF_HELPER_2(monitor, void, env, tl)
+DEF_HELPER_2(mwait, void, env, int)
+DEF_HELPER_1(debug, void, env)
 DEF_HELPER_1(reset_rf, void, env)
 DEF_HELPER_3(raise_interrupt, void, env, int, int)
 DEF_HELPER_2(raise_exception, void, env, int)
@@ -72,22 +72,22 @@ DEF_HELPER_1(reset_inhibit_irq, void, env)
 DEF_HELPER_2(boundw, void, tl, int)
 DEF_HELPER_2(boundl, void, tl, int)
 DEF_HELPER_1(rsm, void, env)
-DEF_HELPER_1(into, void, int)
+DEF_HELPER_2(into, void, env, int)
 DEF_HELPER_1(cmpxchg8b, void, tl)
 #ifdef TARGET_X86_64
 DEF_HELPER_1(cmpxchg16b, void, tl)
 #endif
-DEF_HELPER_0(single_step, void)
-DEF_HELPER_0(cpuid, void)
-DEF_HELPER_0(rdtsc, void)
-DEF_HELPER_0(rdtscp, void)
-DEF_HELPER_0(rdpmc, void)
-DEF_HELPER_0(rdmsr, void)
-DEF_HELPER_0(wrmsr, void)
+DEF_HELPER_1(single_step, void, env)
+DEF_HELPER_1(cpuid, void, env)
+DEF_HELPER_1(rdtsc, void, env)
+DEF_HELPER_1(rdtscp, void, env)
+DEF_HELPER_1(rdpmc, void, env)
+DEF_HELPER_1(rdmsr, void, env)
+DEF_HELPER_1(wrmsr, void, env)
 
-DEF_HELPER_1(check_iob, void, i32)
-DEF_HELPER_1(check_iow, void, i32)
-DEF_HELPER_1(check_iol, void, i32)
+DEF_HELPER_2(check_iob, void, env, i32)
+DEF_HELPER_2(check_iow, void, env, i32)
+DEF_HELPER_2(check_iol, void, env, i32)
 DEF_HELPER_2(outb, void, i32, i32)
 DEF_HELPER_1(inb, tl, i32)
 DEF_HELPER_2(outw, void, i32, i32)
diff --git a/target-i386/misc_helper.c b/target-i386/misc_helper.c
index 272a636..154601b 100644
--- a/target-i386/misc_helper.c
+++ b/target-i386/misc_helper.c
@@ -18,16 +18,11 @@
  */
 
 #include "cpu.h"
-#include "dyngen-exec.h"
 #include "ioport.h"
 #include "helper.h"
 
-#if !defined(CONFIG_USER_ONLY)
-#include "softmmu_exec.h"
-#endif /* !defined(CONFIG_USER_ONLY) */
-
 /* check if Port I/O is allowed in TSS */
-static inline void check_io(int addr, int size)
+static inline void check_io(CPUX86State *env, int addr, int size)
 {
     int io_offset, val, mask;
 
@@ -37,13 +32,13 @@ static inline void check_io(int addr, int size)
         env->tr.limit < 103) {
         goto fail;
     }
-    io_offset = lduw_kernel(env->tr.base + 0x66);
+    io_offset = cpu_lduw_kernel(env, env->tr.base + 0x66);
     io_offset += (addr >> 3);
     /* Note: the check needs two bytes */
     if ((io_offset + 1) > env->tr.limit) {
         goto fail;
     }
-    val = lduw_kernel(env->tr.base + io_offset);
+    val = cpu_lduw_kernel(env, env->tr.base + io_offset);
     val >>= (addr & 7);
     mask = (1 << size) - 1;
     /* all bits must be zero to allow the I/O */
@@ -53,19 +48,19 @@ static inline void check_io(int addr, int size)
     }
 }
 
-void helper_check_iob(uint32_t t0)
+void helper_check_iob(CPUX86State *env, uint32_t t0)
 {
-    check_io(t0, 1);
+    check_io(env, t0, 1);
 }
 
-void helper_check_iow(uint32_t t0)
+void helper_check_iow(CPUX86State *env, uint32_t t0)
 {
-    check_io(t0, 2);
+    check_io(env, t0, 2);
 }
 
-void helper_check_iol(uint32_t t0)
+void helper_check_iol(CPUX86State *env, uint32_t t0)
 {
-    check_io(t0, 4);
+    check_io(env, t0, 4);
 }
 
 void helper_outb(uint32_t port, uint32_t data)
@@ -98,7 +93,7 @@ target_ulong helper_inl(uint32_t port)
     return cpu_inl(port);
 }
 
-void helper_into(int next_eip_addend)
+void helper_into(CPUX86State *env, int next_eip_addend)
 {
     int eflags;
 
@@ -108,7 +103,7 @@ void helper_into(int next_eip_addend)
     }
 }
 
-void helper_single_step(void)
+void helper_single_step(CPUX86State *env)
 {
 #ifndef CONFIG_USER_ONLY
     check_hw_breakpoints(env, 1);
@@ -117,7 +112,7 @@ void helper_single_step(void)
     raise_exception(env, EXCP01_DB);
 }
 
-void helper_cpuid(void)
+void helper_cpuid(CPUX86State *env)
 {
     uint32_t eax, ebx, ecx, edx;
 
@@ -131,20 +126,20 @@ void helper_cpuid(void)
 }
 
 #if defined(CONFIG_USER_ONLY)
-target_ulong helper_read_crN(int reg)
+target_ulong helper_read_crN(CPUX86State *env, int reg)
 {
     return 0;
 }
 
-void helper_write_crN(int reg, target_ulong t0)
+void helper_write_crN(CPUX86State *env, int reg, target_ulong t0)
 {
 }
 
-void helper_movl_drN_T0(int reg, target_ulong t0)
+void helper_movl_drN_T0(CPUX86State *env, int reg, target_ulong t0)
 {
 }
 #else
-target_ulong helper_read_crN(int reg)
+target_ulong helper_read_crN(CPUX86State *env, int reg)
 {
     target_ulong val;
 
@@ -164,7 +159,7 @@ target_ulong helper_read_crN(int reg)
     return val;
 }
 
-void helper_write_crN(int reg, target_ulong t0)
+void helper_write_crN(CPUX86State *env, int reg, target_ulong t0)
 {
     cpu_svm_check_intercept_param(env, SVM_EXIT_WRITE_CR0 + reg, 0);
     switch (reg) {
@@ -189,7 +184,7 @@ void helper_write_crN(int reg, target_ulong t0)
     }
 }
 
-void helper_movl_drN_T0(int reg, target_ulong t0)
+void helper_movl_drN_T0(CPUX86State *env, int reg, target_ulong t0)
 {
     int i;
 
@@ -211,21 +206,21 @@ void helper_movl_drN_T0(int reg, target_ulong t0)
 }
 #endif
 
-void helper_lmsw(target_ulong t0)
+void helper_lmsw(CPUX86State *env, target_ulong t0)
 {
     /* only 4 lower bits of CR0 are modified. PE cannot be set to zero
        if already set to one. */
     t0 = (env->cr[0] & ~0xe) | (t0 & 0xf);
-    helper_write_crN(0, t0);
+    helper_write_crN(env, 0, t0);
 }
 
-void helper_invlpg(target_ulong addr)
+void helper_invlpg(CPUX86State *env, target_ulong addr)
 {
     cpu_svm_check_intercept_param(env, SVM_EXIT_INVLPG, 0);
     tlb_flush_page(env, addr);
 }
 
-void helper_rdtsc(void)
+void helper_rdtsc(CPUX86State *env)
 {
     uint64_t val;
 
@@ -239,13 +234,13 @@ void helper_rdtsc(void)
     EDX = (uint32_t)(val >> 32);
 }
 
-void helper_rdtscp(void)
+void helper_rdtscp(CPUX86State *env)
 {
-    helper_rdtsc();
+    helper_rdtsc(env);
     ECX = (uint32_t)(env->tsc_aux);
 }
 
-void helper_rdpmc(void)
+void helper_rdpmc(CPUX86State *env)
 {
     if ((env->cr[4] & CR4_PCE_MASK) && ((env->hflags & HF_CPL_MASK) != 0)) {
         raise_exception(env, EXCP0D_GPF);
@@ -258,15 +253,15 @@ void helper_rdpmc(void)
 }
 
 #if defined(CONFIG_USER_ONLY)
-void helper_wrmsr(void)
+void helper_wrmsr(CPUX86State *env)
 {
 }
 
-void helper_rdmsr(void)
+void helper_rdmsr(CPUX86State *env)
 {
 }
 #else
-void helper_wrmsr(void)
+void helper_wrmsr(CPUX86State *env)
 {
     uint64_t val;
 
@@ -413,7 +408,7 @@ void helper_wrmsr(void)
     }
 }
 
-void helper_rdmsr(void)
+void helper_rdmsr(CPUX86State *env)
 {
     uint64_t val;
 
@@ -554,7 +549,7 @@ void helper_rdmsr(void)
 }
 #endif
 
-static void do_hlt(void)
+static void do_hlt(CPUX86State *env)
 {
     env->hflags &= ~HF_INHIBIT_IRQ_MASK; /* needed if sti is just before */
     env->halted = 1;
@@ -562,15 +557,15 @@ static void do_hlt(void)
     cpu_loop_exit(env);
 }
 
-void helper_hlt(int next_eip_addend)
+void helper_hlt(CPUX86State *env, int next_eip_addend)
 {
     cpu_svm_check_intercept_param(env, SVM_EXIT_HLT, 0);
     EIP += next_eip_addend;
 
-    do_hlt();
+    do_hlt(env);
 }
 
-void helper_monitor(target_ulong ptr)
+void helper_monitor(CPUX86State *env, target_ulong ptr)
 {
     if ((uint32_t)ECX != 0) {
         raise_exception(env, EXCP0D_GPF);
@@ -579,7 +574,7 @@ void helper_monitor(target_ulong ptr)
     cpu_svm_check_intercept_param(env, SVM_EXIT_MONITOR, 0);
 }
 
-void helper_mwait(int next_eip_addend)
+void helper_mwait(CPUX86State *env, int next_eip_addend)
 {
     if ((uint32_t)ECX != 0) {
         raise_exception(env, EXCP0D_GPF);
@@ -592,11 +587,11 @@ void helper_mwait(int next_eip_addend)
         /* more than one CPU: do not sleep because another CPU may
            wake this one */
     } else {
-        do_hlt();
+        do_hlt(env);
     }
 }
 
-void helper_debug(void)
+void helper_debug(CPUX86State *env)
 {
     env->exception_index = EXCP_DEBUG;
     cpu_loop_exit(env);
diff --git a/target-i386/translate.c b/target-i386/translate.c
index 840d281..a4c2ae0 100644
--- a/target-i386/translate.c
+++ b/target-i386/translate.c
@@ -740,9 +740,15 @@ static void gen_check_io(DisasContext *s, int ot, target_ulong cur_eip,
         state_saved = 1;
         tcg_gen_trunc_tl_i32(cpu_tmp2_i32, cpu_T[0]);
         switch (ot) {
-        case 0: gen_helper_check_iob(cpu_tmp2_i32); break;
-        case 1: gen_helper_check_iow(cpu_tmp2_i32); break;
-        case 2: gen_helper_check_iol(cpu_tmp2_i32); break;
+        case 0:
+            gen_helper_check_iob(cpu_env, cpu_tmp2_i32);
+            break;
+        case 1:
+            gen_helper_check_iow(cpu_env, cpu_tmp2_i32);
+            break;
+        case 2:
+            gen_helper_check_iol(cpu_env, cpu_tmp2_i32);
+            break;
         }
     }
     if(s->flags & HF_SVMI_MASK) {
@@ -2736,7 +2742,7 @@ static void gen_debug(DisasContext *s, target_ulong cur_eip)
     if (s->cc_op != CC_OP_DYNAMIC)
         gen_op_set_cc_op(s->cc_op);
     gen_jmp_im(cur_eip);
-    gen_helper_debug();
+    gen_helper_debug(cpu_env);
     s->is_jmp = DISAS_TB_JUMP;
 }
 
@@ -2753,9 +2759,9 @@ static void gen_eob(DisasContext *s)
         gen_helper_reset_rf(cpu_env);
     }
     if (s->singlestep_enabled) {
-        gen_helper_debug();
+        gen_helper_debug(cpu_env);
     } else if (s->tf) {
-	gen_helper_single_step();
+        gen_helper_single_step(cpu_env);
     } else {
         tcg_gen_exit_tb(0);
     }
@@ -6832,7 +6838,7 @@ static target_ulong disas_insn(DisasContext *s, target_ulong pc_start)
         if (s->cc_op != CC_OP_DYNAMIC)
             gen_op_set_cc_op(s->cc_op);
         gen_jmp_im(pc_start - s->cs_base);
-        gen_helper_into(tcg_const_i32(s->pc - pc_start));
+        gen_helper_into(cpu_env, tcg_const_i32(s->pc - pc_start));
         break;
 #ifdef WANT_ICEBP
     case 0xf1: /* icebp (undocumented, exits to external debugger) */
@@ -6989,9 +6995,9 @@ static target_ulong disas_insn(DisasContext *s, target_ulong pc_start)
                 gen_op_set_cc_op(s->cc_op);
             gen_jmp_im(pc_start - s->cs_base);
             if (b & 2) {
-                gen_helper_rdmsr();
+                gen_helper_rdmsr(cpu_env);
             } else {
-                gen_helper_wrmsr();
+                gen_helper_wrmsr(cpu_env);
             }
         }
         break;
@@ -7001,7 +7007,7 @@ static target_ulong disas_insn(DisasContext *s, target_ulong pc_start)
         gen_jmp_im(pc_start - s->cs_base);
         if (use_icount)
             gen_io_start();
-        gen_helper_rdtsc();
+        gen_helper_rdtsc(cpu_env);
         if (use_icount) {
             gen_io_end();
             gen_jmp(s, s->pc - s->cs_base);
@@ -7011,7 +7017,7 @@ static target_ulong disas_insn(DisasContext *s, target_ulong pc_start)
         if (s->cc_op != CC_OP_DYNAMIC)
             gen_op_set_cc_op(s->cc_op);
         gen_jmp_im(pc_start - s->cs_base);
-        gen_helper_rdpmc();
+        gen_helper_rdpmc(cpu_env);
         break;
     case 0x134: /* sysenter */
         /* For Intel SYSENTER is valid on 64-bit */
@@ -7065,7 +7071,7 @@ static target_ulong disas_insn(DisasContext *s, target_ulong pc_start)
         if (s->cc_op != CC_OP_DYNAMIC)
             gen_op_set_cc_op(s->cc_op);
         gen_jmp_im(pc_start - s->cs_base);
-        gen_helper_cpuid();
+        gen_helper_cpuid(cpu_env);
         break;
     case 0xf4: /* hlt */
         if (s->cpl != 0) {
@@ -7074,7 +7080,7 @@ static target_ulong disas_insn(DisasContext *s, target_ulong pc_start)
             if (s->cc_op != CC_OP_DYNAMIC)
                 gen_op_set_cc_op(s->cc_op);
             gen_jmp_im(pc_start - s->cs_base);
-            gen_helper_hlt(tcg_const_i32(s->pc - pc_start));
+            gen_helper_hlt(cpu_env, tcg_const_i32(s->pc - pc_start));
             s->is_jmp = DISAS_TB_JUMP;
         }
         break;
@@ -7186,7 +7192,7 @@ static target_ulong disas_insn(DisasContext *s, target_ulong pc_start)
                             gen_op_andl_A0_ffff();
                     }
                     gen_add_A0_ds_seg(s);
-                    gen_helper_monitor(cpu_A0);
+                    gen_helper_monitor(cpu_env, cpu_A0);
                     break;
                 case 1: /* mwait */
                     if (!(s->cpuid_ext_features & CPUID_EXT_MONITOR) ||
@@ -7194,7 +7200,7 @@ static target_ulong disas_insn(DisasContext *s, target_ulong pc_start)
                         goto illegal_op;
                     gen_update_cc_op(s);
                     gen_jmp_im(pc_start - s->cs_base);
-                    gen_helper_mwait(tcg_const_i32(s->pc - pc_start));
+                    gen_helper_mwait(cpu_env, tcg_const_i32(s->pc - pc_start));
                     gen_eob(s);
                     break;
                 default:
@@ -7334,7 +7340,7 @@ static target_ulong disas_insn(DisasContext *s, target_ulong pc_start)
             } else {
                 gen_svm_check_intercept(s, pc_start, SVM_EXIT_WRITE_CR0);
                 gen_ldst_modrm(s, modrm, OT_WORD, OR_TMP0, 0);
-                gen_helper_lmsw(cpu_T[0]);
+                gen_helper_lmsw(cpu_env, cpu_T[0]);
                 gen_jmp_im(s->pc - s->cs_base);
                 gen_eob(s);
             }
@@ -7348,7 +7354,7 @@ static target_ulong disas_insn(DisasContext *s, target_ulong pc_start)
                         gen_op_set_cc_op(s->cc_op);
                     gen_jmp_im(pc_start - s->cs_base);
                     gen_lea_modrm(s, modrm, &reg_addr, &offset_addr);
-                    gen_helper_invlpg(cpu_A0);
+                    gen_helper_invlpg(cpu_env, cpu_A0);
                     gen_jmp_im(s->pc - s->cs_base);
                     gen_eob(s);
                 }
@@ -7383,7 +7389,7 @@ static target_ulong disas_insn(DisasContext *s, target_ulong pc_start)
                     gen_jmp_im(pc_start - s->cs_base);
                     if (use_icount)
                         gen_io_start();
-                    gen_helper_rdtscp();
+                    gen_helper_rdtscp(cpu_env);
                     if (use_icount) {
                         gen_io_end();
                         gen_jmp(s, s->pc - s->cs_base);
@@ -7565,11 +7571,12 @@ static target_ulong disas_insn(DisasContext *s, target_ulong pc_start)
                 gen_jmp_im(pc_start - s->cs_base);
                 if (b & 2) {
                     gen_op_mov_TN_reg(ot, 0, rm);
-                    gen_helper_write_crN(tcg_const_i32(reg), cpu_T[0]);
+                    gen_helper_write_crN(cpu_env, tcg_const_i32(reg),
+                                         cpu_T[0]);
                     gen_jmp_im(s->pc - s->cs_base);
                     gen_eob(s);
                 } else {
-                    gen_helper_read_crN(cpu_T[0], tcg_const_i32(reg));
+                    gen_helper_read_crN(cpu_T[0], cpu_env, tcg_const_i32(reg));
                     gen_op_mov_reg_T0(ot, rm);
                 }
                 break;
@@ -7598,7 +7605,7 @@ static target_ulong disas_insn(DisasContext *s, target_ulong pc_start)
             if (b & 2) {
                 gen_svm_check_intercept(s, pc_start, SVM_EXIT_WRITE_DR0 + reg);
                 gen_op_mov_TN_reg(ot, 0, rm);
-                gen_helper_movl_drN_T0(tcg_const_i32(reg), cpu_T[0]);
+                gen_helper_movl_drN_T0(cpu_env, tcg_const_i32(reg), cpu_T[0]);
                 gen_jmp_im(s->pc - s->cs_base);
                 gen_eob(s);
             } else {
commit 329e607d8efc77553b1bbf5059045301e50c32c8
Author: Blue Swirl <blauwirbel at gmail.com>
Date:   Sun Apr 29 19:11:01 2012 +0000

    x86: use wrappers for memory access helpers
    
    Switch to wrapped versions of memory access functions.
    
    Signed-off-by: Blue Swirl <blauwirbel at gmail.com>

diff --git a/target-i386/cpu.h b/target-i386/cpu.h
index b6d5e83..f33be16 100644
--- a/target-i386/cpu.h
+++ b/target-i386/cpu.h
@@ -1149,4 +1149,14 @@ void cpu_stw_data(CPUX86State *env, target_ulong ptr, uint32_t data);
 void cpu_stl_data(CPUX86State *env, target_ulong ptr, uint32_t data);
 void cpu_stq_data(CPUX86State *env, target_ulong ptr, uint64_t data);
 
+uint32_t cpu_ldub_kernel(CPUX86State *env, target_ulong ptr);
+uint32_t cpu_lduw_kernel(CPUX86State *env, target_ulong ptr);
+uint32_t cpu_ldl_kernel(CPUX86State *env, target_ulong ptr);
+uint64_t cpu_ldq_kernel(CPUX86State *env, target_ulong ptr);
+
+void cpu_stb_kernel(CPUX86State *env, target_ulong ptr, uint32_t data);
+void cpu_stw_kernel(CPUX86State *env, target_ulong ptr, uint32_t data);
+void cpu_stl_kernel(CPUX86State *env, target_ulong ptr, uint32_t data);
+void cpu_stq_kernel(CPUX86State *env, target_ulong ptr, uint64_t data);
+
 #endif /* CPU_I386_H */
diff --git a/target-i386/mem_helper.c b/target-i386/mem_helper.c
index 30c3bd0..3dd4406 100644
--- a/target-i386/mem_helper.c
+++ b/target-i386/mem_helper.c
@@ -190,6 +190,11 @@ WRAP_LD(uint32_t, ldub_data)
 WRAP_LD(uint32_t, lduw_data)
 WRAP_LD(uint32_t, ldl_data)
 WRAP_LD(uint64_t, ldq_data)
+
+WRAP_LD(uint32_t, ldub_kernel)
+WRAP_LD(uint32_t, lduw_kernel)
+WRAP_LD(uint32_t, ldl_kernel)
+WRAP_LD(uint64_t, ldq_kernel)
 #undef WRAP_LD
 
 #define WRAP_ST(datatype, fn)                                           \
@@ -207,4 +212,9 @@ WRAP_ST(uint32_t, stb_data)
 WRAP_ST(uint32_t, stw_data)
 WRAP_ST(uint32_t, stl_data)
 WRAP_ST(uint64_t, stq_data)
+
+WRAP_ST(uint32_t, stb_kernel)
+WRAP_ST(uint32_t, stw_kernel)
+WRAP_ST(uint32_t, stl_kernel)
+WRAP_ST(uint64_t, stq_kernel)
 #undef WRAP_ST
diff --git a/target-i386/seg_helper.c b/target-i386/seg_helper.c
index 41d146c..f5dcf01 100644
--- a/target-i386/seg_helper.c
+++ b/target-i386/seg_helper.c
@@ -23,10 +23,6 @@
 #include "qemu-log.h"
 #include "helper.h"
 
-#if !defined(CONFIG_USER_ONLY)
-#include "softmmu_exec.h"
-#endif /* !defined(CONFIG_USER_ONLY) */
-
 //#define DEBUG_PCALL
 
 #ifdef DEBUG_PCALL
@@ -56,8 +52,8 @@ static inline int load_segment(uint32_t *e1_ptr, uint32_t *e2_ptr,
         return -1;
     }
     ptr = dt->base + index;
-    *e1_ptr = ldl_kernel(ptr);
-    *e2_ptr = ldl_kernel(ptr + 4);
+    *e1_ptr = cpu_ldl_kernel(env, ptr);
+    *e2_ptr = cpu_ldl_kernel(env, ptr + 4);
     return 0;
 }
 
@@ -125,11 +121,11 @@ static inline void get_ss_esp_from_tss(uint32_t *ss_ptr,
         raise_exception_err(env, EXCP0A_TSS, env->tr.selector & 0xfffc);
     }
     if (shift == 0) {
-        *esp_ptr = lduw_kernel(env->tr.base + index);
-        *ss_ptr = lduw_kernel(env->tr.base + index + 2);
+        *esp_ptr = cpu_lduw_kernel(env, env->tr.base + index);
+        *ss_ptr = cpu_lduw_kernel(env, env->tr.base + index + 2);
     } else {
-        *esp_ptr = ldl_kernel(env->tr.base + index);
-        *ss_ptr = lduw_kernel(env->tr.base + index + 4);
+        *esp_ptr = cpu_ldl_kernel(env, env->tr.base + index);
+        *ss_ptr = cpu_lduw_kernel(env, env->tr.base + index + 4);
     }
 }
 
@@ -262,29 +258,30 @@ static void switch_tss(int tss_selector,
     /* read all the registers from the new TSS */
     if (type & 8) {
         /* 32 bit */
-        new_cr3 = ldl_kernel(tss_base + 0x1c);
-        new_eip = ldl_kernel(tss_base + 0x20);
-        new_eflags = ldl_kernel(tss_base + 0x24);
+        new_cr3 = cpu_ldl_kernel(env, tss_base + 0x1c);
+        new_eip = cpu_ldl_kernel(env, tss_base + 0x20);
+        new_eflags = cpu_ldl_kernel(env, tss_base + 0x24);
         for (i = 0; i < 8; i++) {
-            new_regs[i] = ldl_kernel(tss_base + (0x28 + i * 4));
+            new_regs[i] = cpu_ldl_kernel(env, tss_base + (0x28 + i * 4));
         }
         for (i = 0; i < 6; i++) {
-            new_segs[i] = lduw_kernel(tss_base + (0x48 + i * 4));
+            new_segs[i] = cpu_lduw_kernel(env, tss_base + (0x48 + i * 4));
         }
-        new_ldt = lduw_kernel(tss_base + 0x60);
-        new_trap = ldl_kernel(tss_base + 0x64);
+        new_ldt = cpu_lduw_kernel(env, tss_base + 0x60);
+        new_trap = cpu_ldl_kernel(env, tss_base + 0x64);
     } else {
         /* 16 bit */
         new_cr3 = 0;
-        new_eip = lduw_kernel(tss_base + 0x0e);
-        new_eflags = lduw_kernel(tss_base + 0x10);
+        new_eip = cpu_lduw_kernel(env, tss_base + 0x0e);
+        new_eflags = cpu_lduw_kernel(env, tss_base + 0x10);
         for (i = 0; i < 8; i++) {
-            new_regs[i] = lduw_kernel(tss_base + (0x12 + i * 2)) | 0xffff0000;
+            new_regs[i] = cpu_lduw_kernel(env, tss_base + (0x12 + i * 2)) |
+                0xffff0000;
         }
         for (i = 0; i < 4; i++) {
-            new_segs[i] = lduw_kernel(tss_base + (0x22 + i * 4));
+            new_segs[i] = cpu_lduw_kernel(env, tss_base + (0x22 + i * 4));
         }
-        new_ldt = lduw_kernel(tss_base + 0x2a);
+        new_ldt = cpu_lduw_kernel(env, tss_base + 0x2a);
         new_segs[R_FS] = 0;
         new_segs[R_GS] = 0;
         new_trap = 0;
@@ -299,10 +296,10 @@ static void switch_tss(int tss_selector,
     /* XXX: it can still fail in some cases, so a bigger hack is
        necessary to valid the TLB after having done the accesses */
 
-    v1 = ldub_kernel(env->tr.base);
-    v2 = ldub_kernel(env->tr.base + old_tss_limit_max);
-    stb_kernel(env->tr.base, v1);
-    stb_kernel(env->tr.base + old_tss_limit_max, v2);
+    v1 = cpu_ldub_kernel(env, env->tr.base);
+    v2 = cpu_ldub_kernel(env, env->tr.base + old_tss_limit_max);
+    cpu_stb_kernel(env, env->tr.base, v1);
+    cpu_stb_kernel(env, env->tr.base + old_tss_limit_max, v2);
 
     /* clear busy bit (it is restartable) */
     if (source == SWITCH_TSS_JMP || source == SWITCH_TSS_IRET) {
@@ -310,9 +307,9 @@ static void switch_tss(int tss_selector,
         uint32_t e2;
 
         ptr = env->gdt.base + (env->tr.selector & ~7);
-        e2 = ldl_kernel(ptr + 4);
+        e2 = cpu_ldl_kernel(env, ptr + 4);
         e2 &= ~DESC_TSS_BUSY_MASK;
-        stl_kernel(ptr + 4, e2);
+        cpu_stl_kernel(env, ptr + 4, e2);
     }
     old_eflags = cpu_compute_eflags(env);
     if (source == SWITCH_TSS_IRET) {
@@ -322,33 +319,35 @@ static void switch_tss(int tss_selector,
     /* save the current state in the old TSS */
     if (type & 8) {
         /* 32 bit */
-        stl_kernel(env->tr.base + 0x20, next_eip);
-        stl_kernel(env->tr.base + 0x24, old_eflags);
-        stl_kernel(env->tr.base + (0x28 + 0 * 4), EAX);
-        stl_kernel(env->tr.base + (0x28 + 1 * 4), ECX);
-        stl_kernel(env->tr.base + (0x28 + 2 * 4), EDX);
-        stl_kernel(env->tr.base + (0x28 + 3 * 4), EBX);
-        stl_kernel(env->tr.base + (0x28 + 4 * 4), ESP);
-        stl_kernel(env->tr.base + (0x28 + 5 * 4), EBP);
-        stl_kernel(env->tr.base + (0x28 + 6 * 4), ESI);
-        stl_kernel(env->tr.base + (0x28 + 7 * 4), EDI);
+        cpu_stl_kernel(env, env->tr.base + 0x20, next_eip);
+        cpu_stl_kernel(env, env->tr.base + 0x24, old_eflags);
+        cpu_stl_kernel(env, env->tr.base + (0x28 + 0 * 4), EAX);
+        cpu_stl_kernel(env, env->tr.base + (0x28 + 1 * 4), ECX);
+        cpu_stl_kernel(env, env->tr.base + (0x28 + 2 * 4), EDX);
+        cpu_stl_kernel(env, env->tr.base + (0x28 + 3 * 4), EBX);
+        cpu_stl_kernel(env, env->tr.base + (0x28 + 4 * 4), ESP);
+        cpu_stl_kernel(env, env->tr.base + (0x28 + 5 * 4), EBP);
+        cpu_stl_kernel(env, env->tr.base + (0x28 + 6 * 4), ESI);
+        cpu_stl_kernel(env, env->tr.base + (0x28 + 7 * 4), EDI);
         for (i = 0; i < 6; i++) {
-            stw_kernel(env->tr.base + (0x48 + i * 4), env->segs[i].selector);
+            cpu_stw_kernel(env, env->tr.base + (0x48 + i * 4),
+                           env->segs[i].selector);
         }
     } else {
         /* 16 bit */
-        stw_kernel(env->tr.base + 0x0e, next_eip);
-        stw_kernel(env->tr.base + 0x10, old_eflags);
-        stw_kernel(env->tr.base + (0x12 + 0 * 2), EAX);
-        stw_kernel(env->tr.base + (0x12 + 1 * 2), ECX);
-        stw_kernel(env->tr.base + (0x12 + 2 * 2), EDX);
-        stw_kernel(env->tr.base + (0x12 + 3 * 2), EBX);
-        stw_kernel(env->tr.base + (0x12 + 4 * 2), ESP);
-        stw_kernel(env->tr.base + (0x12 + 5 * 2), EBP);
-        stw_kernel(env->tr.base + (0x12 + 6 * 2), ESI);
-        stw_kernel(env->tr.base + (0x12 + 7 * 2), EDI);
+        cpu_stw_kernel(env, env->tr.base + 0x0e, next_eip);
+        cpu_stw_kernel(env, env->tr.base + 0x10, old_eflags);
+        cpu_stw_kernel(env, env->tr.base + (0x12 + 0 * 2), EAX);
+        cpu_stw_kernel(env, env->tr.base + (0x12 + 1 * 2), ECX);
+        cpu_stw_kernel(env, env->tr.base + (0x12 + 2 * 2), EDX);
+        cpu_stw_kernel(env, env->tr.base + (0x12 + 3 * 2), EBX);
+        cpu_stw_kernel(env, env->tr.base + (0x12 + 4 * 2), ESP);
+        cpu_stw_kernel(env, env->tr.base + (0x12 + 5 * 2), EBP);
+        cpu_stw_kernel(env, env->tr.base + (0x12 + 6 * 2), ESI);
+        cpu_stw_kernel(env, env->tr.base + (0x12 + 7 * 2), EDI);
         for (i = 0; i < 4; i++) {
-            stw_kernel(env->tr.base + (0x22 + i * 4), env->segs[i].selector);
+            cpu_stw_kernel(env, env->tr.base + (0x22 + i * 4),
+                           env->segs[i].selector);
         }
     }
 
@@ -356,7 +355,7 @@ static void switch_tss(int tss_selector,
        context */
 
     if (source == SWITCH_TSS_CALL) {
-        stw_kernel(tss_base, env->tr.selector);
+        cpu_stw_kernel(env, tss_base, env->tr.selector);
         new_eflags |= NT_MASK;
     }
 
@@ -366,9 +365,9 @@ static void switch_tss(int tss_selector,
         uint32_t e2;
 
         ptr = env->gdt.base + (tss_selector & ~7);
-        e2 = ldl_kernel(ptr + 4);
+        e2 = cpu_ldl_kernel(env, ptr + 4);
         e2 |= DESC_TSS_BUSY_MASK;
-        stl_kernel(ptr + 4, e2);
+        cpu_stl_kernel(env, ptr + 4, e2);
     }
 
     /* set the new CPU state */
@@ -434,8 +433,8 @@ static void switch_tss(int tss_selector,
             raise_exception_err(env, EXCP0A_TSS, new_ldt & 0xfffc);
         }
         ptr = dt->base + index;
-        e1 = ldl_kernel(ptr);
-        e2 = ldl_kernel(ptr + 4);
+        e1 = cpu_ldl_kernel(env, ptr);
+        e2 = cpu_ldl_kernel(env, ptr + 4);
         if ((e2 & DESC_S_MASK) || ((e2 >> DESC_TYPE_SHIFT) & 0xf) != 2) {
             raise_exception_err(env, EXCP0A_TSS, new_ldt & 0xfffc);
         }
@@ -521,28 +520,28 @@ static int exception_has_error_code(int intno)
 #define SEG_ADDL(ssp, sp, sp_mask) ((uint32_t)((ssp) + (sp & (sp_mask))))
 
 /* XXX: add a is_user flag to have proper security support */
-#define PUSHW(ssp, sp, sp_mask, val)                    \
-    {                                                   \
-        sp -= 2;                                        \
-        stw_kernel((ssp) + (sp & (sp_mask)), (val));    \
+#define PUSHW(ssp, sp, sp_mask, val)                             \
+    {                                                            \
+        sp -= 2;                                                 \
+        cpu_stw_kernel(env, (ssp) + (sp & (sp_mask)), (val));    \
     }
 
 #define PUSHL(ssp, sp, sp_mask, val)                                    \
     {                                                                   \
         sp -= 4;                                                        \
-        stl_kernel(SEG_ADDL(ssp, sp, sp_mask), (uint32_t)(val));        \
+        cpu_stl_kernel(env, SEG_ADDL(ssp, sp, sp_mask), (uint32_t)(val)); \
     }
 
-#define POPW(ssp, sp, sp_mask, val)                     \
-    {                                                   \
-        val = lduw_kernel((ssp) + (sp & (sp_mask)));    \
-        sp += 2;                                        \
+#define POPW(ssp, sp, sp_mask, val)                              \
+    {                                                            \
+        val = cpu_lduw_kernel(env, (ssp) + (sp & (sp_mask)));    \
+        sp += 2;                                                 \
     }
 
-#define POPL(ssp, sp, sp_mask, val)                             \
-    {                                                           \
-        val = (uint32_t)ldl_kernel(SEG_ADDL(ssp, sp, sp_mask)); \
-        sp += 4;                                                \
+#define POPL(ssp, sp, sp_mask, val)                                     \
+    {                                                                   \
+        val = (uint32_t)cpu_ldl_kernel(env, SEG_ADDL(ssp, sp, sp_mask)); \
+        sp += 4;                                                        \
     }
 
 /* protected mode interrupt */
@@ -571,8 +570,8 @@ static void do_interrupt_protected(int intno, int is_int, int error_code,
         raise_exception_err(env, EXCP0D_GPF, intno * 8 + 2);
     }
     ptr = dt->base + intno * 8;
-    e1 = ldl_kernel(ptr);
-    e2 = ldl_kernel(ptr + 4);
+    e1 = cpu_ldl_kernel(env, ptr);
+    e2 = cpu_ldl_kernel(env, ptr + 4);
     /* check gate type */
     type = (e2 >> DESC_TYPE_SHIFT) & 0x1f;
     switch (type) {
@@ -597,9 +596,9 @@ static void do_interrupt_protected(int intno, int is_int, int error_code,
             esp = (ESP - (2 << shift)) & mask;
             ssp = env->segs[R_SS].base + esp;
             if (shift) {
-                stl_kernel(ssp, error_code);
+                cpu_stl_kernel(env, ssp, error_code);
             } else {
-                stw_kernel(ssp, error_code);
+                cpu_stw_kernel(env, ssp, error_code);
             }
             SET_ESP(esp, mask);
         }
@@ -765,12 +764,12 @@ static void do_interrupt_protected(int intno, int is_int, int error_code,
 #define PUSHQ(sp, val)                          \
     {                                           \
         sp -= 8;                                \
-        stq_kernel(sp, (val));                  \
+        cpu_stq_kernel(env, sp, (val));         \
     }
 
 #define POPQ(sp, val)                           \
     {                                           \
-        val = ldq_kernel(sp);                   \
+        val = cpu_ldq_kernel(env, sp);          \
         sp += 8;                                \
     }
 
@@ -790,7 +789,7 @@ static inline target_ulong get_rsp_from_tss(int level)
     if ((index + 7) > env->tr.limit) {
         raise_exception_err(env, EXCP0A_TSS, env->tr.selector & 0xfffc);
     }
-    return ldq_kernel(env->tr.base + index);
+    return cpu_ldq_kernel(env, env->tr.base + index);
 }
 
 /* 64 bit interrupt */
@@ -819,9 +818,9 @@ static void do_interrupt64(int intno, int is_int, int error_code,
         raise_exception_err(env, EXCP0D_GPF, intno * 16 + 2);
     }
     ptr = dt->base + intno * 16;
-    e1 = ldl_kernel(ptr);
-    e2 = ldl_kernel(ptr + 4);
-    e3 = ldl_kernel(ptr + 8);
+    e1 = cpu_ldl_kernel(env, ptr);
+    e2 = cpu_ldl_kernel(env, ptr + 4);
+    e3 = cpu_ldl_kernel(env, ptr + 8);
     /* check gate type */
     type = (e2 >> DESC_TYPE_SHIFT) & 0x1f;
     switch (type) {
@@ -1063,8 +1062,8 @@ static void do_interrupt_real(int intno, int is_int, int error_code,
         raise_exception_err(env, EXCP0D_GPF, intno * 8 + 2);
     }
     ptr = dt->base + intno * 4;
-    offset = lduw_kernel(ptr);
-    selector = lduw_kernel(ptr + 2);
+    offset = cpu_lduw_kernel(env, ptr);
+    selector = cpu_lduw_kernel(env, ptr + 2);
     esp = ESP;
     ssp = env->segs[R_SS].base;
     if (is_int) {
@@ -1103,7 +1102,7 @@ static void do_interrupt_user(int intno, int is_int, int error_code,
         shift = 3;
     }
     ptr = dt->base + (intno << shift);
-    e2 = ldl_kernel(ptr + 4);
+    e2 = cpu_ldl_kernel(env, ptr + 4);
 
     dpl = (e2 >> DESC_DPL_SHIFT) & 3;
     cpl = env->hflags & HF_CPL_MASK;
@@ -1281,20 +1280,22 @@ void helper_enter_level(int level, int data32, target_ulong t1)
         while (--level) {
             esp -= 4;
             ebp -= 4;
-            stl(ssp + (esp & esp_mask), ldl(ssp + (ebp & esp_mask)));
+            cpu_stl_data(env, ssp + (esp & esp_mask),
+                         cpu_ldl_data(env, ssp + (ebp & esp_mask)));
         }
         esp -= 4;
-        stl(ssp + (esp & esp_mask), t1);
+        cpu_stl_data(env, ssp + (esp & esp_mask), t1);
     } else {
         /* 16 bit */
         esp -= 2;
         while (--level) {
             esp -= 2;
             ebp -= 2;
-            stw(ssp + (esp & esp_mask), lduw(ssp + (ebp & esp_mask)));
+            cpu_stw_data(env, ssp + (esp & esp_mask),
+                         cpu_lduw_data(env, ssp + (ebp & esp_mask)));
         }
         esp -= 2;
-        stw(ssp + (esp & esp_mask), t1);
+        cpu_stw_data(env, ssp + (esp & esp_mask), t1);
     }
 }
 
@@ -1312,20 +1313,20 @@ void helper_enter64_level(int level, int data64, target_ulong t1)
         while (--level) {
             esp -= 8;
             ebp -= 8;
-            stq(esp, ldq(ebp));
+            cpu_stq_data(env, esp, cpu_ldq_data(env, ebp));
         }
         esp -= 8;
-        stq(esp, t1);
+        cpu_stq_data(env, esp, t1);
     } else {
         /* 16 bit */
         esp -= 2;
         while (--level) {
             esp -= 2;
             ebp -= 2;
-            stw(esp, lduw(ebp));
+            cpu_stw_data(env, esp, cpu_lduw_data(env, ebp));
         }
         esp -= 2;
-        stw(esp, t1);
+        cpu_stw_data(env, esp, t1);
     }
 }
 #endif
@@ -1360,8 +1361,8 @@ void helper_lldt(int selector)
             raise_exception_err(env, EXCP0D_GPF, selector & 0xfffc);
         }
         ptr = dt->base + index;
-        e1 = ldl_kernel(ptr);
-        e2 = ldl_kernel(ptr + 4);
+        e1 = cpu_ldl_kernel(env, ptr);
+        e2 = cpu_ldl_kernel(env, ptr + 4);
         if ((e2 & DESC_S_MASK) || ((e2 >> DESC_TYPE_SHIFT) & 0xf) != 2) {
             raise_exception_err(env, EXCP0D_GPF, selector & 0xfffc);
         }
@@ -1372,7 +1373,7 @@ void helper_lldt(int selector)
         if (env->hflags & HF_LMA_MASK) {
             uint32_t e3;
 
-            e3 = ldl_kernel(ptr + 8);
+            e3 = cpu_ldl_kernel(env, ptr + 8);
             load_seg_cache_raw_dt(&env->ldt, e1, e2);
             env->ldt.base |= (target_ulong)e3 << 32;
         } else
@@ -1415,8 +1416,8 @@ void helper_ltr(int selector)
             raise_exception_err(env, EXCP0D_GPF, selector & 0xfffc);
         }
         ptr = dt->base + index;
-        e1 = ldl_kernel(ptr);
-        e2 = ldl_kernel(ptr + 4);
+        e1 = cpu_ldl_kernel(env, ptr);
+        e2 = cpu_ldl_kernel(env, ptr + 4);
         type = (e2 >> DESC_TYPE_SHIFT) & 0xf;
         if ((e2 & DESC_S_MASK) ||
             (type != 1 && type != 9)) {
@@ -1429,8 +1430,8 @@ void helper_ltr(int selector)
         if (env->hflags & HF_LMA_MASK) {
             uint32_t e3, e4;
 
-            e3 = ldl_kernel(ptr + 8);
-            e4 = ldl_kernel(ptr + 12);
+            e3 = cpu_ldl_kernel(env, ptr + 8);
+            e4 = cpu_ldl_kernel(env, ptr + 12);
             if ((e4 >> DESC_TYPE_SHIFT) & 0xf) {
                 raise_exception_err(env, EXCP0D_GPF, selector & 0xfffc);
             }
@@ -1442,7 +1443,7 @@ void helper_ltr(int selector)
             load_seg_cache_raw_dt(&env->tr, e1, e2);
         }
         e2 |= DESC_TSS_BUSY_MASK;
-        stl_kernel(ptr + 4, e2);
+        cpu_stl_kernel(env, ptr + 4, e2);
     }
     env->tr.selector = selector;
 }
@@ -1480,8 +1481,8 @@ void helper_load_seg(int seg_reg, int selector)
             raise_exception_err(env, EXCP0D_GPF, selector & 0xfffc);
         }
         ptr = dt->base + index;
-        e1 = ldl_kernel(ptr);
-        e2 = ldl_kernel(ptr + 4);
+        e1 = cpu_ldl_kernel(env, ptr);
+        e2 = cpu_ldl_kernel(env, ptr + 4);
 
         if (!(e2 & DESC_S_MASK)) {
             raise_exception_err(env, EXCP0D_GPF, selector & 0xfffc);
@@ -1521,7 +1522,7 @@ void helper_load_seg(int seg_reg, int selector)
         /* set the access bit if not already set */
         if (!(e2 & DESC_A_MASK)) {
             e2 |= DESC_A_MASK;
-            stl_kernel(ptr + 4, e2);
+            cpu_stl_kernel(env, ptr + 4, e2);
         }
 
         cpu_x86_load_seg_cache(env, seg_reg, selector,
@@ -1843,14 +1844,16 @@ void helper_lcall_protected(int new_cs, target_ulong new_eip,
                 PUSHL(ssp, sp, sp_mask, env->segs[R_SS].selector);
                 PUSHL(ssp, sp, sp_mask, ESP);
                 for (i = param_count - 1; i >= 0; i--) {
-                    val = ldl_kernel(old_ssp + ((ESP + i * 4) & old_sp_mask));
+                    val = cpu_ldl_kernel(env, old_ssp + ((ESP + i * 4) &
+                                                         old_sp_mask));
                     PUSHL(ssp, sp, sp_mask, val);
                 }
             } else {
                 PUSHW(ssp, sp, sp_mask, env->segs[R_SS].selector);
                 PUSHW(ssp, sp, sp_mask, ESP);
                 for (i = param_count - 1; i >= 0; i--) {
-                    val = lduw_kernel(old_ssp + ((ESP + i * 2) & old_sp_mask));
+                    val = cpu_lduw_kernel(env, old_ssp + ((ESP + i * 2) &
+                                                          old_sp_mask));
                     PUSHW(ssp, sp, sp_mask, val);
                 }
             }
@@ -2189,7 +2192,7 @@ void helper_iret_protected(int shift, int next_eip)
             raise_exception_err(env, EXCP0D_GPF, 0);
         }
 #endif
-        tss_selector = lduw_kernel(env->tr.base + 0);
+        tss_selector = cpu_lduw_kernel(env, env->tr.base + 0);
         if (tss_selector & 4) {
             raise_exception_err(env, EXCP0A_TSS, tss_selector & 0xfffc);
         }
commit 608badfc660b1c4d20e67a64b639c7bcd2d5ba16
Author: Blue Swirl <blauwirbel at gmail.com>
Date:   Sun Apr 29 17:54:21 2012 +0000

    x86: avoid AREG0 for SMM helpers
    
    Add an explicit CPUX86State parameter instead of relying on AREG0.
    
    Signed-off-by: Blue Swirl <blauwirbel at gmail.com>

diff --git a/target-i386/Makefile.objs b/target-i386/Makefile.objs
index a3450f6..36b97bc 100644
--- a/target-i386/Makefile.objs
+++ b/target-i386/Makefile.objs
@@ -7,7 +7,6 @@ obj-$(CONFIG_NO_KVM) += kvm-stub.o
 obj-$(CONFIG_LINUX_USER) += ioport-user.o
 obj-$(CONFIG_BSD_USER) += ioport-user.o
 
-$(obj)/smm_helper.o: QEMU_CFLAGS += $(HELPER_CFLAGS)
 $(obj)/misc_helper.o: QEMU_CFLAGS += $(HELPER_CFLAGS)
 $(obj)/mem_helper.o: QEMU_CFLAGS += $(HELPER_CFLAGS)
 $(obj)/seg_helper.o: QEMU_CFLAGS += $(HELPER_CFLAGS)
diff --git a/target-i386/helper.h b/target-i386/helper.h
index 601b8dd..ec7edca 100644
--- a/target-i386/helper.h
+++ b/target-i386/helper.h
@@ -71,7 +71,7 @@ DEF_HELPER_1(set_inhibit_irq, void, env)
 DEF_HELPER_1(reset_inhibit_irq, void, env)
 DEF_HELPER_2(boundw, void, tl, int)
 DEF_HELPER_2(boundl, void, tl, int)
-DEF_HELPER_0(rsm, void)
+DEF_HELPER_1(rsm, void, env)
 DEF_HELPER_1(into, void, int)
 DEF_HELPER_1(cmpxchg8b, void, tl)
 #ifdef TARGET_X86_64
diff --git a/target-i386/smm_helper.c b/target-i386/smm_helper.c
index bc1bfa2..8b04eb2 100644
--- a/target-i386/smm_helper.c
+++ b/target-i386/smm_helper.c
@@ -18,18 +18,17 @@
  */
 
 #include "cpu.h"
-#include "dyngen-exec.h"
 #include "helper.h"
 
 /* SMM support */
 
 #if defined(CONFIG_USER_ONLY)
 
-void do_smm_enter(CPUX86State *env1)
+void do_smm_enter(CPUX86State *env)
 {
 }
 
-void helper_rsm(void)
+void helper_rsm(CPUX86State *env)
 {
 }
 
@@ -41,15 +40,11 @@ void helper_rsm(void)
 #define SMM_REVISION_ID 0x00020000
 #endif
 
-void do_smm_enter(CPUX86State *env1)
+void do_smm_enter(CPUX86State *env)
 {
     target_ulong sm_state;
     SegmentCache *dt;
     int i, offset;
-    CPUX86State *saved_env;
-
-    saved_env = env;
-    env = env1;
 
     qemu_log_mask(CPU_LOG_INT, "SMM: enter\n");
     log_cpu_state_mask(CPU_LOG_INT, env, X86_DUMP_CCOP);
@@ -180,10 +175,9 @@ void do_smm_enter(CPUX86State *env1)
     cpu_x86_update_cr4(env, 0);
     env->dr[7] = 0x00000400;
     CC_OP = CC_OP_EFLAGS;
-    env = saved_env;
 }
 
-void helper_rsm(void)
+void helper_rsm(CPUX86State *env)
 {
     target_ulong sm_state;
     int i, offset;
diff --git a/target-i386/translate.c b/target-i386/translate.c
index 9f4c712..840d281 100644
--- a/target-i386/translate.c
+++ b/target-i386/translate.c
@@ -7721,7 +7721,7 @@ static target_ulong disas_insn(DisasContext *s, target_ulong pc_start)
             goto illegal_op;
         gen_update_cc_op(s);
         gen_jmp_im(s->pc - s->cs_base);
-        gen_helper_rsm();
+        gen_helper_rsm(cpu_env);
         gen_eob(s);
         break;
     case 0x1b8: /* SSE4.2 popcnt */
commit 052e80d5e026a5414a02d5d979c37521eb33e07d
Author: Blue Swirl <blauwirbel at gmail.com>
Date:   Sun Apr 29 15:51:49 2012 +0000

    x86: avoid AREG0 for SVM helpers
    
    Add an explicit CPUX86State parameter instead of relying on AREG0.
    
    Signed-off-by: Blue Swirl <blauwirbel at gmail.com>

diff --git a/target-i386/Makefile.objs b/target-i386/Makefile.objs
index d39ec8e..a3450f6 100644
--- a/target-i386/Makefile.objs
+++ b/target-i386/Makefile.objs
@@ -7,7 +7,6 @@ obj-$(CONFIG_NO_KVM) += kvm-stub.o
 obj-$(CONFIG_LINUX_USER) += ioport-user.o
 obj-$(CONFIG_BSD_USER) += ioport-user.o
 
-$(obj)/svm_helper.o: QEMU_CFLAGS += $(HELPER_CFLAGS)
 $(obj)/smm_helper.o: QEMU_CFLAGS += $(HELPER_CFLAGS)
 $(obj)/misc_helper.o: QEMU_CFLAGS += $(HELPER_CFLAGS)
 $(obj)/mem_helper.o: QEMU_CFLAGS += $(HELPER_CFLAGS)
diff --git a/target-i386/helper.h b/target-i386/helper.h
index 67c81bf..601b8dd 100644
--- a/target-i386/helper.h
+++ b/target-i386/helper.h
@@ -95,17 +95,17 @@ DEF_HELPER_1(inw, tl, i32)
 DEF_HELPER_2(outl, void, i32, i32)
 DEF_HELPER_1(inl, tl, i32)
 
-DEF_HELPER_2(svm_check_intercept_param, void, i32, i64)
-DEF_HELPER_2(vmexit, void, i32, i64)
-DEF_HELPER_3(svm_check_io, void, i32, i32, i32)
-DEF_HELPER_2(vmrun, void, int, int)
-DEF_HELPER_0(vmmcall, void)
-DEF_HELPER_1(vmload, void, int)
-DEF_HELPER_1(vmsave, void, int)
-DEF_HELPER_0(stgi, void)
-DEF_HELPER_0(clgi, void)
-DEF_HELPER_0(skinit, void)
-DEF_HELPER_1(invlpga, void, int)
+DEF_HELPER_3(svm_check_intercept_param, void, env, i32, i64)
+DEF_HELPER_3(vmexit, void, env, i32, i64)
+DEF_HELPER_4(svm_check_io, void, env, i32, i32, i32)
+DEF_HELPER_3(vmrun, void, env, int, int)
+DEF_HELPER_1(vmmcall, void, env)
+DEF_HELPER_2(vmload, void, env, int)
+DEF_HELPER_2(vmsave, void, env, int)
+DEF_HELPER_1(stgi, void, env)
+DEF_HELPER_1(clgi, void, env)
+DEF_HELPER_1(skinit, void, env)
+DEF_HELPER_2(invlpga, void, env, int)
 
 /* x86 FPU */
 
diff --git a/target-i386/svm_helper.c b/target-i386/svm_helper.c
index 64d842c..f370ac5 100644
--- a/target-i386/svm_helper.c
+++ b/target-i386/svm_helper.c
@@ -18,46 +18,46 @@
  */
 
 #include "cpu.h"
-#include "dyngen-exec.h"
+#include "cpu-all.h"
 #include "helper.h"
 
 /* Secure Virtual Machine helpers */
 
 #if defined(CONFIG_USER_ONLY)
 
-void helper_vmrun(int aflag, int next_eip_addend)
+void helper_vmrun(CPUX86State *env, int aflag, int next_eip_addend)
 {
 }
 
-void helper_vmmcall(void)
+void helper_vmmcall(CPUX86State *env)
 {
 }
 
-void helper_vmload(int aflag)
+void helper_vmload(CPUX86State *env, int aflag)
 {
 }
 
-void helper_vmsave(int aflag)
+void helper_vmsave(CPUX86State *env, int aflag)
 {
 }
 
-void helper_stgi(void)
+void helper_stgi(CPUX86State *env)
 {
 }
 
-void helper_clgi(void)
+void helper_clgi(CPUX86State *env)
 {
 }
 
-void helper_skinit(void)
+void helper_skinit(CPUX86State *env)
 {
 }
 
-void helper_invlpga(int aflag)
+void helper_invlpga(CPUX86State *env, int aflag)
 {
 }
 
-void helper_vmexit(uint32_t exit_code, uint64_t exit_info_1)
+void helper_vmexit(CPUX86State *env, uint32_t exit_code, uint64_t exit_info_1)
 {
 }
 
@@ -65,7 +65,8 @@ void cpu_vmexit(CPUX86State *nenv, uint32_t exit_code, uint64_t exit_info_1)
 {
 }
 
-void helper_svm_check_intercept_param(uint32_t type, uint64_t param)
+void helper_svm_check_intercept_param(CPUX86State *env, uint32_t type,
+                                      uint64_t param)
 {
 }
 
@@ -74,13 +75,13 @@ void cpu_svm_check_intercept_param(CPUX86State *env, uint32_t type,
 {
 }
 
-void helper_svm_check_io(uint32_t port, uint32_t param,
+void helper_svm_check_io(CPUX86State *env, uint32_t port, uint32_t param,
                          uint32_t next_eip_addend)
 {
 }
 #else
 
-static inline void svm_save_seg(target_phys_addr_t addr,
+static inline void svm_save_seg(CPUX86State *env, target_phys_addr_t addr,
                                 const SegmentCache *sc)
 {
     stw_phys(addr + offsetof(struct vmcb_seg, selector),
@@ -93,7 +94,8 @@ static inline void svm_save_seg(target_phys_addr_t addr,
              ((sc->flags >> 8) & 0xff) | ((sc->flags >> 12) & 0x0f00));
 }
 
-static inline void svm_load_seg(target_phys_addr_t addr, SegmentCache *sc)
+static inline void svm_load_seg(CPUX86State *env, target_phys_addr_t addr,
+                                SegmentCache *sc)
 {
     unsigned int flags;
 
@@ -104,23 +106,23 @@ static inline void svm_load_seg(target_phys_addr_t addr, SegmentCache *sc)
     sc->flags = ((flags & 0xff) << 8) | ((flags & 0x0f00) << 12);
 }
 
-static inline void svm_load_seg_cache(target_phys_addr_t addr,
-                                      CPUX86State *env, int seg_reg)
+static inline void svm_load_seg_cache(CPUX86State *env, target_phys_addr_t addr,
+                                      int seg_reg)
 {
     SegmentCache sc1, *sc = &sc1;
 
-    svm_load_seg(addr, sc);
+    svm_load_seg(env, addr, sc);
     cpu_x86_load_seg_cache(env, seg_reg, sc->selector,
                            sc->base, sc->limit, sc->flags);
 }
 
-void helper_vmrun(int aflag, int next_eip_addend)
+void helper_vmrun(CPUX86State *env, int aflag, int next_eip_addend)
 {
     target_ulong addr;
     uint32_t event_inj;
     uint32_t int_ctl;
 
-    helper_svm_check_intercept_param(SVM_EXIT_VMRUN, 0);
+    cpu_svm_check_intercept_param(env, SVM_EXIT_VMRUN, 0);
 
     if (aflag == 2) {
         addr = EAX;
@@ -154,13 +156,13 @@ void helper_vmrun(int aflag, int next_eip_addend)
     stq_phys(env->vm_hsave + offsetof(struct vmcb, save.rflags),
              cpu_compute_eflags(env));
 
-    svm_save_seg(env->vm_hsave + offsetof(struct vmcb, save.es),
+    svm_save_seg(env, env->vm_hsave + offsetof(struct vmcb, save.es),
                  &env->segs[R_ES]);
-    svm_save_seg(env->vm_hsave + offsetof(struct vmcb, save.cs),
+    svm_save_seg(env, env->vm_hsave + offsetof(struct vmcb, save.cs),
                  &env->segs[R_CS]);
-    svm_save_seg(env->vm_hsave + offsetof(struct vmcb, save.ss),
+    svm_save_seg(env, env->vm_hsave + offsetof(struct vmcb, save.ss),
                  &env->segs[R_SS]);
-    svm_save_seg(env->vm_hsave + offsetof(struct vmcb, save.ds),
+    svm_save_seg(env, env->vm_hsave + offsetof(struct vmcb, save.ds),
                  &env->segs[R_DS]);
 
     stq_phys(env->vm_hsave + offsetof(struct vmcb, save.rip),
@@ -233,14 +235,14 @@ void helper_vmrun(int aflag, int next_eip_addend)
                     ~(CC_O | CC_S | CC_Z | CC_A | CC_P | CC_C | DF_MASK));
     CC_OP = CC_OP_EFLAGS;
 
-    svm_load_seg_cache(env->vm_vmcb + offsetof(struct vmcb, save.es),
-                       env, R_ES);
-    svm_load_seg_cache(env->vm_vmcb + offsetof(struct vmcb, save.cs),
-                       env, R_CS);
-    svm_load_seg_cache(env->vm_vmcb + offsetof(struct vmcb, save.ss),
-                       env, R_SS);
-    svm_load_seg_cache(env->vm_vmcb + offsetof(struct vmcb, save.ds),
-                       env, R_DS);
+    svm_load_seg_cache(env, env->vm_vmcb + offsetof(struct vmcb, save.es),
+                       R_ES);
+    svm_load_seg_cache(env, env->vm_vmcb + offsetof(struct vmcb, save.cs),
+                       R_CS);
+    svm_load_seg_cache(env, env->vm_vmcb + offsetof(struct vmcb, save.ss),
+                       R_SS);
+    svm_load_seg_cache(env, env->vm_vmcb + offsetof(struct vmcb, save.ds),
+                       R_DS);
 
     EIP = ldq_phys(env->vm_vmcb + offsetof(struct vmcb, save.rip));
     env->eip = EIP;
@@ -320,17 +322,17 @@ void helper_vmrun(int aflag, int next_eip_addend)
     }
 }
 
-void helper_vmmcall(void)
+void helper_vmmcall(CPUX86State *env)
 {
-    helper_svm_check_intercept_param(SVM_EXIT_VMMCALL, 0);
+    cpu_svm_check_intercept_param(env, SVM_EXIT_VMMCALL, 0);
     raise_exception(env, EXCP06_ILLOP);
 }
 
-void helper_vmload(int aflag)
+void helper_vmload(CPUX86State *env, int aflag)
 {
     target_ulong addr;
 
-    helper_svm_check_intercept_param(SVM_EXIT_VMLOAD, 0);
+    cpu_svm_check_intercept_param(env, SVM_EXIT_VMLOAD, 0);
 
     if (aflag == 2) {
         addr = EAX;
@@ -340,17 +342,14 @@ void helper_vmload(int aflag)
 
     qemu_log_mask(CPU_LOG_TB_IN_ASM, "vmload! " TARGET_FMT_lx
                   "\nFS: %016" PRIx64 " | " TARGET_FMT_lx "\n",
-                  addr, ldq_phys(addr + offsetof(struct vmcb, save.fs.base)),
+                  addr, ldq_phys(addr + offsetof(struct vmcb,
+                                                          save.fs.base)),
                   env->segs[R_FS].base);
 
-    svm_load_seg_cache(addr + offsetof(struct vmcb, save.fs),
-                       env, R_FS);
-    svm_load_seg_cache(addr + offsetof(struct vmcb, save.gs),
-                       env, R_GS);
-    svm_load_seg(addr + offsetof(struct vmcb, save.tr),
-                 &env->tr);
-    svm_load_seg(addr + offsetof(struct vmcb, save.ldtr),
-                 &env->ldt);
+    svm_load_seg_cache(env, addr + offsetof(struct vmcb, save.fs), R_FS);
+    svm_load_seg_cache(env, addr + offsetof(struct vmcb, save.gs), R_GS);
+    svm_load_seg(env, addr + offsetof(struct vmcb, save.tr), &env->tr);
+    svm_load_seg(env, addr + offsetof(struct vmcb, save.ldtr), &env->ldt);
 
 #ifdef TARGET_X86_64
     env->kernelgsbase = ldq_phys(addr + offsetof(struct vmcb,
@@ -367,11 +366,11 @@ void helper_vmload(int aflag)
                                                  save.sysenter_eip));
 }
 
-void helper_vmsave(int aflag)
+void helper_vmsave(CPUX86State *env, int aflag)
 {
     target_ulong addr;
 
-    helper_svm_check_intercept_param(SVM_EXIT_VMSAVE, 0);
+    cpu_svm_check_intercept_param(env, SVM_EXIT_VMSAVE, 0);
 
     if (aflag == 2) {
         addr = EAX;
@@ -384,13 +383,13 @@ void helper_vmsave(int aflag)
                   addr, ldq_phys(addr + offsetof(struct vmcb, save.fs.base)),
                   env->segs[R_FS].base);
 
-    svm_save_seg(addr + offsetof(struct vmcb, save.fs),
+    svm_save_seg(env, addr + offsetof(struct vmcb, save.fs),
                  &env->segs[R_FS]);
-    svm_save_seg(addr + offsetof(struct vmcb, save.gs),
+    svm_save_seg(env, addr + offsetof(struct vmcb, save.gs),
                  &env->segs[R_GS]);
-    svm_save_seg(addr + offsetof(struct vmcb, save.tr),
+    svm_save_seg(env, addr + offsetof(struct vmcb, save.tr),
                  &env->tr);
-    svm_save_seg(addr + offsetof(struct vmcb, save.ldtr),
+    svm_save_seg(env, addr + offsetof(struct vmcb, save.ldtr),
                  &env->ldt);
 
 #ifdef TARGET_X86_64
@@ -408,30 +407,30 @@ void helper_vmsave(int aflag)
              env->sysenter_eip);
 }
 
-void helper_stgi(void)
+void helper_stgi(CPUX86State *env)
 {
-    helper_svm_check_intercept_param(SVM_EXIT_STGI, 0);
+    cpu_svm_check_intercept_param(env, SVM_EXIT_STGI, 0);
     env->hflags2 |= HF2_GIF_MASK;
 }
 
-void helper_clgi(void)
+void helper_clgi(CPUX86State *env)
 {
-    helper_svm_check_intercept_param(SVM_EXIT_CLGI, 0);
+    cpu_svm_check_intercept_param(env, SVM_EXIT_CLGI, 0);
     env->hflags2 &= ~HF2_GIF_MASK;
 }
 
-void helper_skinit(void)
+void helper_skinit(CPUX86State *env)
 {
-    helper_svm_check_intercept_param(SVM_EXIT_SKINIT, 0);
+    cpu_svm_check_intercept_param(env, SVM_EXIT_SKINIT, 0);
     /* XXX: not implemented */
     raise_exception(env, EXCP06_ILLOP);
 }
 
-void helper_invlpga(int aflag)
+void helper_invlpga(CPUX86State *env, int aflag)
 {
     target_ulong addr;
 
-    helper_svm_check_intercept_param(SVM_EXIT_INVLPGA, 0);
+    cpu_svm_check_intercept_param(env, SVM_EXIT_INVLPGA, 0);
 
     if (aflag == 2) {
         addr = EAX;
@@ -444,7 +443,8 @@ void helper_invlpga(int aflag)
     tlb_flush_page(env, addr);
 }
 
-void helper_svm_check_intercept_param(uint32_t type, uint64_t param)
+void helper_svm_check_intercept_param(CPUX86State *env, uint32_t type,
+                                      uint64_t param)
 {
     if (likely(!(env->hflags & HF_SVMI_MASK))) {
         return;
@@ -452,27 +452,27 @@ void helper_svm_check_intercept_param(uint32_t type, uint64_t param)
     switch (type) {
     case SVM_EXIT_READ_CR0 ... SVM_EXIT_READ_CR0 + 8:
         if (env->intercept_cr_read & (1 << (type - SVM_EXIT_READ_CR0))) {
-            helper_vmexit(type, param);
+            helper_vmexit(env, type, param);
         }
         break;
     case SVM_EXIT_WRITE_CR0 ... SVM_EXIT_WRITE_CR0 + 8:
         if (env->intercept_cr_write & (1 << (type - SVM_EXIT_WRITE_CR0))) {
-            helper_vmexit(type, param);
+            helper_vmexit(env, type, param);
         }
         break;
     case SVM_EXIT_READ_DR0 ... SVM_EXIT_READ_DR0 + 7:
         if (env->intercept_dr_read & (1 << (type - SVM_EXIT_READ_DR0))) {
-            helper_vmexit(type, param);
+            helper_vmexit(env, type, param);
         }
         break;
     case SVM_EXIT_WRITE_DR0 ... SVM_EXIT_WRITE_DR0 + 7:
         if (env->intercept_dr_write & (1 << (type - SVM_EXIT_WRITE_DR0))) {
-            helper_vmexit(type, param);
+            helper_vmexit(env, type, param);
         }
         break;
     case SVM_EXIT_EXCP_BASE ... SVM_EXIT_EXCP_BASE + 31:
         if (env->intercept_exceptions & (1 << (type - SVM_EXIT_EXCP_BASE))) {
-            helper_vmexit(type, param);
+            helper_vmexit(env, type, param);
         }
         break;
     case SVM_EXIT_MSR:
@@ -499,36 +499,31 @@ void helper_svm_check_intercept_param(uint32_t type, uint64_t param)
                 t0 %= 8;
                 break;
             default:
-                helper_vmexit(type, param);
+                helper_vmexit(env, type, param);
                 t0 = 0;
                 t1 = 0;
                 break;
             }
             if (ldub_phys(addr + t1) & ((1 << param) << t0)) {
-                helper_vmexit(type, param);
+                helper_vmexit(env, type, param);
             }
         }
         break;
     default:
         if (env->intercept & (1ULL << (type - SVM_EXIT_INTR))) {
-            helper_vmexit(type, param);
+            helper_vmexit(env, type, param);
         }
         break;
     }
 }
 
-void cpu_svm_check_intercept_param(CPUX86State *env1, uint32_t type,
+void cpu_svm_check_intercept_param(CPUX86State *env, uint32_t type,
                                    uint64_t param)
 {
-    CPUX86State *saved_env;
-
-    saved_env = env;
-    env = env1;
-    helper_svm_check_intercept_param(type, param);
-    env = saved_env;
+    helper_svm_check_intercept_param(env, type, param);
 }
 
-void helper_svm_check_io(uint32_t port, uint32_t param,
+void helper_svm_check_io(CPUX86State *env, uint32_t port, uint32_t param,
                          uint32_t next_eip_addend)
 {
     if (env->intercept & (1ULL << (SVM_EXIT_IOIO - SVM_EXIT_INTR))) {
@@ -541,13 +536,13 @@ void helper_svm_check_io(uint32_t port, uint32_t param,
             /* next EIP */
             stq_phys(env->vm_vmcb + offsetof(struct vmcb, control.exit_info_2),
                      env->eip + next_eip_addend);
-            helper_vmexit(SVM_EXIT_IOIO, param | (port << 16));
+            helper_vmexit(env, SVM_EXIT_IOIO, param | (port << 16));
         }
     }
 }
 
 /* Note: currently only 32 bits of exit_code are used */
-void helper_vmexit(uint32_t exit_code, uint64_t exit_info_1)
+void helper_vmexit(CPUX86State *env, uint32_t exit_code, uint64_t exit_info_1)
 {
     uint32_t int_ctl;
 
@@ -567,13 +562,13 @@ void helper_vmexit(uint32_t exit_code, uint64_t exit_info_1)
     }
 
     /* Save the VM state in the vmcb */
-    svm_save_seg(env->vm_vmcb + offsetof(struct vmcb, save.es),
+    svm_save_seg(env, env->vm_vmcb + offsetof(struct vmcb, save.es),
                  &env->segs[R_ES]);
-    svm_save_seg(env->vm_vmcb + offsetof(struct vmcb, save.cs),
+    svm_save_seg(env, env->vm_vmcb + offsetof(struct vmcb, save.cs),
                  &env->segs[R_CS]);
-    svm_save_seg(env->vm_vmcb + offsetof(struct vmcb, save.ss),
+    svm_save_seg(env, env->vm_vmcb + offsetof(struct vmcb, save.ss),
                  &env->segs[R_SS]);
-    svm_save_seg(env->vm_vmcb + offsetof(struct vmcb, save.ds),
+    svm_save_seg(env, env->vm_vmcb + offsetof(struct vmcb, save.ds),
                  &env->segs[R_DS]);
 
     stq_phys(env->vm_vmcb + offsetof(struct vmcb, save.gdtr.base),
@@ -602,7 +597,8 @@ void helper_vmexit(uint32_t exit_code, uint64_t exit_info_1)
 
     stq_phys(env->vm_vmcb + offsetof(struct vmcb, save.rflags),
              cpu_compute_eflags(env));
-    stq_phys(env->vm_vmcb + offsetof(struct vmcb, save.rip), env->eip);
+    stq_phys(env->vm_vmcb + offsetof(struct vmcb, save.rip),
+             env->eip);
     stq_phys(env->vm_vmcb + offsetof(struct vmcb, save.rsp), ESP);
     stq_phys(env->vm_vmcb + offsetof(struct vmcb, save.rax), EAX);
     stq_phys(env->vm_vmcb + offsetof(struct vmcb, save.dr7), env->dr[7]);
@@ -645,14 +641,14 @@ void helper_vmexit(uint32_t exit_code, uint64_t exit_info_1)
                     ~(CC_O | CC_S | CC_Z | CC_A | CC_P | CC_C | DF_MASK));
     CC_OP = CC_OP_EFLAGS;
 
-    svm_load_seg_cache(env->vm_hsave + offsetof(struct vmcb, save.es),
-                       env, R_ES);
-    svm_load_seg_cache(env->vm_hsave + offsetof(struct vmcb, save.cs),
-                       env, R_CS);
-    svm_load_seg_cache(env->vm_hsave + offsetof(struct vmcb, save.ss),
-                       env, R_SS);
-    svm_load_seg_cache(env->vm_hsave + offsetof(struct vmcb, save.ds),
-                       env, R_DS);
+    svm_load_seg_cache(env, env->vm_hsave + offsetof(struct vmcb, save.es),
+                       R_ES);
+    svm_load_seg_cache(env, env->vm_hsave + offsetof(struct vmcb, save.cs),
+                       R_CS);
+    svm_load_seg_cache(env, env->vm_hsave + offsetof(struct vmcb, save.ss),
+                       R_SS);
+    svm_load_seg_cache(env, env->vm_hsave + offsetof(struct vmcb, save.ds),
+                       R_DS);
 
     EIP = ldq_phys(env->vm_hsave + offsetof(struct vmcb, save.rip));
     ESP = ldq_phys(env->vm_hsave + offsetof(struct vmcb, save.rsp));
@@ -707,10 +703,9 @@ void helper_vmexit(uint32_t exit_code, uint64_t exit_info_1)
     cpu_loop_exit(env);
 }
 
-void cpu_vmexit(CPUX86State *nenv, uint32_t exit_code, uint64_t exit_info_1)
+void cpu_vmexit(CPUX86State *env, uint32_t exit_code, uint64_t exit_info_1)
 {
-    env = nenv;
-    helper_vmexit(exit_code, exit_info_1);
+    helper_vmexit(env, exit_code, exit_info_1);
 }
 
 #endif
diff --git a/target-i386/translate.c b/target-i386/translate.c
index 37732e0..9f4c712 100644
--- a/target-i386/translate.c
+++ b/target-i386/translate.c
@@ -754,7 +754,8 @@ static void gen_check_io(DisasContext *s, int ot, target_ulong cur_eip,
         svm_flags |= (1 << (4 + ot));
         next_eip = s->pc - s->cs_base;
         tcg_gen_trunc_tl_i32(cpu_tmp2_i32, cpu_T[0]);
-        gen_helper_svm_check_io(cpu_tmp2_i32, tcg_const_i32(svm_flags),
+        gen_helper_svm_check_io(cpu_env, cpu_tmp2_i32,
+                                tcg_const_i32(svm_flags),
                                 tcg_const_i32(next_eip - cur_eip));
     }
 }
@@ -2465,7 +2466,7 @@ gen_svm_check_intercept_param(DisasContext *s, target_ulong pc_start,
     if (s->cc_op != CC_OP_DYNAMIC)
         gen_op_set_cc_op(s->cc_op);
     gen_jmp_im(pc_start - s->cs_base);
-    gen_helper_svm_check_intercept_param(tcg_const_i32(type),
+    gen_helper_svm_check_intercept_param(cpu_env, tcg_const_i32(type),
                                          tcg_const_i64(param));
 }
 
@@ -7225,7 +7226,7 @@ static target_ulong disas_insn(DisasContext *s, target_ulong pc_start)
                         gen_exception(s, EXCP0D_GPF, pc_start - s->cs_base);
                         break;
                     } else {
-                        gen_helper_vmrun(tcg_const_i32(s->aflag),
+                        gen_helper_vmrun(cpu_env, tcg_const_i32(s->aflag),
                                          tcg_const_i32(s->pc - pc_start));
                         tcg_gen_exit_tb(0);
                         s->is_jmp = DISAS_TB_JUMP;
@@ -7234,7 +7235,7 @@ static target_ulong disas_insn(DisasContext *s, target_ulong pc_start)
                 case 1: /* VMMCALL */
                     if (!(s->flags & HF_SVME_MASK))
                         goto illegal_op;
-                    gen_helper_vmmcall();
+                    gen_helper_vmmcall(cpu_env);
                     break;
                 case 2: /* VMLOAD */
                     if (!(s->flags & HF_SVME_MASK) || !s->pe)
@@ -7243,7 +7244,7 @@ static target_ulong disas_insn(DisasContext *s, target_ulong pc_start)
                         gen_exception(s, EXCP0D_GPF, pc_start - s->cs_base);
                         break;
                     } else {
-                        gen_helper_vmload(tcg_const_i32(s->aflag));
+                        gen_helper_vmload(cpu_env, tcg_const_i32(s->aflag));
                     }
                     break;
                 case 3: /* VMSAVE */
@@ -7253,7 +7254,7 @@ static target_ulong disas_insn(DisasContext *s, target_ulong pc_start)
                         gen_exception(s, EXCP0D_GPF, pc_start - s->cs_base);
                         break;
                     } else {
-                        gen_helper_vmsave(tcg_const_i32(s->aflag));
+                        gen_helper_vmsave(cpu_env, tcg_const_i32(s->aflag));
                     }
                     break;
                 case 4: /* STGI */
@@ -7265,7 +7266,7 @@ static target_ulong disas_insn(DisasContext *s, target_ulong pc_start)
                         gen_exception(s, EXCP0D_GPF, pc_start - s->cs_base);
                         break;
                     } else {
-                        gen_helper_stgi();
+                        gen_helper_stgi(cpu_env);
                     }
                     break;
                 case 5: /* CLGI */
@@ -7275,7 +7276,7 @@ static target_ulong disas_insn(DisasContext *s, target_ulong pc_start)
                         gen_exception(s, EXCP0D_GPF, pc_start - s->cs_base);
                         break;
                     } else {
-                        gen_helper_clgi();
+                        gen_helper_clgi(cpu_env);
                     }
                     break;
                 case 6: /* SKINIT */
@@ -7283,7 +7284,7 @@ static target_ulong disas_insn(DisasContext *s, target_ulong pc_start)
                          !(s->cpuid_ext3_features & CPUID_EXT3_SKINIT)) || 
                         !s->pe)
                         goto illegal_op;
-                    gen_helper_skinit();
+                    gen_helper_skinit(cpu_env);
                     break;
                 case 7: /* INVLPGA */
                     if (!(s->flags & HF_SVME_MASK) || !s->pe)
@@ -7292,7 +7293,7 @@ static target_ulong disas_insn(DisasContext *s, target_ulong pc_start)
                         gen_exception(s, EXCP0D_GPF, pc_start - s->cs_base);
                         break;
                     } else {
-                        gen_helper_invlpga(tcg_const_i32(s->aflag));
+                        gen_helper_invlpga(cpu_env, tcg_const_i32(s->aflag));
                     }
                     break;
                 default:
commit 7923057bae23e44f75a52ce3735c3bd5d55872c1
Author: Blue Swirl <blauwirbel at gmail.com>
Date:   Sun Apr 29 14:11:56 2012 +0000

    x86: avoid AREG0 for integer helpers
    
    Add an explicit CPUX86State parameter instead of relying on AREG0.
    
    Signed-off-by: Blue Swirl <blauwirbel at gmail.com>

diff --git a/target-i386/Makefile.objs b/target-i386/Makefile.objs
index 54a6556..d39ec8e 100644
--- a/target-i386/Makefile.objs
+++ b/target-i386/Makefile.objs
@@ -7,7 +7,6 @@ obj-$(CONFIG_NO_KVM) += kvm-stub.o
 obj-$(CONFIG_LINUX_USER) += ioport-user.o
 obj-$(CONFIG_BSD_USER) += ioport-user.o
 
-$(obj)/int_helper.o: QEMU_CFLAGS += $(HELPER_CFLAGS)
 $(obj)/svm_helper.o: QEMU_CFLAGS += $(HELPER_CFLAGS)
 $(obj)/smm_helper.o: QEMU_CFLAGS += $(HELPER_CFLAGS)
 $(obj)/misc_helper.o: QEMU_CFLAGS += $(HELPER_CFLAGS)
diff --git a/target-i386/helper.h b/target-i386/helper.h
index d647e54..67c81bf 100644
--- a/target-i386/helper.h
+++ b/target-i386/helper.h
@@ -7,26 +7,26 @@ DEF_HELPER_0(lock, void)
 DEF_HELPER_0(unlock, void)
 DEF_HELPER_3(write_eflags, void, env, tl, i32)
 DEF_HELPER_1(read_eflags, tl, env)
-DEF_HELPER_1(divb_AL, void, tl)
-DEF_HELPER_1(idivb_AL, void, tl)
-DEF_HELPER_1(divw_AX, void, tl)
-DEF_HELPER_1(idivw_AX, void, tl)
-DEF_HELPER_1(divl_EAX, void, tl)
-DEF_HELPER_1(idivl_EAX, void, tl)
+DEF_HELPER_2(divb_AL, void, env, tl)
+DEF_HELPER_2(idivb_AL, void, env, tl)
+DEF_HELPER_2(divw_AX, void, env, tl)
+DEF_HELPER_2(idivw_AX, void, env, tl)
+DEF_HELPER_2(divl_EAX, void, env, tl)
+DEF_HELPER_2(idivl_EAX, void, env, tl)
 #ifdef TARGET_X86_64
-DEF_HELPER_1(mulq_EAX_T0, void, tl)
-DEF_HELPER_1(imulq_EAX_T0, void, tl)
-DEF_HELPER_2(imulq_T0_T1, tl, tl, tl)
-DEF_HELPER_1(divq_EAX, void, tl)
-DEF_HELPER_1(idivq_EAX, void, tl)
+DEF_HELPER_2(mulq_EAX_T0, void, env, tl)
+DEF_HELPER_2(imulq_EAX_T0, void, env, tl)
+DEF_HELPER_3(imulq_T0_T1, tl, env, tl, tl)
+DEF_HELPER_2(divq_EAX, void, env, tl)
+DEF_HELPER_2(idivq_EAX, void, env, tl)
 #endif
 
-DEF_HELPER_1(aam, void, int)
-DEF_HELPER_1(aad, void, int)
-DEF_HELPER_0(aaa, void)
-DEF_HELPER_0(aas, void)
-DEF_HELPER_0(daa, void)
-DEF_HELPER_0(das, void)
+DEF_HELPER_2(aam, void, env, int)
+DEF_HELPER_2(aad, void, env, int)
+DEF_HELPER_1(aaa, void, env)
+DEF_HELPER_1(aas, void, env)
+DEF_HELPER_1(daa, void, env)
+DEF_HELPER_1(das, void, env)
 
 DEF_HELPER_1(lsl, tl, tl)
 DEF_HELPER_1(lar, tl, tl)
@@ -207,15 +207,15 @@ DEF_HELPER_3(movq, void, env, ptr, ptr)
 #define SHIFT 1
 #include "ops_sse_header.h"
 
-DEF_HELPER_2(rclb, tl, tl, tl)
-DEF_HELPER_2(rclw, tl, tl, tl)
-DEF_HELPER_2(rcll, tl, tl, tl)
-DEF_HELPER_2(rcrb, tl, tl, tl)
-DEF_HELPER_2(rcrw, tl, tl, tl)
-DEF_HELPER_2(rcrl, tl, tl, tl)
+DEF_HELPER_3(rclb, tl, env, tl, tl)
+DEF_HELPER_3(rclw, tl, env, tl, tl)
+DEF_HELPER_3(rcll, tl, env, tl, tl)
+DEF_HELPER_3(rcrb, tl, env, tl, tl)
+DEF_HELPER_3(rcrw, tl, env, tl, tl)
+DEF_HELPER_3(rcrl, tl, env, tl, tl)
 #ifdef TARGET_X86_64
-DEF_HELPER_2(rclq, tl, tl, tl)
-DEF_HELPER_2(rcrq, tl, tl, tl)
+DEF_HELPER_3(rclq, tl, env, tl, tl)
+DEF_HELPER_3(rcrq, tl, env, tl, tl)
 #endif
 
 #include "def-helper.h"
diff --git a/target-i386/int_helper.c b/target-i386/int_helper.c
index 1a13e4e..f39747e 100644
--- a/target-i386/int_helper.c
+++ b/target-i386/int_helper.c
@@ -18,7 +18,6 @@
  */
 
 #include "cpu.h"
-#include "dyngen-exec.h"
 #include "host-utils.h"
 #include "helper.h"
 
@@ -42,7 +41,7 @@ static const uint8_t rclw_table[32] = {
 
 /* division, flags are undefined */
 
-void helper_divb_AL(target_ulong t0)
+void helper_divb_AL(CPUX86State *env, target_ulong t0)
 {
     unsigned int num, den, q, r;
 
@@ -60,7 +59,7 @@ void helper_divb_AL(target_ulong t0)
     EAX = (EAX & ~0xffff) | (r << 8) | q;
 }
 
-void helper_idivb_AL(target_ulong t0)
+void helper_idivb_AL(CPUX86State *env, target_ulong t0)
 {
     int num, den, q, r;
 
@@ -78,7 +77,7 @@ void helper_idivb_AL(target_ulong t0)
     EAX = (EAX & ~0xffff) | (r << 8) | q;
 }
 
-void helper_divw_AX(target_ulong t0)
+void helper_divw_AX(CPUX86State *env, target_ulong t0)
 {
     unsigned int num, den, q, r;
 
@@ -97,7 +96,7 @@ void helper_divw_AX(target_ulong t0)
     EDX = (EDX & ~0xffff) | r;
 }
 
-void helper_idivw_AX(target_ulong t0)
+void helper_idivw_AX(CPUX86State *env, target_ulong t0)
 {
     int num, den, q, r;
 
@@ -116,7 +115,7 @@ void helper_idivw_AX(target_ulong t0)
     EDX = (EDX & ~0xffff) | r;
 }
 
-void helper_divl_EAX(target_ulong t0)
+void helper_divl_EAX(CPUX86State *env, target_ulong t0)
 {
     unsigned int den, r;
     uint64_t num, q;
@@ -135,7 +134,7 @@ void helper_divl_EAX(target_ulong t0)
     EDX = (uint32_t)r;
 }
 
-void helper_idivl_EAX(target_ulong t0)
+void helper_idivl_EAX(CPUX86State *env, target_ulong t0)
 {
     int den, r;
     int64_t num, q;
@@ -157,7 +156,7 @@ void helper_idivl_EAX(target_ulong t0)
 /* bcd */
 
 /* XXX: exception */
-void helper_aam(int base)
+void helper_aam(CPUX86State *env, int base)
 {
     int al, ah;
 
@@ -168,7 +167,7 @@ void helper_aam(int base)
     CC_DST = al;
 }
 
-void helper_aad(int base)
+void helper_aad(CPUX86State *env, int base)
 {
     int al, ah;
 
@@ -179,7 +178,7 @@ void helper_aad(int base)
     CC_DST = al;
 }
 
-void helper_aaa(void)
+void helper_aaa(CPUX86State *env)
 {
     int icarry;
     int al, ah, af;
@@ -203,7 +202,7 @@ void helper_aaa(void)
     CC_SRC = eflags;
 }
 
-void helper_aas(void)
+void helper_aas(CPUX86State *env)
 {
     int icarry;
     int al, ah, af;
@@ -227,7 +226,7 @@ void helper_aas(void)
     CC_SRC = eflags;
 }
 
-void helper_daa(void)
+void helper_daa(CPUX86State *env)
 {
     int old_al, al, af, cf;
     int eflags;
@@ -254,7 +253,7 @@ void helper_daa(void)
     CC_SRC = eflags;
 }
 
-void helper_das(void)
+void helper_das(CPUX86State *env)
 {
     int al, al1, af, cf;
     int eflags;
@@ -375,7 +374,7 @@ static int idiv64(uint64_t *plow, uint64_t *phigh, int64_t b)
     return 0;
 }
 
-void helper_mulq_EAX_T0(target_ulong t0)
+void helper_mulq_EAX_T0(CPUX86State *env, target_ulong t0)
 {
     uint64_t r0, r1;
 
@@ -386,7 +385,7 @@ void helper_mulq_EAX_T0(target_ulong t0)
     CC_SRC = r1;
 }
 
-void helper_imulq_EAX_T0(target_ulong t0)
+void helper_imulq_EAX_T0(CPUX86State *env, target_ulong t0)
 {
     uint64_t r0, r1;
 
@@ -397,7 +396,8 @@ void helper_imulq_EAX_T0(target_ulong t0)
     CC_SRC = ((int64_t)r1 != ((int64_t)r0 >> 63));
 }
 
-target_ulong helper_imulq_T0_T1(target_ulong t0, target_ulong t1)
+target_ulong helper_imulq_T0_T1(CPUX86State *env, target_ulong t0,
+                                target_ulong t1)
 {
     uint64_t r0, r1;
 
@@ -407,7 +407,7 @@ target_ulong helper_imulq_T0_T1(target_ulong t0, target_ulong t1)
     return r0;
 }
 
-void helper_divq_EAX(target_ulong t0)
+void helper_divq_EAX(CPUX86State *env, target_ulong t0)
 {
     uint64_t r0, r1;
 
@@ -423,7 +423,7 @@ void helper_divq_EAX(target_ulong t0)
     EDX = r1;
 }
 
-void helper_idivq_EAX(target_ulong t0)
+void helper_idivq_EAX(CPUX86State *env, target_ulong t0)
 {
     uint64_t r0, r1;
 
diff --git a/target-i386/shift_helper_template.h b/target-i386/shift_helper_template.h
index dacfdd2..dda0da3 100644
--- a/target-i386/shift_helper_template.h
+++ b/target-i386/shift_helper_template.h
@@ -41,7 +41,8 @@
 #error unhandled operand size
 #endif
 
-target_ulong glue(helper_rcl, SUFFIX)(target_ulong t0, target_ulong t1)
+target_ulong glue(helper_rcl, SUFFIX)(CPUX86State *env, target_ulong t0,
+                                      target_ulong t1)
 {
     int count, eflags;
     target_ulong src;
@@ -71,7 +72,8 @@ target_ulong glue(helper_rcl, SUFFIX)(target_ulong t0, target_ulong t1)
     return t0;
 }
 
-target_ulong glue(helper_rcr, SUFFIX)(target_ulong t0, target_ulong t1)
+target_ulong glue(helper_rcr, SUFFIX)(CPUX86State *env, target_ulong t0,
+                                      target_ulong t1)
 {
     int count, eflags;
     target_ulong src;
diff --git a/target-i386/translate.c b/target-i386/translate.c
index 15b5b63..37732e0 100644
--- a/target-i386/translate.c
+++ b/target-i386/translate.c
@@ -1773,20 +1773,36 @@ static void gen_rotc_rm_T1(DisasContext *s, int ot, int op1,
     
     if (is_right) {
         switch (ot) {
-        case 0: gen_helper_rcrb(cpu_T[0], cpu_T[0], cpu_T[1]); break;
-        case 1: gen_helper_rcrw(cpu_T[0], cpu_T[0], cpu_T[1]); break;
-        case 2: gen_helper_rcrl(cpu_T[0], cpu_T[0], cpu_T[1]); break;
+        case 0:
+            gen_helper_rcrb(cpu_T[0], cpu_env, cpu_T[0], cpu_T[1]);
+            break;
+        case 1:
+            gen_helper_rcrw(cpu_T[0], cpu_env, cpu_T[0], cpu_T[1]);
+            break;
+        case 2:
+            gen_helper_rcrl(cpu_T[0], cpu_env, cpu_T[0], cpu_T[1]);
+            break;
 #ifdef TARGET_X86_64
-        case 3: gen_helper_rcrq(cpu_T[0], cpu_T[0], cpu_T[1]); break;
+        case 3:
+            gen_helper_rcrq(cpu_T[0], cpu_env, cpu_T[0], cpu_T[1]);
+            break;
 #endif
         }
     } else {
         switch (ot) {
-        case 0: gen_helper_rclb(cpu_T[0], cpu_T[0], cpu_T[1]); break;
-        case 1: gen_helper_rclw(cpu_T[0], cpu_T[0], cpu_T[1]); break;
-        case 2: gen_helper_rcll(cpu_T[0], cpu_T[0], cpu_T[1]); break;
+        case 0:
+            gen_helper_rclb(cpu_T[0], cpu_env, cpu_T[0], cpu_T[1]);
+            break;
+        case 1:
+            gen_helper_rclw(cpu_T[0], cpu_env, cpu_T[0], cpu_T[1]);
+            break;
+        case 2:
+            gen_helper_rcll(cpu_T[0], cpu_env, cpu_T[0], cpu_T[1]);
+            break;
 #ifdef TARGET_X86_64
-        case 3: gen_helper_rclq(cpu_T[0], cpu_T[0], cpu_T[1]); break;
+        case 3:
+            gen_helper_rclq(cpu_T[0], cpu_env, cpu_T[0], cpu_T[1]);
+            break;
 #endif
         }
     }
@@ -4541,7 +4557,7 @@ static target_ulong disas_insn(DisasContext *s, target_ulong pc_start)
                 break;
 #ifdef TARGET_X86_64
             case OT_QUAD:
-                gen_helper_mulq_EAX_T0(cpu_T[0]);
+                gen_helper_mulq_EAX_T0(cpu_env, cpu_T[0]);
                 s->cc_op = CC_OP_MULQ;
                 break;
 #endif
@@ -4611,7 +4627,7 @@ static target_ulong disas_insn(DisasContext *s, target_ulong pc_start)
                 break;
 #ifdef TARGET_X86_64
             case OT_QUAD:
-                gen_helper_imulq_EAX_T0(cpu_T[0]);
+                gen_helper_imulq_EAX_T0(cpu_env, cpu_T[0]);
                 s->cc_op = CC_OP_MULQ;
                 break;
 #endif
@@ -4621,21 +4637,21 @@ static target_ulong disas_insn(DisasContext *s, target_ulong pc_start)
             switch(ot) {
             case OT_BYTE:
                 gen_jmp_im(pc_start - s->cs_base);
-                gen_helper_divb_AL(cpu_T[0]);
+                gen_helper_divb_AL(cpu_env, cpu_T[0]);
                 break;
             case OT_WORD:
                 gen_jmp_im(pc_start - s->cs_base);
-                gen_helper_divw_AX(cpu_T[0]);
+                gen_helper_divw_AX(cpu_env, cpu_T[0]);
                 break;
             default:
             case OT_LONG:
                 gen_jmp_im(pc_start - s->cs_base);
-                gen_helper_divl_EAX(cpu_T[0]);
+                gen_helper_divl_EAX(cpu_env, cpu_T[0]);
                 break;
 #ifdef TARGET_X86_64
             case OT_QUAD:
                 gen_jmp_im(pc_start - s->cs_base);
-                gen_helper_divq_EAX(cpu_T[0]);
+                gen_helper_divq_EAX(cpu_env, cpu_T[0]);
                 break;
 #endif
             }
@@ -4644,21 +4660,21 @@ static target_ulong disas_insn(DisasContext *s, target_ulong pc_start)
             switch(ot) {
             case OT_BYTE:
                 gen_jmp_im(pc_start - s->cs_base);
-                gen_helper_idivb_AL(cpu_T[0]);
+                gen_helper_idivb_AL(cpu_env, cpu_T[0]);
                 break;
             case OT_WORD:
                 gen_jmp_im(pc_start - s->cs_base);
-                gen_helper_idivw_AX(cpu_T[0]);
+                gen_helper_idivw_AX(cpu_env, cpu_T[0]);
                 break;
             default:
             case OT_LONG:
                 gen_jmp_im(pc_start - s->cs_base);
-                gen_helper_idivl_EAX(cpu_T[0]);
+                gen_helper_idivl_EAX(cpu_env, cpu_T[0]);
                 break;
 #ifdef TARGET_X86_64
             case OT_QUAD:
                 gen_jmp_im(pc_start - s->cs_base);
-                gen_helper_idivq_EAX(cpu_T[0]);
+                gen_helper_idivq_EAX(cpu_env, cpu_T[0]);
                 break;
 #endif
             }
@@ -4871,7 +4887,7 @@ static target_ulong disas_insn(DisasContext *s, target_ulong pc_start)
 
 #ifdef TARGET_X86_64
         if (ot == OT_QUAD) {
-            gen_helper_imulq_T0_T1(cpu_T[0], cpu_T[0], cpu_T[1]);
+            gen_helper_imulq_T0_T1(cpu_T[0], cpu_env, cpu_T[0], cpu_T[1]);
         } else
 #endif
         if (ot == OT_LONG) {
@@ -6727,7 +6743,7 @@ static target_ulong disas_insn(DisasContext *s, target_ulong pc_start)
             goto illegal_op;
         if (s->cc_op != CC_OP_DYNAMIC)
             gen_op_set_cc_op(s->cc_op);
-        gen_helper_daa();
+        gen_helper_daa(cpu_env);
         s->cc_op = CC_OP_EFLAGS;
         break;
     case 0x2f: /* das */
@@ -6735,7 +6751,7 @@ static target_ulong disas_insn(DisasContext *s, target_ulong pc_start)
             goto illegal_op;
         if (s->cc_op != CC_OP_DYNAMIC)
             gen_op_set_cc_op(s->cc_op);
-        gen_helper_das();
+        gen_helper_das(cpu_env);
         s->cc_op = CC_OP_EFLAGS;
         break;
     case 0x37: /* aaa */
@@ -6743,7 +6759,7 @@ static target_ulong disas_insn(DisasContext *s, target_ulong pc_start)
             goto illegal_op;
         if (s->cc_op != CC_OP_DYNAMIC)
             gen_op_set_cc_op(s->cc_op);
-        gen_helper_aaa();
+        gen_helper_aaa(cpu_env);
         s->cc_op = CC_OP_EFLAGS;
         break;
     case 0x3f: /* aas */
@@ -6751,7 +6767,7 @@ static target_ulong disas_insn(DisasContext *s, target_ulong pc_start)
             goto illegal_op;
         if (s->cc_op != CC_OP_DYNAMIC)
             gen_op_set_cc_op(s->cc_op);
-        gen_helper_aas();
+        gen_helper_aas(cpu_env);
         s->cc_op = CC_OP_EFLAGS;
         break;
     case 0xd4: /* aam */
@@ -6761,7 +6777,7 @@ static target_ulong disas_insn(DisasContext *s, target_ulong pc_start)
         if (val == 0) {
             gen_exception(s, EXCP00_DIVZ, pc_start - s->cs_base);
         } else {
-            gen_helper_aam(tcg_const_i32(val));
+            gen_helper_aam(cpu_env, tcg_const_i32(val));
             s->cc_op = CC_OP_LOGICB;
         }
         break;
@@ -6769,7 +6785,7 @@ static target_ulong disas_insn(DisasContext *s, target_ulong pc_start)
         if (CODE64(s))
             goto illegal_op;
         val = ldub_code(s->pc++);
-        gen_helper_aad(tcg_const_i32(val));
+        gen_helper_aad(cpu_env, tcg_const_i32(val));
         s->cc_op = CC_OP_LOGICB;
         break;
         /************************/
commit f0967a1add1e01df75607b9de5ef6cf83bfa0f82
Author: Blue Swirl <blauwirbel at gmail.com>
Date:   Sun Apr 29 12:45:34 2012 +0000

    x86: avoid AREG0 for condition code helpers
    
    Add an explicit CPUX86State parameter instead of relying on AREG0.
    
    Signed-off-by: Blue Swirl <blauwirbel at gmail.com>

diff --git a/target-i386/Makefile.objs b/target-i386/Makefile.objs
index 88e7280..54a6556 100644
--- a/target-i386/Makefile.objs
+++ b/target-i386/Makefile.objs
@@ -7,7 +7,6 @@ obj-$(CONFIG_NO_KVM) += kvm-stub.o
 obj-$(CONFIG_LINUX_USER) += ioport-user.o
 obj-$(CONFIG_BSD_USER) += ioport-user.o
 
-$(obj)/cc_helper.o: QEMU_CFLAGS += $(HELPER_CFLAGS)
 $(obj)/int_helper.o: QEMU_CFLAGS += $(HELPER_CFLAGS)
 $(obj)/svm_helper.o: QEMU_CFLAGS += $(HELPER_CFLAGS)
 $(obj)/smm_helper.o: QEMU_CFLAGS += $(HELPER_CFLAGS)
diff --git a/target-i386/cc_helper.c b/target-i386/cc_helper.c
index ff654bc..07892f9 100644
--- a/target-i386/cc_helper.c
+++ b/target-i386/cc_helper.c
@@ -18,7 +18,6 @@
  */
 
 #include "cpu.h"
-#include "dyngen-exec.h"
 #include "helper.h"
 
 const uint8_t parity_table[256] = {
@@ -76,184 +75,177 @@ const uint8_t parity_table[256] = {
 
 #endif
 
-static int compute_all_eflags(void)
+static int compute_all_eflags(CPUX86State *env)
 {
     return CC_SRC;
 }
 
-static int compute_c_eflags(void)
+static int compute_c_eflags(CPUX86State *env)
 {
     return CC_SRC & CC_C;
 }
 
-uint32_t helper_cc_compute_all(int op)
+uint32_t helper_cc_compute_all(CPUX86State *env, int op)
 {
     switch (op) {
     default: /* should never happen */
         return 0;
 
     case CC_OP_EFLAGS:
-        return compute_all_eflags();
+        return compute_all_eflags(env);
 
     case CC_OP_MULB:
-        return compute_all_mulb();
+        return compute_all_mulb(env);
     case CC_OP_MULW:
-        return compute_all_mulw();
+        return compute_all_mulw(env);
     case CC_OP_MULL:
-        return compute_all_mull();
+        return compute_all_mull(env);
 
     case CC_OP_ADDB:
-        return compute_all_addb();
+        return compute_all_addb(env);
     case CC_OP_ADDW:
-        return compute_all_addw();
+        return compute_all_addw(env);
     case CC_OP_ADDL:
-        return compute_all_addl();
+        return compute_all_addl(env);
 
     case CC_OP_ADCB:
-        return compute_all_adcb();
+        return compute_all_adcb(env);
     case CC_OP_ADCW:
-        return compute_all_adcw();
+        return compute_all_adcw(env);
     case CC_OP_ADCL:
-        return compute_all_adcl();
+        return compute_all_adcl(env);
 
     case CC_OP_SUBB:
-        return compute_all_subb();
+        return compute_all_subb(env);
     case CC_OP_SUBW:
-        return compute_all_subw();
+        return compute_all_subw(env);
     case CC_OP_SUBL:
-        return compute_all_subl();
+        return compute_all_subl(env);
 
     case CC_OP_SBBB:
-        return compute_all_sbbb();
+        return compute_all_sbbb(env);
     case CC_OP_SBBW:
-        return compute_all_sbbw();
+        return compute_all_sbbw(env);
     case CC_OP_SBBL:
-        return compute_all_sbbl();
+        return compute_all_sbbl(env);
 
     case CC_OP_LOGICB:
-        return compute_all_logicb();
+        return compute_all_logicb(env);
     case CC_OP_LOGICW:
-        return compute_all_logicw();
+        return compute_all_logicw(env);
     case CC_OP_LOGICL:
-        return compute_all_logicl();
+        return compute_all_logicl(env);
 
     case CC_OP_INCB:
-        return compute_all_incb();
+        return compute_all_incb(env);
     case CC_OP_INCW:
-        return compute_all_incw();
+        return compute_all_incw(env);
     case CC_OP_INCL:
-        return compute_all_incl();
+        return compute_all_incl(env);
 
     case CC_OP_DECB:
-        return compute_all_decb();
+        return compute_all_decb(env);
     case CC_OP_DECW:
-        return compute_all_decw();
+        return compute_all_decw(env);
     case CC_OP_DECL:
-        return compute_all_decl();
+        return compute_all_decl(env);
 
     case CC_OP_SHLB:
-        return compute_all_shlb();
+        return compute_all_shlb(env);
     case CC_OP_SHLW:
-        return compute_all_shlw();
+        return compute_all_shlw(env);
     case CC_OP_SHLL:
-        return compute_all_shll();
+        return compute_all_shll(env);
 
     case CC_OP_SARB:
-        return compute_all_sarb();
+        return compute_all_sarb(env);
     case CC_OP_SARW:
-        return compute_all_sarw();
+        return compute_all_sarw(env);
     case CC_OP_SARL:
-        return compute_all_sarl();
+        return compute_all_sarl(env);
 
 #ifdef TARGET_X86_64
     case CC_OP_MULQ:
-        return compute_all_mulq();
+        return compute_all_mulq(env);
 
     case CC_OP_ADDQ:
-        return compute_all_addq();
+        return compute_all_addq(env);
 
     case CC_OP_ADCQ:
-        return compute_all_adcq();
+        return compute_all_adcq(env);
 
     case CC_OP_SUBQ:
-        return compute_all_subq();
+        return compute_all_subq(env);
 
     case CC_OP_SBBQ:
-        return compute_all_sbbq();
+        return compute_all_sbbq(env);
 
     case CC_OP_LOGICQ:
-        return compute_all_logicq();
+        return compute_all_logicq(env);
 
     case CC_OP_INCQ:
-        return compute_all_incq();
+        return compute_all_incq(env);
 
     case CC_OP_DECQ:
-        return compute_all_decq();
+        return compute_all_decq(env);
 
     case CC_OP_SHLQ:
-        return compute_all_shlq();
+        return compute_all_shlq(env);
 
     case CC_OP_SARQ:
-        return compute_all_sarq();
+        return compute_all_sarq(env);
 #endif
     }
 }
 
-uint32_t cpu_cc_compute_all(CPUX86State *env1, int op)
+uint32_t cpu_cc_compute_all(CPUX86State *env, int op)
 {
-    CPUX86State *saved_env;
-    uint32_t ret;
-
-    saved_env = env;
-    env = env1;
-    ret = helper_cc_compute_all(op);
-    env = saved_env;
-    return ret;
+    return helper_cc_compute_all(env, op);
 }
 
-uint32_t helper_cc_compute_c(int op)
+uint32_t helper_cc_compute_c(CPUX86State *env, int op)
 {
     switch (op) {
     default: /* should never happen */
         return 0;
 
     case CC_OP_EFLAGS:
-        return compute_c_eflags();
+        return compute_c_eflags(env);
 
     case CC_OP_MULB:
-        return compute_c_mull();
+        return compute_c_mull(env);
     case CC_OP_MULW:
-        return compute_c_mull();
+        return compute_c_mull(env);
     case CC_OP_MULL:
-        return compute_c_mull();
+        return compute_c_mull(env);
 
     case CC_OP_ADDB:
-        return compute_c_addb();
+        return compute_c_addb(env);
     case CC_OP_ADDW:
-        return compute_c_addw();
+        return compute_c_addw(env);
     case CC_OP_ADDL:
-        return compute_c_addl();
+        return compute_c_addl(env);
 
     case CC_OP_ADCB:
-        return compute_c_adcb();
+        return compute_c_adcb(env);
     case CC_OP_ADCW:
-        return compute_c_adcw();
+        return compute_c_adcw(env);
     case CC_OP_ADCL:
-        return compute_c_adcl();
+        return compute_c_adcl(env);
 
     case CC_OP_SUBB:
-        return compute_c_subb();
+        return compute_c_subb(env);
     case CC_OP_SUBW:
-        return compute_c_subw();
+        return compute_c_subw(env);
     case CC_OP_SUBL:
-        return compute_c_subl();
+        return compute_c_subl(env);
 
     case CC_OP_SBBB:
-        return compute_c_sbbb();
+        return compute_c_sbbb(env);
     case CC_OP_SBBW:
-        return compute_c_sbbw();
+        return compute_c_sbbw(env);
     case CC_OP_SBBL:
-        return compute_c_sbbl();
+        return compute_c_sbbl(env);
 
     case CC_OP_LOGICB:
         return compute_c_logicb();
@@ -263,111 +255,112 @@ uint32_t helper_cc_compute_c(int op)
         return compute_c_logicl();
 
     case CC_OP_INCB:
-        return compute_c_incl();
+        return compute_c_incl(env);
     case CC_OP_INCW:
-        return compute_c_incl();
+        return compute_c_incl(env);
     case CC_OP_INCL:
-        return compute_c_incl();
+        return compute_c_incl(env);
 
     case CC_OP_DECB:
-        return compute_c_incl();
+        return compute_c_incl(env);
     case CC_OP_DECW:
-        return compute_c_incl();
+        return compute_c_incl(env);
     case CC_OP_DECL:
-        return compute_c_incl();
+        return compute_c_incl(env);
 
     case CC_OP_SHLB:
-        return compute_c_shlb();
+        return compute_c_shlb(env);
     case CC_OP_SHLW:
-        return compute_c_shlw();
+        return compute_c_shlw(env);
     case CC_OP_SHLL:
-        return compute_c_shll();
+        return compute_c_shll(env);
 
     case CC_OP_SARB:
-        return compute_c_sarl();
+        return compute_c_sarl(env);
     case CC_OP_SARW:
-        return compute_c_sarl();
+        return compute_c_sarl(env);
     case CC_OP_SARL:
-        return compute_c_sarl();
+        return compute_c_sarl(env);
 
 #ifdef TARGET_X86_64
     case CC_OP_MULQ:
-        return compute_c_mull();
+        return compute_c_mull(env);
 
     case CC_OP_ADDQ:
-        return compute_c_addq();
+        return compute_c_addq(env);
 
     case CC_OP_ADCQ:
-        return compute_c_adcq();
+        return compute_c_adcq(env);
 
     case CC_OP_SUBQ:
-        return compute_c_subq();
+        return compute_c_subq(env);
 
     case CC_OP_SBBQ:
-        return compute_c_sbbq();
+        return compute_c_sbbq(env);
 
     case CC_OP_LOGICQ:
         return compute_c_logicq();
 
     case CC_OP_INCQ:
-        return compute_c_incl();
+        return compute_c_incl(env);
 
     case CC_OP_DECQ:
-        return compute_c_incl();
+        return compute_c_incl(env);
 
     case CC_OP_SHLQ:
-        return compute_c_shlq();
+        return compute_c_shlq(env);
 
     case CC_OP_SARQ:
-        return compute_c_sarl();
+        return compute_c_sarl(env);
 #endif
     }
 }
 
-void helper_write_eflags(target_ulong t0, uint32_t update_mask)
+void helper_write_eflags(CPUX86State *env, target_ulong t0,
+                         uint32_t update_mask)
 {
     cpu_load_eflags(env, t0, update_mask);
 }
 
-target_ulong helper_read_eflags(void)
+target_ulong helper_read_eflags(CPUX86State *env)
 {
     uint32_t eflags;
 
-    eflags = helper_cc_compute_all(CC_OP);
+    eflags = helper_cc_compute_all(env, CC_OP);
     eflags |= (DF & DF_MASK);
     eflags |= env->eflags & ~(VM_MASK | RF_MASK);
     return eflags;
 }
 
-void helper_clts(void)
+void helper_clts(CPUX86State *env)
 {
     env->cr[0] &= ~CR0_TS_MASK;
     env->hflags &= ~HF_TS_MASK;
 }
 
-void helper_reset_rf(void)
+void helper_reset_rf(CPUX86State *env)
 {
     env->eflags &= ~RF_MASK;
 }
 
-void helper_cli(void)
+void helper_cli(CPUX86State *env)
 {
     env->eflags &= ~IF_MASK;
 }
 
-void helper_sti(void)
+void helper_sti(CPUX86State *env)
 {
     env->eflags |= IF_MASK;
 }
 
 #if 0
 /* vm86plus instructions */
-void helper_cli_vm(void)
+void helper_cli_vm(CPUX86State *env)
 {
     env->eflags &= ~VIF_MASK;
 }
 
-void helper_sti_vm(void)
+void helper_sti_vm(CPUX86State *env)
 {
     env->eflags |= VIF_MASK;
     if (env->eflags & VIP_MASK) {
@@ -376,12 +369,12 @@ void helper_sti_vm(void)
 }
 #endif
 
-void helper_set_inhibit_irq(void)
+void helper_set_inhibit_irq(CPUX86State *env)
 {
     env->hflags |= HF_INHIBIT_IRQ_MASK;
 }
 
-void helper_reset_inhibit_irq(void)
+void helper_reset_inhibit_irq(CPUX86State *env)
 {
     env->hflags &= ~HF_INHIBIT_IRQ_MASK;
 }
diff --git a/target-i386/cc_helper_template.h b/target-i386/cc_helper_template.h
index ff22830..1f94e11 100644
--- a/target-i386/cc_helper_template.h
+++ b/target-i386/cc_helper_template.h
@@ -42,7 +42,7 @@
 
 /* dynamic flags computation */
 
-static int glue(compute_all_add, SUFFIX)(void)
+static int glue(compute_all_add, SUFFIX)(CPUX86State *env)
 {
     int cf, pf, af, zf, sf, of;
     target_long src1, src2;
@@ -58,7 +58,7 @@ static int glue(compute_all_add, SUFFIX)(void)
     return cf | pf | af | zf | sf | of;
 }
 
-static int glue(compute_c_add, SUFFIX)(void)
+static int glue(compute_c_add, SUFFIX)(CPUX86State *env)
 {
     int cf;
     target_long src1;
@@ -68,7 +68,7 @@ static int glue(compute_c_add, SUFFIX)(void)
     return cf;
 }
 
-static int glue(compute_all_adc, SUFFIX)(void)
+static int glue(compute_all_adc, SUFFIX)(CPUX86State *env)
 {
     int cf, pf, af, zf, sf, of;
     target_long src1, src2;
@@ -84,7 +84,7 @@ static int glue(compute_all_adc, SUFFIX)(void)
     return cf | pf | af | zf | sf | of;
 }
 
-static int glue(compute_c_adc, SUFFIX)(void)
+static int glue(compute_c_adc, SUFFIX)(CPUX86State *env)
 {
     int cf;
     target_long src1;
@@ -94,7 +94,7 @@ static int glue(compute_c_adc, SUFFIX)(void)
     return cf;
 }
 
-static int glue(compute_all_sub, SUFFIX)(void)
+static int glue(compute_all_sub, SUFFIX)(CPUX86State *env)
 {
     int cf, pf, af, zf, sf, of;
     target_long src1, src2;
@@ -110,7 +110,7 @@ static int glue(compute_all_sub, SUFFIX)(void)
     return cf | pf | af | zf | sf | of;
 }
 
-static int glue(compute_c_sub, SUFFIX)(void)
+static int glue(compute_c_sub, SUFFIX)(CPUX86State *env)
 {
     int cf;
     target_long src1, src2;
@@ -121,7 +121,7 @@ static int glue(compute_c_sub, SUFFIX)(void)
     return cf;
 }
 
-static int glue(compute_all_sbb, SUFFIX)(void)
+static int glue(compute_all_sbb, SUFFIX)(CPUX86State *env)
 {
     int cf, pf, af, zf, sf, of;
     target_long src1, src2;
@@ -137,7 +137,7 @@ static int glue(compute_all_sbb, SUFFIX)(void)
     return cf | pf | af | zf | sf | of;
 }
 
-static int glue(compute_c_sbb, SUFFIX)(void)
+static int glue(compute_c_sbb, SUFFIX)(CPUX86State *env)
 {
     int cf;
     target_long src1, src2;
@@ -148,7 +148,7 @@ static int glue(compute_c_sbb, SUFFIX)(void)
     return cf;
 }
 
-static int glue(compute_all_logic, SUFFIX)(void)
+static int glue(compute_all_logic, SUFFIX)(CPUX86State *env)
 {
     int cf, pf, af, zf, sf, of;
 
@@ -166,7 +166,7 @@ static int glue(compute_c_logic, SUFFIX)(void)
     return 0;
 }
 
-static int glue(compute_all_inc, SUFFIX)(void)
+static int glue(compute_all_inc, SUFFIX)(CPUX86State *env)
 {
     int cf, pf, af, zf, sf, of;
     target_long src1, src2;
@@ -183,13 +183,13 @@ static int glue(compute_all_inc, SUFFIX)(void)
 }
 
 #if DATA_BITS == 32
-static int glue(compute_c_inc, SUFFIX)(void)
+static int glue(compute_c_inc, SUFFIX)(CPUX86State *env)
 {
     return CC_SRC;
 }
 #endif
 
-static int glue(compute_all_dec, SUFFIX)(void)
+static int glue(compute_all_dec, SUFFIX)(CPUX86State *env)
 {
     int cf, pf, af, zf, sf, of;
     target_long src1, src2;
@@ -205,7 +205,7 @@ static int glue(compute_all_dec, SUFFIX)(void)
     return cf | pf | af | zf | sf | of;
 }
 
-static int glue(compute_all_shl, SUFFIX)(void)
+static int glue(compute_all_shl, SUFFIX)(CPUX86State *env)
 {
     int cf, pf, af, zf, sf, of;
 
@@ -219,19 +219,19 @@ static int glue(compute_all_shl, SUFFIX)(void)
     return cf | pf | af | zf | sf | of;
 }
 
-static int glue(compute_c_shl, SUFFIX)(void)
+static int glue(compute_c_shl, SUFFIX)(CPUX86State *env)
 {
     return (CC_SRC >> (DATA_BITS - 1)) & CC_C;
 }
 
 #if DATA_BITS == 32
-static int glue(compute_c_sar, SUFFIX)(void)
+static int glue(compute_c_sar, SUFFIX)(CPUX86State *env)
 {
     return CC_SRC & 1;
 }
 #endif
 
-static int glue(compute_all_sar, SUFFIX)(void)
+static int glue(compute_all_sar, SUFFIX)(CPUX86State *env)
 {
     int cf, pf, af, zf, sf, of;
 
@@ -246,7 +246,7 @@ static int glue(compute_all_sar, SUFFIX)(void)
 }
 
 #if DATA_BITS == 32
-static int glue(compute_c_mul, SUFFIX)(void)
+static int glue(compute_c_mul, SUFFIX)(CPUX86State *env)
 {
     int cf;
 
@@ -257,7 +257,7 @@ static int glue(compute_c_mul, SUFFIX)(void)
 
 /* NOTE: we compute the flags like the P4. On olders CPUs, only OF and
    CF are modified and it is slower to do that. */
-static int glue(compute_all_mul, SUFFIX)(void)
+static int glue(compute_all_mul, SUFFIX)(CPUX86State *env)
 {
     int cf, pf, af, zf, sf, of;
 
diff --git a/target-i386/helper.h b/target-i386/helper.h
index 6fdee8a..d647e54 100644
--- a/target-i386/helper.h
+++ b/target-i386/helper.h
@@ -1,12 +1,12 @@
 #include "def-helper.h"
 
-DEF_HELPER_FLAGS_1(cc_compute_all, TCG_CALL_PURE, i32, int)
-DEF_HELPER_FLAGS_1(cc_compute_c, TCG_CALL_PURE, i32, int)
+DEF_HELPER_FLAGS_2(cc_compute_all, TCG_CALL_PURE, i32, env, int)
+DEF_HELPER_FLAGS_2(cc_compute_c, TCG_CALL_PURE, i32, env, int)
 
 DEF_HELPER_0(lock, void)
 DEF_HELPER_0(unlock, void)
-DEF_HELPER_2(write_eflags, void, tl, i32)
-DEF_HELPER_0(read_eflags, tl)
+DEF_HELPER_3(write_eflags, void, env, tl, i32)
+DEF_HELPER_1(read_eflags, tl, env)
 DEF_HELPER_1(divb_AL, void, tl)
 DEF_HELPER_1(idivb_AL, void, tl)
 DEF_HELPER_1(divw_AX, void, tl)
@@ -44,7 +44,7 @@ DEF_HELPER_2(lret_protected, void, int, int)
 DEF_HELPER_1(read_crN, tl, int)
 DEF_HELPER_2(write_crN, void, int, tl)
 DEF_HELPER_1(lmsw, void, tl)
-DEF_HELPER_0(clts, void)
+DEF_HELPER_1(clts, void, env)
 DEF_HELPER_2(movl_drN_T0, void, int, tl)
 DEF_HELPER_1(invlpg, void, tl)
 
@@ -62,13 +62,13 @@ DEF_HELPER_1(hlt, void, int)
 DEF_HELPER_1(monitor, void, tl)
 DEF_HELPER_1(mwait, void, int)
 DEF_HELPER_0(debug, void)
-DEF_HELPER_0(reset_rf, void)
+DEF_HELPER_1(reset_rf, void, env)
 DEF_HELPER_3(raise_interrupt, void, env, int, int)
 DEF_HELPER_2(raise_exception, void, env, int)
-DEF_HELPER_0(cli, void)
-DEF_HELPER_0(sti, void)
-DEF_HELPER_0(set_inhibit_irq, void)
-DEF_HELPER_0(reset_inhibit_irq, void)
+DEF_HELPER_1(cli, void, env)
+DEF_HELPER_1(sti, void, env)
+DEF_HELPER_1(set_inhibit_irq, void, env)
+DEF_HELPER_1(reset_inhibit_irq, void, env)
 DEF_HELPER_2(boundw, void, tl, int)
 DEF_HELPER_2(boundl, void, tl, int)
 DEF_HELPER_0(rsm, void)
diff --git a/target-i386/int_helper.c b/target-i386/int_helper.c
index e1f66f5..1a13e4e 100644
--- a/target-i386/int_helper.c
+++ b/target-i386/int_helper.c
@@ -185,7 +185,7 @@ void helper_aaa(void)
     int al, ah, af;
     int eflags;
 
-    eflags = helper_cc_compute_all(CC_OP);
+    eflags = cpu_cc_compute_all(env, CC_OP);
     af = eflags & CC_A;
     al = EAX & 0xff;
     ah = (EAX >> 8) & 0xff;
@@ -209,7 +209,7 @@ void helper_aas(void)
     int al, ah, af;
     int eflags;
 
-    eflags = helper_cc_compute_all(CC_OP);
+    eflags = cpu_cc_compute_all(env, CC_OP);
     af = eflags & CC_A;
     al = EAX & 0xff;
     ah = (EAX >> 8) & 0xff;
@@ -232,7 +232,7 @@ void helper_daa(void)
     int old_al, al, af, cf;
     int eflags;
 
-    eflags = helper_cc_compute_all(CC_OP);
+    eflags = cpu_cc_compute_all(env, CC_OP);
     cf = eflags & CC_C;
     af = eflags & CC_A;
     old_al = al = EAX & 0xff;
@@ -259,7 +259,7 @@ void helper_das(void)
     int al, al1, af, cf;
     int eflags;
 
-    eflags = helper_cc_compute_all(CC_OP);
+    eflags = cpu_cc_compute_all(env, CC_OP);
     cf = eflags & CC_C;
     af = eflags & CC_A;
     al = EAX & 0xff;
diff --git a/target-i386/mem_helper.c b/target-i386/mem_helper.c
index 4e0af4b..30c3bd0 100644
--- a/target-i386/mem_helper.c
+++ b/target-i386/mem_helper.c
@@ -44,7 +44,7 @@ void helper_cmpxchg8b(target_ulong a0)
     uint64_t d;
     int eflags;
 
-    eflags = helper_cc_compute_all(CC_OP);
+    eflags = cpu_cc_compute_all(env, CC_OP);
     d = ldq(a0);
     if (d == (((uint64_t)EDX << 32) | (uint32_t)EAX)) {
         stq(a0, ((uint64_t)ECX << 32) | (uint32_t)EBX);
@@ -68,7 +68,7 @@ void helper_cmpxchg16b(target_ulong a0)
     if ((a0 & 0xf) != 0) {
         raise_exception(env, EXCP0D_GPF);
     }
-    eflags = helper_cc_compute_all(CC_OP);
+    eflags = cpu_cc_compute_all(env, CC_OP);
     d0 = ldq(a0);
     d1 = ldq(a0 + 8);
     if (d0 == EAX && d1 == EDX) {
diff --git a/target-i386/misc_helper.c b/target-i386/misc_helper.c
index ce675b7..272a636 100644
--- a/target-i386/misc_helper.c
+++ b/target-i386/misc_helper.c
@@ -102,7 +102,7 @@ void helper_into(int next_eip_addend)
 {
     int eflags;
 
-    eflags = helper_cc_compute_all(CC_OP);
+    eflags = cpu_cc_compute_all(env, CC_OP);
     if (eflags & CC_O) {
         raise_interrupt(env, EXCP04_INTO, 1, 0, next_eip_addend);
     }
diff --git a/target-i386/seg_helper.c b/target-i386/seg_helper.c
index a4b8b64..41d146c 100644
--- a/target-i386/seg_helper.c
+++ b/target-i386/seg_helper.c
@@ -2294,7 +2294,7 @@ target_ulong helper_lsl(target_ulong selector1)
     int rpl, dpl, cpl, type;
 
     selector = selector1 & 0xffff;
-    eflags = helper_cc_compute_all(CC_OP);
+    eflags = cpu_cc_compute_all(env, CC_OP);
     if ((selector & 0xfffc) == 0) {
         goto fail;
     }
@@ -2341,7 +2341,7 @@ target_ulong helper_lar(target_ulong selector1)
     int rpl, dpl, cpl, type;
 
     selector = selector1 & 0xffff;
-    eflags = helper_cc_compute_all(CC_OP);
+    eflags = cpu_cc_compute_all(env, CC_OP);
     if ((selector & 0xfffc) == 0) {
         goto fail;
     }
@@ -2390,7 +2390,7 @@ void helper_verr(target_ulong selector1)
     int rpl, dpl, cpl;
 
     selector = selector1 & 0xffff;
-    eflags = helper_cc_compute_all(CC_OP);
+    eflags = cpu_cc_compute_all(env, CC_OP);
     if ((selector & 0xfffc) == 0) {
         goto fail;
     }
@@ -2428,7 +2428,7 @@ void helper_verw(target_ulong selector1)
     int rpl, dpl, cpl;
 
     selector = selector1 & 0xffff;
-    eflags = helper_cc_compute_all(CC_OP);
+    eflags = cpu_cc_compute_all(env, CC_OP);
     if ((selector & 0xfffc) == 0) {
         goto fail;
     }
diff --git a/target-i386/shift_helper_template.h b/target-i386/shift_helper_template.h
index 239ee09..dacfdd2 100644
--- a/target-i386/shift_helper_template.h
+++ b/target-i386/shift_helper_template.h
@@ -54,7 +54,7 @@ target_ulong glue(helper_rcl, SUFFIX)(target_ulong t0, target_ulong t1)
     count = rclb_table[count];
 #endif
     if (count) {
-        eflags = helper_cc_compute_all(CC_OP);
+        eflags = helper_cc_compute_all(env, CC_OP);
         t0 &= DATA_MASK;
         src = t0;
         res = (t0 << count) | ((target_ulong)(eflags & CC_C) << (count - 1));
@@ -84,7 +84,7 @@ target_ulong glue(helper_rcr, SUFFIX)(target_ulong t0, target_ulong t1)
     count = rclb_table[count];
 #endif
     if (count) {
-        eflags = helper_cc_compute_all(CC_OP);
+        eflags = helper_cc_compute_all(env, CC_OP);
         t0 &= DATA_MASK;
         src = t0;
         res = (t0 >> count) |
diff --git a/target-i386/translate.c b/target-i386/translate.c
index 5e9da9d..15b5b63 100644
--- a/target-i386/translate.c
+++ b/target-i386/translate.c
@@ -811,14 +811,14 @@ static void gen_op_update_neg_cc(void)
 /* compute eflags.C to reg */
 static void gen_compute_eflags_c(TCGv reg)
 {
-    gen_helper_cc_compute_c(cpu_tmp2_i32, cpu_cc_op);
+    gen_helper_cc_compute_c(cpu_tmp2_i32, cpu_env, cpu_cc_op);
     tcg_gen_extu_i32_tl(reg, cpu_tmp2_i32);
 }
 
 /* compute all eflags to cc_src */
 static void gen_compute_eflags(TCGv reg)
 {
-    gen_helper_cc_compute_all(cpu_tmp2_i32, cpu_cc_op);
+    gen_helper_cc_compute_all(cpu_tmp2_i32, cpu_env, cpu_cc_op);
     tcg_gen_extu_i32_tl(reg, cpu_tmp2_i32);
 }
 
@@ -2730,10 +2730,10 @@ static void gen_eob(DisasContext *s)
     if (s->cc_op != CC_OP_DYNAMIC)
         gen_op_set_cc_op(s->cc_op);
     if (s->tb->flags & HF_INHIBIT_IRQ_MASK) {
-        gen_helper_reset_inhibit_irq();
+        gen_helper_reset_inhibit_irq(cpu_env);
     }
     if (s->tb->flags & HF_RF_MASK) {
-        gen_helper_reset_rf();
+        gen_helper_reset_rf(cpu_env);
     }
     if (s->singlestep_enabled) {
         gen_helper_debug();
@@ -5143,7 +5143,7 @@ static target_ulong disas_insn(DisasContext *s, target_ulong pc_start)
             /* If several instructions disable interrupts, only the
                _first_ does it */
             if (!(s->tb->flags & HF_INHIBIT_IRQ_MASK))
-                gen_helper_set_inhibit_irq();
+                gen_helper_set_inhibit_irq(cpu_env);
             s->tf = 0;
         }
         if (s->is_jmp) {
@@ -5219,7 +5219,7 @@ static target_ulong disas_insn(DisasContext *s, target_ulong pc_start)
             /* If several instructions disable interrupts, only the
                _first_ does it */
             if (!(s->tb->flags & HF_INHIBIT_IRQ_MASK))
-                gen_helper_set_inhibit_irq();
+                gen_helper_set_inhibit_irq(cpu_env);
             s->tf = 0;
         }
         if (s->is_jmp) {
@@ -6475,7 +6475,7 @@ static target_ulong disas_insn(DisasContext *s, target_ulong pc_start)
         } else {
             if (s->cc_op != CC_OP_DYNAMIC)
                 gen_op_set_cc_op(s->cc_op);
-            gen_helper_read_eflags(cpu_T[0]);
+            gen_helper_read_eflags(cpu_T[0], cpu_env);
             gen_push_T0(s);
         }
         break;
@@ -6487,28 +6487,46 @@ static target_ulong disas_insn(DisasContext *s, target_ulong pc_start)
             gen_pop_T0(s);
             if (s->cpl == 0) {
                 if (s->dflag) {
-                    gen_helper_write_eflags(cpu_T[0],
-                                       tcg_const_i32((TF_MASK | AC_MASK | ID_MASK | NT_MASK | IF_MASK | IOPL_MASK)));
+                    gen_helper_write_eflags(cpu_env, cpu_T[0],
+                                            tcg_const_i32((TF_MASK | AC_MASK |
+                                                           ID_MASK | NT_MASK |
+                                                           IF_MASK |
+                                                           IOPL_MASK)));
                 } else {
-                    gen_helper_write_eflags(cpu_T[0],
-                                       tcg_const_i32((TF_MASK | AC_MASK | ID_MASK | NT_MASK | IF_MASK | IOPL_MASK) & 0xffff));
+                    gen_helper_write_eflags(cpu_env, cpu_T[0],
+                                            tcg_const_i32((TF_MASK | AC_MASK |
+                                                           ID_MASK | NT_MASK |
+                                                           IF_MASK | IOPL_MASK)
+                                                          & 0xffff));
                 }
             } else {
                 if (s->cpl <= s->iopl) {
                     if (s->dflag) {
-                        gen_helper_write_eflags(cpu_T[0],
-                                           tcg_const_i32((TF_MASK | AC_MASK | ID_MASK | NT_MASK | IF_MASK)));
+                        gen_helper_write_eflags(cpu_env, cpu_T[0],
+                                                tcg_const_i32((TF_MASK |
+                                                               AC_MASK |
+                                                               ID_MASK |
+                                                               NT_MASK |
+                                                               IF_MASK)));
                     } else {
-                        gen_helper_write_eflags(cpu_T[0],
-                                           tcg_const_i32((TF_MASK | AC_MASK | ID_MASK | NT_MASK | IF_MASK) & 0xffff));
+                        gen_helper_write_eflags(cpu_env, cpu_T[0],
+                                                tcg_const_i32((TF_MASK |
+                                                               AC_MASK |
+                                                               ID_MASK |
+                                                               NT_MASK |
+                                                               IF_MASK)
+                                                              & 0xffff));
                     }
                 } else {
                     if (s->dflag) {
-                        gen_helper_write_eflags(cpu_T[0],
-                                           tcg_const_i32((TF_MASK | AC_MASK | ID_MASK | NT_MASK)));
+                        gen_helper_write_eflags(cpu_env, cpu_T[0],
+                                           tcg_const_i32((TF_MASK | AC_MASK |
+                                                          ID_MASK | NT_MASK)));
                     } else {
-                        gen_helper_write_eflags(cpu_T[0],
-                                           tcg_const_i32((TF_MASK | AC_MASK | ID_MASK | NT_MASK) & 0xffff));
+                        gen_helper_write_eflags(cpu_env, cpu_T[0],
+                                           tcg_const_i32((TF_MASK | AC_MASK |
+                                                          ID_MASK | NT_MASK)
+                                                         & 0xffff));
                     }
                 }
             }
@@ -6814,13 +6832,13 @@ static target_ulong disas_insn(DisasContext *s, target_ulong pc_start)
     case 0xfa: /* cli */
         if (!s->vm86) {
             if (s->cpl <= s->iopl) {
-                gen_helper_cli();
+                gen_helper_cli(cpu_env);
             } else {
                 gen_exception(s, EXCP0D_GPF, pc_start - s->cs_base);
             }
         } else {
             if (s->iopl == 3) {
-                gen_helper_cli();
+                gen_helper_cli(cpu_env);
             } else {
                 gen_exception(s, EXCP0D_GPF, pc_start - s->cs_base);
             }
@@ -6830,12 +6848,12 @@ static target_ulong disas_insn(DisasContext *s, target_ulong pc_start)
         if (!s->vm86) {
             if (s->cpl <= s->iopl) {
             gen_sti:
-                gen_helper_sti();
+                gen_helper_sti(cpu_env);
                 /* interruptions are enabled only the first insn after sti */
                 /* If several instructions disable interrupts, only the
                    _first_ does it */
                 if (!(s->tb->flags & HF_INHIBIT_IRQ_MASK))
-                    gen_helper_set_inhibit_irq();
+                    gen_helper_set_inhibit_irq(cpu_env);
                 /* give a chance to handle pending irqs */
                 gen_jmp_im(s->pc - s->cs_base);
                 gen_eob(s);
@@ -7578,7 +7596,7 @@ static target_ulong disas_insn(DisasContext *s, target_ulong pc_start)
             gen_exception(s, EXCP0D_GPF, pc_start - s->cs_base);
         } else {
             gen_svm_check_intercept(s, pc_start, SVM_EXIT_WRITE_CR0);
-            gen_helper_clts();
+            gen_helper_clts(cpu_env);
             /* abort block because static cpu state changed */
             gen_jmp_im(s->pc - s->cs_base);
             gen_eob(s);
commit d3eb5eaeb56e48891bb98ab5f092f43e142e3f28
Author: Blue Swirl <blauwirbel at gmail.com>
Date:   Sat Apr 28 21:28:09 2012 +0000

    x86: avoid AREG0 for FPU helpers
    
    Make FPU helpers take a parameter for CPUState instead
    of relying on global env.
    
    Introduce temporary wrappers for FPU load and store ops. Remove
    wrappers for non-AREG0 code. Don't call unconverted helpers
    directly.
    
    Signed-off-by: Blue Swirl <blauwirbel at gmail.com>

diff --git a/target-i386/Makefile.objs b/target-i386/Makefile.objs
index 0715f58..88e7280 100644
--- a/target-i386/Makefile.objs
+++ b/target-i386/Makefile.objs
@@ -7,7 +7,6 @@ obj-$(CONFIG_NO_KVM) += kvm-stub.o
 obj-$(CONFIG_LINUX_USER) += ioport-user.o
 obj-$(CONFIG_BSD_USER) += ioport-user.o
 
-$(obj)/fpu_helper.o: QEMU_CFLAGS += $(HELPER_CFLAGS)
 $(obj)/cc_helper.o: QEMU_CFLAGS += $(HELPER_CFLAGS)
 $(obj)/int_helper.o: QEMU_CFLAGS += $(HELPER_CFLAGS)
 $(obj)/svm_helper.o: QEMU_CFLAGS += $(HELPER_CFLAGS)
diff --git a/target-i386/cpu.h b/target-i386/cpu.h
index 60f9e97..b6d5e83 100644
--- a/target-i386/cpu.h
+++ b/target-i386/cpu.h
@@ -1138,4 +1138,15 @@ void do_smm_enter(CPUX86State *env1);
 
 void cpu_report_tpr_access(CPUX86State *env, TPRAccess access);
 
+/* temporary wrappers */
+uint32_t cpu_ldub_data(CPUX86State *env, target_ulong ptr);
+uint32_t cpu_lduw_data(CPUX86State *env, target_ulong ptr);
+uint32_t cpu_ldl_data(CPUX86State *env, target_ulong ptr);
+uint64_t cpu_ldq_data(CPUX86State *env, target_ulong ptr);
+
+void cpu_stb_data(CPUX86State *env, target_ulong ptr, uint32_t data);
+void cpu_stw_data(CPUX86State *env, target_ulong ptr, uint32_t data);
+void cpu_stl_data(CPUX86State *env, target_ulong ptr, uint32_t data);
+void cpu_stq_data(CPUX86State *env, target_ulong ptr, uint64_t data);
+
 #endif /* CPU_I386_H */
diff --git a/target-i386/fpu_helper.c b/target-i386/fpu_helper.c
index 6065c2e..a1d7ef7 100644
--- a/target-i386/fpu_helper.c
+++ b/target-i386/fpu_helper.c
@@ -19,13 +19,8 @@
 
 #include <math.h>
 #include "cpu.h"
-#include "dyngen-exec.h"
 #include "helper.h"
 
-#if !defined(CONFIG_USER_ONLY)
-#include "softmmu_exec.h"
-#endif /* !defined(CONFIG_USER_ONLY) */
-
 #define FPU_RC_MASK         0xc00
 #define FPU_RC_NEAR         0x000
 #define FPU_RC_DOWN         0x400
@@ -58,39 +53,39 @@
 #define floatx80_l2e make_floatx80(0x3fff, 0xb8aa3b295c17f0bcLL)
 #define floatx80_l2t make_floatx80(0x4000, 0xd49a784bcd1b8afeLL)
 
-static inline void fpush(void)
+static inline void fpush(CPUX86State *env)
 {
     env->fpstt = (env->fpstt - 1) & 7;
     env->fptags[env->fpstt] = 0; /* validate stack entry */
 }
 
-static inline void fpop(void)
+static inline void fpop(CPUX86State *env)
 {
     env->fptags[env->fpstt] = 1; /* invalidate stack entry */
     env->fpstt = (env->fpstt + 1) & 7;
 }
 
-static inline floatx80 helper_fldt(target_ulong ptr)
+static inline floatx80 helper_fldt(CPUX86State *env, target_ulong ptr)
 {
     CPU_LDoubleU temp;
 
-    temp.l.lower = ldq(ptr);
-    temp.l.upper = lduw(ptr + 8);
+    temp.l.lower = cpu_ldq_data(env, ptr);
+    temp.l.upper = cpu_lduw_data(env, ptr + 8);
     return temp.d;
 }
 
-static inline void helper_fstt(floatx80 f, target_ulong ptr)
+static inline void helper_fstt(CPUX86State *env, floatx80 f, target_ulong ptr)
 {
     CPU_LDoubleU temp;
 
     temp.d = f;
-    stq(ptr, temp.l.lower);
-    stw(ptr + 8, temp.l.upper);
+    cpu_stq_data(env, ptr, temp.l.lower);
+    cpu_stw_data(env, ptr + 8, temp.l.upper);
 }
 
 /* x87 FPU helpers */
 
-static inline double floatx80_to_double(floatx80 a)
+static inline double floatx80_to_double(CPUX86State *env, floatx80 a)
 {
     union {
         float64 f64;
@@ -101,7 +96,7 @@ static inline double floatx80_to_double(floatx80 a)
     return u.d;
 }
 
-static inline floatx80 double_to_floatx80(double a)
+static inline floatx80 double_to_floatx80(CPUX86State *env, double a)
 {
     union {
         float64 f64;
@@ -112,7 +107,7 @@ static inline floatx80 double_to_floatx80(double a)
     return float64_to_floatx80(u.f64, &env->fp_status);
 }
 
-static void fpu_set_exception(int mask)
+static void fpu_set_exception(CPUX86State *env, int mask)
 {
     env->fpus |= mask;
     if (env->fpus & (~env->fpuc & FPUC_EM)) {
@@ -120,15 +115,15 @@ static void fpu_set_exception(int mask)
     }
 }
 
-static inline floatx80 helper_fdiv(floatx80 a, floatx80 b)
+static inline floatx80 helper_fdiv(CPUX86State *env, floatx80 a, floatx80 b)
 {
     if (floatx80_is_zero(b)) {
-        fpu_set_exception(FPUS_ZE);
+        fpu_set_exception(env, FPUS_ZE);
     }
     return floatx80_div(a, b, &env->fp_status);
 }
 
-static void fpu_raise_exception(void)
+static void fpu_raise_exception(CPUX86State *env)
 {
     if (env->cr[0] & CR0_NE_MASK) {
         raise_exception(env, EXCP10_COPR);
@@ -140,7 +135,7 @@ static void fpu_raise_exception(void)
 #endif
 }
 
-void helper_flds_FT0(uint32_t val)
+void helper_flds_FT0(CPUX86State *env, uint32_t val)
 {
     union {
         float32 f;
@@ -151,7 +146,7 @@ void helper_flds_FT0(uint32_t val)
     FT0 = float32_to_floatx80(u.f, &env->fp_status);
 }
 
-void helper_fldl_FT0(uint64_t val)
+void helper_fldl_FT0(CPUX86State *env, uint64_t val)
 {
     union {
         float64 f;
@@ -162,12 +157,12 @@ void helper_fldl_FT0(uint64_t val)
     FT0 = float64_to_floatx80(u.f, &env->fp_status);
 }
 
-void helper_fildl_FT0(int32_t val)
+void helper_fildl_FT0(CPUX86State *env, int32_t val)
 {
     FT0 = int32_to_floatx80(val, &env->fp_status);
 }
 
-void helper_flds_ST0(uint32_t val)
+void helper_flds_ST0(CPUX86State *env, uint32_t val)
 {
     int new_fpstt;
     union {
@@ -182,7 +177,7 @@ void helper_flds_ST0(uint32_t val)
     env->fptags[new_fpstt] = 0; /* validate stack entry */
 }
 
-void helper_fldl_ST0(uint64_t val)
+void helper_fldl_ST0(CPUX86State *env, uint64_t val)
 {
     int new_fpstt;
     union {
@@ -197,7 +192,7 @@ void helper_fldl_ST0(uint64_t val)
     env->fptags[new_fpstt] = 0; /* validate stack entry */
 }
 
-void helper_fildl_ST0(int32_t val)
+void helper_fildl_ST0(CPUX86State *env, int32_t val)
 {
     int new_fpstt;
 
@@ -207,7 +202,7 @@ void helper_fildl_ST0(int32_t val)
     env->fptags[new_fpstt] = 0; /* validate stack entry */
 }
 
-void helper_fildll_ST0(int64_t val)
+void helper_fildll_ST0(CPUX86State *env, int64_t val)
 {
     int new_fpstt;
 
@@ -217,7 +212,7 @@ void helper_fildll_ST0(int64_t val)
     env->fptags[new_fpstt] = 0; /* validate stack entry */
 }
 
-uint32_t helper_fsts_ST0(void)
+uint32_t helper_fsts_ST0(CPUX86State *env)
 {
     union {
         float32 f;
@@ -228,7 +223,7 @@ uint32_t helper_fsts_ST0(void)
     return u.i;
 }
 
-uint64_t helper_fstl_ST0(void)
+uint64_t helper_fstl_ST0(CPUX86State *env)
 {
     union {
         float64 f;
@@ -239,7 +234,7 @@ uint64_t helper_fstl_ST0(void)
     return u.i;
 }
 
-int32_t helper_fist_ST0(void)
+int32_t helper_fist_ST0(CPUX86State *env)
 {
     int32_t val;
 
@@ -250,7 +245,7 @@ int32_t helper_fist_ST0(void)
     return val;
 }
 
-int32_t helper_fistl_ST0(void)
+int32_t helper_fistl_ST0(CPUX86State *env)
 {
     int32_t val;
 
@@ -258,7 +253,7 @@ int32_t helper_fistl_ST0(void)
     return val;
 }
 
-int64_t helper_fistll_ST0(void)
+int64_t helper_fistll_ST0(CPUX86State *env)
 {
     int64_t val;
 
@@ -266,7 +261,7 @@ int64_t helper_fistll_ST0(void)
     return val;
 }
 
-int32_t helper_fistt_ST0(void)
+int32_t helper_fistt_ST0(CPUX86State *env)
 {
     int32_t val;
 
@@ -277,7 +272,7 @@ int32_t helper_fistt_ST0(void)
     return val;
 }
 
-int32_t helper_fisttl_ST0(void)
+int32_t helper_fisttl_ST0(CPUX86State *env)
 {
     int32_t val;
 
@@ -285,7 +280,7 @@ int32_t helper_fisttl_ST0(void)
     return val;
 }
 
-int64_t helper_fisttll_ST0(void)
+int64_t helper_fisttll_ST0(CPUX86State *env)
 {
     int64_t val;
 
@@ -293,38 +288,38 @@ int64_t helper_fisttll_ST0(void)
     return val;
 }
 
-void helper_fldt_ST0(target_ulong ptr)
+void helper_fldt_ST0(CPUX86State *env, target_ulong ptr)
 {
     int new_fpstt;
 
     new_fpstt = (env->fpstt - 1) & 7;
-    env->fpregs[new_fpstt].d = helper_fldt(ptr);
+    env->fpregs[new_fpstt].d = helper_fldt(env, ptr);
     env->fpstt = new_fpstt;
     env->fptags[new_fpstt] = 0; /* validate stack entry */
 }
 
-void helper_fstt_ST0(target_ulong ptr)
+void helper_fstt_ST0(CPUX86State *env, target_ulong ptr)
 {
-    helper_fstt(ST0, ptr);
+    helper_fstt(env, ST0, ptr);
 }
 
-void helper_fpush(void)
+void helper_fpush(CPUX86State *env)
 {
-    fpush();
+    fpush(env);
 }
 
-void helper_fpop(void)
+void helper_fpop(CPUX86State *env)
 {
-    fpop();
+    fpop(env);
 }
 
-void helper_fdecstp(void)
+void helper_fdecstp(CPUX86State *env)
 {
     env->fpstt = (env->fpstt - 1) & 7;
     env->fpus &= ~0x4700;
 }
 
-void helper_fincstp(void)
+void helper_fincstp(CPUX86State *env)
 {
     env->fpstt = (env->fpstt + 1) & 7;
     env->fpus &= ~0x4700;
@@ -332,32 +327,32 @@ void helper_fincstp(void)
 
 /* FPU move */
 
-void helper_ffree_STN(int st_index)
+void helper_ffree_STN(CPUX86State *env, int st_index)
 {
     env->fptags[(env->fpstt + st_index) & 7] = 1;
 }
 
-void helper_fmov_ST0_FT0(void)
+void helper_fmov_ST0_FT0(CPUX86State *env)
 {
     ST0 = FT0;
 }
 
-void helper_fmov_FT0_STN(int st_index)
+void helper_fmov_FT0_STN(CPUX86State *env, int st_index)
 {
     FT0 = ST(st_index);
 }
 
-void helper_fmov_ST0_STN(int st_index)
+void helper_fmov_ST0_STN(CPUX86State *env, int st_index)
 {
     ST0 = ST(st_index);
 }
 
-void helper_fmov_STN_ST0(int st_index)
+void helper_fmov_STN_ST0(CPUX86State *env, int st_index)
 {
     ST(st_index) = ST0;
 }
 
-void helper_fxchg_ST0_STN(int st_index)
+void helper_fxchg_ST0_STN(CPUX86State *env, int st_index)
 {
     floatx80 tmp;
 
@@ -370,7 +365,7 @@ void helper_fxchg_ST0_STN(int st_index)
 
 static const int fcom_ccval[4] = {0x0100, 0x4000, 0x0000, 0x4500};
 
-void helper_fcom_ST0_FT0(void)
+void helper_fcom_ST0_FT0(CPUX86State *env)
 {
     int ret;
 
@@ -378,7 +373,7 @@ void helper_fcom_ST0_FT0(void)
     env->fpus = (env->fpus & ~0x4500) | fcom_ccval[ret + 1];
 }
 
-void helper_fucom_ST0_FT0(void)
+void helper_fucom_ST0_FT0(CPUX86State *env)
 {
     int ret;
 
@@ -388,158 +383,158 @@ void helper_fucom_ST0_FT0(void)
 
 static const int fcomi_ccval[4] = {CC_C, CC_Z, 0, CC_Z | CC_P | CC_C};
 
-void helper_fcomi_ST0_FT0(void)
+void helper_fcomi_ST0_FT0(CPUX86State *env)
 {
     int eflags;
     int ret;
 
     ret = floatx80_compare(ST0, FT0, &env->fp_status);
-    eflags = helper_cc_compute_all(CC_OP);
+    eflags = cpu_cc_compute_all(env, CC_OP);
     eflags = (eflags & ~(CC_Z | CC_P | CC_C)) | fcomi_ccval[ret + 1];
     CC_SRC = eflags;
 }
 
-void helper_fucomi_ST0_FT0(void)
+void helper_fucomi_ST0_FT0(CPUX86State *env)
 {
     int eflags;
     int ret;
 
     ret = floatx80_compare_quiet(ST0, FT0, &env->fp_status);
-    eflags = helper_cc_compute_all(CC_OP);
+    eflags = cpu_cc_compute_all(env, CC_OP);
     eflags = (eflags & ~(CC_Z | CC_P | CC_C)) | fcomi_ccval[ret + 1];
     CC_SRC = eflags;
 }
 
-void helper_fadd_ST0_FT0(void)
+void helper_fadd_ST0_FT0(CPUX86State *env)
 {
     ST0 = floatx80_add(ST0, FT0, &env->fp_status);
 }
 
-void helper_fmul_ST0_FT0(void)
+void helper_fmul_ST0_FT0(CPUX86State *env)
 {
     ST0 = floatx80_mul(ST0, FT0, &env->fp_status);
 }
 
-void helper_fsub_ST0_FT0(void)
+void helper_fsub_ST0_FT0(CPUX86State *env)
 {
     ST0 = floatx80_sub(ST0, FT0, &env->fp_status);
 }
 
-void helper_fsubr_ST0_FT0(void)
+void helper_fsubr_ST0_FT0(CPUX86State *env)
 {
     ST0 = floatx80_sub(FT0, ST0, &env->fp_status);
 }
 
-void helper_fdiv_ST0_FT0(void)
+void helper_fdiv_ST0_FT0(CPUX86State *env)
 {
-    ST0 = helper_fdiv(ST0, FT0);
+    ST0 = helper_fdiv(env, ST0, FT0);
 }
 
-void helper_fdivr_ST0_FT0(void)
+void helper_fdivr_ST0_FT0(CPUX86State *env)
 {
-    ST0 = helper_fdiv(FT0, ST0);
+    ST0 = helper_fdiv(env, FT0, ST0);
 }
 
 /* fp operations between STN and ST0 */
 
-void helper_fadd_STN_ST0(int st_index)
+void helper_fadd_STN_ST0(CPUX86State *env, int st_index)
 {
     ST(st_index) = floatx80_add(ST(st_index), ST0, &env->fp_status);
 }
 
-void helper_fmul_STN_ST0(int st_index)
+void helper_fmul_STN_ST0(CPUX86State *env, int st_index)
 {
     ST(st_index) = floatx80_mul(ST(st_index), ST0, &env->fp_status);
 }
 
-void helper_fsub_STN_ST0(int st_index)
+void helper_fsub_STN_ST0(CPUX86State *env, int st_index)
 {
     ST(st_index) = floatx80_sub(ST(st_index), ST0, &env->fp_status);
 }
 
-void helper_fsubr_STN_ST0(int st_index)
+void helper_fsubr_STN_ST0(CPUX86State *env, int st_index)
 {
     ST(st_index) = floatx80_sub(ST0, ST(st_index), &env->fp_status);
 }
 
-void helper_fdiv_STN_ST0(int st_index)
+void helper_fdiv_STN_ST0(CPUX86State *env, int st_index)
 {
     floatx80 *p;
 
     p = &ST(st_index);
-    *p = helper_fdiv(*p, ST0);
+    *p = helper_fdiv(env, *p, ST0);
 }
 
-void helper_fdivr_STN_ST0(int st_index)
+void helper_fdivr_STN_ST0(CPUX86State *env, int st_index)
 {
     floatx80 *p;
 
     p = &ST(st_index);
-    *p = helper_fdiv(ST0, *p);
+    *p = helper_fdiv(env, ST0, *p);
 }
 
 /* misc FPU operations */
-void helper_fchs_ST0(void)
+void helper_fchs_ST0(CPUX86State *env)
 {
     ST0 = floatx80_chs(ST0);
 }
 
-void helper_fabs_ST0(void)
+void helper_fabs_ST0(CPUX86State *env)
 {
     ST0 = floatx80_abs(ST0);
 }
 
-void helper_fld1_ST0(void)
+void helper_fld1_ST0(CPUX86State *env)
 {
     ST0 = floatx80_one;
 }
 
-void helper_fldl2t_ST0(void)
+void helper_fldl2t_ST0(CPUX86State *env)
 {
     ST0 = floatx80_l2t;
 }
 
-void helper_fldl2e_ST0(void)
+void helper_fldl2e_ST0(CPUX86State *env)
 {
     ST0 = floatx80_l2e;
 }
 
-void helper_fldpi_ST0(void)
+void helper_fldpi_ST0(CPUX86State *env)
 {
     ST0 = floatx80_pi;
 }
 
-void helper_fldlg2_ST0(void)
+void helper_fldlg2_ST0(CPUX86State *env)
 {
     ST0 = floatx80_lg2;
 }
 
-void helper_fldln2_ST0(void)
+void helper_fldln2_ST0(CPUX86State *env)
 {
     ST0 = floatx80_ln2;
 }
 
-void helper_fldz_ST0(void)
+void helper_fldz_ST0(CPUX86State *env)
 {
     ST0 = floatx80_zero;
 }
 
-void helper_fldz_FT0(void)
+void helper_fldz_FT0(CPUX86State *env)
 {
     FT0 = floatx80_zero;
 }
 
-uint32_t helper_fnstsw(void)
+uint32_t helper_fnstsw(CPUX86State *env)
 {
     return (env->fpus & ~0x3800) | (env->fpstt & 0x7) << 11;
 }
 
-uint32_t helper_fnstcw(void)
+uint32_t helper_fnstcw(CPUX86State *env)
 {
     return env->fpuc;
 }
 
-static void update_fp_status(void)
+static void update_fp_status(CPUX86State *env)
 {
     int rnd_type;
 
@@ -575,25 +570,25 @@ static void update_fp_status(void)
     set_floatx80_rounding_precision(rnd_type, &env->fp_status);
 }
 
-void helper_fldcw(uint32_t val)
+void helper_fldcw(CPUX86State *env, uint32_t val)
 {
     env->fpuc = val;
-    update_fp_status();
+    update_fp_status(env);
 }
 
-void helper_fclex(void)
+void helper_fclex(CPUX86State *env)
 {
     env->fpus &= 0x7f00;
 }
 
-void helper_fwait(void)
+void helper_fwait(CPUX86State *env)
 {
     if (env->fpus & FPUS_SE) {
-        fpu_raise_exception();
+        fpu_raise_exception(env);
     }
 }
 
-void helper_fninit(void)
+void helper_fninit(CPUX86State *env)
 {
     env->fpus = 0;
     env->fpstt = 0;
@@ -610,7 +605,7 @@ void helper_fninit(void)
 
 /* BCD ops */
 
-void helper_fbld_ST0(target_ulong ptr)
+void helper_fbld_ST0(CPUX86State *env, target_ulong ptr)
 {
     floatx80 tmp;
     uint64_t val;
@@ -619,18 +614,18 @@ void helper_fbld_ST0(target_ulong ptr)
 
     val = 0;
     for (i = 8; i >= 0; i--) {
-        v = ldub(ptr + i);
+        v = cpu_ldub_data(env, ptr + i);
         val = (val * 100) + ((v >> 4) * 10) + (v & 0xf);
     }
     tmp = int64_to_floatx80(val, &env->fp_status);
-    if (ldub(ptr + 9) & 0x80) {
+    if (cpu_ldub_data(env, ptr + 9) & 0x80) {
         floatx80_chs(tmp);
     }
-    fpush();
+    fpush(env);
     ST0 = tmp;
 }
 
-void helper_fbst_ST0(target_ulong ptr)
+void helper_fbst_ST0(CPUX86State *env, target_ulong ptr)
 {
     int v;
     target_ulong mem_ref, mem_end;
@@ -640,10 +635,10 @@ void helper_fbst_ST0(target_ulong ptr)
     mem_ref = ptr;
     mem_end = mem_ref + 9;
     if (val < 0) {
-        stb(mem_end, 0x80);
+        cpu_stb_data(env, mem_end, 0x80);
         val = -val;
     } else {
-        stb(mem_end, 0x00);
+        cpu_stb_data(env, mem_end, 0x00);
     }
     while (mem_ref < mem_end) {
         if (val == 0) {
@@ -652,63 +647,63 @@ void helper_fbst_ST0(target_ulong ptr)
         v = val % 100;
         val = val / 100;
         v = ((v / 10) << 4) | (v % 10);
-        stb(mem_ref++, v);
+        cpu_stb_data(env, mem_ref++, v);
     }
     while (mem_ref < mem_end) {
-        stb(mem_ref++, 0);
+        cpu_stb_data(env, mem_ref++, 0);
     }
 }
 
-void helper_f2xm1(void)
+void helper_f2xm1(CPUX86State *env)
 {
-    double val = floatx80_to_double(ST0);
+    double val = floatx80_to_double(env, ST0);
 
     val = pow(2.0, val) - 1.0;
-    ST0 = double_to_floatx80(val);
+    ST0 = double_to_floatx80(env, val);
 }
 
-void helper_fyl2x(void)
+void helper_fyl2x(CPUX86State *env)
 {
-    double fptemp = floatx80_to_double(ST0);
+    double fptemp = floatx80_to_double(env, ST0);
 
     if (fptemp > 0.0) {
         fptemp = log(fptemp) / log(2.0); /* log2(ST) */
-        fptemp *= floatx80_to_double(ST1);
-        ST1 = double_to_floatx80(fptemp);
-        fpop();
+        fptemp *= floatx80_to_double(env, ST1);
+        ST1 = double_to_floatx80(env, fptemp);
+        fpop(env);
     } else {
         env->fpus &= ~0x4700;
         env->fpus |= 0x400;
     }
 }
 
-void helper_fptan(void)
+void helper_fptan(CPUX86State *env)
 {
-    double fptemp = floatx80_to_double(ST0);
+    double fptemp = floatx80_to_double(env, ST0);
 
     if ((fptemp > MAXTAN) || (fptemp < -MAXTAN)) {
         env->fpus |= 0x400;
     } else {
         fptemp = tan(fptemp);
-        ST0 = double_to_floatx80(fptemp);
-        fpush();
+        ST0 = double_to_floatx80(env, fptemp);
+        fpush(env);
         ST0 = floatx80_one;
         env->fpus &= ~0x400; /* C2 <-- 0 */
         /* the above code is for |arg| < 2**52 only */
     }
 }
 
-void helper_fpatan(void)
+void helper_fpatan(CPUX86State *env)
 {
     double fptemp, fpsrcop;
 
-    fpsrcop = floatx80_to_double(ST1);
-    fptemp = floatx80_to_double(ST0);
-    ST1 = double_to_floatx80(atan2(fpsrcop, fptemp));
-    fpop();
+    fpsrcop = floatx80_to_double(env, ST1);
+    fptemp = floatx80_to_double(env, ST0);
+    ST1 = double_to_floatx80(env, atan2(fpsrcop, fptemp));
+    fpop(env);
 }
 
-void helper_fxtract(void)
+void helper_fxtract(CPUX86State *env)
 {
     CPU_LDoubleU temp;
 
@@ -718,7 +713,7 @@ void helper_fxtract(void)
         /* Easy way to generate -inf and raising division by 0 exception */
         ST0 = floatx80_div(floatx80_chs(floatx80_one), floatx80_zero,
                            &env->fp_status);
-        fpush();
+        fpush(env);
         ST0 = temp.d;
     } else {
         int expdif;
@@ -726,24 +721,24 @@ void helper_fxtract(void)
         expdif = EXPD(temp) - EXPBIAS;
         /* DP exponent bias */
         ST0 = int32_to_floatx80(expdif, &env->fp_status);
-        fpush();
+        fpush(env);
         BIASEXPONENT(temp);
         ST0 = temp.d;
     }
 }
 
-void helper_fprem1(void)
+void helper_fprem1(CPUX86State *env)
 {
     double st0, st1, dblq, fpsrcop, fptemp;
     CPU_LDoubleU fpsrcop1, fptemp1;
     int expdif;
     signed long long int q;
 
-    st0 = floatx80_to_double(ST0);
-    st1 = floatx80_to_double(ST1);
+    st0 = floatx80_to_double(env, ST0);
+    st1 = floatx80_to_double(env, ST1);
 
     if (isinf(st0) || isnan(st0) || isnan(st1) || (st1 == 0.0)) {
-        ST0 = double_to_floatx80(0.0 / 0.0); /* NaN */
+        ST0 = double_to_floatx80(env, 0.0 / 0.0); /* NaN */
         env->fpus &= ~0x4700; /* (C3,C2,C1,C0) <-- 0000 */
         return;
     }
@@ -788,21 +783,21 @@ void helper_fprem1(void)
                   -(floor(fabs(fpsrcop))) : floor(fpsrcop);
         st0 -= (st1 * fpsrcop * fptemp);
     }
-    ST0 = double_to_floatx80(st0);
+    ST0 = double_to_floatx80(env, st0);
 }
 
-void helper_fprem(void)
+void helper_fprem(CPUX86State *env)
 {
     double st0, st1, dblq, fpsrcop, fptemp;
     CPU_LDoubleU fpsrcop1, fptemp1;
     int expdif;
     signed long long int q;
 
-    st0 = floatx80_to_double(ST0);
-    st1 = floatx80_to_double(ST1);
+    st0 = floatx80_to_double(env, ST0);
+    st1 = floatx80_to_double(env, ST1);
 
     if (isinf(st0) || isnan(st0) || isnan(st1) || (st1 == 0.0)) {
-        ST0 = double_to_floatx80(0.0 / 0.0); /* NaN */
+        ST0 = double_to_floatx80(env, 0.0 / 0.0); /* NaN */
         env->fpus &= ~0x4700; /* (C3,C2,C1,C0) <-- 0000 */
         return;
     }
@@ -849,25 +844,25 @@ void helper_fprem(void)
                   -(floor(fabs(fpsrcop))) : floor(fpsrcop);
         st0 -= (st1 * fpsrcop * fptemp);
     }
-    ST0 = double_to_floatx80(st0);
+    ST0 = double_to_floatx80(env, st0);
 }
 
-void helper_fyl2xp1(void)
+void helper_fyl2xp1(CPUX86State *env)
 {
-    double fptemp = floatx80_to_double(ST0);
+    double fptemp = floatx80_to_double(env, ST0);
 
     if ((fptemp + 1.0) > 0.0) {
         fptemp = log(fptemp + 1.0) / log(2.0); /* log2(ST + 1.0) */
-        fptemp *= floatx80_to_double(ST1);
-        ST1 = double_to_floatx80(fptemp);
-        fpop();
+        fptemp *= floatx80_to_double(env, ST1);
+        ST1 = double_to_floatx80(env, fptemp);
+        fpop(env);
     } else {
         env->fpus &= ~0x4700;
         env->fpus |= 0x400;
     }
 }
 
-void helper_fsqrt(void)
+void helper_fsqrt(CPUX86State *env)
 {
     if (floatx80_is_neg(ST0)) {
         env->fpus &= ~0x4700;  /* (C3,C2,C1,C0) <-- 0000 */
@@ -876,27 +871,27 @@ void helper_fsqrt(void)
     ST0 = floatx80_sqrt(ST0, &env->fp_status);
 }
 
-void helper_fsincos(void)
+void helper_fsincos(CPUX86State *env)
 {
-    double fptemp = floatx80_to_double(ST0);
+    double fptemp = floatx80_to_double(env, ST0);
 
     if ((fptemp > MAXTAN) || (fptemp < -MAXTAN)) {
         env->fpus |= 0x400;
     } else {
-        ST0 = double_to_floatx80(sin(fptemp));
-        fpush();
-        ST0 = double_to_floatx80(cos(fptemp));
+        ST0 = double_to_floatx80(env, sin(fptemp));
+        fpush(env);
+        ST0 = double_to_floatx80(env, cos(fptemp));
         env->fpus &= ~0x400;  /* C2 <-- 0 */
         /* the above code is for |arg| < 2**63 only */
     }
 }
 
-void helper_frndint(void)
+void helper_frndint(CPUX86State *env)
 {
     ST0 = floatx80_round_to_int(ST0, &env->fp_status);
 }
 
-void helper_fscale(void)
+void helper_fscale(CPUX86State *env)
 {
     if (floatx80_is_any_nan(ST1)) {
         ST0 = ST1;
@@ -906,33 +901,33 @@ void helper_fscale(void)
     }
 }
 
-void helper_fsin(void)
+void helper_fsin(CPUX86State *env)
 {
-    double fptemp = floatx80_to_double(ST0);
+    double fptemp = floatx80_to_double(env, ST0);
 
     if ((fptemp > MAXTAN) || (fptemp < -MAXTAN)) {
         env->fpus |= 0x400;
     } else {
-        ST0 = double_to_floatx80(sin(fptemp));
+        ST0 = double_to_floatx80(env, sin(fptemp));
         env->fpus &= ~0x400;  /* C2 <-- 0 */
         /* the above code is for |arg| < 2**53 only */
     }
 }
 
-void helper_fcos(void)
+void helper_fcos(CPUX86State *env)
 {
-    double fptemp = floatx80_to_double(ST0);
+    double fptemp = floatx80_to_double(env, ST0);
 
     if ((fptemp > MAXTAN) || (fptemp < -MAXTAN)) {
         env->fpus |= 0x400;
     } else {
-        ST0 = double_to_floatx80(cos(fptemp));
+        ST0 = double_to_floatx80(env, cos(fptemp));
         env->fpus &= ~0x400;  /* C2 <-- 0 */
         /* the above code is for |arg| < 2**63 only */
     }
 }
 
-void helper_fxam_ST0(void)
+void helper_fxam_ST0(CPUX86State *env)
 {
     CPU_LDoubleU temp;
     int expdif;
@@ -963,7 +958,7 @@ void helper_fxam_ST0(void)
     }
 }
 
-void helper_fstenv(target_ulong ptr, int data32)
+void helper_fstenv(CPUX86State *env, target_ulong ptr, int data32)
 {
     int fpus, fptag, exp, i;
     uint64_t mant;
@@ -991,37 +986,37 @@ void helper_fstenv(target_ulong ptr, int data32)
     }
     if (data32) {
         /* 32 bit */
-        stl(ptr, env->fpuc);
-        stl(ptr + 4, fpus);
-        stl(ptr + 8, fptag);
-        stl(ptr + 12, 0); /* fpip */
-        stl(ptr + 16, 0); /* fpcs */
-        stl(ptr + 20, 0); /* fpoo */
-        stl(ptr + 24, 0); /* fpos */
+        cpu_stl_data(env, ptr, env->fpuc);
+        cpu_stl_data(env, ptr + 4, fpus);
+        cpu_stl_data(env, ptr + 8, fptag);
+        cpu_stl_data(env, ptr + 12, 0); /* fpip */
+        cpu_stl_data(env, ptr + 16, 0); /* fpcs */
+        cpu_stl_data(env, ptr + 20, 0); /* fpoo */
+        cpu_stl_data(env, ptr + 24, 0); /* fpos */
     } else {
         /* 16 bit */
-        stw(ptr, env->fpuc);
-        stw(ptr + 2, fpus);
-        stw(ptr + 4, fptag);
-        stw(ptr + 6, 0);
-        stw(ptr + 8, 0);
-        stw(ptr + 10, 0);
-        stw(ptr + 12, 0);
+        cpu_stw_data(env, ptr, env->fpuc);
+        cpu_stw_data(env, ptr + 2, fpus);
+        cpu_stw_data(env, ptr + 4, fptag);
+        cpu_stw_data(env, ptr + 6, 0);
+        cpu_stw_data(env, ptr + 8, 0);
+        cpu_stw_data(env, ptr + 10, 0);
+        cpu_stw_data(env, ptr + 12, 0);
     }
 }
 
-void helper_fldenv(target_ulong ptr, int data32)
+void helper_fldenv(CPUX86State *env, target_ulong ptr, int data32)
 {
     int i, fpus, fptag;
 
     if (data32) {
-        env->fpuc = lduw(ptr);
-        fpus = lduw(ptr + 4);
-        fptag = lduw(ptr + 8);
+        env->fpuc = cpu_lduw_data(env, ptr);
+        fpus = cpu_lduw_data(env, ptr + 4);
+        fptag = cpu_lduw_data(env, ptr + 8);
     } else {
-        env->fpuc = lduw(ptr);
-        fpus = lduw(ptr + 2);
-        fptag = lduw(ptr + 4);
+        env->fpuc = cpu_lduw_data(env, ptr);
+        fpus = cpu_lduw_data(env, ptr + 2);
+        fptag = cpu_lduw_data(env, ptr + 4);
     }
     env->fpstt = (fpus >> 11) & 7;
     env->fpus = fpus & ~0x3800;
@@ -1031,17 +1026,17 @@ void helper_fldenv(target_ulong ptr, int data32)
     }
 }
 
-void helper_fsave(target_ulong ptr, int data32)
+void helper_fsave(CPUX86State *env, target_ulong ptr, int data32)
 {
     floatx80 tmp;
     int i;
 
-    helper_fstenv(ptr, data32);
+    helper_fstenv(env, ptr, data32);
 
     ptr += (14 << data32);
     for (i = 0; i < 8; i++) {
         tmp = ST(i);
-        helper_fstt(tmp, ptr);
+        helper_fstt(env, tmp, ptr);
         ptr += 10;
     }
 
@@ -1059,48 +1054,34 @@ void helper_fsave(target_ulong ptr, int data32)
     env->fptags[7] = 1;
 }
 
-void helper_frstor(target_ulong ptr, int data32)
+void helper_frstor(CPUX86State *env, target_ulong ptr, int data32)
 {
     floatx80 tmp;
     int i;
 
-    helper_fldenv(ptr, data32);
+    helper_fldenv(env, ptr, data32);
     ptr += (14 << data32);
 
     for (i = 0; i < 8; i++) {
-        tmp = helper_fldt(ptr);
+        tmp = helper_fldt(env, ptr);
         ST(i) = tmp;
         ptr += 10;
     }
 }
 
 #if defined(CONFIG_USER_ONLY)
-void cpu_x86_fsave(CPUX86State *s, target_ulong ptr, int data32)
+void cpu_x86_fsave(CPUX86State *env, target_ulong ptr, int data32)
 {
-    CPUX86State *saved_env;
-
-    saved_env = env;
-    env = s;
-
-    helper_fsave(ptr, data32);
-
-    env = saved_env;
+    helper_fsave(env, ptr, data32);
 }
 
-void cpu_x86_frstor(CPUX86State *s, target_ulong ptr, int data32)
+void cpu_x86_frstor(CPUX86State *env, target_ulong ptr, int data32)
 {
-    CPUX86State *saved_env;
-
-    saved_env = env;
-    env = s;
-
-    helper_frstor(ptr, data32);
-
-    env = saved_env;
+    helper_frstor(env, ptr, data32);
 }
 #endif
 
-void helper_fxsave(target_ulong ptr, int data64)
+void helper_fxsave(CPUX86State *env, target_ulong ptr, int data64)
 {
     int fpus, fptag, i, nb_xmm_regs;
     floatx80 tmp;
@@ -1116,33 +1097,33 @@ void helper_fxsave(target_ulong ptr, int data64)
     for (i = 0; i < 8; i++) {
         fptag |= (env->fptags[i] << i);
     }
-    stw(ptr, env->fpuc);
-    stw(ptr + 2, fpus);
-    stw(ptr + 4, fptag ^ 0xff);
+    cpu_stw_data(env, ptr, env->fpuc);
+    cpu_stw_data(env, ptr + 2, fpus);
+    cpu_stw_data(env, ptr + 4, fptag ^ 0xff);
 #ifdef TARGET_X86_64
     if (data64) {
-        stq(ptr + 0x08, 0); /* rip */
-        stq(ptr + 0x10, 0); /* rdp */
+        cpu_stq_data(env, ptr + 0x08, 0); /* rip */
+        cpu_stq_data(env, ptr + 0x10, 0); /* rdp */
     } else
 #endif
     {
-        stl(ptr + 0x08, 0); /* eip */
-        stl(ptr + 0x0c, 0); /* sel  */
-        stl(ptr + 0x10, 0); /* dp */
-        stl(ptr + 0x14, 0); /* sel  */
+        cpu_stl_data(env, ptr + 0x08, 0); /* eip */
+        cpu_stl_data(env, ptr + 0x0c, 0); /* sel  */
+        cpu_stl_data(env, ptr + 0x10, 0); /* dp */
+        cpu_stl_data(env, ptr + 0x14, 0); /* sel  */
     }
 
     addr = ptr + 0x20;
     for (i = 0; i < 8; i++) {
         tmp = ST(i);
-        helper_fstt(tmp, addr);
+        helper_fstt(env, tmp, addr);
         addr += 16;
     }
 
     if (env->cr[4] & CR4_OSFXSR_MASK) {
         /* XXX: finish it */
-        stl(ptr + 0x18, env->mxcsr); /* mxcsr */
-        stl(ptr + 0x1c, 0x0000ffff); /* mxcsr_mask */
+        cpu_stl_data(env, ptr + 0x18, env->mxcsr); /* mxcsr */
+        cpu_stl_data(env, ptr + 0x1c, 0x0000ffff); /* mxcsr_mask */
         if (env->hflags & HF_CS64_MASK) {
             nb_xmm_regs = 16;
         } else {
@@ -1154,15 +1135,15 @@ void helper_fxsave(target_ulong ptr, int data64)
             || (env->hflags & HF_CPL_MASK)
             || !(env->hflags & HF_LMA_MASK)) {
             for (i = 0; i < nb_xmm_regs; i++) {
-                stq(addr, env->xmm_regs[i].XMM_Q(0));
-                stq(addr + 8, env->xmm_regs[i].XMM_Q(1));
+                cpu_stq_data(env, addr, env->xmm_regs[i].XMM_Q(0));
+                cpu_stq_data(env, addr + 8, env->xmm_regs[i].XMM_Q(1));
                 addr += 16;
             }
         }
     }
 }
 
-void helper_fxrstor(target_ulong ptr, int data64)
+void helper_fxrstor(CPUX86State *env, target_ulong ptr, int data64)
 {
     int i, fpus, fptag, nb_xmm_regs;
     floatx80 tmp;
@@ -1173,9 +1154,9 @@ void helper_fxrstor(target_ulong ptr, int data64)
         raise_exception(env, EXCP0D_GPF);
     }
 
-    env->fpuc = lduw(ptr);
-    fpus = lduw(ptr + 2);
-    fptag = lduw(ptr + 4);
+    env->fpuc = cpu_lduw_data(env, ptr);
+    fpus = cpu_lduw_data(env, ptr + 2);
+    fptag = cpu_lduw_data(env, ptr + 4);
     env->fpstt = (fpus >> 11) & 7;
     env->fpus = fpus & ~0x3800;
     fptag ^= 0xff;
@@ -1185,15 +1166,15 @@ void helper_fxrstor(target_ulong ptr, int data64)
 
     addr = ptr + 0x20;
     for (i = 0; i < 8; i++) {
-        tmp = helper_fldt(addr);
+        tmp = helper_fldt(env, addr);
         ST(i) = tmp;
         addr += 16;
     }
 
     if (env->cr[4] & CR4_OSFXSR_MASK) {
         /* XXX: finish it */
-        env->mxcsr = ldl(ptr + 0x18);
-        /* ldl(ptr + 0x1c); */
+        env->mxcsr = cpu_ldl_data(env, ptr + 0x18);
+        /* cpu_ldl_data(env, ptr + 0x1c); */
         if (env->hflags & HF_CS64_MASK) {
             nb_xmm_regs = 16;
         } else {
@@ -1205,8 +1186,8 @@ void helper_fxrstor(target_ulong ptr, int data64)
             || (env->hflags & HF_CPL_MASK)
             || !(env->hflags & HF_LMA_MASK)) {
             for (i = 0; i < nb_xmm_regs; i++) {
-                env->xmm_regs[i].XMM_Q(0) = ldq(addr);
-                env->xmm_regs[i].XMM_Q(1) = ldq(addr + 8);
+                env->xmm_regs[i].XMM_Q(0) = cpu_ldq_data(env, addr);
+                env->xmm_regs[i].XMM_Q(1) = cpu_ldq_data(env, addr + 8);
                 addr += 16;
             }
         }
@@ -1242,7 +1223,7 @@ floatx80 cpu_set_fp80(uint64_t mant, uint16_t upper)
 #define SSE_RC_CHOP         0x6000
 #define SSE_FZ              0x8000
 
-static void update_sse_status(void)
+static void update_sse_status(CPUX86State *env)
 {
     int rnd_type;
 
@@ -1271,20 +1252,20 @@ static void update_sse_status(void)
     set_flush_to_zero((env->mxcsr & SSE_FZ) ? 1 : 0, &env->fp_status);
 }
 
-void helper_ldmxcsr(uint32_t val)
+void helper_ldmxcsr(CPUX86State *env, uint32_t val)
 {
     env->mxcsr = val;
-    update_sse_status();
+    update_sse_status(env);
 }
 
-void helper_enter_mmx(void)
+void helper_enter_mmx(CPUX86State *env)
 {
     env->fpstt = 0;
     *(uint32_t *)(env->fptags) = 0;
     *(uint32_t *)(env->fptags + 4) = 0;
 }
 
-void helper_emms(void)
+void helper_emms(CPUX86State *env)
 {
     /* set to empty state */
     *(uint32_t *)(env->fptags) = 0x01010101;
@@ -1292,7 +1273,7 @@ void helper_emms(void)
 }
 
 /* XXX: suppress */
-void helper_movq(void *d, void *s)
+void helper_movq(CPUX86State *env, void *d, void *s)
 {
     *(uint64_t *)d = *(uint64_t *)s;
 }
diff --git a/target-i386/helper.h b/target-i386/helper.h
index 99ca183..6fdee8a 100644
--- a/target-i386/helper.h
+++ b/target-i386/helper.h
@@ -109,98 +109,98 @@ DEF_HELPER_1(invlpga, void, int)
 
 /* x86 FPU */
 
-DEF_HELPER_1(flds_FT0, void, i32)
-DEF_HELPER_1(fldl_FT0, void, i64)
-DEF_HELPER_1(fildl_FT0, void, s32)
-DEF_HELPER_1(flds_ST0, void, i32)
-DEF_HELPER_1(fldl_ST0, void, i64)
-DEF_HELPER_1(fildl_ST0, void, s32)
-DEF_HELPER_1(fildll_ST0, void, s64)
-DEF_HELPER_0(fsts_ST0, i32)
-DEF_HELPER_0(fstl_ST0, i64)
-DEF_HELPER_0(fist_ST0, s32)
-DEF_HELPER_0(fistl_ST0, s32)
-DEF_HELPER_0(fistll_ST0, s64)
-DEF_HELPER_0(fistt_ST0, s32)
-DEF_HELPER_0(fisttl_ST0, s32)
-DEF_HELPER_0(fisttll_ST0, s64)
-DEF_HELPER_1(fldt_ST0, void, tl)
-DEF_HELPER_1(fstt_ST0, void, tl)
-DEF_HELPER_0(fpush, void)
-DEF_HELPER_0(fpop, void)
-DEF_HELPER_0(fdecstp, void)
-DEF_HELPER_0(fincstp, void)
-DEF_HELPER_1(ffree_STN, void, int)
-DEF_HELPER_0(fmov_ST0_FT0, void)
-DEF_HELPER_1(fmov_FT0_STN, void, int)
-DEF_HELPER_1(fmov_ST0_STN, void, int)
-DEF_HELPER_1(fmov_STN_ST0, void, int)
-DEF_HELPER_1(fxchg_ST0_STN, void, int)
-DEF_HELPER_0(fcom_ST0_FT0, void)
-DEF_HELPER_0(fucom_ST0_FT0, void)
-DEF_HELPER_0(fcomi_ST0_FT0, void)
-DEF_HELPER_0(fucomi_ST0_FT0, void)
-DEF_HELPER_0(fadd_ST0_FT0, void)
-DEF_HELPER_0(fmul_ST0_FT0, void)
-DEF_HELPER_0(fsub_ST0_FT0, void)
-DEF_HELPER_0(fsubr_ST0_FT0, void)
-DEF_HELPER_0(fdiv_ST0_FT0, void)
-DEF_HELPER_0(fdivr_ST0_FT0, void)
-DEF_HELPER_1(fadd_STN_ST0, void, int)
-DEF_HELPER_1(fmul_STN_ST0, void, int)
-DEF_HELPER_1(fsub_STN_ST0, void, int)
-DEF_HELPER_1(fsubr_STN_ST0, void, int)
-DEF_HELPER_1(fdiv_STN_ST0, void, int)
-DEF_HELPER_1(fdivr_STN_ST0, void, int)
-DEF_HELPER_0(fchs_ST0, void)
-DEF_HELPER_0(fabs_ST0, void)
-DEF_HELPER_0(fxam_ST0, void)
-DEF_HELPER_0(fld1_ST0, void)
-DEF_HELPER_0(fldl2t_ST0, void)
-DEF_HELPER_0(fldl2e_ST0, void)
-DEF_HELPER_0(fldpi_ST0, void)
-DEF_HELPER_0(fldlg2_ST0, void)
-DEF_HELPER_0(fldln2_ST0, void)
-DEF_HELPER_0(fldz_ST0, void)
-DEF_HELPER_0(fldz_FT0, void)
-DEF_HELPER_0(fnstsw, i32)
-DEF_HELPER_0(fnstcw, i32)
-DEF_HELPER_1(fldcw, void, i32)
-DEF_HELPER_0(fclex, void)
-DEF_HELPER_0(fwait, void)
-DEF_HELPER_0(fninit, void)
-DEF_HELPER_1(fbld_ST0, void, tl)
-DEF_HELPER_1(fbst_ST0, void, tl)
-DEF_HELPER_0(f2xm1, void)
-DEF_HELPER_0(fyl2x, void)
-DEF_HELPER_0(fptan, void)
-DEF_HELPER_0(fpatan, void)
-DEF_HELPER_0(fxtract, void)
-DEF_HELPER_0(fprem1, void)
-DEF_HELPER_0(fprem, void)
-DEF_HELPER_0(fyl2xp1, void)
-DEF_HELPER_0(fsqrt, void)
-DEF_HELPER_0(fsincos, void)
-DEF_HELPER_0(frndint, void)
-DEF_HELPER_0(fscale, void)
-DEF_HELPER_0(fsin, void)
-DEF_HELPER_0(fcos, void)
-DEF_HELPER_2(fstenv, void, tl, int)
-DEF_HELPER_2(fldenv, void, tl, int)
-DEF_HELPER_2(fsave, void, tl, int)
-DEF_HELPER_2(frstor, void, tl, int)
-DEF_HELPER_2(fxsave, void, tl, int)
-DEF_HELPER_2(fxrstor, void, tl, int)
+DEF_HELPER_2(flds_FT0, void, env, i32)
+DEF_HELPER_2(fldl_FT0, void, env, i64)
+DEF_HELPER_2(fildl_FT0, void, env, s32)
+DEF_HELPER_2(flds_ST0, void, env, i32)
+DEF_HELPER_2(fldl_ST0, void, env, i64)
+DEF_HELPER_2(fildl_ST0, void, env, s32)
+DEF_HELPER_2(fildll_ST0, void, env, s64)
+DEF_HELPER_1(fsts_ST0, i32, env)
+DEF_HELPER_1(fstl_ST0, i64, env)
+DEF_HELPER_1(fist_ST0, s32, env)
+DEF_HELPER_1(fistl_ST0, s32, env)
+DEF_HELPER_1(fistll_ST0, s64, env)
+DEF_HELPER_1(fistt_ST0, s32, env)
+DEF_HELPER_1(fisttl_ST0, s32, env)
+DEF_HELPER_1(fisttll_ST0, s64, env)
+DEF_HELPER_2(fldt_ST0, void, env, tl)
+DEF_HELPER_2(fstt_ST0, void, env, tl)
+DEF_HELPER_1(fpush, void, env)
+DEF_HELPER_1(fpop, void, env)
+DEF_HELPER_1(fdecstp, void, env)
+DEF_HELPER_1(fincstp, void, env)
+DEF_HELPER_2(ffree_STN, void, env, int)
+DEF_HELPER_1(fmov_ST0_FT0, void, env)
+DEF_HELPER_2(fmov_FT0_STN, void, env, int)
+DEF_HELPER_2(fmov_ST0_STN, void, env, int)
+DEF_HELPER_2(fmov_STN_ST0, void, env, int)
+DEF_HELPER_2(fxchg_ST0_STN, void, env, int)
+DEF_HELPER_1(fcom_ST0_FT0, void, env)
+DEF_HELPER_1(fucom_ST0_FT0, void, env)
+DEF_HELPER_1(fcomi_ST0_FT0, void, env)
+DEF_HELPER_1(fucomi_ST0_FT0, void, env)
+DEF_HELPER_1(fadd_ST0_FT0, void, env)
+DEF_HELPER_1(fmul_ST0_FT0, void, env)
+DEF_HELPER_1(fsub_ST0_FT0, void, env)
+DEF_HELPER_1(fsubr_ST0_FT0, void, env)
+DEF_HELPER_1(fdiv_ST0_FT0, void, env)
+DEF_HELPER_1(fdivr_ST0_FT0, void, env)
+DEF_HELPER_2(fadd_STN_ST0, void, env, int)
+DEF_HELPER_2(fmul_STN_ST0, void, env, int)
+DEF_HELPER_2(fsub_STN_ST0, void, env, int)
+DEF_HELPER_2(fsubr_STN_ST0, void, env, int)
+DEF_HELPER_2(fdiv_STN_ST0, void, env, int)
+DEF_HELPER_2(fdivr_STN_ST0, void, env, int)
+DEF_HELPER_1(fchs_ST0, void, env)
+DEF_HELPER_1(fabs_ST0, void, env)
+DEF_HELPER_1(fxam_ST0, void, env)
+DEF_HELPER_1(fld1_ST0, void, env)
+DEF_HELPER_1(fldl2t_ST0, void, env)
+DEF_HELPER_1(fldl2e_ST0, void, env)
+DEF_HELPER_1(fldpi_ST0, void, env)
+DEF_HELPER_1(fldlg2_ST0, void, env)
+DEF_HELPER_1(fldln2_ST0, void, env)
+DEF_HELPER_1(fldz_ST0, void, env)
+DEF_HELPER_1(fldz_FT0, void, env)
+DEF_HELPER_1(fnstsw, i32, env)
+DEF_HELPER_1(fnstcw, i32, env)
+DEF_HELPER_2(fldcw, void, env, i32)
+DEF_HELPER_1(fclex, void, env)
+DEF_HELPER_1(fwait, void, env)
+DEF_HELPER_1(fninit, void, env)
+DEF_HELPER_2(fbld_ST0, void, env, tl)
+DEF_HELPER_2(fbst_ST0, void, env, tl)
+DEF_HELPER_1(f2xm1, void, env)
+DEF_HELPER_1(fyl2x, void, env)
+DEF_HELPER_1(fptan, void, env)
+DEF_HELPER_1(fpatan, void, env)
+DEF_HELPER_1(fxtract, void, env)
+DEF_HELPER_1(fprem1, void, env)
+DEF_HELPER_1(fprem, void, env)
+DEF_HELPER_1(fyl2xp1, void, env)
+DEF_HELPER_1(fsqrt, void, env)
+DEF_HELPER_1(fsincos, void, env)
+DEF_HELPER_1(frndint, void, env)
+DEF_HELPER_1(fscale, void, env)
+DEF_HELPER_1(fsin, void, env)
+DEF_HELPER_1(fcos, void, env)
+DEF_HELPER_3(fstenv, void, env, tl, int)
+DEF_HELPER_3(fldenv, void, env, tl, int)
+DEF_HELPER_3(fsave, void, env, tl, int)
+DEF_HELPER_3(frstor, void, env, tl, int)
+DEF_HELPER_3(fxsave, void, env, tl, int)
+DEF_HELPER_3(fxrstor, void, env, tl, int)
 DEF_HELPER_1(bsf, tl, tl)
 DEF_HELPER_1(bsr, tl, tl)
 DEF_HELPER_2(lzcnt, tl, tl, int)
 
 /* MMX/SSE */
 
-DEF_HELPER_1(ldmxcsr, void, i32)
-DEF_HELPER_0(enter_mmx, void)
-DEF_HELPER_0(emms, void)
-DEF_HELPER_2(movq, void, ptr, ptr)
+DEF_HELPER_2(ldmxcsr, void, env, i32)
+DEF_HELPER_1(enter_mmx, void, env)
+DEF_HELPER_1(emms, void, env)
+DEF_HELPER_3(movq, void, env, ptr, ptr)
 
 #define SHIFT 0
 #include "ops_sse_header.h"
diff --git a/target-i386/mem_helper.c b/target-i386/mem_helper.c
index 91353c0..4e0af4b 100644
--- a/target-i386/mem_helper.c
+++ b/target-i386/mem_helper.c
@@ -159,3 +159,52 @@ void tlb_fill(CPUX86State *env1, target_ulong addr, int is_write, int mmu_idx,
     env = saved_env;
 }
 #endif
+
+/* temporary wrappers */
+#if defined(CONFIG_USER_ONLY)
+#define ldub_data(addr) ldub_raw(addr)
+#define lduw_data(addr) lduw_raw(addr)
+#define ldl_data(addr) ldl_raw(addr)
+#define ldq_data(addr) ldq_raw(addr)
+
+#define stb_data(addr, data) stb_raw(addr, data)
+#define stw_data(addr, data) stw_raw(addr, data)
+#define stl_data(addr, data) stl_raw(addr, data)
+#define stq_data(addr, data) stq_raw(addr, data)
+#endif
+
+#define WRAP_LD(rettype, fn)                                    \
+    rettype cpu_ ## fn(CPUX86State *env1, target_ulong addr)    \
+    {                                                           \
+        CPUX86State *saved_env;                                 \
+        rettype ret;                                            \
+                                                                \
+        saved_env = env;                                        \
+        env = env1;                                             \
+        ret = fn(addr);                                         \
+        env = saved_env;                                        \
+        return ret;                                             \
+    }
+
+WRAP_LD(uint32_t, ldub_data)
+WRAP_LD(uint32_t, lduw_data)
+WRAP_LD(uint32_t, ldl_data)
+WRAP_LD(uint64_t, ldq_data)
+#undef WRAP_LD
+
+#define WRAP_ST(datatype, fn)                                           \
+    void cpu_ ## fn(CPUX86State *env1, target_ulong addr, datatype val) \
+    {                                                                   \
+        CPUX86State *saved_env;                                         \
+                                                                        \
+        saved_env = env;                                                \
+        env = env1;                                                     \
+        fn(addr, val);                                                  \
+        env = saved_env;                                                \
+    }
+
+WRAP_ST(uint32_t, stb_data)
+WRAP_ST(uint32_t, stw_data)
+WRAP_ST(uint32_t, stl_data)
+WRAP_ST(uint64_t, stq_data)
+#undef WRAP_ST
diff --git a/target-i386/ops_sse.h b/target-i386/ops_sse.h
index d109512..cad9d75 100644
--- a/target-i386/ops_sse.h
+++ b/target-i386/ops_sse.h
@@ -35,7 +35,7 @@
 #define SUFFIX _xmm
 #endif
 
-void glue(helper_psrlw, SUFFIX)(Reg *d, Reg *s)
+void glue(helper_psrlw, SUFFIX)(CPUX86State *env, Reg *d, Reg *s)
 {
     int shift;
 
@@ -59,7 +59,7 @@ void glue(helper_psrlw, SUFFIX)(Reg *d, Reg *s)
     }
 }
 
-void glue(helper_psraw, SUFFIX)(Reg *d, Reg *s)
+void glue(helper_psraw, SUFFIX)(CPUX86State *env, Reg *d, Reg *s)
 {
     int shift;
 
@@ -80,7 +80,7 @@ void glue(helper_psraw, SUFFIX)(Reg *d, Reg *s)
 #endif
 }
 
-void glue(helper_psllw, SUFFIX)(Reg *d, Reg *s)
+void glue(helper_psllw, SUFFIX)(CPUX86State *env, Reg *d, Reg *s)
 {
     int shift;
 
@@ -104,7 +104,7 @@ void glue(helper_psllw, SUFFIX)(Reg *d, Reg *s)
     }
 }
 
-void glue(helper_psrld, SUFFIX)(Reg *d, Reg *s)
+void glue(helper_psrld, SUFFIX)(CPUX86State *env, Reg *d, Reg *s)
 {
     int shift;
 
@@ -124,7 +124,7 @@ void glue(helper_psrld, SUFFIX)(Reg *d, Reg *s)
     }
 }
 
-void glue(helper_psrad, SUFFIX)(Reg *d, Reg *s)
+void glue(helper_psrad, SUFFIX)(CPUX86State *env, Reg *d, Reg *s)
 {
     int shift;
 
@@ -141,7 +141,7 @@ void glue(helper_psrad, SUFFIX)(Reg *d, Reg *s)
 #endif
 }
 
-void glue(helper_pslld, SUFFIX)(Reg *d, Reg *s)
+void glue(helper_pslld, SUFFIX)(CPUX86State *env, Reg *d, Reg *s)
 {
     int shift;
 
@@ -161,7 +161,7 @@ void glue(helper_pslld, SUFFIX)(Reg *d, Reg *s)
     }
 }
 
-void glue(helper_psrlq, SUFFIX)(Reg *d, Reg *s)
+void glue(helper_psrlq, SUFFIX)(CPUX86State *env, Reg *d, Reg *s)
 {
     int shift;
 
@@ -179,7 +179,7 @@ void glue(helper_psrlq, SUFFIX)(Reg *d, Reg *s)
     }
 }
 
-void glue(helper_psllq, SUFFIX)(Reg *d, Reg *s)
+void glue(helper_psllq, SUFFIX)(CPUX86State *env, Reg *d, Reg *s)
 {
     int shift;
 
@@ -198,7 +198,7 @@ void glue(helper_psllq, SUFFIX)(Reg *d, Reg *s)
 }
 
 #if SHIFT == 1
-void glue(helper_psrldq, SUFFIX)(Reg *d, Reg *s)
+void glue(helper_psrldq, SUFFIX)(CPUX86State *env, Reg *d, Reg *s)
 {
     int shift, i;
 
@@ -214,7 +214,7 @@ void glue(helper_psrldq, SUFFIX)(Reg *d, Reg *s)
     }
 }
 
-void glue(helper_pslldq, SUFFIX)(Reg *d, Reg *s)
+void glue(helper_pslldq, SUFFIX)(CPUX86State *env, Reg *d, Reg *s)
 {
     int shift, i;
 
@@ -232,7 +232,7 @@ void glue(helper_pslldq, SUFFIX)(Reg *d, Reg *s)
 #endif
 
 #define SSE_HELPER_B(name, F)                                   \
-    void glue(name, SUFFIX)(Reg *d, Reg *s)                     \
+    void glue(name, SUFFIX)(CPUX86State *env, Reg *d, Reg *s)   \
     {                                                           \
         d->B(0) = F(d->B(0), s->B(0));                          \
         d->B(1) = F(d->B(1), s->B(1));                          \
@@ -255,7 +255,7 @@ void glue(helper_pslldq, SUFFIX)(Reg *d, Reg *s)
             }
 
 #define SSE_HELPER_W(name, F)                                   \
-    void glue(name, SUFFIX)(Reg *d, Reg *s)                     \
+    void glue(name, SUFFIX)(CPUX86State *env, Reg *d, Reg *s)   \
     {                                                           \
         d->W(0) = F(d->W(0), s->W(0));                          \
         d->W(1) = F(d->W(1), s->W(1));                          \
@@ -270,7 +270,7 @@ void glue(helper_pslldq, SUFFIX)(Reg *d, Reg *s)
             }
 
 #define SSE_HELPER_L(name, F)                                   \
-    void glue(name, SUFFIX)(Reg *d, Reg *s)                     \
+    void glue(name, SUFFIX)(CPUX86State *env, Reg *d, Reg *s)   \
     {                                                           \
         d->L(0) = F(d->L(0), s->L(0));                          \
         d->L(1) = F(d->L(1), s->L(1));                          \
@@ -281,7 +281,7 @@ void glue(helper_pslldq, SUFFIX)(Reg *d, Reg *s)
             }
 
 #define SSE_HELPER_Q(name, F)                                   \
-    void glue(name, SUFFIX)(Reg *d, Reg *s)                     \
+    void glue(name, SUFFIX)(CPUX86State *env, Reg *d, Reg *s)   \
     {                                                           \
         d->Q(0) = F(d->Q(0), s->Q(0));                          \
         XMM_ONLY(                                               \
@@ -417,7 +417,7 @@ SSE_HELPER_W(helper_pmulhw, FMULHW)
 SSE_HELPER_B(helper_pavgb, FAVG)
 SSE_HELPER_W(helper_pavgw, FAVG)
 
-void glue(helper_pmuludq, SUFFIX)(Reg *d, Reg *s)
+void glue(helper_pmuludq, SUFFIX)(CPUX86State *env, Reg *d, Reg *s)
 {
     d->Q(0) = (uint64_t)s->L(0) * (uint64_t)d->L(0);
 #if SHIFT == 1
@@ -425,7 +425,7 @@ void glue(helper_pmuludq, SUFFIX)(Reg *d, Reg *s)
 #endif
 }
 
-void glue(helper_pmaddwd, SUFFIX)(Reg *d, Reg *s)
+void glue(helper_pmaddwd, SUFFIX)(CPUX86State *env, Reg *d, Reg *s)
 {
     int i;
 
@@ -445,7 +445,7 @@ static inline int abs1(int a)
     }
 }
 #endif
-void glue(helper_psadbw, SUFFIX)(Reg *d, Reg *s)
+void glue(helper_psadbw, SUFFIX)(CPUX86State *env, Reg *d, Reg *s)
 {
     unsigned int val;
 
@@ -473,13 +473,14 @@ void glue(helper_psadbw, SUFFIX)(Reg *d, Reg *s)
 #endif
 }
 
-void glue(helper_maskmov, SUFFIX)(Reg *d, Reg *s, target_ulong a0)
+void glue(helper_maskmov, SUFFIX)(CPUX86State *env, Reg *d, Reg *s,
+                                  target_ulong a0)
 {
     int i;
 
     for (i = 0; i < (8 << SHIFT); i++) {
         if (s->B(i) & 0x80) {
-            stb(a0 + i, d->B(i));
+            cpu_stb_data(env, a0 + i, d->B(i));
         }
     }
 }
@@ -575,29 +576,29 @@ void glue(helper_pshufhw, SUFFIX)(Reg *d, Reg *s, int order)
 /* FPU ops */
 /* XXX: not accurate */
 
-#define SSE_HELPER_S(name, F)                           \
-    void helper_ ## name ## ps(Reg *d, Reg *s)          \
-    {                                                   \
-        d->XMM_S(0) = F(32, d->XMM_S(0), s->XMM_S(0));  \
-        d->XMM_S(1) = F(32, d->XMM_S(1), s->XMM_S(1));  \
-        d->XMM_S(2) = F(32, d->XMM_S(2), s->XMM_S(2));  \
-        d->XMM_S(3) = F(32, d->XMM_S(3), s->XMM_S(3));  \
-    }                                                   \
-                                                        \
-    void helper_ ## name ## ss(Reg *d, Reg *s)          \
-    {                                                   \
-        d->XMM_S(0) = F(32, d->XMM_S(0), s->XMM_S(0));  \
-    }                                                   \
-                                                        \
-    void helper_ ## name ## pd(Reg *d, Reg *s)          \
-    {                                                   \
-        d->XMM_D(0) = F(64, d->XMM_D(0), s->XMM_D(0));  \
-        d->XMM_D(1) = F(64, d->XMM_D(1), s->XMM_D(1));  \
-    }                                                   \
-                                                        \
-    void helper_ ## name ## sd(Reg *d, Reg *s)          \
-    {                                                   \
-        d->XMM_D(0) = F(64, d->XMM_D(0), s->XMM_D(0));  \
+#define SSE_HELPER_S(name, F)                                           \
+    void helper_ ## name ## ps(CPUX86State *env, Reg *d, Reg *s)        \
+    {                                                                   \
+        d->XMM_S(0) = F(32, d->XMM_S(0), s->XMM_S(0));                  \
+        d->XMM_S(1) = F(32, d->XMM_S(1), s->XMM_S(1));                  \
+        d->XMM_S(2) = F(32, d->XMM_S(2), s->XMM_S(2));                  \
+        d->XMM_S(3) = F(32, d->XMM_S(3), s->XMM_S(3));                  \
+    }                                                                   \
+                                                                        \
+    void helper_ ## name ## ss(CPUX86State *env, Reg *d, Reg *s)        \
+    {                                                                   \
+        d->XMM_S(0) = F(32, d->XMM_S(0), s->XMM_S(0));                  \
+    }                                                                   \
+                                                                        \
+    void helper_ ## name ## pd(CPUX86State *env, Reg *d, Reg *s)        \
+    {                                                                   \
+        d->XMM_D(0) = F(64, d->XMM_D(0), s->XMM_D(0));                  \
+        d->XMM_D(1) = F(64, d->XMM_D(1), s->XMM_D(1));                  \
+    }                                                                   \
+                                                                        \
+    void helper_ ## name ## sd(CPUX86State *env, Reg *d, Reg *s)        \
+    {                                                                   \
+        d->XMM_D(0) = F(64, d->XMM_D(0), s->XMM_D(0));                  \
     }
 
 #define FPU_ADD(size, a, b) float ## size ## _add(a, b, &env->sse_status)
@@ -625,7 +626,7 @@ SSE_HELPER_S(sqrt, FPU_SQRT)
 
 
 /* float to float conversions */
-void helper_cvtps2pd(Reg *d, Reg *s)
+void helper_cvtps2pd(CPUX86State *env, Reg *d, Reg *s)
 {
     float32 s0, s1;
 
@@ -635,25 +636,25 @@ void helper_cvtps2pd(Reg *d, Reg *s)
     d->XMM_D(1) = float32_to_float64(s1, &env->sse_status);
 }
 
-void helper_cvtpd2ps(Reg *d, Reg *s)
+void helper_cvtpd2ps(CPUX86State *env, Reg *d, Reg *s)
 {
     d->XMM_S(0) = float64_to_float32(s->XMM_D(0), &env->sse_status);
     d->XMM_S(1) = float64_to_float32(s->XMM_D(1), &env->sse_status);
     d->Q(1) = 0;
 }
 
-void helper_cvtss2sd(Reg *d, Reg *s)
+void helper_cvtss2sd(CPUX86State *env, Reg *d, Reg *s)
 {
     d->XMM_D(0) = float32_to_float64(s->XMM_S(0), &env->sse_status);
 }
 
-void helper_cvtsd2ss(Reg *d, Reg *s)
+void helper_cvtsd2ss(CPUX86State *env, Reg *d, Reg *s)
 {
     d->XMM_S(0) = float64_to_float32(s->XMM_D(0), &env->sse_status);
 }
 
 /* integer to float */
-void helper_cvtdq2ps(Reg *d, Reg *s)
+void helper_cvtdq2ps(CPUX86State *env, Reg *d, Reg *s)
 {
     d->XMM_S(0) = int32_to_float32(s->XMM_L(0), &env->sse_status);
     d->XMM_S(1) = int32_to_float32(s->XMM_L(1), &env->sse_status);
@@ -661,7 +662,7 @@ void helper_cvtdq2ps(Reg *d, Reg *s)
     d->XMM_S(3) = int32_to_float32(s->XMM_L(3), &env->sse_status);
 }
 
-void helper_cvtdq2pd(Reg *d, Reg *s)
+void helper_cvtdq2pd(CPUX86State *env, Reg *d, Reg *s)
 {
     int32_t l0, l1;
 
@@ -671,42 +672,42 @@ void helper_cvtdq2pd(Reg *d, Reg *s)
     d->XMM_D(1) = int32_to_float64(l1, &env->sse_status);
 }
 
-void helper_cvtpi2ps(XMMReg *d, MMXReg *s)
+void helper_cvtpi2ps(CPUX86State *env, XMMReg *d, MMXReg *s)
 {
     d->XMM_S(0) = int32_to_float32(s->MMX_L(0), &env->sse_status);
     d->XMM_S(1) = int32_to_float32(s->MMX_L(1), &env->sse_status);
 }
 
-void helper_cvtpi2pd(XMMReg *d, MMXReg *s)
+void helper_cvtpi2pd(CPUX86State *env, XMMReg *d, MMXReg *s)
 {
     d->XMM_D(0) = int32_to_float64(s->MMX_L(0), &env->sse_status);
     d->XMM_D(1) = int32_to_float64(s->MMX_L(1), &env->sse_status);
 }
 
-void helper_cvtsi2ss(XMMReg *d, uint32_t val)
+void helper_cvtsi2ss(CPUX86State *env, XMMReg *d, uint32_t val)
 {
     d->XMM_S(0) = int32_to_float32(val, &env->sse_status);
 }
 
-void helper_cvtsi2sd(XMMReg *d, uint32_t val)
+void helper_cvtsi2sd(CPUX86State *env, XMMReg *d, uint32_t val)
 {
     d->XMM_D(0) = int32_to_float64(val, &env->sse_status);
 }
 
 #ifdef TARGET_X86_64
-void helper_cvtsq2ss(XMMReg *d, uint64_t val)
+void helper_cvtsq2ss(CPUX86State *env, XMMReg *d, uint64_t val)
 {
     d->XMM_S(0) = int64_to_float32(val, &env->sse_status);
 }
 
-void helper_cvtsq2sd(XMMReg *d, uint64_t val)
+void helper_cvtsq2sd(CPUX86State *env, XMMReg *d, uint64_t val)
 {
     d->XMM_D(0) = int64_to_float64(val, &env->sse_status);
 }
 #endif
 
 /* float to integer */
-void helper_cvtps2dq(XMMReg *d, XMMReg *s)
+void helper_cvtps2dq(CPUX86State *env, XMMReg *d, XMMReg *s)
 {
     d->XMM_L(0) = float32_to_int32(s->XMM_S(0), &env->sse_status);
     d->XMM_L(1) = float32_to_int32(s->XMM_S(1), &env->sse_status);
@@ -714,49 +715,49 @@ void helper_cvtps2dq(XMMReg *d, XMMReg *s)
     d->XMM_L(3) = float32_to_int32(s->XMM_S(3), &env->sse_status);
 }
 
-void helper_cvtpd2dq(XMMReg *d, XMMReg *s)
+void helper_cvtpd2dq(CPUX86State *env, XMMReg *d, XMMReg *s)
 {
     d->XMM_L(0) = float64_to_int32(s->XMM_D(0), &env->sse_status);
     d->XMM_L(1) = float64_to_int32(s->XMM_D(1), &env->sse_status);
     d->XMM_Q(1) = 0;
 }
 
-void helper_cvtps2pi(MMXReg *d, XMMReg *s)
+void helper_cvtps2pi(CPUX86State *env, MMXReg *d, XMMReg *s)
 {
     d->MMX_L(0) = float32_to_int32(s->XMM_S(0), &env->sse_status);
     d->MMX_L(1) = float32_to_int32(s->XMM_S(1), &env->sse_status);
 }
 
-void helper_cvtpd2pi(MMXReg *d, XMMReg *s)
+void helper_cvtpd2pi(CPUX86State *env, MMXReg *d, XMMReg *s)
 {
     d->MMX_L(0) = float64_to_int32(s->XMM_D(0), &env->sse_status);
     d->MMX_L(1) = float64_to_int32(s->XMM_D(1), &env->sse_status);
 }
 
-int32_t helper_cvtss2si(XMMReg *s)
+int32_t helper_cvtss2si(CPUX86State *env, XMMReg *s)
 {
     return float32_to_int32(s->XMM_S(0), &env->sse_status);
 }
 
-int32_t helper_cvtsd2si(XMMReg *s)
+int32_t helper_cvtsd2si(CPUX86State *env, XMMReg *s)
 {
     return float64_to_int32(s->XMM_D(0), &env->sse_status);
 }
 
 #ifdef TARGET_X86_64
-int64_t helper_cvtss2sq(XMMReg *s)
+int64_t helper_cvtss2sq(CPUX86State *env, XMMReg *s)
 {
     return float32_to_int64(s->XMM_S(0), &env->sse_status);
 }
 
-int64_t helper_cvtsd2sq(XMMReg *s)
+int64_t helper_cvtsd2sq(CPUX86State *env, XMMReg *s)
 {
     return float64_to_int64(s->XMM_D(0), &env->sse_status);
 }
 #endif
 
 /* float to integer truncated */
-void helper_cvttps2dq(XMMReg *d, XMMReg *s)
+void helper_cvttps2dq(CPUX86State *env, XMMReg *d, XMMReg *s)
 {
     d->XMM_L(0) = float32_to_int32_round_to_zero(s->XMM_S(0), &env->sse_status);
     d->XMM_L(1) = float32_to_int32_round_to_zero(s->XMM_S(1), &env->sse_status);
@@ -764,48 +765,48 @@ void helper_cvttps2dq(XMMReg *d, XMMReg *s)
     d->XMM_L(3) = float32_to_int32_round_to_zero(s->XMM_S(3), &env->sse_status);
 }
 
-void helper_cvttpd2dq(XMMReg *d, XMMReg *s)
+void helper_cvttpd2dq(CPUX86State *env, XMMReg *d, XMMReg *s)
 {
     d->XMM_L(0) = float64_to_int32_round_to_zero(s->XMM_D(0), &env->sse_status);
     d->XMM_L(1) = float64_to_int32_round_to_zero(s->XMM_D(1), &env->sse_status);
     d->XMM_Q(1) = 0;
 }
 
-void helper_cvttps2pi(MMXReg *d, XMMReg *s)
+void helper_cvttps2pi(CPUX86State *env, MMXReg *d, XMMReg *s)
 {
     d->MMX_L(0) = float32_to_int32_round_to_zero(s->XMM_S(0), &env->sse_status);
     d->MMX_L(1) = float32_to_int32_round_to_zero(s->XMM_S(1), &env->sse_status);
 }
 
-void helper_cvttpd2pi(MMXReg *d, XMMReg *s)
+void helper_cvttpd2pi(CPUX86State *env, MMXReg *d, XMMReg *s)
 {
     d->MMX_L(0) = float64_to_int32_round_to_zero(s->XMM_D(0), &env->sse_status);
     d->MMX_L(1) = float64_to_int32_round_to_zero(s->XMM_D(1), &env->sse_status);
 }
 
-int32_t helper_cvttss2si(XMMReg *s)
+int32_t helper_cvttss2si(CPUX86State *env, XMMReg *s)
 {
     return float32_to_int32_round_to_zero(s->XMM_S(0), &env->sse_status);
 }
 
-int32_t helper_cvttsd2si(XMMReg *s)
+int32_t helper_cvttsd2si(CPUX86State *env, XMMReg *s)
 {
     return float64_to_int32_round_to_zero(s->XMM_D(0), &env->sse_status);
 }
 
 #ifdef TARGET_X86_64
-int64_t helper_cvttss2sq(XMMReg *s)
+int64_t helper_cvttss2sq(CPUX86State *env, XMMReg *s)
 {
     return float32_to_int64_round_to_zero(s->XMM_S(0), &env->sse_status);
 }
 
-int64_t helper_cvttsd2sq(XMMReg *s)
+int64_t helper_cvttsd2sq(CPUX86State *env, XMMReg *s)
 {
     return float64_to_int64_round_to_zero(s->XMM_D(0), &env->sse_status);
 }
 #endif
 
-void helper_rsqrtps(XMMReg *d, XMMReg *s)
+void helper_rsqrtps(CPUX86State *env, XMMReg *d, XMMReg *s)
 {
     d->XMM_S(0) = float32_div(float32_one,
                               float32_sqrt(s->XMM_S(0), &env->sse_status),
@@ -821,14 +822,14 @@ void helper_rsqrtps(XMMReg *d, XMMReg *s)
                               &env->sse_status);
 }
 
-void helper_rsqrtss(XMMReg *d, XMMReg *s)
+void helper_rsqrtss(CPUX86State *env, XMMReg *d, XMMReg *s)
 {
     d->XMM_S(0) = float32_div(float32_one,
                               float32_sqrt(s->XMM_S(0), &env->sse_status),
                               &env->sse_status);
 }
 
-void helper_rcpps(XMMReg *d, XMMReg *s)
+void helper_rcpps(CPUX86State *env, XMMReg *d, XMMReg *s)
 {
     d->XMM_S(0) = float32_div(float32_one, s->XMM_S(0), &env->sse_status);
     d->XMM_S(1) = float32_div(float32_one, s->XMM_S(1), &env->sse_status);
@@ -836,7 +837,7 @@ void helper_rcpps(XMMReg *d, XMMReg *s)
     d->XMM_S(3) = float32_div(float32_one, s->XMM_S(3), &env->sse_status);
 }
 
-void helper_rcpss(XMMReg *d, XMMReg *s)
+void helper_rcpss(CPUX86State *env, XMMReg *d, XMMReg *s)
 {
     d->XMM_S(0) = float32_div(float32_one, s->XMM_S(0), &env->sse_status);
 }
@@ -853,12 +854,12 @@ static inline uint64_t helper_extrq(uint64_t src, int shift, int len)
     return (src >> shift) & mask;
 }
 
-void helper_extrq_r(XMMReg *d, XMMReg *s)
+void helper_extrq_r(CPUX86State *env, XMMReg *d, XMMReg *s)
 {
     d->XMM_Q(0) = helper_extrq(d->XMM_Q(0), s->XMM_B(1), s->XMM_B(0));
 }
 
-void helper_extrq_i(XMMReg *d, int index, int length)
+void helper_extrq_i(CPUX86State *env, XMMReg *d, int index, int length)
 {
     d->XMM_Q(0) = helper_extrq(d->XMM_Q(0), index, length);
 }
@@ -875,17 +876,17 @@ static inline uint64_t helper_insertq(uint64_t src, int shift, int len)
     return (src & ~(mask << shift)) | ((src & mask) << shift);
 }
 
-void helper_insertq_r(XMMReg *d, XMMReg *s)
+void helper_insertq_r(CPUX86State *env, XMMReg *d, XMMReg *s)
 {
     d->XMM_Q(0) = helper_insertq(s->XMM_Q(0), s->XMM_B(9), s->XMM_B(8));
 }
 
-void helper_insertq_i(XMMReg *d, int index, int length)
+void helper_insertq_i(CPUX86State *env, XMMReg *d, int index, int length)
 {
     d->XMM_Q(0) = helper_insertq(d->XMM_Q(0), index, length);
 }
 
-void helper_haddps(XMMReg *d, XMMReg *s)
+void helper_haddps(CPUX86State *env, XMMReg *d, XMMReg *s)
 {
     XMMReg r;
 
@@ -896,7 +897,7 @@ void helper_haddps(XMMReg *d, XMMReg *s)
     *d = r;
 }
 
-void helper_haddpd(XMMReg *d, XMMReg *s)
+void helper_haddpd(CPUX86State *env, XMMReg *d, XMMReg *s)
 {
     XMMReg r;
 
@@ -905,7 +906,7 @@ void helper_haddpd(XMMReg *d, XMMReg *s)
     *d = r;
 }
 
-void helper_hsubps(XMMReg *d, XMMReg *s)
+void helper_hsubps(CPUX86State *env, XMMReg *d, XMMReg *s)
 {
     XMMReg r;
 
@@ -916,7 +917,7 @@ void helper_hsubps(XMMReg *d, XMMReg *s)
     *d = r;
 }
 
-void helper_hsubpd(XMMReg *d, XMMReg *s)
+void helper_hsubpd(CPUX86State *env, XMMReg *d, XMMReg *s)
 {
     XMMReg r;
 
@@ -925,7 +926,7 @@ void helper_hsubpd(XMMReg *d, XMMReg *s)
     *d = r;
 }
 
-void helper_addsubps(XMMReg *d, XMMReg *s)
+void helper_addsubps(CPUX86State *env, XMMReg *d, XMMReg *s)
 {
     d->XMM_S(0) = float32_sub(d->XMM_S(0), s->XMM_S(0), &env->sse_status);
     d->XMM_S(1) = float32_add(d->XMM_S(1), s->XMM_S(1), &env->sse_status);
@@ -933,36 +934,36 @@ void helper_addsubps(XMMReg *d, XMMReg *s)
     d->XMM_S(3) = float32_add(d->XMM_S(3), s->XMM_S(3), &env->sse_status);
 }
 
-void helper_addsubpd(XMMReg *d, XMMReg *s)
+void helper_addsubpd(CPUX86State *env, XMMReg *d, XMMReg *s)
 {
     d->XMM_D(0) = float64_sub(d->XMM_D(0), s->XMM_D(0), &env->sse_status);
     d->XMM_D(1) = float64_add(d->XMM_D(1), s->XMM_D(1), &env->sse_status);
 }
 
 /* XXX: unordered */
-#define SSE_HELPER_CMP(name, F)                         \
-    void helper_ ## name ## ps(Reg *d, Reg *s)          \
-    {                                                   \
-        d->XMM_L(0) = F(32, d->XMM_S(0), s->XMM_S(0));  \
-        d->XMM_L(1) = F(32, d->XMM_S(1), s->XMM_S(1));  \
-        d->XMM_L(2) = F(32, d->XMM_S(2), s->XMM_S(2));  \
-        d->XMM_L(3) = F(32, d->XMM_S(3), s->XMM_S(3));  \
-    }                                                   \
-                                                        \
-    void helper_ ## name ## ss(Reg *d, Reg *s)          \
-    {                                                   \
-        d->XMM_L(0) = F(32, d->XMM_S(0), s->XMM_S(0));  \
-    }                                                   \
-                                                        \
-    void helper_ ## name ## pd(Reg *d, Reg *s)          \
-    {                                                   \
-        d->XMM_Q(0) = F(64, d->XMM_D(0), s->XMM_D(0));  \
-        d->XMM_Q(1) = F(64, d->XMM_D(1), s->XMM_D(1));  \
-    }                                                   \
-                                                        \
-    void helper_ ## name ## sd(Reg *d, Reg *s)          \
-    {                                                   \
-        d->XMM_Q(0) = F(64, d->XMM_D(0), s->XMM_D(0));  \
+#define SSE_HELPER_CMP(name, F)                                         \
+    void helper_ ## name ## ps(CPUX86State *env, Reg *d, Reg *s)        \
+    {                                                                   \
+        d->XMM_L(0) = F(32, d->XMM_S(0), s->XMM_S(0));                  \
+        d->XMM_L(1) = F(32, d->XMM_S(1), s->XMM_S(1));                  \
+        d->XMM_L(2) = F(32, d->XMM_S(2), s->XMM_S(2));                  \
+        d->XMM_L(3) = F(32, d->XMM_S(3), s->XMM_S(3));                  \
+    }                                                                   \
+                                                                        \
+    void helper_ ## name ## ss(CPUX86State *env, Reg *d, Reg *s)        \
+    {                                                                   \
+        d->XMM_L(0) = F(32, d->XMM_S(0), s->XMM_S(0));                  \
+    }                                                                   \
+                                                                        \
+    void helper_ ## name ## pd(CPUX86State *env, Reg *d, Reg *s)        \
+    {                                                                   \
+        d->XMM_Q(0) = F(64, d->XMM_D(0), s->XMM_D(0));                  \
+        d->XMM_Q(1) = F(64, d->XMM_D(1), s->XMM_D(1));                  \
+    }                                                                   \
+                                                                        \
+    void helper_ ## name ## sd(CPUX86State *env, Reg *d, Reg *s)        \
+    {                                                                   \
+        d->XMM_Q(0) = F(64, d->XMM_D(0), s->XMM_D(0));                  \
     }
 
 #define FPU_CMPEQ(size, a, b)                                           \
@@ -993,7 +994,7 @@ SSE_HELPER_CMP(cmpord, FPU_CMPORD)
 
 static const int comis_eflags[4] = {CC_C, CC_Z, 0, CC_Z | CC_P | CC_C};
 
-void helper_ucomiss(Reg *d, Reg *s)
+void helper_ucomiss(CPUX86State *env, Reg *d, Reg *s)
 {
     int ret;
     float32 s0, s1;
@@ -1004,7 +1005,7 @@ void helper_ucomiss(Reg *d, Reg *s)
     CC_SRC = comis_eflags[ret + 1];
 }
 
-void helper_comiss(Reg *d, Reg *s)
+void helper_comiss(CPUX86State *env, Reg *d, Reg *s)
 {
     int ret;
     float32 s0, s1;
@@ -1015,7 +1016,7 @@ void helper_comiss(Reg *d, Reg *s)
     CC_SRC = comis_eflags[ret + 1];
 }
 
-void helper_ucomisd(Reg *d, Reg *s)
+void helper_ucomisd(CPUX86State *env, Reg *d, Reg *s)
 {
     int ret;
     float64 d0, d1;
@@ -1026,7 +1027,7 @@ void helper_ucomisd(Reg *d, Reg *s)
     CC_SRC = comis_eflags[ret + 1];
 }
 
-void helper_comisd(Reg *d, Reg *s)
+void helper_comisd(CPUX86State *env, Reg *d, Reg *s)
 {
     int ret;
     float64 d0, d1;
@@ -1037,7 +1038,7 @@ void helper_comisd(Reg *d, Reg *s)
     CC_SRC = comis_eflags[ret + 1];
 }
 
-uint32_t helper_movmskps(Reg *s)
+uint32_t helper_movmskps(CPUX86State *env, Reg *s)
 {
     int b0, b1, b2, b3;
 
@@ -1048,7 +1049,7 @@ uint32_t helper_movmskps(Reg *s)
     return b0 | (b1 << 1) | (b2 << 2) | (b3 << 3);
 }
 
-uint32_t helper_movmskpd(Reg *s)
+uint32_t helper_movmskpd(CPUX86State *env, Reg *s)
 {
     int b0, b1;
 
@@ -1059,7 +1060,7 @@ uint32_t helper_movmskpd(Reg *s)
 
 #endif
 
-uint32_t glue(helper_pmovmskb, SUFFIX)(Reg *s)
+uint32_t glue(helper_pmovmskb, SUFFIX)(CPUX86State *env, Reg *s)
 {
     uint32_t val;
 
@@ -1085,7 +1086,7 @@ uint32_t glue(helper_pmovmskb, SUFFIX)(Reg *s)
     return val;
 }
 
-void glue(helper_packsswb, SUFFIX)(Reg *d, Reg *s)
+void glue(helper_packsswb, SUFFIX)(CPUX86State *env, Reg *d, Reg *s)
 {
     Reg r;
 
@@ -1112,7 +1113,7 @@ void glue(helper_packsswb, SUFFIX)(Reg *d, Reg *s)
     *d = r;
 }
 
-void glue(helper_packuswb, SUFFIX)(Reg *d, Reg *s)
+void glue(helper_packuswb, SUFFIX)(CPUX86State *env, Reg *d, Reg *s)
 {
     Reg r;
 
@@ -1139,7 +1140,7 @@ void glue(helper_packuswb, SUFFIX)(Reg *d, Reg *s)
     *d = r;
 }
 
-void glue(helper_packssdw, SUFFIX)(Reg *d, Reg *s)
+void glue(helper_packssdw, SUFFIX)(CPUX86State *env, Reg *d, Reg *s)
 {
     Reg r;
 
@@ -1160,7 +1161,8 @@ void glue(helper_packssdw, SUFFIX)(Reg *d, Reg *s)
 
 #define UNPCK_OP(base_name, base)                                       \
                                                                         \
-    void glue(helper_punpck ## base_name ## bw, SUFFIX)(Reg *d, Reg *s) \
+    void glue(helper_punpck ## base_name ## bw, SUFFIX)(CPUX86State *env,\
+                                                        Reg *d, Reg *s) \
     {                                                                   \
         Reg r;                                                          \
                                                                         \
@@ -1181,11 +1183,12 @@ void glue(helper_packssdw, SUFFIX)(Reg *d, Reg *s)
                  r.B(13) = s->B((base << (SHIFT + 2)) + 6);             \
                  r.B(14) = d->B((base << (SHIFT + 2)) + 7);             \
                  r.B(15) = s->B((base << (SHIFT + 2)) + 7);             \
-                                                                        ) \
+                                                                      ) \
             *d = r;                                                     \
     }                                                                   \
                                                                         \
-    void glue(helper_punpck ## base_name ## wd, SUFFIX)(Reg *d, Reg *s) \
+    void glue(helper_punpck ## base_name ## wd, SUFFIX)(CPUX86State *env,\
+                                                        Reg *d, Reg *s) \
     {                                                                   \
         Reg r;                                                          \
                                                                         \
@@ -1198,11 +1201,12 @@ void glue(helper_packssdw, SUFFIX)(Reg *d, Reg *s)
                  r.W(5) = s->W((base << (SHIFT + 1)) + 2);              \
                  r.W(6) = d->W((base << (SHIFT + 1)) + 3);              \
                  r.W(7) = s->W((base << (SHIFT + 1)) + 3);              \
-                                                                        ) \
+                                                                      ) \
             *d = r;                                                     \
     }                                                                   \
                                                                         \
-    void glue(helper_punpck ## base_name ## dq, SUFFIX)(Reg *d, Reg *s) \
+    void glue(helper_punpck ## base_name ## dq, SUFFIX)(CPUX86State *env,\
+                                                        Reg *d, Reg *s) \
     {                                                                   \
         Reg r;                                                          \
                                                                         \
@@ -1211,12 +1215,14 @@ void glue(helper_packssdw, SUFFIX)(Reg *d, Reg *s)
         XMM_ONLY(                                                       \
                  r.L(2) = d->L((base << SHIFT) + 1);                    \
                  r.L(3) = s->L((base << SHIFT) + 1);                    \
-                                                                        ) \
+                                                                      ) \
             *d = r;                                                     \
     }                                                                   \
                                                                         \
     XMM_ONLY(                                                           \
-             void glue(helper_punpck ## base_name ## qdq, SUFFIX)(Reg *d, \
+             void glue(helper_punpck ## base_name ## qdq, SUFFIX)(CPUX86State \
+                                                                  *env, \
+                                                                  Reg *d, \
                                                                   Reg *s) \
              {                                                          \
                  Reg r;                                                 \
@@ -1232,25 +1238,25 @@ UNPCK_OP(h, 1)
 
 /* 3DNow! float ops */
 #if SHIFT == 0
-void helper_pi2fd(MMXReg *d, MMXReg *s)
+void helper_pi2fd(CPUX86State *env, MMXReg *d, MMXReg *s)
 {
     d->MMX_S(0) = int32_to_float32(s->MMX_L(0), &env->mmx_status);
     d->MMX_S(1) = int32_to_float32(s->MMX_L(1), &env->mmx_status);
 }
 
-void helper_pi2fw(MMXReg *d, MMXReg *s)
+void helper_pi2fw(CPUX86State *env, MMXReg *d, MMXReg *s)
 {
     d->MMX_S(0) = int32_to_float32((int16_t)s->MMX_W(0), &env->mmx_status);
     d->MMX_S(1) = int32_to_float32((int16_t)s->MMX_W(2), &env->mmx_status);
 }
 
-void helper_pf2id(MMXReg *d, MMXReg *s)
+void helper_pf2id(CPUX86State *env, MMXReg *d, MMXReg *s)
 {
     d->MMX_L(0) = float32_to_int32_round_to_zero(s->MMX_S(0), &env->mmx_status);
     d->MMX_L(1) = float32_to_int32_round_to_zero(s->MMX_S(1), &env->mmx_status);
 }
 
-void helper_pf2iw(MMXReg *d, MMXReg *s)
+void helper_pf2iw(CPUX86State *env, MMXReg *d, MMXReg *s)
 {
     d->MMX_L(0) = satsw(float32_to_int32_round_to_zero(s->MMX_S(0),
                                                        &env->mmx_status));
@@ -1258,7 +1264,7 @@ void helper_pf2iw(MMXReg *d, MMXReg *s)
                                                        &env->mmx_status));
 }
 
-void helper_pfacc(MMXReg *d, MMXReg *s)
+void helper_pfacc(CPUX86State *env, MMXReg *d, MMXReg *s)
 {
     MMXReg r;
 
@@ -1267,13 +1273,13 @@ void helper_pfacc(MMXReg *d, MMXReg *s)
     *d = r;
 }
 
-void helper_pfadd(MMXReg *d, MMXReg *s)
+void helper_pfadd(CPUX86State *env, MMXReg *d, MMXReg *s)
 {
     d->MMX_S(0) = float32_add(d->MMX_S(0), s->MMX_S(0), &env->mmx_status);
     d->MMX_S(1) = float32_add(d->MMX_S(1), s->MMX_S(1), &env->mmx_status);
 }
 
-void helper_pfcmpeq(MMXReg *d, MMXReg *s)
+void helper_pfcmpeq(CPUX86State *env, MMXReg *d, MMXReg *s)
 {
     d->MMX_L(0) = float32_eq_quiet(d->MMX_S(0), s->MMX_S(0),
                                    &env->mmx_status) ? -1 : 0;
@@ -1281,7 +1287,7 @@ void helper_pfcmpeq(MMXReg *d, MMXReg *s)
                                    &env->mmx_status) ? -1 : 0;
 }
 
-void helper_pfcmpge(MMXReg *d, MMXReg *s)
+void helper_pfcmpge(CPUX86State *env, MMXReg *d, MMXReg *s)
 {
     d->MMX_L(0) = float32_le(s->MMX_S(0), d->MMX_S(0),
                              &env->mmx_status) ? -1 : 0;
@@ -1289,7 +1295,7 @@ void helper_pfcmpge(MMXReg *d, MMXReg *s)
                              &env->mmx_status) ? -1 : 0;
 }
 
-void helper_pfcmpgt(MMXReg *d, MMXReg *s)
+void helper_pfcmpgt(CPUX86State *env, MMXReg *d, MMXReg *s)
 {
     d->MMX_L(0) = float32_lt(s->MMX_S(0), d->MMX_S(0),
                              &env->mmx_status) ? -1 : 0;
@@ -1297,7 +1303,7 @@ void helper_pfcmpgt(MMXReg *d, MMXReg *s)
                              &env->mmx_status) ? -1 : 0;
 }
 
-void helper_pfmax(MMXReg *d, MMXReg *s)
+void helper_pfmax(CPUX86State *env, MMXReg *d, MMXReg *s)
 {
     if (float32_lt(d->MMX_S(0), s->MMX_S(0), &env->mmx_status)) {
         d->MMX_S(0) = s->MMX_S(0);
@@ -1307,7 +1313,7 @@ void helper_pfmax(MMXReg *d, MMXReg *s)
     }
 }
 
-void helper_pfmin(MMXReg *d, MMXReg *s)
+void helper_pfmin(CPUX86State *env, MMXReg *d, MMXReg *s)
 {
     if (float32_lt(s->MMX_S(0), d->MMX_S(0), &env->mmx_status)) {
         d->MMX_S(0) = s->MMX_S(0);
@@ -1317,13 +1323,13 @@ void helper_pfmin(MMXReg *d, MMXReg *s)
     }
 }
 
-void helper_pfmul(MMXReg *d, MMXReg *s)
+void helper_pfmul(CPUX86State *env, MMXReg *d, MMXReg *s)
 {
     d->MMX_S(0) = float32_mul(d->MMX_S(0), s->MMX_S(0), &env->mmx_status);
     d->MMX_S(1) = float32_mul(d->MMX_S(1), s->MMX_S(1), &env->mmx_status);
 }
 
-void helper_pfnacc(MMXReg *d, MMXReg *s)
+void helper_pfnacc(CPUX86State *env, MMXReg *d, MMXReg *s)
 {
     MMXReg r;
 
@@ -1332,7 +1338,7 @@ void helper_pfnacc(MMXReg *d, MMXReg *s)
     *d = r;
 }
 
-void helper_pfpnacc(MMXReg *d, MMXReg *s)
+void helper_pfpnacc(CPUX86State *env, MMXReg *d, MMXReg *s)
 {
     MMXReg r;
 
@@ -1341,13 +1347,13 @@ void helper_pfpnacc(MMXReg *d, MMXReg *s)
     *d = r;
 }
 
-void helper_pfrcp(MMXReg *d, MMXReg *s)
+void helper_pfrcp(CPUX86State *env, MMXReg *d, MMXReg *s)
 {
     d->MMX_S(0) = float32_div(float32_one, s->MMX_S(0), &env->mmx_status);
     d->MMX_S(1) = d->MMX_S(0);
 }
 
-void helper_pfrsqrt(MMXReg *d, MMXReg *s)
+void helper_pfrsqrt(CPUX86State *env, MMXReg *d, MMXReg *s)
 {
     d->MMX_L(1) = s->MMX_L(0) & 0x7fffffff;
     d->MMX_S(1) = float32_div(float32_one,
@@ -1357,19 +1363,19 @@ void helper_pfrsqrt(MMXReg *d, MMXReg *s)
     d->MMX_L(0) = d->MMX_L(1);
 }
 
-void helper_pfsub(MMXReg *d, MMXReg *s)
+void helper_pfsub(CPUX86State *env, MMXReg *d, MMXReg *s)
 {
     d->MMX_S(0) = float32_sub(d->MMX_S(0), s->MMX_S(0), &env->mmx_status);
     d->MMX_S(1) = float32_sub(d->MMX_S(1), s->MMX_S(1), &env->mmx_status);
 }
 
-void helper_pfsubr(MMXReg *d, MMXReg *s)
+void helper_pfsubr(CPUX86State *env, MMXReg *d, MMXReg *s)
 {
     d->MMX_S(0) = float32_sub(s->MMX_S(0), d->MMX_S(0), &env->mmx_status);
     d->MMX_S(1) = float32_sub(s->MMX_S(1), d->MMX_S(1), &env->mmx_status);
 }
 
-void helper_pswapd(MMXReg *d, MMXReg *s)
+void helper_pswapd(CPUX86State *env, MMXReg *d, MMXReg *s)
 {
     MMXReg r;
 
@@ -1380,7 +1386,7 @@ void helper_pswapd(MMXReg *d, MMXReg *s)
 #endif
 
 /* SSSE3 op helpers */
-void glue(helper_pshufb, SUFFIX)(Reg *d, Reg *s)
+void glue(helper_pshufb, SUFFIX)(CPUX86State *env, Reg *d, Reg *s)
 {
     int i;
     Reg r;
@@ -1392,7 +1398,7 @@ void glue(helper_pshufb, SUFFIX)(Reg *d, Reg *s)
     *d = r;
 }
 
-void glue(helper_phaddw, SUFFIX)(Reg *d, Reg *s)
+void glue(helper_phaddw, SUFFIX)(CPUX86State *env, Reg *d, Reg *s)
 {
     d->W(0) = (int16_t)d->W(0) + (int16_t)d->W(1);
     d->W(1) = (int16_t)d->W(2) + (int16_t)d->W(3);
@@ -1404,7 +1410,7 @@ void glue(helper_phaddw, SUFFIX)(Reg *d, Reg *s)
     XMM_ONLY(d->W(7) = (int16_t)s->W(6) + (int16_t)s->W(7));
 }
 
-void glue(helper_phaddd, SUFFIX)(Reg *d, Reg *s)
+void glue(helper_phaddd, SUFFIX)(CPUX86State *env, Reg *d, Reg *s)
 {
     d->L(0) = (int32_t)d->L(0) + (int32_t)d->L(1);
     XMM_ONLY(d->L(1) = (int32_t)d->L(2) + (int32_t)d->L(3));
@@ -1412,7 +1418,7 @@ void glue(helper_phaddd, SUFFIX)(Reg *d, Reg *s)
     XMM_ONLY(d->L(3) = (int32_t)s->L(2) + (int32_t)s->L(3));
 }
 
-void glue(helper_phaddsw, SUFFIX)(Reg *d, Reg *s)
+void glue(helper_phaddsw, SUFFIX)(CPUX86State *env, Reg *d, Reg *s)
 {
     d->W(0) = satsw((int16_t)d->W(0) + (int16_t)d->W(1));
     d->W(1) = satsw((int16_t)d->W(2) + (int16_t)d->W(3));
@@ -1424,7 +1430,7 @@ void glue(helper_phaddsw, SUFFIX)(Reg *d, Reg *s)
     XMM_ONLY(d->W(7) = satsw((int16_t)s->W(6) + (int16_t)s->W(7)));
 }
 
-void glue(helper_pmaddubsw, SUFFIX)(Reg *d, Reg *s)
+void glue(helper_pmaddubsw, SUFFIX)(CPUX86State *env, Reg *d, Reg *s)
 {
     d->W(0) = satsw((int8_t)s->B(0) * (uint8_t)d->B(0) +
                     (int8_t)s->B(1) * (uint8_t)d->B(1));
@@ -1446,7 +1452,7 @@ void glue(helper_pmaddubsw, SUFFIX)(Reg *d, Reg *s)
 #endif
 }
 
-void glue(helper_phsubw, SUFFIX)(Reg *d, Reg *s)
+void glue(helper_phsubw, SUFFIX)(CPUX86State *env, Reg *d, Reg *s)
 {
     d->W(0) = (int16_t)d->W(0) - (int16_t)d->W(1);
     d->W(1) = (int16_t)d->W(2) - (int16_t)d->W(3);
@@ -1458,7 +1464,7 @@ void glue(helper_phsubw, SUFFIX)(Reg *d, Reg *s)
     XMM_ONLY(d->W(7) = (int16_t)s->W(6) - (int16_t)s->W(7));
 }
 
-void glue(helper_phsubd, SUFFIX)(Reg *d, Reg *s)
+void glue(helper_phsubd, SUFFIX)(CPUX86State *env, Reg *d, Reg *s)
 {
     d->L(0) = (int32_t)d->L(0) - (int32_t)d->L(1);
     XMM_ONLY(d->L(1) = (int32_t)d->L(2) - (int32_t)d->L(3));
@@ -1466,7 +1472,7 @@ void glue(helper_phsubd, SUFFIX)(Reg *d, Reg *s)
     XMM_ONLY(d->L(3) = (int32_t)s->L(2) - (int32_t)s->L(3));
 }
 
-void glue(helper_phsubsw, SUFFIX)(Reg *d, Reg *s)
+void glue(helper_phsubsw, SUFFIX)(CPUX86State *env, Reg *d, Reg *s)
 {
     d->W(0) = satsw((int16_t)d->W(0) - (int16_t)d->W(1));
     d->W(1) = satsw((int16_t)d->W(2) - (int16_t)d->W(3));
@@ -1495,7 +1501,8 @@ SSE_HELPER_B(helper_psignb, FSIGNB)
 SSE_HELPER_W(helper_psignw, FSIGNW)
 SSE_HELPER_L(helper_psignd, FSIGNL)
 
-void glue(helper_palignr, SUFFIX)(Reg *d, Reg *s, int32_t shift)
+void glue(helper_palignr, SUFFIX)(CPUX86State *env, Reg *d, Reg *s,
+                                  int32_t shift)
 {
     Reg r;
 
@@ -1529,7 +1536,7 @@ void glue(helper_palignr, SUFFIX)(Reg *d, Reg *s, int32_t shift)
 
 #if SHIFT == 1
 #define SSE_HELPER_V(name, elem, num, F)                                \
-    void glue(name, SUFFIX)(Reg *d, Reg *s)                             \
+    void glue(name, SUFFIX)(CPUX86State *env, Reg *d, Reg *s)           \
     {                                                                   \
         d->elem(0) = F(d->elem(0), s->elem(0), XMM0.elem(0));           \
         d->elem(1) = F(d->elem(1), s->elem(1), XMM0.elem(1));           \
@@ -1556,7 +1563,7 @@ void glue(helper_palignr, SUFFIX)(Reg *d, Reg *s, int32_t shift)
     }
 
 #define SSE_HELPER_I(name, elem, num, F)                                \
-    void glue(name, SUFFIX)(Reg *d, Reg *s, uint32_t imm)               \
+    void glue(name, SUFFIX)(CPUX86State *env, Reg *d, Reg *s, uint32_t imm) \
     {                                                                   \
         d->elem(0) = F(d->elem(0), s->elem(0), ((imm >> 0) & 1));       \
         d->elem(1) = F(d->elem(1), s->elem(1), ((imm >> 1) & 1));       \
@@ -1596,7 +1603,7 @@ SSE_HELPER_V(helper_pblendvb, B, 16, FBLENDVB)
 SSE_HELPER_V(helper_blendvps, L, 4, FBLENDVPS)
 SSE_HELPER_V(helper_blendvpd, Q, 2, FBLENDVPD)
 
-void glue(helper_ptest, SUFFIX)(Reg *d, Reg *s)
+void glue(helper_ptest, SUFFIX)(CPUX86State *env, Reg *d, Reg *s)
 {
     uint64_t zf = (s->Q(0) &  d->Q(0)) | (s->Q(1) &  d->Q(1));
     uint64_t cf = (s->Q(0) & ~d->Q(0)) | (s->Q(1) & ~d->Q(1));
@@ -1605,7 +1612,7 @@ void glue(helper_ptest, SUFFIX)(Reg *d, Reg *s)
 }
 
 #define SSE_HELPER_F(name, elem, num, F)        \
-    void glue(name, SUFFIX)(Reg *d, Reg *s)     \
+    void glue(name, SUFFIX)(CPUX86State *env, Reg *d, Reg *s)     \
     {                                           \
         d->elem(0) = F(0);                      \
         d->elem(1) = F(1);                      \
@@ -1634,7 +1641,7 @@ SSE_HELPER_F(helper_pmovzxwd, L, 4, s->W)
 SSE_HELPER_F(helper_pmovzxwq, Q, 2, s->W)
 SSE_HELPER_F(helper_pmovzxdq, Q, 2, s->L)
 
-void glue(helper_pmuldq, SUFFIX)(Reg *d, Reg *s)
+void glue(helper_pmuldq, SUFFIX)(CPUX86State *env, Reg *d, Reg *s)
 {
     d->Q(0) = (int64_t)(int32_t) d->L(0) * (int32_t) s->L(0);
     d->Q(1) = (int64_t)(int32_t) d->L(2) * (int32_t) s->L(2);
@@ -1643,7 +1650,7 @@ void glue(helper_pmuldq, SUFFIX)(Reg *d, Reg *s)
 #define FCMPEQQ(d, s) (d == s ? -1 : 0)
 SSE_HELPER_Q(helper_pcmpeqq, FCMPEQQ)
 
-void glue(helper_packusdw, SUFFIX)(Reg *d, Reg *s)
+void glue(helper_packusdw, SUFFIX)(CPUX86State *env, Reg *d, Reg *s)
 {
     d->W(0) = satuw((int32_t) d->L(0));
     d->W(1) = satuw((int32_t) d->L(1));
@@ -1671,7 +1678,7 @@ SSE_HELPER_L(helper_pmaxud, MAX)
 #define FMULLD(d, s) ((int32_t)d * (int32_t)s)
 SSE_HELPER_L(helper_pmulld, FMULLD)
 
-void glue(helper_phminposuw, SUFFIX)(Reg *d, Reg *s)
+void glue(helper_phminposuw, SUFFIX)(CPUX86State *env, Reg *d, Reg *s)
 {
     int idx = 0;
 
@@ -1703,7 +1710,8 @@ void glue(helper_phminposuw, SUFFIX)(Reg *d, Reg *s)
     d->W(0) = s->W(idx);
 }
 
-void glue(helper_roundps, SUFFIX)(Reg *d, Reg *s, uint32_t mode)
+void glue(helper_roundps, SUFFIX)(CPUX86State *env, Reg *d, Reg *s,
+                                  uint32_t mode)
 {
     signed char prev_rounding_mode;
 
@@ -1740,7 +1748,8 @@ void glue(helper_roundps, SUFFIX)(Reg *d, Reg *s, uint32_t mode)
     env->sse_status.float_rounding_mode = prev_rounding_mode;
 }
 
-void glue(helper_roundpd, SUFFIX)(Reg *d, Reg *s, uint32_t mode)
+void glue(helper_roundpd, SUFFIX)(CPUX86State *env, Reg *d, Reg *s,
+                                  uint32_t mode)
 {
     signed char prev_rounding_mode;
 
@@ -1775,7 +1784,8 @@ void glue(helper_roundpd, SUFFIX)(Reg *d, Reg *s, uint32_t mode)
     env->sse_status.float_rounding_mode = prev_rounding_mode;
 }
 
-void glue(helper_roundss, SUFFIX)(Reg *d, Reg *s, uint32_t mode)
+void glue(helper_roundss, SUFFIX)(CPUX86State *env, Reg *d, Reg *s,
+                                  uint32_t mode)
 {
     signed char prev_rounding_mode;
 
@@ -1809,7 +1819,8 @@ void glue(helper_roundss, SUFFIX)(Reg *d, Reg *s, uint32_t mode)
     env->sse_status.float_rounding_mode = prev_rounding_mode;
 }
 
-void glue(helper_roundsd, SUFFIX)(Reg *d, Reg *s, uint32_t mode)
+void glue(helper_roundsd, SUFFIX)(CPUX86State *env, Reg *d, Reg *s,
+                                  uint32_t mode)
 {
     signed char prev_rounding_mode;
 
@@ -1848,7 +1859,7 @@ SSE_HELPER_I(helper_blendps, L, 4, FBLENDP)
 SSE_HELPER_I(helper_blendpd, Q, 2, FBLENDP)
 SSE_HELPER_I(helper_pblendw, W, 8, FBLENDP)
 
-void glue(helper_dpps, SUFFIX)(Reg *d, Reg *s, uint32_t mask)
+void glue(helper_dpps, SUFFIX)(CPUX86State *env, Reg *d, Reg *s, uint32_t mask)
 {
     float32 iresult = float32_zero;
 
@@ -1882,7 +1893,7 @@ void glue(helper_dpps, SUFFIX)(Reg *d, Reg *s, uint32_t mask)
     d->XMM_S(3) = (mask & (1 << 3)) ? iresult : float32_zero;
 }
 
-void glue(helper_dppd, SUFFIX)(Reg *d, Reg *s, uint32_t mask)
+void glue(helper_dppd, SUFFIX)(CPUX86State *env, Reg *d, Reg *s, uint32_t mask)
 {
     float64 iresult = float64_zero;
 
@@ -1902,7 +1913,8 @@ void glue(helper_dppd, SUFFIX)(Reg *d, Reg *s, uint32_t mask)
     d->XMM_D(1) = (mask & (1 << 1)) ? iresult : float64_zero;
 }
 
-void glue(helper_mpsadbw, SUFFIX)(Reg *d, Reg *s, uint32_t offset)
+void glue(helper_mpsadbw, SUFFIX)(CPUX86State *env, Reg *d, Reg *s,
+                                  uint32_t offset)
 {
     int s0 = (offset & 3) << 2;
     int d0 = (offset & 4) << 0;
@@ -1925,7 +1937,7 @@ void glue(helper_mpsadbw, SUFFIX)(Reg *d, Reg *s, uint32_t offset)
 #define FCMPGTQ(d, s) (d > s ? -1 : 0)
 SSE_HELPER_Q(helper_pcmpgtq, FCMPGTQ)
 
-static inline int pcmp_elen(int reg, uint32_t ctrl)
+static inline int pcmp_elen(CPUX86State *env, int reg, uint32_t ctrl)
 {
     int val;
 
@@ -1980,7 +1992,7 @@ static inline int pcmp_val(Reg *r, uint8_t ctrl, int i)
     }
 }
 
-static inline unsigned pcmpxstrx(Reg *d, Reg *s,
+static inline unsigned pcmpxstrx(CPUX86State *env, Reg *d, Reg *s,
                                  int8_t ctrl, int valids, int validd)
 {
     unsigned int res = 0;
@@ -2080,11 +2092,12 @@ static inline int ffs1(unsigned int val)
     return ret;
 }
 
-void glue(helper_pcmpestri, SUFFIX)(Reg *d, Reg *s, uint32_t ctrl)
+void glue(helper_pcmpestri, SUFFIX)(CPUX86State *env, Reg *d, Reg *s,
+                                    uint32_t ctrl)
 {
-    unsigned int res = pcmpxstrx(d, s, ctrl,
-                                 pcmp_elen(R_EDX, ctrl),
-                                 pcmp_elen(R_EAX, ctrl));
+    unsigned int res = pcmpxstrx(env, d, s, ctrl,
+                                 pcmp_elen(env, R_EDX, ctrl),
+                                 pcmp_elen(env, R_EAX, ctrl));
 
     if (res) {
         env->regs[R_ECX] = ((ctrl & (1 << 6)) ? rffs1 : ffs1)(res) - 1;
@@ -2093,12 +2106,13 @@ void glue(helper_pcmpestri, SUFFIX)(Reg *d, Reg *s, uint32_t ctrl)
     }
 }
 
-void glue(helper_pcmpestrm, SUFFIX)(Reg *d, Reg *s, uint32_t ctrl)
+void glue(helper_pcmpestrm, SUFFIX)(CPUX86State *env, Reg *d, Reg *s,
+                                    uint32_t ctrl)
 {
     int i;
-    unsigned int res = pcmpxstrx(d, s, ctrl,
-                                 pcmp_elen(R_EDX, ctrl),
-                                 pcmp_elen(R_EAX, ctrl));
+    unsigned int res = pcmpxstrx(env, d, s, ctrl,
+                                 pcmp_elen(env, R_EDX, ctrl),
+                                 pcmp_elen(env, R_EAX, ctrl));
 
     if ((ctrl >> 6) & 1) {
         if (ctrl & 1) {
@@ -2116,9 +2130,10 @@ void glue(helper_pcmpestrm, SUFFIX)(Reg *d, Reg *s, uint32_t ctrl)
     }
 }
 
-void glue(helper_pcmpistri, SUFFIX)(Reg *d, Reg *s, uint32_t ctrl)
+void glue(helper_pcmpistri, SUFFIX)(CPUX86State *env, Reg *d, Reg *s,
+                                    uint32_t ctrl)
 {
-    unsigned int res = pcmpxstrx(d, s, ctrl,
+    unsigned int res = pcmpxstrx(env, d, s, ctrl,
                                  pcmp_ilen(s, ctrl),
                                  pcmp_ilen(d, ctrl));
 
@@ -2129,10 +2144,11 @@ void glue(helper_pcmpistri, SUFFIX)(Reg *d, Reg *s, uint32_t ctrl)
     }
 }
 
-void glue(helper_pcmpistrm, SUFFIX)(Reg *d, Reg *s, uint32_t ctrl)
+void glue(helper_pcmpistrm, SUFFIX)(CPUX86State *env, Reg *d, Reg *s,
+                                    uint32_t ctrl)
 {
     int i;
-    unsigned int res = pcmpxstrx(d, s, ctrl,
+    unsigned int res = pcmpxstrx(env, d, s, ctrl,
                                  pcmp_ilen(s, ctrl),
                                  pcmp_ilen(d, ctrl));
 
@@ -2168,7 +2184,7 @@ target_ulong helper_crc32(uint32_t crc1, target_ulong msg, uint32_t len)
 
 #define POPMASK(i)     ((target_ulong) -1 / ((1LL << (1 << i)) + 1))
 #define POPCOUNT(n, i) ((n & POPMASK(i)) + ((n >> (1 << i)) & POPMASK(i)))
-target_ulong helper_popcnt(target_ulong n, uint32_t type)
+target_ulong helper_popcnt(CPUX86State *env, target_ulong n, uint32_t type)
 {
     CC_SRC = n ? 0 : CC_Z;
 
diff --git a/target-i386/ops_sse_header.h b/target-i386/ops_sse_header.h
index 8d4b2b7..401eac6 100644
--- a/target-i386/ops_sse_header.h
+++ b/target-i386/ops_sse_header.h
@@ -34,31 +34,31 @@
 #define dh_is_signed_XMMReg dh_is_signed_ptr
 #define dh_is_signed_MMXReg dh_is_signed_ptr
 
-DEF_HELPER_2(glue(psrlw, SUFFIX), void, Reg, Reg)
-DEF_HELPER_2(glue(psraw, SUFFIX), void, Reg, Reg)
-DEF_HELPER_2(glue(psllw, SUFFIX), void, Reg, Reg)
-DEF_HELPER_2(glue(psrld, SUFFIX), void, Reg, Reg)
-DEF_HELPER_2(glue(psrad, SUFFIX), void, Reg, Reg)
-DEF_HELPER_2(glue(pslld, SUFFIX), void, Reg, Reg)
-DEF_HELPER_2(glue(psrlq, SUFFIX), void, Reg, Reg)
-DEF_HELPER_2(glue(psllq, SUFFIX), void, Reg, Reg)
+DEF_HELPER_3(glue(psrlw, SUFFIX), void, env, Reg, Reg)
+DEF_HELPER_3(glue(psraw, SUFFIX), void, env, Reg, Reg)
+DEF_HELPER_3(glue(psllw, SUFFIX), void, env, Reg, Reg)
+DEF_HELPER_3(glue(psrld, SUFFIX), void, env, Reg, Reg)
+DEF_HELPER_3(glue(psrad, SUFFIX), void, env, Reg, Reg)
+DEF_HELPER_3(glue(pslld, SUFFIX), void, env, Reg, Reg)
+DEF_HELPER_3(glue(psrlq, SUFFIX), void, env, Reg, Reg)
+DEF_HELPER_3(glue(psllq, SUFFIX), void, env, Reg, Reg)
 
 #if SHIFT == 1
-DEF_HELPER_2(glue(psrldq, SUFFIX), void, Reg, Reg)
-DEF_HELPER_2(glue(pslldq, SUFFIX), void, Reg, Reg)
+DEF_HELPER_3(glue(psrldq, SUFFIX), void, env, Reg, Reg)
+DEF_HELPER_3(glue(pslldq, SUFFIX), void, env, Reg, Reg)
 #endif
 
 #define SSE_HELPER_B(name, F)\
-    DEF_HELPER_2(glue(name, SUFFIX), void, Reg, Reg)
+    DEF_HELPER_3(glue(name, SUFFIX), void, env, Reg, Reg)
 
 #define SSE_HELPER_W(name, F)\
-    DEF_HELPER_2(glue(name, SUFFIX), void, Reg, Reg)
+    DEF_HELPER_3(glue(name, SUFFIX), void, env, Reg, Reg)
 
 #define SSE_HELPER_L(name, F)\
-    DEF_HELPER_2(glue(name, SUFFIX), void, Reg, Reg)
+    DEF_HELPER_3(glue(name, SUFFIX), void, env, Reg, Reg)
 
 #define SSE_HELPER_Q(name, F)\
-    DEF_HELPER_2(glue(name, SUFFIX), void, Reg, Reg)
+    DEF_HELPER_3(glue(name, SUFFIX), void, env, Reg, Reg)
 
 SSE_HELPER_B(paddb, FADD)
 SSE_HELPER_W(paddw, FADD)
@@ -109,11 +109,11 @@ SSE_HELPER_W(pmulhw, FMULHW)
 SSE_HELPER_B(pavgb, FAVG)
 SSE_HELPER_W(pavgw, FAVG)
 
-DEF_HELPER_2(glue(pmuludq, SUFFIX), void, Reg, Reg)
-DEF_HELPER_2(glue(pmaddwd, SUFFIX), void, Reg, Reg)
+DEF_HELPER_3(glue(pmuludq, SUFFIX), void, env, Reg, Reg)
+DEF_HELPER_3(glue(pmaddwd, SUFFIX), void, env, Reg, Reg)
 
-DEF_HELPER_2(glue(psadbw, SUFFIX), void, Reg, Reg)
-DEF_HELPER_3(glue(maskmov, SUFFIX), void, Reg, Reg, tl)
+DEF_HELPER_3(glue(psadbw, SUFFIX), void, env, Reg, Reg)
+DEF_HELPER_4(glue(maskmov, SUFFIX), void, env, Reg, Reg, tl)
 DEF_HELPER_2(glue(movl_mm_T0, SUFFIX), void, Reg, i32)
 #ifdef TARGET_X86_64
 DEF_HELPER_2(glue(movq_mm_T0, SUFFIX), void, Reg, i64)
@@ -133,11 +133,11 @@ DEF_HELPER_3(glue(pshufhw, SUFFIX), void, Reg, Reg, int)
 /* FPU ops */
 /* XXX: not accurate */
 
-#define SSE_HELPER_S(name, F)\
-    DEF_HELPER_2(name ## ps , void, Reg, Reg)        \
-    DEF_HELPER_2(name ## ss , void, Reg, Reg)        \
-    DEF_HELPER_2(name ## pd , void, Reg, Reg)        \
-    DEF_HELPER_2(name ## sd , void, Reg, Reg)
+#define SSE_HELPER_S(name, F)                            \
+    DEF_HELPER_3(name ## ps, void, env, Reg, Reg)        \
+    DEF_HELPER_3(name ## ss, void, env, Reg, Reg)        \
+    DEF_HELPER_3(name ## pd, void, env, Reg, Reg)        \
+    DEF_HELPER_3(name ## sd, void, env, Reg, Reg)
 
 SSE_HELPER_S(add, FPU_ADD)
 SSE_HELPER_S(sub, FPU_SUB)
@@ -148,64 +148,64 @@ SSE_HELPER_S(max, FPU_MAX)
 SSE_HELPER_S(sqrt, FPU_SQRT)
 
 
-DEF_HELPER_2(cvtps2pd, void, Reg, Reg)
-DEF_HELPER_2(cvtpd2ps, void, Reg, Reg)
-DEF_HELPER_2(cvtss2sd, void, Reg, Reg)
-DEF_HELPER_2(cvtsd2ss, void, Reg, Reg)
-DEF_HELPER_2(cvtdq2ps, void, Reg, Reg)
-DEF_HELPER_2(cvtdq2pd, void, Reg, Reg)
-DEF_HELPER_2(cvtpi2ps, void, XMMReg, MMXReg)
-DEF_HELPER_2(cvtpi2pd, void, XMMReg, MMXReg)
-DEF_HELPER_2(cvtsi2ss, void, XMMReg, i32)
-DEF_HELPER_2(cvtsi2sd, void, XMMReg, i32)
+DEF_HELPER_3(cvtps2pd, void, env, Reg, Reg)
+DEF_HELPER_3(cvtpd2ps, void, env, Reg, Reg)
+DEF_HELPER_3(cvtss2sd, void, env, Reg, Reg)
+DEF_HELPER_3(cvtsd2ss, void, env, Reg, Reg)
+DEF_HELPER_3(cvtdq2ps, void, env, Reg, Reg)
+DEF_HELPER_3(cvtdq2pd, void, env, Reg, Reg)
+DEF_HELPER_3(cvtpi2ps, void, env, XMMReg, MMXReg)
+DEF_HELPER_3(cvtpi2pd, void, env, XMMReg, MMXReg)
+DEF_HELPER_3(cvtsi2ss, void, env, XMMReg, i32)
+DEF_HELPER_3(cvtsi2sd, void, env, XMMReg, i32)
 
 #ifdef TARGET_X86_64
-DEF_HELPER_2(cvtsq2ss, void, XMMReg, i64)
-DEF_HELPER_2(cvtsq2sd, void, XMMReg, i64)
+DEF_HELPER_3(cvtsq2ss, void, env, XMMReg, i64)
+DEF_HELPER_3(cvtsq2sd, void, env, XMMReg, i64)
 #endif
 
-DEF_HELPER_2(cvtps2dq, void, XMMReg, XMMReg)
-DEF_HELPER_2(cvtpd2dq, void, XMMReg, XMMReg)
-DEF_HELPER_2(cvtps2pi, void, MMXReg, XMMReg)
-DEF_HELPER_2(cvtpd2pi, void, MMXReg, XMMReg)
-DEF_HELPER_1(cvtss2si, s32, XMMReg)
-DEF_HELPER_1(cvtsd2si, s32, XMMReg)
+DEF_HELPER_3(cvtps2dq, void, env, XMMReg, XMMReg)
+DEF_HELPER_3(cvtpd2dq, void, env, XMMReg, XMMReg)
+DEF_HELPER_3(cvtps2pi, void, env, MMXReg, XMMReg)
+DEF_HELPER_3(cvtpd2pi, void, env, MMXReg, XMMReg)
+DEF_HELPER_2(cvtss2si, s32, env, XMMReg)
+DEF_HELPER_2(cvtsd2si, s32, env, XMMReg)
 #ifdef TARGET_X86_64
-DEF_HELPER_1(cvtss2sq, s64, XMMReg)
-DEF_HELPER_1(cvtsd2sq, s64, XMMReg)
+DEF_HELPER_2(cvtss2sq, s64, env, XMMReg)
+DEF_HELPER_2(cvtsd2sq, s64, env, XMMReg)
 #endif
 
-DEF_HELPER_2(cvttps2dq, void, XMMReg, XMMReg)
-DEF_HELPER_2(cvttpd2dq, void, XMMReg, XMMReg)
-DEF_HELPER_2(cvttps2pi, void, MMXReg, XMMReg)
-DEF_HELPER_2(cvttpd2pi, void, MMXReg, XMMReg)
-DEF_HELPER_1(cvttss2si, s32, XMMReg)
-DEF_HELPER_1(cvttsd2si, s32, XMMReg)
+DEF_HELPER_3(cvttps2dq, void, env, XMMReg, XMMReg)
+DEF_HELPER_3(cvttpd2dq, void, env, XMMReg, XMMReg)
+DEF_HELPER_3(cvttps2pi, void, env, MMXReg, XMMReg)
+DEF_HELPER_3(cvttpd2pi, void, env, MMXReg, XMMReg)
+DEF_HELPER_2(cvttss2si, s32, env, XMMReg)
+DEF_HELPER_2(cvttsd2si, s32, env, XMMReg)
 #ifdef TARGET_X86_64
-DEF_HELPER_1(cvttss2sq, s64, XMMReg)
-DEF_HELPER_1(cvttsd2sq, s64, XMMReg)
+DEF_HELPER_2(cvttss2sq, s64, env, XMMReg)
+DEF_HELPER_2(cvttsd2sq, s64, env, XMMReg)
 #endif
 
-DEF_HELPER_2(rsqrtps, void, XMMReg, XMMReg)
-DEF_HELPER_2(rsqrtss, void, XMMReg, XMMReg)
-DEF_HELPER_2(rcpps, void, XMMReg, XMMReg)
-DEF_HELPER_2(rcpss, void, XMMReg, XMMReg)
-DEF_HELPER_2(extrq_r, void, XMMReg, XMMReg)
-DEF_HELPER_3(extrq_i, void, XMMReg, int, int)
-DEF_HELPER_2(insertq_r, void, XMMReg, XMMReg)
-DEF_HELPER_3(insertq_i, void, XMMReg, int, int)
-DEF_HELPER_2(haddps, void, XMMReg, XMMReg)
-DEF_HELPER_2(haddpd, void, XMMReg, XMMReg)
-DEF_HELPER_2(hsubps, void, XMMReg, XMMReg)
-DEF_HELPER_2(hsubpd, void, XMMReg, XMMReg)
-DEF_HELPER_2(addsubps, void, XMMReg, XMMReg)
-DEF_HELPER_2(addsubpd, void, XMMReg, XMMReg)
-
-#define SSE_HELPER_CMP(name, F)\
-    DEF_HELPER_2( name ## ps , void, Reg, Reg)        \
-    DEF_HELPER_2( name ## ss , void, Reg, Reg)        \
-    DEF_HELPER_2( name ## pd , void, Reg, Reg)        \
-    DEF_HELPER_2( name ## sd , void, Reg, Reg)
+DEF_HELPER_3(rsqrtps, void, env, XMMReg, XMMReg)
+DEF_HELPER_3(rsqrtss, void, env, XMMReg, XMMReg)
+DEF_HELPER_3(rcpps, void, env, XMMReg, XMMReg)
+DEF_HELPER_3(rcpss, void, env, XMMReg, XMMReg)
+DEF_HELPER_3(extrq_r, void, env, XMMReg, XMMReg)
+DEF_HELPER_4(extrq_i, void, env, XMMReg, int, int)
+DEF_HELPER_3(insertq_r, void, env, XMMReg, XMMReg)
+DEF_HELPER_4(insertq_i, void, env, XMMReg, int, int)
+DEF_HELPER_3(haddps, void, env, XMMReg, XMMReg)
+DEF_HELPER_3(haddpd, void, env, XMMReg, XMMReg)
+DEF_HELPER_3(hsubps, void, env, XMMReg, XMMReg)
+DEF_HELPER_3(hsubpd, void, env, XMMReg, XMMReg)
+DEF_HELPER_3(addsubps, void, env, XMMReg, XMMReg)
+DEF_HELPER_3(addsubpd, void, env, XMMReg, XMMReg)
+
+#define SSE_HELPER_CMP(name, F)                           \
+    DEF_HELPER_3(name ## ps, void, env, Reg, Reg)         \
+    DEF_HELPER_3(name ## ss, void, env, Reg, Reg)         \
+    DEF_HELPER_3(name ## pd, void, env, Reg, Reg)         \
+    DEF_HELPER_3(name ## sd, void, env, Reg, Reg)
 
 SSE_HELPER_CMP(cmpeq, FPU_CMPEQ)
 SSE_HELPER_CMP(cmplt, FPU_CMPLT)
@@ -216,124 +216,124 @@ SSE_HELPER_CMP(cmpnlt, FPU_CMPNLT)
 SSE_HELPER_CMP(cmpnle, FPU_CMPNLE)
 SSE_HELPER_CMP(cmpord, FPU_CMPORD)
 
-DEF_HELPER_2(ucomiss, void, Reg, Reg)
-DEF_HELPER_2(comiss, void, Reg, Reg)
-DEF_HELPER_2(ucomisd, void, Reg, Reg)
-DEF_HELPER_2(comisd, void, Reg, Reg)
-DEF_HELPER_1(movmskps, i32, Reg)
-DEF_HELPER_1(movmskpd, i32, Reg)
+DEF_HELPER_3(ucomiss, void, env, Reg, Reg)
+DEF_HELPER_3(comiss, void, env, Reg, Reg)
+DEF_HELPER_3(ucomisd, void, env, Reg, Reg)
+DEF_HELPER_3(comisd, void, env, Reg, Reg)
+DEF_HELPER_2(movmskps, i32, env, Reg)
+DEF_HELPER_2(movmskpd, i32, env, Reg)
 #endif
 
-DEF_HELPER_1(glue(pmovmskb, SUFFIX), i32, Reg)
-DEF_HELPER_2(glue(packsswb, SUFFIX), void, Reg, Reg)
-DEF_HELPER_2(glue(packuswb, SUFFIX), void, Reg, Reg)
-DEF_HELPER_2(glue(packssdw, SUFFIX), void, Reg, Reg)
-#define UNPCK_OP(base_name, base)                               \
-    DEF_HELPER_2(glue(punpck ## base_name ## bw, SUFFIX) , void, Reg, Reg) \
-    DEF_HELPER_2(glue(punpck ## base_name ## wd, SUFFIX) , void, Reg, Reg) \
-    DEF_HELPER_2(glue(punpck ## base_name ## dq, SUFFIX) , void, Reg, Reg)
+DEF_HELPER_2(glue(pmovmskb, SUFFIX), i32, env, Reg)
+DEF_HELPER_3(glue(packsswb, SUFFIX), void, env, Reg, Reg)
+DEF_HELPER_3(glue(packuswb, SUFFIX), void, env, Reg, Reg)
+DEF_HELPER_3(glue(packssdw, SUFFIX), void, env, Reg, Reg)
+#define UNPCK_OP(base_name, base)                                       \
+    DEF_HELPER_3(glue(punpck ## base_name ## bw, SUFFIX), void, env, Reg, Reg) \
+    DEF_HELPER_3(glue(punpck ## base_name ## wd, SUFFIX), void, env, Reg, Reg) \
+    DEF_HELPER_3(glue(punpck ## base_name ## dq, SUFFIX), void, env, Reg, Reg)
 
 UNPCK_OP(l, 0)
 UNPCK_OP(h, 1)
 
 #if SHIFT == 1
-DEF_HELPER_2(glue(punpcklqdq, SUFFIX), void, Reg, Reg)
-DEF_HELPER_2(glue(punpckhqdq, SUFFIX), void, Reg, Reg)
+DEF_HELPER_3(glue(punpcklqdq, SUFFIX), void, env, Reg, Reg)
+DEF_HELPER_3(glue(punpckhqdq, SUFFIX), void, env, Reg, Reg)
 #endif
 
 /* 3DNow! float ops */
 #if SHIFT == 0
-DEF_HELPER_2(pi2fd, void, MMXReg, MMXReg)
-DEF_HELPER_2(pi2fw, void, MMXReg, MMXReg)
-DEF_HELPER_2(pf2id, void, MMXReg, MMXReg)
-DEF_HELPER_2(pf2iw, void, MMXReg, MMXReg)
-DEF_HELPER_2(pfacc, void, MMXReg, MMXReg)
-DEF_HELPER_2(pfadd, void, MMXReg, MMXReg)
-DEF_HELPER_2(pfcmpeq, void, MMXReg, MMXReg)
-DEF_HELPER_2(pfcmpge, void, MMXReg, MMXReg)
-DEF_HELPER_2(pfcmpgt, void, MMXReg, MMXReg)
-DEF_HELPER_2(pfmax, void, MMXReg, MMXReg)
-DEF_HELPER_2(pfmin, void, MMXReg, MMXReg)
-DEF_HELPER_2(pfmul, void, MMXReg, MMXReg)
-DEF_HELPER_2(pfnacc, void, MMXReg, MMXReg)
-DEF_HELPER_2(pfpnacc, void, MMXReg, MMXReg)
-DEF_HELPER_2(pfrcp, void, MMXReg, MMXReg)
-DEF_HELPER_2(pfrsqrt, void, MMXReg, MMXReg)
-DEF_HELPER_2(pfsub, void, MMXReg, MMXReg)
-DEF_HELPER_2(pfsubr, void, MMXReg, MMXReg)
-DEF_HELPER_2(pswapd, void, MMXReg, MMXReg)
+DEF_HELPER_3(pi2fd, void, env, MMXReg, MMXReg)
+DEF_HELPER_3(pi2fw, void, env, MMXReg, MMXReg)
+DEF_HELPER_3(pf2id, void, env, MMXReg, MMXReg)
+DEF_HELPER_3(pf2iw, void, env, MMXReg, MMXReg)
+DEF_HELPER_3(pfacc, void, env, MMXReg, MMXReg)
+DEF_HELPER_3(pfadd, void, env, MMXReg, MMXReg)
+DEF_HELPER_3(pfcmpeq, void, env, MMXReg, MMXReg)
+DEF_HELPER_3(pfcmpge, void, env, MMXReg, MMXReg)
+DEF_HELPER_3(pfcmpgt, void, env, MMXReg, MMXReg)
+DEF_HELPER_3(pfmax, void, env, MMXReg, MMXReg)
+DEF_HELPER_3(pfmin, void, env, MMXReg, MMXReg)
+DEF_HELPER_3(pfmul, void, env, MMXReg, MMXReg)
+DEF_HELPER_3(pfnacc, void, env, MMXReg, MMXReg)
+DEF_HELPER_3(pfpnacc, void, env, MMXReg, MMXReg)
+DEF_HELPER_3(pfrcp, void, env, MMXReg, MMXReg)
+DEF_HELPER_3(pfrsqrt, void, env, MMXReg, MMXReg)
+DEF_HELPER_3(pfsub, void, env, MMXReg, MMXReg)
+DEF_HELPER_3(pfsubr, void, env, MMXReg, MMXReg)
+DEF_HELPER_3(pswapd, void, env, MMXReg, MMXReg)
 #endif
 
 /* SSSE3 op helpers */
-DEF_HELPER_2(glue(phaddw, SUFFIX), void, Reg, Reg)
-DEF_HELPER_2(glue(phaddd, SUFFIX), void, Reg, Reg)
-DEF_HELPER_2(glue(phaddsw, SUFFIX), void, Reg, Reg)
-DEF_HELPER_2(glue(phsubw, SUFFIX), void, Reg, Reg)
-DEF_HELPER_2(glue(phsubd, SUFFIX), void, Reg, Reg)
-DEF_HELPER_2(glue(phsubsw, SUFFIX), void, Reg, Reg)
-DEF_HELPER_2(glue(pabsb, SUFFIX), void, Reg, Reg)
-DEF_HELPER_2(glue(pabsw, SUFFIX), void, Reg, Reg)
-DEF_HELPER_2(glue(pabsd, SUFFIX), void, Reg, Reg)
-DEF_HELPER_2(glue(pmaddubsw, SUFFIX), void, Reg, Reg)
-DEF_HELPER_2(glue(pmulhrsw, SUFFIX), void, Reg, Reg)
-DEF_HELPER_2(glue(pshufb, SUFFIX), void, Reg, Reg)
-DEF_HELPER_2(glue(psignb, SUFFIX), void, Reg, Reg)
-DEF_HELPER_2(glue(psignw, SUFFIX), void, Reg, Reg)
-DEF_HELPER_2(glue(psignd, SUFFIX), void, Reg, Reg)
-DEF_HELPER_3(glue(palignr, SUFFIX), void, Reg, Reg, s32)
+DEF_HELPER_3(glue(phaddw, SUFFIX), void, env, Reg, Reg)
+DEF_HELPER_3(glue(phaddd, SUFFIX), void, env, Reg, Reg)
+DEF_HELPER_3(glue(phaddsw, SUFFIX), void, env, Reg, Reg)
+DEF_HELPER_3(glue(phsubw, SUFFIX), void, env, Reg, Reg)
+DEF_HELPER_3(glue(phsubd, SUFFIX), void, env, Reg, Reg)
+DEF_HELPER_3(glue(phsubsw, SUFFIX), void, env, Reg, Reg)
+DEF_HELPER_3(glue(pabsb, SUFFIX), void, env, Reg, Reg)
+DEF_HELPER_3(glue(pabsw, SUFFIX), void, env, Reg, Reg)
+DEF_HELPER_3(glue(pabsd, SUFFIX), void, env, Reg, Reg)
+DEF_HELPER_3(glue(pmaddubsw, SUFFIX), void, env, Reg, Reg)
+DEF_HELPER_3(glue(pmulhrsw, SUFFIX), void, env, Reg, Reg)
+DEF_HELPER_3(glue(pshufb, SUFFIX), void, env, Reg, Reg)
+DEF_HELPER_3(glue(psignb, SUFFIX), void, env, Reg, Reg)
+DEF_HELPER_3(glue(psignw, SUFFIX), void, env, Reg, Reg)
+DEF_HELPER_3(glue(psignd, SUFFIX), void, env, Reg, Reg)
+DEF_HELPER_4(glue(palignr, SUFFIX), void, env, Reg, Reg, s32)
 
 /* SSE4.1 op helpers */
 #if SHIFT == 1
-DEF_HELPER_2(glue(pblendvb, SUFFIX), void, Reg, Reg)
-DEF_HELPER_2(glue(blendvps, SUFFIX), void, Reg, Reg)
-DEF_HELPER_2(glue(blendvpd, SUFFIX), void, Reg, Reg)
-DEF_HELPER_2(glue(ptest, SUFFIX), void, Reg, Reg)
-DEF_HELPER_2(glue(pmovsxbw, SUFFIX), void, Reg, Reg)
-DEF_HELPER_2(glue(pmovsxbd, SUFFIX), void, Reg, Reg)
-DEF_HELPER_2(glue(pmovsxbq, SUFFIX), void, Reg, Reg)
-DEF_HELPER_2(glue(pmovsxwd, SUFFIX), void, Reg, Reg)
-DEF_HELPER_2(glue(pmovsxwq, SUFFIX), void, Reg, Reg)
-DEF_HELPER_2(glue(pmovsxdq, SUFFIX), void, Reg, Reg)
-DEF_HELPER_2(glue(pmovzxbw, SUFFIX), void, Reg, Reg)
-DEF_HELPER_2(glue(pmovzxbd, SUFFIX), void, Reg, Reg)
-DEF_HELPER_2(glue(pmovzxbq, SUFFIX), void, Reg, Reg)
-DEF_HELPER_2(glue(pmovzxwd, SUFFIX), void, Reg, Reg)
-DEF_HELPER_2(glue(pmovzxwq, SUFFIX), void, Reg, Reg)
-DEF_HELPER_2(glue(pmovzxdq, SUFFIX), void, Reg, Reg)
-DEF_HELPER_2(glue(pmuldq, SUFFIX), void, Reg, Reg)
-DEF_HELPER_2(glue(pcmpeqq, SUFFIX), void, Reg, Reg)
-DEF_HELPER_2(glue(packusdw, SUFFIX), void, Reg, Reg)
-DEF_HELPER_2(glue(pminsb, SUFFIX), void, Reg, Reg)
-DEF_HELPER_2(glue(pminsd, SUFFIX), void, Reg, Reg)
-DEF_HELPER_2(glue(pminuw, SUFFIX), void, Reg, Reg)
-DEF_HELPER_2(glue(pminud, SUFFIX), void, Reg, Reg)
-DEF_HELPER_2(glue(pmaxsb, SUFFIX), void, Reg, Reg)
-DEF_HELPER_2(glue(pmaxsd, SUFFIX), void, Reg, Reg)
-DEF_HELPER_2(glue(pmaxuw, SUFFIX), void, Reg, Reg)
-DEF_HELPER_2(glue(pmaxud, SUFFIX), void, Reg, Reg)
-DEF_HELPER_2(glue(pmulld, SUFFIX), void, Reg, Reg)
-DEF_HELPER_2(glue(phminposuw, SUFFIX), void, Reg, Reg)
-DEF_HELPER_3(glue(roundps, SUFFIX), void, Reg, Reg, i32)
-DEF_HELPER_3(glue(roundpd, SUFFIX), void, Reg, Reg, i32)
-DEF_HELPER_3(glue(roundss, SUFFIX), void, Reg, Reg, i32)
-DEF_HELPER_3(glue(roundsd, SUFFIX), void, Reg, Reg, i32)
-DEF_HELPER_3(glue(blendps, SUFFIX), void, Reg, Reg, i32)
-DEF_HELPER_3(glue(blendpd, SUFFIX), void, Reg, Reg, i32)
-DEF_HELPER_3(glue(pblendw, SUFFIX), void, Reg, Reg, i32)
-DEF_HELPER_3(glue(dpps, SUFFIX), void, Reg, Reg, i32)
-DEF_HELPER_3(glue(dppd, SUFFIX), void, Reg, Reg, i32)
-DEF_HELPER_3(glue(mpsadbw, SUFFIX), void, Reg, Reg, i32)
+DEF_HELPER_3(glue(pblendvb, SUFFIX), void, env, Reg, Reg)
+DEF_HELPER_3(glue(blendvps, SUFFIX), void, env, Reg, Reg)
+DEF_HELPER_3(glue(blendvpd, SUFFIX), void, env, Reg, Reg)
+DEF_HELPER_3(glue(ptest, SUFFIX), void, env, Reg, Reg)
+DEF_HELPER_3(glue(pmovsxbw, SUFFIX), void, env, Reg, Reg)
+DEF_HELPER_3(glue(pmovsxbd, SUFFIX), void, env, Reg, Reg)
+DEF_HELPER_3(glue(pmovsxbq, SUFFIX), void, env, Reg, Reg)
+DEF_HELPER_3(glue(pmovsxwd, SUFFIX), void, env, Reg, Reg)
+DEF_HELPER_3(glue(pmovsxwq, SUFFIX), void, env, Reg, Reg)
+DEF_HELPER_3(glue(pmovsxdq, SUFFIX), void, env, Reg, Reg)
+DEF_HELPER_3(glue(pmovzxbw, SUFFIX), void, env, Reg, Reg)
+DEF_HELPER_3(glue(pmovzxbd, SUFFIX), void, env, Reg, Reg)
+DEF_HELPER_3(glue(pmovzxbq, SUFFIX), void, env, Reg, Reg)
+DEF_HELPER_3(glue(pmovzxwd, SUFFIX), void, env, Reg, Reg)
+DEF_HELPER_3(glue(pmovzxwq, SUFFIX), void, env, Reg, Reg)
+DEF_HELPER_3(glue(pmovzxdq, SUFFIX), void, env, Reg, Reg)
+DEF_HELPER_3(glue(pmuldq, SUFFIX), void, env, Reg, Reg)
+DEF_HELPER_3(glue(pcmpeqq, SUFFIX), void, env, Reg, Reg)
+DEF_HELPER_3(glue(packusdw, SUFFIX), void, env, Reg, Reg)
+DEF_HELPER_3(glue(pminsb, SUFFIX), void, env, Reg, Reg)
+DEF_HELPER_3(glue(pminsd, SUFFIX), void, env, Reg, Reg)
+DEF_HELPER_3(glue(pminuw, SUFFIX), void, env, Reg, Reg)
+DEF_HELPER_3(glue(pminud, SUFFIX), void, env, Reg, Reg)
+DEF_HELPER_3(glue(pmaxsb, SUFFIX), void, env, Reg, Reg)
+DEF_HELPER_3(glue(pmaxsd, SUFFIX), void, env, Reg, Reg)
+DEF_HELPER_3(glue(pmaxuw, SUFFIX), void, env, Reg, Reg)
+DEF_HELPER_3(glue(pmaxud, SUFFIX), void, env, Reg, Reg)
+DEF_HELPER_3(glue(pmulld, SUFFIX), void, env, Reg, Reg)
+DEF_HELPER_3(glue(phminposuw, SUFFIX), void, env, Reg, Reg)
+DEF_HELPER_4(glue(roundps, SUFFIX), void, env, Reg, Reg, i32)
+DEF_HELPER_4(glue(roundpd, SUFFIX), void, env, Reg, Reg, i32)
+DEF_HELPER_4(glue(roundss, SUFFIX), void, env, Reg, Reg, i32)
+DEF_HELPER_4(glue(roundsd, SUFFIX), void, env, Reg, Reg, i32)
+DEF_HELPER_4(glue(blendps, SUFFIX), void, env, Reg, Reg, i32)
+DEF_HELPER_4(glue(blendpd, SUFFIX), void, env, Reg, Reg, i32)
+DEF_HELPER_4(glue(pblendw, SUFFIX), void, env, Reg, Reg, i32)
+DEF_HELPER_4(glue(dpps, SUFFIX), void, env, Reg, Reg, i32)
+DEF_HELPER_4(glue(dppd, SUFFIX), void, env, Reg, Reg, i32)
+DEF_HELPER_4(glue(mpsadbw, SUFFIX), void, env, Reg, Reg, i32)
 #endif
 
 /* SSE4.2 op helpers */
 #if SHIFT == 1
-DEF_HELPER_2(glue(pcmpgtq, SUFFIX), void, Reg, Reg)
-DEF_HELPER_3(glue(pcmpestri, SUFFIX), void, Reg, Reg, i32)
-DEF_HELPER_3(glue(pcmpestrm, SUFFIX), void, Reg, Reg, i32)
-DEF_HELPER_3(glue(pcmpistri, SUFFIX), void, Reg, Reg, i32)
-DEF_HELPER_3(glue(pcmpistrm, SUFFIX), void, Reg, Reg, i32)
+DEF_HELPER_3(glue(pcmpgtq, SUFFIX), void, env, Reg, Reg)
+DEF_HELPER_4(glue(pcmpestri, SUFFIX), void, env, Reg, Reg, i32)
+DEF_HELPER_4(glue(pcmpestrm, SUFFIX), void, env, Reg, Reg, i32)
+DEF_HELPER_4(glue(pcmpistri, SUFFIX), void, env, Reg, Reg, i32)
+DEF_HELPER_4(glue(pcmpistrm, SUFFIX), void, env, Reg, Reg, i32)
 DEF_HELPER_3(crc32, tl, i32, tl, i32)
-DEF_HELPER_2(popcnt, tl, tl, i32)
+DEF_HELPER_3(popcnt, tl, env, tl, i32)
 #endif
 
 #undef SHIFT
diff --git a/target-i386/translate.c b/target-i386/translate.c
index 2b11333..5e9da9d 100644
--- a/target-i386/translate.c
+++ b/target-i386/translate.c
@@ -1266,14 +1266,30 @@ GEN_REPZ2(cmps)
 static void gen_helper_fp_arith_ST0_FT0(int op)
 {
     switch (op) {
-    case 0: gen_helper_fadd_ST0_FT0(); break;
-    case 1: gen_helper_fmul_ST0_FT0(); break;
-    case 2: gen_helper_fcom_ST0_FT0(); break;
-    case 3: gen_helper_fcom_ST0_FT0(); break;
-    case 4: gen_helper_fsub_ST0_FT0(); break;
-    case 5: gen_helper_fsubr_ST0_FT0(); break;
-    case 6: gen_helper_fdiv_ST0_FT0(); break;
-    case 7: gen_helper_fdivr_ST0_FT0(); break;
+    case 0:
+        gen_helper_fadd_ST0_FT0(cpu_env);
+        break;
+    case 1:
+        gen_helper_fmul_ST0_FT0(cpu_env);
+        break;
+    case 2:
+        gen_helper_fcom_ST0_FT0(cpu_env);
+        break;
+    case 3:
+        gen_helper_fcom_ST0_FT0(cpu_env);
+        break;
+    case 4:
+        gen_helper_fsub_ST0_FT0(cpu_env);
+        break;
+    case 5:
+        gen_helper_fsubr_ST0_FT0(cpu_env);
+        break;
+    case 6:
+        gen_helper_fdiv_ST0_FT0(cpu_env);
+        break;
+    case 7:
+        gen_helper_fdivr_ST0_FT0(cpu_env);
+        break;
     }
 }
 
@@ -1282,12 +1298,24 @@ static void gen_helper_fp_arith_STN_ST0(int op, int opreg)
 {
     TCGv_i32 tmp = tcg_const_i32(opreg);
     switch (op) {
-    case 0: gen_helper_fadd_STN_ST0(tmp); break;
-    case 1: gen_helper_fmul_STN_ST0(tmp); break;
-    case 4: gen_helper_fsubr_STN_ST0(tmp); break;
-    case 5: gen_helper_fsub_STN_ST0(tmp); break;
-    case 6: gen_helper_fdivr_STN_ST0(tmp); break;
-    case 7: gen_helper_fdiv_STN_ST0(tmp); break;
+    case 0:
+        gen_helper_fadd_STN_ST0(cpu_env, tmp);
+        break;
+    case 1:
+        gen_helper_fmul_STN_ST0(cpu_env, tmp);
+        break;
+    case 4:
+        gen_helper_fsubr_STN_ST0(cpu_env, tmp);
+        break;
+    case 5:
+        gen_helper_fsub_STN_ST0(cpu_env, tmp);
+        break;
+    case 6:
+        gen_helper_fdivr_STN_ST0(cpu_env, tmp);
+        break;
+    case 7:
+        gen_helper_fdiv_STN_ST0(cpu_env, tmp);
+        break;
     }
 }
 
@@ -2796,13 +2824,16 @@ static inline void gen_op_movq_env_0(int d_offset)
     tcg_gen_st_i64(cpu_tmp1_i64, cpu_env, d_offset);
 }
 
-typedef void (*SSEFunc_i_p)(TCGv_i32 val, TCGv_ptr reg);
-typedef void (*SSEFunc_l_p)(TCGv_i64 val, TCGv_ptr reg);
-typedef void (*SSEFunc_0_pi)(TCGv_ptr reg, TCGv_i32 val);
-typedef void (*SSEFunc_0_pl)(TCGv_ptr reg, TCGv_i64 val);
-typedef void (*SSEFunc_0_pp)(TCGv_ptr reg_a, TCGv_ptr reg_b);
+typedef void (*SSEFunc_i_ep)(TCGv_i32 val, TCGv_ptr env, TCGv_ptr reg);
+typedef void (*SSEFunc_l_ep)(TCGv_i64 val, TCGv_ptr env, TCGv_ptr reg);
+typedef void (*SSEFunc_0_epi)(TCGv_ptr env, TCGv_ptr reg, TCGv_i32 val);
+typedef void (*SSEFunc_0_epl)(TCGv_ptr env, TCGv_ptr reg, TCGv_i64 val);
+typedef void (*SSEFunc_0_epp)(TCGv_ptr env, TCGv_ptr reg_a, TCGv_ptr reg_b);
+typedef void (*SSEFunc_0_eppi)(TCGv_ptr env, TCGv_ptr reg_a, TCGv_ptr reg_b,
+                               TCGv_i32 val);
 typedef void (*SSEFunc_0_ppi)(TCGv_ptr reg_a, TCGv_ptr reg_b, TCGv_i32 val);
-typedef void (*SSEFunc_0_ppt)(TCGv_ptr reg_a, TCGv_ptr reg_b, TCGv val);
+typedef void (*SSEFunc_0_eppt)(TCGv_ptr env, TCGv_ptr reg_a, TCGv_ptr reg_b,
+                               TCGv val);
 
 #define SSE_SPECIAL ((void *)1)
 #define SSE_DUMMY ((void *)2)
@@ -2811,7 +2842,7 @@ typedef void (*SSEFunc_0_ppt)(TCGv_ptr reg_a, TCGv_ptr reg_b, TCGv val);
 #define SSE_FOP(x) { gen_helper_ ## x ## ps, gen_helper_ ## x ## pd, \
                      gen_helper_ ## x ## ss, gen_helper_ ## x ## sd, }
 
-static const SSEFunc_0_pp sse_op_table1[256][4] = {
+static const SSEFunc_0_epp sse_op_table1[256][4] = {
     /* 3DNow! extensions */
     [0x0e] = { SSE_DUMMY }, /* femms */
     [0x0f] = { SSE_DUMMY }, /* pf... */
@@ -2852,8 +2883,8 @@ static const SSEFunc_0_pp sse_op_table1[256][4] = {
     [0x5f] = SSE_FOP(max),
 
     [0xc2] = SSE_FOP(cmpeq),
-    [0xc6] = { (SSEFunc_0_pp)gen_helper_shufps,
-               (SSEFunc_0_pp)gen_helper_shufpd }, /* XXX: casts */
+    [0xc6] = { (SSEFunc_0_epp)gen_helper_shufps,
+               (SSEFunc_0_epp)gen_helper_shufpd }, /* XXX: casts */
 
     [0x38] = { SSE_SPECIAL, SSE_SPECIAL, NULL, SSE_SPECIAL }, /* SSSE3/SSE4 */
     [0x3a] = { SSE_SPECIAL, SSE_SPECIAL }, /* SSSE3/SSE4 */
@@ -2875,10 +2906,10 @@ static const SSEFunc_0_pp sse_op_table1[256][4] = {
     [0x6d] = { NULL, gen_helper_punpckhqdq_xmm },
     [0x6e] = { SSE_SPECIAL, SSE_SPECIAL }, /* movd mm, ea */
     [0x6f] = { SSE_SPECIAL, SSE_SPECIAL, SSE_SPECIAL }, /* movq, movdqa, , movqdu */
-    [0x70] = { (SSEFunc_0_pp)gen_helper_pshufw_mmx,
-               (SSEFunc_0_pp)gen_helper_pshufd_xmm,
-               (SSEFunc_0_pp)gen_helper_pshufhw_xmm,
-               (SSEFunc_0_pp)gen_helper_pshuflw_xmm }, /* XXX: casts */
+    [0x70] = { (SSEFunc_0_epp)gen_helper_pshufw_mmx,
+               (SSEFunc_0_epp)gen_helper_pshufd_xmm,
+               (SSEFunc_0_epp)gen_helper_pshufhw_xmm,
+               (SSEFunc_0_epp)gen_helper_pshuflw_xmm }, /* XXX: casts */
     [0x71] = { SSE_SPECIAL, SSE_SPECIAL }, /* shiftw */
     [0x72] = { SSE_SPECIAL, SSE_SPECIAL }, /* shiftd */
     [0x73] = { SSE_SPECIAL, SSE_SPECIAL }, /* shiftq */
@@ -2933,8 +2964,8 @@ static const SSEFunc_0_pp sse_op_table1[256][4] = {
     [0xf4] = MMX_OP2(pmuludq),
     [0xf5] = MMX_OP2(pmaddwd),
     [0xf6] = MMX_OP2(psadbw),
-    [0xf7] = { (SSEFunc_0_pp)gen_helper_maskmov_mmx,
-               (SSEFunc_0_pp)gen_helper_maskmov_xmm }, /* XXX: casts */
+    [0xf7] = { (SSEFunc_0_epp)gen_helper_maskmov_mmx,
+               (SSEFunc_0_epp)gen_helper_maskmov_xmm }, /* XXX: casts */
     [0xf8] = MMX_OP2(psubb),
     [0xf9] = MMX_OP2(psubw),
     [0xfa] = MMX_OP2(psubl),
@@ -2944,7 +2975,7 @@ static const SSEFunc_0_pp sse_op_table1[256][4] = {
     [0xfe] = MMX_OP2(paddl),
 };
 
-static const SSEFunc_0_pp sse_op_table2[3 * 8][2] = {
+static const SSEFunc_0_epp sse_op_table2[3 * 8][2] = {
     [0 + 2] = MMX_OP2(psrlw),
     [0 + 4] = MMX_OP2(psraw),
     [0 + 6] = MMX_OP2(psllw),
@@ -2957,19 +2988,19 @@ static const SSEFunc_0_pp sse_op_table2[3 * 8][2] = {
     [16 + 7] = { NULL, gen_helper_pslldq_xmm },
 };
 
-static const SSEFunc_0_pi sse_op_table3ai[] = {
+static const SSEFunc_0_epi sse_op_table3ai[] = {
     gen_helper_cvtsi2ss,
     gen_helper_cvtsi2sd
 };
 
 #ifdef TARGET_X86_64
-static const SSEFunc_0_pl sse_op_table3aq[] = {
+static const SSEFunc_0_epl sse_op_table3aq[] = {
     gen_helper_cvtsq2ss,
     gen_helper_cvtsq2sd
 };
 #endif
 
-static const SSEFunc_i_p sse_op_table3bi[] = {
+static const SSEFunc_i_ep sse_op_table3bi[] = {
     gen_helper_cvttss2si,
     gen_helper_cvtss2si,
     gen_helper_cvttsd2si,
@@ -2977,7 +3008,7 @@ static const SSEFunc_i_p sse_op_table3bi[] = {
 };
 
 #ifdef TARGET_X86_64
-static const SSEFunc_l_p sse_op_table3bq[] = {
+static const SSEFunc_l_ep sse_op_table3bq[] = {
     gen_helper_cvttss2sq,
     gen_helper_cvtss2sq,
     gen_helper_cvttsd2sq,
@@ -2985,7 +3016,7 @@ static const SSEFunc_l_p sse_op_table3bq[] = {
 };
 #endif
 
-static const SSEFunc_0_pp sse_op_table4[8][4] = {
+static const SSEFunc_0_epp sse_op_table4[8][4] = {
     SSE_FOP(cmpeq),
     SSE_FOP(cmplt),
     SSE_FOP(cmple),
@@ -2996,7 +3027,7 @@ static const SSEFunc_0_pp sse_op_table4[8][4] = {
     SSE_FOP(cmpord),
 };
 
-static const SSEFunc_0_pp sse_op_table5[256] = {
+static const SSEFunc_0_epp sse_op_table5[256] = {
     [0x0c] = gen_helper_pi2fw,
     [0x0d] = gen_helper_pi2fd,
     [0x1c] = gen_helper_pf2iw,
@@ -3023,13 +3054,13 @@ static const SSEFunc_0_pp sse_op_table5[256] = {
     [0xbf] = gen_helper_pavgb_mmx /* pavgusb */
 };
 
-struct SSEOpHelper_pp {
-    SSEFunc_0_pp op[2];
+struct SSEOpHelper_epp {
+    SSEFunc_0_epp op[2];
     uint32_t ext_mask;
 };
 
-struct SSEOpHelper_ppi {
-    SSEFunc_0_ppi op[2];
+struct SSEOpHelper_eppi {
+    SSEFunc_0_eppi op[2];
     uint32_t ext_mask;
 };
 
@@ -3038,7 +3069,7 @@ struct SSEOpHelper_ppi {
 #define SSE42_OP(x) { { NULL, gen_helper_ ## x ## _xmm }, CPUID_EXT_SSE42 }
 #define SSE41_SPECIAL { { NULL, SSE_SPECIAL }, CPUID_EXT_SSE41 }
 
-static const struct SSEOpHelper_pp sse_op_table6[256] = {
+static const struct SSEOpHelper_epp sse_op_table6[256] = {
     [0x00] = SSSE3_OP(pshufb),
     [0x01] = SSSE3_OP(phaddw),
     [0x02] = SSSE3_OP(phaddd),
@@ -3087,7 +3118,7 @@ static const struct SSEOpHelper_pp sse_op_table6[256] = {
     [0x41] = SSE41_OP(phminposuw),
 };
 
-static const struct SSEOpHelper_ppi sse_op_table7[256] = {
+static const struct SSEOpHelper_eppi sse_op_table7[256] = {
     [0x08] = SSE41_OP(roundps),
     [0x09] = SSE41_OP(roundpd),
     [0x0a] = SSE41_OP(roundss),
@@ -3116,9 +3147,10 @@ static void gen_sse(DisasContext *s, int b, target_ulong pc_start, int rex_r)
 {
     int b1, op1_offset, op2_offset, is_xmm, val, ot;
     int modrm, mod, rm, reg, reg_addr, offset_addr;
-    SSEFunc_0_pp sse_fn_pp;
+    SSEFunc_0_epp sse_fn_epp;
+    SSEFunc_0_eppi sse_fn_eppi;
     SSEFunc_0_ppi sse_fn_ppi;
-    SSEFunc_0_ppt sse_fn_ppt;
+    SSEFunc_0_eppt sse_fn_eppt;
 
     b &= 0xff;
     if (s->prefix & PREFIX_DATA)
@@ -3129,8 +3161,8 @@ static void gen_sse(DisasContext *s, int b, target_ulong pc_start, int rex_r)
         b1 = 3;
     else
         b1 = 0;
-    sse_fn_pp = sse_op_table1[b][b1];
-    if (!sse_fn_pp) {
+    sse_fn_epp = sse_op_table1[b][b1];
+    if (!sse_fn_epp) {
         goto illegal_op;
     }
     if ((b <= 0x5f && b >= 0x10) || b == 0xc6 || b == 0xc2) {
@@ -3160,18 +3192,18 @@ static void gen_sse(DisasContext *s, int b, target_ulong pc_start, int rex_r)
         if (!(s->cpuid_ext2_features & CPUID_EXT2_3DNOW))
             goto illegal_op;
         /* femms */
-        gen_helper_emms();
+        gen_helper_emms(cpu_env);
         return;
     }
     if (b == 0x77) {
         /* emms */
-        gen_helper_emms();
+        gen_helper_emms(cpu_env);
         return;
     }
     /* prepare MMX state (XXX: optimize by storing fptt and fptags in
        the static cpu state) */
     if (!is_xmm) {
-        gen_helper_enter_mmx();
+        gen_helper_enter_mmx(cpu_env);
     }
 
     modrm = ldub_code(s->pc++);
@@ -3179,7 +3211,7 @@ static void gen_sse(DisasContext *s, int b, target_ulong pc_start, int rex_r)
     if (is_xmm)
         reg |= rex_r;
     mod = (modrm >> 6) & 3;
-    if (sse_fn_pp == SSE_SPECIAL) {
+    if (sse_fn_epp == SSE_SPECIAL) {
         b |= (b1 << 8);
         switch(b) {
         case 0x0e7: /* movntq */
@@ -3383,11 +3415,13 @@ static void gen_sse(DisasContext *s, int b, target_ulong pc_start, int rex_r)
                 tcg_gen_addi_ptr(cpu_ptr0, cpu_env,
                     offsetof(CPUX86State,xmm_regs[reg]));
                 if (b1 == 1)
-                    gen_helper_extrq_i(cpu_ptr0, tcg_const_i32(bit_index),
-                        tcg_const_i32(field_length));
+                    gen_helper_extrq_i(cpu_env, cpu_ptr0,
+                                       tcg_const_i32(bit_index),
+                                       tcg_const_i32(field_length));
                 else
-                    gen_helper_insertq_i(cpu_ptr0, tcg_const_i32(bit_index),
-                        tcg_const_i32(field_length));
+                    gen_helper_insertq_i(cpu_env, cpu_ptr0,
+                                         tcg_const_i32(bit_index),
+                                         tcg_const_i32(field_length));
             }
             break;
         case 0x7e: /* movd ea, mm */
@@ -3516,8 +3550,9 @@ static void gen_sse(DisasContext *s, int b, target_ulong pc_start, int rex_r)
                 tcg_gen_st32_tl(cpu_T[0], cpu_env, offsetof(CPUX86State,mmx_t0.MMX_L(1)));
                 op1_offset = offsetof(CPUX86State,mmx_t0);
             }
-            sse_fn_pp = sse_op_table2[((b - 1) & 3) * 8 + (((modrm >> 3)) & 7)][b1];
-            if (!sse_fn_pp) {
+            sse_fn_epp = sse_op_table2[((b - 1) & 3) * 8 +
+                                       (((modrm >> 3)) & 7)][b1];
+            if (!sse_fn_epp) {
                 goto illegal_op;
             }
             if (is_xmm) {
@@ -3529,13 +3564,13 @@ static void gen_sse(DisasContext *s, int b, target_ulong pc_start, int rex_r)
             }
             tcg_gen_addi_ptr(cpu_ptr0, cpu_env, op2_offset);
             tcg_gen_addi_ptr(cpu_ptr1, cpu_env, op1_offset);
-            sse_fn_pp(cpu_ptr0, cpu_ptr1);
+            sse_fn_epp(cpu_env, cpu_ptr0, cpu_ptr1);
             break;
         case 0x050: /* movmskps */
             rm = (modrm & 7) | REX_B(s);
             tcg_gen_addi_ptr(cpu_ptr0, cpu_env, 
                              offsetof(CPUX86State,xmm_regs[rm]));
-            gen_helper_movmskps(cpu_tmp2_i32, cpu_ptr0);
+            gen_helper_movmskps(cpu_tmp2_i32, cpu_env, cpu_ptr0);
             tcg_gen_extu_i32_tl(cpu_T[0], cpu_tmp2_i32);
             gen_op_mov_reg_T0(OT_LONG, reg);
             break;
@@ -3543,13 +3578,13 @@ static void gen_sse(DisasContext *s, int b, target_ulong pc_start, int rex_r)
             rm = (modrm & 7) | REX_B(s);
             tcg_gen_addi_ptr(cpu_ptr0, cpu_env, 
                              offsetof(CPUX86State,xmm_regs[rm]));
-            gen_helper_movmskpd(cpu_tmp2_i32, cpu_ptr0);
+            gen_helper_movmskpd(cpu_tmp2_i32, cpu_env, cpu_ptr0);
             tcg_gen_extu_i32_tl(cpu_T[0], cpu_tmp2_i32);
             gen_op_mov_reg_T0(OT_LONG, reg);
             break;
         case 0x02a: /* cvtpi2ps */
         case 0x12a: /* cvtpi2pd */
-            gen_helper_enter_mmx();
+            gen_helper_enter_mmx(cpu_env);
             if (mod != 3) {
                 gen_lea_modrm(s, modrm, &reg_addr, &offset_addr);
                 op2_offset = offsetof(CPUX86State,mmx_t0);
@@ -3563,11 +3598,11 @@ static void gen_sse(DisasContext *s, int b, target_ulong pc_start, int rex_r)
             tcg_gen_addi_ptr(cpu_ptr1, cpu_env, op2_offset);
             switch(b >> 8) {
             case 0x0:
-                gen_helper_cvtpi2ps(cpu_ptr0, cpu_ptr1);
+                gen_helper_cvtpi2ps(cpu_env, cpu_ptr0, cpu_ptr1);
                 break;
             default:
             case 0x1:
-                gen_helper_cvtpi2pd(cpu_ptr0, cpu_ptr1);
+                gen_helper_cvtpi2pd(cpu_env, cpu_ptr0, cpu_ptr1);
                 break;
             }
             break;
@@ -3578,13 +3613,13 @@ static void gen_sse(DisasContext *s, int b, target_ulong pc_start, int rex_r)
             op1_offset = offsetof(CPUX86State,xmm_regs[reg]);
             tcg_gen_addi_ptr(cpu_ptr0, cpu_env, op1_offset);
             if (ot == OT_LONG) {
-                SSEFunc_0_pi sse_fn_pi = sse_op_table3ai[(b >> 8) & 1];
+                SSEFunc_0_epi sse_fn_epi = sse_op_table3ai[(b >> 8) & 1];
                 tcg_gen_trunc_tl_i32(cpu_tmp2_i32, cpu_T[0]);
-                sse_fn_pi(cpu_ptr0, cpu_tmp2_i32);
+                sse_fn_epi(cpu_env, cpu_ptr0, cpu_tmp2_i32);
             } else {
 #ifdef TARGET_X86_64
-                SSEFunc_0_pl sse_fn_pl = sse_op_table3aq[(b >> 8) & 1];
-                sse_fn_pl(cpu_ptr0, cpu_T[0]);
+                SSEFunc_0_epl sse_fn_epl = sse_op_table3aq[(b >> 8) & 1];
+                sse_fn_epl(cpu_env, cpu_ptr0, cpu_T[0]);
 #else
                 goto illegal_op;
 #endif
@@ -3594,7 +3629,7 @@ static void gen_sse(DisasContext *s, int b, target_ulong pc_start, int rex_r)
         case 0x12c: /* cvttpd2pi */
         case 0x02d: /* cvtps2pi */
         case 0x12d: /* cvtpd2pi */
-            gen_helper_enter_mmx();
+            gen_helper_enter_mmx(cpu_env);
             if (mod != 3) {
                 gen_lea_modrm(s, modrm, &reg_addr, &offset_addr);
                 op2_offset = offsetof(CPUX86State,xmm_t0);
@@ -3608,16 +3643,16 @@ static void gen_sse(DisasContext *s, int b, target_ulong pc_start, int rex_r)
             tcg_gen_addi_ptr(cpu_ptr1, cpu_env, op2_offset);
             switch(b) {
             case 0x02c:
-                gen_helper_cvttps2pi(cpu_ptr0, cpu_ptr1);
+                gen_helper_cvttps2pi(cpu_env, cpu_ptr0, cpu_ptr1);
                 break;
             case 0x12c:
-                gen_helper_cvttpd2pi(cpu_ptr0, cpu_ptr1);
+                gen_helper_cvttpd2pi(cpu_env, cpu_ptr0, cpu_ptr1);
                 break;
             case 0x02d:
-                gen_helper_cvtps2pi(cpu_ptr0, cpu_ptr1);
+                gen_helper_cvtps2pi(cpu_env, cpu_ptr0, cpu_ptr1);
                 break;
             case 0x12d:
-                gen_helper_cvtpd2pi(cpu_ptr0, cpu_ptr1);
+                gen_helper_cvtpd2pi(cpu_env, cpu_ptr0, cpu_ptr1);
                 break;
             }
             break;
@@ -3641,15 +3676,15 @@ static void gen_sse(DisasContext *s, int b, target_ulong pc_start, int rex_r)
             }
             tcg_gen_addi_ptr(cpu_ptr0, cpu_env, op2_offset);
             if (ot == OT_LONG) {
-                SSEFunc_i_p sse_fn_i_p =
+                SSEFunc_i_ep sse_fn_i_ep =
                     sse_op_table3bi[((b >> 7) & 2) | (b & 1)];
-                sse_fn_i_p(cpu_tmp2_i32, cpu_ptr0);
+                sse_fn_i_ep(cpu_tmp2_i32, cpu_env, cpu_ptr0);
                 tcg_gen_extu_i32_tl(cpu_T[0], cpu_tmp2_i32);
             } else {
 #ifdef TARGET_X86_64
-                SSEFunc_l_p sse_fn_l_p =
+                SSEFunc_l_ep sse_fn_l_ep =
                     sse_op_table3bq[((b >> 7) & 2) | (b & 1)];
-                sse_fn_l_p(cpu_T[0], cpu_ptr0);
+                sse_fn_l_ep(cpu_T[0], cpu_env, cpu_ptr0);
 #else
                 goto illegal_op;
 #endif
@@ -3703,14 +3738,14 @@ static void gen_sse(DisasContext *s, int b, target_ulong pc_start, int rex_r)
             }
             break;
         case 0x2d6: /* movq2dq */
-            gen_helper_enter_mmx();
+            gen_helper_enter_mmx(cpu_env);
             rm = (modrm & 7);
             gen_op_movq(offsetof(CPUX86State,xmm_regs[reg].XMM_Q(0)),
                         offsetof(CPUX86State,fpregs[rm].mmx));
             gen_op_movq_env_0(offsetof(CPUX86State,xmm_regs[reg].XMM_Q(1)));
             break;
         case 0x3d6: /* movdq2q */
-            gen_helper_enter_mmx();
+            gen_helper_enter_mmx(cpu_env);
             rm = (modrm & 7) | REX_B(s);
             gen_op_movq(offsetof(CPUX86State,fpregs[reg & 7].mmx),
                         offsetof(CPUX86State,xmm_regs[rm].XMM_Q(0)));
@@ -3722,11 +3757,11 @@ static void gen_sse(DisasContext *s, int b, target_ulong pc_start, int rex_r)
             if (b1) {
                 rm = (modrm & 7) | REX_B(s);
                 tcg_gen_addi_ptr(cpu_ptr0, cpu_env, offsetof(CPUX86State,xmm_regs[rm]));
-                gen_helper_pmovmskb_xmm(cpu_tmp2_i32, cpu_ptr0);
+                gen_helper_pmovmskb_xmm(cpu_tmp2_i32, cpu_env, cpu_ptr0);
             } else {
                 rm = (modrm & 7);
                 tcg_gen_addi_ptr(cpu_ptr0, cpu_env, offsetof(CPUX86State,fpregs[rm].mmx));
-                gen_helper_pmovmskb_mmx(cpu_tmp2_i32, cpu_ptr0);
+                gen_helper_pmovmskb_mmx(cpu_tmp2_i32, cpu_env, cpu_ptr0);
             }
             tcg_gen_extu_i32_tl(cpu_T[0], cpu_tmp2_i32);
             reg = ((modrm >> 3) & 7) | rex_r;
@@ -3745,8 +3780,8 @@ static void gen_sse(DisasContext *s, int b, target_ulong pc_start, int rex_r)
                 goto illegal_op;
             }
 
-            sse_fn_pp = sse_op_table6[b].op[b1];
-            if (!sse_fn_pp) {
+            sse_fn_epp = sse_op_table6[b].op[b1];
+            if (!sse_fn_epp) {
                 goto illegal_op;
             }
             if (!(s->cpuid_ext_features & sse_op_table6[b].ext_mask))
@@ -3797,13 +3832,13 @@ static void gen_sse(DisasContext *s, int b, target_ulong pc_start, int rex_r)
                     gen_ldq_env_A0(s->mem_index, op2_offset);
                 }
             }
-            if (sse_fn_pp == SSE_SPECIAL) {
+            if (sse_fn_epp == SSE_SPECIAL) {
                 goto illegal_op;
             }
 
             tcg_gen_addi_ptr(cpu_ptr0, cpu_env, op1_offset);
             tcg_gen_addi_ptr(cpu_ptr1, cpu_env, op2_offset);
-            sse_fn_pp(cpu_ptr0, cpu_ptr1);
+            sse_fn_epp(cpu_env, cpu_ptr0, cpu_ptr1);
 
             if (b == 0x17)
                 s->cc_op = CC_OP_EFLAGS;
@@ -3849,14 +3884,14 @@ static void gen_sse(DisasContext *s, int b, target_ulong pc_start, int rex_r)
                 goto illegal_op;
             }
 
-            sse_fn_ppi = sse_op_table7[b].op[b1];
-            if (!sse_fn_ppi) {
+            sse_fn_eppi = sse_op_table7[b].op[b1];
+            if (!sse_fn_eppi) {
                 goto illegal_op;
             }
             if (!(s->cpuid_ext_features & sse_op_table7[b].ext_mask))
                 goto illegal_op;
 
-            if (sse_fn_ppi == SSE_SPECIAL) {
+            if (sse_fn_eppi == SSE_SPECIAL) {
                 ot = (s->dflag == 2) ? OT_QUAD : OT_LONG;
                 rm = (modrm & 7) | REX_B(s);
                 if (mod != 3)
@@ -4017,7 +4052,7 @@ static void gen_sse(DisasContext *s, int b, target_ulong pc_start, int rex_r)
 
             tcg_gen_addi_ptr(cpu_ptr0, cpu_env, op1_offset);
             tcg_gen_addi_ptr(cpu_ptr1, cpu_env, op2_offset);
-            sse_fn_ppi(cpu_ptr0, cpu_ptr1, tcg_const_i32(val));
+            sse_fn_eppi(cpu_env, cpu_ptr0, cpu_ptr1, tcg_const_i32(val));
             break;
         default:
             goto illegal_op;
@@ -4072,13 +4107,13 @@ static void gen_sse(DisasContext *s, int b, target_ulong pc_start, int rex_r)
             if (!(s->cpuid_ext2_features & CPUID_EXT2_3DNOW))
                 goto illegal_op;
             val = ldub_code(s->pc++);
-            sse_fn_pp = sse_op_table5[val];
-            if (!sse_fn_pp) {
+            sse_fn_epp = sse_op_table5[val];
+            if (!sse_fn_epp) {
                 goto illegal_op;
             }
             tcg_gen_addi_ptr(cpu_ptr0, cpu_env, op1_offset);
             tcg_gen_addi_ptr(cpu_ptr1, cpu_env, op2_offset);
-            sse_fn_pp(cpu_ptr0, cpu_ptr1);
+            sse_fn_epp(cpu_env, cpu_ptr0, cpu_ptr1);
             break;
         case 0x70: /* pshufx insn */
         case 0xc6: /* pshufx insn */
@@ -4086,7 +4121,7 @@ static void gen_sse(DisasContext *s, int b, target_ulong pc_start, int rex_r)
             tcg_gen_addi_ptr(cpu_ptr0, cpu_env, op1_offset);
             tcg_gen_addi_ptr(cpu_ptr1, cpu_env, op2_offset);
             /* XXX: introduce a new table? */
-            sse_fn_ppi = (SSEFunc_0_ppi)sse_fn_pp;
+            sse_fn_ppi = (SSEFunc_0_ppi)sse_fn_epp;
             sse_fn_ppi(cpu_ptr0, cpu_ptr1, tcg_const_i32(val));
             break;
         case 0xc2:
@@ -4094,11 +4129,11 @@ static void gen_sse(DisasContext *s, int b, target_ulong pc_start, int rex_r)
             val = ldub_code(s->pc++);
             if (val >= 8)
                 goto illegal_op;
-            sse_fn_pp = sse_op_table4[val][b1];
+            sse_fn_epp = sse_op_table4[val][b1];
 
             tcg_gen_addi_ptr(cpu_ptr0, cpu_env, op1_offset);
             tcg_gen_addi_ptr(cpu_ptr1, cpu_env, op2_offset);
-            sse_fn_pp(cpu_ptr0, cpu_ptr1);
+            sse_fn_epp(cpu_env, cpu_ptr0, cpu_ptr1);
             break;
         case 0xf7:
             /* maskmov : we must prepare A0 */
@@ -4119,13 +4154,13 @@ static void gen_sse(DisasContext *s, int b, target_ulong pc_start, int rex_r)
             tcg_gen_addi_ptr(cpu_ptr0, cpu_env, op1_offset);
             tcg_gen_addi_ptr(cpu_ptr1, cpu_env, op2_offset);
             /* XXX: introduce a new table? */
-            sse_fn_ppt = (SSEFunc_0_ppt)sse_fn_pp;
-            sse_fn_ppt(cpu_ptr0, cpu_ptr1, cpu_A0);
+            sse_fn_eppt = (SSEFunc_0_eppt)sse_fn_epp;
+            sse_fn_eppt(cpu_env, cpu_ptr0, cpu_ptr1, cpu_A0);
             break;
         default:
             tcg_gen_addi_ptr(cpu_ptr0, cpu_env, op1_offset);
             tcg_gen_addi_ptr(cpu_ptr1, cpu_env, op2_offset);
-            sse_fn_pp(cpu_ptr0, cpu_ptr1);
+            sse_fn_epp(cpu_env, cpu_ptr0, cpu_ptr1);
             break;
         }
         if (b == 0x2e || b == 0x2f) {
@@ -5542,30 +5577,30 @@ static target_ulong disas_insn(DisasContext *s, target_ulong pc_start)
                     case 0:
                         gen_op_ld_T0_A0(OT_LONG + s->mem_index);
                         tcg_gen_trunc_tl_i32(cpu_tmp2_i32, cpu_T[0]);
-                        gen_helper_flds_FT0(cpu_tmp2_i32);
+                        gen_helper_flds_FT0(cpu_env, cpu_tmp2_i32);
                         break;
                     case 1:
                         gen_op_ld_T0_A0(OT_LONG + s->mem_index);
                         tcg_gen_trunc_tl_i32(cpu_tmp2_i32, cpu_T[0]);
-                        gen_helper_fildl_FT0(cpu_tmp2_i32);
+                        gen_helper_fildl_FT0(cpu_env, cpu_tmp2_i32);
                         break;
                     case 2:
                         tcg_gen_qemu_ld64(cpu_tmp1_i64, cpu_A0, 
                                           (s->mem_index >> 2) - 1);
-                        gen_helper_fldl_FT0(cpu_tmp1_i64);
+                        gen_helper_fldl_FT0(cpu_env, cpu_tmp1_i64);
                         break;
                     case 3:
                     default:
                         gen_op_lds_T0_A0(OT_WORD + s->mem_index);
                         tcg_gen_trunc_tl_i32(cpu_tmp2_i32, cpu_T[0]);
-                        gen_helper_fildl_FT0(cpu_tmp2_i32);
+                        gen_helper_fildl_FT0(cpu_env, cpu_tmp2_i32);
                         break;
                     }
 
                     gen_helper_fp_arith_ST0_FT0(op1);
                     if (op1 == 3) {
                         /* fcomp needs pop */
-                        gen_helper_fpop();
+                        gen_helper_fpop(cpu_env);
                     }
                 }
                 break;
@@ -5581,23 +5616,23 @@ static target_ulong disas_insn(DisasContext *s, target_ulong pc_start)
                     case 0:
                         gen_op_ld_T0_A0(OT_LONG + s->mem_index);
                         tcg_gen_trunc_tl_i32(cpu_tmp2_i32, cpu_T[0]);
-                        gen_helper_flds_ST0(cpu_tmp2_i32);
+                        gen_helper_flds_ST0(cpu_env, cpu_tmp2_i32);
                         break;
                     case 1:
                         gen_op_ld_T0_A0(OT_LONG + s->mem_index);
                         tcg_gen_trunc_tl_i32(cpu_tmp2_i32, cpu_T[0]);
-                        gen_helper_fildl_ST0(cpu_tmp2_i32);
+                        gen_helper_fildl_ST0(cpu_env, cpu_tmp2_i32);
                         break;
                     case 2:
                         tcg_gen_qemu_ld64(cpu_tmp1_i64, cpu_A0, 
                                           (s->mem_index >> 2) - 1);
-                        gen_helper_fldl_ST0(cpu_tmp1_i64);
+                        gen_helper_fldl_ST0(cpu_env, cpu_tmp1_i64);
                         break;
                     case 3:
                     default:
                         gen_op_lds_T0_A0(OT_WORD + s->mem_index);
                         tcg_gen_trunc_tl_i32(cpu_tmp2_i32, cpu_T[0]);
-                        gen_helper_fildl_ST0(cpu_tmp2_i32);
+                        gen_helper_fildl_ST0(cpu_env, cpu_tmp2_i32);
                         break;
                     }
                     break;
@@ -5605,50 +5640,50 @@ static target_ulong disas_insn(DisasContext *s, target_ulong pc_start)
                     /* XXX: the corresponding CPUID bit must be tested ! */
                     switch(op >> 4) {
                     case 1:
-                        gen_helper_fisttl_ST0(cpu_tmp2_i32);
+                        gen_helper_fisttl_ST0(cpu_tmp2_i32, cpu_env);
                         tcg_gen_extu_i32_tl(cpu_T[0], cpu_tmp2_i32);
                         gen_op_st_T0_A0(OT_LONG + s->mem_index);
                         break;
                     case 2:
-                        gen_helper_fisttll_ST0(cpu_tmp1_i64);
+                        gen_helper_fisttll_ST0(cpu_tmp1_i64, cpu_env);
                         tcg_gen_qemu_st64(cpu_tmp1_i64, cpu_A0, 
                                           (s->mem_index >> 2) - 1);
                         break;
                     case 3:
                     default:
-                        gen_helper_fistt_ST0(cpu_tmp2_i32);
+                        gen_helper_fistt_ST0(cpu_tmp2_i32, cpu_env);
                         tcg_gen_extu_i32_tl(cpu_T[0], cpu_tmp2_i32);
                         gen_op_st_T0_A0(OT_WORD + s->mem_index);
                         break;
                     }
-                    gen_helper_fpop();
+                    gen_helper_fpop(cpu_env);
                     break;
                 default:
                     switch(op >> 4) {
                     case 0:
-                        gen_helper_fsts_ST0(cpu_tmp2_i32);
+                        gen_helper_fsts_ST0(cpu_tmp2_i32, cpu_env);
                         tcg_gen_extu_i32_tl(cpu_T[0], cpu_tmp2_i32);
                         gen_op_st_T0_A0(OT_LONG + s->mem_index);
                         break;
                     case 1:
-                        gen_helper_fistl_ST0(cpu_tmp2_i32);
+                        gen_helper_fistl_ST0(cpu_tmp2_i32, cpu_env);
                         tcg_gen_extu_i32_tl(cpu_T[0], cpu_tmp2_i32);
                         gen_op_st_T0_A0(OT_LONG + s->mem_index);
                         break;
                     case 2:
-                        gen_helper_fstl_ST0(cpu_tmp1_i64);
+                        gen_helper_fstl_ST0(cpu_tmp1_i64, cpu_env);
                         tcg_gen_qemu_st64(cpu_tmp1_i64, cpu_A0, 
                                           (s->mem_index >> 2) - 1);
                         break;
                     case 3:
                     default:
-                        gen_helper_fist_ST0(cpu_tmp2_i32);
+                        gen_helper_fist_ST0(cpu_tmp2_i32, cpu_env);
                         tcg_gen_extu_i32_tl(cpu_T[0], cpu_tmp2_i32);
                         gen_op_st_T0_A0(OT_WORD + s->mem_index);
                         break;
                     }
                     if ((op & 7) == 3)
-                        gen_helper_fpop();
+                        gen_helper_fpop(cpu_env);
                     break;
                 }
                 break;
@@ -5656,22 +5691,21 @@ static target_ulong disas_insn(DisasContext *s, target_ulong pc_start)
                 if (s->cc_op != CC_OP_DYNAMIC)
                     gen_op_set_cc_op(s->cc_op);
                 gen_jmp_im(pc_start - s->cs_base);
-                gen_helper_fldenv(
-                                   cpu_A0, tcg_const_i32(s->dflag));
+                gen_helper_fldenv(cpu_env, cpu_A0, tcg_const_i32(s->dflag));
                 break;
             case 0x0d: /* fldcw mem */
                 gen_op_ld_T0_A0(OT_WORD + s->mem_index);
                 tcg_gen_trunc_tl_i32(cpu_tmp2_i32, cpu_T[0]);
-                gen_helper_fldcw(cpu_tmp2_i32);
+                gen_helper_fldcw(cpu_env, cpu_tmp2_i32);
                 break;
             case 0x0e: /* fnstenv mem */
                 if (s->cc_op != CC_OP_DYNAMIC)
                     gen_op_set_cc_op(s->cc_op);
                 gen_jmp_im(pc_start - s->cs_base);
-                gen_helper_fstenv(cpu_A0, tcg_const_i32(s->dflag));
+                gen_helper_fstenv(cpu_env, cpu_A0, tcg_const_i32(s->dflag));
                 break;
             case 0x0f: /* fnstcw mem */
-                gen_helper_fnstcw(cpu_tmp2_i32);
+                gen_helper_fnstcw(cpu_tmp2_i32, cpu_env);
                 tcg_gen_extu_i32_tl(cpu_T[0], cpu_tmp2_i32);
                 gen_op_st_T0_A0(OT_WORD + s->mem_index);
                 break;
@@ -5679,29 +5713,29 @@ static target_ulong disas_insn(DisasContext *s, target_ulong pc_start)
                 if (s->cc_op != CC_OP_DYNAMIC)
                     gen_op_set_cc_op(s->cc_op);
                 gen_jmp_im(pc_start - s->cs_base);
-                gen_helper_fldt_ST0(cpu_A0);
+                gen_helper_fldt_ST0(cpu_env, cpu_A0);
                 break;
             case 0x1f: /* fstpt mem */
                 if (s->cc_op != CC_OP_DYNAMIC)
                     gen_op_set_cc_op(s->cc_op);
                 gen_jmp_im(pc_start - s->cs_base);
-                gen_helper_fstt_ST0(cpu_A0);
-                gen_helper_fpop();
+                gen_helper_fstt_ST0(cpu_env, cpu_A0);
+                gen_helper_fpop(cpu_env);
                 break;
             case 0x2c: /* frstor mem */
                 if (s->cc_op != CC_OP_DYNAMIC)
                     gen_op_set_cc_op(s->cc_op);
                 gen_jmp_im(pc_start - s->cs_base);
-                gen_helper_frstor(cpu_A0, tcg_const_i32(s->dflag));
+                gen_helper_frstor(cpu_env, cpu_A0, tcg_const_i32(s->dflag));
                 break;
             case 0x2e: /* fnsave mem */
                 if (s->cc_op != CC_OP_DYNAMIC)
                     gen_op_set_cc_op(s->cc_op);
                 gen_jmp_im(pc_start - s->cs_base);
-                gen_helper_fsave(cpu_A0, tcg_const_i32(s->dflag));
+                gen_helper_fsave(cpu_env, cpu_A0, tcg_const_i32(s->dflag));
                 break;
             case 0x2f: /* fnstsw mem */
-                gen_helper_fnstsw(cpu_tmp2_i32);
+                gen_helper_fnstsw(cpu_tmp2_i32, cpu_env);
                 tcg_gen_extu_i32_tl(cpu_T[0], cpu_tmp2_i32);
                 gen_op_st_T0_A0(OT_WORD + s->mem_index);
                 break;
@@ -5709,25 +5743,25 @@ static target_ulong disas_insn(DisasContext *s, target_ulong pc_start)
                 if (s->cc_op != CC_OP_DYNAMIC)
                     gen_op_set_cc_op(s->cc_op);
                 gen_jmp_im(pc_start - s->cs_base);
-                gen_helper_fbld_ST0(cpu_A0);
+                gen_helper_fbld_ST0(cpu_env, cpu_A0);
                 break;
             case 0x3e: /* fbstp */
                 if (s->cc_op != CC_OP_DYNAMIC)
                     gen_op_set_cc_op(s->cc_op);
                 gen_jmp_im(pc_start - s->cs_base);
-                gen_helper_fbst_ST0(cpu_A0);
-                gen_helper_fpop();
+                gen_helper_fbst_ST0(cpu_env, cpu_A0);
+                gen_helper_fpop(cpu_env);
                 break;
             case 0x3d: /* fildll */
                 tcg_gen_qemu_ld64(cpu_tmp1_i64, cpu_A0, 
                                   (s->mem_index >> 2) - 1);
-                gen_helper_fildll_ST0(cpu_tmp1_i64);
+                gen_helper_fildll_ST0(cpu_env, cpu_tmp1_i64);
                 break;
             case 0x3f: /* fistpll */
-                gen_helper_fistll_ST0(cpu_tmp1_i64);
+                gen_helper_fistll_ST0(cpu_tmp1_i64, cpu_env);
                 tcg_gen_qemu_st64(cpu_tmp1_i64, cpu_A0, 
                                   (s->mem_index >> 2) - 1);
-                gen_helper_fpop();
+                gen_helper_fpop(cpu_env);
                 break;
             default:
                 goto illegal_op;
@@ -5738,13 +5772,14 @@ static target_ulong disas_insn(DisasContext *s, target_ulong pc_start)
 
             switch(op) {
             case 0x08: /* fld sti */
-                gen_helper_fpush();
-                gen_helper_fmov_ST0_STN(tcg_const_i32((opreg + 1) & 7));
+                gen_helper_fpush(cpu_env);
+                gen_helper_fmov_ST0_STN(cpu_env,
+                                        tcg_const_i32((opreg + 1) & 7));
                 break;
             case 0x09: /* fxchg sti */
             case 0x29: /* fxchg4 sti, undocumented op */
             case 0x39: /* fxchg7 sti, undocumented op */
-                gen_helper_fxchg_ST0_STN(tcg_const_i32(opreg));
+                gen_helper_fxchg_ST0_STN(cpu_env, tcg_const_i32(opreg));
                 break;
             case 0x0a: /* grp d9/2 */
                 switch(rm) {
@@ -5753,7 +5788,7 @@ static target_ulong disas_insn(DisasContext *s, target_ulong pc_start)
                     if (s->cc_op != CC_OP_DYNAMIC)
                         gen_op_set_cc_op(s->cc_op);
                     gen_jmp_im(pc_start - s->cs_base);
-                    gen_helper_fwait();
+                    gen_helper_fwait(cpu_env);
                     break;
                 default:
                     goto illegal_op;
@@ -5762,17 +5797,17 @@ static target_ulong disas_insn(DisasContext *s, target_ulong pc_start)
             case 0x0c: /* grp d9/4 */
                 switch(rm) {
                 case 0: /* fchs */
-                    gen_helper_fchs_ST0();
+                    gen_helper_fchs_ST0(cpu_env);
                     break;
                 case 1: /* fabs */
-                    gen_helper_fabs_ST0();
+                    gen_helper_fabs_ST0(cpu_env);
                     break;
                 case 4: /* ftst */
-                    gen_helper_fldz_FT0();
-                    gen_helper_fcom_ST0_FT0();
+                    gen_helper_fldz_FT0(cpu_env);
+                    gen_helper_fcom_ST0_FT0(cpu_env);
                     break;
                 case 5: /* fxam */
-                    gen_helper_fxam_ST0();
+                    gen_helper_fxam_ST0(cpu_env);
                     break;
                 default:
                     goto illegal_op;
@@ -5782,32 +5817,32 @@ static target_ulong disas_insn(DisasContext *s, target_ulong pc_start)
                 {
                     switch(rm) {
                     case 0:
-                        gen_helper_fpush();
-                        gen_helper_fld1_ST0();
+                        gen_helper_fpush(cpu_env);
+                        gen_helper_fld1_ST0(cpu_env);
                         break;
                     case 1:
-                        gen_helper_fpush();
-                        gen_helper_fldl2t_ST0();
+                        gen_helper_fpush(cpu_env);
+                        gen_helper_fldl2t_ST0(cpu_env);
                         break;
                     case 2:
-                        gen_helper_fpush();
-                        gen_helper_fldl2e_ST0();
+                        gen_helper_fpush(cpu_env);
+                        gen_helper_fldl2e_ST0(cpu_env);
                         break;
                     case 3:
-                        gen_helper_fpush();
-                        gen_helper_fldpi_ST0();
+                        gen_helper_fpush(cpu_env);
+                        gen_helper_fldpi_ST0(cpu_env);
                         break;
                     case 4:
-                        gen_helper_fpush();
-                        gen_helper_fldlg2_ST0();
+                        gen_helper_fpush(cpu_env);
+                        gen_helper_fldlg2_ST0(cpu_env);
                         break;
                     case 5:
-                        gen_helper_fpush();
-                        gen_helper_fldln2_ST0();
+                        gen_helper_fpush(cpu_env);
+                        gen_helper_fldln2_ST0(cpu_env);
                         break;
                     case 6:
-                        gen_helper_fpush();
-                        gen_helper_fldz_ST0();
+                        gen_helper_fpush(cpu_env);
+                        gen_helper_fldz_ST0(cpu_env);
                         break;
                     default:
                         goto illegal_op;
@@ -5817,58 +5852,58 @@ static target_ulong disas_insn(DisasContext *s, target_ulong pc_start)
             case 0x0e: /* grp d9/6 */
                 switch(rm) {
                 case 0: /* f2xm1 */
-                    gen_helper_f2xm1();
+                    gen_helper_f2xm1(cpu_env);
                     break;
                 case 1: /* fyl2x */
-                    gen_helper_fyl2x();
+                    gen_helper_fyl2x(cpu_env);
                     break;
                 case 2: /* fptan */
-                    gen_helper_fptan();
+                    gen_helper_fptan(cpu_env);
                     break;
                 case 3: /* fpatan */
-                    gen_helper_fpatan();
+                    gen_helper_fpatan(cpu_env);
                     break;
                 case 4: /* fxtract */
-                    gen_helper_fxtract();
+                    gen_helper_fxtract(cpu_env);
                     break;
                 case 5: /* fprem1 */
-                    gen_helper_fprem1();
+                    gen_helper_fprem1(cpu_env);
                     break;
                 case 6: /* fdecstp */
-                    gen_helper_fdecstp();
+                    gen_helper_fdecstp(cpu_env);
                     break;
                 default:
                 case 7: /* fincstp */
-                    gen_helper_fincstp();
+                    gen_helper_fincstp(cpu_env);
                     break;
                 }
                 break;
             case 0x0f: /* grp d9/7 */
                 switch(rm) {
                 case 0: /* fprem */
-                    gen_helper_fprem();
+                    gen_helper_fprem(cpu_env);
                     break;
                 case 1: /* fyl2xp1 */
-                    gen_helper_fyl2xp1();
+                    gen_helper_fyl2xp1(cpu_env);
                     break;
                 case 2: /* fsqrt */
-                    gen_helper_fsqrt();
+                    gen_helper_fsqrt(cpu_env);
                     break;
                 case 3: /* fsincos */
-                    gen_helper_fsincos();
+                    gen_helper_fsincos(cpu_env);
                     break;
                 case 5: /* fscale */
-                    gen_helper_fscale();
+                    gen_helper_fscale(cpu_env);
                     break;
                 case 4: /* frndint */
-                    gen_helper_frndint();
+                    gen_helper_frndint(cpu_env);
                     break;
                 case 6: /* fsin */
-                    gen_helper_fsin();
+                    gen_helper_fsin(cpu_env);
                     break;
                 default:
                 case 7: /* fcos */
-                    gen_helper_fcos();
+                    gen_helper_fcos(cpu_env);
                     break;
                 }
                 break;
@@ -5882,32 +5917,32 @@ static target_ulong disas_insn(DisasContext *s, target_ulong pc_start)
                     if (op >= 0x20) {
                         gen_helper_fp_arith_STN_ST0(op1, opreg);
                         if (op >= 0x30)
-                            gen_helper_fpop();
+                            gen_helper_fpop(cpu_env);
                     } else {
-                        gen_helper_fmov_FT0_STN(tcg_const_i32(opreg));
+                        gen_helper_fmov_FT0_STN(cpu_env, tcg_const_i32(opreg));
                         gen_helper_fp_arith_ST0_FT0(op1);
                     }
                 }
                 break;
             case 0x02: /* fcom */
             case 0x22: /* fcom2, undocumented op */
-                gen_helper_fmov_FT0_STN(tcg_const_i32(opreg));
-                gen_helper_fcom_ST0_FT0();
+                gen_helper_fmov_FT0_STN(cpu_env, tcg_const_i32(opreg));
+                gen_helper_fcom_ST0_FT0(cpu_env);
                 break;
             case 0x03: /* fcomp */
             case 0x23: /* fcomp3, undocumented op */
             case 0x32: /* fcomp5, undocumented op */
-                gen_helper_fmov_FT0_STN(tcg_const_i32(opreg));
-                gen_helper_fcom_ST0_FT0();
-                gen_helper_fpop();
+                gen_helper_fmov_FT0_STN(cpu_env, tcg_const_i32(opreg));
+                gen_helper_fcom_ST0_FT0(cpu_env);
+                gen_helper_fpop(cpu_env);
                 break;
             case 0x15: /* da/5 */
                 switch(rm) {
                 case 1: /* fucompp */
-                    gen_helper_fmov_FT0_STN(tcg_const_i32(1));
-                    gen_helper_fucom_ST0_FT0();
-                    gen_helper_fpop();
-                    gen_helper_fpop();
+                    gen_helper_fmov_FT0_STN(cpu_env, tcg_const_i32(1));
+                    gen_helper_fucom_ST0_FT0(cpu_env);
+                    gen_helper_fpop(cpu_env);
+                    gen_helper_fpop(cpu_env);
                     break;
                 default:
                     goto illegal_op;
@@ -5920,10 +5955,10 @@ static target_ulong disas_insn(DisasContext *s, target_ulong pc_start)
                 case 1: /* fdisi (287 only, just do nop here) */
                     break;
                 case 2: /* fclex */
-                    gen_helper_fclex();
+                    gen_helper_fclex(cpu_env);
                     break;
                 case 3: /* fninit */
-                    gen_helper_fninit();
+                    gen_helper_fninit(cpu_env);
                     break;
                 case 4: /* fsetpm (287 only, just do nop here) */
                     break;
@@ -5934,59 +5969,59 @@ static target_ulong disas_insn(DisasContext *s, target_ulong pc_start)
             case 0x1d: /* fucomi */
                 if (s->cc_op != CC_OP_DYNAMIC)
                     gen_op_set_cc_op(s->cc_op);
-                gen_helper_fmov_FT0_STN(tcg_const_i32(opreg));
-                gen_helper_fucomi_ST0_FT0();
+                gen_helper_fmov_FT0_STN(cpu_env, tcg_const_i32(opreg));
+                gen_helper_fucomi_ST0_FT0(cpu_env);
                 s->cc_op = CC_OP_EFLAGS;
                 break;
             case 0x1e: /* fcomi */
                 if (s->cc_op != CC_OP_DYNAMIC)
                     gen_op_set_cc_op(s->cc_op);
-                gen_helper_fmov_FT0_STN(tcg_const_i32(opreg));
-                gen_helper_fcomi_ST0_FT0();
+                gen_helper_fmov_FT0_STN(cpu_env, tcg_const_i32(opreg));
+                gen_helper_fcomi_ST0_FT0(cpu_env);
                 s->cc_op = CC_OP_EFLAGS;
                 break;
             case 0x28: /* ffree sti */
-                gen_helper_ffree_STN(tcg_const_i32(opreg));
+                gen_helper_ffree_STN(cpu_env, tcg_const_i32(opreg));
                 break;
             case 0x2a: /* fst sti */
-                gen_helper_fmov_STN_ST0(tcg_const_i32(opreg));
+                gen_helper_fmov_STN_ST0(cpu_env, tcg_const_i32(opreg));
                 break;
             case 0x2b: /* fstp sti */
             case 0x0b: /* fstp1 sti, undocumented op */
             case 0x3a: /* fstp8 sti, undocumented op */
             case 0x3b: /* fstp9 sti, undocumented op */
-                gen_helper_fmov_STN_ST0(tcg_const_i32(opreg));
-                gen_helper_fpop();
+                gen_helper_fmov_STN_ST0(cpu_env, tcg_const_i32(opreg));
+                gen_helper_fpop(cpu_env);
                 break;
             case 0x2c: /* fucom st(i) */
-                gen_helper_fmov_FT0_STN(tcg_const_i32(opreg));
-                gen_helper_fucom_ST0_FT0();
+                gen_helper_fmov_FT0_STN(cpu_env, tcg_const_i32(opreg));
+                gen_helper_fucom_ST0_FT0(cpu_env);
                 break;
             case 0x2d: /* fucomp st(i) */
-                gen_helper_fmov_FT0_STN(tcg_const_i32(opreg));
-                gen_helper_fucom_ST0_FT0();
-                gen_helper_fpop();
+                gen_helper_fmov_FT0_STN(cpu_env, tcg_const_i32(opreg));
+                gen_helper_fucom_ST0_FT0(cpu_env);
+                gen_helper_fpop(cpu_env);
                 break;
             case 0x33: /* de/3 */
                 switch(rm) {
                 case 1: /* fcompp */
-                    gen_helper_fmov_FT0_STN(tcg_const_i32(1));
-                    gen_helper_fcom_ST0_FT0();
-                    gen_helper_fpop();
-                    gen_helper_fpop();
+                    gen_helper_fmov_FT0_STN(cpu_env, tcg_const_i32(1));
+                    gen_helper_fcom_ST0_FT0(cpu_env);
+                    gen_helper_fpop(cpu_env);
+                    gen_helper_fpop(cpu_env);
                     break;
                 default:
                     goto illegal_op;
                 }
                 break;
             case 0x38: /* ffreep sti, undocumented op */
-                gen_helper_ffree_STN(tcg_const_i32(opreg));
-                gen_helper_fpop();
+                gen_helper_ffree_STN(cpu_env, tcg_const_i32(opreg));
+                gen_helper_fpop(cpu_env);
                 break;
             case 0x3c: /* df/4 */
                 switch(rm) {
                 case 0:
-                    gen_helper_fnstsw(cpu_tmp2_i32);
+                    gen_helper_fnstsw(cpu_tmp2_i32, cpu_env);
                     tcg_gen_extu_i32_tl(cpu_T[0], cpu_tmp2_i32);
                     gen_op_mov_reg_T0(OT_WORD, R_EAX);
                     break;
@@ -5997,17 +6032,17 @@ static target_ulong disas_insn(DisasContext *s, target_ulong pc_start)
             case 0x3d: /* fucomip */
                 if (s->cc_op != CC_OP_DYNAMIC)
                     gen_op_set_cc_op(s->cc_op);
-                gen_helper_fmov_FT0_STN(tcg_const_i32(opreg));
-                gen_helper_fucomi_ST0_FT0();
-                gen_helper_fpop();
+                gen_helper_fmov_FT0_STN(cpu_env, tcg_const_i32(opreg));
+                gen_helper_fucomi_ST0_FT0(cpu_env);
+                gen_helper_fpop(cpu_env);
                 s->cc_op = CC_OP_EFLAGS;
                 break;
             case 0x3e: /* fcomip */
                 if (s->cc_op != CC_OP_DYNAMIC)
                     gen_op_set_cc_op(s->cc_op);
-                gen_helper_fmov_FT0_STN(tcg_const_i32(opreg));
-                gen_helper_fcomi_ST0_FT0();
-                gen_helper_fpop();
+                gen_helper_fmov_FT0_STN(cpu_env, tcg_const_i32(opreg));
+                gen_helper_fcomi_ST0_FT0(cpu_env);
+                gen_helper_fpop(cpu_env);
                 s->cc_op = CC_OP_EFLAGS;
                 break;
             case 0x10 ... 0x13: /* fcmovxx */
@@ -6023,7 +6058,7 @@ static target_ulong disas_insn(DisasContext *s, target_ulong pc_start)
                     op1 = fcmov_cc[op & 3] | (((op >> 3) & 1) ^ 1);
                     l1 = gen_new_label();
                     gen_jcc1(s, s->cc_op, op1, l1);
-                    gen_helper_fmov_ST0_STN(tcg_const_i32(opreg));
+                    gen_helper_fmov_ST0_STN(cpu_env, tcg_const_i32(opreg));
                     gen_set_label(l1);
                 }
                 break;
@@ -6742,7 +6777,7 @@ static target_ulong disas_insn(DisasContext *s, target_ulong pc_start)
             if (s->cc_op != CC_OP_DYNAMIC)
                 gen_op_set_cc_op(s->cc_op);
             gen_jmp_im(pc_start - s->cs_base);
-            gen_helper_fwait();
+            gen_helper_fwait(cpu_env);
         }
         break;
     case 0xcc: /* int3 */
@@ -7579,7 +7614,7 @@ static target_ulong disas_insn(DisasContext *s, target_ulong pc_start)
             if (s->cc_op != CC_OP_DYNAMIC)
                 gen_op_set_cc_op(s->cc_op);
             gen_jmp_im(pc_start - s->cs_base);
-            gen_helper_fxsave(cpu_A0, tcg_const_i32((s->dflag == 2)));
+            gen_helper_fxsave(cpu_env, cpu_A0, tcg_const_i32((s->dflag == 2)));
             break;
         case 1: /* fxrstor */
             if (mod == 3 || !(s->cpuid_features & CPUID_FXSR) ||
@@ -7593,7 +7628,8 @@ static target_ulong disas_insn(DisasContext *s, target_ulong pc_start)
             if (s->cc_op != CC_OP_DYNAMIC)
                 gen_op_set_cc_op(s->cc_op);
             gen_jmp_im(pc_start - s->cs_base);
-            gen_helper_fxrstor(cpu_A0, tcg_const_i32((s->dflag == 2)));
+            gen_helper_fxrstor(cpu_env, cpu_A0,
+                               tcg_const_i32((s->dflag == 2)));
             break;
         case 2: /* ldmxcsr */
         case 3: /* stmxcsr */
@@ -7608,7 +7644,7 @@ static target_ulong disas_insn(DisasContext *s, target_ulong pc_start)
             if (op == 2) {
                 gen_op_ld_T0_A0(OT_LONG + s->mem_index);
                 tcg_gen_trunc_tl_i32(cpu_tmp2_i32, cpu_T[0]);
-                gen_helper_ldmxcsr(cpu_tmp2_i32);
+                gen_helper_ldmxcsr(cpu_env, cpu_tmp2_i32);
             } else {
                 tcg_gen_ld32u_tl(cpu_T[0], cpu_env, offsetof(CPUX86State, mxcsr));
                 gen_op_st_T0_A0(OT_LONG + s->mem_index);
@@ -7671,7 +7707,7 @@ static target_ulong disas_insn(DisasContext *s, target_ulong pc_start)
             ot = OT_QUAD;
 
         gen_ldst_modrm(s, modrm, ot, OR_TMP0, 0);
-        gen_helper_popcnt(cpu_T[0], cpu_T[0], tcg_const_i32(ot));
+        gen_helper_popcnt(cpu_T[0], cpu_env, cpu_T[0], tcg_const_i32(ot));
         gen_op_mov_reg_T0(ot, reg);
 
         s->cc_op = CC_OP_EFLAGS;
commit 28a9a00e95f935542512e3e682c073617c741bef
Merge: 2f00463... 01afdad...
Author: Anthony Liguori <aliguori at us.ibm.com>
Date:   Tue Aug 14 13:46:35 2012 -0500

    Merge remote-tracking branch 'kraxel/seabios-5a02306' into staging
    
    * kraxel/seabios-5a02306:
      update seabios to latest master

commit 2f00463fa67d42864a747fc5b85f1db8bf5556ce
Author: Stefan Hajnoczi <stefanha at linux.vnet.ibm.com>
Date:   Tue Aug 14 10:10:09 2012 +0100

    MAINTAINERS: Update email address for Stefan Hajnoczi
    
    Switch to my personal email address.
    
    Signed-off-by: Stefan Hajnoczi <stefanha at linux.vnet.ibm.com>
    Signed-off-by: Anthony Liguori <aliguori at us.ibm.com>

diff --git a/MAINTAINERS b/MAINTAINERS
index 708ad54..6d864c1 100644
--- a/MAINTAINERS
+++ b/MAINTAINERS
@@ -568,7 +568,7 @@ F: monitor.c
 
 Network device layer
 M: Anthony Liguori <aliguori at us.ibm.com>
-M: Stefan Hajnoczi <stefanha at linux.vnet.ibm.com>
+M: Stefan Hajnoczi <stefanha at gmail.com>
 S: Maintained
 F: net/
 T: git git://github.com/stefanha/qemu.git net
@@ -588,7 +588,7 @@ F: slirp/
 T: git git://git.kiszka.org/qemu.git queues/slirp
 
 Tracing
-M: Stefan Hajnoczi <stefanha at linux.vnet.ibm.com>
+M: Stefan Hajnoczi <stefanha at gmail.com>
 S: Maintained
 F: trace/
 F: scripts/tracetool.py
commit 4552e41025af4694c55854448c3ae4d95e72c7f6
Author: Stefan Weil <sw at weilnetz.de>
Date:   Mon Aug 13 21:51:16 2012 +0200

    trace/simple: Replace asprintf by g_strdup_printf
    
    asprintf is not available for all hosts. g_strdup_printf is
    more portable and simplifies the code because if does not
    need error handling.
    
    The static variable does not need an explicit assignment to be NULL.
    
    Cc: Stefan Hajnoczi <stefanha at linux.vnet.ibm.com>
    Signed-off-by: Stefan Weil <sw at weilnetz.de>
    Signed-off-by: Stefan Hajnoczi <stefanha at linux.vnet.ibm.com>

diff --git a/trace/simple.c b/trace/simple.c
index 8e175ec..d83681b 100644
--- a/trace/simple.c
+++ b/trace/simple.c
@@ -55,7 +55,7 @@ static unsigned int trace_idx;
 static unsigned int writeout_idx;
 static uint64_t dropped_events;
 static FILE *trace_fp;
-static char *trace_file_name = NULL;
+static char *trace_file_name;
 
 /* * Trace buffer entry */
 typedef struct {
@@ -329,18 +329,12 @@ bool st_set_trace_file(const char *file)
 {
     st_set_trace_file_enabled(false);
 
-    free(trace_file_name);
+    g_free(trace_file_name);
 
     if (!file) {
-        if (asprintf(&trace_file_name, CONFIG_TRACE_FILE, getpid()) < 0) {
-            trace_file_name = NULL;
-            return false;
-        }
+        trace_file_name = g_strdup_printf(CONFIG_TRACE_FILE, getpid());
     } else {
-        if (asprintf(&trace_file_name, "%s", file) < 0) {
-            trace_file_name = NULL;
-            return false;
-        }
+        trace_file_name = g_strdup_printf("%s", file);
     }
 
     st_set_trace_file_enabled(true);
commit 964d0a7b2bab935d48d3b2c4d6ab9b0efc74ce8b
Author: Stefan Weil <sw at weilnetz.de>
Date:   Mon Aug 13 21:50:56 2012 +0200

    trace/simple: Fix compiler warning for 32 bit hosts
    
    gcc complains when a 32 bit pointer is casted to a 64 bit integer.
    
    Cc: Stefan Hajnoczi <stefanha at linux.vnet.ibm.com>
    Signed-off-by: Stefan Weil <sw at weilnetz.de>
    Signed-off-by: Stefan Hajnoczi <stefanha at linux.vnet.ibm.com>

diff --git a/scripts/tracetool/backend/simple.py b/scripts/tracetool/backend/simple.py
index c7e47d6..e4b4a7f 100644
--- a/scripts/tracetool/backend/simple.py
+++ b/scripts/tracetool/backend/simple.py
@@ -79,7 +79,7 @@ def c(events):
                        )
                 # pointer var (not string)
                 elif type_.endswith('*'):
-                    out('    trace_record_write_u64(&rec, (uint64_t)(uint64_t *)%(name)s);',
+                    out('    trace_record_write_u64(&rec, (uintptr_t)(uint64_t *)%(name)s);',
                         name = name,
                        )
                 # primitive data type
commit db8894f2090629a2e12b1e7324c4c5c53367e048
Author: Harsh Prateek Bora <harsh at linux.vnet.ibm.com>
Date:   Fri Jul 20 18:52:15 2012 +0530

    trace: avoid pointer aliasing in trace_record_finish()
    
    Declaring a TraceRecord on the stack works fine.  No need for a
    uint8_t array and pointer aliasing.
    
    Signed-off-by: Harsh Prateek Bora <harsh at linux.vnet.ibm.com>
    Signed-off-by: Stefan Hajnoczi <stefanha at linux.vnet.ibm.com>

diff --git a/trace/simple.c b/trace/simple.c
index 4fed07f..8e175ec 100644
--- a/trace/simple.c
+++ b/trace/simple.c
@@ -269,12 +269,11 @@ static unsigned int write_to_buffer(unsigned int idx, void *dataptr, size_t size
 
 void trace_record_finish(TraceBufferRecord *rec)
 {
-    uint8_t temp_rec[sizeof(TraceRecord)];
-    TraceRecord *record = (TraceRecord *) temp_rec;
-    read_from_buffer(rec->tbuf_idx, temp_rec, sizeof(TraceRecord));
+    TraceRecord record;
+    read_from_buffer(rec->tbuf_idx, &record, sizeof(TraceRecord));
     smp_wmb(); /* write barrier before marking as valid */
-    record->event |= TRACE_RECORD_VALID;
-    write_to_buffer(rec->tbuf_idx, temp_rec, sizeof(TraceRecord));
+    record.event |= TRACE_RECORD_VALID;
+    write_to_buffer(rec->tbuf_idx, &record, sizeof(TraceRecord));
 
     if ((trace_idx - writeout_idx) > TRACE_BUF_FLUSH_THRESHOLD) {
         flush_trace_file(false);
commit fd82f015a1cc2df5972f06b75b350f65da68f9cf
Author: Harsh Prateek Bora <harsh at linux.vnet.ibm.com>
Date:   Fri Jul 20 18:52:14 2012 +0530

    trace: drop unused TraceBufferRecord->next_tbuf_idx field
    
    Signed-off-by: Harsh Prateek Bora <harsh at linux.vnet.ibm.com>
    Signed-off-by: Stefan Hajnoczi <stefanha at linux.vnet.ibm.com>

diff --git a/trace/simple.c b/trace/simple.c
index a0e0f05..4fed07f 100644
--- a/trace/simple.c
+++ b/trace/simple.c
@@ -231,8 +231,6 @@ int trace_record_start(TraceBufferRecord *rec, TraceEventID event, size_t datasi
     }
 
     idx = old_idx % TRACE_BUF_LEN;
-    /*  To check later if threshold crossed */
-    rec->next_tbuf_idx = new_idx % TRACE_BUF_LEN;
 
     rec_off = idx;
     rec_off = write_to_buffer(rec_off, &event, sizeof(event));
diff --git a/trace/simple.h b/trace/simple.h
index 7e521c1..2ab96a8 100644
--- a/trace/simple.h
+++ b/trace/simple.h
@@ -29,7 +29,6 @@ void st_flush_trace_buffer(void);
 
 typedef struct {
     unsigned int tbuf_idx;
-    unsigned int next_tbuf_idx;
     unsigned int rec_off;
 } TraceBufferRecord;
 
commit 83d35d3e9909614e952021a92dbb39421977affc
Author: Harsh Prateek Bora <harsh at linux.vnet.ibm.com>
Date:   Fri Jul 20 18:52:13 2012 +0530

    trace: remove unnecessary write_to_buffer() typecasting
    
    The buffer argument is void* so it is not necessary to cast.
    
    Signed-off-by: Harsh Prateek Bora <harsh at linux.vnet.ibm.com>
    Signed-off-by: Stefan Hajnoczi <stefanha at linux.vnet.ibm.com>

diff --git a/trace/simple.c b/trace/simple.c
index 5d92939..a0e0f05 100644
--- a/trace/simple.c
+++ b/trace/simple.c
@@ -235,9 +235,9 @@ int trace_record_start(TraceBufferRecord *rec, TraceEventID event, size_t datasi
     rec->next_tbuf_idx = new_idx % TRACE_BUF_LEN;
 
     rec_off = idx;
-    rec_off = write_to_buffer(rec_off, (uint8_t*)&event, sizeof(event));
-    rec_off = write_to_buffer(rec_off, (uint8_t*)&timestamp_ns, sizeof(timestamp_ns));
-    rec_off = write_to_buffer(rec_off, (uint8_t*)&rec_len, sizeof(rec_len));
+    rec_off = write_to_buffer(rec_off, &event, sizeof(event));
+    rec_off = write_to_buffer(rec_off, &timestamp_ns, sizeof(timestamp_ns));
+    rec_off = write_to_buffer(rec_off, &rec_len, sizeof(rec_len));
 
     rec->tbuf_idx = idx;
     rec->rec_off  = (idx + sizeof(TraceRecord)) % TRACE_BUF_LEN;
commit 8ae601e8fedbbc9b1a1514796bb608e942660bd9
Author: Harsh Prateek Bora <harsh at linux.vnet.ibm.com>
Date:   Fri Jul 20 18:52:12 2012 +0530

    trace: rename TraceRecordHeader to TraceLogHeader
    
    The TraceRecordHeader is really the header for the entire trace log
    file.  It's not per-record header so make this obvious by renaming it.
    
    Signed-off-by: Harsh Prateek Bora <harsh at linux.vnet.ibm.com>
    Signed-off-by: Stefan Hajnoczi <stefanha at linux.vnet.ibm.com>

diff --git a/trace/simple.c b/trace/simple.c
index b700ea3..5d92939 100644
--- a/trace/simple.c
+++ b/trace/simple.c
@@ -70,7 +70,7 @@ typedef struct {
     uint64_t header_event_id; /* HEADER_EVENT_ID */
     uint64_t header_magic;    /* HEADER_MAGIC    */
     uint64_t header_version;  /* HEADER_VERSION  */
-} TraceRecordHeader;
+} TraceLogHeader;
 
 
 static void read_from_buffer(unsigned int idx, void *dataptr, size_t size);
@@ -295,7 +295,7 @@ void st_set_trace_file_enabled(bool enable)
     flush_trace_file(true);
 
     if (enable) {
-        static const TraceRecordHeader header = {
+        static const TraceLogHeader header = {
             .header_event_id = HEADER_EVENT_ID,
             .header_magic = HEADER_MAGIC,
             /* Older log readers will check for version at next location */
commit 633decd71119a4293e5e53e6059026c517a8bef0
Merge: ac839cc... 70b7660...
Author: Anthony Liguori <aliguori at us.ibm.com>
Date:   Mon Aug 13 16:12:35 2012 -0500

    Merge remote-tracking branch 'qmp/queue/qmp' into staging
    
    * qmp/queue/qmp: (48 commits)
      target-ppc: add implementation of query-cpu-definitions (v2)
      target-i386: add implementation of query-cpu-definitions (v2)
      qapi: add query-cpu-definitions command (v2)
      compiler: add macro for GCC weak symbols
      qapi: add query-machines command
      qapi: mark QOM commands stable
      qmp: introduce device-list-properties command
      qmp: add SUSPEND_DISK event
      qmp: qmp-events.txt: add missing doc for the SUSPEND event
      qmp: qmp-events.txt: put events in alphabetical order
      qmp: emit the WAKEUP event when the guest is put to run
      qmp: don't emit the RESET event on wakeup from S3
      scripts: qapi-commands.py: qmp-commands.h: include qdict.h
      docs: writing-qmp-commands.txt: update error section
      error, qerror: drop QDict member
      qerror: drop qerror_table and qerror_format()
      error, qerror: pass desc string to error calls
      error: drop error_get_qobject()/error_set_qobject()
      qemu-ga: switch to the new error format on the wire
      qmp: switch to the new error format on the wire
      ...

commit ac839ccd8c30fe5706cc43f00e056049d6e55377
Merge: 6a1f9d0... dd051c7...
Author: Anthony Liguori <aliguori at us.ibm.com>
Date:   Mon Aug 13 16:02:11 2012 -0500

    Merge remote-tracking branch 'quintela/migration-next-20120808' into staging
    
    * quintela/migration-next-20120808:
      Restart optimization on stage3 update version
      Add XBZRLE statistics
      Add migration accounting for normal and duplicate pages
      Change total_time to total-time in MigrationStats
      Add migrate_set_cache_size command
      Add XBZRLE to ram_save_block and ram_save_live
      Add xbzrle_encode_buffer and xbzrle_decode_buffer functions
      Add uleb encoding/decoding functions
      Add cache handling functions
      Add XBZRLE documentation
      Add migrate-set-capabilities
      Add migration capabilities

commit 6a1f9d0c1fbf186d3d68cb2af43d047637c93072
Merge: d517872... 58f9b98...
Author: Anthony Liguori <aliguori at us.ibm.com>
Date:   Mon Aug 13 15:59:11 2012 -0500

    Merge remote-tracking branch 'pmaydell/arm-devs.next' into staging
    
    * pmaydell/arm-devs.next:
      arm: Move some ARM devices into libhw
      ssd0323: abort() instead of exit(1) on error.
      hw/sd.c: make sd_wp_addr() return bool
      hw/sd.c: make sd_dataready() return bool
      hw/sd.c: convert binary variables to bool
      hw/sd.c: introduce wrapper for conversion address to wp group
      hw/sd.c: make sd_wp_addr() accept 64 bit address argument
      hw/sd.c: convert wp_groups in SDState to bitfield
      armv7m: Guard against no -kernel argument
      hw/armv7m_nvic: Fix incorrect default for num-irqs property

commit 70b7660a4ed0ca3891ee51bda78e10b4c36cd358
Author: Anthony Liguori <aliguori at us.ibm.com>
Date:   Fri Aug 10 11:04:15 2012 -0500

    target-ppc: add implementation of query-cpu-definitions (v2)
    
    Signed-off-by: Anthony Liguori <aliguori at us.ibm.com>
    Signed-off-by: Luiz Capitulino <lcapitulino at redhat.com>

diff --git a/target-ppc/translate_init.c b/target-ppc/translate_init.c
index 5742229..6fe4168 100644
--- a/target-ppc/translate_init.c
+++ b/target-ppc/translate_init.c
@@ -27,6 +27,7 @@
 #include "gdbstub.h"
 #include <kvm.h>
 #include "kvm_ppc.h"
+#include "qmp-commands.h"
 
 //#define PPC_DUMP_CPU
 //#define PPC_DEBUG_SPR
@@ -10345,6 +10346,31 @@ void ppc_cpu_list (FILE *f, fprintf_function cpu_fprintf)
     }
 }
 
+CpuDefinitionInfoList *qmp_query_cpu_definitions(Error **errp)
+{
+    CpuDefinitionInfoList *cpu_list = NULL;
+    int i;
+
+    for (i = 0; i < ARRAY_SIZE(ppc_defs); i++) {
+        CpuDefinitionInfoList *entry;
+        CpuDefinitionInfo *info;
+
+        if (!ppc_cpu_usable(&ppc_defs[i])) {
+            continue;
+        }
+
+        info = g_malloc0(sizeof(*info));
+        info->name = g_strdup(ppc_defs[i].name);
+
+        entry = g_malloc0(sizeof(*entry));
+        entry->value = info;
+        entry->next = cpu_list;
+        cpu_list = entry;
+    }
+
+    return cpu_list;
+}
+
 /* CPUClass::reset() */
 static void ppc_cpu_reset(CPUState *s)
 {
commit e3966126d077ef60997f651d8e42b71c623b44a6
Author: Anthony Liguori <aliguori at us.ibm.com>
Date:   Fri Aug 10 11:04:14 2012 -0500

    target-i386: add implementation of query-cpu-definitions (v2)
    
    Signed-off-by: Anthony Liguori <aliguori at us.ibm.com>
    Signed-off-by: Luiz Capitulino <lcapitulino at redhat.com>

diff --git a/target-i386/cpu.c b/target-i386/cpu.c
index 880cfea..6d5d0d6 100644
--- a/target-i386/cpu.c
+++ b/target-i386/cpu.c
@@ -28,6 +28,7 @@
 #include "qemu-config.h"
 
 #include "qapi/qapi-visit-core.h"
+#include "qmp-commands.h"
 
 #include "hyperv.h"
 
@@ -1125,6 +1126,27 @@ void x86_cpu_list(FILE *f, fprintf_function cpu_fprintf, const char *optarg)
     }
 }
 
+CpuDefinitionInfoList *qmp_query_cpu_definitions(Error **errp)
+{
+    CpuDefinitionInfoList *cpu_list = NULL;
+    x86_def_t *def;
+
+    for (def = x86_defs; def; def = def->next) {
+        CpuDefinitionInfoList *entry;
+        CpuDefinitionInfo *info;
+
+        info = g_malloc0(sizeof(*info));
+        info->name = g_strdup(def->name);
+
+        entry = g_malloc0(sizeof(*entry));
+        entry->value = info;
+        entry->next = cpu_list;
+        cpu_list = entry;
+    }
+
+    return cpu_list;
+}
+
 int cpu_x86_register(X86CPU *cpu, const char *cpu_model)
 {
     CPUX86State *env = &cpu->env;
commit e4e31c6324af480a22bf4150266b278368eaa336
Author: Anthony Liguori <aliguori at us.ibm.com>
Date:   Fri Aug 10 11:04:13 2012 -0500

    qapi: add query-cpu-definitions command (v2)
    
    This command attempts to map to the behavior of -cpu ?.  Unfortunately, the
    output of this command differs wildly across targets.
    
    To accommodate this, we use a weak symbol to implement a default version of the
    command that fails with a QERR_NOT_SUPPORTED error code.  Targets can then
    override and implement this command if it makes sense for them.
    
    Signed-off-by: Anthony Liguori <aliguori at us.ibm.com>
    Signed-off-by: Luiz Capitulino <lcapitulino at redhat.com>

diff --git a/qapi-schema.json b/qapi-schema.json
index e51753c..9347b6a 100644
--- a/qapi-schema.json
+++ b/qapi-schema.json
@@ -2222,3 +2222,26 @@
 # Since: 1.2.0
 ##
 { 'command': 'query-machines', 'returns': ['MachineInfo'] }
+
+##
+# @CpuDefinitionInfo:
+#
+# Virtual CPU definition.
+#
+# @name: the name of the CPU definition
+#
+# Since: 1.2.0
+##
+{ 'type': 'CpuDefinitionInfo',
+  'data': { 'name': 'str' } }
+
+##
+# @query-cpu-definitions:
+#
+# Return a list of supported virtual CPU definitions
+#
+# Returns: a list of CpuDefInfo
+#
+# Since: 1.2.0
+##
+{ 'command': 'query-cpu-definitions', 'returns': ['CpuDefinitionInfo'] }
diff --git a/qmp-commands.hx b/qmp-commands.hx
index fd87775..521da10 100644
--- a/qmp-commands.hx
+++ b/qmp-commands.hx
@@ -2230,3 +2230,9 @@ EQMP
         .mhandler.cmd_new = qmp_marshal_input_query_machines,
     },
 
+    {
+        .name       = "query-cpu-definitions",
+        .args_type  = "",
+        .mhandler.cmd_new = qmp_marshal_input_query_cpu_definitions,
+    },
+
diff --git a/qmp.c b/qmp.c
index 254a32f..6c1e4e8 100644
--- a/qmp.c
+++ b/qmp.c
@@ -467,3 +467,9 @@ DevicePropertyInfoList *qmp_device_list_properties(const char *typename,
 
     return prop_list;
 }
+
+CpuDefinitionInfoList GCC_WEAK *qmp_query_cpu_definitions(Error **errp)
+{
+    error_set(errp, QERR_NOT_SUPPORTED);
+    return NULL;
+}
commit 6ee373a0032b8fa6b630c6df9cd6618a7a02902b
Author: Anthony Liguori <aliguori at us.ibm.com>
Date:   Fri Aug 10 11:04:12 2012 -0500

    compiler: add macro for GCC weak symbols
    
    This lets us provide a default implementation of a symbol which targets can
    override.
    
    Signed-off-by: Anthony Liguori <aliguori at us.ibm.com>
    Signed-off-by: Luiz Capitulino <lcapitulino at redhat.com>

diff --git a/compiler.h b/compiler.h
index 736e770..f76921e 100644
--- a/compiler.h
+++ b/compiler.h
@@ -45,6 +45,7 @@
 #  define GCC_ATTR __attribute__((__unused__, format(gnu_printf, 1, 2)))
 #  define GCC_FMT_ATTR(n, m) __attribute__((format(gnu_printf, n, m)))
 # endif
+#define GCC_WEAK __attribute__((weak))
 #else
 #define GCC_ATTR /**/
 #define GCC_FMT_ATTR(n, m)
commit 01d3c80d6876c7de6b07bee92b1b2440b48e60c9
Author: Anthony Liguori <aliguori at us.ibm.com>
Date:   Fri Aug 10 11:04:11 2012 -0500

    qapi: add query-machines command
    
    This provides the same output as -M ? but in a structured way.
    
    Signed-off-by: Anthony Liguori <aliguori at us.ibm.com>
    Signed-off-by: Luiz Capitulino <lcapitulino at redhat.com>

diff --git a/qapi-schema.json b/qapi-schema.json
index 1731a92..e51753c 100644
--- a/qapi-schema.json
+++ b/qapi-schema.json
@@ -2194,3 +2194,31 @@
 # Since: 0.14.0
 ##
 { 'command': 'closefd', 'data': {'fdname': 'str'} }
+
+##
+# @MachineInfo:
+#
+# Information describing a machine.
+#
+# @name: the name of the machine
+#
+# @alias: #optional an alias for the machine name
+#
+# @default: #optional whether the machine is default
+#
+# Since: 1.2.0
+##
+{ 'type': 'MachineInfo',
+  'data': { 'name': 'str', '*alias': 'str',
+            '*is-default': 'bool' } }
+
+##
+# @query-machines:
+#
+# Return a list of supported machines
+#
+# Returns: a list of MachineInfo
+#
+# Since: 1.2.0
+##
+{ 'command': 'query-machines', 'returns': ['MachineInfo'] }
diff --git a/qmp-commands.hx b/qmp-commands.hx
index e9e0410..fd87775 100644
--- a/qmp-commands.hx
+++ b/qmp-commands.hx
@@ -2224,3 +2224,9 @@ EQMP
         .mhandler.cmd_new = qmp_marshal_input_device_list_properties,
     },
 
+    {
+        .name       = "query-machines",
+        .args_type  = "",
+        .mhandler.cmd_new = qmp_marshal_input_query_machines,
+    },
+
diff --git a/vl.c b/vl.c
index 97ab39f..d01256a 100644
--- a/vl.c
+++ b/vl.c
@@ -1213,6 +1213,37 @@ QEMUMachine *find_default_machine(void)
     return NULL;
 }
 
+MachineInfoList *qmp_query_machines(Error **errp)
+{
+    MachineInfoList *mach_list = NULL;
+    QEMUMachine *m;
+
+    for (m = first_machine; m; m = m->next) {
+        MachineInfoList *entry;
+        MachineInfo *info;
+
+        info = g_malloc0(sizeof(*info));
+        if (m->is_default) {
+            info->has_is_default = true;
+            info->is_default = true;
+        }
+
+        if (m->alias) {
+            info->has_alias = true;
+            info->alias = g_strdup(m->alias);
+        }
+
+        info->name = g_strdup(m->name);
+
+        entry = g_malloc0(sizeof(*entry));
+        entry->value = info;
+        entry->next = mach_list;
+        mach_list = entry;
+    }
+
+    return mach_list;
+}
+
 /***********************************************************/
 /* main execution loop */
 
commit 5192082097549c5b3aa7c913c6853d97a68172cb
Author: Anthony Liguori <aliguori at us.ibm.com>
Date:   Fri Aug 10 11:04:10 2012 -0500

    qapi: mark QOM commands stable
    
    We've had a cycle to tweak.  It is time to commit to supporting them.
    
    Signed-off-by: Anthony Liguori <aliguori at us.ibm.com>
    Signed-off-by: Luiz Capitulino <lcapitulino at redhat.com>

diff --git a/qapi-schema.json b/qapi-schema.json
index 927fdea..1731a92 100644
--- a/qapi-schema.json
+++ b/qapi-schema.json
@@ -1377,9 +1377,7 @@
 #        4) A link type in the form 'link<subtype>' where subtype is a qdev
 #           device type name.  Link properties form the device model graph.
 #
-# Since: 1.1
-#
-# Notes: This type is experimental.  Its syntax may change in future releases.
+# Since: 1.2
 ##
 { 'type': 'ObjectPropertyInfo',
   'data': { 'name': 'str', 'type': 'str' } }
@@ -1396,10 +1394,7 @@
 # Returns: a list of @ObjectPropertyInfo that describe the properties of the
 #          object.
 #
-# Since: 1.1
-#
-# Notes: This command is experimental.  It's syntax may change in future
-#        releases.
+# Since: 1.2
 ##
 { 'command': 'qom-list',
   'data': { 'path': 'str' },
@@ -1435,9 +1430,7 @@
 #          returns as #str pathnames.  All integer property types (u8, u16, etc)
 #          are returned as #int.
 #
-# Since: 1.1
-#
-# Notes: This command is experimental and may change syntax in future releases.
+# Since: 1.2
 ##
 { 'command': 'qom-get',
   'data': { 'path': 'str', 'property': 'str' },
@@ -1456,9 +1449,7 @@
 # @value: a value who's type is appropriate for the property type.  See @qom-get
 #         for a description of type mapping.
 #
-# Since: 1.1
-#
-# Notes: This command is experimental and may change syntax in future releases.
+# Since: 1.2
 ##
 { 'command': 'qom-set',
   'data': { 'path': 'str', 'property': 'str', 'value': 'visitor' },
@@ -1717,8 +1708,6 @@
 # Returns: a list of @ObjectTypeInfo or an empty list if no results are found
 #
 # Since: 1.1
-#
-# Notes: This command is experimental and may change syntax in future releases.
 ##
 { 'command': 'qom-list-types',
   'data': { '*implements': 'str', '*abstract': 'bool' },
commit 1daa31b9dbec60a7a06690749d73ddeeb35f506d
Author: Anthony Liguori <aliguori at us.ibm.com>
Date:   Fri Aug 10 11:04:09 2012 -0500

    qmp: introduce device-list-properties command
    
    This can be used in conjunction with qom-list-types to determine the supported
    set of devices and their parameters.
    
    Signed-off-by: Anthony Liguori <aliguori at us.ibm.com>
    Signed-off-by: Luiz Capitulino <lcapitulino at redhat.com>

diff --git a/qapi-schema.json b/qapi-schema.json
index ec8d919..927fdea 100644
--- a/qapi-schema.json
+++ b/qapi-schema.json
@@ -1725,6 +1725,34 @@
   'returns': [ 'ObjectTypeInfo' ] }
 
 ##
+# @DevicePropertyInfo:
+#
+# Information about device properties.
+#
+# @name: the name of the property
+# @type: the typename of the property
+#
+# Since: 1.2
+##
+{ 'type': 'DevicePropertyInfo',
+  'data': { 'name': 'str', 'type': 'str' } }
+
+##
+# @device-list-properties:
+#
+# List properties associated with a device.
+#
+# @typename: the type name of a device
+#
+# Returns: a list of DevicePropertyInfo describing a devices properties
+#
+# Since: 1.2
+##
+{ 'command': 'device-list-properties',
+  'data': { 'typename': 'str'},
+  'returns': [ 'DevicePropertyInfo' ] }
+
+##
 # @migrate
 #
 # Migrates the current running guest to another Virtual Machine.
diff --git a/qmp-commands.hx b/qmp-commands.hx
index e07c7b0..e9e0410 100644
--- a/qmp-commands.hx
+++ b/qmp-commands.hx
@@ -2217,3 +2217,10 @@ EQMP
         .args_type  = "implements:s?,abstract:b?",
         .mhandler.cmd_new = qmp_marshal_input_qom_list_types,
     },
+
+    {
+        .name       = "device-list-properties",
+        .args_type  = "typename:s",
+        .mhandler.cmd_new = qmp_marshal_input_device_list_properties,
+    },
+
diff --git a/qmp.c b/qmp.c
index fee9fb2..254a32f 100644
--- a/qmp.c
+++ b/qmp.c
@@ -417,3 +417,53 @@ ObjectTypeInfoList *qmp_qom_list_types(bool has_implements,
 
     return ret;
 }
+
+DevicePropertyInfoList *qmp_device_list_properties(const char *typename,
+                                                   Error **errp)
+{
+    ObjectClass *klass;
+    Property *prop;
+    DevicePropertyInfoList *prop_list = NULL;
+
+    klass = object_class_by_name(typename);
+    if (klass == NULL) {
+        error_set(errp, QERR_DEVICE_NOT_FOUND, typename);
+        return NULL;
+    }
+
+    klass = object_class_dynamic_cast(klass, TYPE_DEVICE);
+    if (klass == NULL) {
+        error_set(errp, QERR_INVALID_PARAMETER_VALUE,
+                  "name", TYPE_DEVICE);
+        return NULL;
+    }
+
+    do {
+        for (prop = DEVICE_CLASS(klass)->props; prop && prop->name; prop++) {
+            DevicePropertyInfoList *entry;
+            DevicePropertyInfo *info;
+
+            /*
+             * TODO Properties without a parser are just for dirty hacks.
+             * qdev_prop_ptr is the only such PropertyInfo.  It's marked
+             * for removal.  This conditional should be removed along with
+             * it.
+             */
+            if (!prop->info->set) {
+                continue;           /* no way to set it, don't show */
+            }
+
+            info = g_malloc0(sizeof(*info));
+            info->name = g_strdup(prop->name);
+            info->type = g_strdup(prop->info->legacy_name ?: prop->info->name);
+
+            entry = g_malloc0(sizeof(*entry));
+            entry->value = info;
+            entry->next = prop_list;
+            prop_list = entry;
+        }
+        klass = object_class_get_parent(klass);
+    } while (klass != object_class_by_name(TYPE_DEVICE));
+
+    return prop_list;
+}
commit 25df49f6eb113081f48fdb3a3dd17bf1c0b25600
Author: Luiz Capitulino <lcapitulino at redhat.com>
Date:   Wed Aug 8 17:03:01 2012 -0300

    qmp: add SUSPEND_DISK event
    
    Emitted when the guest makes a request to enter S4 state.
    
    There are three possible ways of having this event, as described here:
    
     http://lists.gnu.org/archive/html/qemu-devel/2012-07/msg02307.html
    
    I've decided to add a new event and make it indepedent of SHUTDOWN.
    This means that the SHUTDOWN event will eventually follow the
    SUSPEND_DISK event.
    
    I've choosen this way because of two reasons:
    
     1. Having an indepedent event makes it possible to query for its
        existence by using query-events
    
     2. In the future, we may allow the user to change what QEMU should
        do as a result of the guest entering S4. So it's a good idea to
        keep both events separated
    
    Signed-off-by: Luiz Capitulino <lcapitulino at redhat.com>

diff --git a/QMP/qmp-events.txt b/QMP/qmp-events.txt
index df190ac..2878058 100644
--- a/QMP/qmp-events.txt
+++ b/QMP/qmp-events.txt
@@ -252,6 +252,20 @@ Example:
 { "event": "SUSPEND",
      "timestamp": { "seconds": 1344456160, "microseconds": 309119 } }
 
+SUSPEND_DISK
+------------
+
+Emitted when the guest makes a request to enter S4 state.
+
+Data: None.
+
+Example:
+
+{ "event": "SUSPEND_DISK",
+     "timestamp": { "seconds": 1344456160, "microseconds": 309119 } }
+
+Note: QEMU shuts down when entering S4 state.
+
 VNC_CONNECTED
 -------------
 
diff --git a/hw/acpi.c b/hw/acpi.c
index effc7ec..f7950be 100644
--- a/hw/acpi.c
+++ b/hw/acpi.c
@@ -22,6 +22,7 @@
 #include "hw.h"
 #include "pc.h"
 #include "acpi.h"
+#include "monitor.h"
 
 struct acpi_table_header {
     uint16_t _length;         /* our length, not actual part of the hdr */
@@ -386,6 +387,7 @@ void acpi_pm1_cnt_write(ACPIREGS *ar, uint16_t val, char s4)
             break;
         default:
             if (sus_typ == s4) { /* S4 request */
+                monitor_protocol_event(QEVENT_SUSPEND_DISK, NULL);
                 qemu_system_shutdown_request();
             }
             break;
diff --git a/monitor.c b/monitor.c
index 3694590..586abae 100644
--- a/monitor.c
+++ b/monitor.c
@@ -432,6 +432,7 @@ static const char *monitor_event_names[] = {
     [QEVENT_BLOCK_JOB_CANCELLED] = "BLOCK_JOB_CANCELLED",
     [QEVENT_DEVICE_TRAY_MOVED] = "DEVICE_TRAY_MOVED",
     [QEVENT_SUSPEND] = "SUSPEND",
+    [QEVENT_SUSPEND_DISK] = "SUSPEND_DISK",
     [QEVENT_WAKEUP] = "WAKEUP",
     [QEVENT_BALLOON_CHANGE] = "BALLOON_CHANGE",
 };
diff --git a/monitor.h b/monitor.h
index 5f4de1b..4ef9a04 100644
--- a/monitor.h
+++ b/monitor.h
@@ -40,6 +40,7 @@ typedef enum MonitorEvent {
     QEVENT_BLOCK_JOB_CANCELLED,
     QEVENT_DEVICE_TRAY_MOVED,
     QEVENT_SUSPEND,
+    QEVENT_SUSPEND_DISK,
     QEVENT_WAKEUP,
     QEVENT_BALLOON_CHANGE,
 
commit 67e3cf2664b3fc858a895d1e0e4b8d81c3400823
Author: Luiz Capitulino <lcapitulino at redhat.com>
Date:   Thu Aug 9 12:02:21 2012 -0300

    qmp: qmp-events.txt: add missing doc for the SUSPEND event
    
    Signed-off-by: Luiz Capitulino <lcapitulino at redhat.com>
    Reviewed-by: Eric Blake <eblake at redhat.com>
    Acked-by: Gerd Hoffmann <kraxel at redhat.com>

diff --git a/QMP/qmp-events.txt b/QMP/qmp-events.txt
index 2389370..df190ac 100644
--- a/QMP/qmp-events.txt
+++ b/QMP/qmp-events.txt
@@ -240,6 +240,18 @@ Example:
 { "event": "STOP",
     "timestamp": { "seconds": 1267041730, "microseconds": 281295 } }
 
+SUSPEND
+-------
+
+Emitted when guest enters S3 state.
+
+Data: None.
+
+Example:
+
+{ "event": "SUSPEND",
+     "timestamp": { "seconds": 1344456160, "microseconds": 309119 } }
+
 VNC_CONNECTED
 -------------
 
commit cb8900fe0d0b5ea33fc31a01b1c4fb41dd6368aa
Author: Luiz Capitulino <lcapitulino at redhat.com>
Date:   Thu Aug 9 11:40:27 2012 -0300

    qmp: qmp-events.txt: put events in alphabetical order
    
    Signed-off-by: Luiz Capitulino <lcapitulino at redhat.com>
    Reviewed-by: Eric Blake <eblake at redhat.com>
    Acked-by: Gerd Hoffmann <kraxel at redhat.com>

diff --git a/QMP/qmp-events.txt b/QMP/qmp-events.txt
index 10f69d1..2389370 100644
--- a/QMP/qmp-events.txt
+++ b/QMP/qmp-events.txt
@@ -1,6 +1,23 @@
                    QEMU Monitor Protocol Events
                    ============================
 
+BALLOON_CHANGE
+--------------
+
+Emitted when the guest changes the actual BALLOON level. This
+value is equivalent to the 'actual' field return by the
+'query-balloon' command
+
+Data:
+
+- "actual": actual level of the guest memory balloon in bytes (json-number)
+
+Example:
+
+{ "event": "BALLOON_CHANGE",
+    "data": { "actual": 944766976 },
+    "timestamp": { "seconds": 1267020223, "microseconds": 435656 } }
+
 BLOCK_IO_ERROR
 --------------
 
@@ -26,6 +43,57 @@ Example:
 Note: If action is "stop", a STOP event will eventually follow the
 BLOCK_IO_ERROR event.
 
+BLOCK_JOB_CANCELLED
+-------------------
+
+Emitted when a block job has been cancelled.
+
+Data:
+
+- "type":     Job type ("stream" for image streaming, json-string)
+- "device":   Device name (json-string)
+- "len":      Maximum progress value (json-int)
+- "offset":   Current progress value (json-int)
+              On success this is equal to len.
+              On failure this is less than len.
+- "speed":    Rate limit, bytes per second (json-int)
+
+Example:
+
+{ "event": "BLOCK_JOB_CANCELLED",
+     "data": { "type": "stream", "device": "virtio-disk0",
+               "len": 10737418240, "offset": 134217728,
+               "speed": 0 },
+     "timestamp": { "seconds": 1267061043, "microseconds": 959568 } }
+
+BLOCK_JOB_COMPLETED
+-------------------
+
+Emitted when a block job has completed.
+
+Data:
+
+- "type":     Job type ("stream" for image streaming, json-string)
+- "device":   Device name (json-string)
+- "len":      Maximum progress value (json-int)
+- "offset":   Current progress value (json-int)
+              On success this is equal to len.
+              On failure this is less than len.
+- "speed":    Rate limit, bytes per second (json-int)
+- "error":    Error message (json-string, optional)
+              Only present on failure.  This field contains a human-readable
+              error message.  There are no semantics other than that streaming
+              has failed and clients should not try to interpret the error
+              string.
+
+Example:
+
+{ "event": "BLOCK_JOB_COMPLETED",
+     "data": { "type": "stream", "device": "virtio-disk0",
+               "len": 10737418240, "offset": 10737418240,
+               "speed": 0 },
+     "timestamp": { "seconds": 1267061043, "microseconds": 959568 } }
+
 DEVICE_TRAY_MOVED
 -----------------
 
@@ -98,6 +166,68 @@ Example:
 Note: If the command-line option "-no-shutdown" has been specified, a STOP
 event will eventually follow the SHUTDOWN event.
 
+SPICE_CONNECTED, SPICE_DISCONNECTED
+-----------------------------------
+
+Emitted when a SPICE client connects or disconnects.
+
+Data:
+
+- "server": Server information (json-object)
+  - "host": IP address (json-string)
+  - "port": port number (json-string)
+  - "family": address family (json-string, "ipv4" or "ipv6")
+- "client": Client information (json-object)
+  - "host": IP address (json-string)
+  - "port": port number (json-string)
+  - "family": address family (json-string, "ipv4" or "ipv6")
+
+Example:
+
+{ "timestamp": {"seconds": 1290688046, "microseconds": 388707},
+  "event": "SPICE_CONNECTED",
+  "data": {
+    "server": { "port": "5920", "family": "ipv4", "host": "127.0.0.1"},
+    "client": {"port": "52873", "family": "ipv4", "host": "127.0.0.1"}
+}}
+
+SPICE_INITIALIZED
+-----------------
+
+Emitted after initial handshake and authentication takes place (if any)
+and the SPICE channel is up'n'running
+
+Data:
+
+- "server": Server information (json-object)
+  - "host": IP address (json-string)
+  - "port": port number (json-string)
+  - "family": address family (json-string, "ipv4" or "ipv6")
+  - "auth": authentication method (json-string, optional)
+- "client": Client information (json-object)
+  - "host": IP address (json-string)
+  - "port": port number (json-string)
+  - "family": address family (json-string, "ipv4" or "ipv6")
+  - "connection-id": spice connection id.  All channels with the same id
+                     belong to the same spice session (json-int)
+  - "channel-type": channel type.  "1" is the main control channel, filter for
+                    this one if you want track spice sessions only (json-int)
+  - "channel-id": channel id.  Usually "0", might be different needed when
+                  multiple channels of the same type exist, such as multiple
+                  display channels in a multihead setup (json-int)
+  - "tls": whevener the channel is encrypted (json-bool)
+
+Example:
+
+{ "timestamp": {"seconds": 1290688046, "microseconds": 417172},
+  "event": "SPICE_INITIALIZED",
+  "data": {"server": {"auth": "spice", "port": "5921",
+                      "family": "ipv4", "host": "127.0.0.1"},
+           "client": {"port": "49004", "family": "ipv4", "channel-type": 3,
+                      "connection-id": 1804289383, "host": "127.0.0.1",
+                      "channel-id": 0, "tls": true}
+}}
+
 STOP
 ----
 
@@ -200,70 +330,6 @@ Example:
                     "host": "127.0.0.1", "sasl_username": "luiz" } },
         "timestamp": { "seconds": 1263475302, "microseconds": 150772 } }
 
-SPICE_CONNECTED, SPICE_DISCONNECTED
------------------------------------
-
-Emitted when a SPICE client connects or disconnects.
-
-Data:
-
-- "server": Server information (json-object)
-  - "host": IP address (json-string)
-  - "port": port number (json-string)
-  - "family": address family (json-string, "ipv4" or "ipv6")
-- "client": Client information (json-object)
-  - "host": IP address (json-string)
-  - "port": port number (json-string)
-  - "family": address family (json-string, "ipv4" or "ipv6")
-
-Example:
-
-{ "timestamp": {"seconds": 1290688046, "microseconds": 388707},
-  "event": "SPICE_CONNECTED",
-  "data": {
-    "server": { "port": "5920", "family": "ipv4", "host": "127.0.0.1"},
-    "client": {"port": "52873", "family": "ipv4", "host": "127.0.0.1"}
-}}
-
-
-SPICE_INITIALIZED
------------------
-
-Emitted after initial handshake and authentication takes place (if any)
-and the SPICE channel is up'n'running
-
-Data:
-
-- "server": Server information (json-object)
-  - "host": IP address (json-string)
-  - "port": port number (json-string)
-  - "family": address family (json-string, "ipv4" or "ipv6")
-  - "auth": authentication method (json-string, optional)
-- "client": Client information (json-object)
-  - "host": IP address (json-string)
-  - "port": port number (json-string)
-  - "family": address family (json-string, "ipv4" or "ipv6")
-  - "connection-id": spice connection id.  All channels with the same id
-                     belong to the same spice session (json-int)
-  - "channel-type": channel type.  "1" is the main control channel, filter for
-                    this one if you want track spice sessions only (json-int)
-  - "channel-id": channel id.  Usually "0", might be different needed when
-                  multiple channels of the same type exist, such as multiple
-                  display channels in a multihead setup (json-int)
-  - "tls": whevener the channel is encrypted (json-bool)
-
-Example:
-
-{ "timestamp": {"seconds": 1290688046, "microseconds": 417172},
-  "event": "SPICE_INITIALIZED",
-  "data": {"server": {"auth": "spice", "port": "5921",
-                      "family": "ipv4", "host": "127.0.0.1"},
-           "client": {"port": "49004", "family": "ipv4", "channel-type": 3,
-                      "connection-id": 1804289383, "host": "127.0.0.1",
-                      "channel-id": 0, "tls": true}
-}}
-
-
 WAKEUP
 ------
 
@@ -276,7 +342,6 @@ Example:
 { "event": "WATCHDOG",
      "timestamp": { "seconds": 1344522075, "microseconds": 745528 } }
 
-
 WATCHDOG
 --------
 
@@ -295,74 +360,3 @@ Example:
 
 Note: If action is "reset", "shutdown", or "pause" the WATCHDOG event is
 followed respectively by the RESET, SHUTDOWN, or STOP events.
-
-
-BLOCK_JOB_COMPLETED
--------------------
-
-Emitted when a block job has completed.
-
-Data:
-
-- "type":     Job type ("stream" for image streaming, json-string)
-- "device":   Device name (json-string)
-- "len":      Maximum progress value (json-int)
-- "offset":   Current progress value (json-int)
-              On success this is equal to len.
-              On failure this is less than len.
-- "speed":    Rate limit, bytes per second (json-int)
-- "error":    Error message (json-string, optional)
-              Only present on failure.  This field contains a human-readable
-              error message.  There are no semantics other than that streaming
-              has failed and clients should not try to interpret the error
-              string.
-
-Example:
-
-{ "event": "BLOCK_JOB_COMPLETED",
-     "data": { "type": "stream", "device": "virtio-disk0",
-               "len": 10737418240, "offset": 10737418240,
-               "speed": 0 },
-     "timestamp": { "seconds": 1267061043, "microseconds": 959568 } }
-
-
-BLOCK_JOB_CANCELLED
--------------------
-
-Emitted when a block job has been cancelled.
-
-Data:
-
-- "type":     Job type ("stream" for image streaming, json-string)
-- "device":   Device name (json-string)
-- "len":      Maximum progress value (json-int)
-- "offset":   Current progress value (json-int)
-              On success this is equal to len.
-              On failure this is less than len.
-- "speed":    Rate limit, bytes per second (json-int)
-
-Example:
-
-{ "event": "BLOCK_JOB_CANCELLED",
-     "data": { "type": "stream", "device": "virtio-disk0",
-               "len": 10737418240, "offset": 134217728,
-               "speed": 0 },
-     "timestamp": { "seconds": 1267061043, "microseconds": 959568 } }
-
-
-BALLOON_CHANGE
-----------
-
-Emitted when the guest changes the actual BALLOON level. This
-value is equivalent to the 'actual' field return by the
-'query-balloon' command
-
-Data:
-
-- "actual": actual level of the guest memory balloon in bytes (json-number)
-
-Example:
-
-{ "event": "BALLOON_CHANGE",
-    "data": { "actual": 944766976 },
-    "timestamp": { "seconds": 1267020223, "microseconds": 435656 } }
commit 17c8660b0b2be17d389e2ffd5681d535cc0d8912
Author: Luiz Capitulino <lcapitulino at redhat.com>
Date:   Thu Aug 9 11:27:30 2012 -0300

    qmp: emit the WAKEUP event when the guest is put to run
    
    Today, the WAKEUP event is emitted when a wakeup _request_ is made.
    This could be the system_wakeup command, for example.
    
    A better semantic would be to emit the event when the guest is
    already running, as that's what matters in the end. This commit does
    that change.
    
    In theory, this could break compatibility. In practice, it shouldn't
    happen though, as clients shouldn't rely on timing characteristics of
    the events. That is, a client relying that the guest is not running
    when the event arrives may break if the event arrives after the guest
    is already running.
    
    This commit also adds the missing documentation for the WAKEUP event.
    
    Signed-off-by: Luiz Capitulino <lcapitulino at redhat.com>
    Acked-by: Gerd Hoffmann <kraxel at redhat.com>

diff --git a/QMP/qmp-events.txt b/QMP/qmp-events.txt
index 9ba7079..10f69d1 100644
--- a/QMP/qmp-events.txt
+++ b/QMP/qmp-events.txt
@@ -264,6 +264,19 @@ Example:
 }}
 
 
+WAKEUP
+------
+
+Emitted when the guest has woken up from S3 and is running.
+
+Data: None.
+
+Example:
+
+{ "event": "WATCHDOG",
+     "timestamp": { "seconds": 1344522075, "microseconds": 745528 } }
+
+
 WATCHDOG
 --------
 
diff --git a/vl.c b/vl.c
index 68fa0a0..97ab39f 100644
--- a/vl.c
+++ b/vl.c
@@ -1465,7 +1465,6 @@ void qemu_system_wakeup_request(WakeupReason reason)
         return;
     }
     runstate_set(RUN_STATE_RUNNING);
-    monitor_protocol_event(QEVENT_WAKEUP, NULL);
     notifier_list_notify(&wakeup_notifiers, &reason);
     wakeup_requested = 1;
     qemu_notify_event();
@@ -1552,6 +1551,7 @@ static bool main_loop_should_exit(void)
         cpu_synchronize_all_states();
         qemu_system_reset(VMRESET_SILENT);
         resume_all_vcpus();
+        monitor_protocol_event(QEVENT_WAKEUP, NULL);
     }
     if (qemu_powerdown_requested()) {
         monitor_protocol_event(QEVENT_POWERDOWN, NULL);
commit 1405819637f53ed8021067eb3ea52e32bef2870b
Author: Luiz Capitulino <lcapitulino at redhat.com>
Date:   Wed Aug 8 17:29:17 2012 -0300

    qmp: don't emit the RESET event on wakeup from S3
    
    QEMU is basically using reset logic when waking up from S3. This
    causes the QMP RESET event to be emitted, which is wrong. Also,
    the runstate checks done in reset are not necessary for S3 wakeup.
    
    Fix this by untangling wakeup from reset logic and passing
    VMRESET_SILENT to qemu_system_reset() to avoid emitting the RESET
    event.
    
    Signed-off-by: Luiz Capitulino <lcapitulino at redhat.com>
    Acked-by: Gerd Hoffmann <kraxel at redhat.com>

diff --git a/vl.c b/vl.c
index 91076f0..68fa0a0 100644
--- a/vl.c
+++ b/vl.c
@@ -1298,6 +1298,7 @@ static pid_t shutdown_pid;
 static int powerdown_requested;
 static int debug_requested;
 static int suspend_requested;
+static int wakeup_requested;
 static NotifierList suspend_notifiers =
     NOTIFIER_LIST_INITIALIZER(suspend_notifiers);
 static NotifierList wakeup_notifiers =
@@ -1352,6 +1353,13 @@ static int qemu_suspend_requested(void)
     return r;
 }
 
+static int qemu_wakeup_requested(void)
+{
+    int r = wakeup_requested;
+    wakeup_requested = 0;
+    return r;
+}
+
 int qemu_powerdown_requested(void)
 {
     int r = powerdown_requested;
@@ -1459,7 +1467,7 @@ void qemu_system_wakeup_request(WakeupReason reason)
     runstate_set(RUN_STATE_RUNNING);
     monitor_protocol_event(QEVENT_WAKEUP, NULL);
     notifier_list_notify(&wakeup_notifiers, &reason);
-    reset_requested = 1;
+    wakeup_requested = 1;
     qemu_notify_event();
 }
 
@@ -1539,6 +1547,12 @@ static bool main_loop_should_exit(void)
             runstate_set(RUN_STATE_PAUSED);
         }
     }
+    if (qemu_wakeup_requested()) {
+        pause_all_vcpus();
+        cpu_synchronize_all_states();
+        qemu_system_reset(VMRESET_SILENT);
+        resume_all_vcpus();
+    }
     if (qemu_powerdown_requested()) {
         monitor_protocol_event(QEVENT_POWERDOWN, NULL);
         qemu_irq_raise(qemu_system_powerdown);
commit 08b76b9fc3f0c25f062216955411aefaefabff89
Author: Luiz Capitulino <lcapitulino at redhat.com>
Date:   Mon Aug 6 11:35:22 2012 -0300

    scripts: qapi-commands.py: qmp-commands.h: include qdict.h
    
    qmp-commands.h declares several functions that have arguments of
    type QDict. However, qdict.h is not included. This will cause a
    build breakage when a file includes qmp-commands.h but doesn't
    include qdict.h.
    
    Signed-off-by: Luiz Capitulino <lcapitulino at redhat.com>

diff --git a/scripts/qapi-commands.py b/scripts/qapi-commands.py
index 9eed40e..3c4678d 100644
--- a/scripts/qapi-commands.py
+++ b/scripts/qapi-commands.py
@@ -342,6 +342,7 @@ def gen_command_decl_prologue(header, guard, prefix=""):
 #define %(guard)s
 
 #include "%(prefix)sqapi-types.h"
+#include "qdict.h"
 #include "error.h"
 
 ''',
commit adb2072ed0fd595b05f6571e985b271a3cfa872d
Author: Luiz Capitulino <lcapitulino at redhat.com>
Date:   Mon Aug 6 11:35:22 2012 -0300

    docs: writing-qmp-commands.txt: update error section
    
    Add information about the new error format and improve the text a bit.
    
    Signed-off-by: Luiz Capitulino <lcapitulino at redhat.com>
    Reviewed-by: Markus Armbruster <armbru at redhat.com>

diff --git a/docs/writing-qmp-commands.txt b/docs/writing-qmp-commands.txt
index 0ad51aa..8349dec 100644
--- a/docs/writing-qmp-commands.txt
+++ b/docs/writing-qmp-commands.txt
@@ -210,19 +210,17 @@ if you don't see these strings, then something went wrong.
 === Errors ===
 
 QMP commands should use the error interface exported by the error.h header
-file. The basic function used to set an error is the error_set() one.
+file. Basically, errors are set by calling the error_set() function.
 
 Let's say we don't accept the string "message" to contain the word "love". If
-it does contain it, we want the "hello-world" command to the return the
-InvalidParameter error.
-
-Only one change is required, and it's in the C implementation:
+it does contain it, we want the "hello-world" command to return an error:
 
 void qmp_hello_world(bool has_message, const char *message, Error **errp)
 {
     if (has_message) {
         if (strstr(message, "love")) {
-            error_set(errp, QERR_INVALID_PARAMETER, "message");
+            error_set(errp, ERROR_CLASS_GENERIC_ERROR,
+                      "the word 'love' is not allowed");
             return;
         }
         printf("%s\n", message);
@@ -231,30 +229,40 @@ void qmp_hello_world(bool has_message, const char *message, Error **errp)
     }
 }
 
-Let's test it. Build qemu, run it as defined in the "Testing" section, and
-then issue the following command:
+The first argument to the error_set() function is the Error pointer to pointer,
+which is passed to all QMP functions. The second argument is a ErrorClass
+value, which should be ERROR_CLASS_GENERIC_ERROR most of the time (more
+details about error classes are given below). The third argument is a human
+description of the error, this is a free-form printf-like string.
+
+Let's test the example above. Build qemu, run it as defined in the "Testing"
+section, and then issue the following command:
 
-{ "execute": "hello-world", "arguments": { "message": "we love qemu" } }
+{ "execute": "hello-world", "arguments": { "message": "all you need is love" } }
 
 The QMP server's response should be:
 
 {
     "error": {
-        "class": "InvalidParameter",
-        "desc": "Invalid parameter 'message'",
-        "data": {
-            "name": "message"
-        }
+        "class": "GenericError",
+        "desc": "the word 'love' is not allowed"
     }
 }
 
-Which is the InvalidParameter error.
+As a general rule, all QMP errors should use ERROR_CLASS_GENERIC_ERROR. There
+are two exceptions to this rule:
+
+ 1. A non-generic ErrorClass value exists* for the failure you want to report
+    (eg. DeviceNotFound)
+
+ 2. Management applications have to take special action on the failure you
+    want to report, hence you have to add a new ErrorClass value so that they
+    can check for it
 
-When you have to return an error but you're unsure what error to return or
-which arguments an error takes, you should look at the qerror.h file. Note
-that you might be required to add new errors if needed.
+If the failure you want to report doesn't fall in one of the two cases above,
+just report ERROR_CLASS_GENERIC_ERROR.
 
-FIXME: describe better the error API and how to add new errors.
+ * All existing ErrorClass values are defined in the qapi-schema.json file
 
 === Command Documentation ===
 
@@ -275,7 +283,6 @@ here goes "hello-world"'s new entry for the qapi-schema.json file:
 # @message: #optional string to be printed
 #
 # Returns: Nothing on success.
-#          If @message contains "love", InvalidParameter
 #
 # Notes: if @message is not provided, the "Hello, world" string will
 #        be printed instead
commit 6d3f0dbb304d59759b2faf1e50db94d996f51f8a
Author: Luiz Capitulino <lcapitulino at redhat.com>
Date:   Wed Aug 1 18:06:44 2012 -0300

    error, qerror: drop QDict member
    
    Used to store error information, but it's unused now.
    
    Signed-off-by: Luiz Capitulino <lcapitulino at redhat.com>
    Reviewed-by: Markus Armbruster <armbru at redhat.com>

diff --git a/error.c b/error.c
index 0e10373..1f05fc4 100644
--- a/error.c
+++ b/error.c
@@ -19,7 +19,6 @@
 
 struct Error
 {
-    QDict *obj;
     char *msg;
     ErrorClass err_class;
 };
@@ -51,8 +50,6 @@ Error *error_copy(const Error *err)
     err_new = g_malloc0(sizeof(*err));
     err_new->msg = g_strdup(err->msg);
     err_new->err_class = err->err_class;
-    err_new->obj = err->obj;
-    QINCREF(err_new->obj);
 
     return err_new;
 }
@@ -75,7 +72,6 @@ const char *error_get_pretty(Error *err)
 void error_free(Error *err)
 {
     if (err) {
-        QDECREF(err->obj);
         g_free(err->msg);
         g_free(err);
     }
diff --git a/qerror.c b/qerror.c
index ccc52be..0818504 100644
--- a/qerror.c
+++ b/qerror.c
@@ -100,7 +100,6 @@ void qerror_report(ErrorClass eclass, const char *fmt, ...)
 /* Evil... */
 struct Error
 {
-    QDict *obj;
     char *msg;
     ErrorClass err_class;
 };
@@ -111,8 +110,6 @@ void qerror_report_err(Error *err)
 
     qerr = qerror_new();
     loc_save(&qerr->loc);
-    QINCREF(err->obj);
-    qerr->error = err->obj;
     qerr->err_msg = g_strdup(err->msg);
     qerr->err_class = err->err_class;
 
@@ -154,7 +151,6 @@ static void qerror_destroy_obj(QObject *obj)
     assert(obj != NULL);
     qerr = qobject_to_qerror(obj);
 
-    QDECREF(qerr->error);
     g_free(qerr->err_msg);
     g_free(qerr);
 }
diff --git a/qerror.h b/qerror.h
index c5ad29f..d0a76a4 100644
--- a/qerror.h
+++ b/qerror.h
@@ -21,7 +21,6 @@
 
 typedef struct QError {
     QObject_HEAD;
-    QDict *error;
     Location loc;
     char *err_msg;
     ErrorClass err_class;
commit 3647f5c161dddb5ec22c2d8e0ab27811959e3ada
Author: Luiz Capitulino <lcapitulino at redhat.com>
Date:   Fri Jul 27 18:11:16 2012 -0300

    qerror: drop qerror_table and qerror_format()
    
    They are unused since last commit.
    
    Signed-off-by: Luiz Capitulino <lcapitulino at redhat.com>
    Reviewed-by: Markus Armbruster <armbru at redhat.com>

diff --git a/qerror.c b/qerror.c
index dda1427..ccc52be 100644
--- a/qerror.c
+++ b/qerror.c
@@ -23,311 +23,6 @@ static const QType qerror_type = {
 };
 
 /**
- * The 'desc' parameter is a printf-like string, the format of the format
- * string is:
- *
- * %(KEY)
- *
- * Where KEY is a QDict key, which has to be passed to qerror_from_info().
- *
- * Example:
- *
- * "foo error on device: %(device) slot: %(slot_nr)"
- *
- * A single percent sign can be printed if followed by a second one,
- * for example:
- *
- * "running out of foo: %(foo)%%"
- *
- * Please keep the entries in alphabetical order.
- * Use scripts/check-qerror.sh to check.
- */
-static const QErrorStringTable qerror_table[] = {
-    {
-         QERR_ADD_CLIENT_FAILED,
-         "Could not add client",
-    },
-    {
-         QERR_AMBIGUOUS_PATH,
-         "Path '%(path)' does not uniquely identify an object"
-    },
-    {
-         QERR_BAD_BUS_FOR_DEVICE,
-         "Device '%(device)' can't go on a %(bad_bus_type) bus",
-    },
-    {
-         QERR_BASE_NOT_FOUND,
-         "Base '%(base)' not found",
-    },
-    {
-         QERR_BLOCK_FORMAT_FEATURE_NOT_SUPPORTED,
-         "Block format '%(format)' used by device '%(name)' does not support feature '%(feature)'",
-    },
-    {
-         QERR_BUS_NO_HOTPLUG,
-         "Bus '%(bus)' does not support hotplugging",
-    },
-    {
-         QERR_BUS_NOT_FOUND,
-         "Bus '%(bus)' not found",
-    },
-    {
-         QERR_COMMAND_DISABLED,
-         "The command %(name) has been disabled for this instance",
-    },
-    {
-         QERR_COMMAND_NOT_FOUND,
-         "The command %(name) has not been found",
-    },
-    {
-         QERR_DEVICE_ENCRYPTED,
-         "'%(device)' (%(filename)) is encrypted",
-    },
-    {
-         QERR_DEVICE_FEATURE_BLOCKS_MIGRATION,
-         "Migration is disabled when using feature '%(feature)' in device '%(device)'",
-    },
-    {
-         QERR_DEVICE_HAS_NO_MEDIUM,
-         "Device '%(device)' has no medium",
-    },
-    {
-         QERR_DEVICE_INIT_FAILED,
-         "Device '%(device)' could not be initialized",
-    },
-    {
-         QERR_DEVICE_IN_USE,
-         "Device '%(device)' is in use",
-    },
-    {
-         QERR_DEVICE_IS_READ_ONLY,
-         "Device '%(device)' is read only",
-    },
-    {
-         QERR_DEVICE_LOCKED,
-         "Device '%(device)' is locked",
-    },
-    {
-         QERR_DEVICE_MULTIPLE_BUSSES,
-         "Device '%(device)' has multiple child busses",
-    },
-    {
-         QERR_DEVICE_NO_BUS,
-         "Device '%(device)' has no child bus",
-    },
-    {
-         QERR_DEVICE_NO_HOTPLUG,
-         "Device '%(device)' does not support hotplugging",
-    },
-    {
-         QERR_DEVICE_NOT_ACTIVE,
-         "Device '%(device)' has not been activated",
-    },
-    {
-         QERR_DEVICE_NOT_ENCRYPTED,
-         "Device '%(device)' is not encrypted",
-    },
-    {
-         QERR_DEVICE_NOT_FOUND,
-         "Device '%(device)' not found",
-    },
-    {
-         QERR_DEVICE_NOT_REMOVABLE,
-         "Device '%(device)' is not removable",
-    },
-    {
-         QERR_DUPLICATE_ID,
-         "Duplicate ID '%(id)' for %(object)",
-    },
-    {
-         QERR_FD_NOT_FOUND,
-         "File descriptor named '%(name)' not found",
-    },
-    {
-         QERR_FD_NOT_SUPPLIED,
-         "No file descriptor supplied via SCM_RIGHTS",
-    },
-    {
-         QERR_FEATURE_DISABLED,
-         "The feature '%(name)' is not enabled",
-    },
-    {
-         QERR_INVALID_BLOCK_FORMAT,
-         "Invalid block format '%(name)'",
-    },
-    {
-         QERR_INVALID_OPTION_GROUP,
-         "There is no option group '%(group)'",
-    },
-    {
-         QERR_INVALID_PARAMETER,
-         "Invalid parameter '%(name)'",
-    },
-    {
-         QERR_INVALID_PARAMETER_COMBINATION,
-         "Invalid parameter combination",
-    },
-    {
-         QERR_INVALID_PARAMETER_TYPE,
-         "Invalid parameter type for '%(name)', expected: %(expected)",
-    },
-    {
-         QERR_INVALID_PARAMETER_VALUE,
-         "Parameter '%(name)' expects %(expected)",
-    },
-    {
-         QERR_INVALID_PASSWORD,
-         "Password incorrect",
-    },
-    {
-         QERR_IO_ERROR,
-         "An IO error has occurred",
-    },
-    {
-         QERR_JSON_PARSE_ERROR,
-         "JSON parse error, %(message)",
-
-    },
-    {
-         QERR_JSON_PARSING,
-         "Invalid JSON syntax",
-    },
-    {
-         QERR_KVM_MISSING_CAP,
-         "Using KVM without %(capability), %(feature) unavailable",
-    },
-    {
-         QERR_MIGRATION_ACTIVE,
-         "There's a migration process in progress",
-    },
-    {
-         QERR_MIGRATION_NOT_SUPPORTED,
-         "State blocked by non-migratable device '%(device)'",
-    },
-    {
-         QERR_MIGRATION_EXPECTED,
-         "An incoming migration is expected before this command can be executed",
-    },
-    {
-         QERR_MISSING_PARAMETER,
-         "Parameter '%(name)' is missing",
-    },
-    {
-         QERR_NO_BUS_FOR_DEVICE,
-         "No '%(bus)' bus found for device '%(device)'",
-    },
-    {
-         QERR_NOT_SUPPORTED,
-         "Not supported",
-    },
-    {
-         QERR_OPEN_FILE_FAILED,
-         "Could not open '%(filename)'",
-    },
-    {
-         QERR_PERMISSION_DENIED,
-         "Insufficient permission to perform this operation",
-    },
-    {
-         QERR_PROPERTY_NOT_FOUND,
-         "Property '%(device).%(property)' not found",
-    },
-    {
-         QERR_PROPERTY_VALUE_BAD,
-         "Property '%(device).%(property)' doesn't take value '%(value)'",
-    },
-    {
-         QERR_PROPERTY_VALUE_IN_USE,
-         "Property '%(device).%(property)' can't take value '%(value)', it's in use",
-    },
-    {
-         QERR_PROPERTY_VALUE_NOT_FOUND,
-         "Property '%(device).%(property)' can't find value '%(value)'",
-    },
-    {
-         QERR_PROPERTY_VALUE_NOT_POWER_OF_2,
-         "Property '%(device).%(property)' doesn't take "
-                     "value '%(value)', it's not a power of 2",
-    },
-    {
-         QERR_PROPERTY_VALUE_OUT_OF_RANGE,
-         "Property '%(device).%(property)' doesn't take "
-                     "value %(value) (minimum: %(min), maximum: %(max))",
-    },
-    {
-         QERR_QGA_COMMAND_FAILED,
-         "Guest agent command failed, error was '%(message)'",
-    },
-    {
-         QERR_QGA_LOGGING_FAILED,
-         "Guest agent failed to log non-optional log statement",
-    },
-    {
-         QERR_QMP_BAD_INPUT_OBJECT,
-         "Expected '%(expected)' in QMP input",
-    },
-    {
-         QERR_QMP_BAD_INPUT_OBJECT_MEMBER,
-         "QMP input object member '%(member)' expects '%(expected)'",
-    },
-    {
-         QERR_QMP_EXTRA_MEMBER,
-         "QMP input object member '%(member)' is unexpected",
-    },
-    {
-         QERR_RESET_REQUIRED,
-         "Resetting the Virtual Machine is required",
-    },
-    {
-         QERR_SET_PASSWD_FAILED,
-         "Could not set password",
-    },
-    {
-         QERR_TOO_MANY_FILES,
-         "Too many open files",
-    },
-    {
-         QERR_UNDEFINED_ERROR,
-         "An undefined error has occurred",
-    },
-    {
-         QERR_UNKNOWN_BLOCK_FORMAT_FEATURE,
-         "'%(device)' uses a %(format) feature which is not "
-                     "supported by this qemu version: %(feature)",
-    },
-    {
-         QERR_UNSUPPORTED,
-         "this feature or command is not currently supported",
-    },
-    {
-         QERR_VIRTFS_FEATURE_BLOCKS_MIGRATION,
-         "Migration is disabled when VirtFS export path '%(path)' "
-                     "is mounted in the guest using mount_tag '%(tag)'",
-    },
-    {
-         QERR_VNC_SERVER_FAILED,
-         "Could not start VNC server on %(target)",
-    },
-    {
-         QERR_SOCKET_CONNECT_FAILED,
-         "Failed to connect to socket",
-    },
-    {
-         QERR_SOCKET_LISTEN_FAILED,
-         "Failed to set socket to listening mode",
-    },
-    {
-         QERR_SOCKET_BIND_FAILED,
-         "Failed to bind socket",
-    },
-    {
-         QERR_SOCKET_CREATE_FAILED,
-         "Failed to create socket",
-    },
-    {}
-};
-
-/**
  * qerror_new(): Create a new QError
  *
  * Return strong reference.
@@ -361,101 +56,6 @@ static QError *qerror_from_info(ErrorClass err_class, const char *fmt,
     return qerr;
 }
 
-static void parse_error(const QErrorStringTable *entry, int c)
-{
-    fprintf(stderr, "expected '%c' in '%s'", c, entry->desc);
-    abort();
-}
-
-static const char *append_field(QDict *error, QString *outstr,
-                                const QErrorStringTable *entry,
-                                const char *start)
-{
-    QObject *obj;
-    QDict *qdict;
-    QString *key_qs;
-    const char *end, *key;
-
-    if (*start != '%')
-        parse_error(entry, '%');
-    start++;
-    if (*start != '(')
-        parse_error(entry, '(');
-    start++;
-
-    end = strchr(start, ')');
-    if (!end)
-        parse_error(entry, ')');
-
-    key_qs = qstring_from_substr(start, 0, end - start - 1);
-    key = qstring_get_str(key_qs);
-
-    qdict = qobject_to_qdict(qdict_get(error, "data"));
-    obj = qdict_get(qdict, key);
-    if (!obj) {
-        abort();
-    }
-
-    switch (qobject_type(obj)) {
-        case QTYPE_QSTRING:
-            qstring_append(outstr, qdict_get_str(qdict, key));
-            break;
-        case QTYPE_QINT:
-            qstring_append_int(outstr, qdict_get_int(qdict, key));
-            break;
-        default:
-            abort();
-    }
-
-    QDECREF(key_qs);
-    return ++end;
-}
-
-static QString *qerror_format_desc(QDict *error,
-                                   const QErrorStringTable *entry)
-{
-    QString *qstring;
-    const char *p;
-
-    assert(entry != NULL);
-
-    qstring = qstring_new();
-
-    for (p = entry->desc; *p != '\0';) {
-        if (*p != '%') {
-            qstring_append_chr(qstring, *p++);
-        } else if (*(p + 1) == '%') {
-            qstring_append_chr(qstring, '%');
-            p += 2;
-        } else {
-            p = append_field(error, qstring, entry, p);
-        }
-    }
-
-    return qstring;
-}
-
-char *qerror_format(const char *fmt, QDict *error)
-{
-    const QErrorStringTable *entry = NULL;
-    QString *qstr;
-    char *ret;
-    int i;
-
-    for (i = 0; qerror_table[i].error_fmt; i++) {
-        if (strcmp(qerror_table[i].error_fmt, fmt) == 0) {
-            entry = &qerror_table[i];
-            break;
-        }
-    }
-
-    qstr = qerror_format_desc(error, entry);
-    ret = g_strdup(qstring_get_str(qstr));
-    QDECREF(qstr);
-
-    return ret;
-}
-
 /**
  * qerror_human(): Format QError data into human-readable string.
  */
diff --git a/qerror.h b/qerror.h
index 057a8f2..c5ad29f 100644
--- a/qerror.h
+++ b/qerror.h
@@ -19,12 +19,6 @@
 #include "qapi-types.h"
 #include <stdarg.h>
 
-typedef struct QErrorStringTable {
-    ErrorClass err_class;
-    const char *error_fmt;
-    const char *desc;
-} QErrorStringTable;
-
 typedef struct QError {
     QObject_HEAD;
     QDict *error;
@@ -37,7 +31,6 @@ QString *qerror_human(const QError *qerror);
 void qerror_report(ErrorClass err_class, const char *fmt, ...) GCC_FMT_ATTR(2, 3);
 void qerror_report_err(Error *err);
 void assert_no_error(Error *err);
-char *qerror_format(const char *fmt, QDict *error);
 
 /*
  * QError class list
commit df1e608a01eb0d55d6639d97f575dba37a44ac4a
Author: Luiz Capitulino <lcapitulino at redhat.com>
Date:   Fri Jul 27 17:51:03 2012 -0300

    error, qerror: pass desc string to error calls
    
    This commit changes all QERR_ macros to contain a human message (ie.
    the desc string found in qerr_table[]) instead of a json dictionary
    in string format.
    
    Before this commit, error_set() and qerror_report() would receive
    a json dictionary in string format and build a qobject from it. Now,
    both function receive a human message instead and the qobject is
    not built anymore.
    
    Signed-off-by: Luiz Capitulino <lcapitulino at redhat.com>
    Reviewed-by: Markus Armbruster <armbru at redhat.com>

diff --git a/error.c b/error.c
index 9d7b35f..0e10373 100644
--- a/error.c
+++ b/error.c
@@ -37,9 +37,8 @@ void error_set(Error **errp, ErrorClass err_class, const char *fmt, ...)
     err = g_malloc0(sizeof(*err));
 
     va_start(ap, fmt);
-    err->obj = qobject_to_qdict(qobject_from_jsonv(fmt, &ap));
+    err->msg = g_strdup_vprintf(fmt, ap);
     va_end(ap);
-    err->msg = qerror_format(fmt, err->obj);
     err->err_class = err_class;
 
     *errp = err;
diff --git a/error.h b/error.h
index 5336fc5..96fc203 100644
--- a/error.h
+++ b/error.h
@@ -17,15 +17,15 @@
 #include <stdbool.h>
 
 /**
- * A class representing internal errors within QEMU.  An error has a string
- * typename and optionally a set of named string parameters.
+ * A class representing internal errors within QEMU.  An error has a ErrorClass
+ * code and a human message.
  */
 typedef struct Error Error;
 
 /**
- * Set an indirect pointer to an error given a printf-style format parameter.
- * Currently, qerror.h defines these error formats.  This function is not
- * meant to be used outside of QEMU.
+ * Set an indirect pointer to an error given a ErrorClass value and a
+ * printf-style human message.  This function is not meant to be used outside
+ * of QEMU.
  */
 void error_set(Error **err, ErrorClass err_class, const char *fmt, ...) GCC_FMT_ATTR(3, 4);
 
diff --git a/qerror.c b/qerror.c
index 0bf8aec..dda1427 100644
--- a/qerror.c
+++ b/qerror.c
@@ -342,45 +342,6 @@ static QError *qerror_new(void)
     return qerr;
 }
 
-static QDict *error_obj_from_fmt_no_fail(const char *fmt, va_list *va)
-{
-    QObject *obj;
-    QDict *ret;
-
-    obj = qobject_from_jsonv(fmt, va);
-    if (!obj) {
-        fprintf(stderr, "invalid json in error dict '%s'\n", fmt);
-        abort();
-    }
-    if (qobject_type(obj) != QTYPE_QDICT) {
-        fprintf(stderr, "error is not a dict '%s'\n", fmt);
-        abort();
-    }
-
-    ret = qobject_to_qdict(obj);
-    obj = qdict_get(ret, "class");
-    if (!obj) {
-        fprintf(stderr, "missing 'class' key in '%s'\n", fmt);
-        abort();
-    }
-    if (qobject_type(obj) != QTYPE_QSTRING) {
-        fprintf(stderr, "'class' key value should be a string in '%s'\n", fmt);
-        abort();
-    }
-
-    obj = qdict_get(ret, "data");
-    if (!obj) {
-        fprintf(stderr, "missing 'data' key in '%s'\n", fmt);
-        abort();
-    }
-    if (qobject_type(obj) != QTYPE_QDICT) {
-        fprintf(stderr, "'data' key value should be a dict in '%s'\n", fmt);
-        abort();
-    }
-
-    return ret;
-}
-
 /**
  * qerror_from_info(): Create a new QError from error information
  *
@@ -394,9 +355,8 @@ static QError *qerror_from_info(ErrorClass err_class, const char *fmt,
     qerr = qerror_new();
     loc_save(&qerr->loc);
 
+    qerr->err_msg = g_strdup_vprintf(fmt, *va);
     qerr->err_class = err_class;
-    qerr->error = error_obj_from_fmt_no_fail(fmt, va);
-    qerr->err_msg = qerror_format(fmt, qerr->error);
 
     return qerr;
 }
diff --git a/qerror.h b/qerror.h
index 4f92218..057a8f2 100644
--- a/qerror.h
+++ b/qerror.h
@@ -45,214 +45,213 @@ char *qerror_format(const char *fmt, QDict *error);
  * Use scripts/check-qerror.sh to check.
  */
 #define QERR_ADD_CLIENT_FAILED \
-    ERROR_CLASS_GENERIC_ERROR, "{ 'class': 'AddClientFailed', 'data': {} }"
+    ERROR_CLASS_GENERIC_ERROR, "Could not add client"
 
 #define QERR_AMBIGUOUS_PATH \
-    ERROR_CLASS_GENERIC_ERROR, "{ 'class': 'AmbiguousPath', 'data': { 'path': %s } }"
+    ERROR_CLASS_GENERIC_ERROR, "Path '%s' does not uniquely identify an object"
 
 #define QERR_BAD_BUS_FOR_DEVICE \
-    ERROR_CLASS_GENERIC_ERROR, "{ 'class': 'BadBusForDevice', 'data': { 'device': %s, 'bad_bus_type': %s } }"
+    ERROR_CLASS_GENERIC_ERROR, "Device '%s' can't go on a %s bus"
 
 #define QERR_BASE_NOT_FOUND \
-    ERROR_CLASS_GENERIC_ERROR, "{ 'class': 'BaseNotFound', 'data': { 'base': %s } }"
+    ERROR_CLASS_GENERIC_ERROR, "Base '%s' not found"
 
 #define QERR_BLOCK_FORMAT_FEATURE_NOT_SUPPORTED \
-    ERROR_CLASS_GENERIC_ERROR, "{ 'class': 'BlockFormatFeatureNotSupported', 'data': { 'format': %s, 'name': %s, 'feature': %s } }"
+    ERROR_CLASS_GENERIC_ERROR, "Block format '%s' used by device '%s' does not support feature '%s'"
 
 #define QERR_BUFFER_OVERRUN \
-    ERROR_CLASS_GENERIC_ERROR, "{ 'class': 'BufferOverrun', 'data': {} }"
+    ERROR_CLASS_GENERIC_ERROR, "An internal buffer overran"
 
 #define QERR_BUS_NO_HOTPLUG \
-    ERROR_CLASS_GENERIC_ERROR, "{ 'class': 'BusNoHotplug', 'data': { 'bus': %s } }"
+    ERROR_CLASS_GENERIC_ERROR, "Bus '%s' does not support hotplugging"
 
 #define QERR_BUS_NOT_FOUND \
-    ERROR_CLASS_GENERIC_ERROR, "{ 'class': 'BusNotFound', 'data': { 'bus': %s } }"
+    ERROR_CLASS_GENERIC_ERROR, "Bus '%s' not found"
 
 #define QERR_COMMAND_DISABLED \
-    ERROR_CLASS_GENERIC_ERROR, "{ 'class': 'CommandDisabled', 'data': { 'name': %s } }"
+    ERROR_CLASS_GENERIC_ERROR, "The command %s has been disabled for this instance"
 
 #define QERR_COMMAND_NOT_FOUND \
-    ERROR_CLASS_COMMAND_NOT_FOUND, "{ 'class': 'CommandNotFound', 'data': { 'name': %s } }"
+    ERROR_CLASS_COMMAND_NOT_FOUND, "The command %s has not been found"
 
 #define QERR_DEVICE_ENCRYPTED \
-    ERROR_CLASS_DEVICE_ENCRYPTED, "{ 'class': 'DeviceEncrypted', 'data': { 'device': %s, 'filename': %s } }"
+    ERROR_CLASS_DEVICE_ENCRYPTED, "'%s' (%s) is encrypted"
 
 #define QERR_DEVICE_FEATURE_BLOCKS_MIGRATION \
-    ERROR_CLASS_GENERIC_ERROR, "{ 'class': 'DeviceFeatureBlocksMigration', 'data': { 'device': %s, 'feature': %s } }"
+    ERROR_CLASS_GENERIC_ERROR, "Migration is disabled when using feature '%s' in device '%s'"
 
 #define QERR_DEVICE_HAS_NO_MEDIUM \
-    ERROR_CLASS_GENERIC_ERROR, "{ 'class': 'DeviceHasNoMedium', 'data': { 'device': %s } }"
+    ERROR_CLASS_GENERIC_ERROR, "Device '%s' has no medium"
 
 #define QERR_DEVICE_INIT_FAILED \
-    ERROR_CLASS_GENERIC_ERROR, "{ 'class': 'DeviceInitFailed', 'data': { 'device': %s } }"
+    ERROR_CLASS_GENERIC_ERROR, "Device '%s' could not be initialized"
 
 #define QERR_DEVICE_IN_USE \
-    ERROR_CLASS_GENERIC_ERROR, "{ 'class': 'DeviceInUse', 'data': { 'device': %s } }"
+    ERROR_CLASS_GENERIC_ERROR, "Device '%s' is in use"
 
 #define QERR_DEVICE_IS_READ_ONLY \
-    ERROR_CLASS_GENERIC_ERROR, "{ 'class': 'DeviceIsReadOnly', 'data': { 'device': %s } }"
+    ERROR_CLASS_GENERIC_ERROR, "Device '%s' is read only"
 
 #define QERR_DEVICE_LOCKED \
-    ERROR_CLASS_GENERIC_ERROR, "{ 'class': 'DeviceLocked', 'data': { 'device': %s } }"
+    ERROR_CLASS_GENERIC_ERROR, "Device '%s' is locked"
 
 #define QERR_DEVICE_MULTIPLE_BUSSES \
-    ERROR_CLASS_GENERIC_ERROR, "{ 'class': 'DeviceMultipleBusses', 'data': { 'device': %s } }"
+    ERROR_CLASS_GENERIC_ERROR, "Device '%s' has multiple child busses"
 
 #define QERR_DEVICE_NO_BUS \
-    ERROR_CLASS_GENERIC_ERROR, "{ 'class': 'DeviceNoBus', 'data': { 'device': %s } }"
+    ERROR_CLASS_GENERIC_ERROR, "Device '%s' has no child bus"
 
 #define QERR_DEVICE_NO_HOTPLUG \
-    ERROR_CLASS_GENERIC_ERROR, "{ 'class': 'DeviceNoHotplug', 'data': { 'device': %s } }"
+    ERROR_CLASS_GENERIC_ERROR, "Device '%s' does not support hotplugging"
 
 #define QERR_DEVICE_NOT_ACTIVE \
-    ERROR_CLASS_DEVICE_NOT_ACTIVE, "{ 'class': 'DeviceNotActive', 'data': { 'device': %s } }"
+    ERROR_CLASS_DEVICE_NOT_ACTIVE, "Device '%s' has not been activated"
 
 #define QERR_DEVICE_NOT_ENCRYPTED \
-    ERROR_CLASS_GENERIC_ERROR, "{ 'class': 'DeviceNotEncrypted', 'data': { 'device': %s } }"
+    ERROR_CLASS_GENERIC_ERROR, "Device '%s' is not encrypted"
 
 #define QERR_DEVICE_NOT_FOUND \
-    ERROR_CLASS_DEVICE_NOT_FOUND, "{ 'class': 'DeviceNotFound', 'data': { 'device': %s } }"
+    ERROR_CLASS_DEVICE_NOT_FOUND, "Device '%s' not found"
 
 #define QERR_DEVICE_NOT_REMOVABLE \
-    ERROR_CLASS_GENERIC_ERROR, "{ 'class': 'DeviceNotRemovable', 'data': { 'device': %s } }"
+    ERROR_CLASS_GENERIC_ERROR, "Device '%s' is not removable"
 
 #define QERR_DUPLICATE_ID \
-    ERROR_CLASS_GENERIC_ERROR, "{ 'class': 'DuplicateId', 'data': { 'id': %s, 'object': %s } }"
+    ERROR_CLASS_GENERIC_ERROR, "Duplicate ID '%s' for %s"
 
 #define QERR_FD_NOT_FOUND \
-    ERROR_CLASS_GENERIC_ERROR, "{ 'class': 'FdNotFound', 'data': { 'name': %s } }"
+    ERROR_CLASS_GENERIC_ERROR, "File descriptor named '%s' not found"
 
 #define QERR_FD_NOT_SUPPLIED \
-    ERROR_CLASS_GENERIC_ERROR, "{ 'class': 'FdNotSupplied', 'data': {} }"
+    ERROR_CLASS_GENERIC_ERROR, "No file descriptor supplied via SCM_RIGHTS"
 
 #define QERR_FEATURE_DISABLED \
-    ERROR_CLASS_GENERIC_ERROR, "{ 'class': 'FeatureDisabled', 'data': { 'name': %s } }"
+    ERROR_CLASS_GENERIC_ERROR, "The feature '%s' is not enabled"
 
 #define QERR_INVALID_BLOCK_FORMAT \
-    ERROR_CLASS_GENERIC_ERROR, "{ 'class': 'InvalidBlockFormat', 'data': { 'name': %s } }"
+    ERROR_CLASS_GENERIC_ERROR, "Invalid block format '%s'"
 
 #define QERR_INVALID_OPTION_GROUP \
-    ERROR_CLASS_GENERIC_ERROR, "{ 'class': 'InvalidOptionGroup', 'data': { 'group': %s } }"
+    ERROR_CLASS_GENERIC_ERROR, "There is no option group '%s'"
 
 #define QERR_INVALID_PARAMETER \
-    ERROR_CLASS_GENERIC_ERROR, "{ 'class': 'InvalidParameter', 'data': { 'name': %s } }"
+    ERROR_CLASS_GENERIC_ERROR, "Invalid parameter '%s'"
 
 #define QERR_INVALID_PARAMETER_COMBINATION \
-    ERROR_CLASS_GENERIC_ERROR, "{ 'class': 'InvalidParameterCombination', 'data': {} }"
+    ERROR_CLASS_GENERIC_ERROR, "Invalid parameter combination"
 
 #define QERR_INVALID_PARAMETER_TYPE \
-    ERROR_CLASS_GENERIC_ERROR, "{ 'class': 'InvalidParameterType', 'data': { 'name': %s,'expected': %s } }"
+    ERROR_CLASS_GENERIC_ERROR, "Invalid parameter type for '%s', expected: %s"
 
 #define QERR_INVALID_PARAMETER_VALUE \
-    ERROR_CLASS_GENERIC_ERROR, "{ 'class': 'InvalidParameterValue', 'data': { 'name': %s, 'expected': %s } }"
+    ERROR_CLASS_GENERIC_ERROR, "Parameter '%s' expects %s"
 
 #define QERR_INVALID_PASSWORD \
-    ERROR_CLASS_GENERIC_ERROR, "{ 'class': 'InvalidPassword', 'data': {} }"
+    ERROR_CLASS_GENERIC_ERROR, "Password incorrect"
 
 #define QERR_IO_ERROR \
-    ERROR_CLASS_GENERIC_ERROR, "{ 'class': 'IOError', 'data': {} }"
+    ERROR_CLASS_GENERIC_ERROR, "An IO error has occurred"
 
 #define QERR_JSON_PARSE_ERROR \
-    ERROR_CLASS_GENERIC_ERROR, "{ 'class': 'JSONParseError', 'data': { 'message': %s } }"
+    ERROR_CLASS_GENERIC_ERROR, "JSON parse error, %s"
 
 #define QERR_JSON_PARSING \
-    ERROR_CLASS_GENERIC_ERROR, "{ 'class': 'JSONParsing', 'data': {} }"
+    ERROR_CLASS_GENERIC_ERROR, "Invalid JSON syntax"
 
 #define QERR_KVM_MISSING_CAP \
-    ERROR_CLASS_K_V_M_MISSING_CAP, "{ 'class': 'KVMMissingCap', 'data': { 'capability': %s, 'feature': %s } }"
+    ERROR_CLASS_K_V_M_MISSING_CAP, "Using KVM without %s, %s unavailable"
 
 #define QERR_MIGRATION_ACTIVE \
-    ERROR_CLASS_GENERIC_ERROR, "{ 'class': 'MigrationActive', 'data': {} }"
+    ERROR_CLASS_GENERIC_ERROR, "There's a migration process in progress"
 
 #define QERR_MIGRATION_NOT_SUPPORTED \
-    ERROR_CLASS_GENERIC_ERROR, "{ 'class': 'MigrationNotSupported', 'data': {'device': %s} }"
+    ERROR_CLASS_GENERIC_ERROR, "State blocked by non-migratable device '%s'"
 
 #define QERR_MIGRATION_EXPECTED \
-    ERROR_CLASS_MIGRATION_EXPECTED, "{ 'class': 'MigrationExpected', 'data': {} }"
+    ERROR_CLASS_MIGRATION_EXPECTED, "An incoming migration is expected before this command can be executed"
 
 #define QERR_MISSING_PARAMETER \
-    ERROR_CLASS_GENERIC_ERROR, "{ 'class': 'MissingParameter', 'data': { 'name': %s } }"
+    ERROR_CLASS_GENERIC_ERROR, "Parameter '%s' is missing"
 
 #define QERR_NO_BUS_FOR_DEVICE \
-    ERROR_CLASS_GENERIC_ERROR, "{ 'class': 'NoBusForDevice', 'data': { 'device': %s, 'bus': %s } }"
+    ERROR_CLASS_GENERIC_ERROR, "No '%s' bus found for device '%s'"
 
 #define QERR_NOT_SUPPORTED \
-    ERROR_CLASS_GENERIC_ERROR, "{ 'class': 'NotSupported', 'data': {} }"
+    ERROR_CLASS_GENERIC_ERROR, "Not supported"
 
 #define QERR_OPEN_FILE_FAILED \
-    ERROR_CLASS_GENERIC_ERROR, "{ 'class': 'OpenFileFailed', 'data': { 'filename': %s } }"
+    ERROR_CLASS_GENERIC_ERROR, "Could not open '%s'"
 
 #define QERR_PERMISSION_DENIED \
-    ERROR_CLASS_GENERIC_ERROR, "{ 'class': 'PermissionDenied', 'data': {} }"
+    ERROR_CLASS_GENERIC_ERROR, "Insufficient permission to perform this operation"
 
 #define QERR_PROPERTY_NOT_FOUND \
-    ERROR_CLASS_GENERIC_ERROR, "{ 'class': 'PropertyNotFound', 'data': { 'device': %s, 'property': %s } }"
+    ERROR_CLASS_GENERIC_ERROR, "Property '%s.%s' not found"
 
 #define QERR_PROPERTY_VALUE_BAD \
-    ERROR_CLASS_GENERIC_ERROR, "{ 'class': 'PropertyValueBad', 'data': { 'device': %s, 'property': %s, 'value': %s } }"
+    ERROR_CLASS_GENERIC_ERROR, "Property '%s.%s' doesn't take value '%s'"
 
 #define QERR_PROPERTY_VALUE_IN_USE \
-    ERROR_CLASS_GENERIC_ERROR, "{ 'class': 'PropertyValueInUse', 'data': { 'device': %s, 'property': %s, 'value': %s } }"
+    ERROR_CLASS_GENERIC_ERROR, "Property '%s.%s' can't take value '%s', it's in use"
 
 #define QERR_PROPERTY_VALUE_NOT_FOUND \
-    ERROR_CLASS_GENERIC_ERROR, "{ 'class': 'PropertyValueNotFound', 'data': { 'device': %s, 'property': %s, 'value': %s } }"
+    ERROR_CLASS_GENERIC_ERROR, "Property '%s.%s' can't find value '%s'"
 
 #define QERR_PROPERTY_VALUE_NOT_POWER_OF_2 \
-    ERROR_CLASS_GENERIC_ERROR, "{ 'class': 'PropertyValueNotPowerOf2', 'data': { " \
-    "'device': %s, 'property': %s, 'value': %"PRId64" } }"
+    ERROR_CLASS_GENERIC_ERROR, "Property %s.%s doesn't take value '%" PRId64 "', it's not a power of 2"
 
 #define QERR_PROPERTY_VALUE_OUT_OF_RANGE \
-    ERROR_CLASS_GENERIC_ERROR, "{ 'class': 'PropertyValueOutOfRange', 'data': { 'device': %s, 'property': %s, 'value': %"PRId64", 'min': %"PRId64", 'max': %"PRId64" } }"
+    ERROR_CLASS_GENERIC_ERROR, "Property %s.%s doesn't take value %" PRId64 " (minimum: %" PRId64 ", maximum: %" PRId64 ")"
 
 #define QERR_QGA_COMMAND_FAILED \
-    ERROR_CLASS_GENERIC_ERROR, "{ 'class': 'QgaCommandFailed', 'data': { 'message': %s } }"
+    ERROR_CLASS_GENERIC_ERROR, "Guest agent command failed, error was '%s'"
 
 #define QERR_QGA_LOGGING_FAILED \
-    ERROR_CLASS_GENERIC_ERROR, "{ 'class': 'QgaLoggingFailed', 'data': {} }"
+    ERROR_CLASS_GENERIC_ERROR, "Guest agent failed to log non-optional log statement"
 
 #define QERR_QMP_BAD_INPUT_OBJECT \
-    ERROR_CLASS_GENERIC_ERROR, "{ 'class': 'QMPBadInputObject', 'data': { 'expected': %s } }"
+    ERROR_CLASS_GENERIC_ERROR, "Expected '%s' in QMP input"
 
 #define QERR_QMP_BAD_INPUT_OBJECT_MEMBER \
-    ERROR_CLASS_GENERIC_ERROR, "{ 'class': 'QMPBadInputObjectMember', 'data': { 'member': %s, 'expected': %s } }"
+    ERROR_CLASS_GENERIC_ERROR, "QMP input object member '%s' expects '%s'"
 
 #define QERR_QMP_EXTRA_MEMBER \
-    ERROR_CLASS_GENERIC_ERROR, "{ 'class': 'QMPExtraInputObjectMember', 'data': { 'member': %s } }"
+    ERROR_CLASS_GENERIC_ERROR, "QMP input object member '%s' is unexpected"
 
 #define QERR_RESET_REQUIRED \
-    ERROR_CLASS_GENERIC_ERROR, "{ 'class': 'ResetRequired', 'data': {} }"
+    ERROR_CLASS_GENERIC_ERROR, "Resetting the Virtual Machine is required"
 
 #define QERR_SET_PASSWD_FAILED \
-    ERROR_CLASS_GENERIC_ERROR, "{ 'class': 'SetPasswdFailed', 'data': {} }"
+    ERROR_CLASS_GENERIC_ERROR, "Could not set password"
 
 #define QERR_TOO_MANY_FILES \
-    ERROR_CLASS_GENERIC_ERROR, "{ 'class': 'TooManyFiles', 'data': {} }"
+    ERROR_CLASS_GENERIC_ERROR, "Too many open files"
 
 #define QERR_UNDEFINED_ERROR \
-    ERROR_CLASS_GENERIC_ERROR, "{ 'class': 'UndefinedError', 'data': {} }"
+    ERROR_CLASS_GENERIC_ERROR, "An undefined error has occurred"
 
 #define QERR_UNKNOWN_BLOCK_FORMAT_FEATURE \
-    ERROR_CLASS_GENERIC_ERROR, "{ 'class': 'UnknownBlockFormatFeature', 'data': { 'device': %s, 'format': %s, 'feature': %s } }"
+    ERROR_CLASS_GENERIC_ERROR, "'%s' uses a %s feature which is not supported by this qemu version: %s"
 
 #define QERR_UNSUPPORTED \
-    ERROR_CLASS_GENERIC_ERROR, "{ 'class': 'Unsupported', 'data': {} }"
+    ERROR_CLASS_GENERIC_ERROR, "this feature or command is not currently supported"
 
 #define QERR_VIRTFS_FEATURE_BLOCKS_MIGRATION \
-    ERROR_CLASS_GENERIC_ERROR, "{ 'class': 'VirtFSFeatureBlocksMigration', 'data': { 'path': %s, 'tag': %s } }"
+    ERROR_CLASS_GENERIC_ERROR, "Migration is disabled when VirtFS export path '%s' is mounted in the guest using mount_tag '%s'"
 
 #define QERR_VNC_SERVER_FAILED \
-    ERROR_CLASS_GENERIC_ERROR, "{ 'class': 'VNCServerFailed', 'data': { 'target': %s } }"
+    ERROR_CLASS_GENERIC_ERROR, "Could not start VNC server on %s"
 
 #define QERR_SOCKET_CONNECT_FAILED \
-    ERROR_CLASS_GENERIC_ERROR, "{ 'class': 'SockConnectFailed', 'data': {} }"
+    ERROR_CLASS_GENERIC_ERROR, "Failed to connect to socket"
 
 #define QERR_SOCKET_LISTEN_FAILED \
-    ERROR_CLASS_GENERIC_ERROR, "{ 'class': 'SockListenFailed', 'data': {} }"
+    ERROR_CLASS_GENERIC_ERROR, "Failed to set socket to listening mode"
 
 #define QERR_SOCKET_BIND_FAILED \
-    ERROR_CLASS_GENERIC_ERROR, "{ 'class': 'SockBindFailed', 'data': {} }"
+    ERROR_CLASS_GENERIC_ERROR, "Failed to bind socket"
 
 #define QERR_SOCKET_CREATE_FAILED \
-    ERROR_CLASS_GENERIC_ERROR, "{ 'class': 'SockCreateFailed', 'data': {} }"
+    ERROR_CLASS_GENERIC_ERROR, "Failed to create socket"
 
 #endif /* QERROR_H */
commit 7795b166d9d1e2b33d428f5acab6d0d5e617ee91
Author: Luiz Capitulino <lcapitulino at redhat.com>
Date:   Wed Aug 1 17:59:59 2012 -0300

    error: drop error_get_qobject()/error_set_qobject()
    
    error_get_qobject() is unused since last commit, error_set_qobject()
    has never been used. Also drops error_int.h.
    
    Signed-off-by: Luiz Capitulino <lcapitulino at redhat.com>
    Reviewed-by: Markus Armbruster <armbru at redhat.com>

diff --git a/error.c b/error.c
index b1d5131..9d7b35f 100644
--- a/error.c
+++ b/error.c
@@ -15,7 +15,6 @@
 #include "qjson.h"
 #include "qdict.h"
 #include "qapi-types.h"
-#include "error_int.h"
 #include "qerror.h"
 
 struct Error
@@ -91,22 +90,3 @@ void error_propagate(Error **dst_err, Error *local_err)
         error_free(local_err);
     }
 }
-
-QObject *error_get_qobject(Error *err)
-{
-    QINCREF(err->obj);
-    return QOBJECT(err->obj);
-}
-
-void error_set_qobject(Error **errp, QObject *obj)
-{
-    Error *err;
-    if (errp == NULL) {
-        return;
-    }
-    err = g_malloc0(sizeof(*err));
-    err->obj = qobject_to_qdict(obj);
-    qobject_incref(obj);
-
-    *errp = err;
-}
diff --git a/error_int.h b/error_int.h
deleted file mode 100644
index 4b00d08..0000000
--- a/error_int.h
+++ /dev/null
@@ -1,28 +0,0 @@
-/*
- * QEMU Error Objects
- *
- * Copyright IBM, Corp. 2011
- *
- * Authors:
- *  Anthony Liguori   <aliguori at us.ibm.com>
- *
- * This work is licensed under the terms of the GNU LGPL, version 2.  See
- * the COPYING.LIB file in the top-level directory.
- */
-#ifndef QEMU_ERROR_INT_H
-#define QEMU_ERROR_INT_H
-
-#include "qemu-common.h"
-#include "qobject.h"
-#include "qdict.h"
-#include "error.h"
-
-/**
- * Internal QEMU functions for working with Error.
- *
- * These are used to convert QErrors to Errors
- */
-QObject *error_get_qobject(Error *err);
-void error_set_qobject(Error **errp, QObject *obj);
-  
-#endif
diff --git a/qapi/qmp-dispatch.c b/qapi/qmp-dispatch.c
index ec613f8..4085994 100644
--- a/qapi/qmp-dispatch.c
+++ b/qapi/qmp-dispatch.c
@@ -16,7 +16,6 @@
 #include "json-parser.h"
 #include "qapi-types.h"
 #include "error.h"
-#include "error_int.h"
 #include "qerror.h"
 
 static QDict *qmp_dispatch_check_obj(const QObject *request, Error **errp)
diff --git a/qemu-ga.c b/qemu-ga.c
index 39abc50..8f87621 100644
--- a/qemu-ga.c
+++ b/qemu-ga.c
@@ -28,7 +28,6 @@
 #include "module.h"
 #include "signal.h"
 #include "qerror.h"
-#include "error_int.h"
 #include "qapi/qmp-core.h"
 #include "qga/channel.h"
 #ifdef _WIN32
commit 93b91c59dbccde6e4d25661150c1529bd5ee4a06
Author: Luiz Capitulino <lcapitulino at redhat.com>
Date:   Wed Aug 1 16:30:13 2012 -0300

    qemu-ga: switch to the new error format on the wire
    
    IMPORTANT: this BREAKS qemu-ga compatibility for the error response.
    
    Instead of returning something like:
    
    { "error": { "class": "InvalidParameterValue",
                 "data": {"name": "mode", "expected": "halt|powerdown|reboot" } } }
    
    qemu-ga now returns:
    
     { "error": { "class": "GenericError",
                  "desc": "Parameter 'mode' expects halt|powerdown|reboot" } }
    
    Notice that this is also a bug fix, as qemu-ga wasn't returning the
    human message.
    
    Signed-off-by: Luiz Capitulino <lcapitulino at redhat.com>
    Reviewed-by: Markus Armbruster <armbru at redhat.com>

diff --git a/Makefile.objs b/Makefile.objs
index 5ebbcfa..8454b53 100644
--- a/Makefile.objs
+++ b/Makefile.objs
@@ -211,6 +211,7 @@ common-obj-$(CONFIG_SMARTCARD_NSS) += $(libcacard-y)
 # qapi
 
 qapi-obj-y = qapi/
+qapi-obj-y += qapi-types.o qapi-visit.o
 
 common-obj-y += qmp-marshal.o qapi-visit.o qapi-types.o
 common-obj-y += qmp.o hmp.o
diff --git a/qapi/qmp-core.h b/qapi/qmp-core.h
index b0f64ba..00446cf 100644
--- a/qapi/qmp-core.h
+++ b/qapi/qmp-core.h
@@ -49,6 +49,7 @@ void qmp_disable_command(const char *name);
 void qmp_enable_command(const char *name);
 bool qmp_command_is_enabled(const char *name);
 char **qmp_get_command_list(void);
+QObject *qmp_build_error_object(Error *errp);
 
 #endif
 
diff --git a/qapi/qmp-dispatch.c b/qapi/qmp-dispatch.c
index 122c1a2..ec613f8 100644
--- a/qapi/qmp-dispatch.c
+++ b/qapi/qmp-dispatch.c
@@ -14,6 +14,7 @@
 #include "qemu-objects.h"
 #include "qapi/qmp-core.h"
 #include "json-parser.h"
+#include "qapi-types.h"
 #include "error.h"
 #include "error_int.h"
 #include "qerror.h"
@@ -109,6 +110,13 @@ static QObject *do_qmp_dispatch(QObject *request, Error **errp)
     return ret;
 }
 
+QObject *qmp_build_error_object(Error *errp)
+{
+    return qobject_from_jsonf("{ 'class': %s, 'desc': %s }",
+                              ErrorClass_lookup[error_get_class(errp)],
+                              error_get_pretty(errp));
+}
+
 QObject *qmp_dispatch(QObject *request)
 {
     Error *err = NULL;
@@ -119,7 +127,7 @@ QObject *qmp_dispatch(QObject *request)
 
     rsp = qdict_new();
     if (err) {
-        qdict_put_obj(rsp, "error", error_get_qobject(err));
+        qdict_put_obj(rsp, "error", qmp_build_error_object(err));
         error_free(err);
     } else if (ret) {
         qdict_put_obj(rsp, "return", ret);
diff --git a/qemu-ga.c b/qemu-ga.c
index f1a39ec..39abc50 100644
--- a/qemu-ga.c
+++ b/qemu-ga.c
@@ -515,7 +515,7 @@ static void process_event(JSONMessageParser *parser, QList *tokens)
         } else {
             g_warning("failed to parse event: %s", error_get_pretty(err));
         }
-        qdict_put_obj(qdict, "error", error_get_qobject(err));
+        qdict_put_obj(qdict, "error", qmp_build_error_object(err));
         error_free(err);
     } else {
         qdict = qobject_to_qdict(obj);
@@ -532,7 +532,7 @@ static void process_event(JSONMessageParser *parser, QList *tokens)
             qdict = qdict_new();
             g_warning("unrecognized payload format");
             error_set(&err, QERR_UNSUPPORTED);
-            qdict_put_obj(qdict, "error", error_get_qobject(err));
+            qdict_put_obj(qdict, "error", qmp_build_error_object(err));
             error_free(err);
         }
         ret = send_response(s, QOBJECT(qdict));
commit de253f14912e88f45dbe66984440d27221a75a60
Author: Luiz Capitulino <lcapitulino at redhat.com>
Date:   Fri Jul 27 16:18:16 2012 -0300

    qmp: switch to the new error format on the wire
    
    IMPORTANT: this BREAKS QMP's compatibility for the error response.
    
    This commit changes QMP's wire protocol to make use of the simpler
    error format introduced by previous commits.
    
    There are two important (and mostly incompatible) changes:
    
     1. Almost all error classes have been replaced by GenericError. The
        only classes that are still supported for compatibility with
        libvirt are: CommandNotFound, DeviceNotActive, KVMMissingCap,
        DeviceNotFound and MigrationExpected
    
     2. The 'data' field of the error dictionary is gone
    
    As an example, an error response like:
    
      { "error": { "class": "DeviceNotRemovable",
                   "data": { "device": "virtio0" },
                   "desc": "Device 'virtio0' is not removable" } }
    
    Will now be emitted as:
    
      { "error": { "class": "GenericError",
                   "desc": "Device 'virtio0' is not removable" } }
    
    Signed-off-by: Luiz Capitulino <lcapitulino at redhat.com>
    Reviewed-by: Markus Armbruster <armbru at redhat.com>

diff --git a/QMP/qmp-spec.txt b/QMP/qmp-spec.txt
index 1ba916c..a277896 100644
--- a/QMP/qmp-spec.txt
+++ b/QMP/qmp-spec.txt
@@ -106,14 +106,11 @@ completed because of an error condition.
 
 The format is:
 
-{ "error": { "class": json-string, "data": json-object, "desc": json-string },
-  "id": json-value }
+{ "error": { "class": json-string, "desc": json-string }, "id": json-value }
 
  Where,
 
-- The "class" member contains the error class name (eg. "ServiceUnavailable")
-- The "data" member contains specific error data and is defined in a
-  per-command basis, it will be an empty json-object if the error has no data
+- The "class" member contains the error class name (eg. "GenericError")
 - The "desc" member is a human-readable error message. Clients should
   not attempt to parse this message.
 - The "id" member contains the transaction identification associated with
@@ -173,8 +170,7 @@ S: {"return": {"enabled": true, "present": true}, "id": "example"}
 ------------------
 
 C: { "execute": }
-S: {"error": {"class": "JSONParsing", "desc": "Invalid JSON syntax", "data":
-{}}}
+S: {"error": {"class": "GenericError", "desc": "Invalid JSON syntax" } }
 
 3.5 Powerdown event
 -------------------
diff --git a/monitor.c b/monitor.c
index aa57167..3694590 100644
--- a/monitor.c
+++ b/monitor.c
@@ -353,16 +353,26 @@ static void monitor_json_emitter(Monitor *mon, const QObject *data)
     QDECREF(json);
 }
 
+static QDict *build_qmp_error_dict(const QError *err)
+{
+    QObject *obj;
+
+    obj = qobject_from_jsonf("{ 'error': { 'class': %s, 'desc': %p } }",
+                             ErrorClass_lookup[err->err_class],
+                             qerror_human(err));
+
+    return qobject_to_qdict(obj);
+}
+
 static void monitor_protocol_emitter(Monitor *mon, QObject *data)
 {
     QDict *qmp;
 
     trace_monitor_protocol_emitter(mon);
 
-    qmp = qdict_new();
-
     if (!monitor_has_error(mon)) {
         /* success response */
+        qmp = qdict_new();
         if (data) {
             qobject_incref(data);
             qdict_put_obj(qmp, "return", data);
@@ -372,9 +382,7 @@ static void monitor_protocol_emitter(Monitor *mon, QObject *data)
         }
     } else {
         /* error response */
-        qdict_put(mon->error->error, "desc", qerror_human(mon->error));
-        qdict_put(qmp, "error", mon->error->error);
-        QINCREF(mon->error->error);
+        qmp = build_qmp_error_dict(mon->error);
         QDECREF(mon->error);
         mon->error = NULL;
     }
diff --git a/qapi-schema.json b/qapi-schema.json
index b513935..ec8d919 100644
--- a/qapi-schema.json
+++ b/qapi-schema.json
@@ -658,7 +658,6 @@
 # Returns information about the current VNC server
 #
 # Returns: @VncInfo
-#          If VNC support is not compiled in, FeatureDisabled
 #
 # Since: 0.14.0
 ##
@@ -1042,9 +1041,6 @@
 #                       virtual address (defaults to CPU 0)
 #
 # Returns: Nothing on success
-#          If @cpu is not a valid VCPU, InvalidParameterValue
-#          If @filename cannot be opened, OpenFileFailed
-#          If an I/O error occurs while writing the file, IOError
 #
 # Since: 0.14.0
 #
@@ -1065,8 +1061,6 @@
 # @filename: the file to save the memory to as binary data
 #
 # Returns: Nothing on success
-#          If @filename cannot be opened, OpenFileFailed
-#          If an I/O error occurs while writing the file, IOError
 #
 # Since: 0.14.0
 #
@@ -1108,7 +1102,6 @@
 # Injects an Non-Maskable Interrupt into all guest's VCPUs.
 #
 # Returns:  If successful, nothing
-#           If the Virtual Machine doesn't support NMI injection, Unsupported
 #
 # Since:  0.14.0
 #
@@ -1159,7 +1152,6 @@
 # Returns: nothing on success
 #          If @device is not a valid block device, DeviceNotFound
 #          If @device is not encrypted, DeviceNotEncrypted
-#          If @password is not valid for this device, InvalidPassword
 #
 # Notes:  Not all block formats support encryption and some that do are not
 #         able to validate that a password is correct.  Disk corruption may
@@ -1200,11 +1192,6 @@
 #
 # Returns: nothing on success
 #          If @device is not a valid block device, DeviceNotFound
-#          If @size is negative, InvalidParameterValue
-#          If the block device has no medium inserted, DeviceHasNoMedium
-#          If the block device does not support resize, Unsupported
-#          If the block device is read-only, DeviceIsReadOnly
-#          If a long-running operation is using the device, DeviceInUse
 #
 # Since: 0.14.0
 ##
@@ -1266,10 +1253,6 @@
 #
 # Returns: nothing on success
 #          If @device is not a valid block device, DeviceNotFound
-#          If @device is busy, DeviceInUse will be returned
-#          If @snapshot-file can't be created, OpenFileFailed
-#          If @snapshot-file can't be opened, OpenFileFailed
-#          If @format is invalid, InvalidBlockFormat
 #
 # Note: The transaction aborts on the first failure.  Therefore, there will
 # be only one device or snapshot file returned in an error condition, and
@@ -1298,8 +1281,6 @@
 #
 # Returns: nothing on success
 #          If @device is not a valid block device, DeviceNotFound
-#          If @snapshot-file can't be opened, OpenFileFailed
-#          If @format is invalid, InvalidBlockFormat
 #
 # Since 0.14.0
 ##
@@ -1501,11 +1482,6 @@
 #
 # Returns: Nothing on success
 #          If Spice is not enabled, DeviceNotFound
-#          If @protocol does not support connected, InvalidParameter
-#          If @protocol is invalid, InvalidParameter
-#          If any other error occurs, SetPasswdFailed
-#
-# Notes: If VNC is not enabled, SetPasswdFailed is returned.
 #
 # Since: 0.14.0
 ##
@@ -1527,8 +1503,6 @@
 #
 # Returns: Nothing on success
 #          If @protocol is `spice' and Spice is not active, DeviceNotFound
-#          If an error occurs setting password expiration, SetPasswdFailed
-#          If @protocol is not `spice' or 'vnc', InvalidParameter
 #
 # Since: 0.14.0
 #
@@ -1551,8 +1525,6 @@
 #
 # Returns:  Nothing on success
 #           If @device is not a valid block device, DeviceNotFound
-#           If @device is not removable and @force is false, DeviceNotRemovable
-#           If @force is false and @device is locked, DeviceLocked
 #
 # Notes:    Ejecting a device will no media results in success
 #
@@ -1595,7 +1567,6 @@
 #
 # Returns: Nothing on success.
 #          If @device is not a valid block device, DeviceNotFound
-#          If @format is not a valid block format, InvalidBlockFormat
 #          If the new block device is encrypted, DeviceEncrypted.  Note that
 #          if this error is returned, the device has been opened successfully
 #          and an additional call to @block_passwd is required to set the
@@ -1631,7 +1602,6 @@
 #
 # Returns: Nothing on success
 #          If @device is not a valid block device, DeviceNotFound
-#          If the argument combination is invalid, InvalidParameterCombination
 #
 # Since: 1.1
 ##
@@ -1665,11 +1635,7 @@
 # @speed:  #optional the maximum speed, in bytes per second
 #
 # Returns: Nothing on success
-#          If streaming is already active on this device, DeviceInUse
 #          If @device does not exist, DeviceNotFound
-#          If image streaming is not supported by this device, NotSupported
-#          If @base does not exist, BaseNotFound
-#          If @speed is invalid, InvalidParameter
 #
 # Since: 1.1
 ##
@@ -1691,8 +1657,6 @@
 #          Defaults to 0.
 #
 # Returns: Nothing on success
-#          If the job type does not support throttling, NotSupported
-#          If the speed value is invalid, InvalidParameter
 #          If no background operation is active on this device, DeviceNotActive
 #
 # Since: 1.1
@@ -1722,7 +1686,6 @@
 #
 # Returns: Nothing on success
 #          If no background operation is active on this device, DeviceNotActive
-#          If cancellation already in progress, DeviceInUse
 #
 # Since: 1.1
 ##
@@ -1792,8 +1755,6 @@
 # format.
 #
 # Returns: Nothing on success
-#          If @filename cannot be opened, OpenFileFailed
-#          If an I/O error occurs while writing the file, IOError
 #
 # Since: 1.1
 ##
@@ -1808,7 +1769,6 @@
 #
 # Returns: Nothing on success
 #          If @id is not a valid device, DeviceNotFound
-#          If the device does not support unplug, BusNoHotplug
 #
 # Notes: When this command completes, the device may not be removed from the
 #        guest.  Hot removal is an operation that requires guest cooperation.
@@ -1849,14 +1809,6 @@
 # want to dump all guest's memory, please specify the start @begin and @length
 #
 # Returns: nothing on success
-#          If @begin contains an invalid address, InvalidParameter
-#          If only one of @begin and @length is specified, MissingParameter
-#          If @protocol stats with "fd:", and the fd cannot be found, FdNotFound
-#          If @protocol starts with "file:", and the file cannot be
-#             opened, OpenFileFailed
-#          If @protocol does not start with "fd:" or "file:", InvalidParameter
-#          If an I/O error occurs while writing the file, IOError
-#          If the target does not support this command, Unsupported
 #
 # Since: 1.2
 ##
@@ -1883,10 +1835,6 @@
 #
 # Returns: Nothing on success
 #          If @type is not a valid network backend, DeviceNotFound
-#          If @id is not a valid identifier, InvalidParameterValue
-#          if @id already exists, DuplicateId
-#          If @props contains an invalid parameter for this backend,
-#            InvalidParameter
 ##
 { 'command': 'netdev_add',
   'data': {'type': 'str', 'id': 'str', '*props': '**'},
@@ -2206,8 +2154,6 @@
 # @fdname: file descriptor name
 #
 # Returns: Nothing on success
-#          If file descriptor was not received, FdNotSupplied
-#          If @fdname is not valid, InvalidParameterType
 #
 # Since: 0.14.0
 #
@@ -2227,7 +2173,6 @@
 # @fdname: file descriptor name
 #
 # Returns: Nothing on success
-#          If @fdname is not found, FdNotFound
 #
 # Since: 0.14.0
 ##
diff --git a/qmp-commands.hx b/qmp-commands.hx
index ac46638..e07c7b0 100644
--- a/qmp-commands.hx
+++ b/qmp-commands.hx
@@ -435,8 +435,8 @@ Example:
 -> { "execute": "inject-nmi" }
 <- { "return": {} }
 
-Note: inject-nmi is only supported for x86 guest currently, it will
-      returns "Unsupported" error for non-x86 guest.
+Note: inject-nmi fails when the guest doesn't support injecting.
+      Currently, only x86 guests do.
 
 EQMP
 
commit a8cb2d302ea20d7ba1be184973fef29d7cab9407
Author: Luiz Capitulino <lcapitulino at redhat.com>
Date:   Thu Jul 26 21:30:40 2012 -0300

    error: drop unused functions
    
    Besides being unused, they operate on the current error format,
    which is going to be replaced soon.
    
    Signed-off-by: Luiz Capitulino <lcapitulino at redhat.com>
    Reviewed-by: Markus Armbruster <armbru at redhat.com>

diff --git a/error.c b/error.c
index 2d34cde..b1d5131 100644
--- a/error.c
+++ b/error.c
@@ -74,29 +74,6 @@ const char *error_get_pretty(Error *err)
     return err->msg;
 }
 
-const char *error_get_field(Error *err, const char *field)
-{
-    if (strcmp(field, "class") == 0) {
-        return qdict_get_str(err->obj, field);
-    } else {
-        QDict *dict = qdict_get_qdict(err->obj, "data");
-        return qdict_get_str(dict, field);
-    }
-}
-
-QDict *error_get_data(Error *err)
-{
-    QDict *data = qdict_get_qdict(err->obj, "data");
-    QINCREF(data);
-    return data;
-}
-
-void error_set_field(Error *err, const char *field, const char *value)
-{
-    QDict *dict = qdict_get_qdict(err->obj, "data");
-    qdict_put(dict, field, qstring_from_str(value));
-}
-
 void error_free(Error *err)
 {
     if (err) {
@@ -106,31 +83,6 @@ void error_free(Error *err)
     }
 }
 
-bool error_is_type(Error *err, ErrorClass err_class, const char *fmt)
-{
-    const char *error_class;
-    char *ptr;
-    char *end;
-
-    if (!err) {
-        return false;
-    }
-
-    ptr = strstr(fmt, "'class': '");
-    assert(ptr != NULL);
-    ptr += strlen("'class': '");
-
-    end = strchr(ptr, '\'');
-    assert(end != NULL);
-
-    error_class = error_get_field(err, "class");
-    if (strlen(error_class) != end - ptr) {
-        return false;
-    }
-
-    return strncmp(ptr, error_class, end - ptr) == 0;
-}
-
 void error_propagate(Error **dst_err, Error *local_err)
 {
     if (dst_err && !*dst_err) {
diff --git a/error.h b/error.h
index 114e24b..5336fc5 100644
--- a/error.h
+++ b/error.h
@@ -51,16 +51,6 @@ Error *error_copy(const Error *err);
 const char *error_get_pretty(Error *err);
 
 /**
- * Get an individual named error field.
- */
-const char *error_get_field(Error *err, const char *field);
-
-/**
- * Get an individual named error field.
- */
-void error_set_field(Error *err, const char *field, const char *value);
-
-/**
  * Propagate an error to an indirect pointer to an error.  This function will
  * always transfer ownership of the error reference and handles the case where
  * dst_err is NULL correctly.  Errors after the first are discarded.
@@ -72,10 +62,4 @@ void error_propagate(Error **dst_err, Error *local_err);
  */
 void error_free(Error *err);
 
-/**
- * Determine if an error is of a speific type (based on the qerror format).
- * Non-QEMU users should get the `class' field to identify the error type.
- */
-bool error_is_type(Error *err, ErrorClass err_class, const char *fmt);
-
 #endif
diff --git a/error_int.h b/error_int.h
index 5e39424..4b00d08 100644
--- a/error_int.h
+++ b/error_int.h
@@ -22,7 +22,6 @@
  *
  * These are used to convert QErrors to Errors
  */
-QDict *error_get_data(Error *err);
 QObject *error_get_qobject(Error *err);
 void error_set_qobject(Error **errp, QObject *obj);
   
commit ab878ddfeee722db8e7f78a9c6e9882864c2fd66
Author: Luiz Capitulino <lcapitulino at redhat.com>
Date:   Mon Aug 6 15:55:22 2012 -0300

    hmp: hmp_change(): use error_get_class()
    
    The error_is_type() function is going to be dropped.
    
    Signed-off-by: Luiz Capitulino <lcapitulino at redhat.com>
    Reviewed-by: Markus Armbruster <armbru at redhat.com>

diff --git a/hmp.c b/hmp.c
index 54c37d7..9b44dfc 100644
--- a/hmp.c
+++ b/hmp.c
@@ -793,7 +793,8 @@ void hmp_change(Monitor *mon, const QDict *qdict)
     }
 
     qmp_change(device, target, !!arg, arg, &err);
-    if (error_is_type(err, QERR_DEVICE_ENCRYPTED)) {
+    if (error_is_set(&err) &&
+        error_get_class(err) == ERROR_CLASS_DEVICE_ENCRYPTED) {
         error_free(err);
         monitor_read_block_device_key(mon, device, NULL, NULL);
         return;
commit ea25fbca88b223877c45c776b6c0e17e0247439f
Author: Luiz Capitulino <lcapitulino at redhat.com>
Date:   Wed Aug 1 16:29:38 2012 -0300

    error: add error_get_class()
    
    Signed-off-by: Luiz Capitulino <lcapitulino at redhat.com>
    Reviewed-by: Markus Armbruster <armbru at redhat.com>

diff --git a/error.c b/error.c
index 648706a..2d34cde 100644
--- a/error.c
+++ b/error.c
@@ -64,6 +64,11 @@ bool error_is_set(Error **errp)
     return (errp && *errp);
 }
 
+ErrorClass error_get_class(const Error *err)
+{
+    return err->err_class;
+}
+
 const char *error_get_pretty(Error *err)
 {
     return err->msg;
diff --git a/error.h b/error.h
index 9678752..114e24b 100644
--- a/error.h
+++ b/error.h
@@ -35,6 +35,11 @@ void error_set(Error **err, ErrorClass err_class, const char *fmt, ...) GCC_FMT_
  */
 bool error_is_set(Error **err);
 
+/*
+ * Get the error class of an error object.
+ */
+ErrorClass error_get_class(const Error *err);
+
 /**
  * Returns an exact copy of the error passed as an argument.
  */
commit 0f32cf6abcea8006fbf1f9c9bc8bc5bedcf6e431
Author: Luiz Capitulino <lcapitulino at redhat.com>
Date:   Fri Jul 27 15:50:19 2012 -0300

    qerror: add proper ErrorClass value for QERR_ macros
    
    This commit replaces the place holder value for the ErrorClass
    argument with a proper ErrorClass value for all QERR_ macros.
    
    All current errors are mapped to GenericError, except for errors
    CommandNotFound, DeviceEncrypted, DeviceNotActive, DeviceNotFound,
    KVMMissingCap and MigrationExpected, which are maintained as they
    are today.
    
    Signed-off-by: Luiz Capitulino <lcapitulino at redhat.com>
    Reviewed-by: Markus Armbruster <armbru at redhat.com>

diff --git a/qerror.h b/qerror.h
index bcc93f8..4f92218 100644
--- a/qerror.h
+++ b/qerror.h
@@ -45,214 +45,214 @@ char *qerror_format(const char *fmt, QDict *error);
  * Use scripts/check-qerror.sh to check.
  */
 #define QERR_ADD_CLIENT_FAILED \
-    -1, "{ 'class': 'AddClientFailed', 'data': {} }"
+    ERROR_CLASS_GENERIC_ERROR, "{ 'class': 'AddClientFailed', 'data': {} }"
 
 #define QERR_AMBIGUOUS_PATH \
-    -1, "{ 'class': 'AmbiguousPath', 'data': { 'path': %s } }"
+    ERROR_CLASS_GENERIC_ERROR, "{ 'class': 'AmbiguousPath', 'data': { 'path': %s } }"
 
 #define QERR_BAD_BUS_FOR_DEVICE \
-    -1, "{ 'class': 'BadBusForDevice', 'data': { 'device': %s, 'bad_bus_type': %s } }"
+    ERROR_CLASS_GENERIC_ERROR, "{ 'class': 'BadBusForDevice', 'data': { 'device': %s, 'bad_bus_type': %s } }"
 
 #define QERR_BASE_NOT_FOUND \
-    -1, "{ 'class': 'BaseNotFound', 'data': { 'base': %s } }"
+    ERROR_CLASS_GENERIC_ERROR, "{ 'class': 'BaseNotFound', 'data': { 'base': %s } }"
 
 #define QERR_BLOCK_FORMAT_FEATURE_NOT_SUPPORTED \
-    -1, "{ 'class': 'BlockFormatFeatureNotSupported', 'data': { 'format': %s, 'name': %s, 'feature': %s } }"
+    ERROR_CLASS_GENERIC_ERROR, "{ 'class': 'BlockFormatFeatureNotSupported', 'data': { 'format': %s, 'name': %s, 'feature': %s } }"
 
 #define QERR_BUFFER_OVERRUN \
-    -1, "{ 'class': 'BufferOverrun', 'data': {} }"
+    ERROR_CLASS_GENERIC_ERROR, "{ 'class': 'BufferOverrun', 'data': {} }"
 
 #define QERR_BUS_NO_HOTPLUG \
-    -1, "{ 'class': 'BusNoHotplug', 'data': { 'bus': %s } }"
+    ERROR_CLASS_GENERIC_ERROR, "{ 'class': 'BusNoHotplug', 'data': { 'bus': %s } }"
 
 #define QERR_BUS_NOT_FOUND \
-    -1, "{ 'class': 'BusNotFound', 'data': { 'bus': %s } }"
+    ERROR_CLASS_GENERIC_ERROR, "{ 'class': 'BusNotFound', 'data': { 'bus': %s } }"
 
 #define QERR_COMMAND_DISABLED \
-    -1, "{ 'class': 'CommandDisabled', 'data': { 'name': %s } }"
+    ERROR_CLASS_GENERIC_ERROR, "{ 'class': 'CommandDisabled', 'data': { 'name': %s } }"
 
 #define QERR_COMMAND_NOT_FOUND \
-    -1, "{ 'class': 'CommandNotFound', 'data': { 'name': %s } }"
+    ERROR_CLASS_COMMAND_NOT_FOUND, "{ 'class': 'CommandNotFound', 'data': { 'name': %s } }"
 
 #define QERR_DEVICE_ENCRYPTED \
-    -1, "{ 'class': 'DeviceEncrypted', 'data': { 'device': %s, 'filename': %s } }"
+    ERROR_CLASS_DEVICE_ENCRYPTED, "{ 'class': 'DeviceEncrypted', 'data': { 'device': %s, 'filename': %s } }"
 
 #define QERR_DEVICE_FEATURE_BLOCKS_MIGRATION \
-    -1, "{ 'class': 'DeviceFeatureBlocksMigration', 'data': { 'device': %s, 'feature': %s } }"
+    ERROR_CLASS_GENERIC_ERROR, "{ 'class': 'DeviceFeatureBlocksMigration', 'data': { 'device': %s, 'feature': %s } }"
 
 #define QERR_DEVICE_HAS_NO_MEDIUM \
-    -1, "{ 'class': 'DeviceHasNoMedium', 'data': { 'device': %s } }"
+    ERROR_CLASS_GENERIC_ERROR, "{ 'class': 'DeviceHasNoMedium', 'data': { 'device': %s } }"
 
 #define QERR_DEVICE_INIT_FAILED \
-    -1, "{ 'class': 'DeviceInitFailed', 'data': { 'device': %s } }"
+    ERROR_CLASS_GENERIC_ERROR, "{ 'class': 'DeviceInitFailed', 'data': { 'device': %s } }"
 
 #define QERR_DEVICE_IN_USE \
-    -1, "{ 'class': 'DeviceInUse', 'data': { 'device': %s } }"
+    ERROR_CLASS_GENERIC_ERROR, "{ 'class': 'DeviceInUse', 'data': { 'device': %s } }"
 
 #define QERR_DEVICE_IS_READ_ONLY \
-    -1, "{ 'class': 'DeviceIsReadOnly', 'data': { 'device': %s } }"
+    ERROR_CLASS_GENERIC_ERROR, "{ 'class': 'DeviceIsReadOnly', 'data': { 'device': %s } }"
 
 #define QERR_DEVICE_LOCKED \
-    -1, "{ 'class': 'DeviceLocked', 'data': { 'device': %s } }"
+    ERROR_CLASS_GENERIC_ERROR, "{ 'class': 'DeviceLocked', 'data': { 'device': %s } }"
 
 #define QERR_DEVICE_MULTIPLE_BUSSES \
-    -1, "{ 'class': 'DeviceMultipleBusses', 'data': { 'device': %s } }"
+    ERROR_CLASS_GENERIC_ERROR, "{ 'class': 'DeviceMultipleBusses', 'data': { 'device': %s } }"
 
 #define QERR_DEVICE_NO_BUS \
-    -1, "{ 'class': 'DeviceNoBus', 'data': { 'device': %s } }"
+    ERROR_CLASS_GENERIC_ERROR, "{ 'class': 'DeviceNoBus', 'data': { 'device': %s } }"
 
 #define QERR_DEVICE_NO_HOTPLUG \
-    -1, "{ 'class': 'DeviceNoHotplug', 'data': { 'device': %s } }"
+    ERROR_CLASS_GENERIC_ERROR, "{ 'class': 'DeviceNoHotplug', 'data': { 'device': %s } }"
 
 #define QERR_DEVICE_NOT_ACTIVE \
-    -1, "{ 'class': 'DeviceNotActive', 'data': { 'device': %s } }"
+    ERROR_CLASS_DEVICE_NOT_ACTIVE, "{ 'class': 'DeviceNotActive', 'data': { 'device': %s } }"
 
 #define QERR_DEVICE_NOT_ENCRYPTED \
-    -1, "{ 'class': 'DeviceNotEncrypted', 'data': { 'device': %s } }"
+    ERROR_CLASS_GENERIC_ERROR, "{ 'class': 'DeviceNotEncrypted', 'data': { 'device': %s } }"
 
 #define QERR_DEVICE_NOT_FOUND \
-    -1, "{ 'class': 'DeviceNotFound', 'data': { 'device': %s } }"
+    ERROR_CLASS_DEVICE_NOT_FOUND, "{ 'class': 'DeviceNotFound', 'data': { 'device': %s } }"
 
 #define QERR_DEVICE_NOT_REMOVABLE \
-    -1, "{ 'class': 'DeviceNotRemovable', 'data': { 'device': %s } }"
+    ERROR_CLASS_GENERIC_ERROR, "{ 'class': 'DeviceNotRemovable', 'data': { 'device': %s } }"
 
 #define QERR_DUPLICATE_ID \
-    -1, "{ 'class': 'DuplicateId', 'data': { 'id': %s, 'object': %s } }"
+    ERROR_CLASS_GENERIC_ERROR, "{ 'class': 'DuplicateId', 'data': { 'id': %s, 'object': %s } }"
 
 #define QERR_FD_NOT_FOUND \
-    -1, "{ 'class': 'FdNotFound', 'data': { 'name': %s } }"
+    ERROR_CLASS_GENERIC_ERROR, "{ 'class': 'FdNotFound', 'data': { 'name': %s } }"
 
 #define QERR_FD_NOT_SUPPLIED \
-    -1, "{ 'class': 'FdNotSupplied', 'data': {} }"
+    ERROR_CLASS_GENERIC_ERROR, "{ 'class': 'FdNotSupplied', 'data': {} }"
 
 #define QERR_FEATURE_DISABLED \
-    -1, "{ 'class': 'FeatureDisabled', 'data': { 'name': %s } }"
+    ERROR_CLASS_GENERIC_ERROR, "{ 'class': 'FeatureDisabled', 'data': { 'name': %s } }"
 
 #define QERR_INVALID_BLOCK_FORMAT \
-    -1, "{ 'class': 'InvalidBlockFormat', 'data': { 'name': %s } }"
+    ERROR_CLASS_GENERIC_ERROR, "{ 'class': 'InvalidBlockFormat', 'data': { 'name': %s } }"
 
 #define QERR_INVALID_OPTION_GROUP \
-    -1, "{ 'class': 'InvalidOptionGroup', 'data': { 'group': %s } }"
+    ERROR_CLASS_GENERIC_ERROR, "{ 'class': 'InvalidOptionGroup', 'data': { 'group': %s } }"
 
 #define QERR_INVALID_PARAMETER \
-    -1, "{ 'class': 'InvalidParameter', 'data': { 'name': %s } }"
+    ERROR_CLASS_GENERIC_ERROR, "{ 'class': 'InvalidParameter', 'data': { 'name': %s } }"
 
 #define QERR_INVALID_PARAMETER_COMBINATION \
-    -1, "{ 'class': 'InvalidParameterCombination', 'data': {} }"
+    ERROR_CLASS_GENERIC_ERROR, "{ 'class': 'InvalidParameterCombination', 'data': {} }"
 
 #define QERR_INVALID_PARAMETER_TYPE \
-    -1, "{ 'class': 'InvalidParameterType', 'data': { 'name': %s,'expected': %s } }"
+    ERROR_CLASS_GENERIC_ERROR, "{ 'class': 'InvalidParameterType', 'data': { 'name': %s,'expected': %s } }"
 
 #define QERR_INVALID_PARAMETER_VALUE \
-    -1, "{ 'class': 'InvalidParameterValue', 'data': { 'name': %s, 'expected': %s } }"
+    ERROR_CLASS_GENERIC_ERROR, "{ 'class': 'InvalidParameterValue', 'data': { 'name': %s, 'expected': %s } }"
 
 #define QERR_INVALID_PASSWORD \
-    -1, "{ 'class': 'InvalidPassword', 'data': {} }"
+    ERROR_CLASS_GENERIC_ERROR, "{ 'class': 'InvalidPassword', 'data': {} }"
 
 #define QERR_IO_ERROR \
-    -1, "{ 'class': 'IOError', 'data': {} }"
+    ERROR_CLASS_GENERIC_ERROR, "{ 'class': 'IOError', 'data': {} }"
 
 #define QERR_JSON_PARSE_ERROR \
-    -1, "{ 'class': 'JSONParseError', 'data': { 'message': %s } }"
+    ERROR_CLASS_GENERIC_ERROR, "{ 'class': 'JSONParseError', 'data': { 'message': %s } }"
 
 #define QERR_JSON_PARSING \
-    -1, "{ 'class': 'JSONParsing', 'data': {} }"
+    ERROR_CLASS_GENERIC_ERROR, "{ 'class': 'JSONParsing', 'data': {} }"
 
 #define QERR_KVM_MISSING_CAP \
-    -1, "{ 'class': 'KVMMissingCap', 'data': { 'capability': %s, 'feature': %s } }"
+    ERROR_CLASS_K_V_M_MISSING_CAP, "{ 'class': 'KVMMissingCap', 'data': { 'capability': %s, 'feature': %s } }"
 
 #define QERR_MIGRATION_ACTIVE \
-    -1, "{ 'class': 'MigrationActive', 'data': {} }"
+    ERROR_CLASS_GENERIC_ERROR, "{ 'class': 'MigrationActive', 'data': {} }"
 
 #define QERR_MIGRATION_NOT_SUPPORTED \
-    -1, "{ 'class': 'MigrationNotSupported', 'data': {'device': %s} }"
+    ERROR_CLASS_GENERIC_ERROR, "{ 'class': 'MigrationNotSupported', 'data': {'device': %s} }"
 
 #define QERR_MIGRATION_EXPECTED \
-    -1, "{ 'class': 'MigrationExpected', 'data': {} }"
+    ERROR_CLASS_MIGRATION_EXPECTED, "{ 'class': 'MigrationExpected', 'data': {} }"
 
 #define QERR_MISSING_PARAMETER \
-    -1, "{ 'class': 'MissingParameter', 'data': { 'name': %s } }"
+    ERROR_CLASS_GENERIC_ERROR, "{ 'class': 'MissingParameter', 'data': { 'name': %s } }"
 
 #define QERR_NO_BUS_FOR_DEVICE \
-    -1, "{ 'class': 'NoBusForDevice', 'data': { 'device': %s, 'bus': %s } }"
+    ERROR_CLASS_GENERIC_ERROR, "{ 'class': 'NoBusForDevice', 'data': { 'device': %s, 'bus': %s } }"
 
 #define QERR_NOT_SUPPORTED \
-    -1, "{ 'class': 'NotSupported', 'data': {} }"
+    ERROR_CLASS_GENERIC_ERROR, "{ 'class': 'NotSupported', 'data': {} }"
 
 #define QERR_OPEN_FILE_FAILED \
-    -1, "{ 'class': 'OpenFileFailed', 'data': { 'filename': %s } }"
+    ERROR_CLASS_GENERIC_ERROR, "{ 'class': 'OpenFileFailed', 'data': { 'filename': %s } }"
 
 #define QERR_PERMISSION_DENIED \
-    -1, "{ 'class': 'PermissionDenied', 'data': {} }"
+    ERROR_CLASS_GENERIC_ERROR, "{ 'class': 'PermissionDenied', 'data': {} }"
 
 #define QERR_PROPERTY_NOT_FOUND \
-    -1, "{ 'class': 'PropertyNotFound', 'data': { 'device': %s, 'property': %s } }"
+    ERROR_CLASS_GENERIC_ERROR, "{ 'class': 'PropertyNotFound', 'data': { 'device': %s, 'property': %s } }"
 
 #define QERR_PROPERTY_VALUE_BAD \
-    -1, "{ 'class': 'PropertyValueBad', 'data': { 'device': %s, 'property': %s, 'value': %s } }"
+    ERROR_CLASS_GENERIC_ERROR, "{ 'class': 'PropertyValueBad', 'data': { 'device': %s, 'property': %s, 'value': %s } }"
 
 #define QERR_PROPERTY_VALUE_IN_USE \
-    -1, "{ 'class': 'PropertyValueInUse', 'data': { 'device': %s, 'property': %s, 'value': %s } }"
+    ERROR_CLASS_GENERIC_ERROR, "{ 'class': 'PropertyValueInUse', 'data': { 'device': %s, 'property': %s, 'value': %s } }"
 
 #define QERR_PROPERTY_VALUE_NOT_FOUND \
-    -1, "{ 'class': 'PropertyValueNotFound', 'data': { 'device': %s, 'property': %s, 'value': %s } }"
+    ERROR_CLASS_GENERIC_ERROR, "{ 'class': 'PropertyValueNotFound', 'data': { 'device': %s, 'property': %s, 'value': %s } }"
 
 #define QERR_PROPERTY_VALUE_NOT_POWER_OF_2 \
-    -1, "{ 'class': 'PropertyValueNotPowerOf2', 'data': { " \
+    ERROR_CLASS_GENERIC_ERROR, "{ 'class': 'PropertyValueNotPowerOf2', 'data': { " \
     "'device': %s, 'property': %s, 'value': %"PRId64" } }"
 
 #define QERR_PROPERTY_VALUE_OUT_OF_RANGE \
-    -1, "{ 'class': 'PropertyValueOutOfRange', 'data': { 'device': %s, 'property': %s, 'value': %"PRId64", 'min': %"PRId64", 'max': %"PRId64" } }"
+    ERROR_CLASS_GENERIC_ERROR, "{ 'class': 'PropertyValueOutOfRange', 'data': { 'device': %s, 'property': %s, 'value': %"PRId64", 'min': %"PRId64", 'max': %"PRId64" } }"
 
 #define QERR_QGA_COMMAND_FAILED \
-    -1, "{ 'class': 'QgaCommandFailed', 'data': { 'message': %s } }"
+    ERROR_CLASS_GENERIC_ERROR, "{ 'class': 'QgaCommandFailed', 'data': { 'message': %s } }"
 
 #define QERR_QGA_LOGGING_FAILED \
-    -1, "{ 'class': 'QgaLoggingFailed', 'data': {} }"
+    ERROR_CLASS_GENERIC_ERROR, "{ 'class': 'QgaLoggingFailed', 'data': {} }"
 
 #define QERR_QMP_BAD_INPUT_OBJECT \
-    -1, "{ 'class': 'QMPBadInputObject', 'data': { 'expected': %s } }"
+    ERROR_CLASS_GENERIC_ERROR, "{ 'class': 'QMPBadInputObject', 'data': { 'expected': %s } }"
 
 #define QERR_QMP_BAD_INPUT_OBJECT_MEMBER \
-    -1, "{ 'class': 'QMPBadInputObjectMember', 'data': { 'member': %s, 'expected': %s } }"
+    ERROR_CLASS_GENERIC_ERROR, "{ 'class': 'QMPBadInputObjectMember', 'data': { 'member': %s, 'expected': %s } }"
 
 #define QERR_QMP_EXTRA_MEMBER \
-    -1, "{ 'class': 'QMPExtraInputObjectMember', 'data': { 'member': %s } }"
+    ERROR_CLASS_GENERIC_ERROR, "{ 'class': 'QMPExtraInputObjectMember', 'data': { 'member': %s } }"
 
 #define QERR_RESET_REQUIRED \
-    -1, "{ 'class': 'ResetRequired', 'data': {} }"
+    ERROR_CLASS_GENERIC_ERROR, "{ 'class': 'ResetRequired', 'data': {} }"
 
 #define QERR_SET_PASSWD_FAILED \
-    -1, "{ 'class': 'SetPasswdFailed', 'data': {} }"
+    ERROR_CLASS_GENERIC_ERROR, "{ 'class': 'SetPasswdFailed', 'data': {} }"
 
 #define QERR_TOO_MANY_FILES \
-    -1, "{ 'class': 'TooManyFiles', 'data': {} }"
+    ERROR_CLASS_GENERIC_ERROR, "{ 'class': 'TooManyFiles', 'data': {} }"
 
 #define QERR_UNDEFINED_ERROR \
-    -1, "{ 'class': 'UndefinedError', 'data': {} }"
+    ERROR_CLASS_GENERIC_ERROR, "{ 'class': 'UndefinedError', 'data': {} }"
 
 #define QERR_UNKNOWN_BLOCK_FORMAT_FEATURE \
-    -1, "{ 'class': 'UnknownBlockFormatFeature', 'data': { 'device': %s, 'format': %s, 'feature': %s } }"
+    ERROR_CLASS_GENERIC_ERROR, "{ 'class': 'UnknownBlockFormatFeature', 'data': { 'device': %s, 'format': %s, 'feature': %s } }"
 
 #define QERR_UNSUPPORTED \
-    -1, "{ 'class': 'Unsupported', 'data': {} }"
+    ERROR_CLASS_GENERIC_ERROR, "{ 'class': 'Unsupported', 'data': {} }"
 
 #define QERR_VIRTFS_FEATURE_BLOCKS_MIGRATION \
-    -1, "{ 'class': 'VirtFSFeatureBlocksMigration', 'data': { 'path': %s, 'tag': %s } }"
+    ERROR_CLASS_GENERIC_ERROR, "{ 'class': 'VirtFSFeatureBlocksMigration', 'data': { 'path': %s, 'tag': %s } }"
 
 #define QERR_VNC_SERVER_FAILED \
-    -1, "{ 'class': 'VNCServerFailed', 'data': { 'target': %s } }"
+    ERROR_CLASS_GENERIC_ERROR, "{ 'class': 'VNCServerFailed', 'data': { 'target': %s } }"
 
 #define QERR_SOCKET_CONNECT_FAILED \
-    -1, "{ 'class': 'SockConnectFailed', 'data': {} }"
+    ERROR_CLASS_GENERIC_ERROR, "{ 'class': 'SockConnectFailed', 'data': {} }"
 
 #define QERR_SOCKET_LISTEN_FAILED \
-    -1, "{ 'class': 'SockListenFailed', 'data': {} }"
+    ERROR_CLASS_GENERIC_ERROR, "{ 'class': 'SockListenFailed', 'data': {} }"
 
 #define QERR_SOCKET_BIND_FAILED \
-    -1, "{ 'class': 'SockBindFailed', 'data': {} }"
+    ERROR_CLASS_GENERIC_ERROR, "{ 'class': 'SockBindFailed', 'data': {} }"
 
 #define QERR_SOCKET_CREATE_FAILED \
-    -1, "{ 'class': 'SockCreateFailed', 'data': {} }"
+    ERROR_CLASS_GENERIC_ERROR, "{ 'class': 'SockCreateFailed', 'data': {} }"
 
 #endif /* QERROR_H */
commit 13f59ae8157e8ec238fa8aefe5309909a1eeb7e2
Author: Luiz Capitulino <lcapitulino at redhat.com>
Date:   Fri Jul 27 14:09:29 2012 -0300

    error, qerror: add ErrorClass argument to error functions
    
    The new argument is added to functions qerror_report() and error_set().
    It's stored in Error and QError. qerror_report_err() is also updated to
    take care of it.
    
    The QERR_ macros are changed to contain a place holder value for the
    new argument, so that the value is used on all current calls to
    qerror_report() and error_set() (and also to initialize qerror_table[]).
    
    Next commit will update the QERR_ macros with a proper ErrorClass
    value.
    
    Signed-off-by: Luiz Capitulino <lcapitulino at redhat.com>
    Reviewed-by: Markus Armbruster <armbru at redhat.com>

diff --git a/error.c b/error.c
index 2ade99b..648706a 100644
--- a/error.c
+++ b/error.c
@@ -14,6 +14,7 @@
 #include "error.h"
 #include "qjson.h"
 #include "qdict.h"
+#include "qapi-types.h"
 #include "error_int.h"
 #include "qerror.h"
 
@@ -21,9 +22,10 @@ struct Error
 {
     QDict *obj;
     char *msg;
+    ErrorClass err_class;
 };
 
-void error_set(Error **errp, const char *fmt, ...)
+void error_set(Error **errp, ErrorClass err_class, const char *fmt, ...)
 {
     Error *err;
     va_list ap;
@@ -39,6 +41,7 @@ void error_set(Error **errp, const char *fmt, ...)
     err->obj = qobject_to_qdict(qobject_from_jsonv(fmt, &ap));
     va_end(ap);
     err->msg = qerror_format(fmt, err->obj);
+    err->err_class = err_class;
 
     *errp = err;
 }
@@ -49,6 +52,7 @@ Error *error_copy(const Error *err)
 
     err_new = g_malloc0(sizeof(*err));
     err_new->msg = g_strdup(err->msg);
+    err_new->err_class = err->err_class;
     err_new->obj = err->obj;
     QINCREF(err_new->obj);
 
@@ -97,7 +101,7 @@ void error_free(Error *err)
     }
 }
 
-bool error_is_type(Error *err, const char *fmt)
+bool error_is_type(Error *err, ErrorClass err_class, const char *fmt)
 {
     const char *error_class;
     char *ptr;
diff --git a/error.h b/error.h
index 3d9d96d..9678752 100644
--- a/error.h
+++ b/error.h
@@ -13,6 +13,7 @@
 #define ERROR_H
 
 #include "compiler.h"
+#include "qapi-types.h"
 #include <stdbool.h>
 
 /**
@@ -26,7 +27,7 @@ typedef struct Error Error;
  * Currently, qerror.h defines these error formats.  This function is not
  * meant to be used outside of QEMU.
  */
-void error_set(Error **err, const char *fmt, ...) GCC_FMT_ATTR(2, 3);
+void error_set(Error **err, ErrorClass err_class, const char *fmt, ...) GCC_FMT_ATTR(3, 4);
 
 /**
  * Returns true if an indirect pointer to an error is pointing to a valid
@@ -70,6 +71,6 @@ void error_free(Error *err);
  * Determine if an error is of a speific type (based on the qerror format).
  * Non-QEMU users should get the `class' field to identify the error type.
  */
-bool error_is_type(Error *err, const char *fmt);
+bool error_is_type(Error *err, ErrorClass err_class, const char *fmt);
 
 #endif
diff --git a/qerror.c b/qerror.c
index ff460b0..0bf8aec 100644
--- a/qerror.c
+++ b/qerror.c
@@ -386,13 +386,15 @@ static QDict *error_obj_from_fmt_no_fail(const char *fmt, va_list *va)
  *
  * Return strong reference.
  */
-static QError *qerror_from_info(const char *fmt, va_list *va)
+static QError *qerror_from_info(ErrorClass err_class, const char *fmt,
+                                va_list *va)
 {
     QError *qerr;
 
     qerr = qerror_new();
     loc_save(&qerr->loc);
 
+    qerr->err_class = err_class;
     qerr->error = error_obj_from_fmt_no_fail(fmt, va);
     qerr->err_msg = qerror_format(fmt, qerr->error);
 
@@ -518,13 +520,13 @@ static void qerror_print(QError *qerror)
     QDECREF(qstring);
 }
 
-void qerror_report(const char *fmt, ...)
+void qerror_report(ErrorClass eclass, const char *fmt, ...)
 {
     va_list va;
     QError *qerror;
 
     va_start(va, fmt);
-    qerror = qerror_from_info(fmt, &va);
+    qerror = qerror_from_info(eclass, fmt, &va);
     va_end(va);
 
     if (monitor_cur_is_qmp()) {
@@ -540,6 +542,7 @@ struct Error
 {
     QDict *obj;
     char *msg;
+    ErrorClass err_class;
 };
 
 void qerror_report_err(Error *err)
@@ -551,6 +554,7 @@ void qerror_report_err(Error *err)
     QINCREF(err->obj);
     qerr->error = err->obj;
     qerr->err_msg = g_strdup(err->msg);
+    qerr->err_class = err->err_class;
 
     if (monitor_cur_is_qmp()) {
         monitor_set_error(cur_mon, qerr);
diff --git a/qerror.h b/qerror.h
index 2e6a49d..bcc93f8 100644
--- a/qerror.h
+++ b/qerror.h
@@ -16,9 +16,11 @@
 #include "qstring.h"
 #include "qemu-error.h"
 #include "error.h"
+#include "qapi-types.h"
 #include <stdarg.h>
 
 typedef struct QErrorStringTable {
+    ErrorClass err_class;
     const char *error_fmt;
     const char *desc;
 } QErrorStringTable;
@@ -28,10 +30,11 @@ typedef struct QError {
     QDict *error;
     Location loc;
     char *err_msg;
+    ErrorClass err_class;
 } QError;
 
 QString *qerror_human(const QError *qerror);
-void qerror_report(const char *fmt, ...) GCC_FMT_ATTR(1, 2);
+void qerror_report(ErrorClass err_class, const char *fmt, ...) GCC_FMT_ATTR(2, 3);
 void qerror_report_err(Error *err);
 void assert_no_error(Error *err);
 char *qerror_format(const char *fmt, QDict *error);
@@ -42,214 +45,214 @@ char *qerror_format(const char *fmt, QDict *error);
  * Use scripts/check-qerror.sh to check.
  */
 #define QERR_ADD_CLIENT_FAILED \
-    "{ 'class': 'AddClientFailed', 'data': {} }"
+    -1, "{ 'class': 'AddClientFailed', 'data': {} }"
 
 #define QERR_AMBIGUOUS_PATH \
-    "{ 'class': 'AmbiguousPath', 'data': { 'path': %s } }"
+    -1, "{ 'class': 'AmbiguousPath', 'data': { 'path': %s } }"
 
 #define QERR_BAD_BUS_FOR_DEVICE \
-    "{ 'class': 'BadBusForDevice', 'data': { 'device': %s, 'bad_bus_type': %s } }"
+    -1, "{ 'class': 'BadBusForDevice', 'data': { 'device': %s, 'bad_bus_type': %s } }"
 
 #define QERR_BASE_NOT_FOUND \
-    "{ 'class': 'BaseNotFound', 'data': { 'base': %s } }"
+    -1, "{ 'class': 'BaseNotFound', 'data': { 'base': %s } }"
 
 #define QERR_BLOCK_FORMAT_FEATURE_NOT_SUPPORTED \
-    "{ 'class': 'BlockFormatFeatureNotSupported', 'data': { 'format': %s, 'name': %s, 'feature': %s } }"
+    -1, "{ 'class': 'BlockFormatFeatureNotSupported', 'data': { 'format': %s, 'name': %s, 'feature': %s } }"
 
 #define QERR_BUFFER_OVERRUN \
-    "{ 'class': 'BufferOverrun', 'data': {} }"
+    -1, "{ 'class': 'BufferOverrun', 'data': {} }"
 
 #define QERR_BUS_NO_HOTPLUG \
-    "{ 'class': 'BusNoHotplug', 'data': { 'bus': %s } }"
+    -1, "{ 'class': 'BusNoHotplug', 'data': { 'bus': %s } }"
 
 #define QERR_BUS_NOT_FOUND \
-    "{ 'class': 'BusNotFound', 'data': { 'bus': %s } }"
+    -1, "{ 'class': 'BusNotFound', 'data': { 'bus': %s } }"
 
 #define QERR_COMMAND_DISABLED \
-    "{ 'class': 'CommandDisabled', 'data': { 'name': %s } }"
+    -1, "{ 'class': 'CommandDisabled', 'data': { 'name': %s } }"
 
 #define QERR_COMMAND_NOT_FOUND \
-    "{ 'class': 'CommandNotFound', 'data': { 'name': %s } }"
+    -1, "{ 'class': 'CommandNotFound', 'data': { 'name': %s } }"
 
 #define QERR_DEVICE_ENCRYPTED \
-    "{ 'class': 'DeviceEncrypted', 'data': { 'device': %s, 'filename': %s } }"
+    -1, "{ 'class': 'DeviceEncrypted', 'data': { 'device': %s, 'filename': %s } }"
 
 #define QERR_DEVICE_FEATURE_BLOCKS_MIGRATION \
-    "{ 'class': 'DeviceFeatureBlocksMigration', 'data': { 'device': %s, 'feature': %s } }"
+    -1, "{ 'class': 'DeviceFeatureBlocksMigration', 'data': { 'device': %s, 'feature': %s } }"
 
 #define QERR_DEVICE_HAS_NO_MEDIUM \
-    "{ 'class': 'DeviceHasNoMedium', 'data': { 'device': %s } }"
+    -1, "{ 'class': 'DeviceHasNoMedium', 'data': { 'device': %s } }"
 
 #define QERR_DEVICE_INIT_FAILED \
-    "{ 'class': 'DeviceInitFailed', 'data': { 'device': %s } }"
+    -1, "{ 'class': 'DeviceInitFailed', 'data': { 'device': %s } }"
 
 #define QERR_DEVICE_IN_USE \
-    "{ 'class': 'DeviceInUse', 'data': { 'device': %s } }"
+    -1, "{ 'class': 'DeviceInUse', 'data': { 'device': %s } }"
 
 #define QERR_DEVICE_IS_READ_ONLY \
-    "{ 'class': 'DeviceIsReadOnly', 'data': { 'device': %s } }"
+    -1, "{ 'class': 'DeviceIsReadOnly', 'data': { 'device': %s } }"
 
 #define QERR_DEVICE_LOCKED \
-    "{ 'class': 'DeviceLocked', 'data': { 'device': %s } }"
+    -1, "{ 'class': 'DeviceLocked', 'data': { 'device': %s } }"
 
 #define QERR_DEVICE_MULTIPLE_BUSSES \
-    "{ 'class': 'DeviceMultipleBusses', 'data': { 'device': %s } }"
+    -1, "{ 'class': 'DeviceMultipleBusses', 'data': { 'device': %s } }"
 
 #define QERR_DEVICE_NO_BUS \
-    "{ 'class': 'DeviceNoBus', 'data': { 'device': %s } }"
+    -1, "{ 'class': 'DeviceNoBus', 'data': { 'device': %s } }"
 
 #define QERR_DEVICE_NO_HOTPLUG \
-    "{ 'class': 'DeviceNoHotplug', 'data': { 'device': %s } }"
+    -1, "{ 'class': 'DeviceNoHotplug', 'data': { 'device': %s } }"
 
 #define QERR_DEVICE_NOT_ACTIVE \
-    "{ 'class': 'DeviceNotActive', 'data': { 'device': %s } }"
+    -1, "{ 'class': 'DeviceNotActive', 'data': { 'device': %s } }"
 
 #define QERR_DEVICE_NOT_ENCRYPTED \
-    "{ 'class': 'DeviceNotEncrypted', 'data': { 'device': %s } }"
+    -1, "{ 'class': 'DeviceNotEncrypted', 'data': { 'device': %s } }"
 
 #define QERR_DEVICE_NOT_FOUND \
-    "{ 'class': 'DeviceNotFound', 'data': { 'device': %s } }"
+    -1, "{ 'class': 'DeviceNotFound', 'data': { 'device': %s } }"
 
 #define QERR_DEVICE_NOT_REMOVABLE \
-    "{ 'class': 'DeviceNotRemovable', 'data': { 'device': %s } }"
+    -1, "{ 'class': 'DeviceNotRemovable', 'data': { 'device': %s } }"
 
 #define QERR_DUPLICATE_ID \
-    "{ 'class': 'DuplicateId', 'data': { 'id': %s, 'object': %s } }"
+    -1, "{ 'class': 'DuplicateId', 'data': { 'id': %s, 'object': %s } }"
 
 #define QERR_FD_NOT_FOUND \
-    "{ 'class': 'FdNotFound', 'data': { 'name': %s } }"
+    -1, "{ 'class': 'FdNotFound', 'data': { 'name': %s } }"
 
 #define QERR_FD_NOT_SUPPLIED \
-    "{ 'class': 'FdNotSupplied', 'data': {} }"
+    -1, "{ 'class': 'FdNotSupplied', 'data': {} }"
 
 #define QERR_FEATURE_DISABLED \
-    "{ 'class': 'FeatureDisabled', 'data': { 'name': %s } }"
+    -1, "{ 'class': 'FeatureDisabled', 'data': { 'name': %s } }"
 
 #define QERR_INVALID_BLOCK_FORMAT \
-    "{ 'class': 'InvalidBlockFormat', 'data': { 'name': %s } }"
+    -1, "{ 'class': 'InvalidBlockFormat', 'data': { 'name': %s } }"
 
 #define QERR_INVALID_OPTION_GROUP \
-    "{ 'class': 'InvalidOptionGroup', 'data': { 'group': %s } }"
+    -1, "{ 'class': 'InvalidOptionGroup', 'data': { 'group': %s } }"
 
 #define QERR_INVALID_PARAMETER \
-    "{ 'class': 'InvalidParameter', 'data': { 'name': %s } }"
+    -1, "{ 'class': 'InvalidParameter', 'data': { 'name': %s } }"
 
 #define QERR_INVALID_PARAMETER_COMBINATION \
-    "{ 'class': 'InvalidParameterCombination', 'data': {} }"
+    -1, "{ 'class': 'InvalidParameterCombination', 'data': {} }"
 
 #define QERR_INVALID_PARAMETER_TYPE \
-    "{ 'class': 'InvalidParameterType', 'data': { 'name': %s,'expected': %s } }"
+    -1, "{ 'class': 'InvalidParameterType', 'data': { 'name': %s,'expected': %s } }"
 
 #define QERR_INVALID_PARAMETER_VALUE \
-    "{ 'class': 'InvalidParameterValue', 'data': { 'name': %s, 'expected': %s } }"
+    -1, "{ 'class': 'InvalidParameterValue', 'data': { 'name': %s, 'expected': %s } }"
 
 #define QERR_INVALID_PASSWORD \
-    "{ 'class': 'InvalidPassword', 'data': {} }"
+    -1, "{ 'class': 'InvalidPassword', 'data': {} }"
 
 #define QERR_IO_ERROR \
-    "{ 'class': 'IOError', 'data': {} }"
+    -1, "{ 'class': 'IOError', 'data': {} }"
 
 #define QERR_JSON_PARSE_ERROR \
-    "{ 'class': 'JSONParseError', 'data': { 'message': %s } }"
+    -1, "{ 'class': 'JSONParseError', 'data': { 'message': %s } }"
 
 #define QERR_JSON_PARSING \
-    "{ 'class': 'JSONParsing', 'data': {} }"
+    -1, "{ 'class': 'JSONParsing', 'data': {} }"
 
 #define QERR_KVM_MISSING_CAP \
-    "{ 'class': 'KVMMissingCap', 'data': { 'capability': %s, 'feature': %s } }"
+    -1, "{ 'class': 'KVMMissingCap', 'data': { 'capability': %s, 'feature': %s } }"
 
 #define QERR_MIGRATION_ACTIVE \
-    "{ 'class': 'MigrationActive', 'data': {} }"
+    -1, "{ 'class': 'MigrationActive', 'data': {} }"
 
 #define QERR_MIGRATION_NOT_SUPPORTED \
-    "{ 'class': 'MigrationNotSupported', 'data': {'device': %s} }"
+    -1, "{ 'class': 'MigrationNotSupported', 'data': {'device': %s} }"
 
 #define QERR_MIGRATION_EXPECTED \
-    "{ 'class': 'MigrationExpected', 'data': {} }"
+    -1, "{ 'class': 'MigrationExpected', 'data': {} }"
 
 #define QERR_MISSING_PARAMETER \
-    "{ 'class': 'MissingParameter', 'data': { 'name': %s } }"
+    -1, "{ 'class': 'MissingParameter', 'data': { 'name': %s } }"
 
 #define QERR_NO_BUS_FOR_DEVICE \
-    "{ 'class': 'NoBusForDevice', 'data': { 'device': %s, 'bus': %s } }"
+    -1, "{ 'class': 'NoBusForDevice', 'data': { 'device': %s, 'bus': %s } }"
 
 #define QERR_NOT_SUPPORTED \
-    "{ 'class': 'NotSupported', 'data': {} }"
+    -1, "{ 'class': 'NotSupported', 'data': {} }"
 
 #define QERR_OPEN_FILE_FAILED \
-    "{ 'class': 'OpenFileFailed', 'data': { 'filename': %s } }"
+    -1, "{ 'class': 'OpenFileFailed', 'data': { 'filename': %s } }"
 
 #define QERR_PERMISSION_DENIED \
-    "{ 'class': 'PermissionDenied', 'data': {} }"
+    -1, "{ 'class': 'PermissionDenied', 'data': {} }"
 
 #define QERR_PROPERTY_NOT_FOUND \
-    "{ 'class': 'PropertyNotFound', 'data': { 'device': %s, 'property': %s } }"
+    -1, "{ 'class': 'PropertyNotFound', 'data': { 'device': %s, 'property': %s } }"
 
 #define QERR_PROPERTY_VALUE_BAD \
-    "{ 'class': 'PropertyValueBad', 'data': { 'device': %s, 'property': %s, 'value': %s } }"
+    -1, "{ 'class': 'PropertyValueBad', 'data': { 'device': %s, 'property': %s, 'value': %s } }"
 
 #define QERR_PROPERTY_VALUE_IN_USE \
-    "{ 'class': 'PropertyValueInUse', 'data': { 'device': %s, 'property': %s, 'value': %s } }"
+    -1, "{ 'class': 'PropertyValueInUse', 'data': { 'device': %s, 'property': %s, 'value': %s } }"
 
 #define QERR_PROPERTY_VALUE_NOT_FOUND \
-    "{ 'class': 'PropertyValueNotFound', 'data': { 'device': %s, 'property': %s, 'value': %s } }"
+    -1, "{ 'class': 'PropertyValueNotFound', 'data': { 'device': %s, 'property': %s, 'value': %s } }"
 
 #define QERR_PROPERTY_VALUE_NOT_POWER_OF_2 \
-    "{ 'class': 'PropertyValueNotPowerOf2', 'data': { " \
+    -1, "{ 'class': 'PropertyValueNotPowerOf2', 'data': { " \
     "'device': %s, 'property': %s, 'value': %"PRId64" } }"
 
 #define QERR_PROPERTY_VALUE_OUT_OF_RANGE \
-    "{ 'class': 'PropertyValueOutOfRange', 'data': { 'device': %s, 'property': %s, 'value': %"PRId64", 'min': %"PRId64", 'max': %"PRId64" } }"
+    -1, "{ 'class': 'PropertyValueOutOfRange', 'data': { 'device': %s, 'property': %s, 'value': %"PRId64", 'min': %"PRId64", 'max': %"PRId64" } }"
 
 #define QERR_QGA_COMMAND_FAILED \
-    "{ 'class': 'QgaCommandFailed', 'data': { 'message': %s } }"
+    -1, "{ 'class': 'QgaCommandFailed', 'data': { 'message': %s } }"
 
 #define QERR_QGA_LOGGING_FAILED \
-    "{ 'class': 'QgaLoggingFailed', 'data': {} }"
+    -1, "{ 'class': 'QgaLoggingFailed', 'data': {} }"
 
 #define QERR_QMP_BAD_INPUT_OBJECT \
-    "{ 'class': 'QMPBadInputObject', 'data': { 'expected': %s } }"
+    -1, "{ 'class': 'QMPBadInputObject', 'data': { 'expected': %s } }"
 
 #define QERR_QMP_BAD_INPUT_OBJECT_MEMBER \
-    "{ 'class': 'QMPBadInputObjectMember', 'data': { 'member': %s, 'expected': %s } }"
+    -1, "{ 'class': 'QMPBadInputObjectMember', 'data': { 'member': %s, 'expected': %s } }"
 
 #define QERR_QMP_EXTRA_MEMBER \
-    "{ 'class': 'QMPExtraInputObjectMember', 'data': { 'member': %s } }"
+    -1, "{ 'class': 'QMPExtraInputObjectMember', 'data': { 'member': %s } }"
 
 #define QERR_RESET_REQUIRED \
-    "{ 'class': 'ResetRequired', 'data': {} }"
+    -1, "{ 'class': 'ResetRequired', 'data': {} }"
 
 #define QERR_SET_PASSWD_FAILED \
-    "{ 'class': 'SetPasswdFailed', 'data': {} }"
+    -1, "{ 'class': 'SetPasswdFailed', 'data': {} }"
 
 #define QERR_TOO_MANY_FILES \
-    "{ 'class': 'TooManyFiles', 'data': {} }"
+    -1, "{ 'class': 'TooManyFiles', 'data': {} }"
 
 #define QERR_UNDEFINED_ERROR \
-    "{ 'class': 'UndefinedError', 'data': {} }"
+    -1, "{ 'class': 'UndefinedError', 'data': {} }"
 
 #define QERR_UNKNOWN_BLOCK_FORMAT_FEATURE \
-    "{ 'class': 'UnknownBlockFormatFeature', 'data': { 'device': %s, 'format': %s, 'feature': %s } }"
+    -1, "{ 'class': 'UnknownBlockFormatFeature', 'data': { 'device': %s, 'format': %s, 'feature': %s } }"
 
 #define QERR_UNSUPPORTED \
-    "{ 'class': 'Unsupported', 'data': {} }"
+    -1, "{ 'class': 'Unsupported', 'data': {} }"
 
 #define QERR_VIRTFS_FEATURE_BLOCKS_MIGRATION \
-    "{ 'class': 'VirtFSFeatureBlocksMigration', 'data': { 'path': %s, 'tag': %s } }"
+    -1, "{ 'class': 'VirtFSFeatureBlocksMigration', 'data': { 'path': %s, 'tag': %s } }"
 
 #define QERR_VNC_SERVER_FAILED \
-    "{ 'class': 'VNCServerFailed', 'data': { 'target': %s } }"
+    -1, "{ 'class': 'VNCServerFailed', 'data': { 'target': %s } }"
 
 #define QERR_SOCKET_CONNECT_FAILED \
-    "{ 'class': 'SockConnectFailed', 'data': {} }"
+    -1, "{ 'class': 'SockConnectFailed', 'data': {} }"
 
 #define QERR_SOCKET_LISTEN_FAILED \
-    "{ 'class': 'SockListenFailed', 'data': {} }"
+    -1, "{ 'class': 'SockListenFailed', 'data': {} }"
 
 #define QERR_SOCKET_BIND_FAILED \
-    "{ 'class': 'SockBindFailed', 'data': {} }"
+    -1, "{ 'class': 'SockBindFailed', 'data': {} }"
 
 #define QERR_SOCKET_CREATE_FAILED \
-    "{ 'class': 'SockCreateFailed', 'data': {} }"
+    -1, "{ 'class': 'SockCreateFailed', 'data': {} }"
 
 #endif /* QERROR_H */
commit 85465051e0e8a79c3c1df3187c2acaacb10d6232
Author: Luiz Capitulino <lcapitulino at redhat.com>
Date:   Fri Jul 27 13:58:30 2012 -0300

    qerror: qerror_table: don't use C99 struct initializers
    
    This allows for changing QERR_ macros to initialize two struct members
    at the same time. See next commit for more details.
    
    Signed-off-by: Luiz Capitulino <lcapitulino at redhat.com>
    Reviewed-by: Markus Armbruster <armbru at redhat.com>

diff --git a/qerror.c b/qerror.c
index 452ec69..ff460b0 100644
--- a/qerror.c
+++ b/qerror.c
@@ -44,285 +44,285 @@ static const QType qerror_type = {
  */
 static const QErrorStringTable qerror_table[] = {
     {
-        .error_fmt = QERR_ADD_CLIENT_FAILED,
-        .desc      = "Could not add client",
+         QERR_ADD_CLIENT_FAILED,
+         "Could not add client",
     },
     {
-        .error_fmt = QERR_AMBIGUOUS_PATH,
-        .desc      = "Path '%(path)' does not uniquely identify an object"
+         QERR_AMBIGUOUS_PATH,
+         "Path '%(path)' does not uniquely identify an object"
     },
     {
-        .error_fmt = QERR_BAD_BUS_FOR_DEVICE,
-        .desc      = "Device '%(device)' can't go on a %(bad_bus_type) bus",
+         QERR_BAD_BUS_FOR_DEVICE,
+         "Device '%(device)' can't go on a %(bad_bus_type) bus",
     },
     {
-        .error_fmt = QERR_BASE_NOT_FOUND,
-        .desc      = "Base '%(base)' not found",
+         QERR_BASE_NOT_FOUND,
+         "Base '%(base)' not found",
     },
     {
-        .error_fmt = QERR_BLOCK_FORMAT_FEATURE_NOT_SUPPORTED,
-        .desc      = "Block format '%(format)' used by device '%(name)' does not support feature '%(feature)'",
+         QERR_BLOCK_FORMAT_FEATURE_NOT_SUPPORTED,
+         "Block format '%(format)' used by device '%(name)' does not support feature '%(feature)'",
     },
     {
-        .error_fmt = QERR_BUS_NO_HOTPLUG,
-        .desc      = "Bus '%(bus)' does not support hotplugging",
+         QERR_BUS_NO_HOTPLUG,
+         "Bus '%(bus)' does not support hotplugging",
     },
     {
-        .error_fmt = QERR_BUS_NOT_FOUND,
-        .desc      = "Bus '%(bus)' not found",
+         QERR_BUS_NOT_FOUND,
+         "Bus '%(bus)' not found",
     },
     {
-        .error_fmt = QERR_COMMAND_DISABLED,
-        .desc      = "The command %(name) has been disabled for this instance",
+         QERR_COMMAND_DISABLED,
+         "The command %(name) has been disabled for this instance",
     },
     {
-        .error_fmt = QERR_COMMAND_NOT_FOUND,
-        .desc      = "The command %(name) has not been found",
+         QERR_COMMAND_NOT_FOUND,
+         "The command %(name) has not been found",
     },
     {
-        .error_fmt = QERR_DEVICE_ENCRYPTED,
-        .desc      = "'%(device)' (%(filename)) is encrypted",
+         QERR_DEVICE_ENCRYPTED,
+         "'%(device)' (%(filename)) is encrypted",
     },
     {
-        .error_fmt = QERR_DEVICE_FEATURE_BLOCKS_MIGRATION,
-        .desc      = "Migration is disabled when using feature '%(feature)' in device '%(device)'",
+         QERR_DEVICE_FEATURE_BLOCKS_MIGRATION,
+         "Migration is disabled when using feature '%(feature)' in device '%(device)'",
     },
     {
-        .error_fmt = QERR_DEVICE_HAS_NO_MEDIUM,
-        .desc      = "Device '%(device)' has no medium",
+         QERR_DEVICE_HAS_NO_MEDIUM,
+         "Device '%(device)' has no medium",
     },
     {
-        .error_fmt = QERR_DEVICE_INIT_FAILED,
-        .desc      = "Device '%(device)' could not be initialized",
+         QERR_DEVICE_INIT_FAILED,
+         "Device '%(device)' could not be initialized",
     },
     {
-        .error_fmt = QERR_DEVICE_IN_USE,
-        .desc      = "Device '%(device)' is in use",
+         QERR_DEVICE_IN_USE,
+         "Device '%(device)' is in use",
     },
     {
-        .error_fmt = QERR_DEVICE_IS_READ_ONLY,
-        .desc      = "Device '%(device)' is read only",
+         QERR_DEVICE_IS_READ_ONLY,
+         "Device '%(device)' is read only",
     },
     {
-        .error_fmt = QERR_DEVICE_LOCKED,
-        .desc      = "Device '%(device)' is locked",
+         QERR_DEVICE_LOCKED,
+         "Device '%(device)' is locked",
     },
     {
-        .error_fmt = QERR_DEVICE_MULTIPLE_BUSSES,
-        .desc      = "Device '%(device)' has multiple child busses",
+         QERR_DEVICE_MULTIPLE_BUSSES,
+         "Device '%(device)' has multiple child busses",
     },
     {
-        .error_fmt = QERR_DEVICE_NO_BUS,
-        .desc      = "Device '%(device)' has no child bus",
+         QERR_DEVICE_NO_BUS,
+         "Device '%(device)' has no child bus",
     },
     {
-        .error_fmt = QERR_DEVICE_NO_HOTPLUG,
-        .desc      = "Device '%(device)' does not support hotplugging",
+         QERR_DEVICE_NO_HOTPLUG,
+         "Device '%(device)' does not support hotplugging",
     },
     {
-        .error_fmt = QERR_DEVICE_NOT_ACTIVE,
-        .desc      = "Device '%(device)' has not been activated",
+         QERR_DEVICE_NOT_ACTIVE,
+         "Device '%(device)' has not been activated",
     },
     {
-        .error_fmt = QERR_DEVICE_NOT_ENCRYPTED,
-        .desc      = "Device '%(device)' is not encrypted",
+         QERR_DEVICE_NOT_ENCRYPTED,
+         "Device '%(device)' is not encrypted",
     },
     {
-        .error_fmt = QERR_DEVICE_NOT_FOUND,
-        .desc      = "Device '%(device)' not found",
+         QERR_DEVICE_NOT_FOUND,
+         "Device '%(device)' not found",
     },
     {
-        .error_fmt = QERR_DEVICE_NOT_REMOVABLE,
-        .desc      = "Device '%(device)' is not removable",
+         QERR_DEVICE_NOT_REMOVABLE,
+         "Device '%(device)' is not removable",
     },
     {
-        .error_fmt = QERR_DUPLICATE_ID,
-        .desc      = "Duplicate ID '%(id)' for %(object)",
+         QERR_DUPLICATE_ID,
+         "Duplicate ID '%(id)' for %(object)",
     },
     {
-        .error_fmt = QERR_FD_NOT_FOUND,
-        .desc      = "File descriptor named '%(name)' not found",
+         QERR_FD_NOT_FOUND,
+         "File descriptor named '%(name)' not found",
     },
     {
-        .error_fmt = QERR_FD_NOT_SUPPLIED,
-        .desc      = "No file descriptor supplied via SCM_RIGHTS",
+         QERR_FD_NOT_SUPPLIED,
+         "No file descriptor supplied via SCM_RIGHTS",
     },
     {
-        .error_fmt = QERR_FEATURE_DISABLED,
-        .desc      = "The feature '%(name)' is not enabled",
+         QERR_FEATURE_DISABLED,
+         "The feature '%(name)' is not enabled",
     },
     {
-        .error_fmt = QERR_INVALID_BLOCK_FORMAT,
-        .desc      = "Invalid block format '%(name)'",
+         QERR_INVALID_BLOCK_FORMAT,
+         "Invalid block format '%(name)'",
     },
     {
-        .error_fmt = QERR_INVALID_OPTION_GROUP,
-        .desc      = "There is no option group '%(group)'",
+         QERR_INVALID_OPTION_GROUP,
+         "There is no option group '%(group)'",
     },
     {
-        .error_fmt = QERR_INVALID_PARAMETER,
-        .desc      = "Invalid parameter '%(name)'",
+         QERR_INVALID_PARAMETER,
+         "Invalid parameter '%(name)'",
     },
     {
-        .error_fmt = QERR_INVALID_PARAMETER_COMBINATION,
-        .desc      = "Invalid parameter combination",
+         QERR_INVALID_PARAMETER_COMBINATION,
+         "Invalid parameter combination",
     },
     {
-        .error_fmt = QERR_INVALID_PARAMETER_TYPE,
-        .desc      = "Invalid parameter type for '%(name)', expected: %(expected)",
+         QERR_INVALID_PARAMETER_TYPE,
+         "Invalid parameter type for '%(name)', expected: %(expected)",
     },
     {
-        .error_fmt = QERR_INVALID_PARAMETER_VALUE,
-        .desc      = "Parameter '%(name)' expects %(expected)",
+         QERR_INVALID_PARAMETER_VALUE,
+         "Parameter '%(name)' expects %(expected)",
     },
     {
-        .error_fmt = QERR_INVALID_PASSWORD,
-        .desc      = "Password incorrect",
+         QERR_INVALID_PASSWORD,
+         "Password incorrect",
     },
     {
-        .error_fmt = QERR_IO_ERROR,
-        .desc      = "An IO error has occurred",
+         QERR_IO_ERROR,
+         "An IO error has occurred",
     },
     {
-        .error_fmt = QERR_JSON_PARSE_ERROR,
-        .desc      = "JSON parse error, %(message)",
+         QERR_JSON_PARSE_ERROR,
+         "JSON parse error, %(message)",
 
     },
     {
-        .error_fmt = QERR_JSON_PARSING,
-        .desc      = "Invalid JSON syntax",
+         QERR_JSON_PARSING,
+         "Invalid JSON syntax",
     },
     {
-        .error_fmt = QERR_KVM_MISSING_CAP,
-        .desc      = "Using KVM without %(capability), %(feature) unavailable",
+         QERR_KVM_MISSING_CAP,
+         "Using KVM without %(capability), %(feature) unavailable",
     },
     {
-        .error_fmt = QERR_MIGRATION_ACTIVE,
-        .desc      = "There's a migration process in progress",
+         QERR_MIGRATION_ACTIVE,
+         "There's a migration process in progress",
     },
     {
-        .error_fmt = QERR_MIGRATION_NOT_SUPPORTED,
-        .desc      = "State blocked by non-migratable device '%(device)'",
+         QERR_MIGRATION_NOT_SUPPORTED,
+         "State blocked by non-migratable device '%(device)'",
     },
     {
-        .error_fmt = QERR_MIGRATION_EXPECTED,
-        .desc      = "An incoming migration is expected before this command can be executed",
+         QERR_MIGRATION_EXPECTED,
+         "An incoming migration is expected before this command can be executed",
     },
     {
-        .error_fmt = QERR_MISSING_PARAMETER,
-        .desc      = "Parameter '%(name)' is missing",
+         QERR_MISSING_PARAMETER,
+         "Parameter '%(name)' is missing",
     },
     {
-        .error_fmt = QERR_NO_BUS_FOR_DEVICE,
-        .desc      = "No '%(bus)' bus found for device '%(device)'",
+         QERR_NO_BUS_FOR_DEVICE,
+         "No '%(bus)' bus found for device '%(device)'",
     },
     {
-        .error_fmt = QERR_NOT_SUPPORTED,
-        .desc      = "Not supported",
+         QERR_NOT_SUPPORTED,
+         "Not supported",
     },
     {
-        .error_fmt = QERR_OPEN_FILE_FAILED,
-        .desc      = "Could not open '%(filename)'",
+         QERR_OPEN_FILE_FAILED,
+         "Could not open '%(filename)'",
     },
     {
-        .error_fmt = QERR_PERMISSION_DENIED,
-        .desc      = "Insufficient permission to perform this operation",
+         QERR_PERMISSION_DENIED,
+         "Insufficient permission to perform this operation",
     },
     {
-        .error_fmt = QERR_PROPERTY_NOT_FOUND,
-        .desc      = "Property '%(device).%(property)' not found",
+         QERR_PROPERTY_NOT_FOUND,
+         "Property '%(device).%(property)' not found",
     },
     {
-        .error_fmt = QERR_PROPERTY_VALUE_BAD,
-        .desc      = "Property '%(device).%(property)' doesn't take value '%(value)'",
+         QERR_PROPERTY_VALUE_BAD,
+         "Property '%(device).%(property)' doesn't take value '%(value)'",
     },
     {
-        .error_fmt = QERR_PROPERTY_VALUE_IN_USE,
-        .desc      = "Property '%(device).%(property)' can't take value '%(value)', it's in use",
+         QERR_PROPERTY_VALUE_IN_USE,
+         "Property '%(device).%(property)' can't take value '%(value)', it's in use",
     },
     {
-        .error_fmt = QERR_PROPERTY_VALUE_NOT_FOUND,
-        .desc      = "Property '%(device).%(property)' can't find value '%(value)'",
+         QERR_PROPERTY_VALUE_NOT_FOUND,
+         "Property '%(device).%(property)' can't find value '%(value)'",
     },
     {
-        .error_fmt = QERR_PROPERTY_VALUE_NOT_POWER_OF_2,
-        .desc      = "Property '%(device).%(property)' doesn't take "
+         QERR_PROPERTY_VALUE_NOT_POWER_OF_2,
+         "Property '%(device).%(property)' doesn't take "
                      "value '%(value)', it's not a power of 2",
     },
     {
-        .error_fmt = QERR_PROPERTY_VALUE_OUT_OF_RANGE,
-        .desc      = "Property '%(device).%(property)' doesn't take "
+         QERR_PROPERTY_VALUE_OUT_OF_RANGE,
+         "Property '%(device).%(property)' doesn't take "
                      "value %(value) (minimum: %(min), maximum: %(max))",
     },
     {
-        .error_fmt = QERR_QGA_COMMAND_FAILED,
-        .desc      = "Guest agent command failed, error was '%(message)'",
+         QERR_QGA_COMMAND_FAILED,
+         "Guest agent command failed, error was '%(message)'",
     },
     {
-        .error_fmt = QERR_QGA_LOGGING_FAILED,
-        .desc      = "Guest agent failed to log non-optional log statement",
+         QERR_QGA_LOGGING_FAILED,
+         "Guest agent failed to log non-optional log statement",
     },
     {
-        .error_fmt = QERR_QMP_BAD_INPUT_OBJECT,
-        .desc      = "Expected '%(expected)' in QMP input",
+         QERR_QMP_BAD_INPUT_OBJECT,
+         "Expected '%(expected)' in QMP input",
     },
     {
-        .error_fmt = QERR_QMP_BAD_INPUT_OBJECT_MEMBER,
-        .desc      = "QMP input object member '%(member)' expects '%(expected)'",
+         QERR_QMP_BAD_INPUT_OBJECT_MEMBER,
+         "QMP input object member '%(member)' expects '%(expected)'",
     },
     {
-        .error_fmt = QERR_QMP_EXTRA_MEMBER,
-        .desc      = "QMP input object member '%(member)' is unexpected",
+         QERR_QMP_EXTRA_MEMBER,
+         "QMP input object member '%(member)' is unexpected",
     },
     {
-        .error_fmt = QERR_RESET_REQUIRED,
-        .desc      = "Resetting the Virtual Machine is required",
+         QERR_RESET_REQUIRED,
+         "Resetting the Virtual Machine is required",
     },
     {
-        .error_fmt = QERR_SET_PASSWD_FAILED,
-        .desc      = "Could not set password",
+         QERR_SET_PASSWD_FAILED,
+         "Could not set password",
     },
     {
-        .error_fmt = QERR_TOO_MANY_FILES,
-        .desc      = "Too many open files",
+         QERR_TOO_MANY_FILES,
+         "Too many open files",
     },
     {
-        .error_fmt = QERR_UNDEFINED_ERROR,
-        .desc      = "An undefined error has occurred",
+         QERR_UNDEFINED_ERROR,
+         "An undefined error has occurred",
     },
     {
-        .error_fmt = QERR_UNKNOWN_BLOCK_FORMAT_FEATURE,
-        .desc      = "'%(device)' uses a %(format) feature which is not "
+         QERR_UNKNOWN_BLOCK_FORMAT_FEATURE,
+         "'%(device)' uses a %(format) feature which is not "
                      "supported by this qemu version: %(feature)",
     },
     {
-        .error_fmt = QERR_UNSUPPORTED,
-        .desc      = "this feature or command is not currently supported",
+         QERR_UNSUPPORTED,
+         "this feature or command is not currently supported",
     },
     {
-        .error_fmt = QERR_VIRTFS_FEATURE_BLOCKS_MIGRATION,
-        .desc      = "Migration is disabled when VirtFS export path '%(path)' "
+         QERR_VIRTFS_FEATURE_BLOCKS_MIGRATION,
+         "Migration is disabled when VirtFS export path '%(path)' "
                      "is mounted in the guest using mount_tag '%(tag)'",
     },
     {
-        .error_fmt = QERR_VNC_SERVER_FAILED,
-        .desc      = "Could not start VNC server on %(target)",
+         QERR_VNC_SERVER_FAILED,
+         "Could not start VNC server on %(target)",
     },
     {
-        .error_fmt = QERR_SOCKET_CONNECT_FAILED,
-        .desc      = "Failed to connect to socket",
+         QERR_SOCKET_CONNECT_FAILED,
+         "Failed to connect to socket",
     },
     {
-        .error_fmt = QERR_SOCKET_LISTEN_FAILED,
-        .desc      = "Failed to set socket to listening mode",
+         QERR_SOCKET_LISTEN_FAILED,
+         "Failed to set socket to listening mode",
     },
     {
-        .error_fmt = QERR_SOCKET_BIND_FAILED,
-        .desc      = "Failed to bind socket",
+         QERR_SOCKET_BIND_FAILED,
+         "Failed to bind socket",
     },
     {
-        .error_fmt = QERR_SOCKET_CREATE_FAILED,
-        .desc      = "Failed to create socket",
+         QERR_SOCKET_CREATE_FAILED,
+         "Failed to create socket",
     },
     {}
 };
diff --git a/qerror.h b/qerror.h
index 52ce58d..2e6a49d 100644
--- a/qerror.h
+++ b/qerror.h
@@ -19,8 +19,8 @@
 #include <stdarg.h>
 
 typedef struct QErrorStringTable {
-    const char *desc;
     const char *error_fmt;
+    const char *desc;
 } QErrorStringTable;
 
 typedef struct QError {
commit dcafd32348a08490cc378bfc50b260e5229ad738
Author: Luiz Capitulino <lcapitulino at redhat.com>
Date:   Fri Jul 27 09:34:50 2012 -0300

    qapi-schema: add ErrorClass enum
    
    Signed-off-by: Luiz Capitulino <lcapitulino at redhat.com>
    Reviewed-by: Markus Armbruster <armbru at redhat.com>

diff --git a/qapi-schema.json b/qapi-schema.json
index a62bf68..b513935 100644
--- a/qapi-schema.json
+++ b/qapi-schema.json
@@ -3,6 +3,36 @@
 # QAPI Schema
 
 ##
+# @ErrorClass
+#
+# QEMU error classes
+#
+# @GenericError: this is used for errors that don't require a specific error
+#                class. This should be the default case for most errors
+#
+# @CommandNotFound: the requested command has not been found
+#
+# @DeviceEncrypted: the requested operation can't be fulfilled because the
+#                   selected device is encrypted
+#
+# @DeviceNotActive: a device has failed to be become active
+#
+# @DeviceNotFound: the requested device has not been found
+#
+# @KVMMissingCap: the requested operation can't be fulfilled because a
+#                 required KVM capability is missing
+#
+# @MigrationExpected: the requested operation can't be fulfilled because a
+#                     migration process is expected
+#
+# Since: 1.2
+##
+{ 'enum': 'ErrorClass',
+  'data': [ 'GenericError', 'CommandNotFound', 'DeviceEncrypted',
+            'DeviceNotActive', 'DeviceNotFound', 'KVMMissingCap',
+            'MigrationExpected' ] }
+
+##
 # @NameInfo:
 #
 # Guest name information.
commit ac4ff701d88c4c742b4a53b83eed7ce356535ef8
Author: Luiz Capitulino <lcapitulino at redhat.com>
Date:   Fri Jul 27 09:38:05 2012 -0300

    qapi: don't convert enum strings to lowercase
    
    Next commit will introduce enum strings in camel case.
    
    Signed-off-by: Luiz Capitulino <lcapitulino at redhat.com>
    Reviewed-by: Markus Armbruster <armbru at redhat.com>

diff --git a/scripts/qapi-types.py b/scripts/qapi-types.py
index 9b7da96..cf601ae 100644
--- a/scripts/qapi-types.py
+++ b/scripts/qapi-types.py
@@ -70,7 +70,7 @@ const char *%(name)s_lookup[] = {
         ret += mcgen('''
     "%(value)s",
 ''',
-                     value=value.lower())
+                     value=value)
 
     ret += mcgen('''
     NULL,
commit f01f594b63becfc17cb23b4c15193230d01592e4
Author: Luiz Capitulino <lcapitulino at redhat.com>
Date:   Fri Jul 27 15:44:25 2012 -0300

    qapi: generate correct enum names for camel case enums
    
    An enum like GenericError in the schema, should generate
    GENERIC_ERROR and not GENERICERROR.
    
    Signed-off-by: Luiz Capitulino <lcapitulino at redhat.com>
    Reviewed-by: Markus Armbruster <armbru at redhat.com>

diff --git a/scripts/qapi-types.py b/scripts/qapi-types.py
index 3ed9f04..9b7da96 100644
--- a/scripts/qapi-types.py
+++ b/scripts/qapi-types.py
@@ -79,6 +79,16 @@ const char *%(name)s_lookup[] = {
 ''')
     return ret
 
+def generate_enum_name(name):
+    if name.isupper():
+        return c_fun(name)
+    new_name = ''
+    for c in c_fun(name):
+        if c.isupper():
+            new_name += '_'
+        new_name += c
+    return new_name.lstrip('_').upper()
+
 def generate_enum(name, values):
     lookup_decl = mcgen('''
 extern const char *%(name)s_lookup[];
@@ -100,7 +110,7 @@ typedef enum %(name)s
     %(abbrev)s_%(value)s = %(i)d,
 ''',
                      abbrev=de_camel_case(name).upper(),
-                     value=c_fun(value).upper(),
+                     value=generate_enum_name(value),
                      i=i)
         i += 1
 
commit b68a8472c17d2d2127afcf1a8dc57884e6584173
Author: Luiz Capitulino <lcapitulino at redhat.com>
Date:   Fri Jul 27 10:56:33 2012 -0300

    qapi: qapi-types.h: don't include qapi/qapi-types-core.h
    
    qapi-types.h needs only qemu-common.h. Including qapi-types-core.h
    causes problems when qerror.h or error.h includes qapi-types.h.
    
    Signed-off-by: Luiz Capitulino <lcapitulino at redhat.com>
    Reviewed-by: Markus Armbruster <armbru at redhat.com>

diff --git a/scripts/qapi-types.py b/scripts/qapi-types.py
index 4a734f5..3ed9f04 100644
--- a/scripts/qapi-types.py
+++ b/scripts/qapi-types.py
@@ -253,7 +253,8 @@ fdecl.write(mcgen('''
 #ifndef %(guard)s
 #define %(guard)s
 
-#include "qapi/qapi-types-core.h"
+#include "qemu-common.h"
+
 ''',
                   guard=guardname(h_file)))
 
commit ff2f990b8212c8822d6a2f66ab4baeb48dae86bd
Author: Luiz Capitulino <lcapitulino at redhat.com>
Date:   Fri Jul 27 10:55:29 2012 -0300

    hmp: hmp.h: include qdict.h
    
    hmp.h is relying on qdict.h being provided by qapi-types.h. Fix this,
    as a future commit will change qapi-types.h not to provide qdict.h.
    
    Signed-off-by: Luiz Capitulino <lcapitulino at redhat.com>
    Reviewed-by: Markus Armbruster <armbru at redhat.com>

diff --git a/hmp.h b/hmp.h
index 8d2b0d7..3275522 100644
--- a/hmp.h
+++ b/hmp.h
@@ -16,6 +16,7 @@
 
 #include "qemu-common.h"
 #include "qapi-types.h"
+#include "qdict.h"
 
 void hmp_info_name(Monitor *mon);
 void hmp_info_version(Monitor *mon);
commit 9aeaddff26d02633b228aceadecf36d28ac18823
Author: Luiz Capitulino <lcapitulino at redhat.com>
Date:   Fri Jul 27 10:52:18 2012 -0300

    block: block_int: include qerror.h
    
    Several block/ files are relying on qerror.h being provided by
    qapi-types.h. Fix this, as a future commit will change qapi-types.h
    not to provide qerror.h.
    
    Signed-off-by: Luiz Capitulino <lcapitulino at redhat.com>
    Reviewed-by: Markus Armbruster <armbru at redhat.com>

diff --git a/block_int.h b/block_int.h
index 6c1d9ca..4452f6f 100644
--- a/block_int.h
+++ b/block_int.h
@@ -30,6 +30,7 @@
 #include "qemu-coroutine.h"
 #include "qemu-timer.h"
 #include "qapi-types.h"
+#include "qerror.h"
 
 #define BLOCK_FLAG_ENCRYPT          1
 #define BLOCK_FLAG_COMPAT6          4
commit 75b81cf0f26f5bb7ada583fc434835adf03f8b77
Author: Luiz Capitulino <lcapitulino at redhat.com>
Date:   Wed Aug 1 14:26:53 2012 -0300

    qerror: drop QERR_SOCKET_CONNECT_IN_PROGRESS
    
    Unused since last commit.
    
    Signed-off-by: Luiz Capitulino <lcapitulino at redhat.com>
    Reviewed-by: Markus Armbruster <armbru at redhat.com>

diff --git a/qerror.c b/qerror.c
index 5d38428..452ec69 100644
--- a/qerror.c
+++ b/qerror.c
@@ -309,10 +309,6 @@ static const QErrorStringTable qerror_table[] = {
         .desc      = "Could not start VNC server on %(target)",
     },
     {
-        .error_fmt = QERR_SOCKET_CONNECT_IN_PROGRESS,
-        .desc      = "Connection can not be completed immediately",
-    },
-    {
         .error_fmt = QERR_SOCKET_CONNECT_FAILED,
         .desc      = "Failed to connect to socket",
     },
diff --git a/qerror.h b/qerror.h
index de8497d..52ce58d 100644
--- a/qerror.h
+++ b/qerror.h
@@ -240,9 +240,6 @@ char *qerror_format(const char *fmt, QDict *error);
 #define QERR_VNC_SERVER_FAILED \
     "{ 'class': 'VNCServerFailed', 'data': { 'target': %s } }"
 
-#define QERR_SOCKET_CONNECT_IN_PROGRESS \
-    "{ 'class': 'SockConnectInprogress', 'data': {} }"
-
 #define QERR_SOCKET_CONNECT_FAILED \
     "{ 'class': 'SockConnectFailed', 'data': {} }"
 
commit 540c79fec9e8b6a6582ec4c65aa2c4c5366e4b89
Author: Luiz Capitulino <lcapitulino at redhat.com>
Date:   Mon Aug 6 16:26:47 2012 -0300

    migration: don't rely on any QERR_SOCKET_*
    
    Use the in_progress argument for QERR_SOCKET_CONNECT_IN_PROGRESS. The
    other errors are handled the same by checking if the error is set and
    then calling migrate_fd_error() if it's.
    
    It's also necessary to change inet_connect_opts() not to set
    QERR_SOCKET_CONNECT_IN_PROGRESS. This error is only used by
    tcp_start_outgoing_migration() and not changing it along with the
    usage of in_progress would break migration.
    
    Furthermore this commit fixes a bug. Today, there's a spurious error
    report when migration succeeds:
    
    (qemu) migrate tcp:0:4444
    migrate: Connection can not be completed immediately
    (qemu)
    
    After this commit no spurious error is reported anymore.
    
    Signed-off-by: Luiz Capitulino <lcapitulino at redhat.com>
    Reviewed-by: Markus Armbruster <armbru at redhat.com>

diff --git a/migration-tcp.c b/migration-tcp.c
index 18944a4..ac891c3 100644
--- a/migration-tcp.c
+++ b/migration-tcp.c
@@ -82,27 +82,23 @@ static void tcp_wait_for_connect(void *opaque)
 int tcp_start_outgoing_migration(MigrationState *s, const char *host_port,
                                  Error **errp)
 {
+    bool in_progress;
+
     s->get_error = socket_errno;
     s->write = socket_write;
     s->close = tcp_close;
 
-    s->fd = inet_connect(host_port, false, NULL, errp);
+    s->fd = inet_connect(host_port, false, &in_progress, errp);
+    if (error_is_set(errp)) {
+        migrate_fd_error(s);
+        return -1;
+    }
 
-    if (!error_is_set(errp)) {
-        migrate_fd_connect(s);
-    } else if (error_is_type(*errp, QERR_SOCKET_CONNECT_IN_PROGRESS)) {
+    if (in_progress) {
         DPRINTF("connect in progress\n");
         qemu_set_fd_handler2(s->fd, NULL, NULL, tcp_wait_for_connect, s);
-    } else if (error_is_type(*errp, QERR_SOCKET_CREATE_FAILED)) {
-        DPRINTF("connect failed\n");
-        return -1;
-    } else if (error_is_type(*errp, QERR_SOCKET_CONNECT_FAILED)) {
-        DPRINTF("connect failed\n");
-        migrate_fd_error(s);
-        return -1;
     } else {
-        DPRINTF("unknown error\n");
-        return -1;
+        migrate_fd_connect(s);
     }
 
     return 0;
diff --git a/qemu-sockets.c b/qemu-sockets.c
index 9cb47d4..361d890 100644
--- a/qemu-sockets.c
+++ b/qemu-sockets.c
@@ -284,8 +284,6 @@ int inet_connect_opts(QemuOpts *opts, bool *in_progress, Error **errp)
             if (in_progress) {
                 *in_progress = true;
             }
-
-            error_set(errp, QERR_SOCKET_CONNECT_IN_PROGRESS);
         } else if (rc < 0) {
             if (NULL == e->ai_next)
                 fprintf(stderr, "%s: connect(%s,%s,%s,%s): %s\n", __FUNCTION__,
commit 02a08fef079469c005d48fe2d181f0e0eb5752ae
Author: Luiz Capitulino <lcapitulino at redhat.com>
Date:   Wed Aug 1 13:42:47 2012 -0300

    net: inet_connect(), inet_connect_opts(): add in_progress argument
    
    It's used to indicate the special case where a valid file-descriptor
    is returned (ie. success) but the connection can't be completed
    w/o blocking.
    
    This is needed because QERR_SOCKET_CONNECT_IN_PROGRESS is not
    treated like an error and a future commit will drop it.
    
    Signed-off-by: Luiz Capitulino <lcapitulino at redhat.com>
    Reviewed-by: Markus Armbruster <armbru at redhat.com>

diff --git a/migration-tcp.c b/migration-tcp.c
index 440804d..18944a4 100644
--- a/migration-tcp.c
+++ b/migration-tcp.c
@@ -86,7 +86,7 @@ int tcp_start_outgoing_migration(MigrationState *s, const char *host_port,
     s->write = socket_write;
     s->close = tcp_close;
 
-    s->fd = inet_connect(host_port, false, errp);
+    s->fd = inet_connect(host_port, false, NULL, errp);
 
     if (!error_is_set(errp)) {
         migrate_fd_connect(s);
diff --git a/nbd.c b/nbd.c
index dc0adf9..0dd60c5 100644
--- a/nbd.c
+++ b/nbd.c
@@ -162,7 +162,7 @@ int tcp_socket_outgoing(const char *address, uint16_t port)
 
 int tcp_socket_outgoing_spec(const char *address_and_port)
 {
-    return inet_connect(address_and_port, true, NULL);
+    return inet_connect(address_and_port, true, NULL, NULL);
 }
 
 int tcp_socket_incoming(const char *address, uint16_t port)
diff --git a/qemu-char.c b/qemu-char.c
index c2aaaee..382c71e 100644
--- a/qemu-char.c
+++ b/qemu-char.c
@@ -2446,7 +2446,7 @@ static CharDriverState *qemu_chr_open_socket(QemuOpts *opts)
         if (is_listen) {
             fd = inet_listen_opts(opts, 0, NULL);
         } else {
-            fd = inet_connect_opts(opts, NULL);
+            fd = inet_connect_opts(opts, NULL, NULL);
         }
     }
     if (fd < 0) {
diff --git a/qemu-sockets.c b/qemu-sockets.c
index beb2bb6..9cb47d4 100644
--- a/qemu-sockets.c
+++ b/qemu-sockets.c
@@ -209,7 +209,7 @@ listen:
     return slisten;
 }
 
-int inet_connect_opts(QemuOpts *opts, Error **errp)
+int inet_connect_opts(QemuOpts *opts, bool *in_progress, Error **errp)
 {
     struct addrinfo ai,*res,*e;
     const char *addr;
@@ -224,6 +224,10 @@ int inet_connect_opts(QemuOpts *opts, Error **errp)
     ai.ai_family = PF_UNSPEC;
     ai.ai_socktype = SOCK_STREAM;
 
+    if (in_progress) {
+        *in_progress = false;
+    }
+
     addr = qemu_opt_get(opts, "host");
     port = qemu_opt_get(opts, "port");
     block = qemu_opt_get_bool(opts, "block", 0);
@@ -277,6 +281,10 @@ int inet_connect_opts(QemuOpts *opts, Error **errp)
   #else
         if (!block && (rc == -EINPROGRESS)) {
   #endif
+            if (in_progress) {
+                *in_progress = true;
+            }
+
             error_set(errp, QERR_SOCKET_CONNECT_IN_PROGRESS);
         } else if (rc < 0) {
             if (NULL == e->ai_next)
@@ -487,7 +495,7 @@ int inet_listen(const char *str, char *ostr, int olen,
     return sock;
 }
 
-int inet_connect(const char *str, bool block, Error **errp)
+int inet_connect(const char *str, bool block, bool *in_progress, Error **errp)
 {
     QemuOpts *opts;
     int sock = -1;
@@ -497,7 +505,7 @@ int inet_connect(const char *str, bool block, Error **errp)
         if (block) {
             qemu_opt_set(opts, "block", "on");
         }
-        sock = inet_connect_opts(opts, errp);
+        sock = inet_connect_opts(opts, in_progress, errp);
     } else {
         error_set(errp, QERR_SOCKET_CREATE_FAILED);
     }
diff --git a/qemu_socket.h b/qemu_socket.h
index 4689ff3..30ae6af 100644
--- a/qemu_socket.h
+++ b/qemu_socket.h
@@ -42,8 +42,8 @@ int send_all(int fd, const void *buf, int len1);
 int inet_listen_opts(QemuOpts *opts, int port_offset, Error **errp);
 int inet_listen(const char *str, char *ostr, int olen,
                 int socktype, int port_offset, Error **errp);
-int inet_connect_opts(QemuOpts *opts, Error **errp);
-int inet_connect(const char *str, bool block, Error **errp);
+int inet_connect_opts(QemuOpts *opts, bool *in_progress, Error **errp);
+int inet_connect(const char *str, bool block, bool *in_progress, Error **errp);
 int inet_dgram_opts(QemuOpts *opts);
 const char *inet_strfamily(int family);
 
diff --git a/ui/vnc.c b/ui/vnc.c
index 312ad7f..385e345 100644
--- a/ui/vnc.c
+++ b/ui/vnc.c
@@ -3061,7 +3061,7 @@ int vnc_display_open(DisplayState *ds, const char *display)
         if (strncmp(display, "unix:", 5) == 0)
             vs->lsock = unix_connect(display+5);
         else
-            vs->lsock = inet_connect(display, true, NULL);
+            vs->lsock = inet_connect(display, true, NULL, NULL);
         if (-1 == vs->lsock) {
             g_free(vs->display);
             vs->display = NULL;
commit eef5ad1086403d8ac8d91208a0e8dc34734b671c
Author: Luiz Capitulino <lcapitulino at redhat.com>
Date:   Mon Aug 6 15:49:34 2012 -0300

    hmp_change(): don't access DeviceEncrypted's data
    
    It's not needed. As the device name is already known, we can replace
    the duplicated password prompting code by monitor_read_block_device_key().
    
    This overly simplifies hmp_change().
    
    Signed-off-by: Luiz Capitulino <lcapitulino at redhat.com>
    Reviewed-by: Markus Armbruster <armbru at redhat.com>

diff --git a/hmp.c b/hmp.c
index 4efaf51..54c37d7 100644
--- a/hmp.c
+++ b/hmp.c
@@ -776,22 +776,6 @@ static void hmp_change_read_arg(Monitor *mon, const char *password,
     monitor_read_command(mon, 1);
 }
 
-static void cb_hmp_change_bdrv_pwd(Monitor *mon, const char *password,
-                                   void *opaque)
-{
-    Error *encryption_err = opaque;
-    Error *err = NULL;
-    const char *device;
-
-    device = error_get_field(encryption_err, "device");
-
-    qmp_block_passwd(device, password, &err);
-    hmp_handle_error(mon, &err);
-    error_free(encryption_err);
-
-    monitor_read_command(mon, 1);
-}
-
 void hmp_change(Monitor *mon, const QDict *qdict)
 {
     const char *device = qdict_get_str(qdict, "device");
@@ -810,17 +794,8 @@ void hmp_change(Monitor *mon, const QDict *qdict)
 
     qmp_change(device, target, !!arg, arg, &err);
     if (error_is_type(err, QERR_DEVICE_ENCRYPTED)) {
-        monitor_printf(mon, "%s (%s) is encrypted.\n",
-                       error_get_field(err, "device"),
-                       error_get_field(err, "filename"));
-        if (!monitor_get_rs(mon)) {
-            monitor_printf(mon,
-                    "terminal does not support password prompting\n");
-            error_free(err);
-            return;
-        }
-        readline_start(monitor_get_rs(mon), "Password: ", 1,
-                       cb_hmp_change_bdrv_pwd, err);
+        error_free(err);
+        monitor_read_block_device_key(mon, device, NULL, NULL);
         return;
     }
     hmp_handle_error(mon, &err);
commit 8b7f6fbbdc5545f749864fdf295f2fae14c7ef0a
Author: Luiz Capitulino <lcapitulino at redhat.com>
Date:   Thu Jul 26 20:41:53 2012 -0300

    hmp: hmp_cont(): don't rely on QERR_DEVICE_ENCRYPTED
    
    This commit changes hmp_cont() to loop through all block devices
    and proactively set an encryption key for any encrypted device
    missing a key.
    
    This change is needed because QERR_DEVICE_ENCRYPTED is going to be
    dropped by a future commit.
    
    Signed-off-by: Luiz Capitulino <lcapitulino at redhat.com>
    Reviewed-by: Markus Armbruster <armbru at redhat.com>

diff --git a/hmp.c b/hmp.c
index 25688ab..4efaf51 100644
--- a/hmp.c
+++ b/hmp.c
@@ -612,34 +612,35 @@ void hmp_pmemsave(Monitor *mon, const QDict *qdict)
 
 static void hmp_cont_cb(void *opaque, int err)
 {
-    Monitor *mon = opaque;
-
     if (!err) {
-        hmp_cont(mon, NULL);
+        qmp_cont(NULL);
     }
 }
 
+static bool key_is_missing(const BlockInfo *bdev)
+{
+    return (bdev->inserted && bdev->inserted->encryption_key_missing);
+}
+
 void hmp_cont(Monitor *mon, const QDict *qdict)
 {
+    BlockInfoList *bdev_list, *bdev;
     Error *errp = NULL;
 
-    qmp_cont(&errp);
-    if (error_is_set(&errp)) {
-        if (error_is_type(errp, QERR_DEVICE_ENCRYPTED)) {
-            const char *device;
-
-            /* The device is encrypted. Ask the user for the password
-               and retry */
-
-            device = error_get_field(errp, "device");
-            assert(device != NULL);
-
-            monitor_read_block_device_key(mon, device, hmp_cont_cb, mon);
-            error_free(errp);
-            return;
+    bdev_list = qmp_query_block(NULL);
+    for (bdev = bdev_list; bdev; bdev = bdev->next) {
+        if (key_is_missing(bdev->value)) {
+            monitor_read_block_device_key(mon, bdev->value->device,
+                                          hmp_cont_cb, NULL);
+            goto out;
         }
-        hmp_handle_error(mon, &errp);
     }
+
+    qmp_cont(&errp);
+    hmp_handle_error(mon, &errp);
+
+out:
+    qapi_free_BlockInfoList(bdev_list);
 }
 
 void hmp_system_wakeup(Monitor *mon, const QDict *qdict)
commit c75a1a8a5a34ef10f704c521c475a6dd4de5e887
Author: Luiz Capitulino <lcapitulino at redhat.com>
Date:   Thu Jul 26 20:28:44 2012 -0300

    qmp: query-block: add 'encryption_key_missing' field
    
    Signed-off-by: Luiz Capitulino <lcapitulino at redhat.com>
    Reviewed-by: Markus Armbruster <armbru at redhat.com>

diff --git a/block.c b/block.c
index 24323c1..016858b 100644
--- a/block.c
+++ b/block.c
@@ -2445,6 +2445,7 @@ BlockInfoList *qmp_query_block(Error **errp)
             info->value->inserted->ro = bs->read_only;
             info->value->inserted->drv = g_strdup(bs->drv->format_name);
             info->value->inserted->encrypted = bs->encrypted;
+            info->value->inserted->encryption_key_missing = bdrv_key_required(bs);
             if (bs->backing_file[0]) {
                 info->value->inserted->has_backing_file = true;
                 info->value->inserted->backing_file = g_strdup(bs->backing_file);
diff --git a/qapi-schema.json b/qapi-schema.json
index bd9c450..a62bf68 100644
--- a/qapi-schema.json
+++ b/qapi-schema.json
@@ -402,6 +402,9 @@
 #
 # @encrypted: true if the backing device is encrypted
 #
+# @encryption_key_missing: true if the backing device is encrypted but an
+#                          valid encryption key is missing
+#
 # @bps: total throughput limit in bytes per second is specified
 #
 # @bps_rd: read throughput limit in bytes per second is specified
@@ -421,9 +424,9 @@
 { 'type': 'BlockDeviceInfo',
   'data': { 'file': 'str', 'ro': 'bool', 'drv': 'str',
             '*backing_file': 'str', 'backing_file_depth': 'int',
-            'encrypted': 'bool', 'bps': 'int', 'bps_rd': 'int',
-            'bps_wr': 'int', 'iops': 'int', 'iops_rd': 'int',
-            'iops_wr': 'int'} }
+            'encrypted': 'bool', 'encryption_key_missing': 'bool',
+            'bps': 'int', 'bps_rd': 'int', 'bps_wr': 'int',
+            'iops': 'int', 'iops_rd': 'int', 'iops_wr': 'int'} }
 
 ##
 # @BlockDeviceIoStatus:
commit dd7520f0646985b08024c73ba2285c31d7318755
Author: Luiz Capitulino <lcapitulino at redhat.com>
Date:   Fri Jul 20 13:43:37 2012 -0300

    error: don't delay error message construction
    
    Today, the error message is only constructed when it's used. This commit
    changes that to construct the error message when the error object is
    built (ie. when the error is reported).
    
    This simplifies the Error object.
    
    Signed-off-by: Luiz Capitulino <lcapitulino at redhat.com>
    Reviewed-by: Markus Armbruster <armbru at redhat.com>

diff --git a/error.c b/error.c
index 3a62592..2ade99b 100644
--- a/error.c
+++ b/error.c
@@ -20,7 +20,6 @@
 struct Error
 {
     QDict *obj;
-    const char *fmt;
     char *msg;
 };
 
@@ -39,7 +38,7 @@ void error_set(Error **errp, const char *fmt, ...)
     va_start(ap, fmt);
     err->obj = qobject_to_qdict(qobject_from_jsonv(fmt, &ap));
     va_end(ap);
-    err->fmt = fmt;
+    err->msg = qerror_format(fmt, err->obj);
 
     *errp = err;
 }
@@ -50,7 +49,6 @@ Error *error_copy(const Error *err)
 
     err_new = g_malloc0(sizeof(*err));
     err_new->msg = g_strdup(err->msg);
-    err_new->fmt = err->fmt;
     err_new->obj = err->obj;
     QINCREF(err_new->obj);
 
@@ -64,10 +62,6 @@ bool error_is_set(Error **errp)
 
 const char *error_get_pretty(Error *err)
 {
-    if (err->msg == NULL) {
-        err->msg = qerror_format(err->fmt, err->obj);
-    }
-
     return err->msg;
 }
 
diff --git a/qerror.c b/qerror.c
index a254f88..5d38428 100644
--- a/qerror.c
+++ b/qerror.c
@@ -543,7 +543,6 @@ void qerror_report(const char *fmt, ...)
 struct Error
 {
     QDict *obj;
-    const char *fmt;
     char *msg;
 };
 
@@ -555,8 +554,7 @@ void qerror_report_err(Error *err)
     loc_save(&qerr->loc);
     QINCREF(err->obj);
     qerr->error = err->obj;
-
-    qerr->err_msg = qerror_format(err->fmt, qerr->error);
+    qerr->err_msg = g_strdup(err->msg);
 
     if (monitor_cur_is_qmp()) {
         monitor_set_error(cur_mon, qerr);
commit 18da7c0f1f24cc00f7c2f80c27cb85e4b234e091
Author: Luiz Capitulino <lcapitulino at redhat.com>
Date:   Fri Jul 20 12:02:58 2012 -0300

    qerror: don't delay error message construction
    
    Today, the error message is only constructed when it's used. This commit
    changes qerror to construct the error message when the error object is
    built (ie. when the error is reported).
    
    This eliminates the need of storing a pointer to qerror_table[], which
    will be dropped soon, and also simplifies the code.
    
    Signed-off-by: Luiz Capitulino <lcapitulino at redhat.com>
    Reviewed-by: Markus Armbruster <armbru at redhat.com>

diff --git a/qerror.c b/qerror.c
index d073ed7..a254f88 100644
--- a/qerror.c
+++ b/qerror.c
@@ -385,22 +385,6 @@ static QDict *error_obj_from_fmt_no_fail(const char *fmt, va_list *va)
     return ret;
 }
 
-static const QErrorStringTable *get_desc_no_fail(const char *fmt)
-{
-    int i;
-
-    // FIXME: inefficient loop
-
-    for (i = 0; qerror_table[i].error_fmt; i++) {
-        if (strcmp(qerror_table[i].error_fmt, fmt) == 0) {
-            return &qerror_table[i];
-        }
-    }
-
-    fprintf(stderr, "error format '%s' not found\n", fmt);
-    abort();
-}
-
 /**
  * qerror_from_info(): Create a new QError from error information
  *
@@ -414,7 +398,7 @@ static QError *qerror_from_info(const char *fmt, va_list *va)
     loc_save(&qerr->loc);
 
     qerr->error = error_obj_from_fmt_no_fail(fmt, va);
-    qerr->entry = get_desc_no_fail(fmt);
+    qerr->err_msg = qerror_format(fmt, qerr->error);
 
     return qerr;
 }
@@ -519,7 +503,7 @@ char *qerror_format(const char *fmt, QDict *error)
  */
 QString *qerror_human(const QError *qerror)
 {
-    return qerror_format_desc(qerror->error, qerror->entry);
+    return qstring_from_str(qerror->err_msg);
 }
 
 /**
@@ -566,19 +550,13 @@ struct Error
 void qerror_report_err(Error *err)
 {
     QError *qerr;
-    int i;
 
     qerr = qerror_new();
     loc_save(&qerr->loc);
     QINCREF(err->obj);
     qerr->error = err->obj;
 
-    for (i = 0; qerror_table[i].error_fmt; i++) {
-        if (strcmp(qerror_table[i].error_fmt, err->fmt) == 0) {
-            qerr->entry = &qerror_table[i];
-            break;
-        }
-    }
+    qerr->err_msg = qerror_format(err->fmt, qerr->error);
 
     if (monitor_cur_is_qmp()) {
         monitor_set_error(cur_mon, qerr);
@@ -619,5 +597,6 @@ static void qerror_destroy_obj(QObject *obj)
     qerr = qobject_to_qerror(obj);
 
     QDECREF(qerr->error);
+    g_free(qerr->err_msg);
     g_free(qerr);
 }
diff --git a/qerror.h b/qerror.h
index aec76b2..de8497d 100644
--- a/qerror.h
+++ b/qerror.h
@@ -27,7 +27,7 @@ typedef struct QError {
     QObject_HEAD;
     QDict *error;
     Location loc;
-    const QErrorStringTable *entry;
+    char *err_msg;
 } QError;
 
 QString *qerror_human(const QError *qerror);
commit 2b38cf2e033d90fb50fc967f535935b170dc507d
Author: Luiz Capitulino <lcapitulino at redhat.com>
Date:   Fri Jul 20 13:30:18 2012 -0300

    qerror: qerror_format(): return an allocated string
    
    Simplifies current and future users.
    
    Signed-off-by: Luiz Capitulino <lcapitulino at redhat.com>
    Reviewed-by: Markus Armbruster <armbru at redhat.com>

diff --git a/error.c b/error.c
index 58f55a0..3a62592 100644
--- a/error.c
+++ b/error.c
@@ -65,10 +65,7 @@ bool error_is_set(Error **errp)
 const char *error_get_pretty(Error *err)
 {
     if (err->msg == NULL) {
-        QString *str;
-        str = qerror_format(err->fmt, err->obj);
-        err->msg = g_strdup(qstring_get_str(str));
-        QDECREF(str);
+        err->msg = qerror_format(err->fmt, err->obj);
     }
 
     return err->msg;
diff --git a/qerror.c b/qerror.c
index 6f9f49c..d073ed7 100644
--- a/qerror.c
+++ b/qerror.c
@@ -493,9 +493,11 @@ static QString *qerror_format_desc(QDict *error,
     return qstring;
 }
 
-QString *qerror_format(const char *fmt, QDict *error)
+char *qerror_format(const char *fmt, QDict *error)
 {
     const QErrorStringTable *entry = NULL;
+    QString *qstr;
+    char *ret;
     int i;
 
     for (i = 0; qerror_table[i].error_fmt; i++) {
@@ -505,7 +507,11 @@ QString *qerror_format(const char *fmt, QDict *error)
         }
     }
 
-    return qerror_format_desc(error, entry);
+    qstr = qerror_format_desc(error, entry);
+    ret = g_strdup(qstring_get_str(qstr));
+    QDECREF(qstr);
+
+    return ret;
 }
 
 /**
diff --git a/qerror.h b/qerror.h
index 3c0b14c..aec76b2 100644
--- a/qerror.h
+++ b/qerror.h
@@ -34,7 +34,7 @@ QString *qerror_human(const QError *qerror);
 void qerror_report(const char *fmt, ...) GCC_FMT_ATTR(1, 2);
 void qerror_report_err(Error *err);
 void assert_no_error(Error *err);
-QString *qerror_format(const char *fmt, QDict *error);
+char *qerror_format(const char *fmt, QDict *error);
 
 /*
  * QError class list
commit 5f0f0e13e1f714704d96f04050674c3102376409
Author: Luiz Capitulino <lcapitulino at redhat.com>
Date:   Fri Jul 20 11:08:17 2012 -0300

    qerror: QError: drop file, linenr, func
    
    They have never been fully used and conflict with future error
    improvements.
    
    Also makes qerror_report() a proper function, as there's no point
    in having it as a macro anymore.
    
    Signed-off-by: Luiz Capitulino <lcapitulino at redhat.com>
    Reviewed-by: Markus Armbruster <armbru at redhat.com>

diff --git a/qerror.c b/qerror.c
index e717496..6f9f49c 100644
--- a/qerror.c
+++ b/qerror.c
@@ -404,27 +404,14 @@ static const QErrorStringTable *get_desc_no_fail(const char *fmt)
 /**
  * qerror_from_info(): Create a new QError from error information
  *
- * The information consists of:
- *
- * - file   the file name of where the error occurred
- * - linenr the line number of where the error occurred
- * - func   the function name of where the error occurred
- * - fmt    JSON printf-like dictionary, there must exist keys 'class' and
- *          'data'
- * - va     va_list of all arguments specified by fmt
- *
  * Return strong reference.
  */
-static QError *qerror_from_info(const char *file, int linenr, const char *func,
-                                const char *fmt, va_list *va)
+static QError *qerror_from_info(const char *fmt, va_list *va)
 {
     QError *qerr;
 
     qerr = qerror_new();
     loc_save(&qerr->loc);
-    qerr->linenr = linenr;
-    qerr->file = file;
-    qerr->func = func;
 
     qerr->error = error_obj_from_fmt_no_fail(fmt, va);
     qerr->entry = get_desc_no_fail(fmt);
@@ -545,14 +532,13 @@ static void qerror_print(QError *qerror)
     QDECREF(qstring);
 }
 
-void qerror_report_internal(const char *file, int linenr, const char *func,
-                            const char *fmt, ...)
+void qerror_report(const char *fmt, ...)
 {
     va_list va;
     QError *qerror;
 
     va_start(va, fmt);
-    qerror = qerror_from_info(file, linenr, func, fmt, &va);
+    qerror = qerror_from_info(fmt, &va);
     va_end(va);
 
     if (monitor_cur_is_qmp()) {
diff --git a/qerror.h b/qerror.h
index fe8870c..3c0b14c 100644
--- a/qerror.h
+++ b/qerror.h
@@ -27,20 +27,14 @@ typedef struct QError {
     QObject_HEAD;
     QDict *error;
     Location loc;
-    int linenr;
-    const char *file;
-    const char *func;
     const QErrorStringTable *entry;
 } QError;
 
 QString *qerror_human(const QError *qerror);
-void qerror_report_internal(const char *file, int linenr, const char *func,
-                            const char *fmt, ...) GCC_FMT_ATTR(4, 5);
+void qerror_report(const char *fmt, ...) GCC_FMT_ATTR(1, 2);
 void qerror_report_err(Error *err);
 void assert_no_error(Error *err);
 QString *qerror_format(const char *fmt, QDict *error);
-#define qerror_report(fmt, ...) \
-    qerror_report_internal(__FILE__, __LINE__, __func__, fmt, ## __VA_ARGS__)
 
 /*
  * QError class list
commit f2dd1d69edf0080d7d08dd3e8c7bfc6b488d59e4
Author: Luiz Capitulino <lcapitulino at redhat.com>
Date:   Tue Jul 31 15:41:13 2012 -0300

    qerror: avoid passing qerr pointer
    
    Helps dropping/modifying qerror functions.
    
    Signed-off-by: Luiz Capitulino <lcapitulino at redhat.com>
    Reviewed-by: Markus Armbruster <armbru at redhat.com>

diff --git a/qerror.c b/qerror.c
index 7cb7c12..e717496 100644
--- a/qerror.c
+++ b/qerror.c
@@ -346,10 +346,10 @@ static QError *qerror_new(void)
     return qerr;
 }
 
-static void GCC_FMT_ATTR(2, 0) qerror_set_data(QError *qerr,
-                                               const char *fmt, va_list *va)
+static QDict *error_obj_from_fmt_no_fail(const char *fmt, va_list *va)
 {
     QObject *obj;
+    QDict *ret;
 
     obj = qobject_from_jsonv(fmt, va);
     if (!obj) {
@@ -361,9 +361,8 @@ static void GCC_FMT_ATTR(2, 0) qerror_set_data(QError *qerr,
         abort();
     }
 
-    qerr->error = qobject_to_qdict(obj);
-
-    obj = qdict_get(qerr->error, "class");
+    ret = qobject_to_qdict(obj);
+    obj = qdict_get(ret, "class");
     if (!obj) {
         fprintf(stderr, "missing 'class' key in '%s'\n", fmt);
         abort();
@@ -372,8 +371,8 @@ static void GCC_FMT_ATTR(2, 0) qerror_set_data(QError *qerr,
         fprintf(stderr, "'class' key value should be a string in '%s'\n", fmt);
         abort();
     }
-    
-    obj = qdict_get(qerr->error, "data");
+
+    obj = qdict_get(ret, "data");
     if (!obj) {
         fprintf(stderr, "missing 'data' key in '%s'\n", fmt);
         abort();
@@ -382,9 +381,11 @@ static void GCC_FMT_ATTR(2, 0) qerror_set_data(QError *qerr,
         fprintf(stderr, "'data' key value should be a dict in '%s'\n", fmt);
         abort();
     }
+
+    return ret;
 }
 
-static void qerror_set_desc(QError *qerr, const char *fmt)
+static const QErrorStringTable *get_desc_no_fail(const char *fmt)
 {
     int i;
 
@@ -392,8 +393,7 @@ static void qerror_set_desc(QError *qerr, const char *fmt)
 
     for (i = 0; qerror_table[i].error_fmt; i++) {
         if (strcmp(qerror_table[i].error_fmt, fmt) == 0) {
-            qerr->entry = &qerror_table[i];
-            return;
+            return &qerror_table[i];
         }
     }
 
@@ -426,8 +426,8 @@ static QError *qerror_from_info(const char *file, int linenr, const char *func,
     qerr->file = file;
     qerr->func = func;
 
-    qerror_set_data(qerr, fmt, va);
-    qerror_set_desc(qerr, fmt);
+    qerr->error = error_obj_from_fmt_no_fail(fmt, va);
+    qerr->entry = get_desc_no_fail(fmt);
 
     return qerr;
 }
commit fbe0a831f68348d228acd9a4ec8a25582396282a
Author: Luiz Capitulino <lcapitulino at redhat.com>
Date:   Fri Jul 20 10:35:18 2012 -0300

    qerror: drop qerror_abort()
    
    qerror_abort() depends on the 'file', 'func' and 'linenr' members of
    QError. However, these members are going to be dropped by the next
    commit, so let's drop qerror_abort() in favor of printing an error
    message to stderr plus a call to abort().
    
    Signed-off-by: Luiz Capitulino <lcapitulino at redhat.com>
    Reviewed-by: Markus Armbruster <armbru at redhat.com>

diff --git a/qerror.c b/qerror.c
index bfb875a..7cb7c12 100644
--- a/qerror.c
+++ b/qerror.c
@@ -346,22 +346,6 @@ static QError *qerror_new(void)
     return qerr;
 }
 
-static void GCC_FMT_ATTR(2, 3) qerror_abort(const QError *qerr,
-                                            const char *fmt, ...)
-{
-    va_list ap;
-
-    fprintf(stderr, "qerror: bad call in function '%s':\n", qerr->func);
-    fprintf(stderr, "qerror: -> ");
-
-    va_start(ap, fmt);
-    vfprintf(stderr, fmt, ap);
-    va_end(ap);
-
-    fprintf(stderr, "\nqerror: call at %s:%d\n", qerr->file, qerr->linenr);
-    abort();
-}
-
 static void GCC_FMT_ATTR(2, 0) qerror_set_data(QError *qerr,
                                                const char *fmt, va_list *va)
 {
@@ -369,28 +353,34 @@ static void GCC_FMT_ATTR(2, 0) qerror_set_data(QError *qerr,
 
     obj = qobject_from_jsonv(fmt, va);
     if (!obj) {
-        qerror_abort(qerr, "invalid format '%s'", fmt);
+        fprintf(stderr, "invalid json in error dict '%s'\n", fmt);
+        abort();
     }
     if (qobject_type(obj) != QTYPE_QDICT) {
-        qerror_abort(qerr, "error format is not a QDict '%s'", fmt);
+        fprintf(stderr, "error is not a dict '%s'\n", fmt);
+        abort();
     }
 
     qerr->error = qobject_to_qdict(obj);
 
     obj = qdict_get(qerr->error, "class");
     if (!obj) {
-        qerror_abort(qerr, "missing 'class' key in '%s'", fmt);
+        fprintf(stderr, "missing 'class' key in '%s'\n", fmt);
+        abort();
     }
     if (qobject_type(obj) != QTYPE_QSTRING) {
-        qerror_abort(qerr, "'class' key value should be a QString");
+        fprintf(stderr, "'class' key value should be a string in '%s'\n", fmt);
+        abort();
     }
     
     obj = qdict_get(qerr->error, "data");
     if (!obj) {
-        qerror_abort(qerr, "missing 'data' key in '%s'", fmt);
+        fprintf(stderr, "missing 'data' key in '%s'\n", fmt);
+        abort();
     }
     if (qobject_type(obj) != QTYPE_QDICT) {
-        qerror_abort(qerr, "'data' key value should be a QDICT");
+        fprintf(stderr, "'data' key value should be a dict in '%s'\n", fmt);
+        abort();
     }
 }
 
@@ -407,7 +397,8 @@ static void qerror_set_desc(QError *qerr, const char *fmt)
         }
     }
 
-    qerror_abort(qerr, "error format '%s' not found", fmt);
+    fprintf(stderr, "error format '%s' not found\n", fmt);
+    abort();
 }
 
 /**
@@ -435,10 +426,6 @@ static QError *qerror_from_info(const char *file, int linenr, const char *func,
     qerr->file = file;
     qerr->func = func;
 
-    if (!fmt) {
-        qerror_abort(qerr, "QDict not specified");
-    }
-
     qerror_set_data(qerr, fmt, va);
     qerror_set_desc(qerr, fmt);
 
commit 2a74440547ea0a15195224fa2b7784b267cbfe15
Author: Luiz Capitulino <lcapitulino at redhat.com>
Date:   Thu Jul 19 17:29:34 2012 -0300

    qerror: reduce public exposure
    
    qerror will be dropped in a near future, let's reduce its public
    exposure by making functions only used in qerror.c static.
    
    Signed-off-by: Luiz Capitulino <lcapitulino at redhat.com>
    Reviewed-by: Markus Armbruster <armbru at redhat.com>

diff --git a/qerror.c b/qerror.c
index de0a79e..bfb875a 100644
--- a/qerror.c
+++ b/qerror.c
@@ -336,7 +336,7 @@ static const QErrorStringTable qerror_table[] = {
  *
  * Return strong reference.
  */
-QError *qerror_new(void)
+static QError *qerror_new(void)
 {
     QError *qerr;
 
@@ -424,8 +424,8 @@ static void qerror_set_desc(QError *qerr, const char *fmt)
  *
  * Return strong reference.
  */
-QError *qerror_from_info(const char *file, int linenr, const char *func,
-                         const char *fmt, va_list *va)
+static QError *qerror_from_info(const char *file, int linenr, const char *func,
+                                const char *fmt, va_list *va)
 {
     QError *qerr;
 
@@ -549,7 +549,7 @@ QString *qerror_human(const QError *qerror)
  * it uses error_report() for this, so that the output is routed to the right
  * place (ie. stderr or Monitor's device).
  */
-void qerror_print(QError *qerror)
+static void qerror_print(QError *qerror)
 {
     QString *qstring = qerror_human(qerror);
     loc_push_restore(&qerror->loc);
@@ -620,7 +620,7 @@ void assert_no_error(Error *err)
 /**
  * qobject_to_qerror(): Convert a QObject into a QError
  */
-QError *qobject_to_qerror(const QObject *obj)
+static QError *qobject_to_qerror(const QObject *obj)
 {
     if (qobject_type(obj) != QTYPE_QERROR) {
         return NULL;
diff --git a/qerror.h b/qerror.h
index b4c8758..fe8870c 100644
--- a/qerror.h
+++ b/qerror.h
@@ -33,11 +33,7 @@ typedef struct QError {
     const QErrorStringTable *entry;
 } QError;
 
-QError *qerror_new(void);
-QError *qerror_from_info(const char *file, int linenr, const char *func,
-                         const char *fmt, va_list *va) GCC_FMT_ATTR(4, 0);
 QString *qerror_human(const QError *qerror);
-void qerror_print(QError *qerror);
 void qerror_report_internal(const char *file, int linenr, const char *func,
                             const char *fmt, ...) GCC_FMT_ATTR(4, 5);
 void qerror_report_err(Error *err);
@@ -45,7 +41,6 @@ void assert_no_error(Error *err);
 QString *qerror_format(const char *fmt, QDict *error);
 #define qerror_report(fmt, ...) \
     qerror_report_internal(__FILE__, __LINE__, __func__, fmt, ## __VA_ARGS__)
-QError *qobject_to_qerror(const QObject *obj);
 
 /*
  * QError class list
commit b5d90f0424ea27eb126a4eaed2554908fc463d9f
Author: Luiz Capitulino <lcapitulino at redhat.com>
Date:   Wed Jul 25 13:16:53 2012 -0300

    qerror: QERR_DEVICE_ENCRYPTED: change error message
    
    Match what HMP commands print on DeviceEncrypted errors.
    
    Signed-off-by: Luiz Capitulino <lcapitulino at redhat.com>
    Reviewed-by: Markus Armbruster <armbru at redhat.com>

diff --git a/qerror.c b/qerror.c
index 082de98..de0a79e 100644
--- a/qerror.c
+++ b/qerror.c
@@ -81,7 +81,7 @@ static const QErrorStringTable qerror_table[] = {
     },
     {
         .error_fmt = QERR_DEVICE_ENCRYPTED,
-        .desc      = "Device '%(device)' is encrypted",
+        .desc      = "'%(device)' (%(filename)) is encrypted",
     },
     {
         .error_fmt = QERR_DEVICE_FEATURE_BLOCKS_MIGRATION,
commit 484051b9960736a6ebff3cfed78c4b29758e63c0
Author: Luiz Capitulino <lcapitulino at redhat.com>
Date:   Wed Jul 25 13:18:41 2012 -0300

    qerror: QERR_AMBIGUOUS_PATH: drop %(object) from human msg
    
    Actually, renames it to 'object'. This must be what the original author
    meant to write, as there's no 'object' in the error's data member.
    
    Signed-off-by: Luiz Capitulino <lcapitulino at redhat.com>
    Reviewed-by: Markus Armbruster <armbru at redhat.com>

diff --git a/qerror.c b/qerror.c
index 92c4eff..082de98 100644
--- a/qerror.c
+++ b/qerror.c
@@ -49,7 +49,7 @@ static const QErrorStringTable qerror_table[] = {
     },
     {
         .error_fmt = QERR_AMBIGUOUS_PATH,
-        .desc      = "Path '%(path)' does not uniquely identify a %(object)"
+        .desc      = "Path '%(path)' does not uniquely identify an object"
     },
     {
         .error_fmt = QERR_BAD_BUS_FOR_DEVICE,
commit 74ee59a825f9c0e6b5a95bea3b7ac4627526f42d
Author: Luiz Capitulino <lcapitulino at redhat.com>
Date:   Thu Jul 19 19:34:38 2012 -0300

    monitor: drop unused monitor debug code
    
    In the old QMP days, this code was used to find out QMP commands that
    might be calling monitor_printf() down its call chain.
    
    This is almost impossible to happen today, because the qapi converted
    commands don't even have a monitor object. Besides, it's been more than
    a year since I used this last time.
    
    Let's just drop it.
    
    Signed-off-by: Luiz Capitulino <lcapitulino at redhat.com>
    Reviewed-by: Markus Armbruster <armbru at redhat.com>

diff --git a/configure b/configure
index f0dbc03..8a06c11 100755
--- a/configure
+++ b/configure
@@ -171,7 +171,6 @@ vhost_net="no"
 kvm="no"
 gprof="no"
 debug_tcg="no"
-debug_mon="no"
 debug="no"
 strip_opt="yes"
 tcg_interpreter="no"
@@ -657,14 +656,9 @@ for opt do
   ;;
   --disable-debug-tcg) debug_tcg="no"
   ;;
-  --enable-debug-mon) debug_mon="yes"
-  ;;
-  --disable-debug-mon) debug_mon="no"
-  ;;
   --enable-debug)
       # Enable debugging options that aren't excessively noisy
       debug_tcg="yes"
-      debug_mon="yes"
       debug="yes"
       strip_opt="no"
   ;;
@@ -3064,7 +3058,6 @@ echo "host CPU          $cpu"
 echo "host big endian   $bigendian"
 echo "target list       $target_list"
 echo "tcg debug enabled $debug_tcg"
-echo "Mon debug enabled $debug_mon"
 echo "gprof enabled     $gprof"
 echo "sparse enabled    $sparse"
 echo "strip binaries    $strip_opt"
@@ -3157,9 +3150,6 @@ echo "ARCH=$ARCH" >> $config_host_mak
 if test "$debug_tcg" = "yes" ; then
   echo "CONFIG_DEBUG_TCG=y" >> $config_host_mak
 fi
-if test "$debug_mon" = "yes" ; then
-  echo "CONFIG_DEBUG_MONITOR=y" >> $config_host_mak
-fi
 if test "$debug" = "yes" ; then
   echo "CONFIG_DEBUG_EXEC=y" >> $config_host_mak
 fi
diff --git a/monitor.c b/monitor.c
index 49dccfe..aa57167 100644
--- a/monitor.c
+++ b/monitor.c
@@ -172,41 +172,11 @@ struct Monitor {
     CPUArchState *mon_cpu;
     BlockDriverCompletionFunc *password_completion_cb;
     void *password_opaque;
-#ifdef CONFIG_DEBUG_MONITOR
-    int print_calls_nr;
-#endif
     QError *error;
     QLIST_HEAD(,mon_fd_t) fds;
     QLIST_ENTRY(Monitor) entry;
 };
 
-#ifdef CONFIG_DEBUG_MONITOR
-#define MON_DEBUG(fmt, ...) do {    \
-    fprintf(stderr, "Monitor: ");       \
-    fprintf(stderr, fmt, ## __VA_ARGS__); } while (0)
-
-static inline void mon_print_count_inc(Monitor *mon)
-{
-    mon->print_calls_nr++;
-}
-
-static inline void mon_print_count_init(Monitor *mon)
-{
-    mon->print_calls_nr = 0;
-}
-
-static inline int mon_print_count_get(const Monitor *mon)
-{
-    return mon->print_calls_nr;
-}
-
-#else /* !CONFIG_DEBUG_MONITOR */
-#define MON_DEBUG(fmt, ...) do { } while (0)
-static inline void mon_print_count_inc(Monitor *mon) { }
-static inline void mon_print_count_init(Monitor *mon) { }
-static inline int mon_print_count_get(const Monitor *mon) { return 0; }
-#endif /* CONFIG_DEBUG_MONITOR */
-
 /* QMP checker flags */
 #define QMP_ACCEPT_UNKNOWNS 1
 
@@ -299,8 +269,6 @@ void monitor_vprintf(Monitor *mon, const char *fmt, va_list ap)
     if (!mon)
         return;
 
-    mon_print_count_inc(mon);
-
     if (monitor_ctrl_mode(mon)) {
         return;
     }
@@ -3860,8 +3828,6 @@ void monitor_set_error(Monitor *mon, QError *qerror)
     if (!mon->error) {
         mon->error = qerror;
     } else {
-        MON_DEBUG("Additional error report at %s:%d\n",
-                  qerror->file, qerror->linenr);
         QDECREF(qerror);
     }
 }
@@ -3875,36 +3841,7 @@ static void handler_audit(Monitor *mon, const mon_cmd_t *cmd, int ret)
          * Action: Report an internal error to the client if in QMP.
          */
         qerror_report(QERR_UNDEFINED_ERROR);
-        MON_DEBUG("command '%s' returned failure but did not pass an error\n",
-                  cmd->name);
     }
-
-#ifdef CONFIG_DEBUG_MONITOR
-    if (!ret && monitor_has_error(mon)) {
-        /*
-         * If it returns success, it must not have passed an error.
-         *
-         * Action: Report the passed error to the client.
-         */
-        MON_DEBUG("command '%s' returned success but passed an error\n",
-                  cmd->name);
-    }
-
-    if (mon_print_count_get(mon) > 0 && strcmp(cmd->name, "info") != 0) {
-        /*
-         * Handlers should not call Monitor print functions.
-         *
-         * Action: Ignore them in QMP.
-         *
-         * (XXX: we don't check any 'info' or 'query' command here
-         * because the user print function _is_ called by do_info(), hence
-         * we will trigger this check. This problem will go away when we
-         * make 'query' commands real and kill do_info())
-         */
-        MON_DEBUG("command '%s' called print functions %d time(s)\n",
-                  cmd->name, mon_print_count_get(mon));
-    }
-#endif
 }
 
 static void handle_user_command(Monitor *mon, const char *cmdline)
@@ -4433,8 +4370,6 @@ static void qmp_call_cmd(Monitor *mon, const mon_cmd_t *cmd,
     int ret;
     QObject *data = NULL;
 
-    mon_print_count_init(mon);
-
     ret = cmd->mhandler.cmd_new(mon, params, &data);
     handler_audit(mon, cmd, ret);
     monitor_protocol_emitter(mon, data);
commit 58f9b98f8a341c8b7bb0c9b38e492a01fe71d666
Author: Andreas Färber <afaerber at suse.de>
Date:   Mon Aug 13 02:11:12 2012 +0000

    arm: Move some ARM devices into libhw
    
    Avoids some unnecessary dependencies on cpu.h and prepares for
    a future armeb-softmmu where most machines would not be built.
    
    Defer touching the SoC devices since most have implicit or explicit
    dependencies on the CPU.
    
    Signed-off-by: Andreas Färber <andreas.faerber at suse.de>
    Signed-off-by: Peter Maydell <peter.maydell at linaro.org>

diff --git a/default-configs/arm-softmmu.mak b/default-configs/arm-softmmu.mak
index e542b4f..f335a72 100644
--- a/default-configs/arm-softmmu.mak
+++ b/default-configs/arm-softmmu.mak
@@ -27,3 +27,21 @@ CONFIG_SMC91C111=y
 CONFIG_DS1338=y
 CONFIG_PFLASH_CFI01=y
 CONFIG_PFLASH_CFI02=y
+
+CONFIG_ARM_TIMER=y
+CONFIG_PL011=y
+CONFIG_PL022=y
+CONFIG_PL031=y
+CONFIG_PL041=y
+CONFIG_PL050=y
+CONFIG_PL061=y
+CONFIG_PL080=y
+CONFIG_PL110=y
+CONFIG_PL181=y
+CONFIG_PL190=y
+CONFIG_PL310=y
+CONFIG_CADENCE=y
+CONFIG_XGMAC=y
+
+CONFIG_VERSATILE_PCI=y
+CONFIG_VERSATILE_I2C=y
diff --git a/hw/Makefile.objs b/hw/Makefile.objs
index 6eee9a0..7f57ed5 100644
--- a/hw/Makefile.objs
+++ b/hw/Makefile.objs
@@ -74,6 +74,26 @@ hw-obj-$(CONFIG_PUV3) += puv3_gpio.o
 hw-obj-$(CONFIG_PUV3) += puv3_pm.o
 hw-obj-$(CONFIG_PUV3) += puv3_dma.o
 
+# ARM devices
+hw-obj-$(CONFIG_ARM_TIMER) += arm_timer.o
+hw-obj-$(CONFIG_PL011) += pl011.o
+hw-obj-$(CONFIG_PL022) += pl022.o
+hw-obj-$(CONFIG_PL031) += pl031.o
+hw-obj-$(CONFIG_PL041) += pl041.o lm4549.o
+hw-obj-$(CONFIG_PL050) += pl050.o
+hw-obj-$(CONFIG_PL061) += pl061.o
+hw-obj-$(CONFIG_PL080) += pl080.o
+hw-obj-$(CONFIG_PL110) += pl110.o
+hw-obj-$(CONFIG_PL181) += pl181.o
+hw-obj-$(CONFIG_PL190) += pl190.o
+hw-obj-$(CONFIG_PL310) += arm_l2x0.o
+hw-obj-$(CONFIG_VERSATILE_PCI) += versatile_pci.o
+hw-obj-$(CONFIG_VERSATILE_I2C) += versatile_i2c.o
+hw-obj-$(CONFIG_CADENCE) += cadence_uart.o
+hw-obj-$(CONFIG_CADENCE) += cadence_ttc.o
+hw-obj-$(CONFIG_CADENCE) += cadence_gem.o
+hw-obj-$(CONFIG_XGMAC) += xgmac.o
+
 # PCI watchdog devices
 hw-obj-$(CONFIG_PCI) += wdt_i6300esb.o
 
diff --git a/hw/arm/Makefile.objs b/hw/arm/Makefile.objs
index c413780..2b39fb3 100644
--- a/hw/arm/Makefile.objs
+++ b/hw/arm/Makefile.objs
@@ -1,10 +1,5 @@
-obj-y = integratorcp.o versatilepb.o arm_pic.o arm_timer.o
-obj-y += arm_boot.o pl011.o pl031.o pl050.o pl080.o pl110.o pl181.o pl190.o
-obj-y += versatile_pci.o
-obj-y += versatile_i2c.o
-obj-y += cadence_uart.o
-obj-y += cadence_ttc.o
-obj-y += cadence_gem.o
+obj-y = integratorcp.o versatilepb.o arm_pic.o
+obj-y += arm_boot.o
 obj-y += xilinx_zynq.o zynq_slcr.o
 obj-y += arm_gic.o arm_gic_common.o
 obj-y += realview_gic.o realview.o arm_sysctl.o arm11mpcore.o a9mpcore.o
@@ -12,12 +7,9 @@ obj-y += exynos4210_gic.o exynos4210_combiner.o exynos4210.o
 obj-y += exynos4_boards.o exynos4210_uart.o exynos4210_pwm.o
 obj-y += exynos4210_pmu.o exynos4210_mct.o exynos4210_fimd.o
 obj-y += exynos4210_rtc.o exynos4210_i2c.o
-obj-y += arm_l2x0.o
 obj-y += arm_mptimer.o a15mpcore.o
-obj-y += armv7m.o armv7m_nvic.o stellaris.o pl022.o stellaris_enet.o
+obj-y += armv7m.o armv7m_nvic.o stellaris.o stellaris_enet.o
 obj-y += highbank.o
-obj-y += pl061.o
-obj-y += xgmac.o
 obj-y += pxa2xx.o pxa2xx_pic.o pxa2xx_gpio.o pxa2xx_timer.o pxa2xx_dma.o
 obj-y += pxa2xx_lcd.o pxa2xx_mmci.o pxa2xx_pcmcia.o pxa2xx_keypad.o
 obj-y += gumstix.o
@@ -37,7 +29,6 @@ obj-y += strongarm.o
 obj-y += collie.o
 obj-y += imx_serial.o imx_ccm.o imx_timer.o imx_avic.o
 obj-y += kzm.o
-obj-y += pl041.o lm4549.o
 obj-$(CONFIG_FDT) += ../device_tree.o
 
 obj-y := $(addprefix ../,$(obj-y))
commit d517872ec289f5bfa6bd9f385a90e09483e9949c
Merge: 33e95c6... 96fda35...
Author: Anthony Liguori <aliguori at us.ibm.com>
Date:   Mon Aug 13 09:25:48 2012 -0500

    Merge remote-tracking branch 'qemu-kvm/uq/master' into staging
    
    * qemu-kvm/uq/master:
      kvm: Add documentation comment for kvm_irqchip_in_kernel()
      kvm: Decouple 'GSI routing' from 'kernel irqchip'
      kvm: Decouple 'MSI routing via irqfds' from 'kernel irqchip'
      kvm: Decouple 'irqfds usable' from 'kernel irqchip'
      kvm: Move kvm_allows_irq0_override() to target-i386, fix return type
      kvm: Rename kvm_irqchip_set_irq() to kvm_set_irq()
      kvm: Decouple 'async interrupt delivery' from 'kernel irqchip'
      configure: Don't implicitly hardcode list of KVM architectures
      kvm: Check if smp_cpus exceeds max cpus supported by kvm

commit dd6e957a142d9582df766b5c6de2fbb6773241f2
Author: Peter Maydell <peter.maydell at linaro.org>
Date:   Mon Jul 23 08:07:22 2012 +0000

    linux-user: Move target_to_host_errno_table[] setup out of ioctl loop
    
    The code to initialise the target_to_host_errno_table[] array was
    accidentally inside the loop through checking and initialising all
    the supported ioctls. This was harmless but meant that we reinitialised the
    array several hundred times on startup.
    
    Signed-off-by: Peter Maydell <peter.maydell at linaro.org>

diff --git a/linux-user/syscall.c b/linux-user/syscall.c
index 3ba3ef5..8a06131 100644
--- a/linux-user/syscall.c
+++ b/linux-user/syscall.c
@@ -4606,6 +4606,12 @@ void syscall_init(void)
 #undef STRUCT
 #undef STRUCT_SPECIAL
 
+    /* Build target_to_host_errno_table[] table from
+     * host_to_target_errno_table[]. */
+    for (i = 0; i < ERRNO_TABLE_SIZE; i++) {
+        target_to_host_errno_table[host_to_target_errno_table[i]] = i;
+    }
+
     /* we patch the ioctl size if necessary. We rely on the fact that
        no ioctl has all the bits at '1' in the size field */
     ie = ioctl_entries;
@@ -4625,11 +4631,6 @@ void syscall_init(void)
                 (size << TARGET_IOC_SIZESHIFT);
         }
 
-        /* Build target_to_host_errno_table[] table from
-         * host_to_target_errno_table[]. */
-        for (i=0; i < ERRNO_TABLE_SIZE; i++)
-                target_to_host_errno_table[host_to_target_errno_table[i]] = i;
-
         /* automatic consistency check if same arch */
 #if (defined(__i386__) && defined(TARGET_I386) && defined(TARGET_ABI32)) || \
     (defined(__x86_64__) && defined(TARGET_X86_64))
commit 5f72307d90a00caabdf786d940418f810bd7c095
Author: Peter Maydell <peter.maydell at linaro.org>
Date:   Mon Jul 23 08:06:15 2012 +0000

    linux-user: Fix SNDCTL_DSP_MAP{IN, OUT}BUF ioctl definitions
    
    Fix the SNDCTL_DSP_MAP{IN,OUT}BUF ioctl definitions so that they
    refer to a suitably defined target struct layout rather than hardcoding
    the ioctl number. This fixes complaints from the syscall_init()
    consistency check when running an x86_64-to-x86_64 linux-user qemu.
    
    Signed-off-by: Peter Maydell <peter.maydell at linaro.org>

diff --git a/linux-user/ioctls.h b/linux-user/ioctls.h
index eb96a08..8a47767 100644
--- a/linux-user/ioctls.h
+++ b/linux-user/ioctls.h
@@ -186,8 +186,8 @@
   IOCTL(SNDCTL_DSP_GETISPACE, IOC_R, MK_PTR(MK_STRUCT(STRUCT_audio_buf_info)))
   IOCTL(SNDCTL_DSP_GETOSPACE, IOC_R, MK_PTR(MK_STRUCT(STRUCT_audio_buf_info)))
   IOCTL(SNDCTL_DSP_GETTRIGGER, IOC_R, MK_PTR(TYPE_INT))
-  IOCTL(SNDCTL_DSP_MAPINBUF, IOC_R, MK_PTR(TYPE_INT))
-  IOCTL(SNDCTL_DSP_MAPOUTBUF, IOC_R, MK_PTR(TYPE_INT))
+  IOCTL(SNDCTL_DSP_MAPINBUF, IOC_R, MK_PTR(MK_STRUCT(STRUCT_buffmem_desc)))
+  IOCTL(SNDCTL_DSP_MAPOUTBUF, IOC_R, MK_PTR(MK_STRUCT(STRUCT_buffmem_desc)))
   IOCTL(SNDCTL_DSP_NONBLOCK, 0, TYPE_NULL)
   IOCTL(SNDCTL_DSP_POST, 0, TYPE_NULL)
   IOCTL(SNDCTL_DSP_RESET, 0, TYPE_NULL)
diff --git a/linux-user/syscall_defs.h b/linux-user/syscall_defs.h
index 2026579..2cfda5a 100644
--- a/linux-user/syscall_defs.h
+++ b/linux-user/syscall_defs.h
@@ -2226,8 +2226,8 @@ struct target_eabi_flock64 {
 #define TARGET_SNDCTL_DSP_GETTRIGGER      TARGET_IOR('P',16, int)
 #define TARGET_SNDCTL_DSP_GETIPTR         TARGET_IORU('P',17)
 #define TARGET_SNDCTL_DSP_GETOPTR         TARGET_IORU('P',18)
-#define TARGET_SNDCTL_DSP_MAPINBUF        0x80085013
-#define TARGET_SNDCTL_DSP_MAPOUTBUF       0x80085014
+#define TARGET_SNDCTL_DSP_MAPINBUF        TARGET_IORU('P', 19)
+#define TARGET_SNDCTL_DSP_MAPOUTBUF       TARGET_IORU('P', 20)
 #define TARGET_SNDCTL_DSP_NONBLOCK        0x0000500e
 #define TARGET_SNDCTL_DSP_SAMPLESIZE      0xc0045005
 #define TARGET_SNDCTL_DSP_SETDUPLEX       0x00005016
diff --git a/linux-user/syscall_types.h b/linux-user/syscall_types.h
index 601618d..44b6a58 100644
--- a/linux-user/syscall_types.h
+++ b/linux-user/syscall_types.h
@@ -77,6 +77,9 @@ STRUCT(audio_buf_info,
 STRUCT(count_info,
        TYPE_INT, TYPE_INT, TYPE_INT)
 
+STRUCT(buffmem_desc,
+       TYPE_PTRVOID, TYPE_INT)
+
 STRUCT(mixer_info,
        MK_ARRAY(TYPE_CHAR, 16), MK_ARRAY(TYPE_CHAR, 32), TYPE_INT, MK_ARRAY(TYPE_INT, 10))
 
commit c8b0bf545631b55f9e8288252a7b026a97872dd3
Author: Peter Maydell <peter.maydell at linaro.org>
Date:   Mon Jul 23 08:05:20 2012 +0000

    linux-user: Fix incorrect TARGET_BLKBSZGET, TARGET_BLKBSZSET
    
    The definitions for the ioctl numbers TARGET_BLKBSZGET and
    TARGET_BLKBSZSET had the wrong size parameters (they are defined
    with size_t, not int, even though the ioctl implementations themselves
    read and write integers). Since commit 354a0008 we now have an
    ioctl wrapper definition for BLKBSZGET and so on an x86-64-to-x86-64
    linux-user binary we were triggering the mismatch warning in
    syscall_init().
    
    Signed-off-by: Peter Maydell <peter.maydell at linaro.org>

diff --git a/linux-user/syscall_defs.h b/linux-user/syscall_defs.h
index ba9a58c..2026579 100644
--- a/linux-user/syscall_defs.h
+++ b/linux-user/syscall_defs.h
@@ -880,8 +880,8 @@ struct target_pollfd {
 #define TARGET_BLKSECTGET TARGET_IO(0x12,103)/* get max sectors per request (ll_rw_blk.c) */
 #define TARGET_BLKSSZGET  TARGET_IO(0x12,104)/* get block device sector size */
 /* A jump here: 108-111 have been used for various private purposes. */
-#define TARGET_BLKBSZGET  TARGET_IOR(0x12,112,int)
-#define TARGET_BLKBSZSET  TARGET_IOW(0x12,113,int)
+#define TARGET_BLKBSZGET  TARGET_IOR(0x12, 112, abi_ulong)
+#define TARGET_BLKBSZSET  TARGET_IOW(0x12, 113, abi_ulong)
 #define TARGET_BLKGETSIZE64 TARGET_IOR(0x12,114,abi_ulong)
                                              /* return device size in bytes
                                                 (u64 *arg) */
commit b1c265424abfa5a1b2589e606b4e4dafbb5108f0
Author: Peter A. G. Crosthwaite <peter.crosthwaite at petalogix.com>
Date:   Mon Aug 13 11:04:07 2012 +0100

    ssd0323: abort() instead of exit(1) on error.
    
    To be more consistent with the newer ways of error signalling. That and SIGABT
    is easier to debug with than exit(1).
    
    Signed-off-by: Peter A. G. Crosthwaite <peter.crosthwaite at petalogix.com>
    Reviewed-by: Peter Maydell <peter.maydell at linaro.org>
    Signed-off-by: Peter Maydell <peter.maydell at linaro.org>

diff --git a/hw/ssd0323.c b/hw/ssd0323.c
index b0b2e94..b101c51 100644
--- a/hw/ssd0323.c
+++ b/hw/ssd0323.c
@@ -19,7 +19,9 @@
 #define DPRINTF(fmt, ...) \
 do { printf("ssd0323: " fmt , ## __VA_ARGS__); } while (0)
 #define BADF(fmt, ...) \
-do { fprintf(stderr, "ssd0323: error: " fmt , ## __VA_ARGS__); exit(1);} while (0)
+do { \
+    fprintf(stderr, "ssd0323: error: " fmt , ## __VA_ARGS__); abort(); \
+} while (0)
 #else
 #define DPRINTF(fmt, ...) do {} while(0)
 #define BADF(fmt, ...) \
commit 4e8f1be21287a101996c56fc2e22737692e2868d
Author: Mitsyanko Igor <i.mitsyanko at samsung.com>
Date:   Mon Aug 13 11:04:07 2012 +0100

    hw/sd.c: make sd_wp_addr() return bool
    
    For the sake of code clarity
    
    Signed-off-by: Igor Mitsyanko <i.mitsyanko at samsung.com>
    Signed-off-by: Peter Maydell <peter.maydell at linaro.org>

diff --git a/hw/sd.c b/hw/sd.c
index 209bc19..ec26407 100644
--- a/hw/sd.c
+++ b/hw/sd.c
@@ -542,7 +542,7 @@ static void sd_function_switch(SDState *sd, uint32_t arg)
     sd->data[66] = crc & 0xff;
 }
 
-static inline int sd_wp_addr(SDState *sd, uint64_t addr)
+static inline bool sd_wp_addr(SDState *sd, uint64_t addr)
 {
     return test_bit(sd_addr_to_wpnum(addr), sd->wp_groups);
 }
commit 879bf4a716410c9c7933dea5a5f3d3867734efb6
Author: Mitsyanko Igor <i.mitsyanko at samsung.com>
Date:   Mon Aug 13 11:04:07 2012 +0100

    hw/sd.c: make sd_dataready() return bool
    
    For the sake of code clarity
    
    Signed-off-by: Igor Mitsyanko <i.mitsyanko at samsung.com>
    Reviewed-by: Peter Maydell <peter.maydell at linaro.org>
    Signed-off-by: Peter Maydell <peter.maydell at linaro.org>

diff --git a/hw/sd.c b/hw/sd.c
index ebc4e7c..209bc19 100644
--- a/hw/sd.c
+++ b/hw/sd.c
@@ -1703,7 +1703,7 @@ uint8_t sd_read_data(SDState *sd)
     return ret;
 }
 
-int sd_data_ready(SDState *sd)
+bool sd_data_ready(SDState *sd)
 {
     return sd->state == sd_sendingdata_state;
 }
diff --git a/hw/sd.h b/hw/sd.h
index d25342f..4eb9679 100644
--- a/hw/sd.h
+++ b/hw/sd.h
@@ -73,7 +73,7 @@ int sd_do_command(SDState *sd, SDRequest *req,
 void sd_write_data(SDState *sd, uint8_t value);
 uint8_t sd_read_data(SDState *sd);
 void sd_set_cb(SDState *sd, qemu_irq readonly, qemu_irq insert);
-int sd_data_ready(SDState *sd);
+bool sd_data_ready(SDState *sd);
 void sd_enable(SDState *sd, bool enable);
 
 #endif	/* __hw_sd_h */
commit bebd12717c76b251514098bb9682d0309642e565
Author: Mitsyanko Igor <i.mitsyanko at samsung.com>
Date:   Mon Aug 13 11:04:06 2012 +0100

    hw/sd.c: convert binary variables to bool
    
    Several members of SDState have type int when they actually are binary variables.
    Change type of these variables to bool to improve code readability. Change SD API
    to be in consistency with new variables type.
    
    Signed-off-by: Igor Mitsyanko <i.mitsyanko at samsung.com>
    Reviewed-by: Peter Maydell <peter.maydell at linaro.org>
    Signed-off-by: Peter Maydell <peter.maydell at linaro.org>

diff --git a/hw/sd.c b/hw/sd.c
index d0674d5..ebc4e7c 100644
--- a/hw/sd.c
+++ b/hw/sd.c
@@ -81,7 +81,7 @@ struct SDState {
     uint32_t card_status;
     uint8_t sd_status[64];
     uint32_t vhs;
-    int wp_switch;
+    bool wp_switch;
     unsigned long *wp_groups;
     uint64_t size;
     int blk_len;
@@ -91,12 +91,12 @@ struct SDState {
     int pwd_len;
     int function_group[6];
 
-    int spi;
+    bool spi;
     int current_cmd;
     /* True if we will handle the next command as an ACMD. Note that this does
      * *not* track the APP_CMD status bit!
      */
-    int expecting_acmd;
+    bool expecting_acmd;
     int blk_written;
     uint64_t data_start;
     uint32_t data_offset;
@@ -106,7 +106,7 @@ struct SDState {
     BlockDriverState *bdrv;
     uint8_t *buf;
 
-    int enable;
+    bool enable;
 };
 
 static void sd_set_mode(SDState *sd)
@@ -420,7 +420,7 @@ static void sd_reset(SDState *sd, BlockDriverState *bdrv)
 
     if (sd->wp_groups)
         g_free(sd->wp_groups);
-    sd->wp_switch = bdrv ? bdrv_is_read_only(bdrv) : 0;
+    sd->wp_switch = bdrv ? bdrv_is_read_only(bdrv) : false;
     sd->wp_groups = bitmap_new(sect);
     memset(sd->function_group, 0, sizeof(int) * 6);
     sd->erase_start = 0;
@@ -428,7 +428,7 @@ static void sd_reset(SDState *sd, BlockDriverState *bdrv)
     sd->size = size;
     sd->blk_len = 0x200;
     sd->pwd_len = 0;
-    sd->expecting_acmd = 0;
+    sd->expecting_acmd = false;
 }
 
 static void sd_cardchange(void *opaque, bool load)
@@ -450,14 +450,14 @@ static const BlockDevOps sd_block_ops = {
    whether card should be in SSI or MMC/SD mode.  It is also up to the
    board to ensure that ssi transfers only occur when the chip select
    is asserted.  */
-SDState *sd_init(BlockDriverState *bs, int is_spi)
+SDState *sd_init(BlockDriverState *bs, bool is_spi)
 {
     SDState *sd;
 
     sd = (SDState *) g_malloc0(sizeof(SDState));
     sd->buf = qemu_blockalign(bs, 512);
     sd->spi = is_spi;
-    sd->enable = 1;
+    sd->enable = true;
     sd_reset(sd, bs);
     if (sd->bdrv) {
         bdrv_attach_dev_nofail(sd->bdrv, sd);
@@ -1129,7 +1129,7 @@ static sd_rsp_type_t sd_normal_command(SDState *sd,
         if (sd->rca != rca)
             return sd_r0;
 
-        sd->expecting_acmd = 1;
+        sd->expecting_acmd = true;
         sd->card_status |= APP_CMD;
         return sd_r1;
 
@@ -1311,7 +1311,7 @@ int sd_do_command(SDState *sd, SDRequest *req,
     if (sd->card_status & CARD_IS_LOCKED) {
         if (!cmd_valid_while_locked(sd, req)) {
             sd->card_status |= ILLEGAL_COMMAND;
-            sd->expecting_acmd = 0;
+            sd->expecting_acmd = false;
             fprintf(stderr, "SD: Card is locked\n");
             rtype = sd_illegal;
             goto send_response;
@@ -1322,7 +1322,7 @@ int sd_do_command(SDState *sd, SDRequest *req,
     sd_set_mode(sd);
 
     if (sd->expecting_acmd) {
-        sd->expecting_acmd = 0;
+        sd->expecting_acmd = false;
         rtype = sd_app_command(sd, *req);
     } else {
         rtype = sd_normal_command(sd, *req);
@@ -1708,7 +1708,7 @@ int sd_data_ready(SDState *sd)
     return sd->state == sd_sendingdata_state;
 }
 
-void sd_enable(SDState *sd, int enable)
+void sd_enable(SDState *sd, bool enable)
 {
     sd->enable = enable;
 }
diff --git a/hw/sd.h b/hw/sd.h
index ac4b7c4..d25342f 100644
--- a/hw/sd.h
+++ b/hw/sd.h
@@ -67,13 +67,13 @@ typedef struct {
 
 typedef struct SDState SDState;
 
-SDState *sd_init(BlockDriverState *bs, int is_spi);
+SDState *sd_init(BlockDriverState *bs, bool is_spi);
 int sd_do_command(SDState *sd, SDRequest *req,
                   uint8_t *response);
 void sd_write_data(SDState *sd, uint8_t value);
 uint8_t sd_read_data(SDState *sd);
 void sd_set_cb(SDState *sd, qemu_irq readonly, qemu_irq insert);
 int sd_data_ready(SDState *sd);
-void sd_enable(SDState *sd, int enable);
+void sd_enable(SDState *sd, bool enable);
 
 #endif	/* __hw_sd_h */
commit b7202b8870ebb8e9b0246361c96e129172738f82
Author: Mitsyanko Igor <i.mitsyanko at samsung.com>
Date:   Mon Aug 13 11:04:06 2012 +0100

    hw/sd.c: introduce wrapper for conversion address to wp group
    
    Add wrapper function sd_addr_to_wpnum() to replace long address-->wg_group
    conversion line.
    
    Signed-off-by: Igor Mitsyanko <i.mitsyanko at samsung.com>
    Signed-off-by: Peter Maydell <peter.maydell at linaro.org>

diff --git a/hw/sd.c b/hw/sd.c
index e24d04a..d0674d5 100644
--- a/hw/sd.c
+++ b/hw/sd.c
@@ -388,6 +388,11 @@ static void sd_response_r7_make(SDState *sd, uint8_t *response)
     response[3] = (sd->vhs >>  0) & 0xff;
 }
 
+static inline uint64_t sd_addr_to_wpnum(uint64_t addr)
+{
+    return addr >> (HWBLOCK_SHIFT + SECTOR_SHIFT + WPGROUP_SHIFT);
+}
+
 static void sd_reset(SDState *sd, BlockDriverState *bdrv)
 {
     uint64_t size;
@@ -400,7 +405,7 @@ static void sd_reset(SDState *sd, BlockDriverState *bdrv)
     }
     size = sect << 9;
 
-    sect = (size >> (HWBLOCK_SHIFT + SECTOR_SHIFT + WPGROUP_SHIFT)) + 1;
+    sect = sd_addr_to_wpnum(size) + 1;
 
     sd->state = sd_idle_state;
     sd->rca = 0x0000;
@@ -477,10 +482,8 @@ static void sd_erase(SDState *sd)
         return;
     }
 
-    start = sd->erase_start >>
-            (HWBLOCK_SHIFT + SECTOR_SHIFT + WPGROUP_SHIFT);
-    end = sd->erase_end >>
-            (HWBLOCK_SHIFT + SECTOR_SHIFT + WPGROUP_SHIFT);
+    start = sd_addr_to_wpnum(sd->erase_start);
+    end = sd_addr_to_wpnum(sd->erase_end);
     sd->erase_start = 0;
     sd->erase_end = 0;
     sd->csd[14] |= 0x40;
@@ -497,7 +500,7 @@ static uint32_t sd_wpbits(SDState *sd, uint64_t addr)
     uint32_t i, wpnum;
     uint32_t ret = 0;
 
-    wpnum = addr >> (HWBLOCK_SHIFT + SECTOR_SHIFT + WPGROUP_SHIFT);
+    wpnum = sd_addr_to_wpnum(addr);
 
     for (i = 0; i < 32; i++, wpnum++, addr += WPGROUP_SIZE) {
         if (addr < sd->size && test_bit(wpnum, sd->wp_groups)) {
@@ -541,8 +544,7 @@ static void sd_function_switch(SDState *sd, uint32_t arg)
 
 static inline int sd_wp_addr(SDState *sd, uint64_t addr)
 {
-    return test_bit(addr >> (HWBLOCK_SHIFT + SECTOR_SHIFT + WPGROUP_SHIFT),
-            sd->wp_groups);
+    return test_bit(sd_addr_to_wpnum(addr), sd->wp_groups);
 }
 
 static void sd_lock_command(SDState *sd)
@@ -565,8 +567,7 @@ static void sd_lock_command(SDState *sd)
             sd->card_status |= LOCK_UNLOCK_FAILED;
             return;
         }
-        bitmap_zero(sd->wp_groups,
-            (sd->size >> (HWBLOCK_SHIFT + SECTOR_SHIFT + WPGROUP_SHIFT)) + 1);
+        bitmap_zero(sd->wp_groups, sd_addr_to_wpnum(sd->size) + 1);
         sd->csd[14] &= ~0x10;
         sd->card_status &= ~CARD_IS_LOCKED;
         sd->pwd_len = 0;
@@ -1012,8 +1013,7 @@ static sd_rsp_type_t sd_normal_command(SDState *sd,
             }
 
             sd->state = sd_programming_state;
-            set_bit(addr >> (HWBLOCK_SHIFT + SECTOR_SHIFT + WPGROUP_SHIFT),
-                    sd->wp_groups);
+            set_bit(sd_addr_to_wpnum(addr), sd->wp_groups);
             /* Bzzzzzzztt .... Operation complete.  */
             sd->state = sd_transfer_state;
             return sd_r1b;
@@ -1032,8 +1032,7 @@ static sd_rsp_type_t sd_normal_command(SDState *sd,
             }
 
             sd->state = sd_programming_state;
-            clear_bit(addr >> (HWBLOCK_SHIFT + SECTOR_SHIFT + WPGROUP_SHIFT),
-                    sd->wp_groups);
+            clear_bit(sd_addr_to_wpnum(addr), sd->wp_groups);
             /* Bzzzzzzztt .... Operation complete.  */
             sd->state = sd_transfer_state;
             return sd_r1b;
commit 347cab1a762ff8542016f574c5eb32f0c4588ea2
Author: Mitsyanko Igor <i.mitsyanko at samsung.com>
Date:   Mon Aug 13 11:04:06 2012 +0100

    hw/sd.c: make sd_wp_addr() accept 64 bit address argument
    
    Currently sd_wp_addr() accepts 32 bit address arguments therefore implicitly
    restricting SD card address range. Change address argument type to uint64_t.
    
    Signed-off-by: Igor Mitsyanko <i.mitsyanko at samsung.com>
    Signed-off-by: Peter Maydell <peter.maydell at linaro.org>

diff --git a/hw/sd.c b/hw/sd.c
index 575b509..e24d04a 100644
--- a/hw/sd.c
+++ b/hw/sd.c
@@ -539,7 +539,7 @@ static void sd_function_switch(SDState *sd, uint32_t arg)
     sd->data[66] = crc & 0xff;
 }
 
-static inline int sd_wp_addr(SDState *sd, uint32_t addr)
+static inline int sd_wp_addr(SDState *sd, uint64_t addr)
 {
     return test_bit(addr >> (HWBLOCK_SHIFT + SECTOR_SHIFT + WPGROUP_SHIFT),
             sd->wp_groups);
commit a9c0183059d6a4e4d940cd86ac0f9402b0655d24
Author: Mitsyanko Igor <i.mitsyanko at samsung.com>
Date:   Mon Aug 13 11:04:06 2012 +0100

    hw/sd.c: convert wp_groups in SDState to bitfield
    
    Representing each group write protection flag with only one bit instead of int
    variable significantly reduces memory consumption.
    
    Signed-off-by: Igor Mitsyanko <i.mitsyanko at samsung.com>
    Signed-off-by: Peter Maydell <peter.maydell at linaro.org>

diff --git a/hw/sd.c b/hw/sd.c
index 07eb263..575b509 100644
--- a/hw/sd.c
+++ b/hw/sd.c
@@ -32,6 +32,7 @@
 #include "hw.h"
 #include "block.h"
 #include "sd.h"
+#include "bitmap.h"
 
 //#define DEBUG_SD 1
 
@@ -81,7 +82,7 @@ struct SDState {
     uint8_t sd_status[64];
     uint32_t vhs;
     int wp_switch;
-    int *wp_groups;
+    unsigned long *wp_groups;
     uint64_t size;
     int blk_len;
     uint32_t erase_start;
@@ -415,7 +416,7 @@ static void sd_reset(SDState *sd, BlockDriverState *bdrv)
     if (sd->wp_groups)
         g_free(sd->wp_groups);
     sd->wp_switch = bdrv ? bdrv_is_read_only(bdrv) : 0;
-    sd->wp_groups = (int *) g_malloc0(sizeof(int) * sect);
+    sd->wp_groups = bitmap_new(sect);
     memset(sd->function_group, 0, sizeof(int) * 6);
     sd->erase_start = 0;
     sd->erase_end = 0;
@@ -484,9 +485,11 @@ static void sd_erase(SDState *sd)
     sd->erase_end = 0;
     sd->csd[14] |= 0x40;
 
-    for (i = start; i <= end; i ++)
-        if (sd->wp_groups[i])
+    for (i = start; i <= end; i++) {
+        if (test_bit(i, sd->wp_groups)) {
             sd->card_status |= WP_ERASE_SKIP;
+        }
+    }
 }
 
 static uint32_t sd_wpbits(SDState *sd, uint64_t addr)
@@ -496,9 +499,11 @@ static uint32_t sd_wpbits(SDState *sd, uint64_t addr)
 
     wpnum = addr >> (HWBLOCK_SHIFT + SECTOR_SHIFT + WPGROUP_SHIFT);
 
-    for (i = 0; i < 32; i ++, wpnum ++, addr += WPGROUP_SIZE)
-        if (addr < sd->size && sd->wp_groups[wpnum])
+    for (i = 0; i < 32; i++, wpnum++, addr += WPGROUP_SIZE) {
+        if (addr < sd->size && test_bit(wpnum, sd->wp_groups)) {
             ret |= (1 << i);
+        }
+    }
 
     return ret;
 }
@@ -536,8 +541,8 @@ static void sd_function_switch(SDState *sd, uint32_t arg)
 
 static inline int sd_wp_addr(SDState *sd, uint32_t addr)
 {
-    return sd->wp_groups[addr >>
-            (HWBLOCK_SHIFT + SECTOR_SHIFT + WPGROUP_SHIFT)];
+    return test_bit(addr >> (HWBLOCK_SHIFT + SECTOR_SHIFT + WPGROUP_SHIFT),
+            sd->wp_groups);
 }
 
 static void sd_lock_command(SDState *sd)
@@ -560,8 +565,8 @@ static void sd_lock_command(SDState *sd)
             sd->card_status |= LOCK_UNLOCK_FAILED;
             return;
         }
-        memset(sd->wp_groups, 0, sizeof(int) * (sd->size >>
-                        (HWBLOCK_SHIFT + SECTOR_SHIFT + WPGROUP_SHIFT)));
+        bitmap_zero(sd->wp_groups,
+            (sd->size >> (HWBLOCK_SHIFT + SECTOR_SHIFT + WPGROUP_SHIFT)) + 1);
         sd->csd[14] &= ~0x10;
         sd->card_status &= ~CARD_IS_LOCKED;
         sd->pwd_len = 0;
@@ -1007,8 +1012,8 @@ static sd_rsp_type_t sd_normal_command(SDState *sd,
             }
 
             sd->state = sd_programming_state;
-            sd->wp_groups[addr >> (HWBLOCK_SHIFT +
-                            SECTOR_SHIFT + WPGROUP_SHIFT)] = 1;
+            set_bit(addr >> (HWBLOCK_SHIFT + SECTOR_SHIFT + WPGROUP_SHIFT),
+                    sd->wp_groups);
             /* Bzzzzzzztt .... Operation complete.  */
             sd->state = sd_transfer_state;
             return sd_r1b;
@@ -1027,8 +1032,8 @@ static sd_rsp_type_t sd_normal_command(SDState *sd,
             }
 
             sd->state = sd_programming_state;
-            sd->wp_groups[addr >> (HWBLOCK_SHIFT +
-                            SECTOR_SHIFT + WPGROUP_SHIFT)] = 0;
+            clear_bit(addr >> (HWBLOCK_SHIFT + SECTOR_SHIFT + WPGROUP_SHIFT),
+                    sd->wp_groups);
             /* Bzzzzzzztt .... Operation complete.  */
             sd->state = sd_transfer_state;
             return sd_r1b;
commit 01fd41ab3fb69971c24a69ed49cde96086d81278
Author: Peter A. G. Crosthwaite <peter.crosthwaite at petalogix.com>
Date:   Mon Aug 13 11:04:05 2012 +0100

    armv7m: Guard against no -kernel argument
    
    A -kernel argument must be specified for this machine. Guard against no -kernel
    argument. Previously gave an unhelpful "bad address" error message.
    
    Signed-off-by: Peter A. G. Crosthwaite <peter.crosthwaite at petalogix.com>
    Tested-by: Markus Armbruster <armbru at redhat.com>
    Signed-off-by: Peter Maydell <peter.maydell at linaro.org>

diff --git a/hw/armv7m.c b/hw/armv7m.c
index 8cec78d..9f66667 100644
--- a/hw/armv7m.c
+++ b/hw/armv7m.c
@@ -227,6 +227,11 @@ qemu_irq *armv7m_init(MemoryRegion *address_space_mem,
     big_endian = 0;
 #endif
 
+    if (!kernel_filename) {
+        fprintf(stderr, "Guest image must be specified (using -kernel)\n");
+        exit(1);
+    }
+
     image_size = load_elf(kernel_filename, NULL, NULL, &entry, &lowaddr,
                           NULL, big_endian, ELF_MACHINE, 1);
     if (image_size < 0) {
commit 55e00a19b6dc8f20e5688866451bb4a60e649459
Author: Peter Maydell <peter.maydell at linaro.org>
Date:   Mon Aug 13 11:04:05 2012 +0100

    hw/armv7m_nvic: Fix incorrect default for num-irqs property
    
    Fix an incorrect default value for the num-irqs property (we were
    attempting to override it from the default set by the parent class
    but not succeeding, which meant that the lm3s6965evb model would
    assert on startup attempting to wire up nonexistent irq lines).
    Instead of trying to override the parent's Property array, we
    define an instance_init function which runs after default setup
    but before user property setting and can just fix up the default
    value in the gic_state struct.
    
    Reported-by: Peter Crosthwaite <peter.crosthwaite at petalogix.com>
    Tested-by: Peter Crosthwaite <peter.crosthwaite at petalogix.com>
    Signed-off-by: Peter Maydell <peter.maydell at linaro.org>

diff --git a/hw/armv7m_nvic.c b/hw/armv7m_nvic.c
index 4867c1d..6a0832e 100644
--- a/hw/armv7m_nvic.c
+++ b/hw/armv7m_nvic.c
@@ -467,7 +467,7 @@ static int armv7m_nvic_init(SysBusDevice *dev)
     s->gic.num_cpu = 1;
     /* Tell the common code we're an NVIC */
     s->gic.revision = 0xffffffff;
-    s->gic.num_irq = s->num_irq;
+    s->num_irq = s->gic.num_irq;
     nc->parent_init(dev);
     gic_init_irqs_and_distributor(&s->gic, s->num_irq);
     /* The NVIC and system controller register area looks like this:
@@ -498,14 +498,21 @@ static int armv7m_nvic_init(SysBusDevice *dev)
     return 0;
 }
 
-static Property armv7m_nvic_properties[] = {
+static void armv7m_nvic_instance_init(Object *obj)
+{
+    /* We have a different default value for the num-irq property
+     * than our superclass. This function runs after qdev init
+     * has set the defaults from the Property array and before
+     * any user-specified property setting, so just modify the
+     * value in the gic_state struct.
+     */
+    gic_state *s = ARM_GIC_COMMON(obj);
     /* The ARM v7m may have anything from 0 to 496 external interrupt
      * IRQ lines. We default to 64. Other boards may differ and should
-     * set this property appropriately.
+     * set the num-irq property appropriately.
      */
-    DEFINE_PROP_UINT32("num-irq", nvic_state, num_irq, 64),
-    DEFINE_PROP_END_OF_LIST(),
-};
+    s->num_irq = 64;
+}
 
 static void armv7m_nvic_class_init(ObjectClass *klass, void *data)
 {
@@ -518,12 +525,12 @@ static void armv7m_nvic_class_init(ObjectClass *klass, void *data)
     sdc->init = armv7m_nvic_init;
     dc->vmsd  = &vmstate_nvic;
     dc->reset = armv7m_nvic_reset;
-    dc->props = armv7m_nvic_properties;
 }
 
 static TypeInfo armv7m_nvic_info = {
     .name          = TYPE_NVIC,
     .parent        = TYPE_ARM_GIC_COMMON,
+    .instance_init = armv7m_nvic_instance_init,
     .instance_size = sizeof(nvic_state),
     .class_init    = armv7m_nvic_class_init,
     .class_size    = sizeof(NVICClass),
commit 33e95c6328a3149a52615176617997c4f8f7088b
Author: Anthony Liguori <aliguori at us.ibm.com>
Date:   Fri Aug 10 13:16:10 2012 +1000

    qom: Reimplement Interfaces
    
    The current implementation of Interfaces is poorly designed.  Each interface
    that an object implements ends up being an object that's tracked by the
    implementing object.  There's all sorts of gymnastics to deal with casting
    between these objects.
    
    But an interface shouldn't be associated with an Object.  Interfaces are global
    to a class.  This patch moves all Interface knowledge to ObjectClass eliminating
    the relationship between Object and Interfaces.
    
    Interfaces are now abstract (as they should be) but this is okay.  Interfaces
    essentially act as additional parents for the classes and are treated as such.
    
    With this new implementation, we should fully support derived interfaces
    including reimplementing an inherited interface.
    
    PC: Rebased against qom-next merge Jun-2012.
    
    PC: Removed replication of cast logic for interfaces, i.e. there is only
    one cast function - object_dynamic_cast() (and object_dynamic_cast_assert())
    
    Signed-off-by: Anthony Liguori <aliguori at us.ibm.com>
    Signed-off-by: Peter A. G. Crosthwaite <peter.crosthwaite at petalogix.com>
    Acked-by: Paolo Bonzini <pbonzini at redhat.com>
    Signed-off-by: Edgar E. Iglesias <edgar.iglesias at gmail.com>

diff --git a/include/qemu/object.h b/include/qemu/object.h
index 8b17776..cc75fee 100644
--- a/include/qemu/object.h
+++ b/include/qemu/object.h
@@ -239,6 +239,7 @@ struct ObjectClass
 {
     /*< private >*/
     Type type;
+    GSList *interfaces;
 };
 
 /**
@@ -260,7 +261,6 @@ struct Object
 {
     /*< private >*/
     ObjectClass *class;
-    GSList *interfaces;
     QTAILQ_HEAD(, ObjectProperty) properties;
     uint32_t ref;
     Object *parent;
@@ -387,6 +387,16 @@ struct TypeInfo
     OBJECT_CLASS_CHECK(class, object_get_class(OBJECT(obj)), name)
 
 /**
+ * InterfaceInfo:
+ * @type: The name of the interface.
+ *
+ * The information associated with an interface.
+ */
+struct InterfaceInfo {
+    const char *type;
+};
+
+/**
  * InterfaceClass:
  * @parent_class: the base class
  *
@@ -396,26 +406,30 @@ struct TypeInfo
 struct InterfaceClass
 {
     ObjectClass parent_class;
+    /*< private >*/
+    ObjectClass *concrete_class;
 };
 
+#define TYPE_INTERFACE "interface"
+
 /**
- * InterfaceInfo:
- * @type: The name of the interface.
- * @interface_initfn: This method is called during class initialization and is
- *   used to initialize an interface associated with a class.  This function
- *   should initialize any default virtual functions for a class and/or override
- *   virtual functions in a parent class.
- *
- * The information associated with an interface.
+ * INTERFACE_CLASS:
+ * @klass: class to cast from
+ * Returns: An #InterfaceClass or raise an error if cast is invalid
  */
-struct InterfaceInfo
-{
-    const char *type;
+#define INTERFACE_CLASS(klass) \
+    OBJECT_CLASS_CHECK(InterfaceClass, klass, TYPE_INTERFACE)
 
-    void (*interface_initfn)(ObjectClass *class, void *data);
-};
-
-#define TYPE_INTERFACE "interface"
+/**
+ * INTERFACE_CHECK:
+ * @interface: the type to return
+ * @obj: the object to convert to an interface
+ * @name: the interface type name
+ *
+ * Returns: @obj casted to @interface if cast is valid, otherwise raise error.
+ */
+#define INTERFACE_CHECK(interface, obj, name) \
+    ((interface *)object_dynamic_cast_assert(OBJECT((obj)), (name)))
 
 /**
  * object_new:
diff --git a/qom/object.c b/qom/object.c
index 00bb3b0..a552be2 100644
--- a/qom/object.c
+++ b/qom/object.c
@@ -31,9 +31,7 @@ typedef struct TypeImpl TypeImpl;
 
 struct InterfaceImpl
 {
-    const char *parent;
-    void (*interface_initfn)(ObjectClass *class, void *data);
-    TypeImpl *type;
+    const char *typename;
 };
 
 struct TypeImpl
@@ -64,14 +62,6 @@ struct TypeImpl
     InterfaceImpl interfaces[MAX_INTERFACES];
 };
 
-typedef struct Interface
-{
-    Object parent;
-    Object *obj;
-} Interface;
-
-#define INTERFACE(obj) OBJECT_CHECK(Interface, obj, TYPE_INTERFACE)
-
 static Type type_interface;
 
 static GHashTable *type_table_get(void)
@@ -98,6 +88,7 @@ static TypeImpl *type_table_lookup(const char *name)
 static TypeImpl *type_register_internal(const TypeInfo *info)
 {
     TypeImpl *ti = g_malloc0(sizeof(*ti));
+    int i;
 
     g_assert(info->name != NULL);
 
@@ -122,15 +113,10 @@ static TypeImpl *type_register_internal(const TypeInfo *info)
 
     ti->abstract = info->abstract;
 
-    if (info->interfaces) {
-        int i;
-
-        for (i = 0; info->interfaces[i].type; i++) {
-            ti->interfaces[i].parent = info->interfaces[i].type;
-            ti->interfaces[i].interface_initfn = info->interfaces[i].interface_initfn;
-            ti->num_interfaces++;
-        }
+    for (i = 0; info->interfaces && info->interfaces[i].type; i++) {
+        ti->interfaces[i].typename = g_strdup(info->interfaces[i].type);
     }
+    ti->num_interfaces = i;
 
     type_table_add(ti);
 
@@ -198,26 +184,48 @@ static size_t type_object_get_size(TypeImpl *ti)
     return 0;
 }
 
-static void type_class_interface_init(TypeImpl *ti, InterfaceImpl *iface)
+static bool type_is_ancestor(TypeImpl *type, TypeImpl *target_type)
 {
-    TypeInfo info = {
-        .instance_size = sizeof(Interface),
-        .parent = iface->parent,
-        .class_size = sizeof(InterfaceClass),
-        .class_init = iface->interface_initfn,
-        .abstract = true,
-    };
-    char *name = g_strdup_printf("<%s::%s>", ti->name, iface->parent);
+    assert(target_type);
+
+    /* Check if typename is a direct ancestor of type */
+    while (type) {
+        if (type == target_type) {
+            return true;
+        }
 
-    info.name = name;
-    iface->type = type_register_internal(&info);
-    g_free(name);
+        type = type_get_parent(type);
+    }
+
+    return false;
+}
+
+static void type_initialize(TypeImpl *ti);
+
+static void type_initialize_interface(TypeImpl *ti, const char *parent)
+{
+    InterfaceClass *new_iface;
+    TypeInfo info = { };
+    TypeImpl *iface_impl;
+
+    info.parent = parent;
+    info.name = g_strdup_printf("%s::%s", ti->name, info.parent);
+    info.abstract = true;
+
+    iface_impl = type_register(&info);
+    type_initialize(iface_impl);
+    g_free((char *)info.name);
+
+    new_iface = (InterfaceClass *)iface_impl->class;
+    new_iface->concrete_class = ti->class;
+
+    ti->class->interfaces = g_slist_append(ti->class->interfaces,
+                                           iface_impl->class);
 }
 
 static void type_initialize(TypeImpl *ti)
 {
     TypeImpl *parent;
-    int i;
 
     if (ti->class) {
         return;
@@ -231,9 +239,33 @@ static void type_initialize(TypeImpl *ti)
     parent = type_get_parent(ti);
     if (parent) {
         type_initialize(parent);
+        GSList *e;
+        int i;
 
         g_assert(parent->class_size <= ti->class_size);
         memcpy(ti->class, parent->class, parent->class_size);
+
+        for (e = parent->class->interfaces; e; e = e->next) {
+            ObjectClass *iface = e->data;
+            type_initialize_interface(ti, object_class_get_name(iface));
+        }
+
+        for (i = 0; i < ti->num_interfaces; i++) {
+            TypeImpl *t = type_get_by_name(ti->interfaces[i].typename);
+            for (e = ti->class->interfaces; e; e = e->next) {
+                TypeImpl *target_type = OBJECT_CLASS(e->data)->type;
+
+                if (type_is_ancestor(target_type, t)) {
+                    break;
+                }
+            }
+
+            if (e) {
+                continue;
+            }
+
+            type_initialize_interface(ti, ti->interfaces[i].typename);
+        }
     }
 
     ti->class->type = ti;
@@ -245,38 +277,19 @@ static void type_initialize(TypeImpl *ti)
         parent = type_get_parent(parent);
     }
 
-    for (i = 0; i < ti->num_interfaces; i++) {
-        type_class_interface_init(ti, &ti->interfaces[i]);
-    }
-
     if (ti->class_init) {
         ti->class_init(ti->class, ti->class_data);
     }
-}
 
-static void object_interface_init(Object *obj, InterfaceImpl *iface)
-{
-    TypeImpl *ti = iface->type;
-    Interface *iface_obj;
-
-    iface_obj = INTERFACE(object_new(ti->name));
-    iface_obj->obj = obj;
 
-    obj->interfaces = g_slist_prepend(obj->interfaces, iface_obj);
 }
 
 static void object_init_with_type(Object *obj, TypeImpl *ti)
 {
-    int i;
-
     if (type_has_parent(ti)) {
         object_init_with_type(obj, type_get_parent(ti));
     }
 
-    for (i = 0; i < ti->num_interfaces; i++) {
-        object_interface_init(obj, &ti->interfaces[i]);
-    }
-
     if (ti->instance_init) {
         ti->instance_init(obj);
     }
@@ -357,12 +370,6 @@ static void object_deinit(Object *obj, TypeImpl *type)
         type->instance_finalize(obj);
     }
 
-    while (obj->interfaces) {
-        Interface *iface_obj = obj->interfaces->data;
-        obj->interfaces = g_slist_delete_link(obj->interfaces, obj->interfaces);
-        object_delete(OBJECT(iface_obj));
-    }
-
     if (type_has_parent(type)) {
         object_deinit(obj, type_get_parent(type));
     }
@@ -409,74 +416,15 @@ void object_delete(Object *obj)
     g_free(obj);
 }
 
-static bool type_is_ancestor(TypeImpl *type, TypeImpl *target_type)
-{
-    assert(target_type);
-
-    /* Check if typename is a direct ancestor of type */
-    while (type) {
-        if (type == target_type) {
-            return true;
-        }
-
-        type = type_get_parent(type);
-    }
-
-    return false;
-}
-
-static bool object_is_type(Object *obj, TypeImpl *target_type)
-{
-    return !target_type || type_is_ancestor(obj->class->type, target_type);
-}
-
 Object *object_dynamic_cast(Object *obj, const char *typename)
 {
-    TypeImpl *target_type = type_get_by_name(typename);
-    GSList *i;
-
-    /* Check if typename is a direct ancestor.  Special-case TYPE_OBJECT,
-     * we want to go back from interfaces to the parent.
-    */
-    if (target_type && object_is_type(obj, target_type)) {
+    if (object_class_dynamic_cast(object_get_class(obj), typename)) {
         return obj;
     }
 
-    /* Check if obj is an interface and its containing object is a direct
-     * ancestor of typename.  In principle we could do this test at the very
-     * beginning of object_dynamic_cast, avoiding a second call to
-     * object_is_type.  However, casting between interfaces is relatively
-     * rare, and object_is_type(obj, type_interface) would fail almost always.
-     *
-     * Perhaps we could add a magic value to the object header for increased
-     * (run-time) type safety and to speed up tests like this one.  If we ever
-     * do that we can revisit the order here.
-     */
-    if (object_is_type(obj, type_interface)) {
-        assert(!obj->interfaces);
-        obj = INTERFACE(obj)->obj;
-        if (object_is_type(obj, target_type)) {
-            return obj;
-        }
-    }
-
-    if (!target_type) {
-        return obj;
-    }
-
-    /* Check if obj has an interface of typename */
-    for (i = obj->interfaces; i; i = i->next) {
-        Interface *iface = i->data;
-
-        if (object_is_type(OBJECT(iface), target_type)) {
-            return OBJECT(iface);
-        }
-    }
-
     return NULL;
 }
 
-
 Object *object_dynamic_cast_assert(Object *obj, const char *typename)
 {
     Object *inst;
@@ -497,16 +445,30 @@ ObjectClass *object_class_dynamic_cast(ObjectClass *class,
 {
     TypeImpl *target_type = type_get_by_name(typename);
     TypeImpl *type = class->type;
+    ObjectClass *ret = NULL;
 
-    while (type) {
-        if (type == target_type) {
-            return class;
-        }
+    if (type->num_interfaces && type_is_ancestor(target_type, type_interface)) {
+        int found = 0;
+        GSList *i;
 
-        type = type_get_parent(type);
+        for (i = class->interfaces; i; i = i->next) {
+            ObjectClass *target_class = i->data;
+
+            if (type_is_ancestor(target_class->type, target_type)) {
+                ret = target_class;
+                found++;
+            }
+         }
+
+        /* The match was ambiguous, don't allow a cast */
+        if (found > 1) {
+            ret = NULL;
+        }
+    } else if (type_is_ancestor(type, target_type)) {
+        ret = class;
     }
 
-    return NULL;
+    return ret;
 }
 
 ObjectClass *object_class_dynamic_cast_assert(ObjectClass *class,
@@ -920,12 +882,6 @@ void object_property_add_child(Object *obj, const char *name,
 {
     gchar *type;
 
-    /* Registering an interface object in the composition tree will mightily
-     * confuse object_get_canonical_path (which, on the other hand, knows how
-     * to get the canonical path of an interface object).
-     */
-    assert(!object_is_type(obj, type_interface));
-
     type = g_strdup_printf("child<%s>", object_get_typename(OBJECT(child)));
 
     object_property_add(obj, name, type, object_get_child_property,
@@ -1022,10 +978,6 @@ gchar *object_get_canonical_path(Object *obj)
     Object *root = object_get_root();
     char *newpath = NULL, *path = NULL;
 
-    if (object_is_type(obj, type_interface)) {
-        obj = INTERFACE(obj)->obj;
-    }
-
     while (obj != root) {
         ObjectProperty *prop = NULL;
 
@@ -1246,7 +1198,7 @@ static void register_types(void)
 {
     static TypeInfo interface_info = {
         .name = TYPE_INTERFACE,
-        .instance_size = sizeof(Interface),
+        .class_size = sizeof(InterfaceClass),
         .abstract = true,
     };
 
commit 669b4983018cf13e2adafe1b1b4e1e4053eeb90b
Author: Peter A. G. Crosthwaite <peter.crosthwaite at petalogix.com>
Date:   Fri Aug 10 13:16:11 2012 +1000

    xilinx_axi*: Re-implemented interconnect
    
    Re-implemented the interconnect between the Xilinx AXI ethernet and DMA
    controllers. A QOM interface "stream" is created, for the two stream interfaces.
    
    As per Edgars request, this is designed to be more generic than AXI-stream,
    so in the future we may see more clients of this interface beyond AXI stream.
    
    This is based primarily on Paolos original refactoring of the interconnect.
    
    Signed-off-by: Paolo Bonzini <pbonzini at redhat.com>
    Signed-off-by: Peter A.G. Crosthwaite <peter.crosthwaite at petalogix.com>
    Signed-off-by: Edgar E. Iglesias <edgar.iglesias at gmail.com>

diff --git a/hw/Makefile.objs b/hw/Makefile.objs
index 3ba5dd0..6eee9a0 100644
--- a/hw/Makefile.objs
+++ b/hw/Makefile.objs
@@ -65,6 +65,7 @@ hw-obj-$(CONFIG_XILINX) += xilinx_timer.o
 hw-obj-$(CONFIG_XILINX) += xilinx_uartlite.o
 hw-obj-$(CONFIG_XILINX_AXI) += xilinx_axidma.o
 hw-obj-$(CONFIG_XILINX_AXI) += xilinx_axienet.o
+hw-obj-$(CONFIG_XILINX_AXI) += stream.o
 
 # PKUnity SoC devices
 hw-obj-$(CONFIG_PUV3) += puv3_intc.o
diff --git a/hw/petalogix_ml605_mmu.c b/hw/petalogix_ml605_mmu.c
index 6a7d0c0..dced648 100644
--- a/hw/petalogix_ml605_mmu.c
+++ b/hw/petalogix_ml605_mmu.c
@@ -39,7 +39,8 @@
 
 #include "microblaze_boot.h"
 #include "microblaze_pic_cpu.h"
-#include "xilinx_axidma.h"
+
+#include "stream.h"
 
 #define LMB_BRAM_SIZE  (128 * 1024)
 #define FLASH_SIZE     (32 * 1024 * 1024)
@@ -76,7 +77,7 @@ petalogix_ml605_init(ram_addr_t ram_size,
                           const char *initrd_filename, const char *cpu_model)
 {
     MemoryRegion *address_space_mem = get_system_memory();
-    DeviceState *dev;
+    DeviceState *dev, *dma, *eth0;
     MicroBlazeCPU *cpu;
     CPUMBState *env;
     DriveInfo *dinfo;
@@ -125,15 +126,18 @@ petalogix_ml605_init(ram_addr_t ram_size,
     /* 2 timers at irq 2 @ 100 Mhz.  */
     xilinx_timer_create(TIMER_BASEADDR, irq[2], 0, 100 * 1000000);
 
-    /* axi ethernet and dma initialization. TODO: Dynamically connect them.  */
-    {
-        static struct XilinxDMAConnection dmach;
+    /* axi ethernet and dma initialization. */
+    dma = qdev_create(NULL, "xlnx.axi-dma");
 
-        xilinx_axiethernet_create(&dmach, &nd_table[0], 0x82780000,
-                                  irq[3], 0x1000, 0x1000);
-        xilinx_axiethernetdma_create(&dmach, 0x84600000,
-                                     irq[1], irq[0], 100 * 1000000);
-    }
+    /* FIXME: attach to the sysbus instead */
+    object_property_add_child(container_get(qdev_get_machine(), "/unattached"),
+                                  "xilinx-dma", OBJECT(dma), NULL);
+
+    eth0 = xilinx_axiethernet_create(&nd_table[0], STREAM_SLAVE(dma),
+                                     0x82780000, irq[3], 0x1000, 0x1000);
+
+    xilinx_axiethernetdma_init(dma, STREAM_SLAVE(eth0),
+                               0x84600000, irq[1], irq[0], 100 * 1000000);
 
     microblaze_load_kernel(cpu, ddr_base, ram_size, BINARY_DEVICE_TREE_FILE,
                                                             machine_cpu_reset);
diff --git a/hw/stream.c b/hw/stream.c
new file mode 100644
index 0000000..be57e8b
--- /dev/null
+++ b/hw/stream.c
@@ -0,0 +1,23 @@
+#include "stream.h"
+
+void
+stream_push(StreamSlave *sink, uint8_t *buf, size_t len, uint32_t *app)
+{
+    StreamSlaveClass *k =  STREAM_SLAVE_GET_CLASS(sink);
+
+    k->push(sink, buf, len, app);
+}
+
+static TypeInfo stream_slave_info = {
+    .name          = TYPE_STREAM_SLAVE,
+    .parent        = TYPE_INTERFACE,
+    .class_size = sizeof(StreamSlaveClass),
+};
+
+
+static void stream_slave_register_types(void)
+{
+    type_register_static(&stream_slave_info);
+}
+
+type_init(stream_slave_register_types)
diff --git a/hw/stream.h b/hw/stream.h
new file mode 100644
index 0000000..21123a9
--- /dev/null
+++ b/hw/stream.h
@@ -0,0 +1,31 @@
+#ifndef STREAM_H
+#define STREAM_H 1
+
+#include "qemu-common.h"
+#include "qemu/object.h"
+
+/* stream slave. Used until qdev provides a generic way.  */
+#define TYPE_STREAM_SLAVE "stream-slave"
+
+#define STREAM_SLAVE_CLASS(klass) \
+     OBJECT_CLASS_CHECK(StreamSlaveClass, (klass), TYPE_STREAM_SLAVE)
+#define STREAM_SLAVE_GET_CLASS(obj) \
+    OBJECT_GET_CLASS(StreamSlaveClass, (obj), TYPE_STREAM_SLAVE)
+#define STREAM_SLAVE(obj) \
+     INTERFACE_CHECK(StreamSlave, (obj), TYPE_STREAM_SLAVE)
+
+typedef struct StreamSlave {
+    Object Parent;
+} StreamSlave;
+
+typedef struct StreamSlaveClass {
+    InterfaceClass parent;
+
+    void (*push)(StreamSlave *obj, unsigned char *buf, size_t len,
+                                                    uint32_t *app);
+} StreamSlaveClass;
+
+void
+stream_push(StreamSlave *sink, uint8_t *buf, size_t len, uint32_t *app);
+
+#endif /* STREAM_H */
diff --git a/hw/xilinx.h b/hw/xilinx.h
index 7df21eb..556c5aa 100644
--- a/hw/xilinx.h
+++ b/hw/xilinx.h
@@ -1,3 +1,4 @@
+#include "stream.h"
 #include "qemu-common.h"
 #include "net.h"
 
@@ -49,8 +50,8 @@ xilinx_ethlite_create(NICInfo *nd, target_phys_addr_t base, qemu_irq irq,
 }
 
 static inline DeviceState *
-xilinx_axiethernet_create(void *dmach,
-                          NICInfo *nd, target_phys_addr_t base, qemu_irq irq,
+xilinx_axiethernet_create(NICInfo *nd, StreamSlave *peer,
+                          target_phys_addr_t base, qemu_irq irq,
                           int txmem, int rxmem)
 {
     DeviceState *dev;
@@ -60,7 +61,7 @@ xilinx_axiethernet_create(void *dmach,
     qdev_set_nic_properties(dev, nd);
     qdev_prop_set_uint32(dev, "rxmem", rxmem);
     qdev_prop_set_uint32(dev, "txmem", txmem);
-    qdev_prop_set_ptr(dev, "dmach", dmach);
+    object_property_set_link(OBJECT(dev), OBJECT(peer), "tx_dev", NULL);
     qdev_init_nofail(dev);
     sysbus_mmio_map(sysbus_from_qdev(dev), 0, base);
     sysbus_connect_irq(sysbus_from_qdev(dev), 0, irq);
@@ -68,21 +69,16 @@ xilinx_axiethernet_create(void *dmach,
     return dev;
 }
 
-static inline DeviceState *
-xilinx_axiethernetdma_create(void *dmach,
-                             target_phys_addr_t base, qemu_irq irq,
-                             qemu_irq irq2, int freqhz)
+static inline void
+xilinx_axiethernetdma_init(DeviceState *dev, StreamSlave *peer,
+                           target_phys_addr_t base, qemu_irq irq,
+                           qemu_irq irq2, int freqhz)
 {
-    DeviceState *dev = NULL;
-
-    dev = qdev_create(NULL, "xlnx.axi-dma");
     qdev_prop_set_uint32(dev, "freqhz", freqhz);
-    qdev_prop_set_ptr(dev, "dmach", dmach);
+    object_property_set_link(OBJECT(dev), OBJECT(peer), "tx_dev", NULL);
     qdev_init_nofail(dev);
 
     sysbus_mmio_map(sysbus_from_qdev(dev), 0, base);
     sysbus_connect_irq(sysbus_from_qdev(dev), 0, irq);
     sysbus_connect_irq(sysbus_from_qdev(dev), 1, irq2);
-
-    return dev;
 }
diff --git a/hw/xilinx_axidma.c b/hw/xilinx_axidma.c
index f4bec37..0e28c51 100644
--- a/hw/xilinx_axidma.c
+++ b/hw/xilinx_axidma.c
@@ -29,7 +29,7 @@
 #include "qemu-log.h"
 #include "qdev-addr.h"
 
-#include "xilinx_axidma.h"
+#include "stream.h"
 
 #define D(x)
 
@@ -77,7 +77,7 @@ enum {
     SDESC_STATUS_COMPLETE = (1 << 31)
 };
 
-struct AXIStream {
+struct Stream {
     QEMUBH *bh;
     ptimer_state *ptimer;
     qemu_irq irq;
@@ -94,9 +94,9 @@ struct XilinxAXIDMA {
     SysBusDevice busdev;
     MemoryRegion iomem;
     uint32_t freqhz;
-    void *dmach;
+    StreamSlave *tx_dev;
 
-    struct AXIStream streams[2];
+    struct Stream streams[2];
 };
 
 /*
@@ -113,27 +113,27 @@ static inline int stream_desc_eof(struct SDesc *d)
     return d->control & SDESC_CTRL_EOF;
 }
 
-static inline int stream_resetting(struct AXIStream *s)
+static inline int stream_resetting(struct Stream *s)
 {
     return !!(s->regs[R_DMACR] & DMACR_RESET);
 }
 
-static inline int stream_running(struct AXIStream *s)
+static inline int stream_running(struct Stream *s)
 {
     return s->regs[R_DMACR] & DMACR_RUNSTOP;
 }
 
-static inline int stream_halted(struct AXIStream *s)
+static inline int stream_halted(struct Stream *s)
 {
     return s->regs[R_DMASR] & DMASR_HALTED;
 }
 
-static inline int stream_idle(struct AXIStream *s)
+static inline int stream_idle(struct Stream *s)
 {
     return !!(s->regs[R_DMASR] & DMASR_IDLE);
 }
 
-static void stream_reset(struct AXIStream *s)
+static void stream_reset(struct Stream *s)
 {
     s->regs[R_DMASR] = DMASR_HALTED;  /* starts up halted.  */
     s->regs[R_DMACR] = 1 << 16; /* Starts with one in compl threshold.  */
@@ -159,7 +159,7 @@ static void stream_desc_show(struct SDesc *d)
 }
 #endif
 
-static void stream_desc_load(struct AXIStream *s, target_phys_addr_t addr)
+static void stream_desc_load(struct Stream *s, target_phys_addr_t addr)
 {
     struct SDesc *d = &s->desc;
     int i;
@@ -176,7 +176,7 @@ static void stream_desc_load(struct AXIStream *s, target_phys_addr_t addr)
     }
 }
 
-static void stream_desc_store(struct AXIStream *s, target_phys_addr_t addr)
+static void stream_desc_store(struct Stream *s, target_phys_addr_t addr)
 {
     struct SDesc *d = &s->desc;
     int i;
@@ -192,7 +192,7 @@ static void stream_desc_store(struct AXIStream *s, target_phys_addr_t addr)
     cpu_physical_memory_write(addr, (void *) d, sizeof *d);
 }
 
-static void stream_update_irq(struct AXIStream *s)
+static void stream_update_irq(struct Stream *s)
 {
     unsigned int pending, mask, irq;
 
@@ -204,7 +204,7 @@ static void stream_update_irq(struct AXIStream *s)
     qemu_set_irq(s->irq, !!irq);
 }
 
-static void stream_reload_complete_cnt(struct AXIStream *s)
+static void stream_reload_complete_cnt(struct Stream *s)
 {
     unsigned int comp_th;
     comp_th = (s->regs[R_DMACR] >> 16) & 0xff;
@@ -213,14 +213,14 @@ static void stream_reload_complete_cnt(struct AXIStream *s)
 
 static void timer_hit(void *opaque)
 {
-    struct AXIStream *s = opaque;
+    struct Stream *s = opaque;
 
     stream_reload_complete_cnt(s);
     s->regs[R_DMASR] |= DMASR_DLY_IRQ;
     stream_update_irq(s);
 }
 
-static void stream_complete(struct AXIStream *s)
+static void stream_complete(struct Stream *s)
 {
     unsigned int comp_delay;
 
@@ -240,8 +240,8 @@ static void stream_complete(struct AXIStream *s)
     }
 }
 
-static void stream_process_mem2s(struct AXIStream *s,
-                                 struct XilinxDMAConnection *dmach)
+static void stream_process_mem2s(struct Stream *s,
+                                 StreamSlave *tx_dev)
 {
     uint32_t prev_d;
     unsigned char txbuf[16 * 1024];
@@ -276,7 +276,7 @@ static void stream_process_mem2s(struct AXIStream *s,
         s->pos += txlen;
 
         if (stream_desc_eof(&s->desc)) {
-            xlx_dma_push_to_client(dmach, txbuf, s->pos, app);
+            stream_push(tx_dev, txbuf, s->pos, app);
             s->pos = 0;
             stream_complete(s);
         }
@@ -295,7 +295,7 @@ static void stream_process_mem2s(struct AXIStream *s,
     }
 }
 
-static void stream_process_s2mem(struct AXIStream *s,
+static void stream_process_s2mem(struct Stream *s,
                                  unsigned char *buf, size_t len, uint32_t *app)
 {
     uint32_t prev_d;
@@ -351,11 +351,11 @@ static void stream_process_s2mem(struct AXIStream *s,
     }
 }
 
-static
-void axidma_push(void *opaque, unsigned char *buf, size_t len, uint32_t *app)
+static void
+axidma_push(StreamSlave *obj, unsigned char *buf, size_t len, uint32_t *app)
 {
-    struct XilinxAXIDMA *d = opaque;
-    struct AXIStream *s = &d->streams[1];
+    struct XilinxAXIDMA *d = FROM_SYSBUS(typeof(*d), SYS_BUS_DEVICE(obj));
+    struct Stream *s = &d->streams[1];
 
     if (!app) {
         hw_error("No stream app data!\n");
@@ -368,7 +368,7 @@ static uint64_t axidma_read(void *opaque, target_phys_addr_t addr,
                             unsigned size)
 {
     struct XilinxAXIDMA *d = opaque;
-    struct AXIStream *s;
+    struct Stream *s;
     uint32_t r = 0;
     int sid;
 
@@ -403,7 +403,7 @@ static void axidma_write(void *opaque, target_phys_addr_t addr,
                          uint64_t value, unsigned size)
 {
     struct XilinxAXIDMA *d = opaque;
-    struct AXIStream *s;
+    struct Stream *s;
     int sid;
 
     sid = streamid_from_addr(addr);
@@ -440,7 +440,7 @@ static void axidma_write(void *opaque, target_phys_addr_t addr,
             s->regs[addr] = value;
             s->regs[R_DMASR] &= ~DMASR_IDLE; /* Not idle.  */
             if (!sid) {
-                stream_process_mem2s(s, d->dmach);
+                stream_process_mem2s(s, d->tx_dev);
             }
             break;
         default:
@@ -466,12 +466,6 @@ static int xilinx_axidma_init(SysBusDevice *dev)
     sysbus_init_irq(dev, &s->streams[0].irq);
     sysbus_init_irq(dev, &s->streams[1].irq);
 
-    if (!s->dmach) {
-        hw_error("Unconnected DMA channel.\n");
-    }
-
-    xlx_dma_connect_dma(s->dmach, s, axidma_push);
-
     memory_region_init_io(&s->iomem, &axidma_ops, s,
                           "xlnx.axi-dma", R_MAX * 4 * 2);
     sysbus_init_mmio(dev, &s->iomem);
@@ -486,9 +480,16 @@ static int xilinx_axidma_init(SysBusDevice *dev)
     return 0;
 }
 
+static void xilinx_axidma_initfn(Object *obj)
+{
+    struct XilinxAXIDMA *s = FROM_SYSBUS(typeof(*s), SYS_BUS_DEVICE(obj));
+
+    object_property_add_link(obj, "axistream-connected", TYPE_STREAM_SLAVE,
+                             (Object **) &s->tx_dev, NULL);
+}
+
 static Property axidma_properties[] = {
     DEFINE_PROP_UINT32("freqhz", struct XilinxAXIDMA, freqhz, 50000000),
-    DEFINE_PROP_PTR("dmach", struct XilinxAXIDMA, dmach),
     DEFINE_PROP_END_OF_LIST(),
 };
 
@@ -496,9 +497,11 @@ static void axidma_class_init(ObjectClass *klass, void *data)
 {
     DeviceClass *dc = DEVICE_CLASS(klass);
     SysBusDeviceClass *k = SYS_BUS_DEVICE_CLASS(klass);
+    StreamSlaveClass *ssc = STREAM_SLAVE_CLASS(klass);
 
     k->init = xilinx_axidma_init;
     dc->props = axidma_properties;
+    ssc->push = axidma_push;
 }
 
 static TypeInfo axidma_info = {
@@ -506,6 +509,11 @@ static TypeInfo axidma_info = {
     .parent        = TYPE_SYS_BUS_DEVICE,
     .instance_size = sizeof(struct XilinxAXIDMA),
     .class_init    = axidma_class_init,
+    .instance_init = xilinx_axidma_initfn,
+    .interfaces = (InterfaceInfo[]) {
+        { TYPE_STREAM_SLAVE },
+        { }
+    }
 };
 
 static void xilinx_axidma_register_types(void)
diff --git a/hw/xilinx_axidma.h b/hw/xilinx_axidma.h
deleted file mode 100644
index 37cb6f0..0000000
--- a/hw/xilinx_axidma.h
+++ /dev/null
@@ -1,39 +0,0 @@
-/* AXI DMA connection. Used until qdev provides a generic way.  */
-typedef void (*DMAPushFn)(void *opaque,
-                            unsigned char *buf, size_t len, uint32_t *app);
-
-struct XilinxDMAConnection {
-    void *dma;
-    void *client;
-
-    DMAPushFn to_dma;
-    DMAPushFn to_client;
-};
-
-static inline void xlx_dma_connect_client(struct XilinxDMAConnection *dmach,
-                                          void *c, DMAPushFn f)
-{
-    dmach->client = c;
-    dmach->to_client = f;
-}
-
-static inline void xlx_dma_connect_dma(struct XilinxDMAConnection *dmach,
-                                       void *d, DMAPushFn f)
-{
-    dmach->dma = d;
-    dmach->to_dma = f;
-}
-
-static inline
-void xlx_dma_push_to_dma(struct XilinxDMAConnection *dmach,
-                         uint8_t *buf, size_t len, uint32_t *app)
-{
-    dmach->to_dma(dmach->dma, buf, len, app);
-}
-static inline
-void xlx_dma_push_to_client(struct XilinxDMAConnection *dmach,
-                            uint8_t *buf, size_t len, uint32_t *app)
-{
-    dmach->to_client(dmach->client, buf, len, app);
-}
-
diff --git a/hw/xilinx_axienet.c b/hw/xilinx_axienet.c
index 9b08c62..eec155d 100644
--- a/hw/xilinx_axienet.c
+++ b/hw/xilinx_axienet.c
@@ -28,7 +28,7 @@
 #include "net.h"
 #include "net/checksum.h"
 
-#include "xilinx_axidma.h"
+#include "stream.h"
 
 #define DPHY(x)
 
@@ -310,7 +310,7 @@ struct XilinxAXIEnet {
     SysBusDevice busdev;
     MemoryRegion iomem;
     qemu_irq irq;
-    void *dmach;
+    StreamSlave *tx_dev;
     NICState *nic;
     NICConf conf;
 
@@ -772,7 +772,7 @@ static ssize_t eth_rx(NetClientState *nc, const uint8_t *buf, size_t size)
     /* Good frame.  */
     app[2] |= 1 << 6;
 
-    xlx_dma_push_to_dma(s->dmach, (void *)s->rxmem, size, app);
+    stream_push(s->tx_dev, (void *)s->rxmem, size, app);
 
     s->regs[R_IS] |= IS_RX_COMPLETE;
     enet_update_irq(s);
@@ -788,9 +788,9 @@ static void eth_cleanup(NetClientState *nc)
 }
 
 static void
-axienet_stream_push(void *opaque, uint8_t *buf, size_t size, uint32_t *hdr)
+axienet_stream_push(StreamSlave *obj, uint8_t *buf, size_t size, uint32_t *hdr)
 {
-    struct XilinxAXIEnet *s = opaque;
+    struct XilinxAXIEnet *s = FROM_SYSBUS(typeof(*s), SYS_BUS_DEVICE(obj));
 
     /* TX enable ?  */
     if (!(s->tc & TC_TX)) {
@@ -844,12 +844,6 @@ static int xilinx_enet_init(SysBusDevice *dev)
 
     sysbus_init_irq(dev, &s->irq);
 
-    if (!s->dmach) {
-        hw_error("Unconnected Xilinx Ethernet MAC.\n");
-    }
-
-    xlx_dma_connect_client(s->dmach, s, axienet_stream_push);
-
     memory_region_init_io(&s->iomem, &enet_ops, s, "enet", 0x40000);
     sysbus_init_mmio(dev, &s->iomem);
 
@@ -869,11 +863,18 @@ static int xilinx_enet_init(SysBusDevice *dev)
     return 0;
 }
 
+static void xilinx_enet_initfn(Object *obj)
+{
+    struct XilinxAXIEnet *s = FROM_SYSBUS(typeof(*s), SYS_BUS_DEVICE(obj));
+
+    object_property_add_link(obj, "axistream-connected", TYPE_STREAM_SLAVE,
+                             (Object **) &s->tx_dev, NULL);
+}
+
 static Property xilinx_enet_properties[] = {
     DEFINE_PROP_UINT32("phyaddr", struct XilinxAXIEnet, c_phyaddr, 7),
     DEFINE_PROP_UINT32("rxmem", struct XilinxAXIEnet, c_rxmem, 0x1000),
     DEFINE_PROP_UINT32("txmem", struct XilinxAXIEnet, c_txmem, 0x1000),
-    DEFINE_PROP_PTR("dmach", struct XilinxAXIEnet, dmach),
     DEFINE_NIC_PROPERTIES(struct XilinxAXIEnet, conf),
     DEFINE_PROP_END_OF_LIST(),
 };
@@ -882,9 +883,11 @@ static void xilinx_enet_class_init(ObjectClass *klass, void *data)
 {
     DeviceClass *dc = DEVICE_CLASS(klass);
     SysBusDeviceClass *k = SYS_BUS_DEVICE_CLASS(klass);
+    StreamSlaveClass *ssc = STREAM_SLAVE_CLASS(klass);
 
     k->init = xilinx_enet_init;
     dc->props = xilinx_enet_properties;
+    ssc->push = axienet_stream_push;
 }
 
 static TypeInfo xilinx_enet_info = {
@@ -892,6 +895,11 @@ static TypeInfo xilinx_enet_info = {
     .parent        = TYPE_SYS_BUS_DEVICE,
     .instance_size = sizeof(struct XilinxAXIEnet),
     .class_init    = xilinx_enet_class_init,
+    .instance_init = xilinx_enet_initfn,
+    .interfaces = (InterfaceInfo[]) {
+            { TYPE_STREAM_SLAVE },
+            { }
+    }
 };
 
 static void xilinx_enet_register_types(void)
commit 346fe0c4c0b88f11a3d0c01c34d9a170d73429cc
Merge: 53810ba... b90372a...
Author: Anthony Liguori <aliguori at us.ibm.com>
Date:   Sat Aug 11 19:49:03 2012 -0500

    Merge remote-tracking branch 'stefanha/trivial-patches' into staging
    
    * stefanha/trivial-patches:
      target-arm: Fix typos in comments
      arm: translate: comment typo - s/middel/middle/
      vl.c: Exit QEMU early if no machine is found

commit 53810bab3acd73b9844807e53f02d867c1ad1d2a
Merge: 3129426... 166f3c7...
Author: Anthony Liguori <aliguori at us.ibm.com>
Date:   Sat Aug 11 19:48:50 2012 -0500

    Merge remote-tracking branch 'kwolf/for-anthony' into staging
    
    * kwolf/for-anthony:
      qemu-iotests: skip 039 with ./check -nocache
      block: add BLOCK_O_CHECK for qemu-img check
      qcow2: mark image clean after repair succeeds
      qed: mark image clean after repair succeeds
      blockdev: flip default cache mode from writethrough to writeback
      virtio-blk: disable write cache if not negotiated
      virtio-blk: support VIRTIO_BLK_F_CONFIG_WCE
      qemu-iotests: Save some sed processes
      ahci: Fix sglist memleak in ahci_dma_rw_buf()
      ahci: Fix ahci cdrom read corruptions for reads > 128k
      virtio-blk: fix use-after-free while handling scsi commands

commit 312942619af7bd81bda57769224a8280684dd1cf
Merge: c075a72... 5222aaf...
Author: Anthony Liguori <aliguori at us.ibm.com>
Date:   Sat Aug 11 17:11:23 2012 -0500

    Merge remote-tracking branch 'bonzini/scsi-next' into staging
    
    * bonzini/scsi-next:
      scsi-disk: add support for the UNMAP command
      scsi-disk: improve out-of-range LBA detection for WRITE SAME
      scsi-disk: more assertions and resets for aiocb
      virtio-scsi: do not compare 32-bit QEMU tags against 64-bit virtio-scsi tags
      iscsi: Pick default initiator-name based on the name of the VM
      iscsi: reorganize code for parse_initiator_name
      iscsi: do not leak initiator_name

commit c075a7239937e6ae45bcd3793c37b0168bfae93d
Author: Blue Swirl <blauwirbel at gmail.com>
Date:   Thu Aug 9 20:21:25 2012 +0000

    configure: fix double check tests with Clang
    
    Configuring with Clang compiler with -Werror would not work after
    improved checks:
    /tmp/qemu-conf--25992-.c:4:32: error: self-comparison always evaluates
    to true [-Werror,-Wtautological-compare]
    int main(void) { return preadv == preadv; }
    /tmp/qemu-conf--25992-.c:13:26: error: self-comparison always
    evaluates to true [-Werror,-Wtautological-compare]
        return epoll_create1 == epoll_create1;
    /tmp/qemu-conf--25992-.c:3:13: error: explicitly assigning a variable
    of type 'char **' to itself [-Werror,-Wself-assign]
        environ = environ;
    
    Avoid the errors by adjusting the tests.
    
    Reviewed-by: Peter Maydell <peter.maydell at linaro.org>
    Signed-off-by: Blue Swirl <blauwirbel at gmail.com>

diff --git a/configure b/configure
index 12fdc22..f0dbc03 100755
--- a/configure
+++ b/configure
@@ -2256,7 +2256,7 @@ cat > $TMPC <<EOF
 #include <sys/types.h>
 #include <sys/uio.h>
 #include <unistd.h>
-int main(void) { return preadv == preadv; }
+int main(void) { return preadv(0, 0, 0, 0); }
 EOF
 preadv=no
 if compile_prog "" "" ; then
@@ -2552,7 +2552,7 @@ int main(void)
      * warning but not an error, and will proceed to fail the
      * qemu compile where we compile with -Werror.)
      */
-    return epoll_create1 == epoll_create1;
+    return (int)(uintptr_t)&epoll_create1;
 }
 EOF
 if compile_prog "" "" ; then
@@ -2945,7 +2945,7 @@ has_environ=no
 cat > $TMPC << EOF
 #include <unistd.h>
 int main(void) {
-    environ = environ;
+    environ = 0;
     return 0;
 }
 EOF
commit 8dc38a78d0f74e1561c1fe4d276150a1a8a12c4c
Author: Peter Maydell <peter.maydell at linaro.org>
Date:   Wed Jul 18 15:10:28 2012 +0100

    configure: Check for -Werror causing failures when compiling tests
    
    Add support for checking whether test case code can compile without
    warnings, by recompiling each successful test with -Werror. If the
    -Werror version doesn't pass, we bail out. This gives us the same
    level of visibility of warnings in test code as --enable-werror
    provides for the main compile.
    
    Signed-off-by: Peter Maydell <peter.maydell at linaro.org>
    Signed-off-by: Blue Swirl <blauwirbel at gmail.com>

diff --git a/configure b/configure
index efaff00..12fdc22 100755
--- a/configure
+++ b/configure
@@ -27,16 +27,40 @@ printf " '%s'" "$0" "$@" >> config.log
 echo >> config.log
 echo "#" >> config.log
 
+do_cc() {
+    # Run the compiler, capturing its output to the log.
+    echo $cc "$@" >> config.log
+    $cc "$@" >> config.log 2>&1 || return $?
+    # Test passed. If this is an --enable-werror build, rerun
+    # the test with -Werror and bail out if it fails. This
+    # makes warning-generating-errors in configure test code
+    # obvious to developers.
+    if test "$werror" != "yes"; then
+        return 0
+    fi
+    # Don't bother rerunning the compile if we were already using -Werror
+    case "$*" in
+        *-Werror*)
+           return 0
+        ;;
+    esac
+    echo $cc -Werror "$@" >> config.log
+    $cc -Werror "$@" >> config.log 2>&1 && return $?
+    echo "ERROR: configure test passed without -Werror but failed with -Werror."
+    echo "This is probably a bug in the configure script. The failing command"
+    echo "will be at the bottom of config.log."
+    echo "You can run configure with --disable-werror to bypass this check."
+    exit 1
+}
+
 compile_object() {
-  echo $cc $QEMU_CFLAGS -c -o $TMPO $TMPC >> config.log
-  $cc $QEMU_CFLAGS -c -o $TMPO $TMPC >> config.log 2>&1
+  do_cc $QEMU_CFLAGS -c -o $TMPO $TMPC
 }
 
 compile_prog() {
   local_cflags="$1"
   local_ldflags="$2"
-  echo $cc $QEMU_CFLAGS $local_cflags -o $TMPE $TMPC $LDFLAGS $local_ldflags >> config.log
-  $cc $QEMU_CFLAGS $local_cflags -o $TMPE $TMPC $LDFLAGS $local_ldflags >> config.log 2>&1
+  do_cc $QEMU_CFLAGS $local_cflags -o $TMPE $TMPC $LDFLAGS $local_ldflags
 }
 
 # symbolically link $1 to $2.  Portable version of "ln -sf".
commit 5fda043f9c8b8ab18da2704de8e77b7c86fa9435
Author: Igor Mitsyanko <i.mitsyanko at samsung.com>
Date:   Fri Aug 10 18:45:11 2012 +0400

    exec.c: fix dirty bitmap reallocation
    
    For each newly created RAM block, dirty bitmap is reallocated with g_realloc, which doesn't
    make any promises on initial content of new extra data in returned buffer. In theory,
    we initialize this new data with cpu_physical_memory_set_dirty_range() call. The
    problem is, cpu_physical_memory_set_dirty_range() has a side effect of incrementing
    ram_list.dirty_pages variable, but only for pages which are not already dirty. And
    page "cleanliness" is determined using the same not yet uninitialized dirty bitmap
    we've just reallocated. This results in inconsistency between real dirty page number
    and value in ram_list.dirty_pages variable, which in turn could (and will) result
    in errors during VM migration.
    Zero initialize new dirty bitmap bytes to fix this problem.
    
    Signed-off-by: Igor Mitsyanko <i.mitsyanko at samsung.com>
    Signed-off-by: Blue Swirl <blauwirbel at gmail.com>

diff --git a/exec.c b/exec.c
index a42a0b5..929db5c 100644
--- a/exec.c
+++ b/exec.c
@@ -2550,6 +2550,8 @@ ram_addr_t qemu_ram_alloc_from_ptr(ram_addr_t size, void *host,
 
     ram_list.phys_dirty = g_realloc(ram_list.phys_dirty,
                                        last_ram_offset() >> TARGET_PAGE_BITS);
+    memset(ram_list.phys_dirty + (new_block->offset >> TARGET_PAGE_BITS),
+           0, size >> TARGET_PAGE_BITS);
     cpu_physical_memory_set_dirty_range(new_block->offset, size, 0xff);
 
     if (kvm_enabled())
commit 0521d375a154a27d90eabab035303c6806a37920
Author: Stefan Hajnoczi <stefanha at linux.vnet.ibm.com>
Date:   Fri Aug 10 14:08:42 2012 +0100

    Makefile: add qapi.py dependencies
    
    Commit 427a1a2cb1d35b83b6302886f46289f6d617134d ("qapi: avoid reserved
    keywords") modifies qapi.py, which is used by qapi-types.py and other
    Python scripts.  Because Makefile has no dependencies for qapi.py the
    qapi code generator will not be rerun and the following build error is
    produced:
    
      net/slirp.c: In function ‘net_init_slirp’:
      net/slirp.c:721:50: error: ‘NetdevUserOptions’ has no member named ‘q_restrict’
    
    Fix this issue by adding the missing qapi.py dependencies.
    
    Signed-off-by: Stefan Hajnoczi <stefanha at linux.vnet.ibm.com>
    Signed-off-by: Blue Swirl <blauwirbel at gmail.com>

diff --git a/Makefile b/Makefile
index 000b46c..d736ea5 100644
--- a/Makefile
+++ b/Makefile
@@ -181,24 +181,26 @@ ifneq ($(wildcard config-host.mak),)
 include $(SRC_PATH)/tests/Makefile
 endif
 
+qapi-py = $(SRC_PATH)/scripts/qapi.py $(SRC_PATH)/scripts/ordereddict.py
+
 qga/qapi-generated/qga-qapi-types.c qga/qapi-generated/qga-qapi-types.h :\
-$(SRC_PATH)/qapi-schema-guest.json $(SRC_PATH)/scripts/qapi-types.py
+$(SRC_PATH)/qapi-schema-guest.json $(SRC_PATH)/scripts/qapi-types.py $(qapi-py)
 	$(call quiet-command,$(PYTHON) $(SRC_PATH)/scripts/qapi-types.py $(gen-out-type) -o qga/qapi-generated -p "qga-" < $<, "  GEN   $@")
 qga/qapi-generated/qga-qapi-visit.c qga/qapi-generated/qga-qapi-visit.h :\
-$(SRC_PATH)/qapi-schema-guest.json $(SRC_PATH)/scripts/qapi-visit.py
+$(SRC_PATH)/qapi-schema-guest.json $(SRC_PATH)/scripts/qapi-visit.py $(qapi-py)
 	$(call quiet-command,$(PYTHON) $(SRC_PATH)/scripts/qapi-visit.py $(gen-out-type) -o qga/qapi-generated -p "qga-" < $<, "  GEN   $@")
 qga/qapi-generated/qga-qmp-commands.h qga/qapi-generated/qga-qmp-marshal.c :\
-$(SRC_PATH)/qapi-schema-guest.json $(SRC_PATH)/scripts/qapi-commands.py
+$(SRC_PATH)/qapi-schema-guest.json $(SRC_PATH)/scripts/qapi-commands.py $(qapi-py)
 	$(call quiet-command,$(PYTHON) $(SRC_PATH)/scripts/qapi-commands.py $(gen-out-type) -o qga/qapi-generated -p "qga-" < $<, "  GEN   $@")
 
 qapi-types.c qapi-types.h :\
-$(SRC_PATH)/qapi-schema.json $(SRC_PATH)/scripts/qapi-types.py
+$(SRC_PATH)/qapi-schema.json $(SRC_PATH)/scripts/qapi-types.py $(qapi-py)
 	$(call quiet-command,$(PYTHON) $(SRC_PATH)/scripts/qapi-types.py $(gen-out-type) -o "." < $<, "  GEN   $@")
 qapi-visit.c qapi-visit.h :\
-$(SRC_PATH)/qapi-schema.json $(SRC_PATH)/scripts/qapi-visit.py
+$(SRC_PATH)/qapi-schema.json $(SRC_PATH)/scripts/qapi-visit.py $(qapi-py)
 	$(call quiet-command,$(PYTHON) $(SRC_PATH)/scripts/qapi-visit.py $(gen-out-type) -o "."  < $<, "  GEN   $@")
 qmp-commands.h qmp-marshal.c :\
-$(SRC_PATH)/qapi-schema.json $(SRC_PATH)/scripts/qapi-commands.py
+$(SRC_PATH)/qapi-schema.json $(SRC_PATH)/scripts/qapi-commands.py $(qapi-py)
 	$(call quiet-command,$(PYTHON) $(SRC_PATH)/scripts/qapi-commands.py $(gen-out-type) -m -o "." < $<, "  GEN   $@")
 
 QGALIB_GEN=$(addprefix qga/qapi-generated/, qga-qapi-types.h qga-qapi-visit.h qga-qmp-commands.h)
commit ff5928d0f21ba66814600c81da2b31946ff2160e
Author: Guan Xuetao <gxt at mprc.pku.edu.cn>
Date:   Fri Aug 10 14:42:39 2012 +0800

    unicore32-softmmu: Add a minimal curses screen support
    
    This patch adds a minimal curses screen support for unicore32-softmmu.
    We assume 80*30 screen size to minimize the implementation.
    Two problems are not solved, but they are innocuous.
    1. curses windows will be blank when switching to monitor screen and back
    2. backspace is not handled yet
    
    v1->v2: add extra handler for '\r'
    
    Signed-off-by: Zhang Mengchi <zhangmengchi at mprc.pku.edu.cn>
    Signed-off-by: Guan Xuetao <gxt at mprc.pku.edu.cn>
    Signed-off-by: Blue Swirl <blauwirbel at gmail.com>

diff --git a/target-unicore32/helper.c b/target-unicore32/helper.c
index d6eb758..a9e226b 100644
--- a/target-unicore32/helper.c
+++ b/target-unicore32/helper.c
@@ -13,6 +13,7 @@
 #include "gdbstub.h"
 #include "helper.h"
 #include "host-utils.h"
+#include "console.h"
 
 #undef DEBUG_UC32
 
@@ -186,10 +187,50 @@ uint32_t helper_cp0_get(CPUUniCore32State *env, uint32_t creg, uint32_t cop)
     return 0;
 }
 
+#ifdef CONFIG_CURSES
+/*
+ * FIXME:
+ *     1. curses windows will be blank when switching back
+ *     2. backspace is not handled yet
+ */
+static void putc_on_screen(unsigned char ch)
+{
+    static WINDOW *localwin;
+    static int init;
+
+    if (!init) {
+        /* Assume 80 * 30 screen to minimize the implementation */
+        localwin = newwin(30, 80, 0, 0);
+        scrollok(localwin, TRUE);
+        init = TRUE;
+    }
+
+    if (isprint(ch)) {
+        wprintw(localwin, "%c", ch);
+    } else {
+        switch (ch) {
+        case '\n':
+            wprintw(localwin, "%c", ch);
+            break;
+        case '\r':
+            /* If '\r' is put before '\n', the curses window will destroy the
+             * last print line. And meanwhile, '\n' implifies '\r' inside. */
+            break;
+        default: /* Not handled, so just print it hex code */
+            wprintw(localwin, "-- 0x%x --", ch);
+        }
+    }
+
+    wrefresh(localwin);
+}
+#else
+#define putc_on_screen(c)               do { } while (0)
+#endif
+
 void helper_cp1_putc(target_ulong x)
 {
-    /* TODO: curses display should be added here for screen output. */
-    DPRINTF("%c", x);
+    putc_on_screen((unsigned char)x);   /* Output to screen */
+    DPRINTF("%c", x);                   /* Output to stdout */
 }
 #endif
 
commit 1e5cdaa1cad65e7e5480cc43fffde8762cf84535
Author: Guan Xuetao <gxt at mprc.pku.edu.cn>
Date:   Fri Aug 10 14:42:38 2012 +0800

    unicore32: Close dump-option of cpu_dump_state_ucf64 function
    
    Since of tedious output, we close dump-option of cpu_dump_state_ucf64 function.
    
    Signed-off-by: Guan Xuetao <gxt at mprc.pku.edu.cn>
    Signed-off-by: Blue Swirl <blauwirbel at gmail.com>

diff --git a/target-unicore32/translate.c b/target-unicore32/translate.c
index c74c49a..188bf8c 100644
--- a/target-unicore32/translate.c
+++ b/target-unicore32/translate.c
@@ -2138,7 +2138,7 @@ static const char *cpu_mode_names[16] = {
     "UM18", "UM19", "UM1A", "EXTN", "UM1C", "UM1D", "UM1E", "SUSR"
 };
 
-#define UCF64_DUMP_STATE
+#undef UCF64_DUMP_STATE
 #ifdef UCF64_DUMP_STATE
 static void cpu_dump_state_ucf64(CPUUniCore32State *env, FILE *f,
         fprintf_function cpu_fprintf, int flags)
commit c5240d823292f174ed78563043436d3013c21c6f
Author: Guan Xuetao <gxt at mprc.pku.edu.cn>
Date:   Fri Aug 10 14:42:37 2012 +0800

    unicore32: Disintegrate cpu_dump_state_ucf64 function
    
    This patch disintegrates cpu_dump_state_ucf64 function from cpu_dump_state.
    
    Signed-off-by: Guan Xuetao <gxt at mprc.pku.edu.cn>
    Signed-off-by: Blue Swirl <blauwirbel at gmail.com>

diff --git a/target-unicore32/translate.c b/target-unicore32/translate.c
index 5ee3a59..c74c49a 100644
--- a/target-unicore32/translate.c
+++ b/target-unicore32/translate.c
@@ -2139,11 +2139,11 @@ static const char *cpu_mode_names[16] = {
 };
 
 #define UCF64_DUMP_STATE
-void cpu_dump_state(CPUUniCore32State *env, FILE *f, fprintf_function cpu_fprintf,
-        int flags)
+#ifdef UCF64_DUMP_STATE
+static void cpu_dump_state_ucf64(CPUUniCore32State *env, FILE *f,
+        fprintf_function cpu_fprintf, int flags)
 {
     int i;
-#ifdef UCF64_DUMP_STATE
     union {
         uint32_t i;
         float s;
@@ -2155,7 +2155,28 @@ void cpu_dump_state(CPUUniCore32State *env, FILE *f, fprintf_function cpu_fprint
         float64 f64;
         double d;
     } d0;
+
+    for (i = 0; i < 16; i++) {
+        d.d = env->ucf64.regs[i];
+        s0.i = d.l.lower;
+        s1.i = d.l.upper;
+        d0.f64 = d.d;
+        cpu_fprintf(f, "s%02d=%08x(%8g) s%02d=%08x(%8g)",
+                    i * 2, (int)s0.i, s0.s,
+                    i * 2 + 1, (int)s1.i, s1.s);
+        cpu_fprintf(f, " d%02d=%" PRIx64 "(%8g)\n",
+                    i, (uint64_t)d0.f64, d0.d);
+    }
+    cpu_fprintf(f, "FPSCR: %08x\n", (int)env->ucf64.xregs[UC32_UCF64_FPSCR]);
+}
+#else
+#define cpu_dump_state_ucf64(env, file, pr, flags)      do { } while (0)
 #endif
+
+void cpu_dump_state(CPUUniCore32State *env, FILE *f,
+        fprintf_function cpu_fprintf, int flags)
+{
+    int i;
     uint32_t psr;
 
     for (i = 0; i < 32; i++) {
@@ -2175,19 +2196,7 @@ void cpu_dump_state(CPUUniCore32State *env, FILE *f, fprintf_function cpu_fprint
                 psr & (1 << 28) ? 'V' : '-',
                 cpu_mode_names[psr & 0xf]);
 
-#ifdef UCF64_DUMP_STATE
-    for (i = 0; i < 16; i++) {
-        d.d = env->ucf64.regs[i];
-        s0.i = d.l.lower;
-        s1.i = d.l.upper;
-        d0.f64 = d.d;
-        cpu_fprintf(f, "s%02d=%08x(%8g) s%02d=%08x(%8g) d%02d=%" PRIx64 "(%8g)\n",
-                    i * 2, (int)s0.i, s0.s,
-                    i * 2 + 1, (int)s1.i, s1.s,
-                    i, (uint64_t)d0.f64, d0.d);
-    }
-    cpu_fprintf(f, "FPSCR: %08x\n", (int)env->ucf64.xregs[UC32_UCF64_FPSCR]);
-#endif
+    cpu_dump_state_ucf64(env, f, cpu_fprintf, flags);
 }
 
 void restore_state_to_opc(CPUUniCore32State *env, TranslationBlock *tb, int pc_pos)
commit e8ede0a8bb5298a6979bcf7ed84ef64a64a4e3fe
Author: Guan Xuetao <gxt at mprc.pku.edu.cn>
Date:   Fri Aug 10 14:42:36 2012 +0800

    unicore32: Split UniCore-F64 instruction helpers from helper.c
    
    This patch just splits ucf64 instruction simulation helpers from
    helper.c.
    Also, two checkpatch warnings are solved.
    
    v1->v2: adjust copyright information for new ucf64_helper.c
    
    Signed-off-by: Guan Xuetao <gxt at mprc.pku.edu.cn>
    Signed-off-by: Blue Swirl <blauwirbel at gmail.com>

diff --git a/target-unicore32/Makefile.objs b/target-unicore32/Makefile.objs
index 6af1089..777f01f 100644
--- a/target-unicore32/Makefile.objs
+++ b/target-unicore32/Makefile.objs
@@ -1,4 +1,6 @@
 obj-y += translate.o op_helper.o helper.o cpu.o
+obj-y += ucf64_helper.o
+
 obj-$(CONFIG_SOFTMMU) += machine.o softmmu.o
 
 $(obj)/op_helper.o: QEMU_CFLAGS += $(HELPER_CFLAGS)
diff --git a/target-unicore32/helper.c b/target-unicore32/helper.c
index f9f1960..d6eb758 100644
--- a/target-unicore32/helper.c
+++ b/target-unicore32/helper.c
@@ -213,333 +213,3 @@ int uc32_cpu_handle_mmu_fault(CPUUniCore32State *env, target_ulong address,
     return 1;
 }
 #endif
-
-/* UniCore-F64 support.  We follow the convention used for F64 instrunctions:
-   Single precition routines have a "s" suffix, double precision a
-   "d" suffix.  */
-
-/* Convert host exception flags to f64 form.  */
-static inline int ucf64_exceptbits_from_host(int host_bits)
-{
-    int target_bits = 0;
-
-    if (host_bits & float_flag_invalid) {
-        target_bits |= UCF64_FPSCR_FLAG_INVALID;
-    }
-    if (host_bits & float_flag_divbyzero) {
-        target_bits |= UCF64_FPSCR_FLAG_DIVZERO;
-    }
-    if (host_bits & float_flag_overflow) {
-        target_bits |= UCF64_FPSCR_FLAG_OVERFLOW;
-    }
-    if (host_bits & float_flag_underflow) {
-        target_bits |= UCF64_FPSCR_FLAG_UNDERFLOW;
-    }
-    if (host_bits & float_flag_inexact) {
-        target_bits |= UCF64_FPSCR_FLAG_INEXACT;
-    }
-    return target_bits;
-}
-
-uint32_t HELPER(ucf64_get_fpscr)(CPUUniCore32State *env)
-{
-    int i;
-    uint32_t fpscr;
-
-    fpscr = (env->ucf64.xregs[UC32_UCF64_FPSCR] & UCF64_FPSCR_MASK);
-    i = get_float_exception_flags(&env->ucf64.fp_status);
-    fpscr |= ucf64_exceptbits_from_host(i);
-    return fpscr;
-}
-
-/* Convert ucf64 exception flags to target form.  */
-static inline int ucf64_exceptbits_to_host(int target_bits)
-{
-    int host_bits = 0;
-
-    if (target_bits & UCF64_FPSCR_FLAG_INVALID) {
-        host_bits |= float_flag_invalid;
-    }
-    if (target_bits & UCF64_FPSCR_FLAG_DIVZERO) {
-        host_bits |= float_flag_divbyzero;
-    }
-    if (target_bits & UCF64_FPSCR_FLAG_OVERFLOW) {
-        host_bits |= float_flag_overflow;
-    }
-    if (target_bits & UCF64_FPSCR_FLAG_UNDERFLOW) {
-        host_bits |= float_flag_underflow;
-    }
-    if (target_bits & UCF64_FPSCR_FLAG_INEXACT) {
-        host_bits |= float_flag_inexact;
-    }
-    return host_bits;
-}
-
-void HELPER(ucf64_set_fpscr)(CPUUniCore32State *env, uint32_t val)
-{
-    int i;
-    uint32_t changed;
-
-    changed = env->ucf64.xregs[UC32_UCF64_FPSCR];
-    env->ucf64.xregs[UC32_UCF64_FPSCR] = (val & UCF64_FPSCR_MASK);
-
-    changed ^= val;
-    if (changed & (UCF64_FPSCR_RND_MASK)) {
-        i = UCF64_FPSCR_RND(val);
-        switch (i) {
-        case 0:
-            i = float_round_nearest_even;
-            break;
-        case 1:
-            i = float_round_to_zero;
-            break;
-        case 2:
-            i = float_round_up;
-            break;
-        case 3:
-            i = float_round_down;
-            break;
-        default: /* 100 and 101 not implement */
-            cpu_abort(env, "Unsupported UniCore-F64 round mode");
-        }
-        set_float_rounding_mode(i, &env->ucf64.fp_status);
-    }
-
-    i = ucf64_exceptbits_to_host(UCF64_FPSCR_TRAPEN(val));
-    set_float_exception_flags(i, &env->ucf64.fp_status);
-}
-
-float32 HELPER(ucf64_adds)(float32 a, float32 b, CPUUniCore32State *env)
-{
-    return float32_add(a, b, &env->ucf64.fp_status);
-}
-
-float64 HELPER(ucf64_addd)(float64 a, float64 b, CPUUniCore32State *env)
-{
-    return float64_add(a, b, &env->ucf64.fp_status);
-}
-
-float32 HELPER(ucf64_subs)(float32 a, float32 b, CPUUniCore32State *env)
-{
-    return float32_sub(a, b, &env->ucf64.fp_status);
-}
-
-float64 HELPER(ucf64_subd)(float64 a, float64 b, CPUUniCore32State *env)
-{
-    return float64_sub(a, b, &env->ucf64.fp_status);
-}
-
-float32 HELPER(ucf64_muls)(float32 a, float32 b, CPUUniCore32State *env)
-{
-    return float32_mul(a, b, &env->ucf64.fp_status);
-}
-
-float64 HELPER(ucf64_muld)(float64 a, float64 b, CPUUniCore32State *env)
-{
-    return float64_mul(a, b, &env->ucf64.fp_status);
-}
-
-float32 HELPER(ucf64_divs)(float32 a, float32 b, CPUUniCore32State *env)
-{
-    return float32_div(a, b, &env->ucf64.fp_status);
-}
-
-float64 HELPER(ucf64_divd)(float64 a, float64 b, CPUUniCore32State *env)
-{
-    return float64_div(a, b, &env->ucf64.fp_status);
-}
-
-float32 HELPER(ucf64_negs)(float32 a)
-{
-    return float32_chs(a);
-}
-
-float64 HELPER(ucf64_negd)(float64 a)
-{
-    return float64_chs(a);
-}
-
-float32 HELPER(ucf64_abss)(float32 a)
-{
-    return float32_abs(a);
-}
-
-float64 HELPER(ucf64_absd)(float64 a)
-{
-    return float64_abs(a);
-}
-
-/* XXX: check quiet/signaling case */
-void HELPER(ucf64_cmps)(float32 a, float32 b, uint32_t c, CPUUniCore32State *env)
-{
-    int flag;
-    flag = float32_compare_quiet(a, b, &env->ucf64.fp_status);
-    env->CF = 0;
-    switch (c & 0x7) {
-    case 0: /* F */
-        break;
-    case 1: /* UN */
-        if (flag == 2) {
-            env->CF = 1;
-        }
-        break;
-    case 2: /* EQ */
-        if (flag == 0) {
-            env->CF = 1;
-        }
-        break;
-    case 3: /* UEQ */
-        if ((flag == 0) || (flag == 2)) {
-            env->CF = 1;
-        }
-        break;
-    case 4: /* OLT */
-        if (flag == -1) {
-            env->CF = 1;
-        }
-        break;
-    case 5: /* ULT */
-        if ((flag == -1) || (flag == 2)) {
-            env->CF = 1;
-        }
-        break;
-    case 6: /* OLE */
-        if ((flag == -1) || (flag == 0)) {
-            env->CF = 1;
-        }
-        break;
-    case 7: /* ULE */
-        if (flag != 1) {
-            env->CF = 1;
-        }
-        break;
-    }
-    env->ucf64.xregs[UC32_UCF64_FPSCR] = (env->CF << 29)
-                    | (env->ucf64.xregs[UC32_UCF64_FPSCR] & 0x0fffffff);
-}
-
-void HELPER(ucf64_cmpd)(float64 a, float64 b, uint32_t c, CPUUniCore32State *env)
-{
-    int flag;
-    flag = float64_compare_quiet(a, b, &env->ucf64.fp_status);
-    env->CF = 0;
-    switch (c & 0x7) {
-    case 0: /* F */
-        break;
-    case 1: /* UN */
-        if (flag == 2) {
-            env->CF = 1;
-        }
-        break;
-    case 2: /* EQ */
-        if (flag == 0) {
-            env->CF = 1;
-        }
-        break;
-    case 3: /* UEQ */
-        if ((flag == 0) || (flag == 2)) {
-            env->CF = 1;
-        }
-        break;
-    case 4: /* OLT */
-        if (flag == -1) {
-            env->CF = 1;
-        }
-        break;
-    case 5: /* ULT */
-        if ((flag == -1) || (flag == 2)) {
-            env->CF = 1;
-        }
-        break;
-    case 6: /* OLE */
-        if ((flag == -1) || (flag == 0)) {
-            env->CF = 1;
-        }
-        break;
-    case 7: /* ULE */
-        if (flag != 1) {
-            env->CF = 1;
-        }
-        break;
-    }
-    env->ucf64.xregs[UC32_UCF64_FPSCR] = (env->CF << 29)
-                    | (env->ucf64.xregs[UC32_UCF64_FPSCR] & 0x0fffffff);
-}
-
-/* Helper routines to perform bitwise copies between float and int.  */
-static inline float32 ucf64_itos(uint32_t i)
-{
-    union {
-        uint32_t i;
-        float32 s;
-    } v;
-
-    v.i = i;
-    return v.s;
-}
-
-static inline uint32_t ucf64_stoi(float32 s)
-{
-    union {
-        uint32_t i;
-        float32 s;
-    } v;
-
-    v.s = s;
-    return v.i;
-}
-
-static inline float64 ucf64_itod(uint64_t i)
-{
-    union {
-        uint64_t i;
-        float64 d;
-    } v;
-
-    v.i = i;
-    return v.d;
-}
-
-static inline uint64_t ucf64_dtoi(float64 d)
-{
-    union {
-        uint64_t i;
-        float64 d;
-    } v;
-
-    v.d = d;
-    return v.i;
-}
-
-/* Integer to float conversion.  */
-float32 HELPER(ucf64_si2sf)(float32 x, CPUUniCore32State *env)
-{
-    return int32_to_float32(ucf64_stoi(x), &env->ucf64.fp_status);
-}
-
-float64 HELPER(ucf64_si2df)(float32 x, CPUUniCore32State *env)
-{
-    return int32_to_float64(ucf64_stoi(x), &env->ucf64.fp_status);
-}
-
-/* Float to integer conversion.  */
-float32 HELPER(ucf64_sf2si)(float32 x, CPUUniCore32State *env)
-{
-    return ucf64_itos(float32_to_int32(x, &env->ucf64.fp_status));
-}
-
-float32 HELPER(ucf64_df2si)(float64 x, CPUUniCore32State *env)
-{
-    return ucf64_itos(float64_to_int32(x, &env->ucf64.fp_status));
-}
-
-/* floating point conversion */
-float64 HELPER(ucf64_sf2df)(float32 x, CPUUniCore32State *env)
-{
-    return float32_to_float64(x, &env->ucf64.fp_status);
-}
-
-float32 HELPER(ucf64_df2sf)(float64 x, CPUUniCore32State *env)
-{
-    return float64_to_float32(x, &env->ucf64.fp_status);
-}
diff --git a/target-unicore32/ucf64_helper.c b/target-unicore32/ucf64_helper.c
new file mode 100644
index 0000000..a516edd
--- /dev/null
+++ b/target-unicore32/ucf64_helper.c
@@ -0,0 +1,345 @@
+/*
+ * UniCore-F64 simulation helpers for QEMU.
+ *
+ * Copyright (C) 2010-2012 Guan Xuetao
+ *
+ * This program is free software; you can redistribute it and/or modify
+ * it under the terms of the GNU General Public License version 2 as
+ * published by the Free Software Foundation, or any later version.
+ * See the COPYING file in the top-level directory.
+ */
+#include "cpu.h"
+#include "helper.h"
+
+/*
+ * The convention used for UniCore-F64 instructions:
+ *  Single precition routines have a "s" suffix
+ *  Double precision routines have a "d" suffix.
+ */
+
+/* Convert host exception flags to f64 form.  */
+static inline int ucf64_exceptbits_from_host(int host_bits)
+{
+    int target_bits = 0;
+
+    if (host_bits & float_flag_invalid) {
+        target_bits |= UCF64_FPSCR_FLAG_INVALID;
+    }
+    if (host_bits & float_flag_divbyzero) {
+        target_bits |= UCF64_FPSCR_FLAG_DIVZERO;
+    }
+    if (host_bits & float_flag_overflow) {
+        target_bits |= UCF64_FPSCR_FLAG_OVERFLOW;
+    }
+    if (host_bits & float_flag_underflow) {
+        target_bits |= UCF64_FPSCR_FLAG_UNDERFLOW;
+    }
+    if (host_bits & float_flag_inexact) {
+        target_bits |= UCF64_FPSCR_FLAG_INEXACT;
+    }
+    return target_bits;
+}
+
+uint32_t HELPER(ucf64_get_fpscr)(CPUUniCore32State *env)
+{
+    int i;
+    uint32_t fpscr;
+
+    fpscr = (env->ucf64.xregs[UC32_UCF64_FPSCR] & UCF64_FPSCR_MASK);
+    i = get_float_exception_flags(&env->ucf64.fp_status);
+    fpscr |= ucf64_exceptbits_from_host(i);
+    return fpscr;
+}
+
+/* Convert ucf64 exception flags to target form.  */
+static inline int ucf64_exceptbits_to_host(int target_bits)
+{
+    int host_bits = 0;
+
+    if (target_bits & UCF64_FPSCR_FLAG_INVALID) {
+        host_bits |= float_flag_invalid;
+    }
+    if (target_bits & UCF64_FPSCR_FLAG_DIVZERO) {
+        host_bits |= float_flag_divbyzero;
+    }
+    if (target_bits & UCF64_FPSCR_FLAG_OVERFLOW) {
+        host_bits |= float_flag_overflow;
+    }
+    if (target_bits & UCF64_FPSCR_FLAG_UNDERFLOW) {
+        host_bits |= float_flag_underflow;
+    }
+    if (target_bits & UCF64_FPSCR_FLAG_INEXACT) {
+        host_bits |= float_flag_inexact;
+    }
+    return host_bits;
+}
+
+void HELPER(ucf64_set_fpscr)(CPUUniCore32State *env, uint32_t val)
+{
+    int i;
+    uint32_t changed;
+
+    changed = env->ucf64.xregs[UC32_UCF64_FPSCR];
+    env->ucf64.xregs[UC32_UCF64_FPSCR] = (val & UCF64_FPSCR_MASK);
+
+    changed ^= val;
+    if (changed & (UCF64_FPSCR_RND_MASK)) {
+        i = UCF64_FPSCR_RND(val);
+        switch (i) {
+        case 0:
+            i = float_round_nearest_even;
+            break;
+        case 1:
+            i = float_round_to_zero;
+            break;
+        case 2:
+            i = float_round_up;
+            break;
+        case 3:
+            i = float_round_down;
+            break;
+        default: /* 100 and 101 not implement */
+            cpu_abort(env, "Unsupported UniCore-F64 round mode");
+        }
+        set_float_rounding_mode(i, &env->ucf64.fp_status);
+    }
+
+    i = ucf64_exceptbits_to_host(UCF64_FPSCR_TRAPEN(val));
+    set_float_exception_flags(i, &env->ucf64.fp_status);
+}
+
+float32 HELPER(ucf64_adds)(float32 a, float32 b, CPUUniCore32State *env)
+{
+    return float32_add(a, b, &env->ucf64.fp_status);
+}
+
+float64 HELPER(ucf64_addd)(float64 a, float64 b, CPUUniCore32State *env)
+{
+    return float64_add(a, b, &env->ucf64.fp_status);
+}
+
+float32 HELPER(ucf64_subs)(float32 a, float32 b, CPUUniCore32State *env)
+{
+    return float32_sub(a, b, &env->ucf64.fp_status);
+}
+
+float64 HELPER(ucf64_subd)(float64 a, float64 b, CPUUniCore32State *env)
+{
+    return float64_sub(a, b, &env->ucf64.fp_status);
+}
+
+float32 HELPER(ucf64_muls)(float32 a, float32 b, CPUUniCore32State *env)
+{
+    return float32_mul(a, b, &env->ucf64.fp_status);
+}
+
+float64 HELPER(ucf64_muld)(float64 a, float64 b, CPUUniCore32State *env)
+{
+    return float64_mul(a, b, &env->ucf64.fp_status);
+}
+
+float32 HELPER(ucf64_divs)(float32 a, float32 b, CPUUniCore32State *env)
+{
+    return float32_div(a, b, &env->ucf64.fp_status);
+}
+
+float64 HELPER(ucf64_divd)(float64 a, float64 b, CPUUniCore32State *env)
+{
+    return float64_div(a, b, &env->ucf64.fp_status);
+}
+
+float32 HELPER(ucf64_negs)(float32 a)
+{
+    return float32_chs(a);
+}
+
+float64 HELPER(ucf64_negd)(float64 a)
+{
+    return float64_chs(a);
+}
+
+float32 HELPER(ucf64_abss)(float32 a)
+{
+    return float32_abs(a);
+}
+
+float64 HELPER(ucf64_absd)(float64 a)
+{
+    return float64_abs(a);
+}
+
+void HELPER(ucf64_cmps)(float32 a, float32 b, uint32_t c,
+        CPUUniCore32State *env)
+{
+    int flag;
+    flag = float32_compare_quiet(a, b, &env->ucf64.fp_status);
+    env->CF = 0;
+    switch (c & 0x7) {
+    case 0: /* F */
+        break;
+    case 1: /* UN */
+        if (flag == 2) {
+            env->CF = 1;
+        }
+        break;
+    case 2: /* EQ */
+        if (flag == 0) {
+            env->CF = 1;
+        }
+        break;
+    case 3: /* UEQ */
+        if ((flag == 0) || (flag == 2)) {
+            env->CF = 1;
+        }
+        break;
+    case 4: /* OLT */
+        if (flag == -1) {
+            env->CF = 1;
+        }
+        break;
+    case 5: /* ULT */
+        if ((flag == -1) || (flag == 2)) {
+            env->CF = 1;
+        }
+        break;
+    case 6: /* OLE */
+        if ((flag == -1) || (flag == 0)) {
+            env->CF = 1;
+        }
+        break;
+    case 7: /* ULE */
+        if (flag != 1) {
+            env->CF = 1;
+        }
+        break;
+    }
+    env->ucf64.xregs[UC32_UCF64_FPSCR] = (env->CF << 29)
+                    | (env->ucf64.xregs[UC32_UCF64_FPSCR] & 0x0fffffff);
+}
+
+void HELPER(ucf64_cmpd)(float64 a, float64 b, uint32_t c,
+        CPUUniCore32State *env)
+{
+    int flag;
+    flag = float64_compare_quiet(a, b, &env->ucf64.fp_status);
+    env->CF = 0;
+    switch (c & 0x7) {
+    case 0: /* F */
+        break;
+    case 1: /* UN */
+        if (flag == 2) {
+            env->CF = 1;
+        }
+        break;
+    case 2: /* EQ */
+        if (flag == 0) {
+            env->CF = 1;
+        }
+        break;
+    case 3: /* UEQ */
+        if ((flag == 0) || (flag == 2)) {
+            env->CF = 1;
+        }
+        break;
+    case 4: /* OLT */
+        if (flag == -1) {
+            env->CF = 1;
+        }
+        break;
+    case 5: /* ULT */
+        if ((flag == -1) || (flag == 2)) {
+            env->CF = 1;
+        }
+        break;
+    case 6: /* OLE */
+        if ((flag == -1) || (flag == 0)) {
+            env->CF = 1;
+        }
+        break;
+    case 7: /* ULE */
+        if (flag != 1) {
+            env->CF = 1;
+        }
+        break;
+    }
+    env->ucf64.xregs[UC32_UCF64_FPSCR] = (env->CF << 29)
+                    | (env->ucf64.xregs[UC32_UCF64_FPSCR] & 0x0fffffff);
+}
+
+/* Helper routines to perform bitwise copies between float and int.  */
+static inline float32 ucf64_itos(uint32_t i)
+{
+    union {
+        uint32_t i;
+        float32 s;
+    } v;
+
+    v.i = i;
+    return v.s;
+}
+
+static inline uint32_t ucf64_stoi(float32 s)
+{
+    union {
+        uint32_t i;
+        float32 s;
+    } v;
+
+    v.s = s;
+    return v.i;
+}
+
+static inline float64 ucf64_itod(uint64_t i)
+{
+    union {
+        uint64_t i;
+        float64 d;
+    } v;
+
+    v.i = i;
+    return v.d;
+}
+
+static inline uint64_t ucf64_dtoi(float64 d)
+{
+    union {
+        uint64_t i;
+        float64 d;
+    } v;
+
+    v.d = d;
+    return v.i;
+}
+
+/* Integer to float conversion.  */
+float32 HELPER(ucf64_si2sf)(float32 x, CPUUniCore32State *env)
+{
+    return int32_to_float32(ucf64_stoi(x), &env->ucf64.fp_status);
+}
+
+float64 HELPER(ucf64_si2df)(float32 x, CPUUniCore32State *env)
+{
+    return int32_to_float64(ucf64_stoi(x), &env->ucf64.fp_status);
+}
+
+/* Float to integer conversion.  */
+float32 HELPER(ucf64_sf2si)(float32 x, CPUUniCore32State *env)
+{
+    return ucf64_itos(float32_to_int32(x, &env->ucf64.fp_status));
+}
+
+float32 HELPER(ucf64_df2si)(float64 x, CPUUniCore32State *env)
+{
+    return ucf64_itos(float64_to_int32(x, &env->ucf64.fp_status));
+}
+
+/* floating point conversion */
+float64 HELPER(ucf64_sf2df)(float32 x, CPUUniCore32State *env)
+{
+    return float32_to_float64(x, &env->ucf64.fp_status);
+}
+
+float32 HELPER(ucf64_df2sf)(float64 x, CPUUniCore32State *env)
+{
+    return float64_to_float32(x, &env->ucf64.fp_status);
+}
commit 220c21474535d5a859bb10eff2e2be0a48a15694
Author: Guan Xuetao <gxt at mprc.pku.edu.cn>
Date:   Fri Aug 10 14:42:35 2012 +0800

    unicore32-softmmu: Add is_default setting for puv3 machine
    
    This patch sets is_default to 1 for puv3 machine, so that
    find_default_machine() returns puv3 machine.
    Thanks Dunrong for pointing it out.
    
    Cc: Dunrong Huang <riegamaths at gmail.com>
    Signed-off-by: Guan Xuetao <gxt at mprc.pku.edu.cn>
    Signed-off-by: Blue Swirl <blauwirbel at gmail.com>

diff --git a/hw/puv3.c b/hw/puv3.c
index 271df97..43f7216 100644
--- a/hw/puv3.c
+++ b/hw/puv3.c
@@ -119,6 +119,7 @@ static QEMUMachine puv3_machine = {
     .name = "puv3",
     .desc = "PKUnity Version-3 based on UniCore32",
     .init = puv3_init,
+    .is_default = 1,
     .use_scsi = 0,
 };
 
commit ab9528ca8f5227a5fe02fd47a9028a6f21ec7faf
Author: Guan Xuetao <gxt at mprc.pku.edu.cn>
Date:   Fri Aug 10 14:42:34 2012 +0800

    unicore32-softmmu: Add maintainer information for UniCore32 machine
    
    Signed-off-by: Guan Xuetao <gxt at mprc.pku.edu.cn>
    Signed-off-by: Blue Swirl <blauwirbel at gmail.com>

diff --git a/MAINTAINERS b/MAINTAINERS
index 2d219d2..708ad54 100644
--- a/MAINTAINERS
+++ b/MAINTAINERS
@@ -405,6 +405,14 @@ M: Alexander Graf <agraf at suse.de>
 S: Maintained
 F: hw/s390-*.c
 
+UniCore32 Machines
+-------------
+PKUnity-3 SoC initramfs-with-busybox
+M: Guan Xuetao <gxt at mprc.pku.edu.cn>
+S: Maintained
+F: hw/puv3*
+F: hw/unicore32/
+
 X86 Machines
 ------------
 PC
commit 79683f6117ca3fc24563743679a9786a8b83fb9d
Author: Guan Xuetao <gxt at mprc.pku.edu.cn>
Date:   Fri Aug 10 14:42:33 2012 +0800

    unicore32-softmmu: Add ps2 support
    
    This patch adds ps2/keyboard support, and enables CONFIG_PCKBD.
    
    Signed-off-by: Guan Xuetao <gxt at mprc.pku.edu.cn>
    Signed-off-by: Blue Swirl <blauwirbel at gmail.com>

diff --git a/default-configs/unicore32-softmmu.mak b/default-configs/unicore32-softmmu.mak
index 4d4fbfc..de38577 100644
--- a/default-configs/unicore32-softmmu.mak
+++ b/default-configs/unicore32-softmmu.mak
@@ -1,3 +1,4 @@
 # Default configuration for unicore32-softmmu
 CONFIG_PUV3=y
 CONFIG_PTIMER=y
+CONFIG_PCKBD=y
diff --git a/hw/puv3.c b/hw/puv3.c
index 9acfc5a..271df97 100644
--- a/hw/puv3.c
+++ b/hw/puv3.c
@@ -38,6 +38,7 @@ static void puv3_soc_init(CPUUniCore32State *env)
 {
     qemu_irq *cpu_intc, irqs[PUV3_IRQS_NR];
     DeviceState *dev;
+    MemoryRegion *i8042 = g_new(MemoryRegion, 1);
     int i;
 
     /* Initialize interrupt controller */
@@ -57,6 +58,10 @@ static void puv3_soc_init(CPUUniCore32State *env)
             irqs[PUV3_IRQS_GPIOLOW4], irqs[PUV3_IRQS_GPIOLOW5],
             irqs[PUV3_IRQS_GPIOLOW6], irqs[PUV3_IRQS_GPIOLOW7],
             irqs[PUV3_IRQS_GPIOHIGH], NULL);
+
+    /* Keyboard (i8042), mouse disabled for nographic */
+    i8042_mm_init(irqs[PUV3_IRQS_PS2_KBD], NULL, i8042, PUV3_REGS_OFFSET, 4);
+    memory_region_add_subregion(get_system_memory(), PUV3_PS2_BASE, i8042);
 }
 
 static void puv3_board_init(CPUUniCore32State *env, ram_addr_t ram_size)
commit 1ea3489963a9eb20f3c2312224e2638b79256f84
Author: Guan Xuetao <gxt at mprc.pku.edu.cn>
Date:   Fri Aug 10 14:42:32 2012 +0800

    unicore32-softmmu: Add puv3 dma support
    
    This patch adds puv3 dma (Direct Memory Access) support,
    include dma device simulation for kernel booting.
    
    v1->v2: Add initialization to ret in puv3_dma_read.
    
    Signed-off-by: Guan Xuetao <gxt at mprc.pku.edu.cn>
    Signed-off-by: Blue Swirl <blauwirbel at gmail.com>

diff --git a/hw/Makefile.objs b/hw/Makefile.objs
index d84b221..3ba5dd0 100644
--- a/hw/Makefile.objs
+++ b/hw/Makefile.objs
@@ -71,6 +71,7 @@ hw-obj-$(CONFIG_PUV3) += puv3_intc.o
 hw-obj-$(CONFIG_PUV3) += puv3_ost.o
 hw-obj-$(CONFIG_PUV3) += puv3_gpio.o
 hw-obj-$(CONFIG_PUV3) += puv3_pm.o
+hw-obj-$(CONFIG_PUV3) += puv3_dma.o
 
 # PCI watchdog devices
 hw-obj-$(CONFIG_PCI) += wdt_i6300esb.o
diff --git a/hw/puv3.c b/hw/puv3.c
index 3a14b27..9acfc5a 100644
--- a/hw/puv3.c
+++ b/hw/puv3.c
@@ -49,6 +49,7 @@ static void puv3_soc_init(CPUUniCore32State *env)
 
     /* Initialize minimal necessary devices for kernel booting */
     sysbus_create_simple("puv3_pm", PUV3_PM_BASE, NULL);
+    sysbus_create_simple("puv3_dma", PUV3_DMA_BASE, NULL);
     sysbus_create_simple("puv3_ost", PUV3_OST_BASE, irqs[PUV3_IRQS_OST0]);
     sysbus_create_varargs("puv3_gpio", PUV3_GPIO_BASE,
             irqs[PUV3_IRQS_GPIOLOW0], irqs[PUV3_IRQS_GPIOLOW1],
diff --git a/hw/puv3_dma.c b/hw/puv3_dma.c
new file mode 100644
index 0000000..85b97bf
--- /dev/null
+++ b/hw/puv3_dma.c
@@ -0,0 +1,109 @@
+/*
+ * DMA device simulation in PKUnity SoC
+ *
+ * Copyright (C) 2010-2012 Guan Xuetao
+ *
+ * This program is free software; you can redistribute it and/or modify
+ * it under the terms of the GNU General Public License version 2 as
+ * published by the Free Software Foundation, or any later version.
+ * See the COPYING file in the top-level directory.
+ */
+#include "hw.h"
+#include "sysbus.h"
+
+#undef DEBUG_PUV3
+#include "puv3.h"
+
+#define PUV3_DMA_CH_NR          (6)
+#define PUV3_DMA_CH_MASK        (0xff)
+#define PUV3_DMA_CH(offset)     ((offset) >> 8)
+
+typedef struct {
+    SysBusDevice busdev;
+    MemoryRegion iomem;
+    uint32_t reg_CFG[PUV3_DMA_CH_NR];
+} PUV3DMAState;
+
+static uint64_t puv3_dma_read(void *opaque, target_phys_addr_t offset,
+        unsigned size)
+{
+    PUV3DMAState *s = opaque;
+    uint32_t ret = 0;
+
+    assert(PUV3_DMA_CH(offset) < PUV3_DMA_CH_NR);
+
+    switch (offset & PUV3_DMA_CH_MASK) {
+    case 0x10:
+        ret = s->reg_CFG[PUV3_DMA_CH(offset)];
+        break;
+    default:
+        DPRINTF("Bad offset 0x%x\n", offset);
+    }
+    DPRINTF("offset 0x%x, value 0x%x\n", offset, ret);
+
+    return ret;
+}
+
+static void puv3_dma_write(void *opaque, target_phys_addr_t offset,
+        uint64_t value, unsigned size)
+{
+    PUV3DMAState *s = opaque;
+
+    assert(PUV3_DMA_CH(offset) < PUV3_DMA_CH_NR);
+
+    switch (offset & PUV3_DMA_CH_MASK) {
+    case 0x10:
+        s->reg_CFG[PUV3_DMA_CH(offset)] = value;
+        break;
+    default:
+        DPRINTF("Bad offset 0x%x\n", offset);
+    }
+    DPRINTF("offset 0x%x, value 0x%x\n", offset, value);
+}
+
+static const MemoryRegionOps puv3_dma_ops = {
+    .read = puv3_dma_read,
+    .write = puv3_dma_write,
+    .impl = {
+        .min_access_size = 4,
+        .max_access_size = 4,
+    },
+    .endianness = DEVICE_NATIVE_ENDIAN,
+};
+
+static int puv3_dma_init(SysBusDevice *dev)
+{
+    PUV3DMAState *s = FROM_SYSBUS(PUV3DMAState, dev);
+    int i;
+
+    for (i = 0; i < PUV3_DMA_CH_NR; i++) {
+        s->reg_CFG[i] = 0x0;
+    }
+
+    memory_region_init_io(&s->iomem, &puv3_dma_ops, s, "puv3_dma",
+            PUV3_REGS_OFFSET);
+    sysbus_init_mmio(dev, &s->iomem);
+
+    return 0;
+}
+
+static void puv3_dma_class_init(ObjectClass *klass, void *data)
+{
+    SysBusDeviceClass *sdc = SYS_BUS_DEVICE_CLASS(klass);
+
+    sdc->init = puv3_dma_init;
+}
+
+static const TypeInfo puv3_dma_info = {
+    .name = "puv3_dma",
+    .parent = TYPE_SYS_BUS_DEVICE,
+    .instance_size = sizeof(PUV3DMAState),
+    .class_init = puv3_dma_class_init,
+};
+
+static void puv3_dma_register_type(void)
+{
+    type_register_static(&puv3_dma_info);
+}
+
+type_init(puv3_dma_register_type)
commit f716c1973ac97d3838212d16b94dff69becf3d67
Author: Guan Xuetao <gxt at mprc.pku.edu.cn>
Date:   Fri Aug 10 14:42:31 2012 +0800

    unicore32-softmmu: Add puv3 pm support
    
    This patch adds puv3 pm (power management) support,
    include pm device simulation for kernel booting.
    Thank Blue Swirl for pointing out the missing "break".
    
    v1->v2: Add initialization to ret in puv3_pm_read.
    
    Signed-off-by: Guan Xuetao <gxt at mprc.pku.edu.cn>
    Signed-off-by: Blue Swirl <blauwirbel at gmail.com>

diff --git a/hw/Makefile.objs b/hw/Makefile.objs
index 0e6ad8c..d84b221 100644
--- a/hw/Makefile.objs
+++ b/hw/Makefile.objs
@@ -70,6 +70,7 @@ hw-obj-$(CONFIG_XILINX_AXI) += xilinx_axienet.o
 hw-obj-$(CONFIG_PUV3) += puv3_intc.o
 hw-obj-$(CONFIG_PUV3) += puv3_ost.o
 hw-obj-$(CONFIG_PUV3) += puv3_gpio.o
+hw-obj-$(CONFIG_PUV3) += puv3_pm.o
 
 # PCI watchdog devices
 hw-obj-$(CONFIG_PCI) += wdt_i6300esb.o
diff --git a/hw/puv3.c b/hw/puv3.c
index 0354cf6..3a14b27 100644
--- a/hw/puv3.c
+++ b/hw/puv3.c
@@ -48,6 +48,7 @@ static void puv3_soc_init(CPUUniCore32State *env)
     }
 
     /* Initialize minimal necessary devices for kernel booting */
+    sysbus_create_simple("puv3_pm", PUV3_PM_BASE, NULL);
     sysbus_create_simple("puv3_ost", PUV3_OST_BASE, irqs[PUV3_IRQS_OST0]);
     sysbus_create_varargs("puv3_gpio", PUV3_GPIO_BASE,
             irqs[PUV3_IRQS_GPIOLOW0], irqs[PUV3_IRQS_GPIOLOW1],
diff --git a/hw/puv3_pm.c b/hw/puv3_pm.c
new file mode 100644
index 0000000..621c968
--- /dev/null
+++ b/hw/puv3_pm.c
@@ -0,0 +1,149 @@
+/*
+ * Power Management device simulation in PKUnity SoC
+ *
+ * Copyright (C) 2010-2012 Guan Xuetao
+ *
+ * This program is free software; you can redistribute it and/or modify
+ * it under the terms of the GNU General Public License version 2 as
+ * published by the Free Software Foundation, or any later version.
+ * See the COPYING file in the top-level directory.
+ */
+#include "hw.h"
+#include "sysbus.h"
+
+#undef DEBUG_PUV3
+#include "puv3.h"
+
+typedef struct {
+    SysBusDevice busdev;
+    MemoryRegion iomem;
+
+    uint32_t reg_PMCR;
+    uint32_t reg_PCGR;
+    uint32_t reg_PLL_SYS_CFG;
+    uint32_t reg_PLL_DDR_CFG;
+    uint32_t reg_PLL_VGA_CFG;
+    uint32_t reg_DIVCFG;
+} PUV3PMState;
+
+static uint64_t puv3_pm_read(void *opaque, target_phys_addr_t offset,
+        unsigned size)
+{
+    PUV3PMState *s = opaque;
+    uint32_t ret = 0;
+
+    switch (offset) {
+    case 0x14:
+        ret = s->reg_PCGR;
+        break;
+    case 0x18:
+        ret = s->reg_PLL_SYS_CFG;
+        break;
+    case 0x1c:
+        ret = s->reg_PLL_DDR_CFG;
+        break;
+    case 0x20:
+        ret = s->reg_PLL_VGA_CFG;
+        break;
+    case 0x24:
+        ret = s->reg_DIVCFG;
+        break;
+    case 0x28: /* PLL SYS STATUS */
+        ret = 0x00002401;
+        break;
+    case 0x2c: /* PLL DDR STATUS */
+        ret = 0x00100c00;
+        break;
+    case 0x30: /* PLL VGA STATUS */
+        ret = 0x00003801;
+        break;
+    case 0x34: /* DIV STATUS */
+        ret = 0x22f52015;
+        break;
+    case 0x38: /* SW RESET */
+        ret = 0x0;
+        break;
+    case 0x44: /* PLL DFC DONE */
+        ret = 0x7;
+        break;
+    default:
+        DPRINTF("Bad offset 0x%x\n", offset);
+    }
+    DPRINTF("offset 0x%x, value 0x%x\n", offset, ret);
+
+    return ret;
+}
+
+static void puv3_pm_write(void *opaque, target_phys_addr_t offset,
+        uint64_t value, unsigned size)
+{
+    PUV3PMState *s = opaque;
+
+    switch (offset) {
+    case 0x0:
+        s->reg_PMCR = value;
+        break;
+    case 0x14:
+        s->reg_PCGR = value;
+        break;
+    case 0x18:
+        s->reg_PLL_SYS_CFG = value;
+        break;
+    case 0x1c:
+        s->reg_PLL_DDR_CFG = value;
+        break;
+    case 0x20:
+        s->reg_PLL_VGA_CFG = value;
+        break;
+    case 0x24:
+    case 0x38:
+        break;
+    default:
+        DPRINTF("Bad offset 0x%x\n", offset);
+    }
+    DPRINTF("offset 0x%x, value 0x%x\n", offset, value);
+}
+
+static const MemoryRegionOps puv3_pm_ops = {
+    .read = puv3_pm_read,
+    .write = puv3_pm_write,
+    .impl = {
+        .min_access_size = 4,
+        .max_access_size = 4,
+    },
+    .endianness = DEVICE_NATIVE_ENDIAN,
+};
+
+static int puv3_pm_init(SysBusDevice *dev)
+{
+    PUV3PMState *s = FROM_SYSBUS(PUV3PMState, dev);
+
+    s->reg_PCGR = 0x0;
+
+    memory_region_init_io(&s->iomem, &puv3_pm_ops, s, "puv3_pm",
+            PUV3_REGS_OFFSET);
+    sysbus_init_mmio(dev, &s->iomem);
+
+    return 0;
+}
+
+static void puv3_pm_class_init(ObjectClass *klass, void *data)
+{
+    SysBusDeviceClass *sdc = SYS_BUS_DEVICE_CLASS(klass);
+
+    sdc->init = puv3_pm_init;
+}
+
+static const TypeInfo puv3_pm_info = {
+    .name = "puv3_pm",
+    .parent = TYPE_SYS_BUS_DEVICE,
+    .instance_size = sizeof(PUV3PMState),
+    .class_init = puv3_pm_class_init,
+};
+
+static void puv3_pm_register_type(void)
+{
+    type_register_static(&puv3_pm_info);
+}
+
+type_init(puv3_pm_register_type)
commit a89d01c1925e88e7f6432b334e0b681899454486
Author: Guan Xuetao <gxt at mprc.pku.edu.cn>
Date:   Fri Aug 10 14:42:30 2012 +0800

    unicore32-softmmu: Add puv3 gpio support
    
    This patch adds puv3 gpio (General Purpose Input/Output) support,
    include gpio device simulation and its interrupt support.
    
    v1->v2: Add initialization to ret in puv3_gpio_read.
    
    Signed-off-by: Guan Xuetao <gxt at mprc.pku.edu.cn>
    Signed-off-by: Blue Swirl <blauwirbel at gmail.com>

diff --git a/hw/Makefile.objs b/hw/Makefile.objs
index 583dd6d..0e6ad8c 100644
--- a/hw/Makefile.objs
+++ b/hw/Makefile.objs
@@ -69,6 +69,7 @@ hw-obj-$(CONFIG_XILINX_AXI) += xilinx_axienet.o
 # PKUnity SoC devices
 hw-obj-$(CONFIG_PUV3) += puv3_intc.o
 hw-obj-$(CONFIG_PUV3) += puv3_ost.o
+hw-obj-$(CONFIG_PUV3) += puv3_gpio.o
 
 # PCI watchdog devices
 hw-obj-$(CONFIG_PCI) += wdt_i6300esb.o
diff --git a/hw/puv3.c b/hw/puv3.c
index 5a8a27c..0354cf6 100644
--- a/hw/puv3.c
+++ b/hw/puv3.c
@@ -49,6 +49,12 @@ static void puv3_soc_init(CPUUniCore32State *env)
 
     /* Initialize minimal necessary devices for kernel booting */
     sysbus_create_simple("puv3_ost", PUV3_OST_BASE, irqs[PUV3_IRQS_OST0]);
+    sysbus_create_varargs("puv3_gpio", PUV3_GPIO_BASE,
+            irqs[PUV3_IRQS_GPIOLOW0], irqs[PUV3_IRQS_GPIOLOW1],
+            irqs[PUV3_IRQS_GPIOLOW2], irqs[PUV3_IRQS_GPIOLOW3],
+            irqs[PUV3_IRQS_GPIOLOW4], irqs[PUV3_IRQS_GPIOLOW5],
+            irqs[PUV3_IRQS_GPIOLOW6], irqs[PUV3_IRQS_GPIOLOW7],
+            irqs[PUV3_IRQS_GPIOHIGH], NULL);
 }
 
 static void puv3_board_init(CPUUniCore32State *env, ram_addr_t ram_size)
diff --git a/hw/puv3_gpio.c b/hw/puv3_gpio.c
new file mode 100644
index 0000000..9436e6c
--- /dev/null
+++ b/hw/puv3_gpio.c
@@ -0,0 +1,141 @@
+/*
+ * GPIO device simulation in PKUnity SoC
+ *
+ * Copyright (C) 2010-2012 Guan Xuetao
+ *
+ * This program is free software; you can redistribute it and/or modify
+ * it under the terms of the GNU General Public License version 2 as
+ * published by the Free Software Foundation, or any later version.
+ * See the COPYING file in the top-level directory.
+ */
+#include "hw.h"
+#include "sysbus.h"
+
+#undef DEBUG_PUV3
+#include "puv3.h"
+
+typedef struct {
+    SysBusDevice busdev;
+    MemoryRegion iomem;
+    qemu_irq irq[9];
+
+    uint32_t reg_GPLR;
+    uint32_t reg_GPDR;
+    uint32_t reg_GPIR;
+} PUV3GPIOState;
+
+static uint64_t puv3_gpio_read(void *opaque, target_phys_addr_t offset,
+        unsigned size)
+{
+    PUV3GPIOState *s = opaque;
+    uint32_t ret = 0;
+
+    switch (offset) {
+    case 0x00:
+        ret = s->reg_GPLR;
+        break;
+    case 0x04:
+        ret = s->reg_GPDR;
+        break;
+    case 0x20:
+        ret = s->reg_GPIR;
+        break;
+    default:
+        DPRINTF("Bad offset 0x%x\n", offset);
+    }
+    DPRINTF("offset 0x%x, value 0x%x\n", offset, ret);
+
+    return ret;
+}
+
+static void puv3_gpio_write(void *opaque, target_phys_addr_t offset,
+        uint64_t value, unsigned size)
+{
+    PUV3GPIOState *s = opaque;
+
+    DPRINTF("offset 0x%x, value 0x%x\n", offset, value);
+    switch (offset) {
+    case 0x04:
+        s->reg_GPDR = value;
+        break;
+    case 0x08:
+        if (s->reg_GPDR & value) {
+            s->reg_GPLR |= value;
+        } else {
+            DPRINTF("Write gpio input port error!");
+        }
+        break;
+    case 0x0c:
+        if (s->reg_GPDR & value) {
+            s->reg_GPLR &= ~value;
+        } else {
+            DPRINTF("Write gpio input port error!");
+        }
+        break;
+    case 0x10: /* GRER */
+    case 0x14: /* GFER */
+    case 0x18: /* GEDR */
+        break;
+    case 0x20: /* GPIR */
+        s->reg_GPIR = value;
+        break;
+    default:
+        DPRINTF("Bad offset 0x%x\n", offset);
+    }
+}
+
+static const MemoryRegionOps puv3_gpio_ops = {
+    .read = puv3_gpio_read,
+    .write = puv3_gpio_write,
+    .impl = {
+        .min_access_size = 4,
+        .max_access_size = 4,
+    },
+    .endianness = DEVICE_NATIVE_ENDIAN,
+};
+
+static int puv3_gpio_init(SysBusDevice *dev)
+{
+    PUV3GPIOState *s = FROM_SYSBUS(PUV3GPIOState, dev);
+
+    s->reg_GPLR = 0;
+    s->reg_GPDR = 0;
+
+    /* FIXME: these irqs not handled yet */
+    sysbus_init_irq(dev, &s->irq[PUV3_IRQS_GPIOLOW0]);
+    sysbus_init_irq(dev, &s->irq[PUV3_IRQS_GPIOLOW1]);
+    sysbus_init_irq(dev, &s->irq[PUV3_IRQS_GPIOLOW2]);
+    sysbus_init_irq(dev, &s->irq[PUV3_IRQS_GPIOLOW3]);
+    sysbus_init_irq(dev, &s->irq[PUV3_IRQS_GPIOLOW4]);
+    sysbus_init_irq(dev, &s->irq[PUV3_IRQS_GPIOLOW5]);
+    sysbus_init_irq(dev, &s->irq[PUV3_IRQS_GPIOLOW6]);
+    sysbus_init_irq(dev, &s->irq[PUV3_IRQS_GPIOLOW7]);
+    sysbus_init_irq(dev, &s->irq[PUV3_IRQS_GPIOHIGH]);
+
+    memory_region_init_io(&s->iomem, &puv3_gpio_ops, s, "puv3_gpio",
+            PUV3_REGS_OFFSET);
+    sysbus_init_mmio(dev, &s->iomem);
+
+    return 0;
+}
+
+static void puv3_gpio_class_init(ObjectClass *klass, void *data)
+{
+    SysBusDeviceClass *sdc = SYS_BUS_DEVICE_CLASS(klass);
+
+    sdc->init = puv3_gpio_init;
+}
+
+static const TypeInfo puv3_gpio_info = {
+    .name = "puv3_gpio",
+    .parent = TYPE_SYS_BUS_DEVICE,
+    .instance_size = sizeof(PUV3GPIOState),
+    .class_init = puv3_gpio_class_init,
+};
+
+static void puv3_gpio_register_type(void)
+{
+    type_register_static(&puv3_gpio_info);
+}
+
+type_init(puv3_gpio_register_type)
commit 56d07a905025c18a14fef8f85c427e078a7cea79
Author: Guan Xuetao <gxt at mprc.pku.edu.cn>
Date:   Fri Aug 10 14:42:29 2012 +0800

    unicore32-softmmu: Add puv3 ostimer support
    
    This patch adds puv3 ostimer support, include os timer
    device simulation and ptimer support in puv3 machine.
    
    Signed-off-by: Guan Xuetao <gxt at mprc.pku.edu.cn>
    Signed-off-by: Blue Swirl <blauwirbel at gmail.com>

diff --git a/default-configs/unicore32-softmmu.mak b/default-configs/unicore32-softmmu.mak
index 726a338..4d4fbfc 100644
--- a/default-configs/unicore32-softmmu.mak
+++ b/default-configs/unicore32-softmmu.mak
@@ -1,2 +1,3 @@
 # Default configuration for unicore32-softmmu
 CONFIG_PUV3=y
+CONFIG_PTIMER=y
diff --git a/hw/Makefile.objs b/hw/Makefile.objs
index 278070f..583dd6d 100644
--- a/hw/Makefile.objs
+++ b/hw/Makefile.objs
@@ -68,6 +68,7 @@ hw-obj-$(CONFIG_XILINX_AXI) += xilinx_axienet.o
 
 # PKUnity SoC devices
 hw-obj-$(CONFIG_PUV3) += puv3_intc.o
+hw-obj-$(CONFIG_PUV3) += puv3_ost.o
 
 # PCI watchdog devices
 hw-obj-$(CONFIG_PCI) += wdt_i6300esb.o
diff --git a/hw/puv3.c b/hw/puv3.c
index 2870455..5a8a27c 100644
--- a/hw/puv3.c
+++ b/hw/puv3.c
@@ -46,6 +46,9 @@ static void puv3_soc_init(CPUUniCore32State *env)
     for (i = 0; i < PUV3_IRQS_NR; i++) {
         irqs[i] = qdev_get_gpio_in(dev, i);
     }
+
+    /* Initialize minimal necessary devices for kernel booting */
+    sysbus_create_simple("puv3_ost", PUV3_OST_BASE, irqs[PUV3_IRQS_OST0]);
 }
 
 static void puv3_board_init(CPUUniCore32State *env, ram_addr_t ram_size)
diff --git a/hw/puv3_ost.c b/hw/puv3_ost.c
new file mode 100644
index 0000000..dd30cad
--- /dev/null
+++ b/hw/puv3_ost.c
@@ -0,0 +1,151 @@
+/*
+ * OSTimer device simulation in PKUnity SoC
+ *
+ * Copyright (C) 2010-2012 Guan Xuetao
+ *
+ * This program is free software; you can redistribute it and/or modify
+ * it under the terms of the GNU General Public License version 2 as
+ * published by the Free Software Foundation, or any later version.
+ * See the COPYING file in the top-level directory.
+ */
+#include "sysbus.h"
+#include "ptimer.h"
+
+#undef DEBUG_PUV3
+#include "puv3.h"
+
+/* puv3 ostimer implementation. */
+typedef struct {
+    SysBusDevice busdev;
+    MemoryRegion iomem;
+    QEMUBH *bh;
+    qemu_irq irq;
+    ptimer_state *ptimer;
+
+    uint32_t reg_OSMR0;
+    uint32_t reg_OSCR;
+    uint32_t reg_OSSR;
+    uint32_t reg_OIER;
+} PUV3OSTState;
+
+static uint64_t puv3_ost_read(void *opaque, target_phys_addr_t offset,
+        unsigned size)
+{
+    PUV3OSTState *s = opaque;
+    uint32_t ret = 0;
+
+    switch (offset) {
+    case 0x10: /* Counter Register */
+        ret = s->reg_OSMR0 - (uint32_t)ptimer_get_count(s->ptimer);
+        break;
+    case 0x14: /* Status Register */
+        ret = s->reg_OSSR;
+        break;
+    case 0x1c: /* Interrupt Enable Register */
+        ret = s->reg_OIER;
+        break;
+    default:
+        DPRINTF("Bad offset %x\n", (int)offset);
+    }
+    DPRINTF("offset 0x%x, value 0x%x\n", offset, ret);
+    return ret;
+}
+
+static void puv3_ost_write(void *opaque, target_phys_addr_t offset,
+        uint64_t value, unsigned size)
+{
+    PUV3OSTState *s = opaque;
+
+    DPRINTF("offset 0x%x, value 0x%x\n", offset, value);
+    switch (offset) {
+    case 0x00: /* Match Register 0 */
+        s->reg_OSMR0 = value;
+        if (s->reg_OSMR0 > s->reg_OSCR) {
+            ptimer_set_count(s->ptimer, s->reg_OSMR0 - s->reg_OSCR);
+        } else {
+            ptimer_set_count(s->ptimer, s->reg_OSMR0 +
+                    (0xffffffff - s->reg_OSCR));
+        }
+        ptimer_run(s->ptimer, 2);
+        break;
+    case 0x14: /* Status Register */
+        assert(value == 0);
+        if (s->reg_OSSR) {
+            s->reg_OSSR = value;
+            qemu_irq_lower(s->irq);
+        }
+        break;
+    case 0x1c: /* Interrupt Enable Register */
+        s->reg_OIER = value;
+        break;
+    default:
+        DPRINTF("Bad offset %x\n", (int)offset);
+    }
+}
+
+static const MemoryRegionOps puv3_ost_ops = {
+    .read = puv3_ost_read,
+    .write = puv3_ost_write,
+    .impl = {
+        .min_access_size = 4,
+        .max_access_size = 4,
+    },
+    .endianness = DEVICE_NATIVE_ENDIAN,
+};
+
+static void puv3_ost_tick(void *opaque)
+{
+    PUV3OSTState *s = opaque;
+
+    DPRINTF("ost hit when ptimer counter from 0x%x to 0x%x!\n",
+            s->reg_OSCR, s->reg_OSMR0);
+
+    s->reg_OSCR = s->reg_OSMR0;
+    if (s->reg_OIER) {
+        s->reg_OSSR = 1;
+        qemu_irq_raise(s->irq);
+    }
+}
+
+static int puv3_ost_init(SysBusDevice *dev)
+{
+    PUV3OSTState *s = FROM_SYSBUS(PUV3OSTState, dev);
+
+    s->reg_OIER = 0;
+    s->reg_OSSR = 0;
+    s->reg_OSMR0 = 0;
+    s->reg_OSCR = 0;
+
+    sysbus_init_irq(dev, &s->irq);
+
+    s->bh = qemu_bh_new(puv3_ost_tick, s);
+    s->ptimer = ptimer_init(s->bh);
+    ptimer_set_freq(s->ptimer, 50 * 1000 * 1000);
+
+    memory_region_init_io(&s->iomem, &puv3_ost_ops, s, "puv3_ost",
+            PUV3_REGS_OFFSET);
+    sysbus_init_mmio(dev, &s->iomem);
+
+    return 0;
+}
+
+static void puv3_ost_class_init(ObjectClass *klass, void *data)
+{
+    SysBusDeviceClass *sdc = SYS_BUS_DEVICE_CLASS(klass);
+
+    sdc->init = puv3_ost_init;
+}
+
+static const TypeInfo puv3_ost_info = {
+    .name = "puv3_ost",
+    .parent = TYPE_SYS_BUS_DEVICE,
+    .instance_size = sizeof(PUV3OSTState),
+    .class_init = puv3_ost_class_init,
+};
+
+static void puv3_ost_register_type(void)
+{
+    type_register_static(&puv3_ost_info);
+}
+
+type_init(puv3_ost_register_type)
commit 5c8556a6f64842c78c2e3493f9d7544af5736ddb
Author: Guan Xuetao <gxt at mprc.pku.edu.cn>
Date:   Fri Aug 10 14:42:28 2012 +0800

    unicore32-softmmu: Add puv3 interrupt support
    
    This patch adds puv3 interrupt support, include interrupt controler
    device simulation and interrupt handler in puv3 machine.
    
    Signed-off-by: Guan Xuetao <gxt at mprc.pku.edu.cn>
    Signed-off-by: Blue Swirl <blauwirbel at gmail.com>

diff --git a/hw/Makefile.objs b/hw/Makefile.objs
index 12cc141..278070f 100644
--- a/hw/Makefile.objs
+++ b/hw/Makefile.objs
@@ -66,6 +66,9 @@ hw-obj-$(CONFIG_XILINX) += xilinx_uartlite.o
 hw-obj-$(CONFIG_XILINX_AXI) += xilinx_axidma.o
 hw-obj-$(CONFIG_XILINX_AXI) += xilinx_axienet.o
 
+# PKUnity SoC devices
+hw-obj-$(CONFIG_PUV3) += puv3_intc.o
+
 # PCI watchdog devices
 hw-obj-$(CONFIG_PCI) += wdt_i6300esb.o
 
diff --git a/hw/puv3.c b/hw/puv3.c
index 0dc129d..2870455 100644
--- a/hw/puv3.c
+++ b/hw/puv3.c
@@ -22,9 +22,30 @@
 #define KERNEL_LOAD_ADDR        0x03000000
 #define KERNEL_MAX_SIZE         0x00800000 /* Just a guess */
 
+static void puv3_intc_cpu_handler(void *opaque, int irq, int level)
+{
+    CPUUniCore32State *env = opaque;
+
+    assert(irq == 0);
+    if (level) {
+        cpu_interrupt(env, CPU_INTERRUPT_HARD);
+    } else {
+        cpu_reset_interrupt(env, CPU_INTERRUPT_HARD);
+    }
+}
+
 static void puv3_soc_init(CPUUniCore32State *env)
 {
-    /* TODO */
+    qemu_irq *cpu_intc, irqs[PUV3_IRQS_NR];
+    DeviceState *dev;
+    int i;
+
+    /* Initialize interrupt controller */
+    cpu_intc = qemu_allocate_irqs(puv3_intc_cpu_handler, env, 1);
+    dev = sysbus_create_simple("puv3_intc", PUV3_INTC_BASE, *cpu_intc);
+    for (i = 0; i < PUV3_IRQS_NR; i++) {
+        irqs[i] = qdev_get_gpio_in(dev, i);
+    }
 }
 
 static void puv3_board_init(CPUUniCore32State *env, ram_addr_t ram_size)
diff --git a/hw/puv3_intc.c b/hw/puv3_intc.c
new file mode 100644
index 0000000..9e0b975
--- /dev/null
+++ b/hw/puv3_intc.c
@@ -0,0 +1,135 @@
+/*
+ * INTC device simulation in PKUnity SoC
+ *
+ * Copyright (C) 2010-2012 Guan Xuetao
+ *
+ * This program is free software; you can redistribute it and/or modify
+ * it under the terms of the GNU General Public License version 2 as
+ * published by the Free Software Foundation, or any later version.
+ * See the COPYING file in the top-level directory.
+ */
+#include "sysbus.h"
+
+#undef DEBUG_PUV3
+#include "puv3.h"
+
+typedef struct {
+    SysBusDevice busdev;
+    MemoryRegion iomem;
+    qemu_irq parent_irq;
+
+    uint32_t reg_ICMR;
+    uint32_t reg_ICPR;
+} PUV3INTCState;
+
+/* Update interrupt status after enabled or pending bits have been changed.  */
+static void puv3_intc_update(PUV3INTCState *s)
+{
+    if (s->reg_ICMR & s->reg_ICPR) {
+        qemu_irq_raise(s->parent_irq);
+    } else {
+        qemu_irq_lower(s->parent_irq);
+    }
+}
+
+/* Process a change in an external INTC input. */
+static void puv3_intc_handler(void *opaque, int irq, int level)
+{
+    PUV3INTCState *s = opaque;
+
+    DPRINTF("irq 0x%x, level 0x%x\n", irq, level);
+    if (level) {
+        s->reg_ICPR |= (1 << irq);
+    } else {
+        s->reg_ICPR &= ~(1 << irq);
+    }
+    puv3_intc_update(s);
+}
+
+static uint64_t puv3_intc_read(void *opaque, target_phys_addr_t offset,
+        unsigned size)
+{
+    PUV3INTCState *s = opaque;
+    uint32_t ret = 0;
+
+    switch (offset) {
+    case 0x04: /* INTC_ICMR */
+        ret = s->reg_ICMR;
+        break;
+    case 0x0c: /* INTC_ICIP */
+        ret = s->reg_ICPR; /* the same value with ICPR */
+        break;
+    default:
+        DPRINTF("Bad offset %x\n", (int)offset);
+    }
+    DPRINTF("offset 0x%x, value 0x%x\n", offset, ret);
+    return ret;
+}
+
+static void puv3_intc_write(void *opaque, target_phys_addr_t offset,
+        uint64_t value, unsigned size)
+{
+    PUV3INTCState *s = opaque;
+
+    DPRINTF("offset 0x%x, value 0x%x\n", offset, value);
+    switch (offset) {
+    case 0x00: /* INTC_ICLR */
+    case 0x14: /* INTC_ICCR */
+        break;
+    case 0x04: /* INTC_ICMR */
+        s->reg_ICMR = value;
+        break;
+    default:
+        DPRINTF("Bad offset 0x%x\n", (int)offset);
+        return;
+    }
+    puv3_intc_update(s);
+}
+
+static const MemoryRegionOps puv3_intc_ops = {
+    .read = puv3_intc_read,
+    .write = puv3_intc_write,
+    .impl = {
+        .min_access_size = 4,
+        .max_access_size = 4,
+    },
+    .endianness = DEVICE_NATIVE_ENDIAN,
+};
+
+static int puv3_intc_init(SysBusDevice *dev)
+{
+    PUV3INTCState *s = FROM_SYSBUS(PUV3INTCState, dev);
+
+    qdev_init_gpio_in(&s->busdev.qdev, puv3_intc_handler, PUV3_IRQS_NR);
+    sysbus_init_irq(&s->busdev, &s->parent_irq);
+
+    s->reg_ICMR = 0;
+    s->reg_ICPR = 0;
+
+    memory_region_init_io(&s->iomem, &puv3_intc_ops, s, "puv3_intc",
+            PUV3_REGS_OFFSET);
+    sysbus_init_mmio(dev, &s->iomem);
+
+    return 0;
+}
+
+static void puv3_intc_class_init(ObjectClass *klass, void *data)
+{
+    SysBusDeviceClass *sdc = SYS_BUS_DEVICE_CLASS(klass);
+
+    sdc->init = puv3_intc_init;
+}
+
+static const TypeInfo puv3_intc_info = {
+    .name = "puv3_intc",
+    .parent = TYPE_SYS_BUS_DEVICE,
+    .instance_size = sizeof(PUV3INTCState),
+    .class_init = puv3_intc_class_init,
+};
+
+static void puv3_intc_register_type(void)
+{
+    type_register_static(&puv3_intc_info);
+}
+
+type_init(puv3_intc_register_type)
commit fbbdf9838d30ecdf24b0ff9f6a4e9567d74e39bd
Author: Guan Xuetao <gxt at mprc.pku.edu.cn>
Date:   Fri Aug 10 14:42:27 2012 +0800

    unicore32-softmmu: Add puv3 soc/board support
    
    This patch only add puv3 soc/board support, which introduces puv3
    machine description, and specifies console type.
    
    Signed-off-by: Guan Xuetao <gxt at mprc.pku.edu.cn>
    Signed-off-by: Blue Swirl <blauwirbel at gmail.com>

diff --git a/default-configs/unicore32-softmmu.mak b/default-configs/unicore32-softmmu.mak
index 5f04fe3..726a338 100644
--- a/default-configs/unicore32-softmmu.mak
+++ b/default-configs/unicore32-softmmu.mak
@@ -1 +1,2 @@
 # Default configuration for unicore32-softmmu
+CONFIG_PUV3=y
diff --git a/hw/puv3.c b/hw/puv3.c
new file mode 100644
index 0000000..0dc129d
--- /dev/null
+++ b/hw/puv3.c
@@ -0,0 +1,93 @@
+/*
+ * Generic PKUnity SoC machine and board descriptor
+ *
+ * Copyright (C) 2010-2012 Guan Xuetao
+ *
+ * This program is free software; you can redistribute it and/or modify
+ * it under the terms of the GNU General Public License version 2 as
+ * published by the Free Software Foundation, or any later version.
+ * See the COPYING file in the top-level directory.
+ */
+#include "console.h"
+#include "elf.h"
+#include "exec-memory.h"
+#include "sysbus.h"
+#include "boards.h"
+#include "loader.h"
+#include "pc.h"
+
+#undef DEBUG_PUV3
+#include "puv3.h"
+
+#define KERNEL_LOAD_ADDR        0x03000000
+#define KERNEL_MAX_SIZE         0x00800000 /* Just a guess */
+
+static void puv3_soc_init(CPUUniCore32State *env)
+{
+    /* TODO */
+}
+
+static void puv3_board_init(CPUUniCore32State *env, ram_addr_t ram_size)
+{
+    MemoryRegion *ram_memory = g_new(MemoryRegion, 1);
+
+    /* SDRAM at address zero.  */
+    memory_region_init_ram(ram_memory, "puv3.ram", ram_size);
+    vmstate_register_ram_global(ram_memory);
+    memory_region_add_subregion(get_system_memory(), 0, ram_memory);
+}
+
+static void puv3_load_kernel(const char *kernel_filename)
+{
+    int size;
+
+    assert(kernel_filename != NULL);
+
+    /* only zImage format supported */
+    size = load_image_targphys(kernel_filename, KERNEL_LOAD_ADDR,
+            KERNEL_MAX_SIZE);
+    if (size < 0) {
+        hw_error("Load kernel error: '%s'\n", kernel_filename);
+    }
+
+    /* cheat curses that we have a graphic console, only under ocd console */
+    graphic_console_init(NULL, NULL, NULL, NULL, NULL);
+}
+
+static void puv3_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)
+{
+    CPUUniCore32State *env;
+
+    if (initrd_filename) {
+        hw_error("Please use kernel built-in initramdisk.\n");
+    }
+
+    if (!cpu_model) {
+        cpu_model = "UniCore-II";
+    }
+
+    env = cpu_init(cpu_model);
+    if (!env) {
+        hw_error("Unable to find CPU definition\n");
+    }
+
+    puv3_soc_init(env);
+    puv3_board_init(env, ram_size);
+    puv3_load_kernel(kernel_filename);
+}
+
+static QEMUMachine puv3_machine = {
+    .name = "puv3",
+    .desc = "PKUnity Version-3 based on UniCore32",
+    .init = puv3_init,
+    .use_scsi = 0,
+};
+
+static void puv3_machine_init(void)
+{
+    qemu_register_machine(&puv3_machine);
+}
+
+machine_init(puv3_machine_init)
diff --git a/hw/puv3.h b/hw/puv3.h
new file mode 100644
index 0000000..f37adcb
--- /dev/null
+++ b/hw/puv3.h
@@ -0,0 +1,49 @@
+/*
+ * Misc PKUnity SoC declarations
+ *
+ * Copyright (C) 2010-2012 Guan Xuetao
+ *
+ * This program is free software; you can redistribute it and/or modify
+ * it under the terms of the GNU General Public License version 2 as
+ * published by the Free Software Foundation, or any later version.
+ * See the COPYING file in the top-level directory.
+ */
+#ifndef QEMU_HW_PUV3_H
+#define QEMU_HW_PUV3_H
+
+#define PUV3_REGS_OFFSET        (0x1000) /* 4K is reasonable */
+
+/* PKUnity System bus (AHB): 0xc0000000 - 0xedffffff (640MB) */
+#define PUV3_DMA_BASE           (0xc0200000) /* AHB-4 */
+
+/* PKUnity Peripheral bus (APB): 0xee000000 - 0xefffffff (128MB) */
+#define PUV3_GPIO_BASE          (0xee500000) /* APB-5 */
+#define PUV3_INTC_BASE          (0xee600000) /* APB-6 */
+#define PUV3_OST_BASE           (0xee800000) /* APB-8 */
+#define PUV3_PM_BASE            (0xeea00000) /* APB-10 */
+#define PUV3_PS2_BASE           (0xeeb00000) /* APB-11 */
+
+/* Hardware interrupts */
+#define PUV3_IRQS_NR            (32)
+
+#define PUV3_IRQS_GPIOLOW0      (0)
+#define PUV3_IRQS_GPIOLOW1      (1)
+#define PUV3_IRQS_GPIOLOW2      (2)
+#define PUV3_IRQS_GPIOLOW3      (3)
+#define PUV3_IRQS_GPIOLOW4      (4)
+#define PUV3_IRQS_GPIOLOW5      (5)
+#define PUV3_IRQS_GPIOLOW6      (6)
+#define PUV3_IRQS_GPIOLOW7      (7)
+#define PUV3_IRQS_GPIOHIGH      (8)
+#define PUV3_IRQS_PS2_KBD       (22)
+#define PUV3_IRQS_PS2_AUX       (23)
+#define PUV3_IRQS_OST0          (26)
+
+/* All puv3_*.c use DPRINTF for debug. */
+#ifdef DEBUG_PUV3
+#define DPRINTF(fmt, ...) printf("%s: " fmt , __func__, ## __VA_ARGS__)
+#else
+#define DPRINTF(fmt, ...) do {} while (0)
+#endif
+
+#endif /* !QEMU_HW_PUV3_H */
diff --git a/hw/unicore32/Makefile.objs b/hw/unicore32/Makefile.objs
index b6a3383..0725ce3 100644
--- a/hw/unicore32/Makefile.objs
+++ b/hw/unicore32/Makefile.objs
@@ -1 +1,6 @@
 # For UniCore32 machines and boards
+
+# PKUnity-v3 SoC and board information
+obj-${CONFIG_PUV3} += puv3.o
+
+obj-y := $(addprefix ../,$(obj-y))
commit ef03168a8536f4427ab24a1fc43638dfbecc1bf8
Author: Guan Xuetao <gxt at mprc.pku.edu.cn>
Date:   Fri Aug 10 14:42:26 2012 +0800

    unicore32-softmmu: Make sure that kernel can access user space
    
    As a matter of course, we need to access user space in kernel code,
    so we need to correct load/store decoders to indicate correct memory
    region.
    
    Signed-off-by: Guan Xuetao <gxt at mprc.pku.edu.cn>
    Signed-off-by: Blue Swirl <blauwirbel at gmail.com>

diff --git a/target-unicore32/translate.c b/target-unicore32/translate.c
index e37d5be..5ee3a59 100644
--- a/target-unicore32/translate.c
+++ b/target-unicore32/translate.c
@@ -33,9 +33,16 @@ typedef struct DisasContext {
     int condlabel;
     struct TranslationBlock *tb;
     int singlestep_enabled;
+#ifndef CONFIG_USER_ONLY
+    int user;
+#endif
 } DisasContext;
 
-#define IS_USER(s) 1
+#ifndef CONFIG_USER_ONLY
+#define IS_USER(s)      (s->user)
+#else
+#define IS_USER(s)      1
+#endif
 
 /* These instructions trap after executing, so defer them until after the
    conditional executions state has been updated.  */
@@ -1554,12 +1561,12 @@ static void do_misc(CPUUniCore32State *env, DisasContext *s, uint32_t insn)
 /* load/store I_offset and R_offset */
 static void do_ldst_ir(CPUUniCore32State *env, DisasContext *s, uint32_t insn)
 {
-    unsigned int i;
+    unsigned int mmu_idx;
     TCGv tmp;
     TCGv tmp2;
 
     tmp2 = load_reg(s, UCOP_REG_N);
-    i = (IS_USER(s) || (!UCOP_SET_P && UCOP_SET_W));
+    mmu_idx = (IS_USER(s) || (!UCOP_SET_P && UCOP_SET_W));
 
     /* immediate */
     if (UCOP_SET_P) {
@@ -1569,17 +1576,17 @@ static void do_ldst_ir(CPUUniCore32State *env, DisasContext *s, uint32_t insn)
     if (UCOP_SET_L) {
         /* load */
         if (UCOP_SET_B) {
-            tmp = gen_ld8u(tmp2, i);
+            tmp = gen_ld8u(tmp2, mmu_idx);
         } else {
-            tmp = gen_ld32(tmp2, i);
+            tmp = gen_ld32(tmp2, mmu_idx);
         }
     } else {
         /* store */
         tmp = load_reg(s, UCOP_REG_D);
         if (UCOP_SET_B) {
-            gen_st8(tmp, tmp2, i);
+            gen_st8(tmp, tmp2, mmu_idx);
         } else {
-            gen_st32(tmp, tmp2, i);
+            gen_st32(tmp, tmp2, mmu_idx);
         }
     }
     if (!UCOP_SET_P) {
@@ -1682,7 +1689,7 @@ static void do_ldst_hwsb(CPUUniCore32State *env, DisasContext *s, uint32_t insn)
 /* load/store multiple words */
 static void do_ldst_m(CPUUniCore32State *env, DisasContext *s, uint32_t insn)
 {
-    unsigned int val, i;
+    unsigned int val, i, mmu_idx;
     int j, n, reg, user, loaded_base;
     TCGv tmp;
     TCGv tmp2;
@@ -1703,6 +1710,7 @@ static void do_ldst_m(CPUUniCore32State *env, DisasContext *s, uint32_t insn)
         }
     }
 
+    mmu_idx = (IS_USER(s) || (!UCOP_SET_P && UCOP_SET_W));
     addr = load_reg(s, UCOP_REG_N);
 
     /* compute total size */
@@ -1747,7 +1755,7 @@ static void do_ldst_m(CPUUniCore32State *env, DisasContext *s, uint32_t insn)
         }
         if (UCOP_SET(i)) {
             if (UCOP_SET_L) { /* load */
-                tmp = gen_ld32(addr, IS_USER(s));
+                tmp = gen_ld32(addr, mmu_idx);
                 if (reg == 31) {
                     gen_bx(s, tmp);
                 } else if (user) {
@@ -1775,7 +1783,7 @@ static void do_ldst_m(CPUUniCore32State *env, DisasContext *s, uint32_t insn)
                 } else {
                     tmp = load_reg(s, reg);
                 }
-                gen_st32(tmp, addr, IS_USER(s));
+                gen_st32(tmp, addr, mmu_idx);
             }
             j++;
             /* no need to add after the last transfer */
@@ -1964,6 +1972,14 @@ static inline void gen_intermediate_code_internal(CPUUniCore32State *env,
         max_insns = CF_COUNT_MASK;
     }
 
+#ifndef CONFIG_USER_ONLY
+    if ((env->uncached_asr & ASR_M) == ASR_MODE_USER) {
+        dc->user = 1;
+    } else {
+        dc->user = 0;
+    }
+#endif
+
     gen_icount_start();
     do {
         if (unlikely(!QTAILQ_EMPTY(&env->breakpoints))) {
commit f3ccc32369532e8a069ea5b7ee201b75e668deab
Author: Guan Xuetao <gxt at mprc.pku.edu.cn>
Date:   Fri Aug 10 14:42:25 2012 +0800

    unicore32-softmmu: Implement softmmu specific functions
    
    This patch implements softmmu specific functions, include tlb_fill,
    switch_mode, do_interrupt and uc32_cpu_handle_mmu_fault.
    So the full exception handlers and page table walking could work now.
    
    Signed-off-by: Guan Xuetao <gxt at mprc.pku.edu.cn>
    Signed-off-by: Blue Swirl <blauwirbel at gmail.com>

diff --git a/target-unicore32/op_helper.c b/target-unicore32/op_helper.c
index 6df30db..c63789d 100644
--- a/target-unicore32/op_helper.c
+++ b/target-unicore32/op_helper.c
@@ -267,6 +267,26 @@ uint32_t HELPER(ror_cc)(uint32_t x, uint32_t i)
 void tlb_fill(CPUUniCore32State *env1, target_ulong addr, int is_write,
         int mmu_idx, uintptr_t retaddr)
 {
-    cpu_abort(env, "%s not supported yet\n", __func__);
+    TranslationBlock *tb;
+    CPUUniCore32State *saved_env;
+    unsigned long pc;
+    int ret;
+
+    saved_env = env;
+    env = env1;
+    ret = uc32_cpu_handle_mmu_fault(env, addr, is_write, mmu_idx);
+    if (unlikely(ret)) {
+        if (retaddr) {
+            /* now we have a real cpu fault */
+            pc = (unsigned long)retaddr;
+            tb = tb_find_pc(pc);
+            if (tb) {/* the PC is inside the translated code.
+                        It means that we have a virtual CPU fault */
+                cpu_restore_state(tb, env, pc);
+            }
+        }
+        cpu_loop_exit(env);
+    }
+    env = saved_env;
 }
 #endif
diff --git a/target-unicore32/softmmu.c b/target-unicore32/softmmu.c
index 6fec77e..373f94b 100644
--- a/target-unicore32/softmmu.c
+++ b/target-unicore32/softmmu.c
@@ -14,21 +14,249 @@
 
 #include <cpu.h>
 
+#undef DEBUG_UC32
+
+#ifdef DEBUG_UC32
+#define DPRINTF(fmt, ...) printf("%s: " fmt , __func__, ## __VA_ARGS__)
+#else
+#define DPRINTF(fmt, ...) do {} while (0)
+#endif
+
+#define SUPERPAGE_SIZE             (1 << 22)
+#define UC32_PAGETABLE_READ        (1 << 8)
+#define UC32_PAGETABLE_WRITE       (1 << 7)
+#define UC32_PAGETABLE_EXEC        (1 << 6)
+#define UC32_PAGETABLE_EXIST       (1 << 2)
+#define PAGETABLE_TYPE(x)          ((x) & 3)
+
+
+/* Map CPU modes onto saved register banks.  */
+static inline int bank_number(int mode)
+{
+    switch (mode) {
+    case ASR_MODE_USER:
+    case ASR_MODE_SUSR:
+        return 0;
+    case ASR_MODE_PRIV:
+        return 1;
+    case ASR_MODE_TRAP:
+        return 2;
+    case ASR_MODE_EXTN:
+        return 3;
+    case ASR_MODE_INTR:
+        return 4;
+    }
+    cpu_abort(cpu_single_env, "Bad mode %x\n", mode);
+    return -1;
+}
+
 void switch_mode(CPUUniCore32State *env, int mode)
 {
-    cpu_abort(env, "%s not supported yet\n", __func__);
+    int old_mode;
+    int i;
+
+    old_mode = env->uncached_asr & ASR_M;
+    if (mode == old_mode) {
+        return;
+    }
+
+    i = bank_number(old_mode);
+    env->banked_r29[i] = env->regs[29];
+    env->banked_r30[i] = env->regs[30];
+    env->banked_bsr[i] = env->bsr;
+
+    i = bank_number(mode);
+    env->regs[29] = env->banked_r29[i];
+    env->regs[30] = env->banked_r30[i];
+    env->bsr = env->banked_bsr[i];
 }
 
+/* Handle a CPU exception.  */
 void do_interrupt(CPUUniCore32State *env)
 {
-    cpu_abort(env, "%s not supported yet\n", __func__);
+    uint32_t addr;
+    int new_mode;
+
+    switch (env->exception_index) {
+    case UC32_EXCP_PRIV:
+        new_mode = ASR_MODE_PRIV;
+        addr = 0x08;
+        break;
+    case UC32_EXCP_ITRAP:
+        DPRINTF("itrap happened at %x\n", env->regs[31]);
+        new_mode = ASR_MODE_TRAP;
+        addr = 0x0c;
+        break;
+    case UC32_EXCP_DTRAP:
+        DPRINTF("dtrap happened at %x\n", env->regs[31]);
+        new_mode = ASR_MODE_TRAP;
+        addr = 0x10;
+        break;
+    case UC32_EXCP_INTR:
+        new_mode = ASR_MODE_INTR;
+        addr = 0x18;
+        break;
+    default:
+        cpu_abort(env, "Unhandled exception 0x%x\n", env->exception_index);
+        return;
+    }
+    /* High vectors.  */
+    if (env->cp0.c1_sys & (1 << 13)) {
+        addr += 0xffff0000;
+    }
+
+    switch_mode(env, new_mode);
+    env->bsr = cpu_asr_read(env);
+    env->uncached_asr = (env->uncached_asr & ~ASR_M) | new_mode;
+    env->uncached_asr |= ASR_I;
+    /* The PC already points to the proper instruction.  */
+    env->regs[30] = env->regs[31];
+    env->regs[31] = addr;
+    env->interrupt_request |= CPU_INTERRUPT_EXITTB;
+}
+
+static int get_phys_addr_ucv2(CPUUniCore32State *env, uint32_t address,
+        int access_type, int is_user, uint32_t *phys_ptr, int *prot,
+        target_ulong *page_size)
+{
+    int code;
+    uint32_t table;
+    uint32_t desc;
+    uint32_t phys_addr;
+
+    /* Pagetable walk.  */
+    /* Lookup l1 descriptor.  */
+    table = env->cp0.c2_base & 0xfffff000;
+    table |= (address >> 20) & 0xffc;
+    desc = ldl_phys(table);
+    code = 0;
+    switch (PAGETABLE_TYPE(desc)) {
+    case 3:
+        /* Superpage  */
+        if (!(desc & UC32_PAGETABLE_EXIST)) {
+            code = 0x0b; /* superpage miss */
+            goto do_fault;
+        }
+        phys_addr = (desc & 0xffc00000) | (address & 0x003fffff);
+        *page_size = SUPERPAGE_SIZE;
+        break;
+    case 0:
+        /* Lookup l2 entry.  */
+        if (is_user) {
+            DPRINTF("PGD address %x, desc %x\n", table, desc);
+        }
+        if (!(desc & UC32_PAGETABLE_EXIST)) {
+            code = 0x05; /* second pagetable miss */
+            goto do_fault;
+        }
+        table = (desc & 0xfffff000) | ((address >> 10) & 0xffc);
+        desc = ldl_phys(table);
+        /* 4k page.  */
+        if (is_user) {
+            DPRINTF("PTE address %x, desc %x\n", table, desc);
+        }
+        if (!(desc & UC32_PAGETABLE_EXIST)) {
+            code = 0x08; /* page miss */
+            goto do_fault;
+        }
+        switch (PAGETABLE_TYPE(desc)) {
+        case 0:
+            phys_addr = (desc & 0xfffff000) | (address & 0xfff);
+            *page_size = TARGET_PAGE_SIZE;
+            break;
+        default:
+            cpu_abort(env, "wrong page type!");
+        }
+        break;
+    default:
+        cpu_abort(env, "wrong page type!");
+    }
+
+    *phys_ptr = phys_addr;
+    *prot = 0;
+    /* Check access permissions.  */
+    if (desc & UC32_PAGETABLE_READ) {
+        *prot |= PAGE_READ;
+    } else {
+        if (is_user && (access_type == 0)) {
+            code = 0x11; /* access unreadable area */
+            goto do_fault;
+        }
+    }
+
+    if (desc & UC32_PAGETABLE_WRITE) {
+        *prot |= PAGE_WRITE;
+    } else {
+        if (is_user && (access_type == 1)) {
+            code = 0x12; /* access unwritable area */
+            goto do_fault;
+        }
+    }
+
+    if (desc & UC32_PAGETABLE_EXEC) {
+        *prot |= PAGE_EXEC;
+    } else {
+        if (is_user && (access_type == 2)) {
+            code = 0x13; /* access unexecutable area */
+            goto do_fault;
+        }
+    }
+
+do_fault:
+    return code;
 }
 
 int uc32_cpu_handle_mmu_fault(CPUUniCore32State *env, target_ulong address,
                               int access_type, int mmu_idx)
 {
-    cpu_abort(env, "%s not supported yet\n", __func__);
-    return 1;
+    uint32_t phys_addr;
+    target_ulong page_size;
+    int prot;
+    int ret, is_user;
+
+    ret = 1;
+    is_user = mmu_idx == MMU_USER_IDX;
+
+    if ((env->cp0.c1_sys & 1) == 0) {
+        /* MMU disabled.  */
+        phys_addr = address;
+        prot = PAGE_READ | PAGE_WRITE | PAGE_EXEC;
+        page_size = TARGET_PAGE_SIZE;
+        ret = 0;
+    } else {
+        if ((address & (1 << 31)) || (is_user)) {
+            ret = get_phys_addr_ucv2(env, address, access_type, is_user,
+                                    &phys_addr, &prot, &page_size);
+            if (is_user) {
+                DPRINTF("user space access: ret %x, address %x, "
+                        "access_type %x, phys_addr %x, prot %x\n",
+                        ret, address, access_type, phys_addr, prot);
+            }
+        } else {
+            /*IO memory */
+            phys_addr = address | (1 << 31);
+            prot = PAGE_READ | PAGE_WRITE | PAGE_EXEC;
+            page_size = TARGET_PAGE_SIZE;
+            ret = 0;
+        }
+    }
+
+    if (ret == 0) {
+        /* Map a single page.  */
+        phys_addr &= TARGET_PAGE_MASK;
+        address &= TARGET_PAGE_MASK;
+        tlb_set_page(env, address, phys_addr, prot, mmu_idx, page_size);
+        return 0;
+    }
+
+    env->cp0.c3_faultstatus = ret;
+    env->cp0.c4_faultaddr = address;
+    if (access_type == 2) {
+        env->exception_index = UC32_EXCP_ITRAP;
+    } else {
+        env->exception_index = UC32_EXCP_DTRAP;
+    }
+    return ret;
 }
 
 target_phys_addr_t cpu_get_phys_page_debug(CPUUniCore32State *env,
commit 889c134a82ac30f9beafa214b3920b2b39687832
Author: Andreas Färber <afaerber at suse.de>
Date:   Fri Aug 10 14:42:24 2012 +0800

    target-unicore32: Drop UC32_CPUID macros
    
    Any code that depends on a particular CPU type can now go through
    callbacks on the QOM UniCore32CPUClass.
    
    Signed-off-by: Andreas Färber <afaerber at suse.de
    Acked-by: Guan Xuetao <gxt at mprc.pku.edu.cn>
    Signed-off-by: Blue Swirl <blauwirbel at gmail.com>

diff --git a/target-unicore32/cpu.h b/target-unicore32/cpu.h
index d14fde5..06508a1 100644
--- a/target-unicore32/cpu.h
+++ b/target-unicore32/cpu.h
@@ -122,10 +122,6 @@ void cpu_asr_write(CPUUniCore32State *env1, target_ulong val, target_ulong mask)
 #define UC32_HWCAP_CMOV                 4 /* 1 << 2 */
 #define UC32_HWCAP_UCF64                8 /* 1 << 3 */
 
-#define UC32_CPUID(env)                 (env->cp0.c0_cpuid)
-#define UC32_CPUID_UCV2                 0x40010863
-#define UC32_CPUID_ANY                  0xffffffff
-
 #define cpu_init                        uc32_cpu_init
 #define cpu_exec                        uc32_cpu_exec
 #define cpu_signal_handler              uc32_cpu_signal_handler
commit d48813dd7639885339e5e7a8cdf2d0e3ca714e1f
Author: Guan Xuetao <gxt at mprc.pku.edu.cn>
Date:   Fri Aug 10 14:42:23 2012 +0800

    unicore32-softmmu: Make UniCore32 cpuid & exceptions correct and runable
    
    This patch initializes the cpuid to exactly correct value because
    linux kernel will check it.
    In addition, the exception types are specified in proper situations.
    Then it could make exceptions generated correctly and timely.
    
    Signed-off-by: Guan Xuetao <gxt at mprc.pku.edu.cn>
    Signed-off-by: Blue Swirl <blauwirbel at gmail.com>

diff --git a/cpu-exec.c b/cpu-exec.c
index 4fee061..134b3c4 100644
--- a/cpu-exec.c
+++ b/cpu-exec.c
@@ -444,6 +444,7 @@ int cpu_exec(CPUArchState *env)
 #elif defined(TARGET_UNICORE32)
                     if (interrupt_request & CPU_INTERRUPT_HARD
                         && !(env->uncached_asr & ASR_I)) {
+                        env->exception_index = UC32_EXCP_INTR;
                         do_interrupt(env);
                         next_tb = 0;
                     }
diff --git a/linux-user/main.c b/linux-user/main.c
index 53714de..9d921aa 100644
--- a/linux-user/main.c
+++ b/linux-user/main.c
@@ -958,7 +958,8 @@ void cpu_loop(CPUUniCore32State *env)
                 }
             }
             break;
-        case UC32_EXCP_TRAP:
+        case UC32_EXCP_DTRAP:
+        case UC32_EXCP_ITRAP:
             info.si_signo = SIGSEGV;
             info.si_errno = 0;
             /* XXX: check env->error_code */
diff --git a/target-unicore32/cpu.c b/target-unicore32/cpu.c
index de63f58..3425bbe 100644
--- a/target-unicore32/cpu.c
+++ b/target-unicore32/cpu.c
@@ -1,7 +1,7 @@
 /*
  * QEMU UniCore32 CPU
  *
- * Copyright (c) 2010-2011 GUAN Xue-tao
+ * Copyright (c) 2010-2012 Guan Xuetao
  * Copyright (c) 2012 SUSE LINUX Products GmbH
  *
  * This program is free software; you can redistribute it and/or modify
@@ -32,13 +32,16 @@ static void unicore_ii_cpu_initfn(Object *obj)
     UniCore32CPU *cpu = UNICORE32_CPU(obj);
     CPUUniCore32State *env = &cpu->env;
 
-    env->cp0.c0_cpuid = 0x40010863;
+    env->cp0.c0_cpuid = 0x4d000863;
+    env->cp0.c0_cachetype = 0x0d152152;
+    env->cp0.c1_sys = 0x2000;
+    env->cp0.c2_base = 0x0;
+    env->cp0.c3_faultstatus = 0x0;
+    env->cp0.c4_faultaddr = 0x0;
+    env->ucf64.xregs[UC32_UCF64_FPSCR] = 0;
 
     set_feature(env, UC32_HWCAP_CMOV);
     set_feature(env, UC32_HWCAP_UCF64);
-    env->ucf64.xregs[UC32_UCF64_FPSCR] = 0;
-    env->cp0.c0_cachetype = 0x1dd20d2;
-    env->cp0.c1_sys = 0x00090078;
 }
 
 static void uc32_any_cpu_initfn(Object *obj)
@@ -47,6 +50,7 @@ static void uc32_any_cpu_initfn(Object *obj)
     CPUUniCore32State *env = &cpu->env;
 
     env->cp0.c0_cpuid = 0xffffffff;
+    env->ucf64.xregs[UC32_UCF64_FPSCR] = 0;
 
     set_feature(env, UC32_HWCAP_CMOV);
     set_feature(env, UC32_HWCAP_UCF64);
@@ -65,8 +69,13 @@ static void uc32_cpu_initfn(Object *obj)
     cpu_exec_init(env);
     env->cpu_model_str = object_get_typename(obj);
 
+#ifdef CONFIG_USER_ONLY
     env->uncached_asr = ASR_MODE_USER;
     env->regs[31] = 0;
+#else
+    env->uncached_asr = ASR_MODE_PRIV;
+    env->regs[31] = 0x03000000;
+#endif
 
     tlb_flush(env, 1);
 }
diff --git a/target-unicore32/cpu.h b/target-unicore32/cpu.h
index 81c14ff..d14fde5 100644
--- a/target-unicore32/cpu.h
+++ b/target-unicore32/cpu.h
@@ -1,15 +1,15 @@
 /*
  * UniCore32 virtual CPU header
  *
- * Copyright (C) 2010-2011 GUAN Xue-tao
+ * Copyright (C) 2010-2012 Guan Xuetao
  *
  * This program is free software; you can redistribute it and/or modify
  * it under the terms of the GNU General Public License version 2 as
  * published by the Free Software Foundation, or (at your option) any
  * later version. See the COPYING file in the top-level directory.
  */
-#ifndef __CPU_UC32_H__
-#define __CPU_UC32_H__
+#ifndef QEMU_UNICORE32_CPU_H
+#define QEMU_UNICORE32_CPU_H
 
 #define TARGET_LONG_BITS                32
 #define TARGET_PAGE_BITS                12
@@ -89,8 +89,10 @@ typedef struct CPUUniCore32State {
 #define ASR_NZCV                (ASR_N | ASR_Z | ASR_C | ASR_V)
 #define ASR_RESERVED            (~(ASR_M | ASR_I | ASR_NZCV))
 
-#define UC32_EXCP_PRIV          (ASR_MODE_PRIV)
-#define UC32_EXCP_TRAP          (ASR_MODE_TRAP)
+#define UC32_EXCP_PRIV          (1)
+#define UC32_EXCP_ITRAP         (2)
+#define UC32_EXCP_DTRAP         (3)
+#define UC32_EXCP_INTR          (4)
 
 /* Return the current ASR value.  */
 target_ulong cpu_asr_read(CPUUniCore32State *env1);
@@ -189,4 +191,4 @@ static inline bool cpu_has_work(CPUUniCore32State *env)
         (CPU_INTERRUPT_HARD | CPU_INTERRUPT_EXITTB);
 }
 
-#endif /* __CPU_UC32_H__ */
+#endif /* QEMU_UNICORE32_CPU_H */
commit 527d9979b401fea5588b202fab930d1565f13bb1
Author: Guan Xuetao <gxt at mprc.pku.edu.cn>
Date:   Fri Aug 10 14:42:22 2012 +0800

    unicore32-softmmu: Add coprocessor 0(sysctrl) and 1(ocd) instruction support
    
    Coprocessor 0 is system control coprocessor, and we need get/set its contents.
    Also, all cache/tlb ops shoule be implemented here, but just ignored with no harm.
    
    Coprocessor 1 is OCD (on-chip-debugger), which is used for faked console,
    so we could output chars to this console without graphic card.
    TODO: curses display should be added lator for screen output.
    
    Signed-off-by: Guan Xuetao <gxt at mprc.pku.edu.cn>
    Signed-off-by: Blue Swirl <blauwirbel at gmail.com>

diff --git a/target-unicore32/helper.c b/target-unicore32/helper.c
index 9b8ff06..f9f1960 100644
--- a/target-unicore32/helper.c
+++ b/target-unicore32/helper.c
@@ -14,6 +14,14 @@
 #include "helper.h"
 #include "host-utils.h"
 
+#undef DEBUG_UC32
+
+#ifdef DEBUG_UC32
+#define DPRINTF(fmt, ...) printf("%s: " fmt , __func__, ## __VA_ARGS__)
+#else
+#define DPRINTF(fmt, ...) do {} while (0)
+#endif
+
 CPUUniCore32State *uc32_cpu_init(const char *cpu_model)
 {
     UniCore32CPU *cpu;
@@ -45,6 +53,146 @@ uint32_t HELPER(clz)(uint32_t x)
     return clz32(x);
 }
 
+#ifndef CONFIG_USER_ONLY
+void helper_cp0_set(CPUUniCore32State *env, uint32_t val, uint32_t creg,
+        uint32_t cop)
+{
+    /*
+     * movc pp.nn, rn, #imm9
+     *      rn: UCOP_REG_D
+     *      nn: UCOP_REG_N
+     *          1: sys control reg.
+     *          2: page table base reg.
+     *          3: data fault status reg.
+     *          4: insn fault status reg.
+     *          5: cache op. reg.
+     *          6: tlb op. reg.
+     *      imm9: split UCOP_IMM10 with bit5 is 0
+     */
+    switch (creg) {
+    case 1:
+        if (cop != 0) {
+            goto unrecognized;
+        }
+        env->cp0.c1_sys = val;
+        break;
+    case 2:
+        if (cop != 0) {
+            goto unrecognized;
+        }
+        env->cp0.c2_base = val;
+        break;
+    case 3:
+        if (cop != 0) {
+            goto unrecognized;
+        }
+        env->cp0.c3_faultstatus = val;
+        break;
+    case 4:
+        if (cop != 0) {
+            goto unrecognized;
+        }
+        env->cp0.c4_faultaddr = val;
+        break;
+    case 5:
+        switch (cop) {
+        case 28:
+            DPRINTF("Invalidate Entire I&D cache\n");
+            return;
+        case 20:
+            DPRINTF("Invalidate Entire Icache\n");
+            return;
+        case 12:
+            DPRINTF("Invalidate Entire Dcache\n");
+            return;
+        case 10:
+            DPRINTF("Clean Entire Dcache\n");
+            return;
+        case 14:
+            DPRINTF("Flush Entire Dcache\n");
+            return;
+        case 13:
+            DPRINTF("Invalidate Dcache line\n");
+            return;
+        case 11:
+            DPRINTF("Clean Dcache line\n");
+            return;
+        case 15:
+            DPRINTF("Flush Dcache line\n");
+            return;
+        }
+        break;
+    case 6:
+        if ((cop <= 6) && (cop >= 2)) {
+            /* invalid all tlb */
+            tlb_flush(env, 1);
+            return;
+        }
+        break;
+    default:
+        goto unrecognized;
+    }
+    return;
+unrecognized:
+    DPRINTF("Wrong register (%d) or wrong operation (%d) in cp0_set!\n",
+            creg, cop);
+}
+
+uint32_t helper_cp0_get(CPUUniCore32State *env, uint32_t creg, uint32_t cop)
+{
+    /*
+     * movc rd, pp.nn, #imm9
+     *      rd: UCOP_REG_D
+     *      nn: UCOP_REG_N
+     *          0: cpuid and cachetype
+     *          1: sys control reg.
+     *          2: page table base reg.
+     *          3: data fault status reg.
+     *          4: insn fault status reg.
+     *      imm9: split UCOP_IMM10 with bit5 is 0
+     */
+    switch (creg) {
+    case 0:
+        switch (cop) {
+        case 0:
+            return env->cp0.c0_cpuid;
+        case 1:
+            return env->cp0.c0_cachetype;
+        }
+        break;
+    case 1:
+        if (cop == 0) {
+            return env->cp0.c1_sys;
+        }
+        break;
+    case 2:
+        if (cop == 0) {
+            return env->cp0.c2_base;
+        }
+        break;
+    case 3:
+        if (cop == 0) {
+            return env->cp0.c3_faultstatus;
+        }
+        break;
+    case 4:
+        if (cop == 0) {
+            return env->cp0.c4_faultaddr;
+        }
+        break;
+    }
+    DPRINTF("Wrong register (%d) or wrong operation (%d) in cp0_set!\n",
+            creg, cop);
+    return 0;
+}
+
+void helper_cp1_putc(target_ulong x)
+{
+    /* TODO: curses display should be added here for screen output. */
+    DPRINTF("%c", x);
+}
+#endif
+
 #ifdef CONFIG_USER_ONLY
 void switch_mode(CPUUniCore32State *env, int mode)
 {
@@ -66,43 +214,6 @@ int uc32_cpu_handle_mmu_fault(CPUUniCore32State *env, target_ulong address,
 }
 #endif
 
-/* These should probably raise undefined insn exceptions.  */
-void HELPER(set_cp)(CPUUniCore32State *env, uint32_t insn, uint32_t val)
-{
-    int op1 = (insn >> 8) & 0xf;
-    cpu_abort(env, "cp%i insn %08x\n", op1, insn);
-    return;
-}
-
-uint32_t HELPER(get_cp)(CPUUniCore32State *env, uint32_t insn)
-{
-    int op1 = (insn >> 8) & 0xf;
-    cpu_abort(env, "cp%i insn %08x\n", op1, insn);
-    return 0;
-}
-
-void HELPER(set_cp0)(CPUUniCore32State *env, uint32_t insn, uint32_t val)
-{
-    cpu_abort(env, "cp0 insn %08x\n", insn);
-}
-
-uint32_t HELPER(get_cp0)(CPUUniCore32State *env, uint32_t insn)
-{
-    cpu_abort(env, "cp0 insn %08x\n", insn);
-    return 0;
-}
-
-void HELPER(set_r29_banked)(CPUUniCore32State *env, uint32_t mode, uint32_t val)
-{
-    cpu_abort(env, "banked r29 write\n");
-}
-
-uint32_t HELPER(get_r29_banked)(CPUUniCore32State *env, uint32_t mode)
-{
-    cpu_abort(env, "banked r29 read\n");
-    return 0;
-}
-
 /* UniCore-F64 support.  We follow the convention used for F64 instrunctions:
    Single precition routines have a "s" suffix, double precision a
    "d" suffix.  */
diff --git a/target-unicore32/helper.h b/target-unicore32/helper.h
index 5a3b8a4..305318a 100644
--- a/target-unicore32/helper.h
+++ b/target-unicore32/helper.h
@@ -1,5 +1,5 @@
 /*
- * Copyright (C) 2010-2011 GUAN Xue-tao
+ * Copyright (C) 2010-2012 Guan Xuetao
  *
  * This program is free software; you can redistribute it and/or modify
  * it under the terms of the GNU General Public License version 2 as
@@ -8,6 +8,12 @@
  */
 #include "def-helper.h"
 
+#ifndef CONFIG_USER_ONLY
+DEF_HELPER_4(cp0_set, void, env, i32, i32, i32)
+DEF_HELPER_3(cp0_get, i32, env, i32, i32)
+DEF_HELPER_1(cp1_putc, void, i32)
+#endif
+
 DEF_HELPER_1(clz, i32, i32)
 DEF_HELPER_1(clo, i32, i32)
 
@@ -16,12 +22,6 @@ DEF_HELPER_1(exception, void, i32)
 DEF_HELPER_2(asr_write, void, i32, i32)
 DEF_HELPER_0(asr_read, i32)
 
-DEF_HELPER_3(set_cp0, void, env, i32, i32)
-DEF_HELPER_2(get_cp0, i32, env, i32)
-
-DEF_HELPER_3(set_cp, void, env, i32, i32)
-DEF_HELPER_2(get_cp, i32, env, i32)
-
 DEF_HELPER_1(get_user_reg, i32, i32)
 DEF_HELPER_2(set_user_reg, void, i32, i32)
 
@@ -38,9 +38,6 @@ DEF_HELPER_2(shr_cc, i32, i32, i32)
 DEF_HELPER_2(sar_cc, i32, i32, i32)
 DEF_HELPER_2(ror_cc, i32, i32, i32)
 
-DEF_HELPER_2(get_r29_banked, i32, env, i32)
-DEF_HELPER_3(set_r29_banked, void, env, i32, i32)
-
 DEF_HELPER_1(ucf64_get_fpscr, i32, env)
 DEF_HELPER_2(ucf64_set_fpscr, void, env, i32)
 
diff --git a/target-unicore32/translate.c b/target-unicore32/translate.c
index 9793d14..e37d5be 100644
--- a/target-unicore32/translate.c
+++ b/target-unicore32/translate.c
@@ -1,7 +1,7 @@
 /*
  *  UniCore32 translation
  *
- * Copyright (C) 2010-2011 GUAN Xue-tao
+ * Copyright (C) 2010-2012 Guan Xuetao
  *
  * This program is free software; you can redistribute it and/or modify
  * it under the terms of the GNU General Public License version 2 as
@@ -176,6 +176,73 @@ static void store_reg(DisasContext *s, int reg, TCGv var)
                         "Illegal UniCore32 instruction %x at line %d!", \
                         insn, __LINE__)
 
+#ifndef CONFIG_USER_ONLY
+static void disas_cp0_insn(CPUUniCore32State *env, DisasContext *s,
+        uint32_t insn)
+{
+    TCGv tmp, tmp2, tmp3;
+    if ((insn & 0xfe000000) == 0xe0000000) {
+        tmp2 = new_tmp();
+        tmp3 = new_tmp();
+        tcg_gen_movi_i32(tmp2, UCOP_REG_N);
+        tcg_gen_movi_i32(tmp3, UCOP_IMM10);
+        if (UCOP_SET_L) {
+            tmp = new_tmp();
+            gen_helper_cp0_get(tmp, cpu_env, tmp2, tmp3);
+            store_reg(s, UCOP_REG_D, tmp);
+        } else {
+            tmp = load_reg(s, UCOP_REG_D);
+            gen_helper_cp0_set(cpu_env, tmp, tmp2, tmp3);
+            dead_tmp(tmp);
+        }
+        dead_tmp(tmp2);
+        dead_tmp(tmp3);
+        return;
+    }
+    ILLEGAL;
+}
+
+static void disas_ocd_insn(CPUUniCore32State *env, DisasContext *s,
+        uint32_t insn)
+{
+    TCGv tmp;
+
+    if ((insn & 0xff003fff) == 0xe1000400) {
+        /*
+         * movc rd, pp.nn, #imm9
+         *      rd: UCOP_REG_D
+         *      nn: UCOP_REG_N (must be 0)
+         *      imm9: 0
+         */
+        if (UCOP_REG_N == 0) {
+            tmp = new_tmp();
+            tcg_gen_movi_i32(tmp, 0);
+            store_reg(s, UCOP_REG_D, tmp);
+            return;
+        } else {
+            ILLEGAL;
+        }
+    }
+    if ((insn & 0xff003fff) == 0xe0000401) {
+        /*
+         * movc pp.nn, rn, #imm9
+         *      rn: UCOP_REG_D
+         *      nn: UCOP_REG_N (must be 1)
+         *      imm9: 1
+         */
+        if (UCOP_REG_N == 1) {
+            tmp = load_reg(s, UCOP_REG_D);
+            gen_helper_cp1_putc(tmp);
+            dead_tmp(tmp);
+            return;
+        } else {
+            ILLEGAL;
+        }
+    }
+    ILLEGAL;
+}
+#endif
+
 static inline void gen_set_asr(TCGv var, uint32_t mask)
 {
     TCGv tmp_mask = tcg_const_i32(mask);
@@ -1124,9 +1191,18 @@ static void gen_exception_return(DisasContext *s, TCGv pc)
     s->is_jmp = DISAS_UPDATE;
 }
 
-static void disas_coproc_insn(CPUUniCore32State *env, DisasContext *s, uint32_t insn)
+static void disas_coproc_insn(CPUUniCore32State *env, DisasContext *s,
+        uint32_t insn)
 {
     switch (UCOP_CPNUM) {
+#ifndef CONFIG_USER_ONLY
+    case 0:
+        disas_cp0_insn(env, s, insn);
+        break;
+    case 1:
+        disas_ocd_insn(env, s, insn);
+        break;
+#endif
     case 2:
         disas_ucf64_insn(env, s, insn);
         break;
commit 4f23a1e645d4bfba620a63ba2c54c1813bcbfb63
Author: Guan Xuetao <gxt at mprc.pku.edu.cn>
Date:   Fri Aug 10 14:42:21 2012 +0800

    unicore32-softmmu: Add unicore32-softmmu build support
    
    This patch adds unicore32-softmmu build support, include configure,
    makefile, arch_init, and all missing functions needed by softmmu.
    Although all missing functions are empty, unicore32-softmmu could
    be build successfully.
    By 20120804: change QEMU_ARCH_UNICORE32 to 0x4000
    
    Signed-off-by: Guan Xuetao <gxt at mprc.pku.edu.cn>
    Signed-off-by: Blue Swirl <blauwirbel at gmail.com>

diff --git a/arch_init.c b/arch_init.c
index 60823ba..7b65c48 100644
--- a/arch_init.c
+++ b/arch_init.c
@@ -91,6 +91,8 @@ int graphic_depth = 15;
 #define QEMU_ARCH QEMU_ARCH_SPARC
 #elif defined(TARGET_XTENSA)
 #define QEMU_ARCH QEMU_ARCH_XTENSA
+#elif defined(TARGET_UNICORE32)
+#define QEMU_ARCH QEMU_ARCH_UNICORE32
 #endif
 
 const uint32_t arch_type = QEMU_ARCH;
diff --git a/arch_init.h b/arch_init.h
index 3dfea3b..547f93c 100644
--- a/arch_init.h
+++ b/arch_init.h
@@ -17,6 +17,7 @@ enum {
     QEMU_ARCH_SPARC = 2048,
     QEMU_ARCH_XTENSA = 4096,
     QEMU_ARCH_OPENRISC = 8192,
+    QEMU_ARCH_UNICORE32 = 0x4000,
 };
 
 extern const uint32_t arch_type;
diff --git a/configure b/configure
index 280726c..efaff00 100755
--- a/configure
+++ b/configure
@@ -935,6 +935,7 @@ sparc64-softmmu \
 s390x-softmmu \
 xtensa-softmmu \
 xtensaeb-softmmu \
+unicore32-softmmu \
 "
 fi
 # the following are Linux specific
diff --git a/default-configs/unicore32-softmmu.mak b/default-configs/unicore32-softmmu.mak
new file mode 100644
index 0000000..5f04fe3
--- /dev/null
+++ b/default-configs/unicore32-softmmu.mak
@@ -0,0 +1 @@
+# Default configuration for unicore32-softmmu
diff --git a/hw/unicore32/Makefile.objs b/hw/unicore32/Makefile.objs
new file mode 100644
index 0000000..b6a3383
--- /dev/null
+++ b/hw/unicore32/Makefile.objs
@@ -0,0 +1 @@
+# For UniCore32 machines and boards
diff --git a/target-unicore32/Makefile.objs b/target-unicore32/Makefile.objs
index 2e0e093..6af1089 100644
--- a/target-unicore32/Makefile.objs
+++ b/target-unicore32/Makefile.objs
@@ -1,4 +1,4 @@
 obj-y += translate.o op_helper.o helper.o cpu.o
-obj-$(CONFIG_SOFTMMU) += machine.o
+obj-$(CONFIG_SOFTMMU) += machine.o softmmu.o
 
 $(obj)/op_helper.o: QEMU_CFLAGS += $(HELPER_CFLAGS)
diff --git a/target-unicore32/helper.c b/target-unicore32/helper.c
index 9fe4a37..9b8ff06 100644
--- a/target-unicore32/helper.c
+++ b/target-unicore32/helper.c
@@ -1,5 +1,5 @@
 /*
- * Copyright (C) 2010-2011 GUAN Xue-tao
+ * Copyright (C) 2010-2012 Guan Xuetao
  *
  * This program is free software; you can redistribute it and/or modify
  * it under the terms of the GNU General Public License version 2 as
@@ -45,18 +45,26 @@ uint32_t HELPER(clz)(uint32_t x)
     return clz32(x);
 }
 
+#ifdef CONFIG_USER_ONLY
+void switch_mode(CPUUniCore32State *env, int mode)
+{
+    if (mode != ASR_MODE_USER) {
+        cpu_abort(env, "Tried to switch out of user mode\n");
+    }
+}
+
 void do_interrupt(CPUUniCore32State *env)
 {
-    env->exception_index = -1;
+    cpu_abort(env, "NO interrupt in user mode\n");
 }
 
-int uc32_cpu_handle_mmu_fault(CPUUniCore32State *env, target_ulong address, int rw,
-                              int mmu_idx)
+int uc32_cpu_handle_mmu_fault(CPUUniCore32State *env, target_ulong address,
+                              int access_type, int mmu_idx)
 {
-    env->exception_index = UC32_EXCP_TRAP;
-    env->cp0.c4_faultaddr = address;
+    cpu_abort(env, "NO mmu fault in user mode\n");
     return 1;
 }
+#endif
 
 /* These should probably raise undefined insn exceptions.  */
 void HELPER(set_cp)(CPUUniCore32State *env, uint32_t insn, uint32_t val)
@@ -84,13 +92,6 @@ uint32_t HELPER(get_cp0)(CPUUniCore32State *env, uint32_t insn)
     return 0;
 }
 
-void switch_mode(CPUUniCore32State *env, int mode)
-{
-    if (mode != ASR_MODE_USER) {
-        cpu_abort(env, "Tried to switch out of user mode\n");
-    }
-}
-
 void HELPER(set_r29_banked)(CPUUniCore32State *env, uint32_t mode, uint32_t val)
 {
     cpu_abort(env, "banked r29 write\n");
diff --git a/target-unicore32/machine.c b/target-unicore32/machine.c
new file mode 100644
index 0000000..60b2ec1
--- /dev/null
+++ b/target-unicore32/machine.c
@@ -0,0 +1,23 @@
+/*
+ * Generic machine functions for UniCore32 ISA
+ *
+ * Copyright (C) 2010-2012 Guan Xuetao
+ *
+ * This program is free software; you can redistribute it and/or modify
+ * it under the terms of the GNU General Public License version 2 as
+ * published by the Free Software Foundation, or any later version.
+ * See the COPYING file in the top-level directory.
+ */
+#include "hw/hw.h"
+
+void cpu_save(QEMUFile *f, void *opaque)
+{
+    hw_error("%s not supported yet.\n", __func__);
+}
+
+int cpu_load(QEMUFile *f, void *opaque, int version_id)
+{
+    hw_error("%s not supported yet.\n", __func__);
+
+    return 0;
+}
diff --git a/target-unicore32/op_helper.c b/target-unicore32/op_helper.c
index b954c30..6df30db 100644
--- a/target-unicore32/op_helper.c
+++ b/target-unicore32/op_helper.c
@@ -1,7 +1,7 @@
 /*
  *  UniCore32 helper routines
  *
- * Copyright (C) 2010-2011 GUAN Xue-tao
+ * Copyright (C) 2010-2012 Guan Xuetao
  *
  * This program is free software; you can redistribute it and/or modify
  * it under the terms of the GNU General Public License version 2 as
@@ -248,3 +248,25 @@ uint32_t HELPER(ror_cc)(uint32_t x, uint32_t i)
         return ((uint32_t)x >> shift) | (x << (32 - shift));
     }
 }
+
+#ifndef CONFIG_USER_ONLY
+#define MMUSUFFIX _mmu
+
+#define SHIFT 0
+#include "softmmu_template.h"
+
+#define SHIFT 1
+#include "softmmu_template.h"
+
+#define SHIFT 2
+#include "softmmu_template.h"
+
+#define SHIFT 3
+#include "softmmu_template.h"
+
+void tlb_fill(CPUUniCore32State *env1, target_ulong addr, int is_write,
+        int mmu_idx, uintptr_t retaddr)
+{
+    cpu_abort(env, "%s not supported yet\n", __func__);
+}
+#endif
diff --git a/target-unicore32/softmmu.c b/target-unicore32/softmmu.c
new file mode 100644
index 0000000..6fec77e
--- /dev/null
+++ b/target-unicore32/softmmu.c
@@ -0,0 +1,39 @@
+/*
+ * Softmmu related functions
+ *
+ * Copyright (C) 2010-2012 Guan Xuetao
+ *
+ * This program is free software; you can redistribute it and/or modify
+ * it under the terms of the GNU General Public License version 2 as
+ * published by the Free Software Foundation, or any later version.
+ * See the COPYING file in the top-level directory.
+ */
+#ifdef CONFIG_USER_ONLY
+#error This file only exist under softmmu circumstance
+#endif
+
+#include <cpu.h>
+
+void switch_mode(CPUUniCore32State *env, int mode)
+{
+    cpu_abort(env, "%s not supported yet\n", __func__);
+}
+
+void do_interrupt(CPUUniCore32State *env)
+{
+    cpu_abort(env, "%s not supported yet\n", __func__);
+}
+
+int uc32_cpu_handle_mmu_fault(CPUUniCore32State *env, target_ulong address,
+                              int access_type, int mmu_idx)
+{
+    cpu_abort(env, "%s not supported yet\n", __func__);
+    return 1;
+}
+
+target_phys_addr_t cpu_get_phys_page_debug(CPUUniCore32State *env,
+        target_ulong addr)
+{
+    cpu_abort(env, "%s not supported yet\n", __func__);
+    return addr;
+}
commit b90372ad2a69a9cdad2a40766eb46f0a89d98535
Author: Peter Maydell <peter.maydell at linaro.org>
Date:   Mon Aug 6 17:42:18 2012 +0100

    target-arm: Fix typos in comments
    
    Fix a variety of typos in comments in target-arm files.
    
    Signed-off-by: Peter Maydell <peter.maydell at linaro.org>
    Reviewed-by: Peter Crosthwaite <peter.crosthwaite at petalogix.com>
    Signed-off-by: Stefan Hajnoczi <stefanha at linux.vnet.ibm.com>

diff --git a/target-arm/arm-semi.c b/target-arm/arm-semi.c
index 88ca9bb..2495206 100644
--- a/target-arm/arm-semi.c
+++ b/target-arm/arm-semi.c
@@ -281,7 +281,7 @@ uint32_t do_arm_semihosting(CPUARMState *env)
             return len - ret;
         }
     case TARGET_SYS_READC:
-       /* XXX: Read from debug cosole. Not implemented.  */
+       /* XXX: Read from debug console. Not implemented.  */
         return 0;
     case TARGET_SYS_ISTTY:
         if (use_gdb_syscalls()) {
diff --git a/target-arm/cpu.h b/target-arm/cpu.h
index 191895c..d7f93d9 100644
--- a/target-arm/cpu.h
+++ b/target-arm/cpu.h
@@ -79,7 +79,7 @@ struct arm_boot_info;
 typedef struct CPUARMState {
     /* Regs for current mode.  */
     uint32_t regs[16];
-    /* Frequently accessed CPSR bits are stored separately for efficiently.
+    /* Frequently accessed CPSR bits are stored separately for efficiency.
        This contains all the other bits.  Use cpsr_{read,write} to access
        the whole CPSR.  */
     uint32_t uncached_cpsr;
diff --git a/target-arm/helper.c b/target-arm/helper.c
index 5727da2..dceaa95 100644
--- a/target-arm/helper.c
+++ b/target-arm/helper.c
@@ -988,7 +988,7 @@ static void ttbr164_reset(CPUARMState *env, const ARMCPRegInfo *ri)
 }
 
 static const ARMCPRegInfo lpae_cp_reginfo[] = {
-    /* NOP AMAIR0/1: the override is because these clash with tha rather
+    /* NOP AMAIR0/1: the override is because these clash with the rather
      * broadly specified TLB_LOCKDOWN entry in the generic cp_reginfo.
      */
     { .name = "AMAIR0", .cp = 15, .crn = 10, .crm = 3, .opc1 = 0, .opc2 = 0,
@@ -2899,8 +2899,8 @@ uint32_t HELPER(logicq_cc)(uint64_t val)
     return (val >> 32) | (val != 0);
 }
 
-/* VFP support.  We follow the convention used for VFP instrunctions:
-   Single precition routines have a "s" suffix, double precision a
+/* VFP support.  We follow the convention used for VFP instructions:
+   Single precision routines have a "s" suffix, double precision a
    "d" suffix.  */
 
 /* Convert host exception flags to vfp form.  */
diff --git a/target-arm/neon_helper.c b/target-arm/neon_helper.c
index e0b9dbf..8bb5129 100644
--- a/target-arm/neon_helper.c
+++ b/target-arm/neon_helper.c
@@ -530,7 +530,7 @@ NEON_VOP(rshl_s16, neon_s16, 2)
 #undef NEON_FN
 
 /* The addition of the rounding constant may overflow, so we use an
- * intermediate 64 bits accumulator.  */
+ * intermediate 64 bit accumulator.  */
 uint32_t HELPER(neon_rshl_s32)(uint32_t valop, uint32_t shiftop)
 {
     int32_t dest;
@@ -547,8 +547,8 @@ uint32_t HELPER(neon_rshl_s32)(uint32_t valop, uint32_t shiftop)
     return dest;
 }
 
-/* Handling addition overflow with 64 bits inputs values is more
- * tricky than with 32 bits values.  */
+/* Handling addition overflow with 64 bit input values is more
+ * tricky than with 32 bit values.  */
 uint64_t HELPER(neon_rshl_s64)(uint64_t valop, uint64_t shiftop)
 {
     int8_t shift = (int8_t)shiftop;
@@ -590,7 +590,7 @@ NEON_VOP(rshl_u16, neon_u16, 2)
 #undef NEON_FN
 
 /* The addition of the rounding constant may overflow, so we use an
- * intermediate 64 bits accumulator.  */
+ * intermediate 64 bit accumulator.  */
 uint32_t HELPER(neon_rshl_u32)(uint32_t val, uint32_t shiftop)
 {
     uint32_t dest;
@@ -608,8 +608,8 @@ uint32_t HELPER(neon_rshl_u32)(uint32_t val, uint32_t shiftop)
     return dest;
 }
 
-/* Handling addition overflow with 64 bits inputs values is more
- * tricky than with 32 bits values.  */
+/* Handling addition overflow with 64 bit input values is more
+ * tricky than with 32 bit values.  */
 uint64_t HELPER(neon_rshl_u64)(uint64_t val, uint64_t shiftop)
 {
     int8_t shift = (uint8_t)shiftop;
@@ -817,7 +817,7 @@ NEON_VOP_ENV(qrshl_u16, neon_u16, 2)
 #undef NEON_FN
 
 /* The addition of the rounding constant may overflow, so we use an
- * intermediate 64 bits accumulator.  */
+ * intermediate 64 bit accumulator.  */
 uint32_t HELPER(neon_qrshl_u32)(CPUARMState *env, uint32_t val, uint32_t shiftop)
 {
     uint32_t dest;
@@ -846,8 +846,8 @@ uint32_t HELPER(neon_qrshl_u32)(CPUARMState *env, uint32_t val, uint32_t shiftop
     return dest;
 }
 
-/* Handling addition overflow with 64 bits inputs values is more
- * tricky than with 32 bits values.  */
+/* Handling addition overflow with 64 bit input values is more
+ * tricky than with 32 bit values.  */
 uint64_t HELPER(neon_qrshl_u64)(CPUARMState *env, uint64_t val, uint64_t shiftop)
 {
     int8_t shift = (int8_t)shiftop;
@@ -914,7 +914,7 @@ NEON_VOP_ENV(qrshl_s16, neon_s16, 2)
 #undef NEON_FN
 
 /* The addition of the rounding constant may overflow, so we use an
- * intermediate 64 bits accumulator.  */
+ * intermediate 64 bit accumulator.  */
 uint32_t HELPER(neon_qrshl_s32)(CPUARMState *env, uint32_t valop, uint32_t shiftop)
 {
     int32_t dest;
@@ -942,8 +942,8 @@ uint32_t HELPER(neon_qrshl_s32)(CPUARMState *env, uint32_t valop, uint32_t shift
     return dest;
 }
 
-/* Handling addition overflow with 64 bits inputs values is more
- * tricky than with 32 bits values.  */
+/* Handling addition overflow with 64 bit input values is more
+ * tricky than with 32 bit values.  */
 uint64_t HELPER(neon_qrshl_s64)(CPUARMState *env, uint64_t valop, uint64_t shiftop)
 {
     int8_t shift = (uint8_t)shiftop;
@@ -1671,7 +1671,7 @@ uint64_t HELPER(neon_negl_u64)(uint64_t x)
     return -x;
 }
 
-/* Saturnating sign manuipulation.  */
+/* Saturating sign manipulation.  */
 /* ??? Make these use NEON_VOP1 */
 #define DO_QABS8(x) do { \
     if (x == (int8_t)0x80) { \
diff --git a/target-arm/op_helper.c b/target-arm/op_helper.c
index 490111c..d77bfab 100644
--- a/target-arm/op_helper.c
+++ b/target-arm/op_helper.c
@@ -99,7 +99,7 @@ void tlb_fill(CPUARMState *env1, target_ulong addr, int is_write, int mmu_idx,
 }
 #endif
 
-/* FIXME: Pass an axplicit pointer to QF to CPUARMState, and move saturating
+/* FIXME: Pass an explicit pointer to QF to CPUARMState, and move saturating
    instructions into helper.c  */
 uint32_t HELPER(add_setq)(uint32_t a, uint32_t b)
 {
diff --git a/target-arm/translate.c b/target-arm/translate.c
index 494c682..edef79a 100644
--- a/target-arm/translate.c
+++ b/target-arm/translate.c
@@ -53,7 +53,7 @@ typedef struct DisasContext {
     int condjmp;
     /* The label that will be jumped to when the instruction is skipped.  */
     int condlabel;
-    /* Thumb-2 condtional execution bits.  */
+    /* Thumb-2 conditional execution bits.  */
     int condexec_mask;
     int condexec_cond;
     struct TranslationBlock *tb;
@@ -77,7 +77,7 @@ static uint32_t gen_opc_condexec_bits[OPC_BUF_SIZE];
 #endif
 
 /* These instructions trap after executing, so defer them until after the
-   conditional executions state has been updated.  */
+   conditional execution state has been updated.  */
 #define DISAS_WFI 4
 #define DISAS_SWI 5
 
@@ -155,7 +155,7 @@ static void load_reg_var(DisasContext *s, TCGv var, int reg)
 {
     if (reg == 15) {
         uint32_t addr;
-        /* normaly, since we updated PC, we need only to add one insn */
+        /* normally, since we updated PC, we need only to add one insn */
         if (s->thumb)
             addr = (long)s->pc + 2;
         else
@@ -4897,7 +4897,7 @@ static int disas_neon_data_insn(CPUARMState * env, DisasContext *s, uint32_t ins
                     size--;
             }
             shift = (insn >> 16) & ((1 << (3 + size)) - 1);
-            /* To avoid excessive dumplication of ops we implement shift
+            /* To avoid excessive duplication of ops we implement shift
                by immediate using the variable shift operations.  */
             if (op < 8) {
                 /* Shift by immediate:
@@ -6402,7 +6402,7 @@ static void gen_logicq_cc(TCGv_i64 val)
 
 /* Load/Store exclusive instructions are implemented by remembering
    the value/address loaded, and seeing if these are the same
-   when the store is performed. This should be is sufficient to implement
+   when the store is performed. This should be sufficient to implement
    the architecturally mandated semantics, and avoids having to monitor
    regular stores.
 
commit 656267413c17db3344c443fcf2b954a456a6863e
Author: Peter A. G. Crosthwaite <peter.crosthwaite at petalogix.com>
Date:   Mon Aug 6 17:05:56 2012 +1000

    arm: translate: comment typo - s/middel/middle/
    
    Signed-off-by: Peter A. G. Crosthwaite <peter.crosthwaite at petalogix.com>
    Reviewed-by: Andreas Färber <afaerber at suse.de>
    Reviewed-by: Peter Maydell <peter.maydell at linaro.org>
    Signed-off-by: Stefan Hajnoczi <stefanha at linux.vnet.ibm.com>

diff --git a/target-arm/translate.c b/target-arm/translate.c
index 29008a4..494c682 100644
--- a/target-arm/translate.c
+++ b/target-arm/translate.c
@@ -9892,7 +9892,7 @@ static inline void gen_intermediate_code_internal(CPUARMState *env,
     } else {
         /* While branches must always occur at the end of an IT block,
            there are a few other things that can cause us to terminate
-           the TB in the middel of an IT block:
+           the TB in the middle of an IT block:
             - Exception generating instructions (bkpt, swi, undefined).
             - Page boundaries.
             - Hardware watchpoints.
commit fb7c269ed694c103397c5fffbfcccd3e90aed23c
Author: Dunrong Huang <riegamaths at gmail.com>
Date:   Tue Jul 24 00:42:20 2012 +0800

    vl.c: Exit QEMU early if no machine is found
    
    We check whether the variable machine is NULL or not before accessing
    it. If machine is NULL, exit QEMU with an error, this can avoids a
    segfault error.
    
    Markus Armbruster <armbru at redhat.com> adds that the segfault can be
    reproduced as follows:
    
      $ qemu-system-xtensa -cpu help
    
    Signed-off-by: Dunrong Huang <riegamaths at gmail.com>
    Reviewed-by: Markus Armbruster <armbru at redhat.com>
    Signed-off-by: Stefan Hajnoczi <stefanha at linux.vnet.ibm.com>

diff --git a/vl.c b/vl.c
index a4a520f..4871428 100644
--- a/vl.c
+++ b/vl.c
@@ -3204,6 +3204,11 @@ int main(int argc, char **argv, char **envp)
     }
     loc_set_none();
 
+    if (machine == NULL) {
+        fprintf(stderr, "No machine found.\n");
+        exit(1);
+    }
+
     if (machine->hw_version) {
         qemu_set_version(machine->hw_version);
     }
@@ -3246,11 +3251,6 @@ int main(int argc, char **argv, char **envp)
         data_dir = CONFIG_QEMU_DATADIR;
     }
 
-    if (machine == NULL) {
-        fprintf(stderr, "No machine found.\n");
-        exit(1);
-    }
-
     /*
      * Default to max_cpus = smp_cpus, in case the user doesn't
      * specify a max_cpus value.
commit 166f3c7b7026f9cd55a7daeec3b3444ec41092ab
Author: Stefan Hajnoczi <stefanha at linux.vnet.ibm.com>
Date:   Thu Aug 9 13:05:57 2012 +0100

    qemu-iotests: skip 039 with ./check -nocache
    
    When the qemu-io --nocache option is used the 039 test case cannot abort
    QEMU at a point where the image is dirty.  Skip the test case.
    
    Signed-off-by: Stefan Hajnoczi <stefanha at linux.vnet.ibm.com>
    Signed-off-by: Kevin Wolf <kwolf at redhat.com>

diff --git a/tests/qemu-iotests/039 b/tests/qemu-iotests/039
index a749fcf..c5ae806 100755
--- a/tests/qemu-iotests/039
+++ b/tests/qemu-iotests/039
@@ -44,6 +44,7 @@ trap "_cleanup; exit \$status" 0 1 2 3 15
 _supported_fmt qcow2
 _supported_proto generic
 _supported_os Linux
+_unsupported_qemu_io_options --nocache
 
 size=128M
 
diff --git a/tests/qemu-iotests/common.rc b/tests/qemu-iotests/common.rc
index 6b80516..d534e94 100644
--- a/tests/qemu-iotests/common.rc
+++ b/tests/qemu-iotests/common.rc
@@ -297,6 +297,20 @@ _supported_os()
     _notrun "not suitable for this OS: $HOSTOS"
 }
 
+_unsupported_qemu_io_options()
+{
+    for bad_opt
+    do
+        for opt in $QEMU_IO_OPTIONS
+        do
+            if [ "$bad_opt" = "$opt" ]
+            then
+                _notrun "not suitable for qemu-io option: $bad_opt"
+            fi
+        done
+    done
+}
+
 # this test requires that a specified command (executable) exists
 #
 _require_command()
commit 058f8f16db0c1c528b665a6283457f019c8b0926
Author: Stefan Hajnoczi <stefanha at linux.vnet.ibm.com>
Date:   Thu Aug 9 13:05:56 2012 +0100

    block: add BLOCK_O_CHECK for qemu-img check
    
    Image formats with a dirty bit, like qed and qcow2, repair dirty image
    files upon open with BDRV_O_RDWR.  Performing automatic repair when
    qemu-img check runs is not ideal because the bdrv_open() call repairs
    the image before the actual bdrv_check() call from qemu-img.c.
    
    Fix this "double repair" since it leads to confusing output from
    qemu-img check.  Tell the block driver that this image is being opened
    just for bdrv_check().  This skips automatic repair and qemu-img.c can
    invoke it manually with bdrv_check().
    
    Update the golden output for qemu-iotests 039 to reflect the new
    qemu-img check output.
    
    Signed-off-by: Stefan Hajnoczi <stefanha at linux.vnet.ibm.com>
    Signed-off-by: Kevin Wolf <kwolf at redhat.com>

diff --git a/block.h b/block.h
index 650d872..2e2be11 100644
--- a/block.h
+++ b/block.h
@@ -79,6 +79,7 @@ typedef struct BlockDevOps {
 #define BDRV_O_NO_FLUSH    0x0200 /* disable flushing on this disk */
 #define BDRV_O_COPY_ON_READ 0x0400 /* copy read backing sectors into image */
 #define BDRV_O_INCOMING    0x0800  /* consistency hint for incoming migration */
+#define BDRV_O_CHECK       0x1000  /* open solely for consistency check */
 
 #define BDRV_O_CACHE_MASK  (BDRV_O_NOCACHE | BDRV_O_CACHE_WB | BDRV_O_NO_FLUSH)
 
diff --git a/block/qcow2.c b/block/qcow2.c
index 5896fd6..8f183f1 100644
--- a/block/qcow2.c
+++ b/block/qcow2.c
@@ -484,8 +484,8 @@ static int qcow2_open(BlockDriverState *bs, int flags)
     qemu_co_mutex_init(&s->lock);
 
     /* Repair image if dirty */
-    if ((s->incompatible_features & QCOW2_INCOMPAT_DIRTY) &&
-        !bs->read_only) {
+    if (!(flags & BDRV_O_CHECK) && !bs->read_only &&
+        (s->incompatible_features & QCOW2_INCOMPAT_DIRTY)) {
         BdrvCheckResult result = {0};
 
         ret = qcow2_check(bs, &result, BDRV_FIX_ERRORS);
diff --git a/block/qed.c b/block/qed.c
index 226545d..a02dbfd 100644
--- a/block/qed.c
+++ b/block/qed.c
@@ -477,7 +477,7 @@ static int bdrv_qed_open(BlockDriverState *bs, int flags)
     }
 
     /* If image was not closed cleanly, check consistency */
-    if (s->header.features & QED_F_NEED_CHECK) {
+    if (!(flags & BDRV_O_CHECK) && (s->header.features & QED_F_NEED_CHECK)) {
         /* Read-only images cannot be fixed.  There is no risk of corruption
          * since write operations are not possible.  Therefore, allow
          * potentially inconsistent images to be opened read-only.  This can
diff --git a/qemu-img.c b/qemu-img.c
index 94a31ad..b41e670 100644
--- a/qemu-img.c
+++ b/qemu-img.c
@@ -379,7 +379,7 @@ static int img_check(int argc, char **argv)
     BlockDriverState *bs;
     BdrvCheckResult result;
     int fix = 0;
-    int flags = BDRV_O_FLAGS;
+    int flags = BDRV_O_FLAGS | BDRV_O_CHECK;
 
     fmt = NULL;
     for(;;) {
diff --git a/tests/qemu-iotests/039.out b/tests/qemu-iotests/039.out
index 155a05e..cb510d6 100644
--- a/tests/qemu-iotests/039.out
+++ b/tests/qemu-iotests/039.out
@@ -26,6 +26,12 @@ incompatible_features     0x1
 == Repairing the image file must succeed ==
 ERROR OFLAG_COPIED: offset=8000000000050000 refcount=0
 Repairing cluster 5 refcount=0 reference=1
+The following inconsistencies were found and repaired:
+
+    0 leaked clusters
+    1 corruptions
+
+Double checking the fixed image now...
 No errors were found on the image.
 incompatible_features     0x0
 
commit acbe59829e448aa63bdccc6ee484b7e1ac605e25
Author: Stefan Hajnoczi <stefanha at linux.vnet.ibm.com>
Date:   Thu Aug 9 13:05:55 2012 +0100

    qcow2: mark image clean after repair succeeds
    
    The dirty bit is cleared after image repair succeeds in qcow2_open().
    Move this into qcow2_check() so that all callers benefit from this
    behavior when fix mode is enabled.
    
    This is necessary so qemu-img check can call .bdrv_check() and mark the
    image clean.
    
    Signed-off-by: Stefan Hajnoczi <stefanha at linux.vnet.ibm.com>
    Signed-off-by: Kevin Wolf <kwolf at redhat.com>

diff --git a/block/qcow2.c b/block/qcow2.c
index fd5e214..5896fd6 100644
--- a/block/qcow2.c
+++ b/block/qcow2.c
@@ -270,6 +270,20 @@ static int qcow2_mark_clean(BlockDriverState *bs)
     return 0;
 }
 
+static int qcow2_check(BlockDriverState *bs, BdrvCheckResult *result,
+                       BdrvCheckMode fix)
+{
+    int ret = qcow2_check_refcounts(bs, result, fix);
+    if (ret < 0) {
+        return ret;
+    }
+
+    if (fix && result->check_errors == 0 && result->corruptions == 0) {
+        return qcow2_mark_clean(bs);
+    }
+    return ret;
+}
+
 static int qcow2_open(BlockDriverState *bs, int flags)
 {
     BDRVQcowState *s = bs->opaque;
@@ -474,12 +488,7 @@ static int qcow2_open(BlockDriverState *bs, int flags)
         !bs->read_only) {
         BdrvCheckResult result = {0};
 
-        ret = qcow2_check_refcounts(bs, &result, BDRV_FIX_ERRORS);
-        if (ret < 0) {
-            goto fail;
-        }
-
-        ret = qcow2_mark_clean(bs);
+        ret = qcow2_check(bs, &result, BDRV_FIX_ERRORS);
         if (ret < 0) {
             goto fail;
         }
@@ -1568,13 +1577,6 @@ static int qcow2_get_info(BlockDriverState *bs, BlockDriverInfo *bdi)
     return 0;
 }
 
-
-static int qcow2_check(BlockDriverState *bs, BdrvCheckResult *result,
-                       BdrvCheckMode fix)
-{
-    return qcow2_check_refcounts(bs, result, fix);
-}
-
 #if 0
 static void dump_refcounts(BlockDriverState *bs)
 {
commit b10170aca0616df85482dcc7ddda03437bc07cca
Author: Stefan Hajnoczi <stefanha at linux.vnet.ibm.com>
Date:   Thu Aug 9 13:05:54 2012 +0100

    qed: mark image clean after repair succeeds
    
    The dirty bit is cleared after image repair succeeds in qed_open().
    Move this into qed_check() so that all callers benefit from this
    behavior when fix=true.
    
    This is necessary so qemu-img check can call .bdrv_check() and mark the
    image clean.
    
    Signed-off-by: Stefan Hajnoczi <stefanha at linux.vnet.ibm.com>
    Signed-off-by: Kevin Wolf <kwolf at redhat.com>

diff --git a/block/qed-check.c b/block/qed-check.c
index 5edf607..b473dcd 100644
--- a/block/qed-check.c
+++ b/block/qed-check.c
@@ -194,6 +194,28 @@ static void qed_check_for_leaks(QEDCheck *check)
     }
 }
 
+/**
+ * Mark an image clean once it passes check or has been repaired
+ */
+static void qed_check_mark_clean(BDRVQEDState *s, BdrvCheckResult *result)
+{
+    /* Skip if there were unfixable corruptions or I/O errors */
+    if (result->corruptions > 0 || result->check_errors > 0) {
+        return;
+    }
+
+    /* Skip if image is already marked clean */
+    if (!(s->header.features & QED_F_NEED_CHECK)) {
+        return;
+    }
+
+    /* Ensure fixes reach storage before clearing check bit */
+    bdrv_flush(s->bs);
+
+    s->header.features &= ~QED_F_NEED_CHECK;
+    qed_write_header_sync(s);
+}
+
 int qed_check(BDRVQEDState *s, BdrvCheckResult *result, bool fix)
 {
     QEDCheck check = {
@@ -215,6 +237,10 @@ int qed_check(BDRVQEDState *s, BdrvCheckResult *result, bool fix)
     if (ret == 0) {
         /* Only check for leaks if entire image was scanned successfully */
         qed_check_for_leaks(&check);
+
+        if (fix) {
+            qed_check_mark_clean(s, result);
+        }
     }
 
     g_free(check.used_clusters);
diff --git a/block/qed.c b/block/qed.c
index 5f3eefa..226545d 100644
--- a/block/qed.c
+++ b/block/qed.c
@@ -89,7 +89,7 @@ static void qed_header_cpu_to_le(const QEDHeader *cpu, QEDHeader *le)
     le->backing_filename_size = cpu_to_le32(cpu->backing_filename_size);
 }
 
-static int qed_write_header_sync(BDRVQEDState *s)
+int qed_write_header_sync(BDRVQEDState *s)
 {
     QEDHeader le;
     int ret;
@@ -491,13 +491,6 @@ static int bdrv_qed_open(BlockDriverState *bs, int flags)
             if (ret) {
                 goto out;
             }
-            if (!result.corruptions && !result.check_errors) {
-                /* Ensure fixes reach storage before clearing check bit */
-                bdrv_flush(s->bs);
-
-                s->header.features &= ~QED_F_NEED_CHECK;
-                qed_write_header_sync(s);
-            }
         }
     }
 
diff --git a/block/qed.h b/block/qed.h
index c716772..a063bf7 100644
--- a/block/qed.h
+++ b/block/qed.h
@@ -211,6 +211,11 @@ void *gencb_alloc(size_t len, BlockDriverCompletionFunc *cb, void *opaque);
 void gencb_complete(void *opaque, int ret);
 
 /**
+ * Header functions
+ */
+int qed_write_header_sync(BDRVQEDState *s);
+
+/**
  * L2 cache functions
  */
 void qed_init_l2_cache(L2TableCache *l2_cache);
commit 1f212b9d3edd8679bafd3bcf0301795206438724
Author: Paolo Bonzini <pbonzini at redhat.com>
Date:   Thu Aug 9 16:07:21 2012 +0200

    blockdev: flip default cache mode from writethrough to writeback
    
    Now all major device models (IDE, SCSI, virtio) can choose between
    writethrough and writeback at run-time, and virtio will even revert
    to writethrough if the guest is not capable of sending flushes.  So
    we can change the default to writeback at last.
    
    Tested, for lack of a better idea, with a breakpoint on bdrv_open
    and all cache choices one by one.
    
    Signed-off-by: Paolo Bonzini <pbonzini at redhat.com>
    Signed-off-by: Kevin Wolf <kwolf at redhat.com>

diff --git a/blockdev.c b/blockdev.c
index 8669142..7c83baa 100644
--- a/blockdev.c
+++ b/blockdev.c
@@ -377,6 +377,7 @@ DriveInfo *drive_init(QemuOpts *opts, int default_to_scsi)
 	}
     }
 
+    bdrv_flags |= BDRV_O_CACHE_WB;
     if ((buf = qemu_opt_get(opts, "cache")) != NULL) {
         if (bdrv_parse_cache_flags(buf, &bdrv_flags) != 0) {
             error_report("invalid cache option");
commit 9315cbfd8d7074eca44fbc5f93902e97b27d5240
Author: Paolo Bonzini <pbonzini at redhat.com>
Date:   Thu Aug 9 16:07:20 2012 +0200

    virtio-blk: disable write cache if not negotiated
    
    If the guest does not support flushes, we should run in writethrough mode.
    The setting is temporary until the next reset, so that for example the
    BIOS will run in writethrough mode while Linux will run with a writeback
    cache.
    
    Signed-off-by: Paolo Bonzini <pbonzini at redhat.com>
    Signed-off-by: Kevin Wolf <kwolf at redhat.com>

diff --git a/hw/virtio-blk.c b/hw/virtio-blk.c
index 97bb4bd..fd8fa90 100644
--- a/hw/virtio-blk.c
+++ b/hw/virtio-blk.c
@@ -543,6 +543,19 @@ static uint32_t virtio_blk_get_features(VirtIODevice *vdev, uint32_t features)
     return features;
 }
 
+static void virtio_blk_set_status(VirtIODevice *vdev, uint8_t status)
+{
+    VirtIOBlock *s = to_virtio_blk(vdev);
+    uint32_t features;
+
+    if (!(status & VIRTIO_CONFIG_S_DRIVER_OK)) {
+        return;
+    }
+
+    features = vdev->guest_features;
+    bdrv_set_enable_write_cache(s->bs, !!(features & (1 << VIRTIO_BLK_F_WCE)));
+}
+
 static void virtio_blk_save(QEMUFile *f, void *opaque)
 {
     VirtIOBlock *s = opaque;
@@ -623,6 +636,7 @@ VirtIODevice *virtio_blk_init(DeviceState *dev, VirtIOBlkConf *blk)
     s->vdev.get_config = virtio_blk_update_config;
     s->vdev.set_config = virtio_blk_set_config;
     s->vdev.get_features = virtio_blk_get_features;
+    s->vdev.set_status = virtio_blk_set_status;
     s->vdev.reset = virtio_blk_reset;
     s->bs = blk->conf.bs;
     s->conf = &blk->conf;
commit 13e3dce068773c971ff2f19d986378c55897c4a3
Author: Paolo Bonzini <pbonzini at redhat.com>
Date:   Thu Aug 9 16:07:19 2012 +0200

    virtio-blk: support VIRTIO_BLK_F_CONFIG_WCE
    
    Also rename VIRTIO_BLK_F_WCACHE to VIRTIO_BLK_F_WCE for consistency with
    the spec.
    
    Signed-off-by: Paolo Bonzini <pbonzini at redhat.com>
    Signed-off-by: Kevin Wolf <kwolf at redhat.com>

diff --git a/hw/virtio-blk.c b/hw/virtio-blk.c
index 552b3b6..97bb4bd 100644
--- a/hw/virtio-blk.c
+++ b/hw/virtio-blk.c
@@ -510,9 +510,19 @@ static void virtio_blk_update_config(VirtIODevice *vdev, uint8_t *config)
     blkcfg.size_max = 0;
     blkcfg.physical_block_exp = get_physical_block_exp(s->conf);
     blkcfg.alignment_offset = 0;
+    blkcfg.wce = bdrv_enable_write_cache(s->bs);
     memcpy(config, &blkcfg, sizeof(struct virtio_blk_config));
 }
 
+static void virtio_blk_set_config(VirtIODevice *vdev, const uint8_t *config)
+{
+    VirtIOBlock *s = to_virtio_blk(vdev);
+    struct virtio_blk_config blkcfg;
+
+    memcpy(&blkcfg, config, sizeof(blkcfg));
+    bdrv_set_enable_write_cache(s->bs, blkcfg.wce != 0);
+}
+
 static uint32_t virtio_blk_get_features(VirtIODevice *vdev, uint32_t features)
 {
     VirtIOBlock *s = to_virtio_blk(vdev);
@@ -523,9 +533,10 @@ static uint32_t virtio_blk_get_features(VirtIODevice *vdev, uint32_t features)
     features |= (1 << VIRTIO_BLK_F_BLK_SIZE);
     features |= (1 << VIRTIO_BLK_F_SCSI);
 
+    features |= (1 << VIRTIO_BLK_F_CONFIG_WCE);
     if (bdrv_enable_write_cache(s->bs))
-        features |= (1 << VIRTIO_BLK_F_WCACHE);
-    
+        features |= (1 << VIRTIO_BLK_F_WCE);
+
     if (bdrv_is_read_only(s->bs))
         features |= 1 << VIRTIO_BLK_F_RO;
 
@@ -610,6 +621,7 @@ VirtIODevice *virtio_blk_init(DeviceState *dev, VirtIOBlkConf *blk)
                                           sizeof(VirtIOBlock));
 
     s->vdev.get_config = virtio_blk_update_config;
+    s->vdev.set_config = virtio_blk_set_config;
     s->vdev.get_features = virtio_blk_get_features;
     s->vdev.reset = virtio_blk_reset;
     s->bs = blk->conf.bs;
diff --git a/hw/virtio-blk.h b/hw/virtio-blk.h
index 79ebccc..35834cf 100644
--- a/hw/virtio-blk.h
+++ b/hw/virtio-blk.h
@@ -31,8 +31,9 @@
 #define VIRTIO_BLK_F_BLK_SIZE   6       /* Block size of disk is available*/
 #define VIRTIO_BLK_F_SCSI       7       /* Supports scsi command passthru */
 /* #define VIRTIO_BLK_F_IDENTIFY   8       ATA IDENTIFY supported, DEPRECATED */
-#define VIRTIO_BLK_F_WCACHE     9       /* write cache enabled */
+#define VIRTIO_BLK_F_WCE        9       /* write cache enabled */
 #define VIRTIO_BLK_F_TOPOLOGY   10      /* Topology information is available */
+#define VIRTIO_BLK_F_CONFIG_WCE 11      /* write cache configurable */
 
 #define VIRTIO_BLK_ID_BYTES     20      /* ID string length */
 
@@ -49,6 +50,7 @@ struct virtio_blk_config
     uint8_t alignment_offset;
     uint16_t min_io_size;
     uint32_t opt_io_size;
+    uint8_t wce;
 } QEMU_PACKED;
 
 /* These two define direction. */
commit 353a41be05f9616f7bd7120456f706b3c85683ea
Author: Kevin Wolf <kwolf at redhat.com>
Date:   Thu Aug 9 13:17:14 2012 +0200

    qemu-iotests: Save some sed processes
    
    Instead of building a huge pipeline, just pass all expressions to a
    single sed process.
    
    Suggested-by: Eric Blake <eblake at redhat.com>
    Signed-off-by: Kevin Wolf <kwolf at redhat.com>
    Reviewed-by: Eric Blake <eblake at redhat.com>

diff --git a/tests/qemu-iotests/common.rc b/tests/qemu-iotests/common.rc
index 7782808..6b80516 100644
--- a/tests/qemu-iotests/common.rc
+++ b/tests/qemu-iotests/common.rc
@@ -105,16 +105,16 @@ _make_test_img()
 
     # XXX(hch): have global image options?
     $QEMU_IMG create -f $IMGFMT $extra_img_options $TEST_IMG $image_size | \
-    	sed -e "s#$IMGPROTO:$TEST_DIR#TEST_DIR#g" | \
-    	sed -e "s#$TEST_DIR#TEST_DIR#g" | \
-    	sed -e "s#$IMGFMT#IMGFMT#g" | \
-	sed -e "s# encryption=off##g" | \
-	sed -e "s# cluster_size=[0-9]\\+##g" | \
-	sed -e "s# table_size=[0-9]\\+##g" | \
-	sed -e "s# compat='[^']*'##g" | \
-	sed -e "s# compat6=\\(on\\|off\\)##g" | \
-	sed -e "s# static=\\(on\\|off\\)##g" | \
-	sed -e "s# lazy_refcounts=\\(on\\|off\\)##g"
+        sed -e "s#$IMGPROTO:$TEST_DIR#TEST_DIR#g" \
+            -e "s#$TEST_DIR#TEST_DIR#g" \
+            -e "s#$IMGFMT#IMGFMT#g" \
+            -e "s# encryption=off##g" \
+            -e "s# cluster_size=[0-9]\\+##g" \
+            -e "s# table_size=[0-9]\\+##g" \
+            -e "s# compat='[^']*'##g" \
+            -e "s# compat6=\\(on\\|off\\)##g" \
+            -e "s# static=\\(on\\|off\\)##g" \
+            -e "s# lazy_refcounts=\\(on\\|off\\)##g"
 }
 
 _cleanup_test_img()
commit ea8d82a1ed72634f089ed1bccccd9c84cc1ab855
Author: Jason Baron <jbaron at redhat.com>
Date:   Fri Aug 3 15:57:10 2012 -0400

    ahci: Fix sglist memleak in ahci_dma_rw_buf()
    
    I noticed that in hw/ide/ahci:ahci_dma_rw_buf() we do not free the sglist. Thus,
    I've added a call to qemu_sglist_destroy() to fix this memory leak.
    
    In addition, I've adeed a call in qemu_sglist_destroy() to 0 all of the sglist
    fields, in case there is some other codepath that tries to free the sglist.
    
    Signed-off-by: Jason Baron <jbaron at redhat.com>
    Signed-off-by: Kevin Wolf <kwolf at redhat.com>

diff --git a/dma-helpers.c b/dma-helpers.c
index 35cb500..13593d1 100644
--- a/dma-helpers.c
+++ b/dma-helpers.c
@@ -65,6 +65,7 @@ void qemu_sglist_add(QEMUSGList *qsg, dma_addr_t base, dma_addr_t len)
 void qemu_sglist_destroy(QEMUSGList *qsg)
 {
     g_free(qsg->sg);
+    memset(qsg, 0, sizeof(*qsg));
 }
 
 typedef struct {
diff --git a/hw/ide/ahci.c b/hw/ide/ahci.c
index de580a6..5ea3cad 100644
--- a/hw/ide/ahci.c
+++ b/hw/ide/ahci.c
@@ -1073,6 +1073,9 @@ static int ahci_dma_rw_buf(IDEDMA *dma, int is_write)
         dma_buf_write(p, l, &s->sg);
     }
 
+    /* free sglist that was created in ahci_populate_sglist() */
+    qemu_sglist_destroy(&s->sg);
+
     /* update number of transferred bytes */
     ad->cur_cmd->status = cpu_to_le32(le32_to_cpu(ad->cur_cmd->status) + l);
     s->io_buffer_index += l;
commit 61f52e06f0a21bab782f98ef3ea789aa6d0aa046
Author: Jason Baron <jbaron at redhat.com>
Date:   Fri Aug 3 15:57:06 2012 -0400

    ahci: Fix ahci cdrom read corruptions for reads > 128k
    
    While testing q35, which has its cdrom attached to the ahci controller, I found
    that the Fedora 17 install would panic on boot. The panic occurs while
    squashfs is trying to read from the cdrom. The errors are:
    
    [    8.622711] SQUASHFS error: xz_dec_run error, data probably corrupt
    [    8.625180] SQUASHFS error: squashfs_read_data failed to read block
    0x20be48a
    
    I was also able to produce corrupt data reads using an installed piix based
    qemu machine, using 'dd'. I found that the corruptions were only occuring when
    then read size was greater than 128k. For example, the following command
    results in corrupted reads:
    
    dd if=/dev/sr0 of=/tmp/blah bs=256k iflag=direct
    
    The > 128k size reads exercise a different code path than 128k and below. In
    ide_atapi_cmd_read_dma_cb() s->io_buffer_size is capped at 128k. Thus,
    ide_atapi_cmd_read_dma_cb() is called a second time when the read is > 128k.
    However, ahci_dma_rw_buf() restart the read from offset 0, instead of at 128k.
    Thus, resulting in a corrupted read.
    
    To fix this, I've introduced 'io_buffer_offset' field in IDEState to keep
    track of the offset. I've also modified ahci_populate_sglist() to take a new
    3rd offset argument, so that the sglist is property initialized.
    
    I've tested this patch using 'dd' testing, and Fedora 17 now correctly boots
    and installs on q35 with the cdrom ahci controller.
    
    Signed-off-by: Jason Baron <jbaron at redhat.com>
    Tested-by: Andreas Färber <afaerber at suse.de>
    Signed-off-by: Kevin Wolf <kwolf at redhat.com>

diff --git a/hw/ide/ahci.c b/hw/ide/ahci.c
index efea93f..de580a6 100644
--- a/hw/ide/ahci.c
+++ b/hw/ide/ahci.c
@@ -636,7 +636,7 @@ static void ahci_write_fis_d2h(AHCIDevice *ad, uint8_t *cmd_fis)
     }
 }
 
-static int ahci_populate_sglist(AHCIDevice *ad, QEMUSGList *sglist)
+static int ahci_populate_sglist(AHCIDevice *ad, QEMUSGList *sglist, int offset)
 {
     AHCICmdHdr *cmd = ad->cur_cmd;
     uint32_t opts = le32_to_cpu(cmd->opts);
@@ -647,6 +647,10 @@ static int ahci_populate_sglist(AHCIDevice *ad, QEMUSGList *sglist)
     uint8_t *prdt;
     int i;
     int r = 0;
+    int sum = 0;
+    int off_idx = -1;
+    int off_pos = -1;
+    int tbl_entry_size;
 
     if (!sglist_alloc_hint) {
         DPRINTF(ad->port_no, "no sg list given by guest: 0x%08x\n", opts);
@@ -669,10 +673,31 @@ static int ahci_populate_sglist(AHCIDevice *ad, QEMUSGList *sglist)
     /* Get entries in the PRDT, init a qemu sglist accordingly */
     if (sglist_alloc_hint > 0) {
         AHCI_SG *tbl = (AHCI_SG *)prdt;
-
-        qemu_sglist_init(sglist, sglist_alloc_hint, ad->hba->dma);
+        sum = 0;
         for (i = 0; i < sglist_alloc_hint; i++) {
             /* flags_size is zero-based */
+            tbl_entry_size = (le32_to_cpu(tbl[i].flags_size) + 1);
+            if (offset <= (sum + tbl_entry_size)) {
+                off_idx = i;
+                off_pos = offset - sum;
+                break;
+            }
+            sum += tbl_entry_size;
+        }
+        if ((off_idx == -1) || (off_pos < 0) || (off_pos > tbl_entry_size)) {
+            DPRINTF(ad->port_no, "%s: Incorrect offset! "
+                            "off_idx: %d, off_pos: %d\n",
+                            __func__, off_idx, off_pos);
+            r = -1;
+            goto out;
+        }
+
+        qemu_sglist_init(sglist, (sglist_alloc_hint - off_idx), ad->hba->dma);
+        qemu_sglist_add(sglist, le64_to_cpu(tbl[off_idx].addr + off_pos),
+                        le32_to_cpu(tbl[off_idx].flags_size) + 1 - off_pos);
+
+        for (i = off_idx + 1; i < sglist_alloc_hint; i++) {
+            /* flags_size is zero-based */
             qemu_sglist_add(sglist, le64_to_cpu(tbl[i].addr),
                             le32_to_cpu(tbl[i].flags_size) + 1);
         }
@@ -745,7 +770,7 @@ static void process_ncq_command(AHCIState *s, int port, uint8_t *cmd_fis,
             ncq_tfs->lba, ncq_tfs->lba + ncq_tfs->sector_count - 2,
             s->dev[port].port.ifs[0].nb_sectors - 1);
 
-    ahci_populate_sglist(&s->dev[port], &ncq_tfs->sglist);
+    ahci_populate_sglist(&s->dev[port], &ncq_tfs->sglist, 0);
     ncq_tfs->tag = tag;
 
     switch(ncq_fis->command) {
@@ -970,7 +995,7 @@ static int ahci_start_transfer(IDEDMA *dma)
         goto out;
     }
 
-    if (!ahci_populate_sglist(ad, &s->sg)) {
+    if (!ahci_populate_sglist(ad, &s->sg, 0)) {
         has_sglist = 1;
     }
 
@@ -1015,6 +1040,7 @@ static void ahci_start_dma(IDEDMA *dma, IDEState *s,
     DPRINTF(ad->port_no, "\n");
     ad->dma_cb = dma_cb;
     ad->dma_status |= BM_STATUS_DMAING;
+    s->io_buffer_offset = 0;
     dma_cb(s, 0);
 }
 
@@ -1023,7 +1049,7 @@ static int ahci_dma_prepare_buf(IDEDMA *dma, int is_write)
     AHCIDevice *ad = DO_UPCAST(AHCIDevice, dma, dma);
     IDEState *s = &ad->port.ifs[0];
 
-    ahci_populate_sglist(ad, &s->sg);
+    ahci_populate_sglist(ad, &s->sg, 0);
     s->io_buffer_size = s->sg.size;
 
     DPRINTF(ad->port_no, "len=%#x\n", s->io_buffer_size);
@@ -1037,7 +1063,7 @@ static int ahci_dma_rw_buf(IDEDMA *dma, int is_write)
     uint8_t *p = s->io_buffer + s->io_buffer_index;
     int l = s->io_buffer_size - s->io_buffer_index;
 
-    if (ahci_populate_sglist(ad, &s->sg)) {
+    if (ahci_populate_sglist(ad, &s->sg, s->io_buffer_offset)) {
         return 0;
     }
 
@@ -1050,6 +1076,7 @@ static int ahci_dma_rw_buf(IDEDMA *dma, int is_write)
     /* update number of transferred bytes */
     ad->cur_cmd->status = cpu_to_le32(le32_to_cpu(ad->cur_cmd->status) + l);
     s->io_buffer_index += l;
+    s->io_buffer_offset += l;
 
     DPRINTF(ad->port_no, "len=%#x\n", l);
 
diff --git a/hw/ide/internal.h b/hw/ide/internal.h
index 7170bd9..bf7d313 100644
--- a/hw/ide/internal.h
+++ b/hw/ide/internal.h
@@ -393,6 +393,7 @@ struct IDEState {
     struct iovec iov;
     QEMUIOVector qiov;
     /* ATA DMA state */
+    int io_buffer_offset;
     int io_buffer_size;
     QEMUSGList sg;
     /* PIO transfer handling */
commit 730a9c53b4e52681fcfe31cf38854cbf91e132c7
Author: Avi Kivity <avi at redhat.com>
Date:   Mon Aug 6 15:49:03 2012 +0300

    virtio-blk: fix use-after-free while handling scsi commands
    
    The scsi passthrough handler falls through after completing a
    request into the failure path, resulting in a use after free.
    
    Reproducible by running a guest with aio=native on a block device.
    
    Reported-by: Stefan Priebe <s.priebe at profihost.ag>
    Signed-off-by: Avi Kivity <avi at redhat.com>
    Signed-off-by: Stefan Hajnoczi <stefanha at linux.vnet.ibm.com>
    Signed-off-by: Kevin Wolf <kwolf at redhat.com>

diff --git a/hw/virtio-blk.c b/hw/virtio-blk.c
index f21757e..552b3b6 100644
--- a/hw/virtio-blk.c
+++ b/hw/virtio-blk.c
@@ -254,6 +254,7 @@ static void virtio_blk_handle_scsi(VirtIOBlockReq *req)
 
     virtio_blk_req_complete(req, status);
     g_free(req);
+    return;
 #else
     abort();
 #endif
commit 3d1d9652978ac5a32a0beb4bdf6065ca39440d89
Author: Bruce Rogers <brogers at suse.com>
Date:   Thu Aug 9 12:47:40 2012 -0600

    handle device help before accelerator set up
    
    A command line device probe using just -device "?" gets processed
    after qemu-kvm initializes the accelerator. If /dev/kvm is not
    present, the accelerator check will fail (kvm is defaulted to on),
    which causes libvirt to not be set up to handle qemu guests.
    
    Moving the device help handling before the accelerator set up allows
    the device probe to work in this configuration and libvirt succeeds
    in setting up for a qemu hypervisor mode.
    
    Signed-off-by: Bruce Rogers <brogers at suse.com>
    Signed-off-by: Blue Swirl <blauwirbel at gmail.com>

diff --git a/vl.c b/vl.c
index e71cb30..a4a520f 100644
--- a/vl.c
+++ b/vl.c
@@ -3345,6 +3345,11 @@ int main(int argc, char **argv, char **envp)
         ram_size = DEFAULT_RAM_SIZE * 1024 * 1024;
     }
 
+    if (qemu_opts_foreach(qemu_find_opts("device"), device_help_func, NULL, 0)
+        != 0) {
+        exit(0);
+    }
+
     configure_accelerator();
 
     qemu_init_cpu_loop();
@@ -3500,9 +3505,6 @@ int main(int argc, char **argv, char **envp)
     }
     select_vgahw(vga_model);
 
-    if (qemu_opts_foreach(qemu_find_opts("device"), device_help_func, NULL, 0) != 0)
-        exit(0);
-
     if (watchdog) {
         i = select_watchdog(watchdog);
         if (i > 0)
commit d3da41e32bc6d6fac80d402aa1cc0f1d30539d98
Merge: 8227421... d65e981...
Author: Blue Swirl <blauwirbel at gmail.com>
Date:   Thu Aug 9 18:44:49 2012 +0000

    Merge branch 'x86cpu_qom_tcg_v2' of git://github.com/imammedo/qemu
    
    * 'x86cpu_qom_tcg_v2' of git://github.com/imammedo/qemu:
      target-i386: move tcg initialization into x86_cpu_initfn()
      cleanup cpu_set_debug_excp_handler
      target-xtensa: drop usage of prev_debug_excp_handler
      target-i386: drop usage of prev_debug_excp_handler

commit 8227421e0476d9caf2a9a089465bb40c23834e33
Author: Stefano Stabellini <stefano.stabellini at eu.citrix.com>
Date:   Tue May 29 03:35:24 2012 +0000

    qemu_rearm_alarm_timer: do not call rearm if the next deadline is INT64_MAX
    
    qemu_rearm_alarm_timer partially duplicates the code in
    qemu_next_alarm_deadline to figure out if it needs to rearm the timer.
    If it calls qemu_next_alarm_deadline, it always rearms the timer even if
    the next deadline is INT64_MAX.
    
    This patch simplifies the behavior of qemu_rearm_alarm_timer and removes
    the duplicated code, always calling qemu_next_alarm_deadline and only
    rearming the timer if the deadline is less than INT64_MAX.
    
    Signed-off-by: Stefano Stabellini <stefano.stabellini at eu.citrix.com>
    Reviewed-by: Stefan Weil <sw at weilnetz.de>
    Tested-by: Andreas Färber <andreas.faerber at web.de>
    Signed-off-by: Blue Swirl <blauwirbel at gmail.com>

diff --git a/qemu-timer.c b/qemu-timer.c
index 062fdf2..5aea94e 100644
--- a/qemu-timer.c
+++ b/qemu-timer.c
@@ -112,14 +112,10 @@ static int64_t qemu_next_alarm_deadline(void)
 
 static void qemu_rearm_alarm_timer(struct qemu_alarm_timer *t)
 {
-    int64_t nearest_delta_ns;
-    if (!rt_clock->active_timers &&
-        !vm_clock->active_timers &&
-        !host_clock->active_timers) {
-        return;
+    int64_t nearest_delta_ns = qemu_next_alarm_deadline();
+    if (nearest_delta_ns < INT64_MAX) {
+        t->rearm(t, nearest_delta_ns);
     }
-    nearest_delta_ns = qemu_next_alarm_deadline();
-    t->rearm(t, nearest_delta_ns);
 }
 
 /* TODO: MIN_TIMER_REARM_NS should be optimized */
commit 82e5d464146e69789329cf860685d22db6a64862
Author: Max Filippov <jcmvbkbc at gmail.com>
Date:   Thu Aug 9 03:31:38 2012 +0400

    target-xtensa: make 'sim' to be the default machine
    
    This fixes the following error:
    
        $ qemu-system-xtensa -cpu help
        Segmentation fault
    
    Signed-off-by: Max Filippov <jcmvbkbc at gmail.com>
    Signed-off-by: Blue Swirl <blauwirbel at gmail.com>

diff --git a/hw/xtensa_sim.c b/hw/xtensa_sim.c
index ed38bd4..831460b 100644
--- a/hw/xtensa_sim.c
+++ b/hw/xtensa_sim.c
@@ -111,6 +111,7 @@ static void xtensa_sim_init(ram_addr_t ram_size,
 static QEMUMachine xtensa_sim_machine = {
     .name = "sim",
     .desc = "sim machine (" XTENSA_DEFAULT_CPU_MODEL ")",
+    .is_default = true,
     .init = xtensa_sim_init,
     .max_cpus = 4,
 };
commit e38077ff90fac002038805d17044aa05f4f54c24
Author: Max Filippov <jcmvbkbc at gmail.com>
Date:   Wed Aug 8 14:07:14 2012 +0400

    target-xtensa: make default CPU depend on target endianness
    
    This makes usable default for -cpu option both for qemu-system-xtensa
    and qemu-system-xtensaeb fixing the following error:
    
        $ qemu-system-xtensaeb -M sim
        Unable to find CPU definition
    
    Signed-off-by: Max Filippov <jcmvbkbc at gmail.com>
    Tested-by: Markus Armbruster <armbru at redhat.com>
    Signed-off-by: Blue Swirl <blauwirbel at gmail.com>

diff --git a/hw/xtensa_lx60.c b/hw/xtensa_lx60.c
index c4f616f..3653f65 100644
--- a/hw/xtensa_lx60.c
+++ b/hw/xtensa_lx60.c
@@ -173,7 +173,7 @@ static void lx_init(const LxBoardDesc *board,
     int n;
 
     if (!cpu_model) {
-        cpu_model = "dc232b";
+        cpu_model = XTENSA_DEFAULT_CPU_MODEL;
     }
 
     for (n = 0; n < smp_cpus; n++) {
@@ -300,14 +300,14 @@ static void xtensa_lx200_init(ram_addr_t ram_size,
 
 static QEMUMachine xtensa_lx60_machine = {
     .name = "lx60",
-    .desc = "lx60 EVB (dc232b)",
+    .desc = "lx60 EVB (" XTENSA_DEFAULT_CPU_MODEL ")",
     .init = xtensa_lx60_init,
     .max_cpus = 4,
 };
 
 static QEMUMachine xtensa_lx200_machine = {
     .name = "lx200",
-    .desc = "lx200 EVB (dc232b)",
+    .desc = "lx200 EVB (" XTENSA_DEFAULT_CPU_MODEL ")",
     .init = xtensa_lx200_init,
     .max_cpus = 4,
 };
diff --git a/hw/xtensa_sim.c b/hw/xtensa_sim.c
index 1ce07fb..ed38bd4 100644
--- a/hw/xtensa_sim.c
+++ b/hw/xtensa_sim.c
@@ -102,7 +102,7 @@ static void xtensa_sim_init(ram_addr_t ram_size,
                      const char *initrd_filename, const char *cpu_model)
 {
     if (!cpu_model) {
-        cpu_model = "dc232b";
+        cpu_model = XTENSA_DEFAULT_CPU_MODEL;
     }
     sim_init(ram_size, boot_device, kernel_filename, kernel_cmdline,
             initrd_filename, cpu_model);
@@ -110,7 +110,7 @@ static void xtensa_sim_init(ram_addr_t ram_size,
 
 static QEMUMachine xtensa_sim_machine = {
     .name = "sim",
-    .desc = "sim machine (dc232b)",
+    .desc = "sim machine (" XTENSA_DEFAULT_CPU_MODEL ")",
     .init = xtensa_sim_init,
     .max_cpus = 4,
 };
diff --git a/target-xtensa/cpu.h b/target-xtensa/cpu.h
index f7db116..177094a 100644
--- a/target-xtensa/cpu.h
+++ b/target-xtensa/cpu.h
@@ -351,6 +351,12 @@ typedef struct CPUXtensaState {
 #define cpu_signal_handler cpu_xtensa_signal_handler
 #define cpu_list xtensa_cpu_list
 
+#ifdef TARGET_WORDS_BIGENDIAN
+#define XTENSA_DEFAULT_CPU_MODEL "fsf"
+#else
+#define XTENSA_DEFAULT_CPU_MODEL "dc232b"
+#endif
+
 XtensaCPU *cpu_xtensa_init(const char *cpu_model);
 
 static inline CPUXtensaState *cpu_init(const char *cpu_model)
commit f1cb0951c5298753652a73cfd8efc0b1a82f37de
Author: Nathan Froyd <froydnj at codesourcery.com>
Date:   Thu Jun 7 15:04:14 2012 +0000

    MIPS: Correct FCR0 initialization
    
     This change addresses a problem where QEMU incorrectly traps on
    floating-point MADD group instructions with SIGILL, at least while
    emulating MIPS32r2 processors.  These instructions use the COP1X major
    opcode and include ones like:
    
    	madd.d	$f2,$f4,$f2,$f6
    
     Here's Nathan's original analysis of the problem:
    
    "QEMU essentially does:
    
      d = find_cpu (cpu_string)	// get CPU definition
      fpu_init (env, d)		// initialize fpu state (init FCR0, basically)
      cpu_reset (env)
    
    ...and the cpu_reset call clears all interesting state that fpu_init
    setup, then proceeds to reinitialize all the CP0 registers...but not
    FCR0."
    
     I have verified this change with system emulation running the GDB test
    suite for the mips-sde-elf target (o32, big endian, 24Kf CPU emulated),
    there were 55 progressions and no regressions.
    
    Signed-off-by: Maciej W. Rozycki <macro at codesourcery.com>
    Reviewed-by: Richard Henderson <rth at twiddle.net>
    Signed-off-by: Blue Swirl <blauwirbel at gmail.com>

diff --git a/target-mips/translate.c b/target-mips/translate.c
index 4e15ee3..47daf85 100644
--- a/target-mips/translate.c
+++ b/target-mips/translate.c
@@ -12763,6 +12763,7 @@ void cpu_state_reset(CPUMIPSState *env)
     env->CP0_SRSConf3 = env->cpu_model->CP0_SRSConf3;
     env->CP0_SRSConf4_rw_bitmask = env->cpu_model->CP0_SRSConf4_rw_bitmask;
     env->CP0_SRSConf4 = env->cpu_model->CP0_SRSConf4;
+    env->active_fpu.fcr0 = env->cpu_model->CP1_fcr0;
     env->insn_flags = env->cpu_model->insn_flags;
 
 #if defined(CONFIG_USER_ONLY)
commit 832a226b62c6bf75c57ec3ae4d6964923d2aabcd
Author: Blue Swirl <blauwirbel at gmail.com>
Date:   Mon Jul 30 17:46:06 2012 +0000

    scsi-bus: remove overlapping entry
    
    LOAD_UNLOAD and START_STOP have same value, so the table
    entry is initialized twice. Spotted by Clang compiler.
    
    Remove LOAD_UNLOAD entry since START_STOP entry already
    represents both.
    
    Reviewed-by: Markus Armbruster <armbru at redhat.com>
    Signed-off-by: Blue Swirl <blauwirbel at gmail.com>

diff --git a/hw/scsi-bus.c b/hw/scsi-bus.c
index 6120cc8..b8a857d 100644
--- a/hw/scsi-bus.c
+++ b/hw/scsi-bus.c
@@ -1437,7 +1437,6 @@ static const char *scsi_command_name(uint8_t cmd)
         [ ATA_PASSTHROUGH_12       ] = "BLANK/ATA_PASSTHROUGH_12",
         [ MOVE_MEDIUM              ] = "MOVE_MEDIUM",
         [ EXCHANGE_MEDIUM          ] = "EXCHANGE MEDIUM",
-        [ LOAD_UNLOAD              ] = "LOAD_UNLOAD",
         [ READ_12                  ] = "READ_12",
         [ WRITE_12                 ] = "WRITE_12",
         [ ERASE_12                 ] = "ERASE_12/GET_PERFORMANCE",
commit a1e64eb96cfa6b9ddf947487347e5a2ca139629f
Author: Blue Swirl <blauwirbel at gmail.com>
Date:   Mon Jul 30 17:28:04 2012 +0000

    xilinx_axienet: avoid useless self-assignment
    
    Statement s=s; makes little sense, remove it. Spotted by Clang
    compiler.
    
    Signed-off-by: Blue Swirl <blauwirbel at gmail.com>

diff --git a/hw/xilinx_axienet.c b/hw/xilinx_axienet.c
index adfaf2c..9b08c62 100644
--- a/hw/xilinx_axienet.c
+++ b/hw/xilinx_axienet.c
@@ -648,7 +648,6 @@ static ssize_t eth_rx(NetClientState *nc, const uint8_t *buf, size_t size)
     uint16_t csum16;
     int i;
 
-    s = s;
     DENET(qemu_log("%s: %zd bytes\n", __func__, size));
 
     unicast = ~buf[0] & 0x1;
commit 1846ec2c6a36894e61dfa9c566820239052fb28b
Author: Blue Swirl <blauwirbel at gmail.com>
Date:   Mon Jul 30 15:51:17 2012 +0000

    user: fix accidental AREG0 use
    
    Global register AREG0 was always assumed to be usable in user-exec.c,
    but this is incorrect for several targets.
    
    Fix with #ifdeffery and by using other variables.
    
    Signed-off-by: Blue Swirl <blauwirbel at gmail.com>

diff --git a/user-exec.c b/user-exec.c
index 1a9c276..b9ea9dd 100644
--- a/user-exec.c
+++ b/user-exec.c
@@ -18,7 +18,9 @@
  */
 #include "config.h"
 #include "cpu.h"
+#ifndef CONFIG_TCG_PASS_AREG0
 #include "dyngen-exec.h"
+#endif
 #include "disas.h"
 #include "tcg.h"
 
@@ -58,9 +60,11 @@ void cpu_resume_from_signal(CPUArchState *env1, void *puc)
     struct sigcontext *uc = puc;
 #endif
 
+#ifndef CONFIG_TCG_PASS_AREG0
     env = env1;
 
     /* XXX: restore cpu registers saved in host registers */
+#endif
 
     if (puc) {
         /* XXX: use siglongjmp ? */
@@ -74,8 +78,8 @@ void cpu_resume_from_signal(CPUArchState *env1, void *puc)
         sigprocmask(SIG_SETMASK, &uc->sc_mask, NULL);
 #endif
     }
-    env->exception_index = -1;
-    longjmp(env->jmp_env, 1);
+    env1->exception_index = -1;
+    longjmp(env1->jmp_env, 1);
 }
 
 /* 'pc' is the host PC at which the exception was raised. 'address' is
@@ -89,9 +93,11 @@ static inline int handle_cpu_signal(uintptr_t pc, unsigned long address,
     TranslationBlock *tb;
     int ret;
 
+#ifndef CONFIG_TCG_PASS_AREG0
     if (cpu_single_env) {
         env = cpu_single_env; /* XXX: find a correct solution for multithread */
     }
+#endif
 #if defined(DEBUG_SIGNAL)
     qemu_printf("qemu: SIGSEGV pc=0x%08lx address=%08lx w=%d oldset=0x%08lx\n",
                 pc, address, is_write, *(unsigned long *)old_set);
@@ -103,7 +109,8 @@ static inline int handle_cpu_signal(uintptr_t pc, unsigned long address,
     }
 
     /* see if it is an MMU fault */
-    ret = cpu_handle_mmu_fault(env, address, is_write, MMU_USER_IDX);
+    ret = cpu_handle_mmu_fault(cpu_single_env, address, is_write,
+                               MMU_USER_IDX);
     if (ret < 0) {
         return 0; /* not an MMU fault */
     }
@@ -115,13 +122,13 @@ static inline int handle_cpu_signal(uintptr_t pc, unsigned long address,
     if (tb) {
         /* the PC is inside the translated code. It means that we have
            a virtual CPU fault */
-        cpu_restore_state(tb, env, pc);
+        cpu_restore_state(tb, cpu_single_env, pc);
     }
 
     /* we restore the process signal mask as the sigreturn should
        do it (XXX: use sigsetjmp) */
     sigprocmask(SIG_SETMASK, old_set, NULL);
-    exception_action(env);
+    exception_action(cpu_single_env);
 
     /* never comes here */
     return 1;
commit 427a1a2cb1d35b83b6302886f46289f6d617134d
Author: Blue Swirl <blauwirbel at gmail.com>
Date:   Mon Jul 30 15:46:55 2012 +0000

    qapi: avoid reserved keywords
    
    Clang compiler complained about use of reserved word 'restrict' in SLIRP
    and QAPI.
    
    Prefix C keywords with "q_", adjust SLIRP accordingly.
    
    Reviewed-by: Markus Armbruster <armbru at redhat.com>
    Signed-off-by: Blue Swirl <blauwirbel at gmail.com>

diff --git a/net/slirp.c b/net/slirp.c
index 08adb97..8db66ea 100644
--- a/net/slirp.c
+++ b/net/slirp.c
@@ -718,9 +718,9 @@ int net_init_slirp(const NetClientOptions *opts, const char *name,
     net_init_slirp_configs(user->hostfwd, SLIRP_CFG_HOSTFWD);
     net_init_slirp_configs(user->guestfwd, 0);
 
-    ret = net_slirp_init(peer, "user", name, user->restrict, vnet, user->host,
-                         user->hostname, user->tftp, user->bootfile,
-                         user->dhcpstart, user->dns, user->smb,
+    ret = net_slirp_init(peer, "user", name, user->q_restrict, vnet,
+                         user->host, user->hostname, user->tftp,
+                         user->bootfile, user->dhcpstart, user->dns, user->smb,
                          user->smbserver);
 
     while (slirp_configs) {
diff --git a/scripts/qapi.py b/scripts/qapi.py
index d3b8b4d..122b4cb 100644
--- a/scripts/qapi.py
+++ b/scripts/qapi.py
@@ -142,6 +142,22 @@ def camel_case(name):
     return new_name
 
 def c_var(name):
+    # ANSI X3J11/88-090, 3.1.1
+    c89_words = set(['auto', 'break', 'case', 'char', 'const', 'continue',
+                     'default', 'do', 'double', 'else', 'enum', 'extern', 'float',
+                     'for', 'goto', 'if', 'int', 'long', 'register', 'return',
+                     'short', 'signed', 'sizeof', 'static', 'struct', 'switch',
+                     'typedef', 'union', 'unsigned', 'void', 'volatile', 'while'])
+    # ISO/IEC 9899:1999, 6.4.1
+    c99_words = set(['inline', 'restrict', '_Bool', '_Complex', '_Imaginary'])
+    # ISO/IEC 9899:2011, 6.4.1
+    c11_words = set(['_Alignas', '_Alignof', '_Atomic', '_Generic', '_Noreturn',
+                     '_Static_assert', '_Thread_local'])
+    # GCC http://gcc.gnu.org/onlinedocs/gcc-4.7.1/gcc/C-Extensions.html
+    # excluding _.*
+    gcc_words = set(['asm', 'typeof'])
+    if name in c89_words | c99_words | c11_words | gcc_words:
+        return "q_" + name
     return name.replace('-', '_').lstrip("*")
 
 def c_fun(name):
commit 8954bae3ce1ae5b64218b8731da9a8d7f46db9a7
Author: Blue Swirl <blauwirbel at gmail.com>
Date:   Mon Jul 30 15:29:11 2012 +0000

    sparc: fix expression with uninitialized initial value
    
    err was uninitialized, it's not OK to use |=. Spotted by Clang
    compiler.
    
    Fix by implementing the earlier statement which initializes the variable.
    
    Signed-off-by: Blue Swirl <blauwirbel at gmail.com>

diff --git a/linux-user/signal.c b/linux-user/signal.c
index 9be5ac0..7869147 100644
--- a/linux-user/signal.c
+++ b/linux-user/signal.c
@@ -1844,7 +1844,7 @@ typedef struct {
 } __siginfo_t;
 
 typedef struct {
-        unsigned   long si_float_regs [32];
+        abi_ulong       si_float_regs[32];
         unsigned   long si_fsr;
         unsigned   long si_fpqdepth;
         struct {
@@ -2056,11 +2056,9 @@ restore_fpu_state(CPUSPARCState *env, qemu_siginfo_fpu_t *fpu)
                 return -EFAULT;
 #endif
 
-#if 0
         /* XXX: incorrect */
-        err = __copy_from_user(&env->fpr[0], &fpu->si_float_regs[0],
-	                             (sizeof(unsigned long) * 32));
-#endif
+        err = copy_from_user(&env->fpr[0], fpu->si_float_regs[0],
+                             (sizeof(abi_ulong) * 32));
         err |= __get_user(env->fsr, &fpu->si_fsr);
 #if 0
         err |= __get_user(current->thread.fpqdepth, &fpu->si_fpqdepth);
commit acfbe712df86e20634b7860be91e16ae9aa39cd0
Author: Blue Swirl <blauwirbel at gmail.com>
Date:   Mon Jul 30 15:24:23 2012 +0000

    sparc: fix floppy TC line setup
    
    The qemu_irq for Terminal Count (TC) line between FDC and Slavio misc
    device was created only after use, spotted by Clang compiler. Also,
    it was not created if the FDC didn't exist.
    
    Rearrange code to fix order. Always create the TC line.
    
    Signed-off-by: Blue Swirl <blauwirbel at gmail.com>

diff --git a/hw/sun4m.c b/hw/sun4m.c
index a959261..0f909b5 100644
--- a/hw/sun4m.c
+++ b/hw/sun4m.c
@@ -832,6 +832,10 @@ static void cpu_devinit(const char *cpu_model, unsigned int id,
     env->prom_addr = prom_addr;
 }
 
+static void dummy_fdc_tc(void *opaque, int irq, int level)
+{
+}
+
 static void sun4m_hw_init(const struct sun4m_hwdef *hwdef, ram_addr_t RAM_size,
                           const char *boot_device,
                           const char *kernel_filename,
@@ -942,9 +946,6 @@ static void sun4m_hw_init(const struct sun4m_hwdef *hwdef, ram_addr_t RAM_size,
               serial_hds[0], serial_hds[1], ESCC_CLOCK, 1);
 
     cpu_halt = qemu_allocate_irqs(cpu_halt_signal, NULL, 1);
-    slavio_misc_init(hwdef->slavio_base, hwdef->aux1_base, hwdef->aux2_base,
-                     slavio_irq[30], fdc_tc);
-
     if (hwdef->apc_base) {
         apc_init(hwdef->apc_base, cpu_halt[0]);
     }
@@ -955,8 +956,13 @@ static void sun4m_hw_init(const struct sun4m_hwdef *hwdef, ram_addr_t RAM_size,
         fd[0] = drive_get(IF_FLOPPY, 0, 0);
         sun4m_fdctrl_init(slavio_irq[22], hwdef->fd_base, fd,
                           &fdc_tc);
+    } else {
+        fdc_tc = *qemu_allocate_irqs(dummy_fdc_tc, NULL, 1);
     }
 
+    slavio_misc_init(hwdef->slavio_base, hwdef->aux1_base, hwdef->aux2_base,
+                     slavio_irq[30], fdc_tc);
+
     if (drive_get_max_bus(IF_SCSI) > 0) {
         fprintf(stderr, "qemu: too many SCSI bus\n");
         exit(1);
@@ -1772,16 +1778,18 @@ static void sun4c_hw_init(const struct sun4c_hwdef *hwdef, ram_addr_t RAM_size,
               slavio_irq[1], serial_hds[0], serial_hds[1],
               ESCC_CLOCK, 1);
 
-    slavio_misc_init(0, hwdef->aux1_base, 0, slavio_irq[1], fdc_tc);
-
     if (hwdef->fd_base != (target_phys_addr_t)-1) {
         /* there is zero or one floppy drive */
         memset(fd, 0, sizeof(fd));
         fd[0] = drive_get(IF_FLOPPY, 0, 0);
         sun4m_fdctrl_init(slavio_irq[1], hwdef->fd_base, fd,
                           &fdc_tc);
+    } else {
+        fdc_tc = *qemu_allocate_irqs(dummy_fdc_tc, NULL, 1);
     }
 
+    slavio_misc_init(0, hwdef->aux1_base, 0, slavio_irq[1], fdc_tc);
+
     if (drive_get_max_bus(IF_SCSI) > 0) {
         fprintf(stderr, "qemu: too many SCSI bus\n");
         exit(1);
commit cea936b1b5c741c0456f9ccb90be54b5e4b589e5
Author: Hervé Poussineau <hpoussin at reactos.org>
Date:   Sat Aug 4 21:10:06 2012 +0200

    esp: add Tekram DC-390 emulation (PC SCSI adapter)
    
    Difference with AMD PCscsi is that DC-390 contains a EEPROM,
    and that a romfile is available to add INT13 support.
    
    This has been successfully tested on:
    - MS DOS 6.22 (using DC390 ASPI driver)
    - MS Windows 98 SE (using DC390 driver)
    - MS Windows NT 3.1 (using DC390 driver)
    - MS Windows NT 4.0 (using DC390 driver)
    - hard disk and cdrom boot
    
    Signed-off-by: Hervé Poussineau <hpoussin at reactos.org>
    Signed-off-by: Blue Swirl <blauwirbel at gmail.com>

diff --git a/hw/esp-pci.c b/hw/esp-pci.c
index f633a18..170e007 100644
--- a/hw/esp-pci.c
+++ b/hw/esp-pci.c
@@ -24,10 +24,13 @@
  */
 
 #include "pci.h"
+#include "eeprom93xx.h"
 #include "esp.h"
 #include "trace.h"
 #include "qemu-log.h"
 
+#define TYPE_AM53C974_DEVICE "am53c974"
+
 #define DMA_CMD   0x0
 #define DMA_STC   0x1
 #define DMA_SPA   0x2
@@ -382,15 +385,134 @@ static void esp_pci_class_init(ObjectClass *klass, void *data)
 }
 
 static const TypeInfo esp_pci_info = {
-    .name = "am53c974",
+    .name = TYPE_AM53C974_DEVICE,
     .parent = TYPE_PCI_DEVICE,
     .instance_size = sizeof(PCIESPState),
     .class_init = esp_pci_class_init,
 };
 
+typedef struct {
+    PCIESPState pci;
+    eeprom_t *eeprom;
+} DC390State;
+
+#define TYPE_DC390_DEVICE "dc390"
+#define DC390(obj) \
+    OBJECT_CHECK(DC390State, obj, TYPE_DC390_DEVICE)
+
+#define EE_ADAPT_SCSI_ID 64
+#define EE_MODE2         65
+#define EE_DELAY         66
+#define EE_TAG_CMD_NUM   67
+#define EE_ADAPT_OPTIONS 68
+#define EE_BOOT_SCSI_ID  69
+#define EE_BOOT_SCSI_LUN 70
+#define EE_CHKSUM1       126
+#define EE_CHKSUM2       127
+
+#define EE_ADAPT_OPTION_F6_F8_AT_BOOT   0x01
+#define EE_ADAPT_OPTION_BOOT_FROM_CDROM 0x02
+#define EE_ADAPT_OPTION_INT13           0x04
+#define EE_ADAPT_OPTION_SCAM_SUPPORT    0x08
+
+
+static uint32_t dc390_read_config(PCIDevice *dev, uint32_t addr, int l)
+{
+    DC390State *pci = DC390(dev);
+    uint32_t val;
+
+    val = pci_default_read_config(dev, addr, l);
+
+    if (addr == 0x00 && l == 1) {
+        /* First byte of address space is AND-ed with EEPROM DO line */
+        if (!eeprom93xx_read(pci->eeprom)) {
+            val &= ~0xff;
+        }
+    }
+
+    return val;
+}
+
+static void dc390_write_config(PCIDevice *dev,
+                               uint32_t addr, uint32_t val, int l)
+{
+    DC390State *pci = DC390(dev);
+    if (addr == 0x80) {
+        /* EEPROM write */
+        int eesk = val & 0x80 ? 1 : 0;
+        int eedi = val & 0x40 ? 1 : 0;
+        eeprom93xx_write(pci->eeprom, 1, eesk, eedi);
+    } else if (addr == 0xc0) {
+        /* EEPROM CS low */
+        eeprom93xx_write(pci->eeprom, 0, 0, 0);
+    } else {
+        pci_default_write_config(dev, addr, val, l);
+    }
+}
+
+static int dc390_scsi_init(PCIDevice *dev)
+{
+    DC390State *pci = DC390(dev);
+    uint8_t *contents;
+    uint16_t chksum = 0;
+    int i, ret;
+
+    /* init base class */
+    ret = esp_pci_scsi_init(dev);
+    if (ret < 0) {
+        return ret;
+    }
+
+    /* EEPROM */
+    pci->eeprom = eeprom93xx_new(DEVICE(dev), 64);
+
+    /* set default eeprom values */
+    contents = (uint8_t *)eeprom93xx_data(pci->eeprom);
+
+    for (i = 0; i < 16; i++) {
+        contents[i * 2] = 0x57;
+        contents[i * 2 + 1] = 0x00;
+    }
+    contents[EE_ADAPT_SCSI_ID] = 7;
+    contents[EE_MODE2] = 0x0f;
+    contents[EE_TAG_CMD_NUM] = 0x04;
+    contents[EE_ADAPT_OPTIONS] = EE_ADAPT_OPTION_F6_F8_AT_BOOT
+                               | EE_ADAPT_OPTION_BOOT_FROM_CDROM
+                               | EE_ADAPT_OPTION_INT13;
+
+    /* update eeprom checksum */
+    for (i = 0; i < EE_CHKSUM1; i += 2) {
+        chksum += contents[i] + (((uint16_t)contents[i + 1]) << 8);
+    }
+    chksum = 0x1234 - chksum;
+    contents[EE_CHKSUM1] = chksum & 0xff;
+    contents[EE_CHKSUM2] = chksum >> 8;
+
+    return 0;
+}
+
+static void dc390_class_init(ObjectClass *klass, void *data)
+{
+    DeviceClass *dc = DEVICE_CLASS(klass);
+    PCIDeviceClass *k = PCI_DEVICE_CLASS(klass);
+
+    k->init = dc390_scsi_init;
+    k->config_read = dc390_read_config;
+    k->config_write = dc390_write_config;
+    dc->desc = "Tekram DC-390 SCSI adapter";
+}
+
+static const TypeInfo dc390_info = {
+    .name = "dc390",
+    .parent = TYPE_AM53C974_DEVICE,
+    .instance_size = sizeof(DC390State),
+    .class_init = dc390_class_init,
+};
+
 static void esp_pci_register_types(void)
 {
     type_register_static(&esp_pci_info);
+    type_register_static(&dc390_info);
 }
 
 type_init(esp_pci_register_types)
commit bde299a2473bc86acb5eb476e9962c7cf70c536b
Author: Hervé Poussineau <hpoussin at reactos.org>
Date:   Sat Aug 4 21:10:05 2012 +0200

    Revert "pci: add some stubs"
    
    This reverts commit 0883c5159f1df05d8761014f65451c3c3b77ebcf.
    
    Those stubs were only used by PCI ESP emulation, which is now
    not compiled on architectures which have no PCI bus support.
    
    Signed-off-by: Hervé Poussineau <hpoussin at reactos.org>
    Signed-off-by: Blue Swirl <blauwirbel at gmail.com>

diff --git a/hw/pci-stub.c b/hw/pci-stub.c
index e083191..134c448 100644
--- a/hw/pci-stub.c
+++ b/hw/pci-stub.c
@@ -34,21 +34,6 @@ static void pci_error_message(Monitor *mon)
     monitor_printf(mon, "PCI devices not supported\n");
 }
 
-void pci_register_bar(PCIDevice *pci_dev, int region_num,
-                      uint8_t type, MemoryRegion *memory)
-{
-}
-
-const VMStateDescription vmstate_pci_device = {
-    .name = "PCIDeviceStub",
-    .version_id = 1,
-    .minimum_version_id = 1,
-    .minimum_version_id_old = 1,
-    .fields      = (VMStateField[]) {
-        VMSTATE_END_OF_LIST()
-    }
-};
-
 int do_pcie_aer_inject_error(Monitor *mon,
                              const QDict *qdict, QObject **ret_data)
 {
commit aebcf56fdedf17f74a97de12f96f3db0751cec6c
Author: Hervé Poussineau <hpoussin at reactos.org>
Date:   Sat Aug 4 21:10:04 2012 +0200

    esp: move PCI emulation to a new file esp-pci.c
    
    sparc machines loose ability to instanciate PCI ESP SCSI adapter,
    which is not a big loose as they don't have PCI bus support.
    
    Signed-off-by: Hervé Poussineau <hpoussin at reactos.org>
    Signed-off-by: Blue Swirl <blauwirbel at gmail.com>

diff --git a/default-configs/pci.mak b/default-configs/pci.mak
index 9febb47..69e18f1 100644
--- a/default-configs/pci.mak
+++ b/default-configs/pci.mak
@@ -18,3 +18,4 @@ CONFIG_IDE_QDEV=y
 CONFIG_IDE_PCI=y
 CONFIG_AHCI=y
 CONFIG_ESP=y
+CONFIG_ESP_PCI=y
diff --git a/hw/Makefile.objs b/hw/Makefile.objs
index 8327e55..12cc141 100644
--- a/hw/Makefile.objs
+++ b/hw/Makefile.objs
@@ -88,6 +88,7 @@ hw-obj-$(CONFIG_OPENCORES_ETH) += opencores_eth.o
 hw-obj-$(CONFIG_LSI_SCSI_PCI) += lsi53c895a.o
 hw-obj-$(CONFIG_MEGASAS_SCSI_PCI) += megasas.o
 hw-obj-$(CONFIG_ESP) += esp.o
+hw-obj-$(CONFIG_ESP_PCI) += esp-pci.o
 
 hw-obj-y += sysbus.o isa-bus.o
 hw-obj-y += qdev-addr.o
diff --git a/hw/esp-pci.c b/hw/esp-pci.c
new file mode 100644
index 0000000..f633a18
--- /dev/null
+++ b/hw/esp-pci.c
@@ -0,0 +1,396 @@
+/*
+ * QEMU ESP/NCR53C9x emulation
+ *
+ * Copyright (c) 2005-2006 Fabrice Bellard
+ * Copyright (c) 2012 Herve Poussineau
+ *
+ * Permission is hereby granted, free of charge, to any person obtaining a copy
+ * of this software and associated documentation files (the "Software"), to deal
+ * in the Software without restriction, including without limitation the rights
+ * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+ * copies of the Software, and to permit persons to whom the Software is
+ * furnished to do so, subject to the following conditions:
+ *
+ * The above copyright notice and this permission notice shall be included in
+ * all copies or substantial portions of the Software.
+ *
+ * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+ * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+ * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
+ * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+ * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
+ * THE SOFTWARE.
+ */
+
+#include "pci.h"
+#include "esp.h"
+#include "trace.h"
+#include "qemu-log.h"
+
+#define DMA_CMD   0x0
+#define DMA_STC   0x1
+#define DMA_SPA   0x2
+#define DMA_WBC   0x3
+#define DMA_WAC   0x4
+#define DMA_STAT  0x5
+#define DMA_SMDLA 0x6
+#define DMA_WMAC  0x7
+
+#define DMA_CMD_MASK   0x03
+#define DMA_CMD_DIAG   0x04
+#define DMA_CMD_MDL    0x10
+#define DMA_CMD_INTE_P 0x20
+#define DMA_CMD_INTE_D 0x40
+#define DMA_CMD_DIR    0x80
+
+#define DMA_STAT_PWDN    0x01
+#define DMA_STAT_ERROR   0x02
+#define DMA_STAT_ABORT   0x04
+#define DMA_STAT_DONE    0x08
+#define DMA_STAT_SCSIINT 0x10
+#define DMA_STAT_BCMBLT  0x20
+
+#define SBAC_STATUS 0x1000
+
+typedef struct PCIESPState {
+    PCIDevice dev;
+    MemoryRegion io;
+    uint32_t dma_regs[8];
+    uint32_t sbac;
+    ESPState esp;
+} PCIESPState;
+
+static void esp_pci_handle_idle(PCIESPState *pci, uint32_t val)
+{
+    trace_esp_pci_dma_idle(val);
+    esp_dma_enable(&pci->esp, 0, 0);
+}
+
+static void esp_pci_handle_blast(PCIESPState *pci, uint32_t val)
+{
+    trace_esp_pci_dma_blast(val);
+    qemu_log_mask(LOG_UNIMP, "am53c974: cmd BLAST not implemented\n");
+}
+
+static void esp_pci_handle_abort(PCIESPState *pci, uint32_t val)
+{
+    trace_esp_pci_dma_abort(val);
+    if (pci->esp.current_req) {
+        scsi_req_cancel(pci->esp.current_req);
+    }
+}
+
+static void esp_pci_handle_start(PCIESPState *pci, uint32_t val)
+{
+    trace_esp_pci_dma_start(val);
+
+    pci->dma_regs[DMA_WBC] = pci->dma_regs[DMA_STC];
+    pci->dma_regs[DMA_WAC] = pci->dma_regs[DMA_SPA];
+    pci->dma_regs[DMA_WMAC] = pci->dma_regs[DMA_SMDLA];
+
+    pci->dma_regs[DMA_STAT] &= ~(DMA_STAT_BCMBLT | DMA_STAT_SCSIINT
+                               | DMA_STAT_DONE | DMA_STAT_ABORT
+                               | DMA_STAT_ERROR | DMA_STAT_PWDN);
+
+    esp_dma_enable(&pci->esp, 0, 1);
+}
+
+static void esp_pci_dma_write(PCIESPState *pci, uint32_t saddr, uint32_t val)
+{
+    trace_esp_pci_dma_write(saddr, pci->dma_regs[saddr], val);
+    switch (saddr) {
+    case DMA_CMD:
+        pci->dma_regs[saddr] = val;
+        switch (val & DMA_CMD_MASK) {
+        case 0x0: /* IDLE */
+            esp_pci_handle_idle(pci, val);
+            break;
+        case 0x1: /* BLAST */
+            esp_pci_handle_blast(pci, val);
+            break;
+        case 0x2: /* ABORT */
+            esp_pci_handle_abort(pci, val);
+            break;
+        case 0x3: /* START */
+            esp_pci_handle_start(pci, val);
+            break;
+        default: /* can't happen */
+            abort();
+        }
+        break;
+    case DMA_STC:
+    case DMA_SPA:
+    case DMA_SMDLA:
+        pci->dma_regs[saddr] = val;
+        break;
+    case DMA_STAT:
+        if (!(pci->sbac & SBAC_STATUS)) {
+            /* clear some bits on write */
+            uint32_t mask = DMA_STAT_ERROR | DMA_STAT_ABORT | DMA_STAT_DONE;
+            pci->dma_regs[DMA_STAT] &= ~(val & mask);
+        }
+        break;
+    default:
+        trace_esp_pci_error_invalid_write_dma(val, saddr);
+        return;
+    }
+}
+
+static uint32_t esp_pci_dma_read(PCIESPState *pci, uint32_t saddr)
+{
+    uint32_t val;
+
+    val = pci->dma_regs[saddr];
+    if (saddr == DMA_STAT) {
+        if (pci->esp.rregs[ESP_RSTAT] & STAT_INT) {
+            val |= DMA_STAT_SCSIINT;
+        }
+        if (pci->sbac & SBAC_STATUS) {
+            pci->dma_regs[DMA_STAT] &= ~(DMA_STAT_ERROR | DMA_STAT_ABORT |
+                                         DMA_STAT_DONE);
+        }
+    }
+
+    trace_esp_pci_dma_read(saddr, val);
+    return val;
+}
+
+static void esp_pci_io_write(void *opaque, target_phys_addr_t addr,
+                             uint64_t val, unsigned int size)
+{
+    PCIESPState *pci = opaque;
+
+    if (size < 4 || addr & 3) {
+        /* need to upgrade request: we only support 4-bytes accesses */
+        uint32_t current = 0, mask;
+        int shift;
+
+        if (addr < 0x40) {
+            current = pci->esp.wregs[addr >> 2];
+        } else if (addr < 0x60) {
+            current = pci->dma_regs[(addr - 0x40) >> 2];
+        } else if (addr < 0x74) {
+            current = pci->sbac;
+        }
+
+        shift = (4 - size) * 8;
+        mask = (~(uint32_t)0 << shift) >> shift;
+
+        shift = ((4 - (addr & 3)) & 3) * 8;
+        val <<= shift;
+        val |= current & ~(mask << shift);
+        addr &= ~3;
+        size = 4;
+    }
+
+    if (addr < 0x40) {
+        /* SCSI core reg */
+        esp_reg_write(&pci->esp, addr >> 2, val);
+    } else if (addr < 0x60) {
+        /* PCI DMA CCB */
+        esp_pci_dma_write(pci, (addr - 0x40) >> 2, val);
+    } else if (addr == 0x70) {
+        /* DMA SCSI Bus and control */
+        trace_esp_pci_sbac_write(pci->sbac, val);
+        pci->sbac = val;
+    } else {
+        trace_esp_pci_error_invalid_write((int)addr);
+    }
+}
+
+static uint64_t esp_pci_io_read(void *opaque, target_phys_addr_t addr,
+                                unsigned int size)
+{
+    PCIESPState *pci = opaque;
+    uint32_t ret;
+
+    if (addr < 0x40) {
+        /* SCSI core reg */
+        ret = esp_reg_read(&pci->esp, addr >> 2);
+    } else if (addr < 0x60) {
+        /* PCI DMA CCB */
+        ret = esp_pci_dma_read(pci, (addr - 0x40) >> 2);
+    } else if (addr == 0x70) {
+        /* DMA SCSI Bus and control */
+        trace_esp_pci_sbac_read(pci->sbac);
+        ret = pci->sbac;
+    } else {
+        /* Invalid region */
+        trace_esp_pci_error_invalid_read((int)addr);
+        ret = 0;
+    }
+
+    /* give only requested data */
+    ret >>= (addr & 3) * 8;
+    ret &= ~(~(uint64_t)0 << (8 * size));
+
+    return ret;
+}
+
+static void esp_pci_dma_memory_rw(PCIESPState *pci, uint8_t *buf, int len,
+                                  DMADirection dir)
+{
+    dma_addr_t addr;
+    DMADirection expected_dir;
+
+    if (pci->dma_regs[DMA_CMD] & DMA_CMD_DIR) {
+        expected_dir = DMA_DIRECTION_FROM_DEVICE;
+    } else {
+        expected_dir = DMA_DIRECTION_TO_DEVICE;
+    }
+
+    if (dir != expected_dir) {
+        trace_esp_pci_error_invalid_dma_direction();
+        return;
+    }
+
+    if (pci->dma_regs[DMA_STAT] & DMA_CMD_MDL) {
+        qemu_log_mask(LOG_UNIMP, "am53c974: MDL transfer not implemented\n");
+    }
+
+    addr = pci->dma_regs[DMA_SPA];
+    if (pci->dma_regs[DMA_WBC] < len) {
+        len = pci->dma_regs[DMA_WBC];
+    }
+
+    pci_dma_rw(&pci->dev, addr, buf, len, dir);
+
+    /* update status registers */
+    pci->dma_regs[DMA_WBC] -= len;
+    pci->dma_regs[DMA_WAC] += len;
+}
+
+static void esp_pci_dma_memory_read(void *opaque, uint8_t *buf, int len)
+{
+    PCIESPState *pci = opaque;
+    esp_pci_dma_memory_rw(pci, buf, len, DMA_DIRECTION_TO_DEVICE);
+}
+
+static void esp_pci_dma_memory_write(void *opaque, uint8_t *buf, int len)
+{
+    PCIESPState *pci = opaque;
+    esp_pci_dma_memory_rw(pci, buf, len, DMA_DIRECTION_FROM_DEVICE);
+}
+
+static const MemoryRegionOps esp_pci_io_ops = {
+    .read = esp_pci_io_read,
+    .write = esp_pci_io_write,
+    .endianness = DEVICE_LITTLE_ENDIAN,
+    .impl = {
+        .min_access_size = 1,
+        .max_access_size = 4,
+    },
+};
+
+static void esp_pci_hard_reset(DeviceState *dev)
+{
+    PCIESPState *pci = DO_UPCAST(PCIESPState, dev.qdev, dev);
+    esp_hard_reset(&pci->esp);
+    pci->dma_regs[DMA_CMD] &= ~(DMA_CMD_DIR | DMA_CMD_INTE_D | DMA_CMD_INTE_P
+                              | DMA_CMD_MDL | DMA_CMD_DIAG | DMA_CMD_MASK);
+    pci->dma_regs[DMA_WBC] &= ~0xffff;
+    pci->dma_regs[DMA_WAC] = 0xffffffff;
+    pci->dma_regs[DMA_STAT] &= ~(DMA_STAT_BCMBLT | DMA_STAT_SCSIINT
+                               | DMA_STAT_DONE | DMA_STAT_ABORT
+                               | DMA_STAT_ERROR);
+    pci->dma_regs[DMA_WMAC] = 0xfffffffd;
+}
+
+static const VMStateDescription vmstate_esp_pci_scsi = {
+    .name = "pciespscsi",
+    .version_id = 0,
+    .minimum_version_id = 0,
+    .minimum_version_id_old = 0,
+    .fields = (VMStateField[]) {
+        VMSTATE_PCI_DEVICE(dev, PCIESPState),
+        VMSTATE_BUFFER_UNSAFE(dma_regs, PCIESPState, 0, 8 * sizeof(uint32_t)),
+        VMSTATE_STRUCT(esp, PCIESPState, 0, vmstate_esp, ESPState),
+        VMSTATE_END_OF_LIST()
+    }
+};
+
+static void esp_pci_command_complete(SCSIRequest *req, uint32_t status,
+                                     size_t resid)
+{
+    ESPState *s = req->hba_private;
+    PCIESPState *pci = container_of(s, PCIESPState, esp);
+
+    esp_command_complete(req, status, resid);
+    pci->dma_regs[DMA_WBC] = 0;
+    pci->dma_regs[DMA_STAT] |= DMA_STAT_DONE;
+}
+
+static const struct SCSIBusInfo esp_pci_scsi_info = {
+    .tcq = false,
+    .max_target = ESP_MAX_DEVS,
+    .max_lun = 7,
+
+    .transfer_data = esp_transfer_data,
+    .complete = esp_pci_command_complete,
+    .cancel = esp_request_cancelled,
+};
+
+static int esp_pci_scsi_init(PCIDevice *dev)
+{
+    PCIESPState *pci = DO_UPCAST(PCIESPState, dev, dev);
+    ESPState *s = &pci->esp;
+    uint8_t *pci_conf;
+
+    pci_conf = pci->dev.config;
+
+    /* Interrupt pin A */
+    pci_conf[PCI_INTERRUPT_PIN] = 0x01;
+
+    s->dma_memory_read = esp_pci_dma_memory_read;
+    s->dma_memory_write = esp_pci_dma_memory_write;
+    s->dma_opaque = pci;
+    s->chip_id = TCHI_AM53C974;
+    memory_region_init_io(&pci->io, &esp_pci_io_ops, pci, "esp-io", 0x80);
+
+    pci_register_bar(&pci->dev, 0, PCI_BASE_ADDRESS_SPACE_IO, &pci->io);
+    s->irq = pci->dev.irq[0];
+
+    scsi_bus_new(&s->bus, &dev->qdev, &esp_pci_scsi_info);
+    if (!dev->qdev.hotplugged) {
+        return scsi_bus_legacy_handle_cmdline(&s->bus);
+    }
+    return 0;
+}
+
+static void esp_pci_scsi_uninit(PCIDevice *d)
+{
+    PCIESPState *pci = DO_UPCAST(PCIESPState, dev, d);
+
+    memory_region_destroy(&pci->io);
+}
+
+static void esp_pci_class_init(ObjectClass *klass, void *data)
+{
+    DeviceClass *dc = DEVICE_CLASS(klass);
+    PCIDeviceClass *k = PCI_DEVICE_CLASS(klass);
+
+    k->init = esp_pci_scsi_init;
+    k->exit = esp_pci_scsi_uninit;
+    k->vendor_id = PCI_VENDOR_ID_AMD;
+    k->device_id = PCI_DEVICE_ID_AMD_SCSI;
+    k->revision = 0x10;
+    k->class_id = PCI_CLASS_STORAGE_SCSI;
+    dc->desc = "AMD Am53c974 PCscsi-PCI SCSI adapter";
+    dc->reset = esp_pci_hard_reset;
+    dc->vmsd = &vmstate_esp_pci_scsi;
+}
+
+static const TypeInfo esp_pci_info = {
+    .name = "am53c974",
+    .parent = TYPE_PCI_DEVICE,
+    .instance_size = sizeof(PCIESPState),
+    .class_init = esp_pci_class_init,
+};
+
+static void esp_pci_register_types(void)
+{
+    type_register_static(&esp_pci_info);
+}
+
+type_init(esp_pci_register_types)
diff --git a/hw/esp.c b/hw/esp.c
index 60c2221..52c46e6 100644
--- a/hw/esp.c
+++ b/hw/esp.c
@@ -24,7 +24,6 @@
  */
 
 #include "sysbus.h"
-#include "pci.h"
 #include "esp.h"
 #include "trace.h"
 #include "qemu-log.h"
@@ -714,370 +713,9 @@ static const TypeInfo sysbus_esp_info = {
     .class_init    = sysbus_esp_class_init,
 };
 
-#define DMA_CMD   0x0
-#define DMA_STC   0x1
-#define DMA_SPA   0x2
-#define DMA_WBC   0x3
-#define DMA_WAC   0x4
-#define DMA_STAT  0x5
-#define DMA_SMDLA 0x6
-#define DMA_WMAC  0x7
-
-#define DMA_CMD_MASK   0x03
-#define DMA_CMD_DIAG   0x04
-#define DMA_CMD_MDL    0x10
-#define DMA_CMD_INTE_P 0x20
-#define DMA_CMD_INTE_D 0x40
-#define DMA_CMD_DIR    0x80
-
-#define DMA_STAT_PWDN    0x01
-#define DMA_STAT_ERROR   0x02
-#define DMA_STAT_ABORT   0x04
-#define DMA_STAT_DONE    0x08
-#define DMA_STAT_SCSIINT 0x10
-#define DMA_STAT_BCMBLT  0x20
-
-#define SBAC_STATUS 0x1000
-
-typedef struct PCIESPState {
-    PCIDevice dev;
-    MemoryRegion io;
-    uint32_t dma_regs[8];
-    uint32_t sbac;
-    ESPState esp;
-} PCIESPState;
-
-static void esp_pci_handle_idle(PCIESPState *pci, uint32_t val)
-{
-    trace_esp_pci_dma_idle(val);
-    esp_dma_enable(&pci->esp, 0, 0);
-}
-
-static void esp_pci_handle_blast(PCIESPState *pci, uint32_t val)
-{
-    trace_esp_pci_dma_blast(val);
-    qemu_log_mask(LOG_UNIMP, "am53c974: cmd BLAST not implemented\n");
-}
-
-static void esp_pci_handle_abort(PCIESPState *pci, uint32_t val)
-{
-    trace_esp_pci_dma_abort(val);
-    if (pci->esp.current_req) {
-        scsi_req_cancel(pci->esp.current_req);
-    }
-}
-
-static void esp_pci_handle_start(PCIESPState *pci, uint32_t val)
-{
-    trace_esp_pci_dma_start(val);
-
-    pci->dma_regs[DMA_WBC] = pci->dma_regs[DMA_STC];
-    pci->dma_regs[DMA_WAC] = pci->dma_regs[DMA_SPA];
-    pci->dma_regs[DMA_WMAC] = pci->dma_regs[DMA_SMDLA];
-
-    pci->dma_regs[DMA_STAT] &= ~(DMA_STAT_BCMBLT | DMA_STAT_SCSIINT
-                               | DMA_STAT_DONE | DMA_STAT_ABORT
-                               | DMA_STAT_ERROR | DMA_STAT_PWDN);
-
-    esp_dma_enable(&pci->esp, 0, 1);
-}
-
-static void esp_pci_dma_write(PCIESPState *pci, uint32_t saddr, uint32_t val)
-{
-    trace_esp_pci_dma_write(saddr, pci->dma_regs[saddr], val);
-    switch (saddr) {
-    case DMA_CMD:
-        pci->dma_regs[saddr] = val;
-        switch (val & DMA_CMD_MASK) {
-        case 0x0: /* IDLE */
-            esp_pci_handle_idle(pci, val);
-            break;
-        case 0x1: /* BLAST */
-            esp_pci_handle_blast(pci, val);
-            break;
-        case 0x2: /* ABORT */
-            esp_pci_handle_abort(pci, val);
-            break;
-        case 0x3: /* START */
-            esp_pci_handle_start(pci, val);
-            break;
-        default: /* can't happen */
-            abort();
-        }
-        break;
-    case DMA_STC:
-    case DMA_SPA:
-    case DMA_SMDLA:
-        pci->dma_regs[saddr] = val;
-        break;
-    case DMA_STAT:
-        if (!(pci->sbac & SBAC_STATUS)) {
-            /* clear some bits on write */
-            uint32_t mask = DMA_STAT_ERROR | DMA_STAT_ABORT | DMA_STAT_DONE;
-            pci->dma_regs[DMA_STAT] &= ~(val & mask);
-        }
-        break;
-    default:
-        trace_esp_pci_error_invalid_write_dma(val, saddr);
-        return;
-    }
-}
-
-static uint32_t esp_pci_dma_read(PCIESPState *pci, uint32_t saddr)
-{
-    uint32_t val;
-
-    val = pci->dma_regs[saddr];
-    if (saddr == DMA_STAT) {
-        if (pci->esp.rregs[ESP_RSTAT] & STAT_INT) {
-            val |= DMA_STAT_SCSIINT;
-        }
-        if (pci->sbac & SBAC_STATUS) {
-            pci->dma_regs[DMA_STAT] &= ~(DMA_STAT_ERROR | DMA_STAT_ABORT |
-                                         DMA_STAT_DONE);
-        }
-    }
-
-    trace_esp_pci_dma_read(saddr, val);
-    return val;
-}
-
-static void esp_pci_io_write(void *opaque, target_phys_addr_t addr,
-                             uint64_t val, unsigned int size)
-{
-    PCIESPState *pci = opaque;
-
-    if (size < 4 || addr & 3) {
-        /* need to upgrade request: we only support 4-bytes accesses */
-        uint32_t current = 0, mask;
-        int shift;
-
-        if (addr < 0x40) {
-            current = pci->esp.wregs[addr >> 2];
-        } else if (addr < 0x60) {
-            current = pci->dma_regs[(addr - 0x40) >> 2];
-        } else if (addr < 0x74) {
-            current = pci->sbac;
-        }
-
-        shift = (4 - size) * 8;
-        mask = (~(uint32_t)0 << shift) >> shift;
-
-        shift = ((4 - (addr & 3)) & 3) * 8;
-        val <<= shift;
-        val |= current & ~(mask << shift);
-        addr &= ~3;
-        size = 4;
-    }
-
-    if (addr < 0x40) {
-        /* SCSI core reg */
-        esp_reg_write(&pci->esp, addr >> 2, val);
-    } else if (addr < 0x60) {
-        /* PCI DMA CCB */
-        esp_pci_dma_write(pci, (addr - 0x40) >> 2, val);
-    } else if (addr == 0x70) {
-        /* DMA SCSI Bus and control */
-        trace_esp_pci_sbac_write(pci->sbac, val);
-        pci->sbac = val;
-    } else {
-        trace_esp_pci_error_invalid_write((int)addr);
-    }
-}
-
-static uint64_t esp_pci_io_read(void *opaque, target_phys_addr_t addr,
-                                unsigned int size)
-{
-    PCIESPState *pci = opaque;
-    uint32_t ret;
-
-    if (addr < 0x40) {
-        /* SCSI core reg */
-        ret = esp_reg_read(&pci->esp, addr >> 2);
-    } else if (addr < 0x60) {
-        /* PCI DMA CCB */
-        ret = esp_pci_dma_read(pci, (addr - 0x40) >> 2);
-    } else if (addr == 0x70) {
-        /* DMA SCSI Bus and control */
-        trace_esp_pci_sbac_read(pci->sbac);
-        ret = pci->sbac;
-    } else {
-        /* Invalid region */
-        trace_esp_pci_error_invalid_read((int)addr);
-        ret = 0;
-    }
-
-    /* give only requested data */
-    ret >>= (addr & 3) * 8;
-    ret &= ~(~(uint64_t)0 << (8 * size));
-
-    return ret;
-}
-
-static void esp_pci_dma_memory_rw(PCIESPState *pci, uint8_t *buf, int len,
-                                  DMADirection dir)
-{
-    dma_addr_t addr;
-    DMADirection expected_dir;
-
-    if (pci->dma_regs[DMA_CMD] & DMA_CMD_DIR) {
-        expected_dir = DMA_DIRECTION_FROM_DEVICE;
-    } else {
-        expected_dir = DMA_DIRECTION_TO_DEVICE;
-    }
-
-    if (dir != expected_dir) {
-        trace_esp_pci_error_invalid_dma_direction();
-        return;
-    }
-
-    if (pci->dma_regs[DMA_STAT] & DMA_CMD_MDL) {
-        qemu_log_mask(LOG_UNIMP, "am53c974: MDL transfer not implemented\n");
-    }
-
-    addr = pci->dma_regs[DMA_SPA];
-    if (pci->dma_regs[DMA_WBC] < len) {
-        len = pci->dma_regs[DMA_WBC];
-    }
-
-    pci_dma_rw(&pci->dev, addr, buf, len, dir);
-
-    /* update status registers */
-    pci->dma_regs[DMA_WBC] -= len;
-    pci->dma_regs[DMA_WAC] += len;
-}
-
-static void esp_pci_dma_memory_read(void *opaque, uint8_t *buf, int len)
-{
-    PCIESPState *pci = opaque;
-    esp_pci_dma_memory_rw(pci, buf, len, DMA_DIRECTION_TO_DEVICE);
-}
-
-static void esp_pci_dma_memory_write(void *opaque, uint8_t *buf, int len)
-{
-    PCIESPState *pci = opaque;
-    esp_pci_dma_memory_rw(pci, buf, len, DMA_DIRECTION_FROM_DEVICE);
-}
-
-static const MemoryRegionOps esp_pci_io_ops = {
-    .read = esp_pci_io_read,
-    .write = esp_pci_io_write,
-    .endianness = DEVICE_LITTLE_ENDIAN,
-    .impl = {
-        .min_access_size = 1,
-        .max_access_size = 4,
-    },
-};
-
-static void esp_pci_hard_reset(DeviceState *dev)
-{
-    PCIESPState *pci = DO_UPCAST(PCIESPState, dev.qdev, dev);
-    esp_hard_reset(&pci->esp);
-    pci->dma_regs[DMA_CMD] &= ~(DMA_CMD_DIR | DMA_CMD_INTE_D | DMA_CMD_INTE_P
-                              | DMA_CMD_MDL | DMA_CMD_DIAG | DMA_CMD_MASK);
-    pci->dma_regs[DMA_WBC] &= ~0xffff;
-    pci->dma_regs[DMA_WAC] = 0xffffffff;
-    pci->dma_regs[DMA_STAT] &= ~(DMA_STAT_BCMBLT | DMA_STAT_SCSIINT
-                               | DMA_STAT_DONE | DMA_STAT_ABORT
-                               | DMA_STAT_ERROR);
-    pci->dma_regs[DMA_WMAC] = 0xfffffffd;
-}
-
-static const VMStateDescription vmstate_esp_pci_scsi = {
-    .name = "pciespscsi",
-    .version_id = 0,
-    .minimum_version_id = 0,
-    .minimum_version_id_old = 0,
-    .fields = (VMStateField[]) {
-        VMSTATE_PCI_DEVICE(dev, PCIESPState),
-        VMSTATE_BUFFER_UNSAFE(dma_regs, PCIESPState, 0, 8 * sizeof(uint32_t)),
-        VMSTATE_STRUCT(esp, PCIESPState, 0, vmstate_esp, ESPState),
-        VMSTATE_END_OF_LIST()
-    }
-};
-
-static void esp_pci_command_complete(SCSIRequest *req, uint32_t status,
-                                     size_t resid)
-{
-    ESPState *s = req->hba_private;
-    PCIESPState *pci = container_of(s, PCIESPState, esp);
-
-    esp_command_complete(req, status, resid);
-    pci->dma_regs[DMA_WBC] = 0;
-    pci->dma_regs[DMA_STAT] |= DMA_STAT_DONE;
-}
-
-static const struct SCSIBusInfo esp_pci_scsi_info = {
-    .tcq = false,
-    .max_target = ESP_MAX_DEVS,
-    .max_lun = 7,
-
-    .transfer_data = esp_transfer_data,
-    .complete = esp_pci_command_complete,
-    .cancel = esp_request_cancelled,
-};
-
-static int esp_pci_scsi_init(PCIDevice *dev)
-{
-    PCIESPState *pci = DO_UPCAST(PCIESPState, dev, dev);
-    ESPState *s = &pci->esp;
-    uint8_t *pci_conf;
-
-    pci_conf = pci->dev.config;
-
-    /* Interrupt pin A */
-    pci_conf[PCI_INTERRUPT_PIN] = 0x01;
-
-    s->dma_memory_read = esp_pci_dma_memory_read;
-    s->dma_memory_write = esp_pci_dma_memory_write;
-    s->dma_opaque = pci;
-    s->chip_id = TCHI_AM53C974;
-    memory_region_init_io(&pci->io, &esp_pci_io_ops, pci, "esp-io", 0x80);
-
-    pci_register_bar(&pci->dev, 0, PCI_BASE_ADDRESS_SPACE_IO, &pci->io);
-    s->irq = pci->dev.irq[0];
-
-    scsi_bus_new(&s->bus, &dev->qdev, &esp_pci_scsi_info);
-    if (!dev->qdev.hotplugged) {
-        return scsi_bus_legacy_handle_cmdline(&s->bus);
-    }
-    return 0;
-}
-
-static void esp_pci_scsi_uninit(PCIDevice *d)
-{
-    PCIESPState *pci = DO_UPCAST(PCIESPState, dev, d);
-
-    memory_region_destroy(&pci->io);
-}
-
-static void esp_pci_class_init(ObjectClass *klass, void *data)
-{
-    DeviceClass *dc = DEVICE_CLASS(klass);
-    PCIDeviceClass *k = PCI_DEVICE_CLASS(klass);
-
-    k->init = esp_pci_scsi_init;
-    k->exit = esp_pci_scsi_uninit;
-    k->vendor_id = PCI_VENDOR_ID_AMD;
-    k->device_id = PCI_DEVICE_ID_AMD_SCSI;
-    k->revision = 0x10;
-    k->class_id = PCI_CLASS_STORAGE_SCSI;
-    dc->desc = "AMD Am53c974 PCscsi-PCI SCSI adapter";
-    dc->reset = esp_pci_hard_reset;
-    dc->vmsd = &vmstate_esp_pci_scsi;
-}
-
-static const TypeInfo esp_pci_info = {
-    .name = "am53c974",
-    .parent = TYPE_PCI_DEVICE,
-    .instance_size = sizeof(PCIESPState),
-    .class_init = esp_pci_class_init,
-};
-
 static void esp_register_types(void)
 {
     type_register_static(&sysbus_esp_info);
-    type_register_static(&esp_pci_info);
 }
 
 type_init(esp_register_types)
commit 9c7e23fc4d37ad99e5d8cd47286b840184cf3511
Author: Hervé Poussineau <hpoussin at reactos.org>
Date:   Sat Aug 4 21:10:03 2012 +0200

    esp: move some definitions to header file
    
    These will be used by next commits.
    
    Signed-off-by: Hervé Poussineau <hpoussin at reactos.org>
    Signed-off-by: Blue Swirl <blauwirbel at gmail.com>

diff --git a/hw/esp.c b/hw/esp.c
index 77f5707..60c2221 100644
--- a/hw/esp.c
+++ b/hw/esp.c
@@ -25,7 +25,6 @@
 
 #include "sysbus.h"
 #include "pci.h"
-#include "scsi.h"
 #include "esp.h"
 #include "trace.h"
 #include "qemu-log.h"
@@ -38,114 +37,6 @@
  * http://www.ibiblio.org/pub/historic-linux/early-ports/Sparc/NCR/NCR53C9X.txt
  */
 
-#define ESP_REGS 16
-#define TI_BUFSZ 16
-
-typedef struct ESPState ESPState;
-
-struct ESPState {
-    uint8_t rregs[ESP_REGS];
-    uint8_t wregs[ESP_REGS];
-    qemu_irq irq;
-    uint8_t chip_id;
-    int32_t ti_size;
-    uint32_t ti_rptr, ti_wptr;
-    uint32_t status;
-    uint32_t dma;
-    uint8_t ti_buf[TI_BUFSZ];
-    SCSIBus bus;
-    SCSIDevice *current_dev;
-    SCSIRequest *current_req;
-    uint8_t cmdbuf[TI_BUFSZ];
-    uint32_t cmdlen;
-    uint32_t do_cmd;
-
-    /* The amount of data left in the current DMA transfer.  */
-    uint32_t dma_left;
-    /* The size of the current DMA transfer.  Zero if no transfer is in
-       progress.  */
-    uint32_t dma_counter;
-    int dma_enabled;
-
-    uint32_t async_len;
-    uint8_t *async_buf;
-
-    ESPDMAMemoryReadWriteFunc dma_memory_read;
-    ESPDMAMemoryReadWriteFunc dma_memory_write;
-    void *dma_opaque;
-    void (*dma_cb)(ESPState *s);
-};
-
-#define ESP_TCLO   0x0
-#define ESP_TCMID  0x1
-#define ESP_FIFO   0x2
-#define ESP_CMD    0x3
-#define ESP_RSTAT  0x4
-#define ESP_WBUSID 0x4
-#define ESP_RINTR  0x5
-#define ESP_WSEL   0x5
-#define ESP_RSEQ   0x6
-#define ESP_WSYNTP 0x6
-#define ESP_RFLAGS 0x7
-#define ESP_WSYNO  0x7
-#define ESP_CFG1   0x8
-#define ESP_RRES1  0x9
-#define ESP_WCCF   0x9
-#define ESP_RRES2  0xa
-#define ESP_WTEST  0xa
-#define ESP_CFG2   0xb
-#define ESP_CFG3   0xc
-#define ESP_RES3   0xd
-#define ESP_TCHI   0xe
-#define ESP_RES4   0xf
-
-#define CMD_DMA 0x80
-#define CMD_CMD 0x7f
-
-#define CMD_NOP      0x00
-#define CMD_FLUSH    0x01
-#define CMD_RESET    0x02
-#define CMD_BUSRESET 0x03
-#define CMD_TI       0x10
-#define CMD_ICCS     0x11
-#define CMD_MSGACC   0x12
-#define CMD_PAD      0x18
-#define CMD_SATN     0x1a
-#define CMD_RSTATN   0x1b
-#define CMD_SEL      0x41
-#define CMD_SELATN   0x42
-#define CMD_SELATNS  0x43
-#define CMD_ENSEL    0x44
-#define CMD_DISSEL   0x45
-
-#define STAT_DO 0x00
-#define STAT_DI 0x01
-#define STAT_CD 0x02
-#define STAT_ST 0x03
-#define STAT_MO 0x06
-#define STAT_MI 0x07
-#define STAT_PIO_MASK 0x06
-
-#define STAT_TC 0x10
-#define STAT_PE 0x20
-#define STAT_GE 0x40
-#define STAT_INT 0x80
-
-#define BUSID_DID 0x07
-
-#define INTR_FC 0x08
-#define INTR_BS 0x10
-#define INTR_DC 0x20
-#define INTR_RST 0x80
-
-#define SEQ_0 0x0
-#define SEQ_CD 0x4
-
-#define CFG1_RESREPT 0x40
-
-#define TCHI_FAS100A 0x4
-#define TCHI_AM53C974 0x12
-
 static void esp_raise_irq(ESPState *s)
 {
     if (!(s->rregs[ESP_RSTAT] & STAT_INT)) {
@@ -164,7 +55,7 @@ static void esp_lower_irq(ESPState *s)
     }
 }
 
-static void esp_dma_enable(ESPState *s, int irq, int level)
+void esp_dma_enable(ESPState *s, int irq, int level)
 {
     if (level) {
         s->dma_enabled = 1;
@@ -179,7 +70,7 @@ static void esp_dma_enable(ESPState *s, int irq, int level)
     }
 }
 
-static void esp_request_cancelled(SCSIRequest *req)
+void esp_request_cancelled(SCSIRequest *req)
 {
     ESPState *s = req->hba_private;
 
@@ -388,7 +279,7 @@ static void esp_do_dma(ESPState *s)
     esp_dma_done(s);
 }
 
-static void esp_command_complete(SCSIRequest *req, uint32_t status,
+void esp_command_complete(SCSIRequest *req, uint32_t status,
                                  size_t resid)
 {
     ESPState *s = req->hba_private;
@@ -413,7 +304,7 @@ static void esp_command_complete(SCSIRequest *req, uint32_t status,
     }
 }
 
-static void esp_transfer_data(SCSIRequest *req, uint32_t len)
+void esp_transfer_data(SCSIRequest *req, uint32_t len)
 {
     ESPState *s = req->hba_private;
 
@@ -465,7 +356,7 @@ static void handle_ti(ESPState *s)
     }
 }
 
-static void esp_hard_reset(ESPState *s)
+void esp_hard_reset(ESPState *s)
 {
     memset(s->rregs, 0, ESP_REGS);
     memset(s->wregs, 0, ESP_REGS);
@@ -493,7 +384,7 @@ static void parent_esp_reset(ESPState *s, int irq, int level)
     }
 }
 
-static uint64_t esp_reg_read(ESPState *s, uint32_t saddr)
+uint64_t esp_reg_read(ESPState *s, uint32_t saddr)
 {
     uint32_t old_val;
 
@@ -533,7 +424,7 @@ static uint64_t esp_reg_read(ESPState *s, uint32_t saddr)
     return s->rregs[saddr];
 }
 
-static void esp_reg_write(ESPState *s, uint32_t saddr, uint64_t val)
+void esp_reg_write(ESPState *s, uint32_t saddr, uint64_t val)
 {
     trace_esp_mem_writeb(saddr, s->wregs[saddr], val);
     switch (saddr) {
@@ -660,7 +551,7 @@ static bool esp_mem_accepts(void *opaque, target_phys_addr_t addr,
     return (size == 1) || (is_write && size == 4);
 }
 
-static const VMStateDescription vmstate_esp = {
+const VMStateDescription vmstate_esp = {
     .name ="esp",
     .version_id = 3,
     .minimum_version_id = 3,
diff --git a/hw/esp.h b/hw/esp.h
index 62bfd4d..fa855e2 100644
--- a/hw/esp.h
+++ b/hw/esp.h
@@ -1,6 +1,8 @@
 #ifndef QEMU_HW_ESP_H
 #define QEMU_HW_ESP_H
 
+#include "scsi.h"
+
 /* esp.c */
 #define ESP_MAX_DEVS 7
 typedef void (*ESPDMAMemoryReadWriteFunc)(void *opaque, uint8_t *buf, int len);
@@ -10,4 +12,121 @@ void esp_init(target_phys_addr_t espaddr, int it_shift,
               void *dma_opaque, qemu_irq irq, qemu_irq *reset,
               qemu_irq *dma_enable);
 
+#define ESP_REGS 16
+#define TI_BUFSZ 16
+
+typedef struct ESPState ESPState;
+
+struct ESPState {
+    uint8_t rregs[ESP_REGS];
+    uint8_t wregs[ESP_REGS];
+    qemu_irq irq;
+    uint8_t chip_id;
+    int32_t ti_size;
+    uint32_t ti_rptr, ti_wptr;
+    uint32_t status;
+    uint32_t dma;
+    uint8_t ti_buf[TI_BUFSZ];
+    SCSIBus bus;
+    SCSIDevice *current_dev;
+    SCSIRequest *current_req;
+    uint8_t cmdbuf[TI_BUFSZ];
+    uint32_t cmdlen;
+    uint32_t do_cmd;
+
+    /* The amount of data left in the current DMA transfer.  */
+    uint32_t dma_left;
+    /* The size of the current DMA transfer.  Zero if no transfer is in
+       progress.  */
+    uint32_t dma_counter;
+    int dma_enabled;
+
+    uint32_t async_len;
+    uint8_t *async_buf;
+
+    ESPDMAMemoryReadWriteFunc dma_memory_read;
+    ESPDMAMemoryReadWriteFunc dma_memory_write;
+    void *dma_opaque;
+    void (*dma_cb)(ESPState *s);
+};
+
+#define ESP_TCLO   0x0
+#define ESP_TCMID  0x1
+#define ESP_FIFO   0x2
+#define ESP_CMD    0x3
+#define ESP_RSTAT  0x4
+#define ESP_WBUSID 0x4
+#define ESP_RINTR  0x5
+#define ESP_WSEL   0x5
+#define ESP_RSEQ   0x6
+#define ESP_WSYNTP 0x6
+#define ESP_RFLAGS 0x7
+#define ESP_WSYNO  0x7
+#define ESP_CFG1   0x8
+#define ESP_RRES1  0x9
+#define ESP_WCCF   0x9
+#define ESP_RRES2  0xa
+#define ESP_WTEST  0xa
+#define ESP_CFG2   0xb
+#define ESP_CFG3   0xc
+#define ESP_RES3   0xd
+#define ESP_TCHI   0xe
+#define ESP_RES4   0xf
+
+#define CMD_DMA 0x80
+#define CMD_CMD 0x7f
+
+#define CMD_NOP      0x00
+#define CMD_FLUSH    0x01
+#define CMD_RESET    0x02
+#define CMD_BUSRESET 0x03
+#define CMD_TI       0x10
+#define CMD_ICCS     0x11
+#define CMD_MSGACC   0x12
+#define CMD_PAD      0x18
+#define CMD_SATN     0x1a
+#define CMD_RSTATN   0x1b
+#define CMD_SEL      0x41
+#define CMD_SELATN   0x42
+#define CMD_SELATNS  0x43
+#define CMD_ENSEL    0x44
+#define CMD_DISSEL   0x45
+
+#define STAT_DO 0x00
+#define STAT_DI 0x01
+#define STAT_CD 0x02
+#define STAT_ST 0x03
+#define STAT_MO 0x06
+#define STAT_MI 0x07
+#define STAT_PIO_MASK 0x06
+
+#define STAT_TC 0x10
+#define STAT_PE 0x20
+#define STAT_GE 0x40
+#define STAT_INT 0x80
+
+#define BUSID_DID 0x07
+
+#define INTR_FC 0x08
+#define INTR_BS 0x10
+#define INTR_DC 0x20
+#define INTR_RST 0x80
+
+#define SEQ_0 0x0
+#define SEQ_CD 0x4
+
+#define CFG1_RESREPT 0x40
+
+#define TCHI_FAS100A 0x4
+#define TCHI_AM53C974 0x12
+
+void esp_dma_enable(ESPState *s, int irq, int level);
+void esp_request_cancelled(SCSIRequest *req);
+void esp_command_complete(SCSIRequest *req, uint32_t status, size_t resid);
+void esp_transfer_data(SCSIRequest *req, uint32_t len);
+void esp_hard_reset(ESPState *s);
+uint64_t esp_reg_read(ESPState *s, uint32_t saddr);
+void esp_reg_write(ESPState *s, uint32_t saddr, uint64_t val);
+extern const VMStateDescription vmstate_esp;
+
 #endif
commit 5222aaf223e52961cabeb7cabc579892ccd8bc59
Author: Paolo Bonzini <pbonzini at redhat.com>
Date:   Thu Aug 9 11:00:22 2012 +0200

    scsi-disk: add support for the UNMAP command
    
    The unmap command can reuse the same infrastructure as MODE SELECT
    for reading the descriptor list into memory.  The descriptors are
    processed sequentially.
    
    Signed-off-by: Paolo Bonzini <pbonzini at redhat.com>

diff --git a/hw/scsi-disk.c b/hw/scsi-disk.c
index 584aec1..e71809e 100644
--- a/hw/scsi-disk.c
+++ b/hw/scsi-disk.c
@@ -637,7 +637,7 @@ static int scsi_disk_emulate_inquiry(SCSIRequest *req, uint8_t *outbuf)
         {
             buflen = 8;
             outbuf[4] = 0;
-            outbuf[5] = 0x60; /* write_same 10/16 supported */
+            outbuf[5] = 0xe0; /* unmap & write_same 10/16 all supported */
             outbuf[6] = s->qdev.conf.discard_granularity ? 2 : 1;
             outbuf[7] = 0;
             break;
@@ -1449,6 +1449,89 @@ invalid_field:
     return;
 }
 
+typedef struct UnmapCBData {
+    SCSIDiskReq *r;
+    uint8_t *inbuf;
+    int count;
+} UnmapCBData;
+
+static void scsi_unmap_complete(void *opaque, int ret)
+{
+    UnmapCBData *data = opaque;
+    SCSIDiskReq *r = data->r;
+    SCSIDiskState *s = DO_UPCAST(SCSIDiskState, qdev, r->req.dev);
+    uint64_t sector_num;
+    uint32 nb_sectors;
+
+    r->req.aiocb = NULL;
+    if (ret < 0) {
+        if (scsi_handle_rw_error(r, -ret)) {
+            goto done;
+        }
+    }
+
+    if (data->count > 0 && !r->req.io_canceled) {
+        sector_num = ldq_be_p(&data->inbuf[0]);
+        nb_sectors = ldl_be_p(&data->inbuf[8]) & 0xffffffffULL;
+        if (sector_num > sector_num + nb_sectors ||
+            sector_num + nb_sectors - 1 > s->qdev.max_lba) {
+            scsi_check_condition(r, SENSE_CODE(LBA_OUT_OF_RANGE));
+            goto done;
+        }
+
+        r->req.aiocb = bdrv_aio_discard(s->qdev.conf.bs,
+                                        sector_num * (s->qdev.blocksize / 512),
+                                        nb_sectors * (s->qdev.blocksize / 512),
+                                        scsi_unmap_complete, data);
+        data->count--;
+        data->inbuf += 16;
+        return;
+    }
+
+done:
+    if (data->count == 0) {
+        scsi_req_complete(&r->req, GOOD);
+    }
+    if (!r->req.io_canceled) {
+        scsi_req_unref(&r->req);
+    }
+    g_free(data);
+}
+
+static void scsi_disk_emulate_unmap(SCSIDiskReq *r, uint8_t *inbuf)
+{
+    uint8_t *p = inbuf;
+    int len = r->req.cmd.xfer;
+    UnmapCBData *data;
+
+    if (len < 8) {
+        goto invalid_param_len;
+    }
+    if (len < lduw_be_p(&p[0]) + 2) {
+        goto invalid_param_len;
+    }
+    if (len < lduw_be_p(&p[2]) + 8) {
+        goto invalid_param_len;
+    }
+    if (lduw_be_p(&p[2]) & 15) {
+        goto invalid_param_len;
+    }
+
+    data = g_new0(UnmapCBData, 1);
+    data->r = r;
+    data->inbuf = &p[8];
+    data->count = lduw_be_p(&p[2]) >> 4;
+
+    /* The matching unref is in scsi_unmap_complete, before data is freed.  */
+    scsi_req_ref(&r->req);
+    scsi_unmap_complete(data, 0);
+    return;
+
+invalid_param_len:
+    scsi_check_condition(r, SENSE_CODE(INVALID_PARAM_LEN));
+    return;
+}
+
 static void scsi_disk_emulate_write_data(SCSIRequest *req)
 {
     SCSIDiskReq *r = DO_UPCAST(SCSIDiskReq, req, req);
@@ -1468,6 +1551,10 @@ static void scsi_disk_emulate_write_data(SCSIRequest *req)
         scsi_disk_emulate_mode_select(r, r->iov.iov_base);
         break;
 
+    case UNMAP:
+        scsi_disk_emulate_unmap(r, r->iov.iov_base);
+        break;
+
     default:
         abort();
     }
@@ -1702,6 +1789,9 @@ static int32_t scsi_disk_emulate_command(SCSIRequest *req, uint8_t *buf)
     case MODE_SELECT_10:
         DPRINTF("Mode Select(10) (len %lu)\n", (long)r->req.cmd.xfer);
         break;
+    case UNMAP:
+        DPRINTF("Unmap (len %lu)\n", (long)r->req.cmd.xfer);
+        break;
     case WRITE_SAME_10:
         nb_sectors = lduw_be_p(&req->cmd.buf[7]);
         goto write_same;
@@ -2067,6 +2157,7 @@ static const SCSIReqOps *const scsi_disk_reqops_dispatch[256] = {
     [SEEK_10]                         = &scsi_disk_emulate_reqops,
     [MODE_SELECT]                     = &scsi_disk_emulate_reqops,
     [MODE_SELECT_10]                  = &scsi_disk_emulate_reqops,
+    [UNMAP]                           = &scsi_disk_emulate_reqops,
     [WRITE_SAME_10]                   = &scsi_disk_emulate_reqops,
     [WRITE_SAME_16]                   = &scsi_disk_emulate_reqops,
 
commit a084a703df9ab896c9d30ac479e1388e5e4cafb0
Author: Paolo Bonzini <pbonzini at redhat.com>
Date:   Thu Aug 9 13:34:53 2012 +0200

    scsi-disk: improve out-of-range LBA detection for WRITE SAME
    
    Signed-off-by: Paolo Bonzini <pbonzini at redhat.com>

diff --git a/hw/scsi-disk.c b/hw/scsi-disk.c
index 9af9d18..584aec1 100644
--- a/hw/scsi-disk.c
+++ b/hw/scsi-disk.c
@@ -1712,7 +1712,8 @@ static int32_t scsi_disk_emulate_command(SCSIRequest *req, uint8_t *buf)
             scsi_check_condition(r, SENSE_CODE(WRITE_PROTECTED));
             return 0;
         }
-        if (r->req.cmd.lba > s->qdev.max_lba) {
+        if (r->req.cmd.lba > r->req.cmd.lba + nb_sectors ||
+            r->req.cmd.lba + nb_sectors - 1 > s->qdev.max_lba) {
             goto illegal_lba;
         }
 
commit 46e3f30e3c81e23c07f16b2193dfb6928646c205
Author: Paolo Bonzini <pbonzini at redhat.com>
Date:   Thu Aug 9 11:33:26 2012 +0200

    scsi-disk: more assertions and resets for aiocb
    
    Leaving the aiocb to a non-NULL value leads to an assertion failure when
    rerror/werror are set to stop or enospc, and the operation is retried.
    scsi-disk checks that the aiocb member is NULL before filling it.
    
    This patch correctly resets the aiocb to NULL values everywhere,
    and adds the dual assertion that the aiocb was non-NULL before
    calling bdrv_acct_done.
    
    Signed-off-by: Paolo Bonzini <pbonzini at redhat.com>

diff --git a/hw/scsi-disk.c b/hw/scsi-disk.c
index a9c7279..9af9d18 100644
--- a/hw/scsi-disk.c
+++ b/hw/scsi-disk.c
@@ -175,6 +175,8 @@ static void scsi_aio_complete(void *opaque, int ret)
     SCSIDiskReq *r = (SCSIDiskReq *)opaque;
     SCSIDiskState *s = DO_UPCAST(SCSIDiskState, qdev, r->req.dev);
 
+    assert(r->req.aiocb != NULL);
+    r->req.aiocb = NULL;
     bdrv_acct_done(s->qdev.conf.bs, &r->acct);
 
     if (ret < 0) {
@@ -238,10 +240,9 @@ static void scsi_dma_complete(void *opaque, int ret)
     SCSIDiskReq *r = (SCSIDiskReq *)opaque;
     SCSIDiskState *s = DO_UPCAST(SCSIDiskState, qdev, r->req.dev);
 
-    if (r->req.aiocb != NULL) {
-        r->req.aiocb = NULL;
-        bdrv_acct_done(s->qdev.conf.bs, &r->acct);
-    }
+    assert(r->req.aiocb != NULL);
+    r->req.aiocb = NULL;
+    bdrv_acct_done(s->qdev.conf.bs, &r->acct);
 
     if (ret < 0) {
         if (scsi_handle_rw_error(r, -ret)) {
@@ -270,10 +271,9 @@ static void scsi_read_complete(void * opaque, int ret)
     SCSIDiskState *s = DO_UPCAST(SCSIDiskState, qdev, r->req.dev);
     int n;
 
-    if (r->req.aiocb != NULL) {
-        r->req.aiocb = NULL;
-        bdrv_acct_done(s->qdev.conf.bs, &r->acct);
-    }
+    assert(r->req.aiocb != NULL);
+    r->req.aiocb = NULL;
+    bdrv_acct_done(s->qdev.conf.bs, &r->acct);
 
     if (ret < 0) {
         if (scsi_handle_rw_error(r, -ret)) {
commit 96fda35ac477e954eee989d6a3ae9e686cc361d6
Author: Peter Maydell <peter.maydell at linaro.org>
Date:   Thu Jul 26 15:35:17 2012 +0100

    kvm: Add documentation comment for kvm_irqchip_in_kernel()
    
    Now we've cleared out the architecture-independent uses of
    kvm_irqchip_in_kernel(), we can add a doc comment describing
    what it means.
    
    Signed-off-by: Peter Maydell <peter.maydell at linaro.org>
    Signed-off-by: Avi Kivity <avi at redhat.com>

diff --git a/kvm.h b/kvm.h
index 444ed2e..5b8f588 100644
--- a/kvm.h
+++ b/kvm.h
@@ -31,6 +31,17 @@ extern bool kvm_gsi_routing_allowed;
 
 #if defined CONFIG_KVM || !defined NEED_CPU_H
 #define kvm_enabled()           (kvm_allowed)
+/**
+ * kvm_irqchip_in_kernel:
+ *
+ * Returns: true if the user asked us to create an in-kernel
+ * irqchip via the "kernel_irqchip=on" machine option.
+ * What this actually means is architecture and machine model
+ * specific: on PC, for instance, it means that the LAPIC,
+ * IOAPIC and PIT are all in kernel. This function should never
+ * be used from generic target-independent code: use one of the
+ * following functions or some other specific check instead.
+ */
 #define kvm_irqchip_in_kernel() (kvm_kernel_irqchip)
 
 /**
commit f3e1bed8daa35726d2731dd2a010fb91a5bb3792
Author: Peter Maydell <peter.maydell at linaro.org>
Date:   Thu Jul 26 15:35:16 2012 +0100

    kvm: Decouple 'GSI routing' from 'kernel irqchip'
    
    Don't assume having an in-kernel irqchip means that GSI
    routing is enabled.
    
    Signed-off-by: Peter Maydell <peter.maydell at linaro.org>
    Signed-off-by: Avi Kivity <avi at redhat.com>

diff --git a/kvm-all.c b/kvm-all.c
index b9a613e..34b02c1 100644
--- a/kvm-all.c
+++ b/kvm-all.c
@@ -103,6 +103,7 @@ bool kvm_kernel_irqchip;
 bool kvm_async_interrupts_allowed;
 bool kvm_irqfds_allowed;
 bool kvm_msi_via_irqfd_allowed;
+bool kvm_gsi_routing_allowed;
 
 static const KVMCapabilityInfo kvm_required_capabilites[] = {
     KVM_CAP_INFO(USER_MEMORY),
@@ -1099,7 +1100,7 @@ int kvm_irqchip_add_msi_route(KVMState *s, MSIMessage msg)
     struct kvm_irq_routing_entry kroute;
     int virq;
 
-    if (!kvm_irqchip_in_kernel()) {
+    if (!kvm_gsi_routing_enabled()) {
         return -ENOSYS;
     }
 
diff --git a/kvm-stub.c b/kvm-stub.c
index 158bb7b..94c9ea1 100644
--- a/kvm-stub.c
+++ b/kvm-stub.c
@@ -22,6 +22,7 @@ bool kvm_kernel_irqchip;
 bool kvm_async_interrupts_allowed;
 bool kvm_irqfds_allowed;
 bool kvm_msi_via_irqfd_allowed;
+bool kvm_gsi_routing_allowed;
 
 int kvm_init_vcpu(CPUArchState *env)
 {
diff --git a/kvm.h b/kvm.h
index 34d32c7..444ed2e 100644
--- a/kvm.h
+++ b/kvm.h
@@ -27,6 +27,7 @@ extern bool kvm_kernel_irqchip;
 extern bool kvm_async_interrupts_allowed;
 extern bool kvm_irqfds_allowed;
 extern bool kvm_msi_via_irqfd_allowed;
+extern bool kvm_gsi_routing_allowed;
 
 #if defined CONFIG_KVM || !defined NEED_CPU_H
 #define kvm_enabled()           (kvm_allowed)
@@ -60,12 +61,21 @@ extern bool kvm_msi_via_irqfd_allowed;
  */
 #define kvm_msi_via_irqfd_enabled() (kvm_msi_via_irqfd_allowed)
 
+/**
+ * kvm_gsi_routing_enabled:
+ *
+ * Returns: true if GSI routing is enabled (ie the kernel supports
+ * it and we're running in a configuration that permits it).
+ */
+#define kvm_gsi_routing_enabled() (kvm_gsi_routing_allowed)
+
 #else
 #define kvm_enabled()           (0)
 #define kvm_irqchip_in_kernel() (false)
 #define kvm_async_interrupts_enabled() (false)
 #define kvm_irqfds_enabled() (false)
 #define kvm_msi_via_irqfd_enabled() (false)
+#define kvm_gsi_routing_allowed() (false)
 #endif
 
 struct kvm_run;
diff --git a/target-i386/kvm.c b/target-i386/kvm.c
index 7a874ea..696b14a 100644
--- a/target-i386/kvm.c
+++ b/target-i386/kvm.c
@@ -2049,8 +2049,9 @@ void kvm_arch_init_irq_routing(KVMState *s)
     }
     /* We know at this point that we're using the in-kernel
      * irqchip, so we can use irqfds, and on x86 we know
-     * we can use msi via irqfd.
+     * we can use msi via irqfd and GSI routing.
      */
     kvm_irqfds_allowed = true;
     kvm_msi_via_irqfd_allowed = true;
+    kvm_gsi_routing_allowed = true;
 }
commit 614e41bc26dda751321da47acb1f9cb287b52085
Author: Peter Maydell <peter.maydell at linaro.org>
Date:   Thu Jul 26 15:35:15 2012 +0100

    kvm: Decouple 'MSI routing via irqfds' from 'kernel irqchip'
    
    Decouple another x86-specific assumption about what irqchips imply.
    
    Signed-off-by: Peter Maydell <peter.maydell at linaro.org>
    Signed-off-by: Avi Kivity <avi at redhat.com>

diff --git a/hw/virtio-pci.c b/hw/virtio-pci.c
index 125eded..5e6e09e 100644
--- a/hw/virtio-pci.c
+++ b/hw/virtio-pci.c
@@ -627,7 +627,7 @@ static int virtio_pci_set_guest_notifiers(void *opaque, bool assign)
     int r, n;
 
     /* Must unset vector notifier while guest notifier is still assigned */
-    if (kvm_irqchip_in_kernel() && !assign) {
+    if (kvm_msi_via_irqfd_enabled() && !assign) {
         msix_unset_vector_notifiers(&proxy->pci_dev);
         g_free(proxy->vector_irqfd);
         proxy->vector_irqfd = NULL;
@@ -645,7 +645,7 @@ static int virtio_pci_set_guest_notifiers(void *opaque, bool assign)
     }
 
     /* Must set vector notifier after guest notifier has been assigned */
-    if (kvm_irqchip_in_kernel() && assign) {
+    if (kvm_msi_via_irqfd_enabled() && assign) {
         proxy->vector_irqfd =
             g_malloc0(sizeof(*proxy->vector_irqfd) *
                       msix_nr_vectors_allocated(&proxy->pci_dev));
diff --git a/kvm-all.c b/kvm-all.c
index 0704055..b9a613e 100644
--- a/kvm-all.c
+++ b/kvm-all.c
@@ -102,6 +102,7 @@ KVMState *kvm_state;
 bool kvm_kernel_irqchip;
 bool kvm_async_interrupts_allowed;
 bool kvm_irqfds_allowed;
+bool kvm_msi_via_irqfd_allowed;
 
 static const KVMCapabilityInfo kvm_required_capabilites[] = {
     KVM_CAP_INFO(USER_MEMORY),
diff --git a/kvm-stub.c b/kvm-stub.c
index 02e7fe0..158bb7b 100644
--- a/kvm-stub.c
+++ b/kvm-stub.c
@@ -21,6 +21,7 @@ KVMState *kvm_state;
 bool kvm_kernel_irqchip;
 bool kvm_async_interrupts_allowed;
 bool kvm_irqfds_allowed;
+bool kvm_msi_via_irqfd_allowed;
 
 int kvm_init_vcpu(CPUArchState *env)
 {
diff --git a/kvm.h b/kvm.h
index 21436ef..34d32c7 100644
--- a/kvm.h
+++ b/kvm.h
@@ -26,6 +26,7 @@ extern int kvm_allowed;
 extern bool kvm_kernel_irqchip;
 extern bool kvm_async_interrupts_allowed;
 extern bool kvm_irqfds_allowed;
+extern bool kvm_msi_via_irqfd_allowed;
 
 #if defined CONFIG_KVM || !defined NEED_CPU_H
 #define kvm_enabled()           (kvm_allowed)
@@ -50,11 +51,21 @@ extern bool kvm_irqfds_allowed;
  */
 #define kvm_irqfds_enabled() (kvm_irqfds_allowed)
 
+/**
+ * kvm_msi_via_irqfd_enabled:
+ *
+ * Returns: true if we can route a PCI MSI (Message Signaled Interrupt)
+ * to a KVM CPU via an irqfd. This requires that the kernel supports
+ * this and that we're running in a configuration that permits it.
+ */
+#define kvm_msi_via_irqfd_enabled() (kvm_msi_via_irqfd_allowed)
+
 #else
 #define kvm_enabled()           (0)
 #define kvm_irqchip_in_kernel() (false)
 #define kvm_async_interrupts_enabled() (false)
 #define kvm_irqfds_enabled() (false)
+#define kvm_msi_via_irqfd_enabled() (false)
 #endif
 
 struct kvm_run;
diff --git a/target-i386/kvm.c b/target-i386/kvm.c
index 8c28fca..7a874ea 100644
--- a/target-i386/kvm.c
+++ b/target-i386/kvm.c
@@ -2048,7 +2048,9 @@ void kvm_arch_init_irq_routing(KVMState *s)
         no_hpet = 1;
     }
     /* We know at this point that we're using the in-kernel
-     * irqchip, so we can use irqfds.
+     * irqchip, so we can use irqfds, and on x86 we know
+     * we can use msi via irqfd.
      */
     kvm_irqfds_allowed = true;
+    kvm_msi_via_irqfd_allowed = true;
 }
commit cc7e0ddf5a2307015eacfac2ac6a6a765898fcc3
Author: Peter Maydell <peter.maydell at linaro.org>
Date:   Thu Jul 26 15:35:14 2012 +0100

    kvm: Decouple 'irqfds usable' from 'kernel irqchip'
    
    Instead of assuming that we can use irqfds if and only if
    kvm_irqchip_in_kernel(), add a bool to the KVMState which
    indicates this, and is set only on x86 and only if the
    irqchip is in the kernel.
    
    The kernel documentation implies that the only thing
    you need to use KVM_IRQFD is that KVM_CAP_IRQFD is
    advertised, but this seems to be untrue. In particular
    the kernel does not (alas) return a sensible error if you
    try to set up an irqfd when you haven't created an irqchip.
    If it did we could remove all this nonsense and let the
    kernel return the error code.
    
    Signed-off-by: Peter Maydell <peter.maydell at linaro.org>
    Acked-by: Jan Kiszka <jan.kiszka at siemens.com>
    Signed-off-by: Avi Kivity <avi at redhat.com>

diff --git a/kvm-all.c b/kvm-all.c
index f420dfa..0704055 100644
--- a/kvm-all.c
+++ b/kvm-all.c
@@ -101,6 +101,7 @@ struct KVMState
 KVMState *kvm_state;
 bool kvm_kernel_irqchip;
 bool kvm_async_interrupts_allowed;
+bool kvm_irqfds_allowed;
 
 static const KVMCapabilityInfo kvm_required_capabilites[] = {
     KVM_CAP_INFO(USER_MEMORY),
@@ -1126,7 +1127,7 @@ static int kvm_irqchip_assign_irqfd(KVMState *s, int fd, int virq, bool assign)
         .flags = assign ? 0 : KVM_IRQFD_FLAG_DEASSIGN,
     };
 
-    if (!kvm_irqchip_in_kernel()) {
+    if (!kvm_irqfds_enabled()) {
         return -ENOSYS;
     }
 
diff --git a/kvm-stub.c b/kvm-stub.c
index f2b0c61..02e7fe0 100644
--- a/kvm-stub.c
+++ b/kvm-stub.c
@@ -20,6 +20,7 @@
 KVMState *kvm_state;
 bool kvm_kernel_irqchip;
 bool kvm_async_interrupts_allowed;
+bool kvm_irqfds_allowed;
 
 int kvm_init_vcpu(CPUArchState *env)
 {
diff --git a/kvm.h b/kvm.h
index 47bf5ba..21436ef 100644
--- a/kvm.h
+++ b/kvm.h
@@ -25,6 +25,7 @@
 extern int kvm_allowed;
 extern bool kvm_kernel_irqchip;
 extern bool kvm_async_interrupts_allowed;
+extern bool kvm_irqfds_allowed;
 
 #if defined CONFIG_KVM || !defined NEED_CPU_H
 #define kvm_enabled()           (kvm_allowed)
@@ -40,10 +41,20 @@ extern bool kvm_async_interrupts_allowed;
  */
 #define kvm_async_interrupts_enabled() (kvm_async_interrupts_allowed)
 
+/**
+ * kvm_irqfds_enabled:
+ *
+ * Returns: true if we can use irqfds to inject interrupts into
+ * a KVM CPU (ie the kernel supports irqfds and we are running
+ * with a configuration where it is meaningful to use them).
+ */
+#define kvm_irqfds_enabled() (kvm_irqfds_allowed)
+
 #else
 #define kvm_enabled()           (0)
 #define kvm_irqchip_in_kernel() (false)
 #define kvm_async_interrupts_enabled() (false)
+#define kvm_irqfds_enabled() (false)
 #endif
 
 struct kvm_run;
diff --git a/target-i386/kvm.c b/target-i386/kvm.c
index e5decf7..8c28fca 100644
--- a/target-i386/kvm.c
+++ b/target-i386/kvm.c
@@ -2047,4 +2047,8 @@ void kvm_arch_init_irq_routing(KVMState *s)
          */
         no_hpet = 1;
     }
+    /* We know at this point that we're using the in-kernel
+     * irqchip, so we can use irqfds.
+     */
+    kvm_irqfds_allowed = true;
 }
commit 1d31f66bbc886af56d2def349012a358dc3ada06
Author: Peter Maydell <peter.maydell at linaro.org>
Date:   Thu Jul 26 15:35:13 2012 +0100

    kvm: Move kvm_allows_irq0_override() to target-i386, fix return type
    
    kvm_allows_irq0_override() is a totally x86 specific concept:
    move it to the target-specific source file where it belongs.
    This means we need a new header file for the prototype:
    kvm_i386.h, in line with the existing kvm_ppc.h.
    
    While we are moving it, fix the return type to be 'bool' rather
    than 'int'.
    
    Signed-off-by: Peter Maydell <peter.maydell at linaro.org>
    Signed-off-by: Avi Kivity <avi at redhat.com>

diff --git a/hw/pc.c b/hw/pc.c
index 81c391c..e8bcfc0 100644
--- a/hw/pc.c
+++ b/hw/pc.c
@@ -42,6 +42,7 @@
 #include "sysbus.h"
 #include "sysemu.h"
 #include "kvm.h"
+#include "kvm_i386.h"
 #include "xen.h"
 #include "blockdev.h"
 #include "hw/block-common.h"
diff --git a/kvm-all.c b/kvm-all.c
index 002e751..f420dfa 100644
--- a/kvm-all.c
+++ b/kvm-all.c
@@ -1701,11 +1701,6 @@ int kvm_has_gsi_routing(void)
 #endif
 }
 
-int kvm_allows_irq0_override(void)
-{
-    return !kvm_irqchip_in_kernel() || kvm_has_gsi_routing();
-}
-
 void *kvm_vmalloc(ram_addr_t size)
 {
 #ifdef TARGET_S390X
diff --git a/kvm-stub.c b/kvm-stub.c
index a7a03e1..f2b0c61 100644
--- a/kvm-stub.c
+++ b/kvm-stub.c
@@ -72,11 +72,6 @@ int kvm_has_many_ioeventfds(void)
     return 0;
 }
 
-int kvm_allows_irq0_override(void)
-{
-    return 1;
-}
-
 int kvm_has_pit_state2(void)
 {
     return 0;
diff --git a/kvm.h b/kvm.h
index 744209d..47bf5ba 100644
--- a/kvm.h
+++ b/kvm.h
@@ -75,8 +75,6 @@ int kvm_has_pit_state2(void);
 int kvm_has_many_ioeventfds(void);
 int kvm_has_gsi_routing(void);
 
-int kvm_allows_irq0_override(void);
-
 #ifdef NEED_CPU_H
 int kvm_init_vcpu(CPUArchState *env);
 
diff --git a/target-i386/Makefile.objs b/target-i386/Makefile.objs
index 683fd59..0715f58 100644
--- a/target-i386/Makefile.objs
+++ b/target-i386/Makefile.objs
@@ -3,6 +3,7 @@ obj-y += excp_helper.o fpu_helper.o cc_helper.o int_helper.o svm_helper.o
 obj-y += smm_helper.o misc_helper.o mem_helper.o seg_helper.o
 obj-$(CONFIG_SOFTMMU) += machine.o arch_memory_mapping.o arch_dump.o
 obj-$(CONFIG_KVM) += kvm.o hyperv.o
+obj-$(CONFIG_NO_KVM) += kvm-stub.o
 obj-$(CONFIG_LINUX_USER) += ioport-user.o
 obj-$(CONFIG_BSD_USER) += ioport-user.o
 
diff --git a/target-i386/kvm-stub.c b/target-i386/kvm-stub.c
new file mode 100644
index 0000000..11429c4
--- /dev/null
+++ b/target-i386/kvm-stub.c
@@ -0,0 +1,18 @@
+/*
+ * QEMU KVM x86 specific function stubs
+ *
+ * Copyright Linaro Limited 2012
+ *
+ * Author: Peter Maydell <peter.maydell at linaro.org>
+ *
+ * This work is licensed under the terms of the GNU GPL, version 2 or later.
+ * See the COPYING file in the top-level directory.
+ *
+ */
+#include "qemu-common.h"
+#include "kvm_i386.h"
+
+bool kvm_allows_irq0_override(void)
+{
+    return 1;
+}
diff --git a/target-i386/kvm.c b/target-i386/kvm.c
index 4cfb3fa..e5decf7 100644
--- a/target-i386/kvm.c
+++ b/target-i386/kvm.c
@@ -23,6 +23,7 @@
 #include "qemu-common.h"
 #include "sysemu.h"
 #include "kvm.h"
+#include "kvm_i386.h"
 #include "cpu.h"
 #include "gdbstub.h"
 #include "host-utils.h"
@@ -65,6 +66,11 @@ static bool has_msr_async_pf_en;
 static bool has_msr_misc_enable;
 static int lm_capable_kernel;
 
+bool kvm_allows_irq0_override(void)
+{
+    return !kvm_irqchip_in_kernel() || kvm_has_gsi_routing();
+}
+
 static struct kvm_cpuid2 *try_get_cpuid(KVMState *s, int max)
 {
     struct kvm_cpuid2 *cpuid;
diff --git a/target-i386/kvm_i386.h b/target-i386/kvm_i386.h
new file mode 100644
index 0000000..b82bbf4
--- /dev/null
+++ b/target-i386/kvm_i386.h
@@ -0,0 +1,16 @@
+/*
+ * QEMU KVM support -- x86 specific functions.
+ *
+ * Copyright (c) 2012 Linaro Limited
+ *
+ * This work is licensed under the terms of the GNU GPL, version 2 or later.
+ * See the COPYING file in the top-level directory.
+ *
+ */
+
+#ifndef QEMU_KVM_I386_H
+#define QEMU_KVM_I386_H
+
+bool kvm_allows_irq0_override(void);
+
+#endif
commit 3889c3fab10b63e170ab5193d2ce6be99a704e93
Author: Peter Maydell <peter.maydell at linaro.org>
Date:   Thu Jul 26 15:35:12 2012 +0100

    kvm: Rename kvm_irqchip_set_irq() to kvm_set_irq()
    
    Rename the function kvm_irqchip_set_irq() to kvm_set_irq(),
    since it can be used for sending (asynchronous) interrupts whether
    there is a full irqchip model in the kernel or not. (We don't
    include 'async' in the function name since asynchronous is the
    normal case.)
    
    Signed-off-by: Peter Maydell <peter.maydell at linaro.org>
    Signed-off-by: Avi Kivity <avi at redhat.com>

diff --git a/hw/kvm/i8259.c b/hw/kvm/i8259.c
index 94d1b9a..1e24cd4 100644
--- a/hw/kvm/i8259.c
+++ b/hw/kvm/i8259.c
@@ -94,7 +94,7 @@ static void kvm_pic_set_irq(void *opaque, int irq, int level)
 {
     int delivered;
 
-    delivered = kvm_irqchip_set_irq(kvm_state, irq, level);
+    delivered = kvm_set_irq(kvm_state, irq, level);
     apic_report_irq_delivered(delivered);
 }
 
diff --git a/hw/kvm/ioapic.c b/hw/kvm/ioapic.c
index 3ae3175..6c3b8fe 100644
--- a/hw/kvm/ioapic.c
+++ b/hw/kvm/ioapic.c
@@ -82,7 +82,7 @@ static void kvm_ioapic_set_irq(void *opaque, int irq, int level)
     KVMIOAPICState *s = opaque;
     int delivered;
 
-    delivered = kvm_irqchip_set_irq(kvm_state, s->kvm_gsi_base + irq, level);
+    delivered = kvm_set_irq(kvm_state, s->kvm_gsi_base + irq, level);
     apic_report_irq_delivered(delivered);
 }
 
diff --git a/kvm-all.c b/kvm-all.c
index bdb5550..002e751 100644
--- a/kvm-all.c
+++ b/kvm-all.c
@@ -853,7 +853,7 @@ static void kvm_handle_interrupt(CPUArchState *env, int mask)
     }
 }
 
-int kvm_irqchip_set_irq(KVMState *s, int irq, int level)
+int kvm_set_irq(KVMState *s, int irq, int level)
 {
     struct kvm_irq_level event;
     int ret;
@@ -864,7 +864,7 @@ int kvm_irqchip_set_irq(KVMState *s, int irq, int level)
     event.irq = irq;
     ret = kvm_vm_ioctl(s, s->irqchip_inject_ioctl, &event);
     if (ret < 0) {
-        perror("kvm_set_irqchip_line");
+        perror("kvm_set_irq");
         abort();
     }
 
@@ -1089,7 +1089,7 @@ int kvm_irqchip_send_msi(KVMState *s, MSIMessage msg)
 
     assert(route->kroute.type == KVM_IRQ_ROUTING_MSI);
 
-    return kvm_irqchip_set_irq(s, route->kroute.gsi, 1);
+    return kvm_set_irq(s, route->kroute.gsi, 1);
 }
 
 int kvm_irqchip_add_msi_route(KVMState *s, MSIMessage msg)
diff --git a/kvm.h b/kvm.h
index 09818f3..744209d 100644
--- a/kvm.h
+++ b/kvm.h
@@ -146,7 +146,7 @@ int kvm_arch_on_sigbus(int code, void *addr);
 
 void kvm_arch_init_irq_routing(KVMState *s);
 
-int kvm_irqchip_set_irq(KVMState *s, int irq, int level);
+int kvm_set_irq(KVMState *s, int irq, int level);
 int kvm_irqchip_send_msi(KVMState *s, MSIMessage msg);
 
 void kvm_irqchip_add_irq_route(KVMState *s, int gsi, int irqchip, int pin);
commit 7ae26bd484a50810f8d29cb5399bc48108e50bec
Author: Peter Maydell <peter.maydell at linaro.org>
Date:   Thu Jul 26 15:35:11 2012 +0100

    kvm: Decouple 'async interrupt delivery' from 'kernel irqchip'
    
    On x86 userspace delivers interrupts to the kernel asynchronously
    (and therefore VCPU idle management is done in the kernel) if and
    only if there is an in-kernel irqchip. On other architectures this
    isn't necessarily true (they may always send interrupts
    asynchronously), so define a new kvm_async_interrupts_enabled()
    function instead of misusing kvm_irqchip_in_kernel().
    
    Signed-off-by: Peter Maydell <peter.maydell at linaro.org>
    Signed-off-by: Avi Kivity <avi at redhat.com>

diff --git a/cpus.c b/cpus.c
index 3de2e27..e476a3c 100644
--- a/cpus.c
+++ b/cpus.c
@@ -70,7 +70,8 @@ static bool cpu_thread_is_idle(CPUArchState *env)
     if (env->stopped || !runstate_is_running()) {
         return true;
     }
-    if (!env->halted || qemu_cpu_has_work(env) || kvm_irqchip_in_kernel()) {
+    if (!env->halted || qemu_cpu_has_work(env) ||
+        kvm_async_interrupts_enabled()) {
         return false;
     }
     return true;
diff --git a/kvm-all.c b/kvm-all.c
index bf64761..bdb5550 100644
--- a/kvm-all.c
+++ b/kvm-all.c
@@ -100,6 +100,7 @@ struct KVMState
 
 KVMState *kvm_state;
 bool kvm_kernel_irqchip;
+bool kvm_async_interrupts_allowed;
 
 static const KVMCapabilityInfo kvm_required_capabilites[] = {
     KVM_CAP_INFO(USER_MEMORY),
@@ -857,7 +858,7 @@ int kvm_irqchip_set_irq(KVMState *s, int irq, int level)
     struct kvm_irq_level event;
     int ret;
 
-    assert(kvm_irqchip_in_kernel());
+    assert(kvm_async_interrupts_enabled());
 
     event.level = level;
     event.irq = irq;
@@ -1201,6 +1202,10 @@ static int kvm_irqchip_create(KVMState *s)
         s->irqchip_inject_ioctl = KVM_IRQ_LINE_STATUS;
     }
     kvm_kernel_irqchip = true;
+    /* If we have an in-kernel IRQ chip then we must have asynchronous
+     * interrupt delivery (though the reverse is not necessarily true)
+     */
+    kvm_async_interrupts_allowed = true;
 
     kvm_init_irq_routing(s);
 
diff --git a/kvm-stub.c b/kvm-stub.c
index d23b11c..a7a03e1 100644
--- a/kvm-stub.c
+++ b/kvm-stub.c
@@ -19,6 +19,7 @@
 
 KVMState *kvm_state;
 bool kvm_kernel_irqchip;
+bool kvm_async_interrupts_allowed;
 
 int kvm_init_vcpu(CPUArchState *env)
 {
diff --git a/kvm.h b/kvm.h
index 2617dd5..09818f3 100644
--- a/kvm.h
+++ b/kvm.h
@@ -24,13 +24,26 @@
 
 extern int kvm_allowed;
 extern bool kvm_kernel_irqchip;
+extern bool kvm_async_interrupts_allowed;
 
 #if defined CONFIG_KVM || !defined NEED_CPU_H
 #define kvm_enabled()           (kvm_allowed)
 #define kvm_irqchip_in_kernel() (kvm_kernel_irqchip)
+
+/**
+ * kvm_async_interrupts_enabled:
+ *
+ * Returns: true if we can deliver interrupts to KVM
+ * asynchronously (ie by ioctl from any thread at any time)
+ * rather than having to do interrupt delivery synchronously
+ * (where the vcpu must be stopped at a suitable point first).
+ */
+#define kvm_async_interrupts_enabled() (kvm_async_interrupts_allowed)
+
 #else
 #define kvm_enabled()           (0)
 #define kvm_irqchip_in_kernel() (false)
+#define kvm_async_interrupts_enabled() (false)
 #endif
 
 struct kvm_run;
commit 08312a63b77df45ad056d2e8d9e2cbe8f683a23c
Author: Peter Maydell <peter.maydell at linaro.org>
Date:   Fri Aug 3 13:51:25 2012 +0100

    configure: Don't implicitly hardcode list of KVM architectures
    
    The code creating the symlink from linux-headers/asm to the
    architecture specific linux-headers/asm-$arch directory was
    implicitly hardcoding a list of KVM supporting architectures.
    Add a default case for the common "Linux architecture name and
    QEMU CPU name match" case, so future architectures will only
    need to add code if they've managed to get mismatched names.
    
    Signed-off-by: Peter Maydell <peter.maydell at linaro.org>
    Signed-off-by: Marcelo Tosatti <mtosatti at redhat.com>
    Signed-off-by: Avi Kivity <avi at redhat.com>

diff --git a/configure b/configure
index 280726c..b9a0b27 100755
--- a/configure
+++ b/configure
@@ -3538,15 +3538,23 @@ if test "$linux" = "yes" ; then
   mkdir -p linux-headers
   case "$cpu" in
   i386|x86_64)
-    symlink "$source_path/linux-headers/asm-x86" linux-headers/asm
+    linux_arch=x86
     ;;
   ppcemb|ppc|ppc64)
-    symlink "$source_path/linux-headers/asm-powerpc" linux-headers/asm
+    linux_arch=powerpc
     ;;
   s390x)
-    symlink "$source_path/linux-headers/asm-s390" linux-headers/asm
+    linux_arch=s390
+    ;;
+  *)
+    # For most CPUs the kernel architecture name and QEMU CPU name match.
+    linux_arch="$cpu"
     ;;
   esac
+    # For non-KVM architectures we will not have asm headers
+    if [ -e "$source_path/linux-headers/asm-$linux_arch" ]; then
+      symlink "$source_path/linux-headers/asm-$linux_arch" linux-headers/asm
+    fi
 fi
 
 for target in $target_list; do
commit 3ed444e949cd2f0938759836c0991dfabe86f485
Author: Dunrong Huang <riegamaths at gmail.com>
Date:   Tue Jul 31 19:18:17 2012 +0800

    kvm: Check if smp_cpus exceeds max cpus supported by kvm
    
    Add a helper function for fetching max cpus supported by kvm.
    
    Make QEMU exit with an error message if smp_cpus exceeds limit
    of VCPU count retrieved by invoking this helper function.
    
    Signed-off-by: Dunrong Huang <riegamaths at gmail.com>
    Signed-off-by: Marcelo Tosatti <mtosatti at redhat.com>
    Signed-off-by: Avi Kivity <avi at redhat.com>

diff --git a/kvm-all.c b/kvm-all.c
index 2148b20..bf64761 100644
--- a/kvm-all.c
+++ b/kvm-all.c
@@ -1207,6 +1207,26 @@ static int kvm_irqchip_create(KVMState *s)
     return 0;
 }
 
+static int kvm_max_vcpus(KVMState *s)
+{
+    int ret;
+
+    /* Find number of supported CPUs using the recommended
+     * procedure from the kernel API documentation to cope with
+     * older kernels that may be missing capabilities.
+     */
+    ret = kvm_check_extension(s, KVM_CAP_MAX_VCPUS);
+    if (ret) {
+        return ret;
+    }
+    ret = kvm_check_extension(s, KVM_CAP_NR_VCPUS);
+    if (ret) {
+        return ret;
+    }
+
+    return 4;
+}
+
 int kvm_init(void)
 {
     static const char upgrade_note[] =
@@ -1216,6 +1236,7 @@ int kvm_init(void)
     const KVMCapabilityInfo *missing_cap;
     int ret;
     int i;
+    int max_vcpus;
 
     s = g_malloc0(sizeof(KVMState));
 
@@ -1256,6 +1277,14 @@ int kvm_init(void)
         goto err;
     }
 
+    max_vcpus = kvm_max_vcpus(s);
+    if (smp_cpus > max_vcpus) {
+        ret = -EINVAL;
+        fprintf(stderr, "Number of SMP cpus requested (%d) exceeds max cpus "
+                "supported by KVM (%d)\n", smp_cpus, max_vcpus);
+        goto err;
+    }
+
     s->vmfd = kvm_ioctl(s, KVM_CREATE_VM, 0);
     if (s->vmfd < 0) {
 #ifdef TARGET_S390X
commit 4dd7c82cdbabe54386ef31939f865469a095c9c3
Author: Paolo Bonzini <pbonzini at redhat.com>
Date:   Wed Aug 8 16:26:16 2012 +0200

    virtio-scsi: do not compare 32-bit QEMU tags against 64-bit virtio-scsi tags
    
    This patch fixes a problem in handling task management functions
    in virtio-scsi.  The cause of the problem is a mismatch between
    the size of the tag in QEMU (32-bit) and virtio-scsi (64-bit).
    Changing the QEMU size is hard because the migration format
    uses 32 bits to store the tag; so just don't use the QEMU tag
    (virtio-scsi only uses the tag for task management functions
    anyway) and look up the full 64-bit tag in the hba_private field.
    
    The reproducer is a bit obscure.  If you cause an I/O timeout
    (for example with rerror=stop and doing 'cont' on the monitor
    continuously without fixing the error), sooner or later the
    guest will try to abort the command and reissue it.  At this
    point, QEMU will report _two_ errors instead of one when you
    hit 'c', because the first error has not been canceled correctly.
    
    Signed-off-by: Paolo Bonzini <pbonzini at redhat.com>

diff --git a/hw/virtio-scsi.c b/hw/virtio-scsi.c
index c4a5b22..5f737ac 100644
--- a/hw/virtio-scsi.c
+++ b/hw/virtio-scsi.c
@@ -305,11 +305,17 @@ static void virtio_scsi_do_tmf(VirtIOSCSI *s, VirtIOSCSIReq *req)
             goto incorrect_lun;
         }
         QTAILQ_FOREACH_SAFE(r, &d->requests, next, next) {
-            if (r->tag == req->req.tmf->tag) {
+            VirtIOSCSIReq *cmd_req = r->hba_private;
+            if (cmd_req && cmd_req->req.cmd->tag == req->req.tmf->tag) {
                 break;
             }
         }
-        if (r && r->hba_private) {
+        if (r) {
+            /*
+             * Assert that the request has not been completed yet, we
+             * check for it in the loop above.
+             */
+            assert(r->hba_private);
             if (req->req.tmf->subtype == VIRTIO_SCSI_T_TMF_QUERY_TASK) {
                 /* "If the specified command is present in the task set, then
                  * return a service response set to FUNCTION SUCCEEDED".
commit 31459f463a32dc6c1818fa1aaa3d1f56c367b718
Author: Ronnie Sahlberg <ronniesahlberg at gmail.com>
Date:   Mon Aug 6 18:24:55 2012 +1000

    iscsi: Pick default initiator-name based on the name of the VM
    
    This patch updates the iscsi layer to automatically pick a 'unique'
    initiator-name based on the name of the vm in case the user has not set
    an explicit iqn-name to use.
    
    Create a new function qemu_get_vm_name() that returns the name of the VM,
    if specified.
    
    This way we can thus create default names to use as the initiator name
    based on the guest session.
    
    If the VM is not named via the '-name' command line argument, the iscsi
    initiator-name used wiull simply be
    
        iqn.2008-11.org.linux-kvm
    
    If a name for the VM was specified with the '-name' option, iscsi will
    use a default initiatorname of
    
        iqn.2008-11.org.linux-kvm:<name>
    
    These names are just the default iscsi initiator name that qemu will
    generate/use only when the user has not set an explicit initiator name
    via the commandlines or config files.
    
    Signed-off-by: Ronnie Sahlberg <ronniesahlberg at gmail.com>

diff --git a/block/iscsi.c b/block/iscsi.c
index fd954d4..219f927 100644
--- a/block/iscsi.c
+++ b/block/iscsi.c
@@ -896,6 +896,7 @@ static char *parse_initiator_name(const char *target)
     QemuOptsList *list;
     QemuOpts *opts;
     const char *name = NULL;
+    const char *iscsi_name = qemu_get_vm_name();
 
     list = qemu_find_opts("iscsi");
     if (list) {
@@ -911,7 +912,9 @@ static char *parse_initiator_name(const char *target)
     if (name) {
         return g_strdup(name);
     } else {
-        return g_strdup("iqn.2008-11.org.linux-kvm");
+        return g_strdup_printf("iqn.2008-11.org.linux-kvm%s%s",
+                               iscsi_name ? ":" : "",
+                               iscsi_name ? iscsi_name : "");
     }
 }
 
diff --git a/qemu-common.h b/qemu-common.h
index f16079f..f9deca6 100644
--- a/qemu-common.h
+++ b/qemu-common.h
@@ -376,6 +376,7 @@ bool buffer_is_zero(const void *buf, size_t len);
 void qemu_progress_init(int enabled, float min_skip);
 void qemu_progress_end(void);
 void qemu_progress_print(float delta, int max);
+const char *qemu_get_vm_name(void);
 
 #define QEMU_FILE_TYPE_BIOS   0
 #define QEMU_FILE_TYPE_KEYMAP 1
diff --git a/qemu-doc.texi b/qemu-doc.texi
index f32e9e2..35cabbc 100644
--- a/qemu-doc.texi
+++ b/qemu-doc.texi
@@ -734,6 +734,11 @@ Various session related parameters can be set via special options, either
 in a configuration file provided via '-readconfig' or directly on the
 command line.
 
+If the initiator-name is not specified qemu will use a default name
+of 'iqn.2008-11.org.linux-kvm[:<name>'] where <name> is the name of the
+virtual machine.
+
+
 @example
 Setting a specific initiator name to use when logging in to the target
 -iscsi initiator-name=iqn.qemu.test:my-initiator
diff --git a/qemu-options.hx b/qemu-options.hx
index 5e7d0dc..47cb5bd 100644
--- a/qemu-options.hx
+++ b/qemu-options.hx
@@ -1897,6 +1897,11 @@ images for the guest storage. Both disk and cdrom images are supported.
 Syntax for specifying iSCSI LUNs is
 ``iscsi://<target-ip>[:<port>]/<target-iqn>/<lun>''
 
+By default qemu will use the iSCSI initiator-name
+'iqn.2008-11.org.linux-kvm[:<name>]' but this can also be set from the command
+line or a configuration file.
+
+
 Example (without authentication):
 @example
 qemu-system-i386 -iscsi initiator-name=iqn.2001-04.com.example:my-initiator \
@@ -1926,6 +1931,9 @@ DEF("iscsi", HAS_ARG, QEMU_OPTION_iscsi,
     "                iSCSI session parameters\n", QEMU_ARCH_ALL)
 STEXI
 
+iSCSI parameters such as username and password can also be specified via
+a configuration file. See qemu-doc for more information and examples.
+
 @item NBD
 QEMU supports NBD (Network Block Devices) both using TCP protocol as well
 as Unix Domain Sockets.
diff --git a/qemu-tool.c b/qemu-tool.c
index 318c5fc..64b5e88 100644
--- a/qemu-tool.c
+++ b/qemu-tool.c
@@ -30,6 +30,11 @@ struct QEMUBH
     void *opaque;
 };
 
+const char *qemu_get_vm_name(void)
+{
+    return NULL;
+}
+
 Monitor *cur_mon;
 
 int monitor_cur_is_qmp(void)
diff --git a/vl.c b/vl.c
index e71cb30..065aec2 100644
--- a/vl.c
+++ b/vl.c
@@ -293,6 +293,11 @@ static struct {
     { .driver = "qxl-vga",              .flag = &default_vga       },
 };
 
+const char *qemu_get_vm_name(void)
+{
+    return qemu_name;
+}
+
 static void res_free(void)
 {
     if (boot_splash_filedata != NULL) {
commit f2ef4a6dd9f008d4cb30bccfc0491c01b69f1ead
Author: Paolo Bonzini <pbonzini at redhat.com>
Date:   Mon Aug 6 10:54:41 2012 +0200

    iscsi: reorganize code for parse_initiator_name
    
    Merge the occurrences of the "iqn.2008-11.org.linux-kvm" string
    to avoid duplication.
    
    Signed-off-by: Paolo Bonzini <pbonzini at redhat.com>

diff --git a/block/iscsi.c b/block/iscsi.c
index 94063ab..fd954d4 100644
--- a/block/iscsi.c
+++ b/block/iscsi.c
@@ -898,24 +898,21 @@ static char *parse_initiator_name(const char *target)
     const char *name = NULL;
 
     list = qemu_find_opts("iscsi");
-    if (!list) {
-        return g_strdup("iqn.2008-11.org.linux-kvm");
-    }
-
-    opts = qemu_opts_find(list, target);
-    if (opts == NULL) {
-        opts = QTAILQ_FIRST(&list->head);
+    if (list) {
+        opts = qemu_opts_find(list, target);
         if (!opts) {
-            return g_strdup("iqn.2008-11.org.linux-kvm");
+            opts = QTAILQ_FIRST(&list->head);
+        }
+        if (opts) {
+            name = qemu_opt_get(opts, "initiator-name");
         }
     }
 
-    name = qemu_opt_get(opts, "initiator-name");
-    if (!name) {
+    if (name) {
+        return g_strdup(name);
+    } else {
         return g_strdup("iqn.2008-11.org.linux-kvm");
     }
-
-    return g_strdup(name);
 }
 
 /*
commit b93c94f7ec74a577a0f74c724e8d251f01eaf65a
Author: Paolo Bonzini <pbonzini at redhat.com>
Date:   Mon Aug 6 10:52:22 2012 +0200

    iscsi: do not leak initiator_name
    
    The argument of iscsi_create_context is never freed by libiscsi,
    which in fact calls strdup on it.  Avoid a leak.
    
    Signed-off-by: Paolo Bonzini <pbonzini at redhat.com>

diff --git a/block/iscsi.c b/block/iscsi.c
index 993a86d..94063ab 100644
--- a/block/iscsi.c
+++ b/block/iscsi.c
@@ -943,7 +943,7 @@ static int iscsi_open(BlockDriverState *bs, const char *filename, int flags)
         error_report("Failed to parse URL : %s %s", filename,
                      iscsi_get_error(iscsi));
         ret = -EINVAL;
-        goto failed;
+        goto out;
     }
 
     memset(iscsilun, 0, sizeof(IscsiLun));
@@ -954,13 +954,13 @@ static int iscsi_open(BlockDriverState *bs, const char *filename, int flags)
     if (iscsi == NULL) {
         error_report("iSCSI: Failed to create iSCSI context.");
         ret = -ENOMEM;
-        goto failed;
+        goto out;
     }
 
     if (iscsi_set_targetname(iscsi, iscsi_url->target)) {
         error_report("iSCSI: Failed to set target name.");
         ret = -EINVAL;
-        goto failed;
+        goto out;
     }
 
     if (iscsi_url->user != NULL) {
@@ -969,7 +969,7 @@ static int iscsi_open(BlockDriverState *bs, const char *filename, int flags)
         if (ret != 0) {
             error_report("Failed to set initiator username and password");
             ret = -EINVAL;
-            goto failed;
+            goto out;
         }
     }
 
@@ -977,13 +977,13 @@ static int iscsi_open(BlockDriverState *bs, const char *filename, int flags)
     if (parse_chap(iscsi, iscsi_url->target) != 0) {
         error_report("iSCSI: Failed to set CHAP user/password");
         ret = -EINVAL;
-        goto failed;
+        goto out;
     }
 
     if (iscsi_set_session_type(iscsi, ISCSI_SESSION_NORMAL) != 0) {
         error_report("iSCSI: Failed to set session type to normal.");
         ret = -EINVAL;
-        goto failed;
+        goto out;
     }
 
     iscsi_set_header_digest(iscsi, ISCSI_HEADER_DIGEST_NONE_CRC32C);
@@ -1004,7 +1004,7 @@ static int iscsi_open(BlockDriverState *bs, const char *filename, int flags)
         != 0) {
         error_report("iSCSI: Failed to start async connect.");
         ret = -EINVAL;
-        goto failed;
+        goto out;
     }
 
     while (!task.complete) {
@@ -1015,11 +1015,7 @@ static int iscsi_open(BlockDriverState *bs, const char *filename, int flags)
         error_report("iSCSI: Failed to connect to LUN : %s",
                      iscsi_get_error(iscsi));
         ret = -EINVAL;
-        goto failed;
-    }
-
-    if (iscsi_url != NULL) {
-        iscsi_destroy_url(iscsi_url);
+        goto out;
     }
 
     /* Medium changer or tape. We dont have any emulation for this so this must
@@ -1031,19 +1027,22 @@ static int iscsi_open(BlockDriverState *bs, const char *filename, int flags)
         bs->sg = 1;
     }
 
-    return 0;
+    ret = 0;
 
-failed:
+out:
     if (initiator_name != NULL) {
         g_free(initiator_name);
     }
     if (iscsi_url != NULL) {
         iscsi_destroy_url(iscsi_url);
     }
-    if (iscsi != NULL) {
-        iscsi_destroy_context(iscsi);
+
+    if (ret) {
+        if (iscsi != NULL) {
+            iscsi_destroy_context(iscsi);
+        }
+        memset(iscsilun, 0, sizeof(IscsiLun));
     }
-    memset(iscsilun, 0, sizeof(IscsiLun));
     return ret;
 }
 
commit dd051c7217eae04191169ac62f6ffb7531c8da32
Author: Juan Quintela <quintela at redhat.com>
Date:   Mon Aug 6 21:42:58 2012 +0300

    Restart optimization on stage3 update version
    
    Signed-off-by: Juan Quintela <quintela at redhat.com>
    
    Reviewed-by: Luiz Capitulino <lcapitulino at redhat.com>
    Reviewed-by: Eric Blake <eblake at redhat.com>

diff --git a/arch_init.c b/arch_init.c
index ee692ae..a7c0987 100644
--- a/arch_init.c
+++ b/arch_init.c
@@ -275,14 +275,16 @@ static void save_block_hdr(QEMUFile *f, RAMBlock *block, ram_addr_t offset,
 
 static int save_xbzrle_page(QEMUFile *f, uint8_t *current_data,
                             ram_addr_t current_addr, RAMBlock *block,
-                            ram_addr_t offset, int cont)
+                            ram_addr_t offset, int cont, bool last_stage)
 {
     int encoded_len = 0, bytes_sent = -1;
     uint8_t *prev_cached_page;
 
     if (!cache_is_cached(XBZRLE.cache, current_addr)) {
-        cache_insert(XBZRLE.cache, current_addr,
-                     g_memdup(current_data, TARGET_PAGE_SIZE));
+        if (!last_stage) {
+            cache_insert(XBZRLE.cache, current_addr,
+                         g_memdup(current_data, TARGET_PAGE_SIZE));
+        }
         acct_info.xbzrle_cache_miss++;
         return -1;
     }
@@ -308,7 +310,9 @@ static int save_xbzrle_page(QEMUFile *f, uint8_t *current_data,
     }
 
     /* we need to update the data in the cache, in order to get the same data */
-    memcpy(prev_cached_page, XBZRLE.current_buf, TARGET_PAGE_SIZE);
+    if (!last_stage) {
+        memcpy(prev_cached_page, XBZRLE.current_buf, TARGET_PAGE_SIZE);
+    }
 
     /* Send XBZRLE based compressed page */
     save_block_hdr(f, block, offset, cont, RAM_SAVE_FLAG_XBZRLE);
@@ -333,7 +337,7 @@ static ram_addr_t last_offset;
  *           n: the amount of bytes written in other case
  */
 
-static int ram_save_block(QEMUFile *f)
+static int ram_save_block(QEMUFile *f, bool last_stage)
 {
     RAMBlock *block = last_block;
     ram_addr_t offset = last_offset;
@@ -364,8 +368,10 @@ static int ram_save_block(QEMUFile *f)
             } else if (migrate_use_xbzrle()) {
                 current_addr = block->offset + offset;
                 bytes_sent = save_xbzrle_page(f, p, current_addr, block,
-                                              offset, cont);
-                p = get_cached_data(XBZRLE.cache, current_addr);
+                                              offset, cont, last_stage);
+                if (!last_stage) {
+                    p = get_cached_data(XBZRLE.cache, current_addr);
+                }
             }
 
             /* either we didn't send yet (we may have had XBZRLE overflow) */
@@ -538,7 +544,7 @@ static int ram_save_iterate(QEMUFile *f, void *opaque)
     while ((ret = qemu_file_rate_limit(f)) == 0) {
         int bytes_sent;
 
-        bytes_sent = ram_save_block(f);
+        bytes_sent = ram_save_block(f, false);
         /* no more blocks to sent */
         if (bytes_sent < 0) {
             break;
@@ -600,7 +606,7 @@ static int ram_save_complete(QEMUFile *f, void *opaque)
     while (true) {
         int bytes_sent;
 
-        bytes_sent = ram_save_block(f);
+        bytes_sent = ram_save_block(f, true);
         /* no more blocks to sent */
         if (bytes_sent < 0) {
             break;
commit f36d55af7408abceeee2543f697647ff86bd8a24
Author: Orit Wasserman <owasserm at redhat.com>
Date:   Mon Aug 6 21:42:57 2012 +0300

    Add XBZRLE statistics
    
    Signed-off-by: Benoit Hudzia <benoit.hudzia at sap.com>
    Signed-off-by: Petter Svard <petters at cs.umu.se>
    Signed-off-by: Aidan Shribman <aidan.shribman at sap.com>
    Signed-off-by: Orit Wasserman <owasserm at redhat.com>
    Signed-off-by: Juan Quintela <quintela at redhat.com>
    
    Reviewed-by: Luiz Capitulino <lcapitulino at redhat.com>
    Reviewed-by: Eric Blake <eblake at redhat.com>

diff --git a/arch_init.c b/arch_init.c
index 7ddbd7f..ee692ae 100644
--- a/arch_init.c
+++ b/arch_init.c
@@ -206,6 +206,10 @@ typedef struct AccountingInfo {
     uint64_t dup_pages;
     uint64_t norm_pages;
     uint64_t iterations;
+    uint64_t xbzrle_bytes;
+    uint64_t xbzrle_pages;
+    uint64_t xbzrle_cache_miss;
+    uint64_t xbzrle_overflows;
 } AccountingInfo;
 
 static AccountingInfo acct_info;
@@ -235,6 +239,26 @@ uint64_t norm_mig_pages_transferred(void)
     return acct_info.norm_pages;
 }
 
+uint64_t xbzrle_mig_bytes_transferred(void)
+{
+    return acct_info.xbzrle_bytes;
+}
+
+uint64_t xbzrle_mig_pages_transferred(void)
+{
+    return acct_info.xbzrle_pages;
+}
+
+uint64_t xbzrle_mig_pages_cache_miss(void)
+{
+    return acct_info.xbzrle_cache_miss;
+}
+
+uint64_t xbzrle_mig_pages_overflow(void)
+{
+    return acct_info.xbzrle_overflows;
+}
+
 static void save_block_hdr(QEMUFile *f, RAMBlock *block, ram_addr_t offset,
         int cont, int flag)
 {
@@ -259,6 +283,7 @@ static int save_xbzrle_page(QEMUFile *f, uint8_t *current_data,
     if (!cache_is_cached(XBZRLE.cache, current_addr)) {
         cache_insert(XBZRLE.cache, current_addr,
                      g_memdup(current_data, TARGET_PAGE_SIZE));
+        acct_info.xbzrle_cache_miss++;
         return -1;
     }
 
@@ -276,6 +301,7 @@ static int save_xbzrle_page(QEMUFile *f, uint8_t *current_data,
         return 0;
     } else if (encoded_len == -1) {
         DPRINTF("Overflow\n");
+        acct_info.xbzrle_overflows++;
         /* update data in the cache */
         memcpy(prev_cached_page, current_data, TARGET_PAGE_SIZE);
         return -1;
@@ -290,6 +316,8 @@ static int save_xbzrle_page(QEMUFile *f, uint8_t *current_data,
     qemu_put_be16(f, encoded_len);
     qemu_put_buffer(f, XBZRLE.encoded_buf, encoded_len);
     bytes_sent = encoded_len + 1 + 2;
+    acct_info.xbzrle_pages++;
+    acct_info.xbzrle_bytes += bytes_sent;
 
     return bytes_sent;
 }
diff --git a/hmp.c b/hmp.c
index 3347727..c13386b 100644
--- a/hmp.c
+++ b/hmp.c
@@ -177,6 +177,19 @@ void hmp_info_migrate(Monitor *mon)
                        info->disk->total >> 10);
     }
 
+    if (info->has_xbzrle_cache) {
+        monitor_printf(mon, "cache size: %" PRIu64 " bytes\n",
+                       info->xbzrle_cache->cache_size);
+        monitor_printf(mon, "xbzrle transferred: %" PRIu64 " kbytes\n",
+                       info->xbzrle_cache->bytes >> 10);
+        monitor_printf(mon, "xbzrle pages: %" PRIu64 " pages\n",
+                       info->xbzrle_cache->pages);
+        monitor_printf(mon, "xbzrle cache miss: %" PRIu64 "\n",
+                       info->xbzrle_cache->cache_miss);
+        monitor_printf(mon, "xbzrle overflow : %" PRIu64 "\n",
+                       info->xbzrle_cache->overflow);
+    }
+
     qapi_free_MigrationInfo(info);
     qapi_free_MigrationCapabilityStatusList(caps);
 }
diff --git a/migration.c b/migration.c
index ab5e09d..653a3c1 100644
--- a/migration.c
+++ b/migration.c
@@ -141,6 +141,19 @@ MigrationCapabilityStatusList *qmp_query_migrate_capabilities(Error **errp)
     return head;
 }
 
+static void get_xbzrle_cache_stats(MigrationInfo *info)
+{
+    if (migrate_use_xbzrle()) {
+        info->has_xbzrle_cache = true;
+        info->xbzrle_cache = g_malloc0(sizeof(*info->xbzrle_cache));
+        info->xbzrle_cache->cache_size = migrate_xbzrle_cache_size();
+        info->xbzrle_cache->bytes = xbzrle_mig_bytes_transferred();
+        info->xbzrle_cache->pages = xbzrle_mig_pages_transferred();
+        info->xbzrle_cache->cache_miss = xbzrle_mig_pages_cache_miss();
+        info->xbzrle_cache->overflow = xbzrle_mig_pages_overflow();
+    }
+}
+
 MigrationInfo *qmp_query_migrate(Error **errp)
 {
     MigrationInfo *info = g_malloc0(sizeof(*info));
@@ -172,8 +185,12 @@ MigrationInfo *qmp_query_migrate(Error **errp)
             info->disk->remaining = blk_mig_bytes_remaining();
             info->disk->total = blk_mig_bytes_total();
         }
+
+        get_xbzrle_cache_stats(info);
         break;
     case MIG_STATE_COMPLETED:
+        get_xbzrle_cache_stats(info);
+
         info->has_status = true;
         info->status = g_strdup("completed");
 
diff --git a/migration.h b/migration.h
index e4a7cd7..a9852fc 100644
--- a/migration.h
+++ b/migration.h
@@ -91,6 +91,10 @@ uint64_t dup_mig_bytes_transferred(void);
 uint64_t dup_mig_pages_transferred(void);
 uint64_t norm_mig_bytes_transferred(void);
 uint64_t norm_mig_pages_transferred(void);
+uint64_t xbzrle_mig_bytes_transferred(void);
+uint64_t xbzrle_mig_pages_transferred(void);
+uint64_t xbzrle_mig_pages_overflow(void);
+uint64_t xbzrle_mig_pages_cache_miss(void);
 
 /**
  * @migrate_add_blocker - prevent migration from proceeding
diff --git a/qapi-schema.json b/qapi-schema.json
index 3f67b1e..56d9d7b 100644
--- a/qapi-schema.json
+++ b/qapi-schema.json
@@ -278,6 +278,27 @@
            'normal-bytes': 'int' } }
 
 ##
+# @XBZRLECacheStats
+#
+# Detailed XBZRLE migration cache statistics
+#
+# @cache-size: XBZRLE cache size
+#
+# @bytes: amount of bytes already transferred to the target VM
+#
+# @pages: amount of pages transferred to the target VM
+#
+# @cache-miss: number of cache miss
+#
+# @overflow: number of overflows
+#
+# Since: 1.2
+##
+{ 'type': 'XBZRLECacheStats',
+  'data': {'cache-size': 'int', 'bytes': 'int', 'pages': 'int',
+           'cache-miss': 'int', 'overflow': 'int' } }
+
+##
 # @MigrationInfo
 #
 # Information about current migration process.
@@ -295,11 +316,16 @@
 #        status, only returned if status is 'active' and it is a block
 #        migration
 #
+# @xbzrle-cache: #optional @XBZRLECacheStats containing detailed XBZRLE
+#                migration statistics, only returned if XBZRLE feature is on and
+#                status is 'active' or 'completed' (since 1.2)
+#
 # Since: 0.14.0
 ##
 { 'type': 'MigrationInfo',
   'data': {'*status': 'str', '*ram': 'MigrationStats',
-           '*disk': 'MigrationStats'} }
+           '*disk': 'MigrationStats',
+           '*xbzrle-cache': 'XBZRLECacheStats'} }
 
 ##
 # @query-migrate
diff --git a/qmp-commands.hx b/qmp-commands.hx
index c3368f3..0363d7c 100644
--- a/qmp-commands.hx
+++ b/qmp-commands.hx
@@ -2133,7 +2133,13 @@ The main json-object contains the following:
          - "transferred": amount transferred (json-int)
          - "remaining": amount remaining (json-int)
          - "total": total (json-int)
-
+- "xbzrle-cache": only present if XBZRLE is active.
+  It is a json-object with the following XBZRLE information:
+         - "cache-size": XBZRLE cache size
+         - "bytes": total XBZRLE bytes transferred
+         - "pages": number of XBZRLE compressed pages
+         - "cache-miss": number of cache misses
+         - "overflow": number of XBZRLE overflows
 Examples:
 
 1. Before the first migration
@@ -2204,6 +2210,32 @@ Examples:
       }
    }
 
+6. Migration is being performed and XBZRLE is active:
+
+-> { "execute": "query-migrate" }
+<- {
+      "return":{
+         "status":"active",
+         "capabilities" : [ { "capability": "xbzrle", "state" : true } ],
+         "ram":{
+            "total":1057024,
+            "remaining":1053304,
+            "transferred":3720,
+            "total-time":12345,
+            "duplicate":10,
+            "normal":3333,
+            "normal-bytes":3412992
+         },
+         "xbzrle-cache":{
+            "cache-size":67108864,
+            "bytes":20971520,
+            "pages":2444343,
+            "cache-miss":2244,
+            "overflow":34434
+         }
+      }
+   }
+
 EQMP
 
     {
commit 004d4c10aee9d64869ca3a8ef21f56c0045bf31b
Author: Orit Wasserman <owasserm at redhat.com>
Date:   Mon Aug 6 21:42:56 2012 +0300

    Add migration accounting for normal and duplicate pages
    
    Signed-off-by: Benoit Hudzia <benoit.hudzia at sap.com>
    Signed-off-by: Petter Svard <petters at cs.umu.se>
    Signed-off-by: Aidan Shribman <aidan.shribman at sap.com>
    Signed-off-by: Orit Wasserman <owasserm at redhat.com>
    Signed-off-by: Juan Quintela <quintela at redhat.com>
    
    Reviewed-by: Luiz Capitulino <lcapitulino at redhat.com>
    Reviewed-by: Eric Blake <eblake at redhat.com>

diff --git a/arch_init.c b/arch_init.c
index 7fbfe91..7ddbd7f 100644
--- a/arch_init.c
+++ b/arch_init.c
@@ -201,6 +201,40 @@ int64_t xbzrle_cache_resize(int64_t new_size)
     return pow2floor(new_size);
 }
 
+/* accounting for migration statistics */
+typedef struct AccountingInfo {
+    uint64_t dup_pages;
+    uint64_t norm_pages;
+    uint64_t iterations;
+} AccountingInfo;
+
+static AccountingInfo acct_info;
+
+static void acct_clear(void)
+{
+    memset(&acct_info, 0, sizeof(acct_info));
+}
+
+uint64_t dup_mig_bytes_transferred(void)
+{
+    return acct_info.dup_pages * TARGET_PAGE_SIZE;
+}
+
+uint64_t dup_mig_pages_transferred(void)
+{
+    return acct_info.dup_pages;
+}
+
+uint64_t norm_mig_bytes_transferred(void)
+{
+    return acct_info.norm_pages * TARGET_PAGE_SIZE;
+}
+
+uint64_t norm_mig_pages_transferred(void)
+{
+    return acct_info.norm_pages;
+}
+
 static void save_block_hdr(QEMUFile *f, RAMBlock *block, ram_addr_t offset,
         int cont, int flag)
 {
@@ -295,6 +329,7 @@ static int ram_save_block(QEMUFile *f)
             p = memory_region_get_ram_ptr(mr) + offset;
 
             if (is_dup_page(p)) {
+                acct_info.dup_pages++;
                 save_block_hdr(f, block, offset, cont, RAM_SAVE_FLAG_COMPRESS);
                 qemu_put_byte(f, *p);
                 bytes_sent = 1;
@@ -310,6 +345,7 @@ static int ram_save_block(QEMUFile *f)
                 save_block_hdr(f, block, offset, cont, RAM_SAVE_FLAG_PAGE);
                 qemu_put_buffer(f, p, TARGET_PAGE_SIZE);
                 bytes_sent = TARGET_PAGE_SIZE;
+                acct_info.norm_pages++;
             }
 
             /* if page is unmodified, continue to the next */
@@ -431,6 +467,7 @@ static int ram_save_setup(QEMUFile *f, void *opaque)
         }
         XBZRLE.encoded_buf = g_malloc0(TARGET_PAGE_SIZE);
         XBZRLE.current_buf = g_malloc(TARGET_PAGE_SIZE);
+        acct_clear();
     }
 
     /* Make sure all dirty bits are set */
@@ -479,6 +516,7 @@ static int ram_save_iterate(QEMUFile *f, void *opaque)
             break;
         }
         bytes_transferred += bytes_sent;
+        acct_info.iterations++;
         /* we want to check in the 1st loop, just in case it was the 1st time
            and we had to sync the dirty bitmap.
            qemu_get_clock_ns() is a bit expensive, so we only check each some
diff --git a/hmp.c b/hmp.c
index 8abb4bd..3347727 100644
--- a/hmp.c
+++ b/hmp.c
@@ -160,6 +160,12 @@ void hmp_info_migrate(Monitor *mon)
                        info->ram->total >> 10);
         monitor_printf(mon, "total time: %" PRIu64 " milliseconds\n",
                        info->ram->total_time);
+        monitor_printf(mon, "duplicate: %" PRIu64 " pages\n",
+                       info->ram->duplicate);
+        monitor_printf(mon, "normal: %" PRIu64 " pages\n",
+                       info->ram->normal);
+        monitor_printf(mon, "normal bytes: %" PRIu64 " kbytes\n",
+                       info->ram->normal_bytes >> 10);
     }
 
     if (info->has_disk) {
diff --git a/migration.c b/migration.c
index a6c0072..ab5e09d 100644
--- a/migration.c
+++ b/migration.c
@@ -161,6 +161,9 @@ MigrationInfo *qmp_query_migrate(Error **errp)
         info->ram->total = ram_bytes_total();
         info->ram->total_time = qemu_get_clock_ms(rt_clock)
             - s->total_time;
+        info->ram->duplicate = dup_mig_pages_transferred();
+        info->ram->normal = norm_mig_pages_transferred();
+        info->ram->normal_bytes = norm_mig_bytes_transferred();
 
         if (blk_mig_active()) {
             info->has_disk = true;
@@ -180,6 +183,9 @@ MigrationInfo *qmp_query_migrate(Error **errp)
         info->ram->remaining = 0;
         info->ram->total = ram_bytes_total();
         info->ram->total_time = s->total_time;
+        info->ram->duplicate = dup_mig_pages_transferred();
+        info->ram->normal = norm_mig_pages_transferred();
+        info->ram->normal_bytes = norm_mig_bytes_transferred();
         break;
     case MIG_STATE_ERROR:
         info->has_status = true;
diff --git a/migration.h b/migration.h
index 337e225..e4a7cd7 100644
--- a/migration.h
+++ b/migration.h
@@ -87,6 +87,11 @@ uint64_t ram_bytes_total(void);
 
 extern SaveVMHandlers savevm_ram_handlers;
 
+uint64_t dup_mig_bytes_transferred(void);
+uint64_t dup_mig_pages_transferred(void);
+uint64_t norm_mig_bytes_transferred(void);
+uint64_t norm_mig_pages_transferred(void);
+
 /**
  * @migrate_add_blocker - prevent migration from proceeding
  *
diff --git a/qapi-schema.json b/qapi-schema.json
index 901cdf1..3f67b1e 100644
--- a/qapi-schema.json
+++ b/qapi-schema.json
@@ -264,11 +264,18 @@
 #        migration has ended, it returns the total migration
 #        time. (since 1.2)
 #
-# Since: 0.14.0.
+# @duplicate: number of duplicate pages (since 1.2)
+#
+# @normal : number of normal pages (since 1.2)
+#
+# @normal-bytes : number of normal bytes sent (since 1.2)
+#
+# Since: 0.14.0
 ##
 { 'type': 'MigrationStats',
   'data': {'transferred': 'int', 'remaining': 'int', 'total': 'int' ,
-           'total-time': 'int' } }
+           'total-time': 'int', 'duplicate': 'int', 'normal': 'int',
+           'normal-bytes': 'int' } }
 
 ##
 # @MigrationInfo
diff --git a/qmp-commands.hx b/qmp-commands.hx
index d426e56..c3368f3 100644
--- a/qmp-commands.hx
+++ b/qmp-commands.hx
@@ -2125,6 +2125,9 @@ The main json-object contains the following:
          - "total-time": total amount of ms since migration started.  If
                          migration has ended, it returns the total migration time
                          (json-int)
+         - "duplicate": number of duplicated pages (json-int)
+         - "normal" : number of normal pages transferred (json-int)
+         - "normal-bytes" : number of normal bytes transferred (json-int)
 - "disk": only present if "status" is "active" and it is a block migration,
   it is a json-object with the following disk information (in bytes):
          - "transferred": amount transferred (json-int)
@@ -2141,7 +2144,19 @@ Examples:
 2. Migration is done and has succeeded
 
 -> { "execute": "query-migrate" }
-<- { "return": { "status": "completed" } }
+<- { "return": {
+        "status": "completed",
+        "ram":{
+          "transferred":123,
+          "remaining":123,
+          "total":246,
+          "total-time":12345,
+          "duplicate":123,
+          "normal":123,
+          "normal-bytes":123456
+        }
+     }
+   }
 
 3. Migration is done and has failed
 
@@ -2158,7 +2173,10 @@ Examples:
             "transferred":123,
             "remaining":123,
             "total":246,
-            "total-time":12345
+            "total-time":12345,
+            "duplicate":123,
+            "normal":123,
+            "normal-bytes":123456
          }
       }
    }
@@ -2173,7 +2191,10 @@ Examples:
             "total":1057024,
             "remaining":1053304,
             "transferred":3720,
-            "total-time":12345
+            "total-time":12345,
+            "duplicate":123,
+            "normal":123,
+            "normal-bytes":123456
          },
          "disk":{
             "total":20971520,
commit 62d4e3fe31844ee76bf2314bf1c22d25bad37589
Author: Orit Wasserman <owasserm at redhat.com>
Date:   Mon Aug 6 21:42:55 2012 +0300

    Change total_time to total-time in MigrationStats
    
    migration total_time was introduced in commit
    d5f8a5701d3690b5ec0c34b6a5c0b5a24d274540 for QEMU 1.2
    
    Signed-off-by: Orit Wasserman <owasserm at redhat.com>
    
    Reviewed-by: Luiz Capitulino <lcapitulino at redhat.com>
    Reviewed-by: Eric Blake <eblake at redhat.com>

diff --git a/qapi-schema.json b/qapi-schema.json
index dd16dbd..901cdf1 100644
--- a/qapi-schema.json
+++ b/qapi-schema.json
@@ -260,7 +260,7 @@
 #
 # @total: total amount of bytes involved in the migration process
 #
-# @total_time: tota0l amount of ms since migration started.  If
+# @total-time: total amount of ms since migration started.  If
 #        migration has ended, it returns the total migration
 #        time. (since 1.2)
 #
@@ -268,7 +268,7 @@
 ##
 { 'type': 'MigrationStats',
   'data': {'transferred': 'int', 'remaining': 'int', 'total': 'int' ,
-           'total_time': 'int' } }
+           'total-time': 'int' } }
 
 ##
 # @MigrationInfo
diff --git a/qmp-commands.hx b/qmp-commands.hx
index e42b4e3..d426e56 100644
--- a/qmp-commands.hx
+++ b/qmp-commands.hx
@@ -2122,6 +2122,9 @@ The main json-object contains the following:
          - "transferred": amount transferred (json-int)
          - "remaining": amount remaining (json-int)
          - "total": total (json-int)
+         - "total-time": total amount of ms since migration started.  If
+                         migration has ended, it returns the total migration time
+                         (json-int)
 - "disk": only present if "status" is "active" and it is a block migration,
   it is a json-object with the following disk information (in bytes):
          - "transferred": amount transferred (json-int)
@@ -2154,7 +2157,8 @@ Examples:
          "ram":{
             "transferred":123,
             "remaining":123,
-            "total":246
+            "total":246,
+            "total-time":12345
          }
       }
    }
@@ -2168,7 +2172,8 @@ Examples:
          "ram":{
             "total":1057024,
             "remaining":1053304,
-            "transferred":3720
+            "transferred":3720,
+            "total-time":12345
          },
          "disk":{
             "total":20971520,
commit 9e1ba4cc4e2536d9650e84e2614c5691ed45938f
Author: Orit Wasserman <owasserm at redhat.com>
Date:   Mon Aug 6 21:42:54 2012 +0300

    Add migrate_set_cache_size command
    
    Change XBZRLE cache size in bytes (the size should be a power of 2, it will be
    rounded down to the nearest power of 2).
    If XBZRLE cache size is too small there will be many cache miss.
    
    New query-migrate-cache-size QMP command and 'info migrate_cache_size' HMP
    command to query cache value.
    
    Signed-off-by: Benoit Hudzia <benoit.hudzia at sap.com>
    Signed-off-by: Petter Svard <petters at cs.umu.se>
    Signed-off-by: Aidan Shribman <aidan.shribman at sap.com>
    Signed-off-by: Orit Wasserman <owasserm at redhat.com>
    
    Reviewed-by: Luiz Capitulino <lcapitulino at redhat.com>
    Reviewed-by: Eric Blake <eblake at redhat.com>

diff --git a/arch_init.c b/arch_init.c
index 8cff9c6..7fbfe91 100644
--- a/arch_init.c
+++ b/arch_init.c
@@ -191,6 +191,16 @@ static struct {
     .cache = NULL,
 };
 
+
+int64_t xbzrle_cache_resize(int64_t new_size)
+{
+    if (XBZRLE.cache != NULL) {
+        return cache_resize(XBZRLE.cache, new_size / TARGET_PAGE_SIZE) *
+            TARGET_PAGE_SIZE;
+    }
+    return pow2floor(new_size);
+}
+
 static void save_block_hdr(QEMUFile *f, RAMBlock *block, ram_addr_t offset,
         int cont, int flag)
 {
diff --git a/hmp-commands.hx b/hmp-commands.hx
index 476b3cd..f6104b0 100644
--- a/hmp-commands.hx
+++ b/hmp-commands.hx
@@ -829,6 +829,26 @@ STEXI
 @item migrate_cancel
 @findex migrate_cancel
 Cancel the current VM migration.
+
+ETEXI
+
+    {
+        .name       = "migrate_set_cache_size",
+        .args_type  = "value:o",
+        .params     = "value",
+        .help       = "set cache size (in bytes) for XBZRLE migrations,"
+                      "the cache size will be rounded down to the nearest "
+                      "power of 2.\n"
+                      "The cache size affects the number of cache misses."
+                      "In case of a high cache miss ratio you need to increase"
+                      " the cache size",
+        .mhandler.cmd = hmp_migrate_set_cache_size,
+    },
+
+STEXI
+ at item migrate_set_cache_size @var{value}
+ at findex migrate_set_cache_size
+Set cache size to @var{value} (in bytes) for xbzrle migrations.
 ETEXI
 
     {
@@ -1433,6 +1453,8 @@ show user network stack connection states
 show migration status
 @item info migrate_capabilities
 show current migration capabilities
+ at item info migrate_cache_size
+show current migration XBZRLE cache size
 @item info balloon
 show balloon information
 @item info qtree
diff --git a/hmp.c b/hmp.c
index 2a03b44..8abb4bd 100644
--- a/hmp.c
+++ b/hmp.c
@@ -194,6 +194,12 @@ void hmp_info_migrate_capabilities(Monitor *mon)
     qapi_free_MigrationCapabilityStatusList(caps);
 }
 
+void hmp_info_migrate_cache_size(Monitor *mon)
+{
+    monitor_printf(mon, "xbzrel cache size: %" PRId64 " kbytes\n",
+                   qmp_query_migrate_cache_size(NULL) >> 10);
+}
+
 void hmp_info_cpus(Monitor *mon)
 {
     CpuInfoList *cpu_list, *cpu;
@@ -764,6 +770,19 @@ void hmp_migrate_set_downtime(Monitor *mon, const QDict *qdict)
     qmp_migrate_set_downtime(value, NULL);
 }
 
+void hmp_migrate_set_cache_size(Monitor *mon, const QDict *qdict)
+{
+    int64_t value = qdict_get_int(qdict, "value");
+    Error *err = NULL;
+
+    qmp_migrate_set_cache_size(value, &err);
+    if (err) {
+        monitor_printf(mon, "%s\n", error_get_pretty(err));
+        error_free(err);
+        return;
+    }
+}
+
 void hmp_migrate_set_speed(Monitor *mon, const QDict *qdict)
 {
     int64_t value = qdict_get_int(qdict, "value");
diff --git a/hmp.h b/hmp.h
index 3390a92..6d6e53b 100644
--- a/hmp.h
+++ b/hmp.h
@@ -26,6 +26,7 @@ void hmp_info_chardev(Monitor *mon);
 void hmp_info_mice(Monitor *mon);
 void hmp_info_migrate(Monitor *mon);
 void hmp_info_migrate_capabilities(Monitor *mon);
+void hmp_info_migrate_cache_size(Monitor *mon);
 void hmp_info_cpus(Monitor *mon);
 void hmp_info_block(Monitor *mon);
 void hmp_info_blockstats(Monitor *mon);
@@ -53,6 +54,7 @@ void hmp_migrate_cancel(Monitor *mon, const QDict *qdict);
 void hmp_migrate_set_downtime(Monitor *mon, const QDict *qdict);
 void hmp_migrate_set_speed(Monitor *mon, const QDict *qdict);
 void hmp_migrate_set_capability(Monitor *mon, const QDict *qdict);
+void hmp_migrate_set_cache_size(Monitor *mon, const QDict *qdict);
 void hmp_set_password(Monitor *mon, const QDict *qdict);
 void hmp_expire_password(Monitor *mon, const QDict *qdict);
 void hmp_eject(Monitor *mon, const QDict *qdict);
diff --git a/migration.c b/migration.c
index 5a5333c..a6c0072 100644
--- a/migration.c
+++ b/migration.c
@@ -511,6 +511,25 @@ void qmp_migrate_cancel(Error **errp)
     migrate_fd_cancel(migrate_get_current());
 }
 
+void qmp_migrate_set_cache_size(int64_t value, Error **errp)
+{
+    MigrationState *s = migrate_get_current();
+
+    /* Check for truncation */
+    if (value != (size_t)value) {
+        error_set(errp, QERR_INVALID_PARAMETER_VALUE, "cache size",
+                  "exceeding address space");
+        return;
+    }
+
+    s->xbzrle_cache_size = xbzrle_cache_resize(value);
+}
+
+int64_t qmp_query_migrate_cache_size(Error **errp)
+{
+    return migrate_xbzrle_cache_size();
+}
+
 void qmp_migrate_set_speed(int64_t value, Error **errp)
 {
     MigrationState *s;
diff --git a/migration.h b/migration.h
index cdf6787..337e225 100644
--- a/migration.h
+++ b/migration.h
@@ -108,4 +108,6 @@ int xbzrle_decode_buffer(uint8_t *src, int slen, uint8_t *dst, int dlen);
 int migrate_use_xbzrle(void);
 int64_t migrate_xbzrle_cache_size(void);
 
+int64_t xbzrle_cache_resize(int64_t new_size);
+
 #endif
diff --git a/monitor.c b/monitor.c
index 13b681a..5227cf1 100644
--- a/monitor.c
+++ b/monitor.c
@@ -2662,6 +2662,13 @@ static mon_cmd_t info_cmds[] = {
         .mhandler.info = hmp_info_migrate_capabilities,
     },
     {
+        .name       = "migrate_cache_size",
+        .args_type  = "",
+        .params     = "",
+        .help       = "show current migration xbzrle cache size",
+        .mhandler.info = hmp_info_migrate_cache_size,
+    },
+    {
         .name       = "balloon",
         .args_type  = "",
         .params     = "",
diff --git a/qapi-schema.json b/qapi-schema.json
index e3847c8..dd16dbd 100644
--- a/qapi-schema.json
+++ b/qapi-schema.json
@@ -1395,6 +1395,33 @@
 { 'command': 'migrate_set_speed', 'data': {'value': 'int'} }
 
 ##
+# @migrate-set-cache-size
+#
+# Set XBZRLE cache size
+#
+# @value: cache size in bytes
+#
+# The size will be rounded down to the nearest power of 2.
+# The cache size can be modified before and during ongoing migration
+#
+# Returns: nothing on success
+#
+# Since: 1.2
+##
+{ 'command': 'migrate-set-cache-size', 'data': {'value': 'int'} }
+
+##
+# @query-migrate-cache-size
+#
+# query XBZRLE cache size
+#
+# Returns: XBZRLE cache size in bytes
+#
+# Since: 1.2
+##
+{ 'command': 'query-migrate-cache-size', 'returns': 'int' }
+
+##
 # @ObjectPropertyInfo:
 #
 # @name: the name of the property
diff --git a/qmp-commands.hx b/qmp-commands.hx
index a14db90..e42b4e3 100644
--- a/qmp-commands.hx
+++ b/qmp-commands.hx
@@ -520,6 +520,50 @@ Example:
 <- { "return": {} }
 
 EQMP
+{
+        .name       = "migrate-set-cache-size",
+        .args_type  = "value:o",
+        .mhandler.cmd_new = qmp_marshal_input_migrate_set_cache_size,
+    },
+
+SQMP
+migrate-set-cache-size
+---------------------
+
+Set cache size to be used by XBZRLE migration, the cache size will be rounded
+down to the nearest power of 2
+
+Arguments:
+
+- "value": cache size in bytes (json-int)
+
+Example:
+
+-> { "execute": "migrate-set-cache-size", "arguments": { "value": 536870912 } }
+<- { "return": {} }
+
+EQMP
+    {
+        .name       = "query-migrate-cache-size",
+        .args_type  = "",
+        .mhandler.cmd_new = qmp_marshal_input_query_migrate_cache_size,
+    },
+
+SQMP
+query-migrate-cache-size
+---------------------
+
+Show cache size to be used by XBZRLE migration
+
+returns a json-object with the following information:
+- "size" : json-int
+
+Example:
+
+-> { "execute": "query-migrate-cache-size" }
+<- { "return": 67108864 }
+
+EQMP
 
     {
         .name       = "migrate_set_speed",
commit 17ad9b358bceba78ae80f2963c6036eab726010c
Author: Orit Wasserman <owasserm at redhat.com>
Date:   Mon Aug 6 21:42:53 2012 +0300

    Add XBZRLE to ram_save_block and ram_save_live
    
    In the outgoing migration check to see if the page is cached and
    changed, then send compressed page by using save_xbrle_page function.
    In the incoming migration check to see if RAM_SAVE_FLAG_XBZRLE is set
    and decompress the page (by using load_xbrle function).
    
    Signed-off-by: Benoit Hudzia <benoit.hudzia at sap.com>
    Signed-off-by: Petter Svard <petters at cs.umu.se>
    Signed-off-by: Aidan Shribman <aidan.shribman at sap.com>
    Signed-off-by: Orit Wasserman <owasserm at redhat.com>
    
    Reviewed-by: Luiz Capitulino <lcapitulino at redhat.com>
    Reviewed-by: Eric Blake <eblake at redhat.com>

diff --git a/arch_init.c b/arch_init.c
index 60823ba..8cff9c6 100644
--- a/arch_init.c
+++ b/arch_init.c
@@ -43,6 +43,7 @@
 #include "hw/smbios.h"
 #include "exec-memory.h"
 #include "hw/pcspk.h"
+#include "qemu/page_cache.h"
 
 #ifdef DEBUG_ARCH_INIT
 #define DPRINTF(fmt, ...) \
@@ -104,6 +105,7 @@ const uint32_t arch_type = QEMU_ARCH;
 #define RAM_SAVE_FLAG_PAGE     0x08
 #define RAM_SAVE_FLAG_EOS      0x10
 #define RAM_SAVE_FLAG_CONTINUE 0x20
+#define RAM_SAVE_FLAG_XBZRLE   0x40
 
 #ifdef __ALTIVEC__
 #include <altivec.h>
@@ -171,6 +173,24 @@ static int is_dup_page(uint8_t *page)
     return 1;
 }
 
+/* struct contains XBZRLE cache and a static page
+   used by the compression */
+static struct {
+    /* buffer used for XBZRLE encoding */
+    uint8_t *encoded_buf;
+    /* buffer for storing page content */
+    uint8_t *current_buf;
+    /* buffer used for XBZRLE decoding */
+    uint8_t *decoded_buf;
+    /* Cache for XBZRLE */
+    PageCache *cache;
+} XBZRLE = {
+    .encoded_buf = NULL,
+    .current_buf = NULL,
+    .decoded_buf = NULL,
+    .cache = NULL,
+};
+
 static void save_block_hdr(QEMUFile *f, RAMBlock *block, ram_addr_t offset,
         int cont, int flag)
 {
@@ -183,6 +203,53 @@ static void save_block_hdr(QEMUFile *f, RAMBlock *block, ram_addr_t offset,
 
 }
 
+#define ENCODING_FLAG_XBZRLE 0x1
+
+static int save_xbzrle_page(QEMUFile *f, uint8_t *current_data,
+                            ram_addr_t current_addr, RAMBlock *block,
+                            ram_addr_t offset, int cont)
+{
+    int encoded_len = 0, bytes_sent = -1;
+    uint8_t *prev_cached_page;
+
+    if (!cache_is_cached(XBZRLE.cache, current_addr)) {
+        cache_insert(XBZRLE.cache, current_addr,
+                     g_memdup(current_data, TARGET_PAGE_SIZE));
+        return -1;
+    }
+
+    prev_cached_page = get_cached_data(XBZRLE.cache, current_addr);
+
+    /* save current buffer into memory */
+    memcpy(XBZRLE.current_buf, current_data, TARGET_PAGE_SIZE);
+
+    /* XBZRLE encoding (if there is no overflow) */
+    encoded_len = xbzrle_encode_buffer(prev_cached_page, XBZRLE.current_buf,
+                                       TARGET_PAGE_SIZE, XBZRLE.encoded_buf,
+                                       TARGET_PAGE_SIZE);
+    if (encoded_len == 0) {
+        DPRINTF("Skipping unmodified page\n");
+        return 0;
+    } else if (encoded_len == -1) {
+        DPRINTF("Overflow\n");
+        /* update data in the cache */
+        memcpy(prev_cached_page, current_data, TARGET_PAGE_SIZE);
+        return -1;
+    }
+
+    /* we need to update the data in the cache, in order to get the same data */
+    memcpy(prev_cached_page, XBZRLE.current_buf, TARGET_PAGE_SIZE);
+
+    /* Send XBZRLE based compressed page */
+    save_block_hdr(f, block, offset, cont, RAM_SAVE_FLAG_XBZRLE);
+    qemu_put_byte(f, ENCODING_FLAG_XBZRLE);
+    qemu_put_be16(f, encoded_len);
+    qemu_put_buffer(f, XBZRLE.encoded_buf, encoded_len);
+    bytes_sent = encoded_len + 1 + 2;
+
+    return bytes_sent;
+}
+
 static RAMBlock *last_block;
 static ram_addr_t last_offset;
 
@@ -200,6 +267,7 @@ static int ram_save_block(QEMUFile *f)
     ram_addr_t offset = last_offset;
     int bytes_sent = -1;
     MemoryRegion *mr;
+    ram_addr_t current_addr;
 
     if (!block)
         block = QLIST_FIRST(&ram_list.blocks);
@@ -220,13 +288,24 @@ static int ram_save_block(QEMUFile *f)
                 save_block_hdr(f, block, offset, cont, RAM_SAVE_FLAG_COMPRESS);
                 qemu_put_byte(f, *p);
                 bytes_sent = 1;
-            } else {
+            } else if (migrate_use_xbzrle()) {
+                current_addr = block->offset + offset;
+                bytes_sent = save_xbzrle_page(f, p, current_addr, block,
+                                              offset, cont);
+                p = get_cached_data(XBZRLE.cache, current_addr);
+            }
+
+            /* either we didn't send yet (we may have had XBZRLE overflow) */
+            if (bytes_sent == -1) {
                 save_block_hdr(f, block, offset, cont, RAM_SAVE_FLAG_PAGE);
                 qemu_put_buffer(f, p, TARGET_PAGE_SIZE);
                 bytes_sent = TARGET_PAGE_SIZE;
             }
 
-            break;
+            /* if page is unmodified, continue to the next */
+            if (bytes_sent != 0) {
+                break;
+            }
         }
 
         offset += TARGET_PAGE_SIZE;
@@ -304,6 +383,15 @@ static void sort_ram_list(void)
 static void migration_end(void)
 {
     memory_global_dirty_log_stop();
+
+    if (migrate_use_xbzrle()) {
+        cache_fini(XBZRLE.cache);
+        g_free(XBZRLE.cache);
+        g_free(XBZRLE.encoded_buf);
+        g_free(XBZRLE.current_buf);
+        g_free(XBZRLE.decoded_buf);
+        XBZRLE.cache = NULL;
+    }
 }
 
 static void ram_migration_cancel(void *opaque)
@@ -323,6 +411,18 @@ static int ram_save_setup(QEMUFile *f, void *opaque)
     last_offset = 0;
     sort_ram_list();
 
+    if (migrate_use_xbzrle()) {
+        XBZRLE.cache = cache_init(migrate_xbzrle_cache_size() /
+                                  TARGET_PAGE_SIZE,
+                                  TARGET_PAGE_SIZE);
+        if (!XBZRLE.cache) {
+            DPRINTF("Error creating cache\n");
+            return -1;
+        }
+        XBZRLE.encoded_buf = g_malloc0(TARGET_PAGE_SIZE);
+        XBZRLE.current_buf = g_malloc(TARGET_PAGE_SIZE);
+    }
+
     /* Make sure all dirty bits are set */
     QLIST_FOREACH(block, &ram_list.blocks, next) {
         for (addr = 0; addr < block->length; addr += TARGET_PAGE_SIZE) {
@@ -438,6 +538,47 @@ static int ram_save_complete(QEMUFile *f, void *opaque)
     return 0;
 }
 
+static int load_xbzrle(QEMUFile *f, ram_addr_t addr, void *host)
+{
+    int ret, rc = 0;
+    unsigned int xh_len;
+    int xh_flags;
+
+    if (!XBZRLE.decoded_buf) {
+        XBZRLE.decoded_buf = g_malloc(TARGET_PAGE_SIZE);
+    }
+
+    /* extract RLE header */
+    xh_flags = qemu_get_byte(f);
+    xh_len = qemu_get_be16(f);
+
+    if (xh_flags != ENCODING_FLAG_XBZRLE) {
+        fprintf(stderr, "Failed to load XBZRLE page - wrong compression!\n");
+        return -1;
+    }
+
+    if (xh_len > TARGET_PAGE_SIZE) {
+        fprintf(stderr, "Failed to load XBZRLE page - len overflow!\n");
+        return -1;
+    }
+    /* load data and decode */
+    qemu_get_buffer(f, XBZRLE.decoded_buf, xh_len);
+
+    /* decode RLE */
+    ret = xbzrle_decode_buffer(XBZRLE.decoded_buf, xh_len, host,
+                               TARGET_PAGE_SIZE);
+    if (ret == -1) {
+        fprintf(stderr, "Failed to load XBZRLE page - decode error!\n");
+        rc = -1;
+    } else  if (ret > TARGET_PAGE_SIZE) {
+        fprintf(stderr, "Failed to load XBZRLE page - size %d exceeds %d!\n",
+                ret, TARGET_PAGE_SIZE);
+        abort();
+    }
+
+    return rc;
+}
+
 static inline void *host_from_stream_offset(QEMUFile *f,
                                             ram_addr_t offset,
                                             int flags)
@@ -551,6 +692,19 @@ static int ram_load(QEMUFile *f, void *opaque, int version_id)
             }
 
             qemu_get_buffer(f, host, TARGET_PAGE_SIZE);
+        } else if (flags & RAM_SAVE_FLAG_XBZRLE) {
+            if (!migrate_use_xbzrle()) {
+                return -EINVAL;
+            }
+            void *host = host_from_stream_offset(f, addr, flags);
+            if (!host) {
+                return -EINVAL;
+            }
+
+            if (load_xbzrle(f, addr, host) < 0) {
+                ret = -EINVAL;
+                goto done;
+            }
         }
         error = qemu_file_get_error(f);
         if (error) {
diff --git a/migration.c b/migration.c
index ba81df7..5a5333c 100644
--- a/migration.c
+++ b/migration.c
@@ -43,6 +43,9 @@ enum {
 
 #define MAX_THROTTLE  (32 << 20)      /* Migration speed throttling */
 
+/* Migration XBZRLE default cache size */
+#define DEFAULT_MIGRATE_CACHE_SIZE (64 * 1024 * 1024)
+
 static NotifierList migration_state_notifiers =
     NOTIFIER_LIST_INITIALIZER(migration_state_notifiers);
 
@@ -55,6 +58,7 @@ static MigrationState *migrate_get_current(void)
     static MigrationState current_migration = {
         .state = MIG_STATE_SETUP,
         .bandwidth_limit = MAX_THROTTLE,
+        .xbzrle_cache_size = DEFAULT_MIGRATE_CACHE_SIZE,
     };
 
     return &current_migration;
@@ -416,6 +420,7 @@ static MigrationState *migrate_init(const MigrationParams *params)
     MigrationState *s = migrate_get_current();
     int64_t bandwidth_limit = s->bandwidth_limit;
     bool enabled_capabilities[MIGRATION_CAPABILITY_MAX];
+    int64_t xbzrle_cache_size = s->xbzrle_cache_size;
 
     memcpy(enabled_capabilities, s->enabled_capabilities,
            sizeof(enabled_capabilities));
@@ -425,6 +430,7 @@ static MigrationState *migrate_init(const MigrationParams *params)
     s->params = *params;
     memcpy(s->enabled_capabilities, enabled_capabilities,
            sizeof(enabled_capabilities));
+    s->xbzrle_cache_size = xbzrle_cache_size;
 
     s->bandwidth_limit = bandwidth_limit;
     s->state = MIG_STATE_SETUP;
@@ -524,3 +530,21 @@ void qmp_migrate_set_downtime(double value, Error **errp)
     value = MAX(0, MIN(UINT64_MAX, value));
     max_downtime = (uint64_t)value;
 }
+
+int migrate_use_xbzrle(void)
+{
+    MigrationState *s;
+
+    s = migrate_get_current();
+
+    return s->enabled_capabilities[MIGRATION_CAPABILITY_XBZRLE];
+}
+
+int64_t migrate_xbzrle_cache_size(void)
+{
+    MigrationState *s;
+
+    s = migrate_get_current();
+
+    return s->xbzrle_cache_size;
+}
diff --git a/migration.h b/migration.h
index 743c366..cdf6787 100644
--- a/migration.h
+++ b/migration.h
@@ -41,6 +41,7 @@ struct MigrationState
     MigrationParams params;
     int64_t total_time;
     bool enabled_capabilities[MIGRATION_CAPABILITY_MAX];
+    int64_t xbzrle_cache_size;
 };
 
 void process_incoming_migration(QEMUFile *f);
@@ -104,4 +105,7 @@ int xbzrle_encode_buffer(uint8_t *old_buf, uint8_t *new_buf, int slen,
                          uint8_t *dst, int dlen);
 int xbzrle_decode_buffer(uint8_t *src, int slen, uint8_t *dst, int dlen);
 
+int migrate_use_xbzrle(void);
+int64_t migrate_xbzrle_cache_size(void);
+
 #endif
commit 302dfbeb21fc5154c24ca50d296e865a3778c7da
Author: Orit Wasserman <owasserm at redhat.com>
Date:   Mon Aug 6 21:42:52 2012 +0300

    Add xbzrle_encode_buffer and xbzrle_decode_buffer functions
    
    For performance we are encoding long word at a time.
    For nzrun we use long-word-at-a-time NULL-detection tricks from strcmp():
    using ((lword - 0x0101010101010101) & (~lword) & 0x8080808080808080) test
    to find out if any byte in the long word is zero.
    
    Signed-off-by: Benoit Hudzia <benoit.hudzia at sap.com>
    Signed-off-by: Petter Svard <petters at cs.umu.se>
    Signed-off-by: Aidan Shribman <aidan.shribman at sap.com>
    Signed-off-by: Orit Wasserman <owasserm at redhat.com>
    Signed-off-by: Eric Blake <eblake at redhat.com>
    
    Reviewed-by: Luiz Capitulino <lcapitulino at redhat.com>
    Reviewed-by: Eric Blake <eblake at redhat.com>

diff --git a/migration.h b/migration.h
index 713aae0..743c366 100644
--- a/migration.h
+++ b/migration.h
@@ -100,4 +100,8 @@ void migrate_add_blocker(Error *reason);
  */
 void migrate_del_blocker(Error *reason);
 
+int xbzrle_encode_buffer(uint8_t *old_buf, uint8_t *new_buf, int slen,
+                         uint8_t *dst, int dlen);
+int xbzrle_decode_buffer(uint8_t *src, int slen, uint8_t *dst, int dlen);
+
 #endif
diff --git a/savevm.c b/savevm.c
index 6e82b2d..0ea10c9 100644
--- a/savevm.c
+++ b/savevm.c
@@ -2392,3 +2392,162 @@ void vmstate_register_ram_global(MemoryRegion *mr)
 {
     vmstate_register_ram(mr, NULL);
 }
+
+/*
+  page = zrun nzrun
+       | zrun nzrun page
+
+  zrun = length
+
+  nzrun = length byte...
+
+  length = uleb128 encoded integer
+ */
+int xbzrle_encode_buffer(uint8_t *old_buf, uint8_t *new_buf, int slen,
+                         uint8_t *dst, int dlen)
+{
+    uint32_t zrun_len = 0, nzrun_len = 0;
+    int d = 0, i = 0;
+    long res, xor;
+    uint8_t *nzrun_start = NULL;
+
+    g_assert(!(((uintptr_t)old_buf | (uintptr_t)new_buf | slen) %
+               sizeof(long)));
+
+    while (i < slen) {
+        /* overflow */
+        if (d + 2 > dlen) {
+            return -1;
+        }
+
+        /* not aligned to sizeof(long) */
+        res = (slen - i) % sizeof(long);
+        while (res && old_buf[i] == new_buf[i]) {
+            zrun_len++;
+            i++;
+            res--;
+        }
+
+        /* word at a time for speed */
+        if (!res) {
+            while (i < slen &&
+                   (*(long *)(old_buf + i)) == (*(long *)(new_buf + i))) {
+                i += sizeof(long);
+                zrun_len += sizeof(long);
+            }
+
+            /* go over the rest */
+            while (i < slen && old_buf[i] == new_buf[i]) {
+                zrun_len++;
+                i++;
+            }
+        }
+
+        /* buffer unchanged */
+        if (zrun_len == slen) {
+            return 0;
+        }
+
+        /* skip last zero run */
+        if (i == slen) {
+            return d;
+        }
+
+        d += uleb128_encode_small(dst + d, zrun_len);
+
+        zrun_len = 0;
+        nzrun_start = new_buf + i;
+
+        /* overflow */
+        if (d + 2 > dlen) {
+            return -1;
+        }
+        /* not aligned to sizeof(long) */
+        res = (slen - i) % sizeof(long);
+        while (res && old_buf[i] != new_buf[i]) {
+            i++;
+            nzrun_len++;
+            res--;
+        }
+
+        /* word at a time for speed, use of 32-bit long okay */
+        if (!res) {
+            /* truncation to 32-bit long okay */
+            long mask = 0x0101010101010101ULL;
+            while (i < slen) {
+                xor = *(long *)(old_buf + i) ^ *(long *)(new_buf + i);
+                if ((xor - mask) & ~xor & (mask << 7)) {
+                    /* found the end of an nzrun within the current long */
+                    while (old_buf[i] != new_buf[i]) {
+                        nzrun_len++;
+                        i++;
+                    }
+                    break;
+                } else {
+                    i += sizeof(long);
+                    nzrun_len += sizeof(long);
+                }
+            }
+        }
+
+        d += uleb128_encode_small(dst + d, nzrun_len);
+        /* overflow */
+        if (d + nzrun_len > dlen) {
+            return -1;
+        }
+        memcpy(dst + d, nzrun_start, nzrun_len);
+        d += nzrun_len;
+        nzrun_len = 0;
+    }
+
+    return d;
+}
+
+int xbzrle_decode_buffer(uint8_t *src, int slen, uint8_t *dst, int dlen)
+{
+    int i = 0, d = 0;
+    int ret;
+    uint32_t count = 0;
+
+    while (i < slen) {
+
+        /* zrun */
+        if ((slen - i) < 2) {
+            return -1;
+        }
+
+        ret = uleb128_decode_small(src + i, &count);
+        if (ret < 0 || (i && !count)) {
+            return -1;
+        }
+        i += ret;
+        d += count;
+
+        /* overflow */
+        if (d > dlen) {
+            return -1;
+        }
+
+        /* nzrun */
+        if ((slen - i) < 2) {
+            return -1;
+        }
+
+        ret = uleb128_decode_small(src + i, &count);
+        if (ret < 0 || !count) {
+            return -1;
+        }
+        i += ret;
+
+        /* overflow */
+        if (d + count > dlen || i + count > slen) {
+            return -1;
+        }
+
+        memcpy(dst + d, src + i, count);
+        d += count;
+        i += count;
+    }
+
+    return d;
+}
commit e6546bb938f5326269b6669d6cbb44d72458caa4
Author: Orit Wasserman <owasserm at redhat.com>
Date:   Mon Aug 6 21:42:51 2012 +0300

    Add uleb encoding/decoding functions
    
    Implement Unsigned Little Endian Base 128.
    
    Signed-off-by: Orit Wasserman <owasserm at redhat.com>
    
    Reviewed-by: Luiz Capitulino <lcapitulino at redhat.com>
    Reviewed-by: Eric Blake <eblake at redhat.com>

diff --git a/cutils.c b/cutils.c
index 35e2e2b..ee4614d 100644
--- a/cutils.c
+++ b/cutils.c
@@ -391,3 +391,36 @@ int64_t pow2floor(int64_t value)
     }
     return value;
 }
+
+/*
+ * Implementation of  ULEB128 (http://en.wikipedia.org/wiki/LEB128)
+ * Input is limited to 14-bit numbers
+ */
+int uleb128_encode_small(uint8_t *out, uint32_t n)
+{
+    g_assert(n <= 0x3fff);
+    if (n < 0x80) {
+        *out++ = n;
+        return 1;
+    } else {
+        *out++ = (n & 0x7f) | 0x80;
+        *out++ = n >> 7;
+        return 2;
+    }
+}
+
+int uleb128_decode_small(const uint8_t *in, uint32_t *n)
+{
+    if (!(*in & 0x80)) {
+        *n = *in++;
+        return 1;
+    } else {
+        *n = *in++ & 0x7f;
+        /* we exceed 14 bit number */
+        if (*in & 0x80) {
+            return -1;
+        }
+        *n |= *in++ << 7;
+        return 2;
+    }
+}
diff --git a/qemu-common.h b/qemu-common.h
index ff7026e..9c1b955 100644
--- a/qemu-common.h
+++ b/qemu-common.h
@@ -443,4 +443,12 @@ int64_t pow2floor(int64_t value);
 
 #include "module.h"
 
+/*
+ * Implementation of ULEB128 (http://en.wikipedia.org/wiki/LEB128)
+ * Input is limited to 14-bit numbers
+ */
+
+int uleb128_encode_small(uint8_t *out, uint32_t n);
+int uleb128_decode_small(const uint8_t *in, uint32_t *n);
+
 #endif
commit 9fb26641ab497eda9138f9af75cbeb02ed59b5ae
Author: Orit Wasserman <owasserm at redhat.com>
Date:   Mon Aug 6 21:42:50 2012 +0300

    Add cache handling functions
    
    Add MRU page cache mechanism.
    The page are accessed by their address.
    
    Signed-off-by: Benoit Hudzia <benoit.hudzia at sap.com>
    Signed-off-by: Petter Svard <petters at cs.umu.se>
    Signed-off-by: Aidan Shribman <aidan.shribman at sap.com>
    Signed-off-by: Orit Wasserman <owasserm at redhat.com>
    
    Reviewed-by: Luiz Capitulino <lcapitulino at redhat.com>
    Reviewed-by: Eric Blake <eblake at redhat.com>

diff --git a/Makefile.objs b/Makefile.objs
index 5ebbcfa..e0fb69b 100644
--- a/Makefile.objs
+++ b/Makefile.objs
@@ -77,6 +77,7 @@ common-obj-y += qemu-char.o #aio.o
 common-obj-y += block-migration.o iohandler.o
 common-obj-y += pflib.o
 common-obj-y += bitmap.o bitops.o
+common-obj-y += page_cache.o
 
 common-obj-$(CONFIG_POSIX) += migration-exec.o migration-unix.o migration-fd.o
 common-obj-$(CONFIG_WIN32) += version.o
diff --git a/cutils.c b/cutils.c
index 9d4c570..35e2e2b 100644
--- a/cutils.c
+++ b/cutils.c
@@ -382,3 +382,12 @@ int qemu_parse_fd(const char *param)
     }
     return fd;
 }
+
+/* round down to the nearest power of 2*/
+int64_t pow2floor(int64_t value)
+{
+    if (!is_power_of_2(value)) {
+        value = 0x8000000000000000ULL >> clz64(value);
+    }
+    return value;
+}
diff --git a/include/qemu/page_cache.h b/include/qemu/page_cache.h
new file mode 100644
index 0000000..3839ac7
--- /dev/null
+++ b/include/qemu/page_cache.h
@@ -0,0 +1,79 @@
+/*
+ * Page cache for QEMU
+ * The cache is base on a hash of the page address
+ *
+ * Copyright 2012 Red Hat, Inc. and/or its affiliates
+ *
+ * Authors:
+ *  Orit Wasserman  <owasserm at redhat.com>
+ *
+ * This work is licensed under the terms of the GNU GPL, version 2 or later.
+ * See the COPYING file in the top-level directory.
+ *
+ */
+
+#ifndef PAGE_CACHE_H
+#define PAGE_CACHE_H
+
+/* Page cache for storing guest pages */
+typedef struct PageCache PageCache;
+
+/**
+ * cache_init: Initialize the page cache
+ *
+ *
+ * Returns new allocated cache or NULL on error
+ *
+ * @cache pointer to the PageCache struct
+ * @num_pages: cache maximal number of cached pages
+ * @page_size: cache page size
+ */
+PageCache *cache_init(int64_t num_pages, unsigned int page_size);
+
+/**
+ * cache_fini: free all cache resources
+ * @cache pointer to the PageCache struct
+ */
+void cache_fini(PageCache *cache);
+
+/**
+ * cache_is_cached: Checks to see if the page is cached
+ *
+ * Returns %true if page is cached
+ *
+ * @cache pointer to the PageCache struct
+ * @addr: page addr
+ */
+bool cache_is_cached(const PageCache *cache, uint64_t addr);
+
+/**
+ * get_cached_data: Get the data cached for an addr
+ *
+ * Returns pointer to the data cached or NULL if not cached
+ *
+ * @cache pointer to the PageCache struct
+ * @addr: page addr
+ */
+uint8_t *get_cached_data(const PageCache *cache, uint64_t addr);
+
+/**
+ * cache_insert: insert the page into the cache. the previous value will be overwritten
+ *
+ * @cache pointer to the PageCache struct
+ * @addr: page address
+ * @pdata: pointer to the page
+ */
+void cache_insert(PageCache *cache, uint64_t addr, uint8_t *pdata);
+
+/**
+ * cache_resize: resize the page cache. In case of size reduction the extra
+ * pages will be freed
+ *
+ * Returns -1 on error new cache size on success
+ *
+ * @cache pointer to the PageCache struct
+ * @num_pages: new page cache size (in pages)
+ */
+int64_t cache_resize(PageCache *cache, int64_t num_pages);
+
+#endif
diff --git a/page_cache.c b/page_cache.c
new file mode 100644
index 0000000..0294f7e
--- /dev/null
+++ b/page_cache.c
@@ -0,0 +1,218 @@
+/*
+ * Page cache for QEMU
+ * The cache is base on a hash of the page address
+ *
+ * Copyright 2012 Red Hat, Inc. and/or its affiliates
+ *
+ * Authors:
+ *  Orit Wasserman  <owasserm at redhat.com>
+ *
+ * This work is licensed under the terms of the GNU GPL, version 2 or later.
+ * See the COPYING file in the top-level directory.
+ *
+ */
+
+#include <stdint.h>
+#include <stdio.h>
+#include <stdlib.h>
+#include <strings.h>
+#include <string.h>
+#include <sys/time.h>
+#include <sys/types.h>
+#include <stdbool.h>
+#include <glib.h>
+#include <strings.h>
+
+#include "qemu-common.h"
+#include "qemu/page_cache.h"
+
+#ifdef DEBUG_CACHE
+#define DPRINTF(fmt, ...) \
+    do { fprintf(stdout, "cache: " fmt, ## __VA_ARGS__); } while (0)
+#else
+#define DPRINTF(fmt, ...) \
+    do { } while (0)
+#endif
+
+typedef struct CacheItem CacheItem;
+
+struct CacheItem {
+    uint64_t it_addr;
+    uint64_t it_age;
+    uint8_t *it_data;
+};
+
+struct PageCache {
+    CacheItem *page_cache;
+    unsigned int page_size;
+    int64_t max_num_items;
+    uint64_t max_item_age;
+    int64_t num_items;
+};
+
+PageCache *cache_init(int64_t num_pages, unsigned int page_size)
+{
+    int64_t i;
+
+    PageCache *cache;
+
+    if (num_pages <= 0) {
+        DPRINTF("invalid number of pages\n");
+        return NULL;
+    }
+
+    cache = g_malloc(sizeof(*cache));
+
+    /* round down to the nearest power of 2 */
+    if (!is_power_of_2(num_pages)) {
+        num_pages = pow2floor(num_pages);
+        DPRINTF("rounding down to %" PRId64 "\n", num_pages);
+    }
+    cache->page_size = page_size;
+    cache->num_items = 0;
+    cache->max_item_age = 0;
+    cache->max_num_items = num_pages;
+
+    DPRINTF("Setting cache buckets to %" PRId64 "\n", cache->max_num_items);
+
+    cache->page_cache = g_malloc((cache->max_num_items) *
+                                 sizeof(*cache->page_cache));
+
+    for (i = 0; i < cache->max_num_items; i++) {
+        cache->page_cache[i].it_data = NULL;
+        cache->page_cache[i].it_age = 0;
+        cache->page_cache[i].it_addr = -1;
+    }
+
+    return cache;
+}
+
+void cache_fini(PageCache *cache)
+{
+    int64_t i;
+
+    g_assert(cache);
+    g_assert(cache->page_cache);
+
+    for (i = 0; i < cache->max_num_items; i++) {
+        g_free(cache->page_cache[i].it_data);
+    }
+
+    g_free(cache->page_cache);
+    cache->page_cache = NULL;
+}
+
+static size_t cache_get_cache_pos(const PageCache *cache,
+                                  uint64_t address)
+{
+    size_t pos;
+
+    g_assert(cache->max_num_items);
+    pos = (address / cache->page_size) & (cache->max_num_items - 1);
+    return pos;
+}
+
+bool cache_is_cached(const PageCache *cache, uint64_t addr)
+{
+    size_t pos;
+
+    g_assert(cache);
+    g_assert(cache->page_cache);
+
+    pos = cache_get_cache_pos(cache, addr);
+
+    return (cache->page_cache[pos].it_addr == addr);
+}
+
+static CacheItem *cache_get_by_addr(const PageCache *cache, uint64_t addr)
+{
+    size_t pos;
+
+    g_assert(cache);
+    g_assert(cache->page_cache);
+
+    pos = cache_get_cache_pos(cache, addr);
+
+    return &cache->page_cache[pos];
+}
+
+uint8_t *get_cached_data(const PageCache *cache, uint64_t addr)
+{
+    return cache_get_by_addr(cache, addr)->it_data;
+}
+
+void cache_insert(PageCache *cache, uint64_t addr, uint8_t *pdata)
+{
+
+    CacheItem *it = NULL;
+
+    g_assert(cache);
+    g_assert(cache->page_cache);
+
+    /* actual update of entry */
+    it = cache_get_by_addr(cache, addr);
+
+    if (!it->it_data) {
+        cache->num_items++;
+    }
+
+    it->it_data = pdata;
+    it->it_age = ++cache->max_item_age;
+    it->it_addr = addr;
+}
+
+int64_t cache_resize(PageCache *cache, int64_t new_num_pages)
+{
+    PageCache *new_cache;
+    int64_t i;
+
+    CacheItem *old_it, *new_it;
+
+    g_assert(cache);
+
+    /* cache was not inited */
+    if (cache->page_cache == NULL) {
+        return -1;
+    }
+
+    /* same size */
+    if (pow2floor(new_num_pages) == cache->max_num_items) {
+        return cache->max_num_items;
+    }
+
+    new_cache = cache_init(new_num_pages, cache->page_size);
+    if (!(new_cache)) {
+        DPRINTF("Error creating new cache\n");
+        return -1;
+    }
+
+    /* move all data from old cache */
+    for (i = 0; i < cache->max_num_items; i++) {
+        old_it = &cache->page_cache[i];
+        if (old_it->it_addr != -1) {
+            /* check for collision, if there is, keep MRU page */
+            new_it = cache_get_by_addr(new_cache, old_it->it_addr);
+            if (new_it->it_data) {
+                /* keep the MRU page */
+                if (new_it->it_age >= old_it->it_age) {
+                    g_free(old_it->it_data);
+                } else {
+                    g_free(new_it->it_data);
+                    new_it->it_data = old_it->it_data;
+                    new_it->it_age = old_it->it_age;
+                    new_it->it_addr = old_it->it_addr;
+                }
+            } else {
+                cache_insert(new_cache, old_it->it_addr, old_it->it_data);
+            }
+        }
+    }
+
+    cache->page_cache = new_cache->page_cache;
+    cache->max_num_items = new_cache->max_num_items;
+    cache->num_items = new_cache->num_items;
+
+    g_free(new_cache);
+
+    return cache->max_num_items;
+}
diff --git a/qemu-common.h b/qemu-common.h
index f16079f..ff7026e 100644
--- a/qemu-common.h
+++ b/qemu-common.h
@@ -1,3 +1,4 @@
+
 /* Common header file that is included by all of qemu.  */
 #ifndef QEMU_COMMON_H
 #define QEMU_COMMON_H
@@ -428,6 +429,18 @@ static inline uint64_t muldiv64(uint64_t a, uint32_t b, uint32_t c)
 /* Round number up to multiple */
 #define QEMU_ALIGN_UP(n, m) QEMU_ALIGN_DOWN((n) + (m) - 1, (m))
 
+static inline bool is_power_of_2(uint64_t value)
+{
+    if (!value) {
+        return 0;
+    }
+
+    return !(value & (value - 1));
+}
+
+/* round down to the nearest power of 2*/
+int64_t pow2floor(int64_t value);
+
 #include "module.h"
 
 #endif
commit 34c26412b76840e0cab9808047e29aebd429c139
Author: Orit Wasserman <owasserm at redhat.com>
Date:   Mon Aug 6 21:42:49 2012 +0300

    Add XBZRLE documentation
    
    Signed-off-by: Orit Wasserman <owasserm at redhat.com>
    
    Reviewed-by: Luiz Capitulino <lcapitulino at redhat.com>
    Reviewed-by: Eric Blake <eblake at redhat.com>

diff --git a/docs/xbzrle.txt b/docs/xbzrle.txt
new file mode 100644
index 0000000..cc3a26a
--- /dev/null
+++ b/docs/xbzrle.txt
@@ -0,0 +1,128 @@
+XBZRLE (Xor Based Zero Run Length Encoding)
+===========================================
+
+Using XBZRLE (Xor Based Zero Run Length Encoding) allows for the reduction
+of VM downtime and the total live-migration time of Virtual machines.
+It is particularly useful for virtual machines running memory write intensive
+workloads that are typical of large enterprise applications such as SAP ERP
+Systems, and generally speaking for any application that uses a sparse memory
+update pattern.
+
+Instead of sending the changed guest memory page this solution will send a
+compressed version of the updates, thus reducing the amount of data sent during
+live migration.
+In order to be able to calculate the update, the previous memory pages need to
+be stored on the source. Those pages are stored in a dedicated cache
+(hash table) and are accessed by their address.
+The larger the cache size the better the chances are that the page has already
+been stored in the cache.
+A small cache size will result in high cache miss rate.
+Cache size can be changed before and during migration.
+
+Format
+=======
+
+The compression format performs a XOR between the previous and current content
+of the page, where zero represents an unchanged value.
+The page data delta is represented by zero and non zero runs.
+A zero run is represented by its length (in bytes).
+A non zero run is represented by its length (in bytes) and the new data.
+The run length is encoded using ULEB128 (http://en.wikipedia.org/wiki/LEB128)
+
+There can be more than one valid encoding, the sender may send a longer encoding
+for the benefit of reducing computation cost.
+
+page = zrun nzrun
+       | zrun nzrun page
+
+zrun = length
+
+nzrun = length byte...
+
+length = uleb128 encoded integer
+
+On the sender side XBZRLE is used as a compact delta encoding of page updates,
+retrieving the old page content from the cache (default size of 512 MB). The
+receiving side uses the existing page's content and XBZRLE to decode the new
+page's content.
+
+This work was originally based on research results published
+VEE 2011: Evaluation of Delta Compression Techniques for Efficient Live
+Migration of Large Virtual Machines by Benoit, Svard, Tordsson and Elmroth.
+Additionally the delta encoder XBRLE was improved further using the XBZRLE
+instead.
+
+XBZRLE has a sustained bandwidth of 2-2.5 GB/s for typical workloads making it
+ideal for in-line, real-time encoding such as is needed for live-migration.
+
+Example
+old buffer:
+1001 zeros
+05 06 07 08 09 0a 0b 0c 0d 0e 0f 10 11 12 13 68 00 00 6b 00 6d
+3074 zeros
+
+new buffer:
+1001 zeros
+01 02 03 04 05 06 07 08 09 0a 0b 0c 0d 0e 0f 68 00 00 67 00 69
+3074 zeros
+
+encoded buffer:
+
+encoded length 24
+e9 07 0f 01 02 03 04 05 06 07 08 09 0a 0b 0c 0d 0e 0f 03 01 67 01 01 69
+
+Usage
+======================
+1. Verify the destination QEMU version is able to decode the new format.
+    {qemu} info migrate_capabilities
+    {qemu} xbzrle: off , ...
+
+2. Activate xbzrle on both source and destination:
+   {qemu} migrate_set_capability xbzrle on
+
+3. Set the XBZRLE cache size - the cache size is in MBytes and should be a
+power of 2. The cache default value is 64MBytes. (on source only)
+    {qemu} migrate_set_cache_size 256m
+
+4. Start outgoing migration
+    {qemu} migrate -d tcp:destination.host:4444
+    {qemu} info migrate
+    capabilities: xbzrle: on
+    Migration status: active
+    transferred ram: A kbytes
+    remaining ram: B kbytes
+    total ram: C kbytes
+    total time: D milliseconds
+    duplicate: E pages
+    normal: F pages
+    normal bytes: G kbytes
+    cache size: H bytes
+    xbzrle transferred: I kbytes
+    xbzrle pages: J pages
+    xbzrle cache miss: K
+    xbzrle overflow : L
+
+xbzrle cache-miss: the number of cache misses to date - high cache-miss rate
+indicates that the cache size is set too low.
+xbzrle overflow: the number of overflows in the decoding which where the delta
+could not be compressed. This can happen if the changes in the pages are too
+large or there are many short changes; for example, changing every second byte
+(half a page).
+
+Testing: Testing indicated that live migration with XBZRLE was completed in 110
+seconds, whereas without it would not be able to complete.
+
+A simple synthetic memory r/w load generator:
+..    include <stdlib.h>
+..    include <stdio.h>
+..    int main()
+..    {
+..        char *buf = (char *) calloc(4096, 4096);
+..        while (1) {
+..            int i;
+..            for (i = 0; i < 4096 * 4; i++) {
+..                buf[i * 4096 / 4]++;
+..            }
+..            printf(".");
+..        }
+..    }
commit 00458433242dbfb6348d8e0bb6d356603d3e0067
Author: Orit Wasserman <owasserm at redhat.com>
Date:   Mon Aug 6 21:42:48 2012 +0300

    Add migrate-set-capabilities
    
    The management can enable/disable a capability for the next migration by using
    migrate-set-capabilities QMP command.
    The user can use migrate_set_capability HMP command.
    
    Signed-off-by: Orit Wasserman <owasserm at redhat.com>
    Signed-off-by: Juan Quintela <quintela at redhat.com>
    
    Reviewed-by: Luiz Capitulino <lcapitulino at redhat.com>
    Reviewed-by: Eric Blake <eblake at redhat.com>

diff --git a/hmp-commands.hx b/hmp-commands.hx
index 8b94802..476b3cd 100644
--- a/hmp-commands.hx
+++ b/hmp-commands.hx
@@ -861,6 +861,20 @@ Set maximum tolerated downtime (in seconds) for migration.
 ETEXI
 
     {
+        .name       = "migrate_set_capability",
+        .args_type  = "capability:s,state:b",
+        .params     = "capability state",
+        .help       = "Enable/Disable the usage of a capability for migration",
+        .mhandler.cmd = hmp_migrate_set_capability,
+    },
+
+STEXI
+ at item migrate_set_capability @var{capability} @var{state}
+ at findex migrate_set_capability
+Enable/Disable the usage of a capability @var{capability} for migration.
+ETEXI
+
+    {
         .name       = "client_migrate_info",
         .args_type  = "protocol:s,hostname:s,port:i?,tls-port:i?,cert-subject:s?",
         .params     = "protocol hostname port tls-port cert-subject",
diff --git a/hmp.c b/hmp.c
index a17f13b..2a03b44 100644
--- a/hmp.c
+++ b/hmp.c
@@ -770,6 +770,38 @@ void hmp_migrate_set_speed(Monitor *mon, const QDict *qdict)
     qmp_migrate_set_speed(value, NULL);
 }
 
+void hmp_migrate_set_capability(Monitor *mon, const QDict *qdict)
+{
+    const char *cap = qdict_get_str(qdict, "capability");
+    bool state = qdict_get_bool(qdict, "state");
+    Error *err = NULL;
+    MigrationCapabilityStatusList *caps = g_malloc0(sizeof(*caps));
+    int i;
+
+    for (i = 0; i < MIGRATION_CAPABILITY_MAX; i++) {
+        if (strcmp(cap, MigrationCapability_lookup[i]) == 0) {
+            caps->value = g_malloc0(sizeof(*caps->value));
+            caps->value->capability = i;
+            caps->value->state = state;
+            caps->next = NULL;
+            qmp_migrate_set_capabilities(caps, &err);
+            break;
+        }
+    }
+
+    if (i == MIGRATION_CAPABILITY_MAX) {
+        error_set(&err, QERR_INVALID_PARAMETER, cap);
+    }
+
+    qapi_free_MigrationCapabilityStatusList(caps);
+
+    if (err) {
+        monitor_printf(mon, "migrate_set_parameter: %s\n",
+                       error_get_pretty(err));
+        error_free(err);
+    }
+}
+
 void hmp_set_password(Monitor *mon, const QDict *qdict)
 {
     const char *protocol  = qdict_get_str(qdict, "protocol");
diff --git a/hmp.h b/hmp.h
index d111351..3390a92 100644
--- a/hmp.h
+++ b/hmp.h
@@ -52,6 +52,7 @@ void hmp_snapshot_blkdev(Monitor *mon, const QDict *qdict);
 void hmp_migrate_cancel(Monitor *mon, const QDict *qdict);
 void hmp_migrate_set_downtime(Monitor *mon, const QDict *qdict);
 void hmp_migrate_set_speed(Monitor *mon, const QDict *qdict);
+void hmp_migrate_set_capability(Monitor *mon, const QDict *qdict);
 void hmp_set_password(Monitor *mon, const QDict *qdict);
 void hmp_expire_password(Monitor *mon, const QDict *qdict);
 void hmp_eject(Monitor *mon, const QDict *qdict);
diff --git a/migration.c b/migration.c
index fb620ac..ba81df7 100644
--- a/migration.c
+++ b/migration.c
@@ -190,6 +190,22 @@ MigrationInfo *qmp_query_migrate(Error **errp)
     return info;
 }
 
+void qmp_migrate_set_capabilities(MigrationCapabilityStatusList *params,
+                                  Error **errp)
+{
+    MigrationState *s = migrate_get_current();
+    MigrationCapabilityStatusList *cap;
+
+    if (s->state == MIG_STATE_ACTIVE) {
+        error_set(errp, QERR_MIGRATION_ACTIVE);
+        return;
+    }
+
+    for (cap = params; cap; cap = cap->next) {
+        s->enabled_capabilities[cap->value->capability] = cap->value->state;
+    }
+}
+
 /* shared migration helpers */
 
 static int migrate_fd_cleanup(MigrationState *s)
diff --git a/qapi-schema.json b/qapi-schema.json
index f0d4510..e3847c8 100644
--- a/qapi-schema.json
+++ b/qapi-schema.json
@@ -334,6 +334,18 @@
   'data': { 'capability' : 'MigrationCapability', 'state' : 'bool' } }
 
 ##
+# @migrate-set-capabilities
+#
+# Enable/Disable the following migration capabilities (like xbzrle)
+#
+# @capabilities: json array of capability modifications to make
+#
+# Since: 1.2
+##
+{ 'command': 'migrate-set-capabilities',
+  'data': { 'capabilities': ['MigrationCapabilityStatus'] } }
+
+##
 # @query-migrate-capabilities
 #
 # Returns information about the current migration capabilities status
diff --git a/qmp-commands.hx b/qmp-commands.hx
index cb81766..a14db90 100644
--- a/qmp-commands.hx
+++ b/qmp-commands.hx
@@ -2143,6 +2143,29 @@ EQMP
     },
 
 SQMP
+migrate-set-capabilities
+-------
+
+Enable/Disable migration capabilities
+
+- "xbzrle": xbzrle support
+
+Arguments:
+
+Example:
+
+-> { "execute": "migrate-set-capabilities" , "arguments":
+     { "capabilities": [ { "capability": "xbzrle", "state": true } ] } }
+
+EQMP
+
+    {
+        .name       = "migrate-set-capabilities",
+        .args_type  = "capabilities:O",
+        .params     = "capability:s,state:b",
+	.mhandler.cmd_new = qmp_marshal_input_migrate_set_capabilities,
+    },
+SQMP
 query-migrate-capabilities
 -------
 
commit bbf6da32b5bd32018069e4eaeda59a02855903f2
Author: Orit Wasserman <owasserm at redhat.com>
Date:   Mon Aug 6 21:42:47 2012 +0300

    Add migration capabilities
    
    The management can query the current migration capabilities using
    query-migrate-capabilities QMP command.
    The user can use 'info migrate_capabilities' HMP command.
    Currently only XBZRLE capability is available.
    
    Signed-off-by: Orit Wasserman <owasserm at redhat.com>
    Signed-off-by: Juan Quintela <quintela at redhat.com>
    
    Reviewed-by: Luiz Capitulino <lcapitulino at redhat.com>
    Reviewed-by: Eric Blake <eblake at redhat.com>

diff --git a/hmp-commands.hx b/hmp-commands.hx
index 9bbc7f7..8b94802 100644
--- a/hmp-commands.hx
+++ b/hmp-commands.hx
@@ -1417,6 +1417,8 @@ show CPU statistics
 show user network stack connection states
 @item info migrate
 show migration status
+ at item info migrate_capabilities
+show current migration capabilities
 @item info balloon
 show balloon information
 @item info qtree
diff --git a/hmp.c b/hmp.c
index 25688ab..a17f13b 100644
--- a/hmp.c
+++ b/hmp.c
@@ -131,8 +131,21 @@ void hmp_info_mice(Monitor *mon)
 void hmp_info_migrate(Monitor *mon)
 {
     MigrationInfo *info;
+    MigrationCapabilityStatusList *caps, *cap;
 
     info = qmp_query_migrate(NULL);
+    caps = qmp_query_migrate_capabilities(NULL);
+
+    /* do not display parameters during setup */
+    if (info->has_status && caps) {
+        monitor_printf(mon, "capabilities: ");
+        for (cap = caps; cap; cap = cap->next) {
+            monitor_printf(mon, "%s: %s ",
+                           MigrationCapability_lookup[cap->value->capability],
+                           cap->value->state ? "on" : "off");
+        }
+        monitor_printf(mon, "\n");
+    }
 
     if (info->has_status) {
         monitor_printf(mon, "Migration status: %s\n", info->status);
@@ -159,6 +172,26 @@ void hmp_info_migrate(Monitor *mon)
     }
 
     qapi_free_MigrationInfo(info);
+    qapi_free_MigrationCapabilityStatusList(caps);
+}
+
+void hmp_info_migrate_capabilities(Monitor *mon)
+{
+    MigrationCapabilityStatusList *caps, *cap;
+
+    caps = qmp_query_migrate_capabilities(NULL);
+
+    if (caps) {
+        monitor_printf(mon, "capabilities: ");
+        for (cap = caps; cap; cap = cap->next) {
+            monitor_printf(mon, "%s: %s ",
+                           MigrationCapability_lookup[cap->value->capability],
+                           cap->value->state ? "on" : "off");
+        }
+        monitor_printf(mon, "\n");
+    }
+
+    qapi_free_MigrationCapabilityStatusList(caps);
 }
 
 void hmp_info_cpus(Monitor *mon)
diff --git a/hmp.h b/hmp.h
index 8d2b0d7..d111351 100644
--- a/hmp.h
+++ b/hmp.h
@@ -25,6 +25,7 @@ void hmp_info_uuid(Monitor *mon);
 void hmp_info_chardev(Monitor *mon);
 void hmp_info_mice(Monitor *mon);
 void hmp_info_migrate(Monitor *mon);
+void hmp_info_migrate_capabilities(Monitor *mon);
 void hmp_info_cpus(Monitor *mon);
 void hmp_info_block(Monitor *mon);
 void hmp_info_blockstats(Monitor *mon);
diff --git a/migration.c b/migration.c
index 8db1b43..fb620ac 100644
--- a/migration.c
+++ b/migration.c
@@ -113,6 +113,30 @@ uint64_t migrate_max_downtime(void)
     return max_downtime;
 }
 
+MigrationCapabilityStatusList *qmp_query_migrate_capabilities(Error **errp)
+{
+    MigrationCapabilityStatusList *head = NULL;
+    MigrationCapabilityStatusList *caps;
+    MigrationState *s = migrate_get_current();
+    int i;
+
+    for (i = 0; i < MIGRATION_CAPABILITY_MAX; i++) {
+        if (head == NULL) {
+            head = g_malloc0(sizeof(*caps));
+            caps = head;
+        } else {
+            caps->next = g_malloc0(sizeof(*caps));
+            caps = caps->next;
+        }
+        caps->value =
+            g_malloc(sizeof(*caps->value));
+        caps->value->capability = i;
+        caps->value->state = s->enabled_capabilities[i];
+    }
+
+    return head;
+}
+
 MigrationInfo *qmp_query_migrate(Error **errp)
 {
     MigrationInfo *info = g_malloc0(sizeof(*info));
@@ -375,10 +399,16 @@ static MigrationState *migrate_init(const MigrationParams *params)
 {
     MigrationState *s = migrate_get_current();
     int64_t bandwidth_limit = s->bandwidth_limit;
+    bool enabled_capabilities[MIGRATION_CAPABILITY_MAX];
+
+    memcpy(enabled_capabilities, s->enabled_capabilities,
+           sizeof(enabled_capabilities));
 
     memset(s, 0, sizeof(*s));
     s->bandwidth_limit = bandwidth_limit;
     s->params = *params;
+    memcpy(s->enabled_capabilities, enabled_capabilities,
+           sizeof(enabled_capabilities));
 
     s->bandwidth_limit = bandwidth_limit;
     s->state = MIG_STATE_SETUP;
diff --git a/migration.h b/migration.h
index 57572a6..713aae0 100644
--- a/migration.h
+++ b/migration.h
@@ -19,6 +19,7 @@
 #include "notify.h"
 #include "error.h"
 #include "vmstate.h"
+#include "qapi-types.h"
 
 struct MigrationParams {
     bool blk;
@@ -39,6 +40,7 @@ struct MigrationState
     void *opaque;
     MigrationParams params;
     int64_t total_time;
+    bool enabled_capabilities[MIGRATION_CAPABILITY_MAX];
 };
 
 void process_incoming_migration(QEMUFile *f);
diff --git a/monitor.c b/monitor.c
index 49dccfe..13b681a 100644
--- a/monitor.c
+++ b/monitor.c
@@ -2655,6 +2655,13 @@ static mon_cmd_t info_cmds[] = {
         .mhandler.info = hmp_info_migrate,
     },
     {
+        .name       = "migrate_capabilities",
+        .args_type  = "",
+        .params     = "",
+        .help       = "show current migration capabilities",
+        .mhandler.info = hmp_info_migrate_capabilities,
+    },
+    {
         .name       = "balloon",
         .args_type  = "",
         .params     = "",
diff --git a/qapi-schema.json b/qapi-schema.json
index bd9c450..f0d4510 100644
--- a/qapi-schema.json
+++ b/qapi-schema.json
@@ -306,6 +306,45 @@
 { 'command': 'query-migrate', 'returns': 'MigrationInfo' }
 
 ##
+# @MigrationCapability
+#
+# Migration capabilities enumeration
+#
+# @xbzrle: Migration supports xbzrle (Xor Based Zero Run Length Encoding).
+#          This feature allows us to minimize migration traffic for certain work
+#          loads, by sending compressed difference of the pages
+#
+# Since: 1.2
+##
+{ 'enum': 'MigrationCapability',
+  'data': ['xbzrle'] }
+
+##
+# @MigrationCapabilityStatus
+#
+# Migration capability information
+#
+# @capability: capability enum
+#
+# @state: capability state bool
+#
+# Since: 1.2
+##
+{ 'type': 'MigrationCapabilityStatus',
+  'data': { 'capability' : 'MigrationCapability', 'state' : 'bool' } }
+
+##
+# @query-migrate-capabilities
+#
+# Returns information about the current migration capabilities status
+#
+# Returns: @MigrationCapabilitiesStatus
+#
+# Since: 1.2
+##
+{ 'command': 'query-migrate-capabilities', 'returns':   ['MigrationCapabilityStatus']}
+
+##
 # @MouseInfo:
 #
 # Information about a mouse device.
diff --git a/qmp-commands.hx b/qmp-commands.hx
index ac46638..cb81766 100644
--- a/qmp-commands.hx
+++ b/qmp-commands.hx
@@ -2143,6 +2143,32 @@ EQMP
     },
 
 SQMP
+query-migrate-capabilities
+-------
+
+Query current migration capabilities
+
+- "capabilities": migration capabilities state
+         - "xbzrle" : XBZRLE state (json-bool)
+
+Arguments:
+
+Example:
+
+-> { "execute": "query-migrate-capabilities" }
+<- { "return": {
+        "capabilities" :  [ { "capability" : "xbzrle", "state" : false } ]
+     }
+   }
+EQMP
+
+    {
+        .name       = "query-migrate-capabilities",
+        .args_type  = "",
+        .mhandler.cmd_new = qmp_marshal_input_query_migrate_capabilities,
+    },
+
+SQMP
 query-balloon
 -------------
 
commit 01afdadc92e71e29700e64f3a5f42c1c543e3cf9
Author: Gerd Hoffmann <kraxel at redhat.com>
Date:   Tue Aug 7 17:09:37 2012 +0200

    update seabios to latest master
    
    Upstream seabios commit 5a023065388287e261ae9212452ff541f9fa9cd3
    
    Major changes since 1.7.0:
     - Usual share of bugfixes and cleanups ;)
     - Support for 64bit PCI bars and mapping those above 4G.
     - Stack switching for real mode irq handlers to reduce
       seabios stack footprint.
     - Support for booting from lsi scsi hba.
     - Support for booting from usb attached scsi.
     - Support for non-linear apic ids.
    
    Signed-off-by: Gerd Hoffmann <kraxel at redhat.com>

diff --git a/pc-bios/bios.bin b/pc-bios/bios.bin
index 5734ae5..eac67cb 100644
Binary files a/pc-bios/bios.bin and b/pc-bios/bios.bin differ
diff --git a/roms/seabios b/roms/seabios
index a026308..5a02306 160000
--- a/roms/seabios
+++ b/roms/seabios
@@ -1 +1 @@
-Subproject commit a0263083cb4cda172832fbc916dc1417ee930574
+Subproject commit 5a023065388287e261ae9212452ff541f9fa9cd3
commit c03b0aa0ca93480e92dc356e58538df0835fe621
Merge: b262fce... 5441421...
Author: Anthony Liguori <aliguori at us.ibm.com>
Date:   Tue Aug 7 09:46:40 2012 -0500

    Merge remote-tracking branch 'kraxel/usb.58' into staging
    
    * kraxel/usb.58:
      usb-storage: fix SYNCHRONIZE_CACHE
      usb-storage: improve debug logging

commit b262fce11a7409d71be84f68637cf4005e995822
Merge: 0b8db8f... 20caf0f...
Author: Anthony Liguori <aliguori at us.ibm.com>
Date:   Tue Aug 7 09:46:24 2012 -0500

    Merge remote-tracking branch 'kwolf/for-anthony' into staging
    
    * kwolf/for-anthony:
      qemu-img: use QemuOpts instead of QEMUOptionParameter in resize function
      qemu-iotests: Be more flexible with image creation options
      qemu-iotests: add 039 qcow2 lazy refcounts test
      qemu-io: add "abort" command to simulate program crash
      qcow2: implement lazy refcounts
      qemu-iotests: ignore qemu-img create lazy_refcounts output
      docs: add lazy refcounts bit to qcow2 specification
      qcow2: introduce dirty bit
      docs: add dirty bit to qcow2 specification
      qemu-iotests: add qed.py image manipulation utility
      qapi: generalize documentation of streaming commands
      ide scsi: Mess with geometry only for hard disk devices

commit 54414218d78c9d043417b27bb29bd0334b4e3cb5
Author: Gerd Hoffmann <kraxel at redhat.com>
Date:   Fri Jul 13 11:38:13 2012 +0200

    usb-storage: fix SYNCHRONIZE_CACHE
    
    Commit 59310659073d85745854f2f10c4292555c5a1c51 is incomplete,
    we'll arrive in the scsi command complete callback in CSW state
    and must handle that case correctly.
    
    Signed-off-by: Gerd Hoffmann <kraxel at redhat.com>

diff --git a/hw/usb/dev-storage.c b/hw/usb/dev-storage.c
index 976fe1a..ff48d91 100644
--- a/hw/usb/dev-storage.c
+++ b/hw/usb/dev-storage.c
@@ -247,6 +247,9 @@ static void usb_msd_command_complete(SCSIRequest *req, uint32_t status, size_t r
                the status read packet.  */
             usb_msd_send_status(s, p);
             s->mode = USB_MSDM_CBW;
+        } else if (s->mode == USB_MSDM_CSW) {
+            usb_msd_send_status(s, p);
+            s->mode = USB_MSDM_CBW;
         } else {
             if (s->data_len) {
                 int len = (p->iov.size - p->result);
commit 06f9847dc3da670c36629c80ae47fea4bf726268
Author: Gerd Hoffmann <kraxel at redhat.com>
Date:   Fri Jul 13 11:35:51 2012 +0200

    usb-storage: improve debug logging
    
    Signed-off-by: Gerd Hoffmann <kraxel at redhat.com>

diff --git a/hw/usb/dev-storage.c b/hw/usb/dev-storage.c
index 7fa8b83..976fe1a 100644
--- a/hw/usb/dev-storage.c
+++ b/hw/usb/dev-storage.c
@@ -383,6 +383,9 @@ static int usb_msd_handle_data(USBDevice *dev, USBPacket *p)
             assert(le32_to_cpu(s->csw.residue) == 0);
             s->scsi_len = 0;
             s->req = scsi_req_new(s->scsi_dev, tag, 0, cbw.cmd, NULL);
+#ifdef DEBUG_MSD
+            scsi_req_print(s->req);
+#endif
             scsi_req_enqueue(s->req);
             if (s->req && s->req->cmd.xfer != SCSI_XFER_NONE) {
                 scsi_req_continue(s->req);
@@ -410,7 +413,7 @@ static int usb_msd_handle_data(USBDevice *dev, USBPacket *p)
                 }
             }
             if (p->result < p->iov.size) {
-                DPRINTF("Deferring packet %p\n", p);
+                DPRINTF("Deferring packet %p [wait data-out]\n", p);
                 s->packet = p;
                 ret = USB_RET_ASYNC;
             } else {
@@ -445,6 +448,7 @@ static int usb_msd_handle_data(USBDevice *dev, USBPacket *p)
 
             if (s->req) {
                 /* still in flight */
+                DPRINTF("Deferring packet %p [wait status]\n", p);
                 s->packet = p;
                 ret = USB_RET_ASYNC;
             } else {
@@ -471,7 +475,7 @@ static int usb_msd_handle_data(USBDevice *dev, USBPacket *p)
                 }
             }
             if (p->result < p->iov.size) {
-                DPRINTF("Deferring packet %p\n", p);
+                DPRINTF("Deferring packet %p [wait data-in]\n", p);
                 s->packet = p;
                 ret = USB_RET_ASYNC;
             } else {
commit 0b8db8fe15d17a529a5ea90614c11e9f031dfee8
Author: Anthony Liguori <aliguori at us.ibm.com>
Date:   Mon Aug 6 19:31:55 2012 -0500

    slirp: fix build on mingw32
    
    in_addr_t isn't available on mingw32.  Just use an unsigned long instead.  I
    considered typedef'ing in_addr_t on mingw32 but this would potentially be
    brittle if mingw32 did introduce the type.
    
    Cc: Jan Kiszka <jan.kiszka at siemens.com>
    Signed-off-by: Anthony Liguori <aliguori at us.ibm.com>

diff --git a/slirp/main.h b/slirp/main.h
index bf601e2..1f3b84d 100644
--- a/slirp/main.h
+++ b/slirp/main.h
@@ -31,7 +31,7 @@ extern char *exec_shell;
 extern u_int curtime;
 extern fd_set *global_readfds, *global_writefds, *global_xfds;
 extern struct in_addr loopback_addr;
-extern in_addr_t loopback_mask;
+extern unsigned long loopback_mask;
 extern char *username;
 extern char *socket_path;
 extern int towrite_max;
diff --git a/slirp/slirp.c b/slirp/slirp.c
index 9787104..38e0a21 100644
--- a/slirp/slirp.c
+++ b/slirp/slirp.c
@@ -30,7 +30,7 @@
 /* host loopback address */
 struct in_addr loopback_addr;
 /* host loopback network mask */
-in_addr_t loopback_mask;
+unsigned long loopback_mask;
 
 /* emulated hosts use the MAC addr 52:55:IP:IP:IP:IP */
 static const uint8_t special_ethaddr[ETH_ALEN] = {
commit 20caf0f766b48fbbf718eb20aaddb7ffa356a21f
Author: Dong Xu Wang <wdongxu at linux.vnet.ibm.com>
Date:   Mon Aug 6 10:18:42 2012 +0800

    qemu-img: use QemuOpts instead of QEMUOptionParameter in resize function
    
    Signed-off-by: Dong Xu Wang <wdongxu at linux.vnet.ibm.com>
    Reviewed-by: Stefan Hajnoczi <stefanha at linux.vnet.ibm.com>
    Signed-off-by: Kevin Wolf <kwolf at redhat.com>

diff --git a/qemu-img.c b/qemu-img.c
index b866f80..94a31ad 100644
--- a/qemu-img.c
+++ b/qemu-img.c
@@ -1567,14 +1567,19 @@ static int img_resize(int argc, char **argv)
     const char *filename, *fmt, *size;
     int64_t n, total_size;
     BlockDriverState *bs = NULL;
-    QEMUOptionParameter *param;
-    QEMUOptionParameter resize_options[] = {
-        {
-            .name = BLOCK_OPT_SIZE,
-            .type = OPT_SIZE,
-            .help = "Virtual disk size"
+    QemuOpts *param;
+    static QemuOptsList resize_options = {
+        .name = "resize_options",
+        .head = QTAILQ_HEAD_INITIALIZER(resize_options.head),
+        .desc = {
+            {
+                .name = BLOCK_OPT_SIZE,
+                .type = QEMU_OPT_SIZE,
+                .help = "Virtual disk size"
+            }, {
+                /* end of list */
+            }
         },
-        { NULL }
     };
 
     /* Remove size from argv manually so that negative numbers are not treated
@@ -1624,14 +1629,15 @@ static int img_resize(int argc, char **argv)
     }
 
     /* Parse size */
-    param = parse_option_parameters("", resize_options, NULL);
-    if (set_option_parameter(param, BLOCK_OPT_SIZE, size)) {
+    param = qemu_opts_create(&resize_options, NULL, 0, NULL);
+    if (qemu_opt_set(param, BLOCK_OPT_SIZE, size)) {
         /* Error message already printed when size parsing fails */
         ret = -1;
+        qemu_opts_del(param);
         goto out;
     }
-    n = get_option_parameter(param, BLOCK_OPT_SIZE)->value.n;
-    free_option_parameters(param);
+    n = qemu_opt_get_size(param, BLOCK_OPT_SIZE, 0);
+    qemu_opts_del(param);
 
     bs = bdrv_new_open(filename, fmt, BDRV_O_FLAGS | BDRV_O_RDWR);
     if (!bs) {
commit b0869a46b2dc2e6e4d6d6cca8bb5c5bf611f33d0
Author: Kevin Wolf <kwolf at redhat.com>
Date:   Fri Jul 27 15:14:28 2012 +0200

    qemu-iotests: Be more flexible with image creation options
    
    qemu-iotests already filters out image creation options that may be
    present or not in order to get the same output in both cases. However,
    often it only considers the default value of the option. Cover all valid
    values instead so that ./check -o name=value can be used successfull for
    all of them.
    
    Signed-off-by: Kevin Wolf <kwolf at redhat.com>

diff --git a/tests/qemu-iotests/039.out b/tests/qemu-iotests/039.out
index 8ad570d..155a05e 100644
--- a/tests/qemu-iotests/039.out
+++ b/tests/qemu-iotests/039.out
@@ -1,14 +1,14 @@
 QA output created by 039
 
 == Checking that image is clean on shutdown ==
-Formatting 'TEST_DIR/t.IMGFMT', fmt=IMGFMT size=134217728 lazy_refcounts=on 
+Formatting 'TEST_DIR/t.IMGFMT', fmt=IMGFMT size=134217728 
 wrote 512/512 bytes at offset 0
 512 bytes, X ops; XX:XX:XX.X (XXX YYY/sec and XXX ops/sec)
 incompatible_features     0x0
 No errors were found on the image.
 
 == Creating a dirty image file ==
-Formatting 'TEST_DIR/t.IMGFMT', fmt=IMGFMT size=134217728 lazy_refcounts=on 
+Formatting 'TEST_DIR/t.IMGFMT', fmt=IMGFMT size=134217728 
 wrote 512/512 bytes at offset 0
 512 bytes, X ops; XX:XX:XX.X (XXX YYY/sec and XXX ops/sec)
 incompatible_features     0x1
@@ -34,7 +34,7 @@ read 512/512 bytes at offset 0
 512 bytes, X ops; XX:XX:XX.X (XXX YYY/sec and XXX ops/sec)
 
 == Opening a dirty image read/write should repair it ==
-Formatting 'TEST_DIR/t.IMGFMT', fmt=IMGFMT size=134217728 lazy_refcounts=on 
+Formatting 'TEST_DIR/t.IMGFMT', fmt=IMGFMT size=134217728 
 wrote 512/512 bytes at offset 0
 512 bytes, X ops; XX:XX:XX.X (XXX YYY/sec and XXX ops/sec)
 incompatible_features     0x1
diff --git a/tests/qemu-iotests/common.rc b/tests/qemu-iotests/common.rc
index cc4e39b..7782808 100644
--- a/tests/qemu-iotests/common.rc
+++ b/tests/qemu-iotests/common.rc
@@ -110,11 +110,11 @@ _make_test_img()
     	sed -e "s#$IMGFMT#IMGFMT#g" | \
 	sed -e "s# encryption=off##g" | \
 	sed -e "s# cluster_size=[0-9]\\+##g" | \
-	sed -e "s# table_size=0##g" | \
+	sed -e "s# table_size=[0-9]\\+##g" | \
 	sed -e "s# compat='[^']*'##g" | \
-	sed -e "s# compat6=off##g" | \
-	sed -e "s# static=off##g" | \
-	sed -e "s# lazy_refcounts=off##g"
+	sed -e "s# compat6=\\(on\\|off\\)##g" | \
+	sed -e "s# static=\\(on\\|off\\)##g" | \
+	sed -e "s# lazy_refcounts=\\(on\\|off\\)##g"
 }
 
 _cleanup_test_img()
commit dc68afe0f3e8be913a0eb639afc9196e0abab261
Author: Stefan Hajnoczi <stefanha at linux.vnet.ibm.com>
Date:   Fri Jul 27 09:05:24 2012 +0100

    qemu-iotests: add 039 qcow2 lazy refcounts test
    
    This tests establishes the basic post-conditions of the qcow2 lazy
    refcounts features:
    
      1. If the image was closed normally, it is marked clean.
    
      2. If an allocating write was performed and the image was not closed
         normally, then it is marked dirty.
    
         a. Written data can be read back successfully.
         b. The image file can be repaired and will be marked clean again.
         c. The image file is automatically repaired when opened read/write.
    
    Signed-off-by: Stefan Hajnoczi <stefanha at linux.vnet.ibm.com>
    Signed-off-by: Kevin Wolf <kwolf at redhat.com>

diff --git a/tests/qemu-iotests/039 b/tests/qemu-iotests/039
new file mode 100755
index 0000000..a749fcf
--- /dev/null
+++ b/tests/qemu-iotests/039
@@ -0,0 +1,136 @@
+#!/bin/bash
+#
+# Test qcow2 lazy refcounts
+#
+# Copyright (C) 2012 Red Hat, Inc.
+# Copyright IBM, Corp. 2010
+#
+# Based on test 038.
+#
+# This program is free software; you can redistribute it and/or modify
+# it under the terms of the GNU General Public License as published by
+# the Free Software Foundation; either version 2 of the License, or
+# (at your option) any later version.
+#
+# This program is distributed in the hope that it will be useful,
+# but WITHOUT ANY WARRANTY; without even the implied warranty of
+# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+# GNU General Public License for more details.
+#
+# You should have received a copy of the GNU General Public License
+# along with this program.  If not, see <http://www.gnu.org/licenses/>.
+#
+
+# creator
+owner=stefanha at linux.vnet.ibm.com
+
+seq=`basename $0`
+echo "QA output created by $seq"
+
+here=`pwd`
+tmp=/tmp/$$
+status=1	# failure is the default!
+
+_cleanup()
+{
+	_cleanup_test_img
+}
+trap "_cleanup; exit \$status" 0 1 2 3 15
+
+# get standard environment, filters and checks
+. ./common.rc
+. ./common.filter
+
+_supported_fmt qcow2
+_supported_proto generic
+_supported_os Linux
+
+size=128M
+
+echo
+echo "== Checking that image is clean on shutdown =="
+
+IMGOPTS="compat=1.1,lazy_refcounts=on"
+_make_test_img $size
+
+$QEMU_IO -c "write -P 0x5a 0 512" $TEST_IMG | _filter_qemu_io
+
+# The dirty bit must not be set
+./qcow2.py $TEST_IMG dump-header | grep incompatible_features
+_check_test_img
+
+echo
+echo "== Creating a dirty image file =="
+
+IMGOPTS="compat=1.1,lazy_refcounts=on"
+_make_test_img $size
+
+old_ulimit=$(ulimit -c)
+ulimit -c 0 # do not produce a core dump on abort(3)
+$QEMU_IO -c "write -P 0x5a 0 512" -c "abort" $TEST_IMG | _filter_qemu_io
+ulimit -c "$old_ulimit"
+
+# The dirty bit must be set
+./qcow2.py $TEST_IMG dump-header | grep incompatible_features
+_check_test_img
+
+echo
+echo "== Read-only access must still work =="
+
+$QEMU_IO -r -c "read -P 0x5a 0 512" $TEST_IMG | _filter_qemu_io
+
+# The dirty bit must be set
+./qcow2.py $TEST_IMG dump-header | grep incompatible_features
+
+echo
+echo "== Repairing the image file must succeed =="
+
+$QEMU_IMG check -r all $TEST_IMG
+
+# The dirty bit must not be set
+./qcow2.py $TEST_IMG dump-header | grep incompatible_features
+
+echo
+echo "== Data should still be accessible after repair =="
+
+$QEMU_IO -c "read -P 0x5a 0 512" $TEST_IMG | _filter_qemu_io
+
+echo
+echo "== Opening a dirty image read/write should repair it =="
+
+IMGOPTS="compat=1.1,lazy_refcounts=on"
+_make_test_img $size
+
+old_ulimit=$(ulimit -c)
+ulimit -c 0 # do not produce a core dump on abort(3)
+$QEMU_IO -c "write -P 0x5a 0 512" -c "abort" $TEST_IMG | _filter_qemu_io
+ulimit -c "$old_ulimit"
+
+# The dirty bit must be set
+./qcow2.py $TEST_IMG dump-header | grep incompatible_features
+
+$QEMU_IO -c "write 0 512" $TEST_IMG | _filter_qemu_io
+
+# The dirty bit must not be set
+./qcow2.py $TEST_IMG dump-header | grep incompatible_features
+
+echo
+echo "== Creating an image file with lazy_refcounts=off =="
+
+IMGOPTS="compat=1.1,lazy_refcounts=off"
+_make_test_img $size
+
+old_ulimit=$(ulimit -c)
+ulimit -c 0 # do not produce a core dump on abort(3)
+$QEMU_IO -c "write -P 0x5a 0 512" -c "abort" $TEST_IMG | _filter_qemu_io
+ulimit -c "$old_ulimit"
+
+# The dirty bit must not be set since lazy_refcounts=off
+./qcow2.py $TEST_IMG dump-header | grep incompatible_features
+_check_test_img
+
+# success, all done
+echo "*** done"
+rm -f $seq.full
+status=0
+
diff --git a/tests/qemu-iotests/039.out b/tests/qemu-iotests/039.out
new file mode 100644
index 0000000..8ad570d
--- /dev/null
+++ b/tests/qemu-iotests/039.out
@@ -0,0 +1,53 @@
+QA output created by 039
+
+== Checking that image is clean on shutdown ==
+Formatting 'TEST_DIR/t.IMGFMT', fmt=IMGFMT size=134217728 lazy_refcounts=on 
+wrote 512/512 bytes at offset 0
+512 bytes, X ops; XX:XX:XX.X (XXX YYY/sec and XXX ops/sec)
+incompatible_features     0x0
+No errors were found on the image.
+
+== Creating a dirty image file ==
+Formatting 'TEST_DIR/t.IMGFMT', fmt=IMGFMT size=134217728 lazy_refcounts=on 
+wrote 512/512 bytes at offset 0
+512 bytes, X ops; XX:XX:XX.X (XXX YYY/sec and XXX ops/sec)
+incompatible_features     0x1
+ERROR OFLAG_COPIED: offset=8000000000050000 refcount=0
+ERROR cluster 5 refcount=0 reference=1
+
+2 errors were found on the image.
+Data may be corrupted, or further writes to the image may corrupt it.
+
+== Read-only access must still work ==
+read 512/512 bytes at offset 0
+512 bytes, X ops; XX:XX:XX.X (XXX YYY/sec and XXX ops/sec)
+incompatible_features     0x1
+
+== Repairing the image file must succeed ==
+ERROR OFLAG_COPIED: offset=8000000000050000 refcount=0
+Repairing cluster 5 refcount=0 reference=1
+No errors were found on the image.
+incompatible_features     0x0
+
+== Data should still be accessible after repair ==
+read 512/512 bytes at offset 0
+512 bytes, X ops; XX:XX:XX.X (XXX YYY/sec and XXX ops/sec)
+
+== Opening a dirty image read/write should repair it ==
+Formatting 'TEST_DIR/t.IMGFMT', fmt=IMGFMT size=134217728 lazy_refcounts=on 
+wrote 512/512 bytes at offset 0
+512 bytes, X ops; XX:XX:XX.X (XXX YYY/sec and XXX ops/sec)
+incompatible_features     0x1
+ERROR OFLAG_COPIED: offset=8000000000050000 refcount=0
+Repairing cluster 5 refcount=0 reference=1
+wrote 512/512 bytes at offset 0
+512 bytes, X ops; XX:XX:XX.X (XXX YYY/sec and XXX ops/sec)
+incompatible_features     0x0
+
+== Creating an image file with lazy_refcounts=off ==
+Formatting 'TEST_DIR/t.IMGFMT', fmt=IMGFMT size=134217728 
+wrote 512/512 bytes at offset 0
+512 bytes, X ops; XX:XX:XX.X (XXX YYY/sec and XXX ops/sec)
+incompatible_features     0x0
+No errors were found on the image.
+*** done
diff --git a/tests/qemu-iotests/group b/tests/qemu-iotests/group
index 7a2c92b..ebb5ca4 100644
--- a/tests/qemu-iotests/group
+++ b/tests/qemu-iotests/group
@@ -45,3 +45,4 @@
 036 rw auto quick
 037 rw auto backing
 038 rw auto backing
+039 rw auto
commit e01c30d3e20eb8cf068b08af46c532f99975527a
Author: Stefan Hajnoczi <stefanha at linux.vnet.ibm.com>
Date:   Fri Jul 27 09:05:23 2012 +0100

    qemu-io: add "abort" command to simulate program crash
    
    Avoiding data loss and corruption is the top requirement for image file
    formats.  The qemu-io "abort" command makes it possible to simulate
    program crashes and does not give the image format a chance to cleanly
    shut down.  This command is useful for data integrity test cases.
    
    Signed-off-by: Stefan Hajnoczi <stefanha at linux.vnet.ibm.com>
    Signed-off-by: Kevin Wolf <kwolf at redhat.com>

diff --git a/qemu-io.c b/qemu-io.c
index 8f3b94b..d0f4fb7 100644
--- a/qemu-io.c
+++ b/qemu-io.c
@@ -1652,6 +1652,17 @@ static const cmdinfo_t map_cmd = {
        .oneline        = "prints the allocated areas of a file",
 };
 
+static int abort_f(int argc, char **argv)
+{
+    abort();
+}
+
+static const cmdinfo_t abort_cmd = {
+       .name           = "abort",
+       .cfunc          = abort_f,
+       .flags          = CMD_NOFILE_OK,
+       .oneline        = "simulate a program crash using abort(3)",
+};
 
 static int close_f(int argc, char **argv)
 {
@@ -1905,6 +1916,7 @@ int main(int argc, char **argv)
     add_command(&discard_cmd);
     add_command(&alloc_cmd);
     add_command(&map_cmd);
+    add_command(&abort_cmd);
 
     add_args_command(init_args_command);
     add_check_command(init_check_command);
commit bfe8043e9214d2fc6572cc72b5f2218308747acd
Author: Stefan Hajnoczi <stefanha at linux.vnet.ibm.com>
Date:   Fri Jul 27 09:05:22 2012 +0100

    qcow2: implement lazy refcounts
    
    Lazy refcounts is a performance optimization for qcow2 that postpones
    refcount metadata updates and instead marks the image dirty.  In the
    case of crash or power failure the image will be left in a dirty state
    and repaired next time it is opened.
    
    Reducing metadata I/O is important for cache=writethrough and
    cache=directsync because these modes guarantee that data is on disk
    after each write (hence we cannot take advantage of caching updates in
    RAM).  Refcount metadata is not needed for guest->file block address
    translation and therefore does not need to be on-disk at the time of
    write completion - this is the motivation behind the lazy refcount
    optimization.
    
    The lazy refcount optimization must be enabled at image creation time:
    
      qemu-img create -f qcow2 -o compat=1.1,lazy_refcounts=on a.qcow2 10G
      qemu-system-x86_64 -drive if=virtio,file=a.qcow2,cache=writethrough
    
    Update qemu-iotests 031 and 036 since the extension header size changes
    when we add feature bit table entries.
    
    Signed-off-by: Stefan Hajnoczi <stefanha at linux.vnet.ibm.com>
    Signed-off-by: Kevin Wolf <kwolf at redhat.com>

diff --git a/block/qcow2-cluster.c b/block/qcow2-cluster.c
index d7e0e19..e179211 100644
--- a/block/qcow2-cluster.c
+++ b/block/qcow2-cluster.c
@@ -662,7 +662,10 @@ int qcow2_alloc_cluster_link_l2(BlockDriverState *bs, QCowL2Meta *m)
         qcow2_cache_depends_on_flush(s->l2_table_cache);
     }
 
-    qcow2_cache_set_dependency(bs, s->l2_table_cache, s->refcount_block_cache);
+    if (qcow2_need_accurate_refcounts(s)) {
+        qcow2_cache_set_dependency(bs, s->l2_table_cache,
+                                   s->refcount_block_cache);
+    }
     ret = get_cluster_table(bs, m->offset, &l2_table, &l2_index);
     if (ret < 0) {
         goto err;
diff --git a/block/qcow2.c b/block/qcow2.c
index 7fe1567..fd5e214 100644
--- a/block/qcow2.c
+++ b/block/qcow2.c
@@ -215,6 +215,41 @@ static void report_unsupported_feature(BlockDriverState *bs,
 }
 
 /*
+ * Sets the dirty bit and flushes afterwards if necessary.
+ *
+ * The incompatible_features bit is only set if the image file header was
+ * updated successfully.  Therefore it is not required to check the return
+ * value of this function.
+ */
+static int qcow2_mark_dirty(BlockDriverState *bs)
+{
+    BDRVQcowState *s = bs->opaque;
+    uint64_t val;
+    int ret;
+
+    assert(s->qcow_version >= 3);
+
+    if (s->incompatible_features & QCOW2_INCOMPAT_DIRTY) {
+        return 0; /* already dirty */
+    }
+
+    val = cpu_to_be64(s->incompatible_features | QCOW2_INCOMPAT_DIRTY);
+    ret = bdrv_pwrite(bs->file, offsetof(QCowHeader, incompatible_features),
+                      &val, sizeof(val));
+    if (ret < 0) {
+        return ret;
+    }
+    ret = bdrv_flush(bs->file);
+    if (ret < 0) {
+        return ret;
+    }
+
+    /* Only treat image as dirty if the header was updated successfully */
+    s->incompatible_features |= QCOW2_INCOMPAT_DIRTY;
+    return 0;
+}
+
+/*
  * Clears the dirty bit and flushes before if necessary.  Only call this
  * function when there are no pending requests, it does not guard against
  * concurrent requests dirtying the image.
@@ -752,6 +787,11 @@ static coroutine_fn int qcow2_co_writev(BlockDriverState *bs,
             goto fail;
         }
 
+        if (l2meta.nb_clusters > 0 &&
+            (s->compatible_features & QCOW2_COMPAT_LAZY_REFCOUNTS)) {
+            qcow2_mark_dirty(bs);
+        }
+
         cluster_offset = l2meta.cluster_offset;
         assert((cluster_offset & 511) == 0);
 
@@ -994,6 +1034,11 @@ int qcow2_update_header(BlockDriverState *bs)
             .bit  = QCOW2_INCOMPAT_DIRTY_BITNR,
             .name = "dirty bit",
         },
+        {
+            .type = QCOW2_FEAT_TYPE_COMPATIBLE,
+            .bit  = QCOW2_COMPAT_LAZY_REFCOUNTS_BITNR,
+            .name = "lazy refcounts",
+        },
     };
 
     ret = header_ext_add(buf, QCOW2_EXT_MAGIC_FEATURE_TABLE,
@@ -1176,6 +1221,11 @@ static int qcow2_create2(const char *filename, int64_t total_size,
         header.crypt_method = cpu_to_be32(QCOW_CRYPT_NONE);
     }
 
+    if (flags & BLOCK_FLAG_LAZY_REFCOUNTS) {
+        header.compatible_features |=
+            cpu_to_be64(QCOW2_COMPAT_LAZY_REFCOUNTS);
+    }
+
     ret = bdrv_pwrite(bs, 0, &header, sizeof(header));
     if (ret < 0) {
         goto out;
@@ -1289,6 +1339,8 @@ static int qcow2_create(const char *filename, QEMUOptionParameter *options)
                     options->value.s);
                 return -EINVAL;
             }
+        } else if (!strcmp(options->name, BLOCK_OPT_LAZY_REFCOUNTS)) {
+            flags |= options->value.n ? BLOCK_FLAG_LAZY_REFCOUNTS : 0;
         }
         options++;
     }
@@ -1299,6 +1351,12 @@ static int qcow2_create(const char *filename, QEMUOptionParameter *options)
         return -EINVAL;
     }
 
+    if (version < 3 && (flags & BLOCK_FLAG_LAZY_REFCOUNTS)) {
+        fprintf(stderr, "Lazy refcounts only supported with compatibility "
+                "level 1.1 and above (use compat=1.1 or greater)\n");
+        return -EINVAL;
+    }
+
     return qcow2_create2(filename, sectors, backing_file, backing_fmt, flags,
                          cluster_size, prealloc, options, version);
 }
@@ -1485,10 +1543,12 @@ static coroutine_fn int qcow2_co_flush_to_os(BlockDriverState *bs)
         return ret;
     }
 
-    ret = qcow2_cache_flush(bs, s->refcount_block_cache);
-    if (ret < 0) {
-        qemu_co_mutex_unlock(&s->lock);
-        return ret;
+    if (qcow2_need_accurate_refcounts(s)) {
+        ret = qcow2_cache_flush(bs, s->refcount_block_cache);
+        if (ret < 0) {
+            qemu_co_mutex_unlock(&s->lock);
+            return ret;
+        }
     }
     qemu_co_mutex_unlock(&s->lock);
 
@@ -1603,6 +1663,11 @@ static QEMUOptionParameter qcow2_create_options[] = {
         .type = OPT_STRING,
         .help = "Preallocation mode (allowed values: off, metadata)"
     },
+    {
+        .name = BLOCK_OPT_LAZY_REFCOUNTS,
+        .type = OPT_FLAG,
+        .help = "Postpone refcount updates",
+    },
     { NULL }
 };
 
diff --git a/block/qcow2.h b/block/qcow2.h
index b5fefc0..b4eb654 100644
--- a/block/qcow2.h
+++ b/block/qcow2.h
@@ -118,6 +118,14 @@ enum {
     QCOW2_INCOMPAT_MASK          = QCOW2_INCOMPAT_DIRTY,
 };
 
+/* Compatible feature bits */
+enum {
+    QCOW2_COMPAT_LAZY_REFCOUNTS_BITNR = 0,
+    QCOW2_COMPAT_LAZY_REFCOUNTS       = 1 << QCOW2_COMPAT_LAZY_REFCOUNTS_BITNR,
+
+    QCOW2_COMPAT_FEAT_MASK            = QCOW2_COMPAT_LAZY_REFCOUNTS,
+};
+
 typedef struct Qcow2Feature {
     uint8_t type;
     uint8_t bit;
@@ -245,6 +253,11 @@ static inline int qcow2_get_cluster_type(uint64_t l2_entry)
     }
 }
 
+/* Check whether refcounts are eager or lazy */
+static inline bool qcow2_need_accurate_refcounts(BDRVQcowState *s)
+{
+    return !(s->incompatible_features & QCOW2_INCOMPAT_DIRTY);
+}
 
 // FIXME Need qcow2_ prefix to global functions
 
diff --git a/block_int.h b/block_int.h
index d72317f..6c1d9ca 100644
--- a/block_int.h
+++ b/block_int.h
@@ -31,8 +31,9 @@
 #include "qemu-timer.h"
 #include "qapi-types.h"
 
-#define BLOCK_FLAG_ENCRYPT	1
-#define BLOCK_FLAG_COMPAT6	4
+#define BLOCK_FLAG_ENCRYPT          1
+#define BLOCK_FLAG_COMPAT6          4
+#define BLOCK_FLAG_LAZY_REFCOUNTS   8
 
 #define BLOCK_IO_LIMIT_READ     0
 #define BLOCK_IO_LIMIT_WRITE    1
@@ -41,16 +42,17 @@
 #define BLOCK_IO_SLICE_TIME     100000000
 #define NANOSECONDS_PER_SECOND  1000000000.0
 
-#define BLOCK_OPT_SIZE          "size"
-#define BLOCK_OPT_ENCRYPT       "encryption"
-#define BLOCK_OPT_COMPAT6       "compat6"
-#define BLOCK_OPT_BACKING_FILE  "backing_file"
-#define BLOCK_OPT_BACKING_FMT   "backing_fmt"
-#define BLOCK_OPT_CLUSTER_SIZE  "cluster_size"
-#define BLOCK_OPT_TABLE_SIZE    "table_size"
-#define BLOCK_OPT_PREALLOC      "preallocation"
-#define BLOCK_OPT_SUBFMT        "subformat"
-#define BLOCK_OPT_COMPAT_LEVEL  "compat"
+#define BLOCK_OPT_SIZE              "size"
+#define BLOCK_OPT_ENCRYPT           "encryption"
+#define BLOCK_OPT_COMPAT6           "compat6"
+#define BLOCK_OPT_BACKING_FILE      "backing_file"
+#define BLOCK_OPT_BACKING_FMT       "backing_fmt"
+#define BLOCK_OPT_CLUSTER_SIZE      "cluster_size"
+#define BLOCK_OPT_TABLE_SIZE        "table_size"
+#define BLOCK_OPT_PREALLOC          "preallocation"
+#define BLOCK_OPT_SUBFMT            "subformat"
+#define BLOCK_OPT_COMPAT_LEVEL      "compat"
+#define BLOCK_OPT_LAZY_REFCOUNTS    "lazy_refcounts"
 
 typedef struct BdrvTrackedRequest BdrvTrackedRequest;
 
diff --git a/tests/qemu-iotests/031.out b/tests/qemu-iotests/031.out
index 297b458..796c993 100644
--- a/tests/qemu-iotests/031.out
+++ b/tests/qemu-iotests/031.out
@@ -54,7 +54,7 @@ header_length             72
 
 Header extension:
 magic                     0x6803f857
-length                    48
+length                    96
 data                      <binary>
 
 Header extension:
@@ -68,7 +68,7 @@ No errors were found on the image.
 
 magic                     0x514649fb
 version                   2
-backing_file_offset       0xc8
+backing_file_offset       0xf8
 backing_file_size         0x17
 cluster_bits              16
 size                      67108864
@@ -92,7 +92,7 @@ data                      'host_device'
 
 Header extension:
 magic                     0x6803f857
-length                    48
+length                    96
 data                      <binary>
 
 Header extension:
@@ -155,7 +155,7 @@ header_length             104
 
 Header extension:
 magic                     0x6803f857
-length                    48
+length                    96
 data                      <binary>
 
 Header extension:
@@ -169,7 +169,7 @@ No errors were found on the image.
 
 magic                     0x514649fb
 version                   3
-backing_file_offset       0xe8
+backing_file_offset       0x118
 backing_file_size         0x17
 cluster_bits              16
 size                      67108864
@@ -193,7 +193,7 @@ data                      'host_device'
 
 Header extension:
 magic                     0x6803f857
-length                    48
+length                    96
 data                      <binary>
 
 Header extension:
diff --git a/tests/qemu-iotests/036.out b/tests/qemu-iotests/036.out
index ca0fda1..063ca22 100644
--- a/tests/qemu-iotests/036.out
+++ b/tests/qemu-iotests/036.out
@@ -46,7 +46,7 @@ header_length             104
 
 Header extension:
 magic                     0x6803f857
-length                    48
+length                    96
 data                      <binary>
 
 *** done
commit 91cf8a35e777cdbdc3bf0d39c319ac9f76b7a296
Author: Stefan Hajnoczi <stefanha at linux.vnet.ibm.com>
Date:   Fri Jul 27 09:05:21 2012 +0100

    qemu-iotests: ignore qemu-img create lazy_refcounts output
    
    Hide the default lazy_refcounts=off output from qemu-img like we do with
    other image creation options.  This ensures that existing golden outputs
    continue to pass despite the new option that has been added.
    
    Note that this patch applies before the one that actually introduces the
    lazy_refcounts=on|off option.  This ensures git-bisect(1) continues to
    work.
    
    Signed-off-by: Stefan Hajnoczi <stefanha at linux.vnet.ibm.com>
    Signed-off-by: Kevin Wolf <kwolf at redhat.com>

diff --git a/tests/qemu-iotests/common.rc b/tests/qemu-iotests/common.rc
index 5e3a524..cc4e39b 100644
--- a/tests/qemu-iotests/common.rc
+++ b/tests/qemu-iotests/common.rc
@@ -113,7 +113,8 @@ _make_test_img()
 	sed -e "s# table_size=0##g" | \
 	sed -e "s# compat='[^']*'##g" | \
 	sed -e "s# compat6=off##g" | \
-	sed -e "s# static=off##g"
+	sed -e "s# static=off##g" | \
+	sed -e "s# lazy_refcounts=off##g"
 }
 
 _cleanup_test_img()
commit dae8796d009ffc4d980db1f87f26eed0074be4ef
Author: Stefan Hajnoczi <stefanha at linux.vnet.ibm.com>
Date:   Fri Jul 27 09:05:20 2012 +0100

    docs: add lazy refcounts bit to qcow2 specification
    
    The lazy refcounts bit indicates that this image can take advantage of
    the dirty bit and that refcount updates can be postponed.
    
    Signed-off-by: Stefan Hajnoczi <stefanha at linux.vnet.ibm.com>
    Signed-off-by: Kevin Wolf <kwolf at redhat.com>

diff --git a/docs/specs/qcow2.txt b/docs/specs/qcow2.txt
index 339cdc1..36a559d 100644
--- a/docs/specs/qcow2.txt
+++ b/docs/specs/qcow2.txt
@@ -86,7 +86,12 @@ in the description of a field.
                     Bitmask of compatible features. An implementation can
                     safely ignore any unknown bits that are set.
 
-                    Bits 0-63:  Reserved (set to 0)
+                    Bit 0:      Lazy refcounts bit.  If this bit is set then
+                                lazy refcount updates can be used.  This means
+                                marking the image file dirty and postponing
+                                refcount metadata updates.
+
+                    Bits 1-63:  Reserved (set to 0)
 
          88 -  95:  autoclear_features
                     Bitmask of auto-clear features. An implementation may only
commit c61d0004bc37182cae0f92a865ad2f0625762610
Author: Stefan Hajnoczi <stefanha at linux.vnet.ibm.com>
Date:   Fri Jul 27 09:05:19 2012 +0100

    qcow2: introduce dirty bit
    
    This patch adds an incompatible feature bit to mark images that have not
    been closed cleanly.  When a dirty image file is opened a consistency
    check and repair is performed.
    
    Update qemu-iotests 031 and 036 since the extension header size changes
    when we add feature bit table entries.
    
    Signed-off-by: Stefan Hajnoczi <stefanha at linux.vnet.ibm.com>
    Signed-off-by: Kevin Wolf <kwolf at redhat.com>

diff --git a/block/qcow2.c b/block/qcow2.c
index 870148d..7fe1567 100644
--- a/block/qcow2.c
+++ b/block/qcow2.c
@@ -214,6 +214,27 @@ static void report_unsupported_feature(BlockDriverState *bs,
     }
 }
 
+/*
+ * Clears the dirty bit and flushes before if necessary.  Only call this
+ * function when there are no pending requests, it does not guard against
+ * concurrent requests dirtying the image.
+ */
+static int qcow2_mark_clean(BlockDriverState *bs)
+{
+    BDRVQcowState *s = bs->opaque;
+
+    if (s->incompatible_features & QCOW2_INCOMPAT_DIRTY) {
+        int ret = bdrv_flush(bs);
+        if (ret < 0) {
+            return ret;
+        }
+
+        s->incompatible_features &= ~QCOW2_INCOMPAT_DIRTY;
+        return qcow2_update_header(bs);
+    }
+    return 0;
+}
+
 static int qcow2_open(BlockDriverState *bs, int flags)
 {
     BDRVQcowState *s = bs->opaque;
@@ -287,12 +308,13 @@ static int qcow2_open(BlockDriverState *bs, int flags)
     s->compatible_features      = header.compatible_features;
     s->autoclear_features       = header.autoclear_features;
 
-    if (s->incompatible_features != 0) {
+    if (s->incompatible_features & ~QCOW2_INCOMPAT_MASK) {
         void *feature_table = NULL;
         qcow2_read_extensions(bs, header.header_length, ext_end,
                               &feature_table);
         report_unsupported_feature(bs, feature_table,
-                                   s->incompatible_features);
+                                   s->incompatible_features &
+                                   ~QCOW2_INCOMPAT_MASK);
         ret = -ENOTSUP;
         goto fail;
     }
@@ -412,6 +434,22 @@ static int qcow2_open(BlockDriverState *bs, int flags)
     /* Initialise locks */
     qemu_co_mutex_init(&s->lock);
 
+    /* Repair image if dirty */
+    if ((s->incompatible_features & QCOW2_INCOMPAT_DIRTY) &&
+        !bs->read_only) {
+        BdrvCheckResult result = {0};
+
+        ret = qcow2_check_refcounts(bs, &result, BDRV_FIX_ERRORS);
+        if (ret < 0) {
+            goto fail;
+        }
+
+        ret = qcow2_mark_clean(bs);
+        if (ret < 0) {
+            goto fail;
+        }
+    }
+
 #ifdef DEBUG_ALLOC
     {
         BdrvCheckResult result = {0};
@@ -785,6 +823,8 @@ static void qcow2_close(BlockDriverState *bs)
     qcow2_cache_flush(bs, s->l2_table_cache);
     qcow2_cache_flush(bs, s->refcount_block_cache);
 
+    qcow2_mark_clean(bs);
+
     qcow2_cache_destroy(bs, s->l2_table_cache);
     qcow2_cache_destroy(bs, s->refcount_block_cache);
 
@@ -949,7 +989,11 @@ int qcow2_update_header(BlockDriverState *bs)
 
     /* Feature table */
     Qcow2Feature features[] = {
-        /* no feature defined yet */
+        {
+            .type = QCOW2_FEAT_TYPE_INCOMPATIBLE,
+            .bit  = QCOW2_INCOMPAT_DIRTY_BITNR,
+            .name = "dirty bit",
+        },
     };
 
     ret = header_ext_add(buf, QCOW2_EXT_MAGIC_FEATURE_TABLE,
diff --git a/block/qcow2.h b/block/qcow2.h
index 455b6d7..b5fefc0 100644
--- a/block/qcow2.h
+++ b/block/qcow2.h
@@ -110,6 +110,14 @@ enum {
     QCOW2_FEAT_TYPE_AUTOCLEAR       = 2,
 };
 
+/* Incompatible feature bits */
+enum {
+    QCOW2_INCOMPAT_DIRTY_BITNR   = 0,
+    QCOW2_INCOMPAT_DIRTY         = 1 << QCOW2_INCOMPAT_DIRTY_BITNR,
+
+    QCOW2_INCOMPAT_MASK          = QCOW2_INCOMPAT_DIRTY,
+};
+
 typedef struct Qcow2Feature {
     uint8_t type;
     uint8_t bit;
diff --git a/tests/qemu-iotests/031.out b/tests/qemu-iotests/031.out
index d3cab30..297b458 100644
--- a/tests/qemu-iotests/031.out
+++ b/tests/qemu-iotests/031.out
@@ -54,8 +54,8 @@ header_length             72
 
 Header extension:
 magic                     0x6803f857
-length                    0
-data                      ''
+length                    48
+data                      <binary>
 
 Header extension:
 magic                     0x12345678
@@ -68,7 +68,7 @@ No errors were found on the image.
 
 magic                     0x514649fb
 version                   2
-backing_file_offset       0x98
+backing_file_offset       0xc8
 backing_file_size         0x17
 cluster_bits              16
 size                      67108864
@@ -92,8 +92,8 @@ data                      'host_device'
 
 Header extension:
 magic                     0x6803f857
-length                    0
-data                      ''
+length                    48
+data                      <binary>
 
 Header extension:
 magic                     0x12345678
@@ -155,8 +155,8 @@ header_length             104
 
 Header extension:
 magic                     0x6803f857
-length                    0
-data                      ''
+length                    48
+data                      <binary>
 
 Header extension:
 magic                     0x12345678
@@ -169,7 +169,7 @@ No errors were found on the image.
 
 magic                     0x514649fb
 version                   3
-backing_file_offset       0xb8
+backing_file_offset       0xe8
 backing_file_size         0x17
 cluster_bits              16
 size                      67108864
@@ -193,8 +193,8 @@ data                      'host_device'
 
 Header extension:
 magic                     0x6803f857
-length                    0
-data                      ''
+length                    48
+data                      <binary>
 
 Header extension:
 magic                     0x12345678
diff --git a/tests/qemu-iotests/036.out b/tests/qemu-iotests/036.out
index 6953e37..ca0fda1 100644
--- a/tests/qemu-iotests/036.out
+++ b/tests/qemu-iotests/036.out
@@ -46,7 +46,7 @@ header_length             104
 
 Header extension:
 magic                     0x6803f857
-length                    0
-data                      ''
+length                    48
+data                      <binary>
 
 *** done
commit 0f6d767aa84676a2374d38797f42df4595415369
Author: Stefan Hajnoczi <stefanha at linux.vnet.ibm.com>
Date:   Fri Jul 27 09:05:18 2012 +0100

    docs: add dirty bit to qcow2 specification
    
    The dirty bit will make it possible to perform lazy refcount updates,
    where the image file is not kept consistent all the time.  Upon opening
    a dirty image file, it is necessary to perform a consistency check and
    repair any incorrect refcounts.
    
    Therefore the dirty bit must be an incompatible feature bit.  We don't
    want old programs accessing a file with stale refcounts.
    
    Signed-off-by: Stefan Hajnoczi <stefanha at linux.vnet.ibm.com>
    Signed-off-by: Kevin Wolf <kwolf at redhat.com>

diff --git a/docs/specs/qcow2.txt b/docs/specs/qcow2.txt
index 87bf785..339cdc1 100644
--- a/docs/specs/qcow2.txt
+++ b/docs/specs/qcow2.txt
@@ -75,7 +75,12 @@ in the description of a field.
                     Bitmask of incompatible features. An implementation must
                     fail to open an image if an unknown bit is set.
 
-                    Bits 0-63:  Reserved (set to 0)
+                    Bit 0:      Dirty bit.  If this bit is set then refcounts
+                                may be inconsistent, make sure to scan L1/L2
+                                tables to repair refcounts before accessing the
+                                image.
+
+                    Bits 1-63:  Reserved (set to 0)
 
          80 -  87:  compatible_features
                     Bitmask of compatible features. An implementation can
commit e77964f79b905760ce7f0406fc6b988daeabbb65
Author: Stefan Hajnoczi <stefanha at linux.vnet.ibm.com>
Date:   Fri Jul 27 09:01:27 2012 +0100

    qemu-iotests: add qed.py image manipulation utility
    
    The qed.py utility can inspect and manipulate QED image files.  It can
    be used for testing to see the state of image metadata and also to
    inject corruptions into the image file.  It also has a scrubbing feature
    to copy just the metadata out of an image file, allowing users to share
    broken image files without revealing data in bug reports.
    
    This has lived in my local repo for a long time but could be useful
    to others.
    
    Signed-off-by: Stefan Hajnoczi <stefanha at linux.vnet.ibm.com>
    Signed-off-by: Kevin Wolf <kwolf at redhat.com>

diff --git a/tests/qemu-iotests/qed.py b/tests/qemu-iotests/qed.py
new file mode 100755
index 0000000..52ff845
--- /dev/null
+++ b/tests/qemu-iotests/qed.py
@@ -0,0 +1,235 @@
+#!/usr/bin/env python
+#
+# Tool to manipulate QED image files
+#
+# Copyright (C) 2010 IBM, Corp.
+#
+# Authors:
+#  Stefan Hajnoczi <stefanha at linux.vnet.ibm.com>
+#
+# This work is licensed under the terms of the GNU GPL, version 2 or later.
+# See the COPYING file in the top-level directory.
+
+import sys
+import struct
+import random
+import optparse
+
+# This can be used as a module
+__all__ = ['QED_F_NEED_CHECK', 'QED']
+
+QED_F_NEED_CHECK = 0x02
+
+header_fmt = '<IIIIQQQQQII'
+header_size = struct.calcsize(header_fmt)
+field_names = ['magic', 'cluster_size', 'table_size',
+               'header_size', 'features', 'compat_features',
+               'autoclear_features', 'l1_table_offset', 'image_size',
+               'backing_filename_offset', 'backing_filename_size']
+table_elem_fmt = '<Q'
+table_elem_size = struct.calcsize(table_elem_fmt)
+
+def err(msg):
+    sys.stderr.write(msg + '\n')
+    sys.exit(1)
+
+def unpack_header(s):
+    fields = struct.unpack(header_fmt, s)
+    return dict((field_names[idx], val) for idx, val in enumerate(fields))
+
+def pack_header(header):
+    fields = tuple(header[x] for x in field_names)
+    return struct.pack(header_fmt, *fields)
+
+def unpack_table_elem(s):
+    return struct.unpack(table_elem_fmt, s)[0]
+
+def pack_table_elem(elem):
+    return struct.pack(table_elem_fmt, elem)
+
+class QED(object):
+    def __init__(self, f):
+        self.f = f
+
+        self.f.seek(0, 2)
+        self.filesize = f.tell()
+
+        self.load_header()
+        self.load_l1_table()
+
+    def raw_pread(self, offset, size):
+        self.f.seek(offset)
+        return self.f.read(size)
+
+    def raw_pwrite(self, offset, data):
+        self.f.seek(offset)
+        return self.f.write(data)
+
+    def load_header(self):
+        self.header = unpack_header(self.raw_pread(0, header_size))
+
+    def store_header(self):
+        self.raw_pwrite(0, pack_header(self.header))
+
+    def read_table(self, offset):
+        size = self.header['table_size'] * self.header['cluster_size']
+        s = self.raw_pread(offset, size)
+        table = [unpack_table_elem(s[i:i + table_elem_size]) for i in xrange(0, size, table_elem_size)]
+        return table
+
+    def load_l1_table(self):
+        self.l1_table = self.read_table(self.header['l1_table_offset'])
+        self.table_nelems = self.header['table_size'] * self.header['cluster_size'] / table_elem_size
+
+    def write_table(self, offset, table):
+        s = ''.join(pack_table_elem(x) for x in table)
+        self.raw_pwrite(offset, s)
+
+def random_table_item(table):
+    vals = [(index, offset) for index, offset in enumerate(table) if offset != 0]
+    if not vals:
+        err('cannot pick random item because table is empty')
+    return random.choice(vals)
+
+def corrupt_table_duplicate(table):
+    '''Corrupt a table by introducing a duplicate offset'''
+    victim_idx, victim_val = random_table_item(table)
+    unique_vals = set(table)
+    if len(unique_vals) == 1:
+        err('no duplication corruption possible in table')
+    dup_val = random.choice(list(unique_vals.difference([victim_val])))
+    table[victim_idx] = dup_val
+
+def corrupt_table_invalidate(qed, table):
+    '''Corrupt a table by introducing an invalid offset'''
+    index, _ = random_table_item(table)
+    table[index] = qed.filesize + random.randint(0, 100 * 1024 * 1024 * 1024 * 1024)
+
+def cmd_show(qed, *args):
+    '''show [header|l1|l2 <offset>]- Show header or l1/l2 tables'''
+    if not args or args[0] == 'header':
+        print qed.header
+    elif args[0] == 'l1':
+        print qed.l1_table
+    elif len(args) == 2 and args[0] == 'l2':
+        offset = int(args[1])
+        print qed.read_table(offset)
+    else:
+        err('unrecognized sub-command')
+
+def cmd_duplicate(qed, table_level):
+    '''duplicate l1|l2 - Duplicate a random table element'''
+    if table_level == 'l1':
+        offset = qed.header['l1_table_offset']
+        table = qed.l1_table
+    elif table_level == 'l2':
+        _, offset = random_table_item(qed.l1_table)
+        table = qed.read_table(offset)
+    else:
+        err('unrecognized sub-command')
+    corrupt_table_duplicate(table)
+    qed.write_table(offset, table)
+
+def cmd_invalidate(qed, table_level):
+    '''invalidate l1|l2 - Plant an invalid table element at random'''
+    if table_level == 'l1':
+        offset = qed.header['l1_table_offset']
+        table = qed.l1_table
+    elif table_level == 'l2':
+        _, offset = random_table_item(qed.l1_table)
+        table = qed.read_table(offset)
+    else:
+        err('unrecognized sub-command')
+    corrupt_table_invalidate(qed, table)
+    qed.write_table(offset, table)
+
+def cmd_need_check(qed, *args):
+    '''need-check [on|off] - Test, set, or clear the QED_F_NEED_CHECK header bit'''
+    if not args:
+        print bool(qed.header['features'] & QED_F_NEED_CHECK)
+        return
+
+    if args[0] == 'on':
+        qed.header['features'] |= QED_F_NEED_CHECK
+    elif args[0] == 'off':
+        qed.header['features'] &= ~QED_F_NEED_CHECK
+    else:
+        err('unrecognized sub-command')
+    qed.store_header()
+
+def cmd_zero_cluster(qed, pos, *args):
+    '''zero-cluster <pos> [<n>] - Zero data clusters'''
+    pos, n = int(pos), 1
+    if args:
+        if len(args) != 1:
+            err('expected one argument')
+        n = int(args[0])
+
+    for i in xrange(n):
+        l1_index = pos / qed.header['cluster_size'] / len(qed.l1_table)
+        if qed.l1_table[l1_index] == 0:
+            err('no l2 table allocated')
+
+        l2_offset = qed.l1_table[l1_index]
+        l2_table = qed.read_table(l2_offset)
+
+        l2_index = (pos / qed.header['cluster_size']) % len(qed.l1_table)
+        l2_table[l2_index] = 1 # zero the data cluster
+        qed.write_table(l2_offset, l2_table)
+        pos += qed.header['cluster_size']
+
+def cmd_copy_metadata(qed, outfile):
+    '''copy-metadata <outfile> - Copy metadata only (for scrubbing corrupted images)'''
+    out = open(outfile, 'wb')
+
+    # Match file size
+    out.seek(qed.filesize - 1)
+    out.write('\0')
+
+    # Copy header clusters
+    out.seek(0)
+    header_size_bytes = qed.header['header_size'] * qed.header['cluster_size']
+    out.write(qed.raw_pread(0, header_size_bytes))
+
+    # Copy L1 table
+    out.seek(qed.header['l1_table_offset'])
+    s = ''.join(pack_table_elem(x) for x in qed.l1_table)
+    out.write(s)
+
+    # Copy L2 tables
+    for l2_offset in qed.l1_table:
+        if l2_offset == 0:
+            continue
+        l2_table = qed.read_table(l2_offset)
+        out.seek(l2_offset)
+        s = ''.join(pack_table_elem(x) for x in l2_table)
+        out.write(s)
+
+    out.close()
+
+def usage():
+    print 'Usage: %s <file> <cmd> [<arg>, ...]' % sys.argv[0]
+    print
+    print 'Supported commands:'
+    for cmd in sorted(x for x in globals() if x.startswith('cmd_')):
+        print globals()[cmd].__doc__
+    sys.exit(1)
+
+def main():
+    if len(sys.argv) < 3:
+        usage()
+    filename, cmd = sys.argv[1:3]
+
+    cmd = 'cmd_' + cmd.replace('-', '_')
+    if cmd not in globals():
+        usage()
+
+    qed = QED(open(filename, 'r+b'))
+    try:
+        globals()[cmd](qed, *sys.argv[3:])
+    except TypeError, e:
+        sys.stderr.write(globals()[cmd].__doc__ + '\n')
+        sys.exit(1)
+
+if __name__ == '__main__':
+    main()
commit 05290d80c88de1e4d02f2f00605e09206430cca9
Author: Paolo Bonzini <pbonzini at redhat.com>
Date:   Tue Jul 24 13:03:39 2012 +0200

    qapi: generalize documentation of streaming commands
    
    Talk about background operations in general, rather than specifically
    about streaming.
    
    Signed-off-by: Paolo Bonzini <pbonzini at redhat.com>
    Signed-off-by: Kevin Wolf <kwolf at redhat.com>

diff --git a/hmp-commands.hx b/hmp-commands.hx
index eea8b32..9bbc7f7 100644
--- a/hmp-commands.hx
+++ b/hmp-commands.hx
@@ -101,7 +101,7 @@ ETEXI
         .name       = "block_job_cancel",
         .args_type  = "device:B",
         .params     = "device",
-        .help       = "stop an active block streaming operation",
+        .help       = "stop an active background block operation",
         .mhandler.cmd = hmp_block_job_cancel,
     },
 
diff --git a/qapi-schema.json b/qapi-schema.json
index cddf63a..bd9c450 100644
--- a/qapi-schema.json
+++ b/qapi-schema.json
@@ -1660,7 +1660,7 @@
 # Returns: Nothing on success
 #          If the job type does not support throttling, NotSupported
 #          If the speed value is invalid, InvalidParameter
-#          If streaming is not active on this device, DeviceNotActive
+#          If no background operation is active on this device, DeviceNotActive
 #
 # Since: 1.1
 ##
@@ -1670,9 +1670,9 @@
 ##
 # @block-job-cancel:
 #
-# Stop an active block streaming operation.
+# Stop an active background block operation.
 #
-# This command returns immediately after marking the active block streaming
+# This command returns immediately after marking the active background block
 # operation for cancellation.  It is an error to call this command if no
 # operation is in progress.
 #
@@ -1680,16 +1680,15 @@
 # BLOCK_JOB_CANCELLED event.  Before that happens the job is still visible when
 # enumerated using query-block-jobs.
 #
-# The image file retains its backing file unless the streaming operation happens
-# to complete just as it is being cancelled.
-#
-# A new block streaming operation can be started at a later time to finish
-# copying all data from the backing file.
+# For streaming, the image file retains its backing file unless the streaming
+# operation happens to complete just as it is being cancelled.  A new streaming
+# operation can be started at a later time to finish copying all data from the
+# backing file.
 #
 # @device: the device name
 #
 # Returns: Nothing on success
-#          If streaming is not active on this device, DeviceNotActive
+#          If no background operation is active on this device, DeviceNotActive
 #          If cancellation already in progress, DeviceInUse
 #
 # Since: 1.1
commit b2df431407a099ad2fe87a76188d12d99ab12841
Author: Markus Armbruster <armbru at redhat.com>
Date:   Thu Jul 12 18:52:31 2012 +0200

    ide scsi: Mess with geometry only for hard disk devices
    
    Legacy -drive cyls=... are now ignored completely when the drive
    doesn't back a hard disk device.  Before, they were first checked
    against a hard disk's limits, then ignored.
    
    Signed-off-by: Markus Armbruster <armbru at redhat.com>
    Acked-by: Paolo Bonzini <pbonzini at redhat.com>
    Signed-off-by: Kevin Wolf <kwolf at redhat.com>

diff --git a/hw/ide/qdev.c b/hw/ide/qdev.c
index 22e58df..5ea9b8f 100644
--- a/hw/ide/qdev.c
+++ b/hw/ide/qdev.c
@@ -149,7 +149,8 @@ static int ide_dev_initfn(IDEDevice *dev, IDEDriveKind kind)
     }
 
     blkconf_serial(&dev->conf, &dev->serial);
-    if (blkconf_geometry(&dev->conf, &dev->chs_trans, 65536, 16, 255) < 0) {
+    if (kind != IDE_CD
+        && blkconf_geometry(&dev->conf, &dev->chs_trans, 65536, 16, 255) < 0) {
         return -1;
     }
 
diff --git a/hw/scsi-disk.c b/hw/scsi-disk.c
index a9c7279..c8d5edd 100644
--- a/hw/scsi-disk.c
+++ b/hw/scsi-disk.c
@@ -1958,7 +1958,8 @@ static int scsi_initfn(SCSIDevice *dev)
     }
 
     blkconf_serial(&s->qdev.conf, &s->serial);
-    if (blkconf_geometry(&dev->conf, NULL, 65535, 255, 255) < 0) {
+    if (dev->type == TYPE_DISK
+        && blkconf_geometry(&dev->conf, NULL, 65535, 255, 255) < 0) {
         return -1;
     }
 
commit 26b9b5fe17cc1b6be2e8bf8b9d16094f420bb8ad
Author: Paolo Bonzini <pbonzini at redhat.com>
Date:   Mon Aug 6 15:26:14 2012 +0200

    virtio: fix vhost handling
    
    Commit b1f416aa8d870fab71030abc9401cfc77b948e8e breaks vhost_net
    because it always registers the virtio_pci_host_notifier_read() handler
    function on the ioeventfd, even when vhost_net.ko is using the ioeventfd.
    The result is both QEMU and vhost_net.ko polling on the same eventfd
    and the virtio_net.ko guest driver seeing inconsistent results:
    
      # ifconfig eth0 192.168.0.1 netmask 255.255.255.0
      virtio_net virtio0: output:id 0 is not a head!
    
    To fix this, proceed the same as we do for irqfd: add a parameter to
    virtio_queue_set_host_notifier_fd_handler and in that case only set
    the notifier, not the handler.
    
    Cc: Stefan Hajnoczi <stefanha at linux.vnet.ibm.com>
    Tested-by: Stefan Hajnoczi <stefanha at linux.vnet.ibm.com>
    Reviewed-by: Stefan Hajnoczi <stefanha at linux.vnet.ibm.com>
    Signed-off-by: Paolo Bonzini <pbonzini at redhat.com>
    Signed-off-by: Anthony Liguori <aliguori at us.ibm.com>

diff --git a/hw/virtio-pci.c b/hw/virtio-pci.c
index 3ab9747..125eded 100644
--- a/hw/virtio-pci.c
+++ b/hw/virtio-pci.c
@@ -160,7 +160,7 @@ static int virtio_pci_load_queue(void * opaque, int n, QEMUFile *f)
 }
 
 static int virtio_pci_set_host_notifier_internal(VirtIOPCIProxy *proxy,
-                                                 int n, bool assign)
+                                                 int n, bool assign, bool set_handler)
 {
     VirtQueue *vq = virtio_get_queue(proxy->vdev, n);
     EventNotifier *notifier = virtio_queue_get_host_notifier(vq);
@@ -173,13 +173,13 @@ static int virtio_pci_set_host_notifier_internal(VirtIOPCIProxy *proxy,
                          __func__, r);
             return r;
         }
-        virtio_queue_set_host_notifier_fd_handler(vq, true);
+        virtio_queue_set_host_notifier_fd_handler(vq, true, set_handler);
         memory_region_add_eventfd(&proxy->bar, VIRTIO_PCI_QUEUE_NOTIFY, 2,
                                   true, n, notifier);
     } else {
         memory_region_del_eventfd(&proxy->bar, VIRTIO_PCI_QUEUE_NOTIFY, 2,
                                   true, n, notifier);
-        virtio_queue_set_host_notifier_fd_handler(vq, false);
+        virtio_queue_set_host_notifier_fd_handler(vq, false, false);
         event_notifier_cleanup(notifier);
     }
     return r;
@@ -200,7 +200,7 @@ static void virtio_pci_start_ioeventfd(VirtIOPCIProxy *proxy)
             continue;
         }
 
-        r = virtio_pci_set_host_notifier_internal(proxy, n, true);
+        r = virtio_pci_set_host_notifier_internal(proxy, n, true, true);
         if (r < 0) {
             goto assign_error;
         }
@@ -214,7 +214,7 @@ assign_error:
             continue;
         }
 
-        r = virtio_pci_set_host_notifier_internal(proxy, n, false);
+        r = virtio_pci_set_host_notifier_internal(proxy, n, false, false);
         assert(r >= 0);
     }
     proxy->ioeventfd_started = false;
@@ -235,7 +235,7 @@ static void virtio_pci_stop_ioeventfd(VirtIOPCIProxy *proxy)
             continue;
         }
 
-        r = virtio_pci_set_host_notifier_internal(proxy, n, false);
+        r = virtio_pci_set_host_notifier_internal(proxy, n, false, false);
         assert(r >= 0);
     }
     proxy->ioeventfd_started = false;
@@ -683,7 +683,7 @@ static int virtio_pci_set_host_notifier(void *opaque, int n, bool assign)
      * currently only stops on status change away from ok,
      * reset, vmstop and such. If we do add code to start here,
      * need to check vmstate, device state etc. */
-    return virtio_pci_set_host_notifier_internal(proxy, n, assign);
+    return virtio_pci_set_host_notifier_internal(proxy, n, assign, false);
 }
 
 static void virtio_pci_vmstate_change(void *opaque, bool running)
diff --git a/hw/virtio.c b/hw/virtio.c
index d146f86..209c763 100644
--- a/hw/virtio.c
+++ b/hw/virtio.c
@@ -1021,13 +1021,16 @@ static void virtio_queue_host_notifier_read(EventNotifier *n)
     }
 }
 
-void virtio_queue_set_host_notifier_fd_handler(VirtQueue *vq, bool assign)
+void virtio_queue_set_host_notifier_fd_handler(VirtQueue *vq, bool assign,
+                                               bool set_handler)
 {
-    if (assign) {
+    if (assign && set_handler) {
         event_notifier_set_handler(&vq->host_notifier,
                                    virtio_queue_host_notifier_read);
     } else {
         event_notifier_set_handler(&vq->host_notifier, NULL);
+    }
+    if (!assign) {
         /* Test and clear notifier before after disabling event,
          * in case poll callback didn't have time to run. */
         virtio_queue_host_notifier_read(&vq->host_notifier);
diff --git a/hw/virtio.h b/hw/virtio.h
index f8b5535..7a4f564 100644
--- a/hw/virtio.h
+++ b/hw/virtio.h
@@ -233,7 +233,8 @@ EventNotifier *virtio_queue_get_guest_notifier(VirtQueue *vq);
 void virtio_queue_set_guest_notifier_fd_handler(VirtQueue *vq, bool assign,
                                                 bool with_irqfd);
 EventNotifier *virtio_queue_get_host_notifier(VirtQueue *vq);
-void virtio_queue_set_host_notifier_fd_handler(VirtQueue *vq, bool assign);
+void virtio_queue_set_host_notifier_fd_handler(VirtQueue *vq, bool assign,
+                                               bool set_handler);
 void virtio_queue_notify_vq(VirtQueue *vq);
 void virtio_irq(VirtQueue *vq);
 #endif
commit 22d48de65c88c42e3cb2b000491dc6089a240e2a
Merge: f777501... 648cd33...
Author: Anthony Liguori <aliguori at us.ibm.com>
Date:   Mon Aug 6 13:59:59 2012 -0500

    Merge remote-tracking branch 'kiszka/queues/slirp' into staging
    
    * kiszka/queues/slirp:
      slirp: Handle whole 127.0.0.0/8 network as local addresses.

commit f777501cc9e8f3a91da076e937b5565510eb4420
Merge: 17a4ed8... 95c0982...
Author: Blue Swirl <blauwirbel at gmail.com>
Date:   Sat Aug 4 17:58:23 2012 +0000

    Merge branch 'axp-next' of git://repo.or.cz/qemu/rth
    
    * 'axp-next' of git://repo.or.cz/qemu/rth:
      alpha-linux-user: Fix the getpriority syscall
      alpha-linux-user: Properly handle the non-rt sigprocmask syscall.
      alpha-linux-user: Fix a3 error return with v0 error bypass.
      linux-user: Translate pipe2 flags; add to strace
      linux-user: Allocate the right amount of space for non-fixed file maps
      linux-user: Handle O_SYNC, O_NOATIME, O_CLOEXEC, O_PATH
      linux-user: Sync fcntl.h bits with the kernel
      alpha-linux-user: Handle TARGET_SSI_IEEE_RAISE_EXCEPTION properly
      alpha-linux-user: Work around hosted mmap allocation problems
      alpha-linux-user: Fix signal handling

commit 95c098286bd5e8397ef25deee15477e0398979b9
Author: Richard Henderson <rth at twiddle.net>
Date:   Thu Jun 7 15:14:50 2012 -0700

    alpha-linux-user: Fix the getpriority syscall
    
    Alpha uses unbiased priority values in the syscall, with the a3
    return value signaling error conditions.  Therefore, properly
    interpret the libc getpriority as needed for the guest rather
    than passing the host value through unchanged.
    
    Signed-off-by: Richard Henderson <rth at twiddle.net>

diff --git a/linux-user/syscall.c b/linux-user/syscall.c
index 0d3fff5..3ba3ef5 100644
--- a/linux-user/syscall.c
+++ b/linux-user/syscall.c
@@ -218,7 +218,6 @@ _syscall3(int, sys_getdents, uint, fd, struct linux_dirent *, dirp, uint, count)
 #if defined(TARGET_NR_getdents64) && defined(__NR_getdents64)
 _syscall3(int, sys_getdents64, uint, fd, struct linux_dirent64 *, dirp, uint, count);
 #endif
-_syscall2(int, sys_getpriority, int, which, int, who);
 #if defined(TARGET_NR__llseek) && defined(__NR_llseek)
 _syscall5(int, _llseek,  uint,  fd, ulong, hi, ulong, lo,
           loff_t *, res, uint, wh);
@@ -6445,10 +6444,21 @@ abi_long do_syscall(void *cpu_env, int num, abi_long arg1,
         break;
 #endif
     case TARGET_NR_getpriority:
-        /* libc does special remapping of the return value of
-         * sys_getpriority() so it's just easiest to call
-         * sys_getpriority() directly rather than through libc. */
-        ret = get_errno(sys_getpriority(arg1, arg2));
+        /* Note that negative values are valid for getpriority, so we must
+           differentiate based on errno settings.  */
+        errno = 0;
+        ret = getpriority(arg1, arg2);
+        if (ret == -1 && errno != 0) {
+            ret = -host_to_target_errno(errno);
+            break;
+        }
+#ifdef TARGET_ALPHA
+        /* Return value is the unbiased priority.  Signal no error.  */
+        ((CPUAlphaState *)cpu_env)->ir[IR_V0] = 0;
+#else
+        /* Return value is a biased priority to avoid negative numbers.  */
+        ret = 20 - ret;
+#endif
         break;
     case TARGET_NR_setpriority:
         ret = get_errno(setpriority(arg1, arg2, arg3));
commit 0229f5a30efa7af51ac750fa0720a2e37978644e
Author: Richard Henderson <rth at twiddle.net>
Date:   Thu Jun 7 15:02:49 2012 -0700

    alpha-linux-user: Properly handle the non-rt sigprocmask syscall.
    
    Name the syscall properly for QEMU, kernel source notwithstanding.
    Fix syntax errors in the code thus enabled within do_syscall.
    
    Reviewed-by: Peter Maydell <peter.maydell at linaro.org>
    Signed-off-by: Richard Henderson <rth at twiddle.net>

diff --git a/linux-user/alpha/syscall_nr.h b/linux-user/alpha/syscall_nr.h
index f6284db..ac2b6e2 100644
--- a/linux-user/alpha/syscall_nr.h
+++ b/linux-user/alpha/syscall_nr.h
@@ -46,7 +46,7 @@
 #define TARGET_NR_open		 45
 #define TARGET_NR_osf_old_sigaction	 46	/* not implemented */
 #define TARGET_NR_getxgid		 47
-#define TARGET_NR_osf_sigprocmask	 48
+#define TARGET_NR_sigprocmask    48
 #define TARGET_NR_osf_getlogin	 49	/* not implemented */
 #define TARGET_NR_osf_setlogin	 50	/* not implemented */
 #define TARGET_NR_acct		 51
diff --git a/linux-user/syscall.c b/linux-user/syscall.c
index 07823e1..0d3fff5 100644
--- a/linux-user/syscall.c
+++ b/linux-user/syscall.c
@@ -5881,11 +5881,10 @@ abi_long do_syscall(void *cpu_env, int num, abi_long arg1,
             target_to_host_old_sigset(&set, &mask);
 
             ret = get_errno(sigprocmask(how, &set, &oldset));
-
             if (!is_error(ret)) {
                 host_to_target_old_sigset(&mask, &oldset);
                 ret = mask;
-                ((CPUAlphaState *)cpu_env)->[IR_V0] = 0; /* force no error */
+                ((CPUAlphaState *)cpu_env)->ir[IR_V0] = 0; /* force no error */
             }
 #else
             sigset_t set, oldset, *set_ptr;
commit 0e141977e690ee6cd06e5a842eae0be291297efa
Author: Richard Henderson <rth at twiddle.net>
Date:   Thu Jun 7 14:47:41 2012 -0700

    alpha-linux-user: Fix a3 error return with v0 error bypass.
    
    We were failing to initialize a3 for syscalls that bypass the
    negative return value error check.
    
    Signed-off-by: Richard Henderson <rth at twiddle.net>

diff --git a/linux-user/main.c b/linux-user/main.c
index a21942c..53714de 100644
--- a/linux-user/main.c
+++ b/linux-user/main.c
@@ -2846,13 +2846,11 @@ void cpu_loop(CPUAlphaState *env)
                     break;
                 }
                 /* Syscall writes 0 to V0 to bypass error check, similar
-                   to how this is handled internal to Linux kernel.  */
-                if (env->ir[IR_V0] == 0) {
-                    env->ir[IR_V0] = sysret;
-                } else {
-                    env->ir[IR_V0] = (sysret < 0 ? -sysret : sysret);
-                    env->ir[IR_A3] = (sysret < 0);
-                }
+                   to how this is handled internal to Linux kernel.
+                   (Ab)use trapnr temporarily as boolean indicating error.  */
+                trapnr = (env->ir[IR_V0] != 0 && sysret < 0);
+                env->ir[IR_V0] = (trapnr ? -sysret : sysret);
+                env->ir[IR_A3] = trapnr;
                 break;
             case 0x86:
                 /* IMB */
commit e7ea6cbefdddd63851d3e9b7bc1f82c2c2985756
Author: Richard Henderson <rth at twiddle.net>
Date:   Fri Jun 1 18:48:39 2012 -0700

    linux-user: Translate pipe2 flags; add to strace
    
    Reviewed-by: Peter Maydell <peter.maydell at linaro.org>
    Signed-off-by: Richard Henderson <rth at twiddle.net>

diff --git a/linux-user/strace.list b/linux-user/strace.list
index a7eeaef..af3c6a0 100644
--- a/linux-user/strace.list
+++ b/linux-user/strace.list
@@ -1527,3 +1527,6 @@
 #ifdef TARGET_NR_sync_file_range2
 { TARGET_NR_sync_file_range2, "sync_file_range2", NULL, NULL, NULL },
 #endif
+#ifdef TARGET_NR_pipe2
+{ TARGET_NR_pipe2, "pipe2", NULL, NULL, NULL },
+#endif
diff --git a/linux-user/syscall.c b/linux-user/syscall.c
index 7d149a1..07823e1 100644
--- a/linux-user/syscall.c
+++ b/linux-user/syscall.c
@@ -5595,7 +5595,8 @@ abi_long do_syscall(void *cpu_env, int num, abi_long arg1,
         break;
 #ifdef TARGET_NR_pipe2
     case TARGET_NR_pipe2:
-        ret = do_pipe(cpu_env, arg1, arg2, 1);
+        ret = do_pipe(cpu_env, arg1,
+                      target_to_host_bitmask(arg2, fcntl_flags_tbl), 1);
         break;
 #endif
     case TARGET_NR_times:
commit a5e7ee467c6b8cdfc0fc0f1958d5b0f479d76aaf
Author: Richard Henderson <rth at twiddle.net>
Date:   Fri Jun 1 16:07:52 2012 -0700

    linux-user: Allocate the right amount of space for non-fixed file maps
    
    If we let the kernel handle the implementation of mmap_find_vma,
    via an anon mmap, we must use the size as indicated by the user
    and not the size truncated to the filesize.
    
    This happens often in ld.so, where we initially mmap the file to
    the size of the text+data+bss to reserve an area, then mmap+fixed
    over the top to properly handle data and bss.
    
    Signed-off-by: Richard Henderson <rth at twiddle.net>

diff --git a/linux-user/mmap.c b/linux-user/mmap.c
index d9468fe..b412e3f 100644
--- a/linux-user/mmap.c
+++ b/linux-user/mmap.c
@@ -382,7 +382,6 @@ abi_long target_mmap(abi_ulong start, abi_ulong len, int prot,
                      int flags, int fd, abi_ulong offset)
 {
     abi_ulong ret, end, real_start, real_end, retaddr, host_offset, host_len;
-    unsigned long host_start;
 
     mmap_lock();
 #ifdef DEBUG_MMAP
@@ -421,6 +420,19 @@ abi_long target_mmap(abi_ulong start, abi_ulong len, int prot,
     if (len == 0)
         goto the_end;
     real_start = start & qemu_host_page_mask;
+    host_offset = offset & qemu_host_page_mask;
+
+    /* If the user is asking for the kernel to find a location, do that
+       before we truncate the length for mapping files below.  */
+    if (!(flags & MAP_FIXED)) {
+        host_len = len + offset - host_offset;
+        host_len = HOST_PAGE_ALIGN(host_len);
+        start = mmap_find_vma(real_start, host_len);
+        if (start == (abi_ulong)-1) {
+            errno = ENOMEM;
+            goto fail;
+        }
+    }
 
     /* When mapping files into a memory area larger than the file, accesses
        to pages beyond the file size will cause a SIGBUS. 
@@ -453,27 +465,23 @@ abi_long target_mmap(abi_ulong start, abi_ulong len, int prot,
     }
 
     if (!(flags & MAP_FIXED)) {
-        abi_ulong mmap_start;
+        unsigned long host_start;
         void *p;
-        host_offset = offset & qemu_host_page_mask;
+
         host_len = len + offset - host_offset;
         host_len = HOST_PAGE_ALIGN(host_len);
-        mmap_start = mmap_find_vma(real_start, host_len);
-        if (mmap_start == (abi_ulong)-1) {
-            errno = ENOMEM;
-            goto fail;
-        }
+
         /* Note: we prefer to control the mapping address. It is
            especially important if qemu_host_page_size >
            qemu_real_host_page_size */
-        p = mmap(g2h(mmap_start),
-                 host_len, prot, flags | MAP_FIXED | MAP_ANONYMOUS, -1, 0);
+        p = mmap(g2h(start), host_len, prot,
+                 flags | MAP_FIXED | MAP_ANONYMOUS, -1, 0);
         if (p == MAP_FAILED)
             goto fail;
         /* update start so that it points to the file position at 'offset' */
         host_start = (unsigned long)p;
         if (!(flags & MAP_ANONYMOUS)) {
-            p = mmap(g2h(mmap_start), len, prot, 
+            p = mmap(g2h(start), len, prot,
                      flags | MAP_FIXED, fd, host_offset);
             host_start += offset - host_offset;
         }
commit afc8763f9db442abdbeb73a6458e27a0031c73b3
Author: Richard Henderson <rth at twiddle.net>
Date:   Wed Jul 25 14:30:34 2012 -0700

    linux-user: Handle O_SYNC, O_NOATIME, O_CLOEXEC, O_PATH
    
    Reviewed-by: Peter Maydell <peter.maydell at linaro.org>
    Signed-off-by: Richard Henderson <rth at twiddle.net>

diff --git a/linux-user/strace.c b/linux-user/strace.c
index 05a0d3e..6ec90e8 100644
--- a/linux-user/strace.c
+++ b/linux-user/strace.c
@@ -371,11 +371,21 @@ UNUSED static struct flags open_flags[] = {
     FLAG_TARGET(O_NOCTTY),
     FLAG_TARGET(O_NOFOLLOW),
     FLAG_TARGET(O_NONBLOCK),      /* also O_NDELAY */
-    FLAG_TARGET(O_SYNC),
+    FLAG_TARGET(O_DSYNC),
+    FLAG_TARGET(__O_SYNC),
     FLAG_TARGET(O_TRUNC),
 #ifdef O_DIRECT
     FLAG_TARGET(O_DIRECT),
 #endif
+#ifdef O_NOATIME
+    FLAG_TARGET(O_NOATIME),
+#endif
+#ifdef O_CLOEXEC
+    FLAG_TARGET(O_CLOEXEC),
+#endif
+#ifdef O_PATH
+    FLAG_TARGET(O_PATH),
+#endif
     FLAG_END,
 };
 
diff --git a/linux-user/syscall.c b/linux-user/syscall.c
index 6a8d094..7d149a1 100644
--- a/linux-user/syscall.c
+++ b/linux-user/syscall.c
@@ -261,14 +261,27 @@ static bitmask_transtbl fcntl_flags_tbl[] = {
   { TARGET_O_TRUNC,     TARGET_O_TRUNC,     O_TRUNC,     O_TRUNC,     },
   { TARGET_O_APPEND,    TARGET_O_APPEND,    O_APPEND,    O_APPEND,    },
   { TARGET_O_NONBLOCK,  TARGET_O_NONBLOCK,  O_NONBLOCK,  O_NONBLOCK,  },
+  { TARGET_O_SYNC,      TARGET_O_DSYNC,     O_SYNC,      O_DSYNC,     },
   { TARGET_O_SYNC,      TARGET_O_SYNC,      O_SYNC,      O_SYNC,      },
   { TARGET_FASYNC,      TARGET_FASYNC,      FASYNC,      FASYNC,      },
   { TARGET_O_DIRECTORY, TARGET_O_DIRECTORY, O_DIRECTORY, O_DIRECTORY, },
   { TARGET_O_NOFOLLOW,  TARGET_O_NOFOLLOW,  O_NOFOLLOW,  O_NOFOLLOW,  },
-  { TARGET_O_LARGEFILE, TARGET_O_LARGEFILE, O_LARGEFILE, O_LARGEFILE, },
 #if defined(O_DIRECT)
   { TARGET_O_DIRECT,    TARGET_O_DIRECT,    O_DIRECT,    O_DIRECT,    },
 #endif
+#if defined(O_NOATIME)
+  { TARGET_O_NOATIME,   TARGET_O_NOATIME,   O_NOATIME,   O_NOATIME    },
+#endif
+#if defined(O_CLOEXEC)
+  { TARGET_O_CLOEXEC,   TARGET_O_CLOEXEC,   O_CLOEXEC,   O_CLOEXEC    },
+#endif
+#if defined(O_PATH)
+  { TARGET_O_PATH,      TARGET_O_PATH,      O_PATH,      O_PATH       },
+#endif
+  /* Don't terminate the list prematurely on 64-bit host+guest.  */
+#if TARGET_O_LARGEFILE != 0 || O_LARGEFILE != 0
+  { TARGET_O_LARGEFILE, TARGET_O_LARGEFILE, O_LARGEFILE, O_LARGEFILE, },
+#endif
   { 0, 0, 0, 0 }
 };
 
commit 4eeea4f3f12a85ef955ac162c81a153a020cf9d7
Author: Richard Henderson <rth at twiddle.net>
Date:   Wed Jul 25 14:29:31 2012 -0700

    linux-user: Sync fcntl.h bits with the kernel
    
    For each target, only define the bits that appear in
    arch/target/include/asm/fcntl.h.  Mirror the kernel's
    asm-generic layout by handling anything undefined afterward.
    
    Signed-off-by: Richard Henderson <rth at twiddle.net>

diff --git a/linux-user/syscall_defs.h b/linux-user/syscall_defs.h
index 308831f..ba9a58c 100644
--- a/linux-user/syscall_defs.h
+++ b/linux-user/syscall_defs.h
@@ -2046,135 +2046,125 @@ struct target_statfs64 {
 #define TARGET_F_DUPFD_CLOEXEC (TARGET_F_LINUX_SPECIFIC_BASE + 6)
 #define TARGET_F_NOTIFY  (TARGET_F_LINUX_SPECIFIC_BASE+2)
 
-#if defined (TARGET_ARM)
-#define TARGET_O_ACCMODE          0003
-#define TARGET_O_RDONLY             00
-#define TARGET_O_WRONLY             01
-#define TARGET_O_RDWR               02
-#define TARGET_O_CREAT            0100 /* not fcntl */
-#define TARGET_O_EXCL             0200 /* not fcntl */
-#define TARGET_O_NOCTTY           0400 /* not fcntl */
-#define TARGET_O_TRUNC           01000 /* not fcntl */
-#define TARGET_O_APPEND          02000
-#define TARGET_O_NONBLOCK        04000
-#define TARGET_O_NDELAY        TARGET_O_NONBLOCK
-#define TARGET_O_SYNC           010000
-#define TARGET_FASYNC           020000 /* fcntl, for BSD compatibility */
+#if defined(TARGET_ALPHA)
+#define TARGET_O_NONBLOCK           04
+#define TARGET_O_APPEND            010
+#define TARGET_O_CREAT           01000 /* not fcntl */
+#define TARGET_O_TRUNC           02000 /* not fcntl */
+#define TARGET_O_EXCL            04000 /* not fcntl */
+#define TARGET_O_NOCTTY         010000 /* not fcntl */
+#define TARGET_O_DSYNC          040000
+#define TARGET_O_LARGEFILE           0 /* not necessary, always 64-bit */
+#define TARGET_O_DIRECTORY     0100000 /* must be a directory */
+#define TARGET_O_NOFOLLOW      0200000 /* don't follow links */
+#define TARGET_O_DIRECT       02000000 /* direct disk access hint */
+#define TARGET_O_NOATIME      04000000
+#define TARGET_O_CLOEXEC     010000000
+#define TARGET___O_SYNC      020000000
+#define TARGET_O_PATH        040000000
+#elif defined(TARGET_ARM) || defined(TARGET_M68K)
 #define TARGET_O_DIRECTORY      040000 /* must be a directory */
 #define TARGET_O_NOFOLLOW      0100000 /* don't follow links */
 #define TARGET_O_DIRECT        0200000 /* direct disk access hint */
 #define TARGET_O_LARGEFILE     0400000
+#elif defined(TARGET_MIPS)
+#define TARGET_O_APPEND         0x0008
+#define TARGET_O_DSYNC          0x0010
+#define TARGET_O_NONBLOCK       0x0080
+#define TARGET_O_CREAT          0x0100  /* not fcntl */
+#define TARGET_O_TRUNC          0x0200  /* not fcntl */
+#define TARGET_O_EXCL           0x0400  /* not fcntl */
+#define TARGET_O_NOCTTY         0x0800  /* not fcntl */
+#define TARGET_FASYNC           0x1000  /* fcntl, for BSD compatibility */
+#define TARGET_O_LARGEFILE      0x2000  /* allow large file opens */
+#define TARGET___O_SYNC         0x4000
+#define TARGET_O_DIRECT         0x8000  /* direct disk access hint */
 #elif defined (TARGET_PPC)
-#define TARGET_O_ACCMODE          0003
-#define TARGET_O_RDONLY             00
-#define TARGET_O_WRONLY             01
-#define TARGET_O_RDWR               02
-#define TARGET_O_CREAT            0100 /* not fcntl */
-#define TARGET_O_EXCL             0200 /* not fcntl */
-#define TARGET_O_NOCTTY           0400 /* not fcntl */
-#define TARGET_O_TRUNC           01000 /* not fcntl */
-#define TARGET_O_APPEND          02000
-#define TARGET_O_NONBLOCK        04000
-#define TARGET_O_NDELAY        TARGET_O_NONBLOCK
-#define TARGET_O_SYNC           010000
-#define TARGET_FASYNC           020000 /* fcntl, for BSD compatibility */
-#define TARGET_O_DIRECTORY      040000 /* must be a directory */
-#define TARGET_O_NOFOLLOW      0100000 /* don't follow links */
-#define TARGET_O_LARGEFILE     0200000
-#define TARGET_O_DIRECT        0400000 /* direct disk access hint */
-#elif defined (TARGET_MICROBLAZE)
-#define TARGET_O_ACCMODE          0003
-#define TARGET_O_RDONLY             00
-#define TARGET_O_WRONLY             01
-#define TARGET_O_RDWR               02
-#define TARGET_O_CREAT            0100 /* not fcntl */
-#define TARGET_O_EXCL             0200 /* not fcntl */
-#define TARGET_O_NOCTTY           0400 /* not fcntl */
-#define TARGET_O_TRUNC           01000 /* not fcntl */
-#define TARGET_O_APPEND          02000
-#define TARGET_O_NONBLOCK        04000
-#define TARGET_O_NDELAY        TARGET_O_NONBLOCK
-#define TARGET_O_SYNC           010000
-#define TARGET_FASYNC           020000 /* fcntl, for BSD compatibility */
 #define TARGET_O_DIRECTORY      040000 /* must be a directory */
 #define TARGET_O_NOFOLLOW      0100000 /* don't follow links */
 #define TARGET_O_LARGEFILE     0200000
 #define TARGET_O_DIRECT        0400000 /* direct disk access hint */
 #elif defined (TARGET_SPARC)
-#define TARGET_O_RDONLY        0x0000
-#define TARGET_O_WRONLY        0x0001
-#define TARGET_O_RDWR          0x0002
-#define TARGET_O_ACCMODE       0x0003
-#define TARGET_O_APPEND        0x0008
-#define TARGET_FASYNC          0x0040  /* fcntl, for BSD compatibility */
-#define TARGET_O_CREAT         0x0200  /* not fcntl */
-#define TARGET_O_TRUNC         0x0400  /* not fcntl */
-#define TARGET_O_EXCL          0x0800  /* not fcntl */
-#define TARGET_O_SYNC          0x2000
-#define TARGET_O_NONBLOCK      0x4000
-#define TARGET_O_NDELAY        (0x0004 | TARGET_O_NONBLOCK)
-#define TARGET_O_NOCTTY        0x8000  /* not fcntl */
-#define TARGET_O_DIRECTORY     0x10000 /* must be a directory */
-#define TARGET_O_NOFOLLOW      0x20000 /* don't follow links */
+#define TARGET_O_APPEND         0x0008
+#define TARGET_FASYNC           0x0040  /* fcntl, for BSD compatibility */
+#define TARGET_O_CREAT          0x0200  /* not fcntl */
+#define TARGET_O_TRUNC          0x0400  /* not fcntl */
+#define TARGET_O_EXCL           0x0800  /* not fcntl */
+#define TARGET_O_DSYNC          0x2000
+#define TARGET_O_NONBLOCK       0x4000
+# ifdef TARGET_SPARC64
+#  define TARGET_O_NDELAY       0x0004
+# else
+#  define TARGET_O_NDELAY       (0x0004 | TARGET_O_NONBLOCK)
+# endif
+#define TARGET_O_NOCTTY         0x8000  /* not fcntl */
 #define TARGET_O_LARGEFILE     0x40000
-#define TARGET_O_DIRECT        0x100000 /* direct disk access hint */
-#elif defined(TARGET_MIPS)
-#define TARGET_O_ACCMODE	0x0003
-#define TARGET_O_RDONLY	0x0000
-#define TARGET_O_WRONLY	0x0001
-#define TARGET_O_RDWR		0x0002
-#define TARGET_O_APPEND	0x0008
-#define TARGET_O_SYNC		0x0010
-#define TARGET_O_NONBLOCK	0x0080
-#define TARGET_O_CREAT         0x0100	/* not fcntl */
-#define TARGET_O_TRUNC		0x0200	/* not fcntl */
-#define TARGET_O_EXCL		0x0400	/* not fcntl */
-#define TARGET_O_NOCTTY	0x0800	/* not fcntl */
-#define TARGET_FASYNC		0x1000	/* fcntl, for BSD compatibility */
-#define TARGET_O_LARGEFILE	0x2000	/* allow large file opens */
-#define TARGET_O_DIRECT	0x8000	/* direct disk access hint */
-#define TARGET_O_DIRECTORY	0x10000	/* must be a directory */
-#define TARGET_O_NOFOLLOW	0x20000	/* don't follow links */
-#define TARGET_O_NOATIME	0x40000
-#define TARGET_O_NDELAY	TARGET_O_NONBLOCK
-#elif defined(TARGET_ALPHA)
-#define TARGET_O_ACCMODE	0x0003
-#define TARGET_O_RDONLY	0x0000
-#define TARGET_O_WRONLY	0x0001
-#define TARGET_O_RDWR		0x0002
-#define TARGET_O_APPEND	0x0008
-#define TARGET_O_SYNC		0x4000
-#define TARGET_O_NONBLOCK	0x0004
-#define TARGET_O_CREAT         0x0200	/* not fcntl */
-#define TARGET_O_TRUNC		0x0400	/* not fcntl */
-#define TARGET_O_EXCL		0x0800	/* not fcntl */
-#define TARGET_O_NOCTTY	0x1000	/* not fcntl */
-#define TARGET_FASYNC		0x2000	/* fcntl, for BSD compatibility */
-#define TARGET_O_LARGEFILE	0x0000	/* not necessary, always 64-bit */
-#define TARGET_O_DIRECT	0x80000	/* direct disk access hint */
-#define TARGET_O_DIRECTORY	0x8000	/* must be a directory */
-#define TARGET_O_NOFOLLOW	0x10000	/* don't follow links */
-#define TARGET_O_NOATIME	0x100000
-#define TARGET_O_NDELAY	TARGET_O_NONBLOCK
-#else
+#define TARGET_O_DIRECT       0x100000  /* direct disk access hint */
+#define TARGET_O_NOATIME      0x200000
+#define TARGET_O_CLOEXEC      0x400000
+#define TARGET___O_SYNC       0x800000
+#define TARGET_O_PATH        0x1000000
+#endif
+
+/* <asm-generic/fcntl.h> values follow.  */
 #define TARGET_O_ACCMODE          0003
 #define TARGET_O_RDONLY             00
 #define TARGET_O_WRONLY             01
 #define TARGET_O_RDWR               02
+#ifndef TARGET_O_CREAT
 #define TARGET_O_CREAT            0100 /* not fcntl */
+#endif
+#ifndef TARGET_O_EXCL
 #define TARGET_O_EXCL             0200 /* not fcntl */
+#endif
+#ifndef TARGET_O_NOCTTY
 #define TARGET_O_NOCTTY           0400 /* not fcntl */
+#endif
+#ifndef TARGET_O_TRUNC
 #define TARGET_O_TRUNC           01000 /* not fcntl */
+#endif
+#ifndef TARGET_O_APPEND
 #define TARGET_O_APPEND          02000
+#endif
+#ifndef TARGET_O_NONBLOCK
 #define TARGET_O_NONBLOCK        04000
-#define TARGET_O_NDELAY        TARGET_O_NONBLOCK
-#define TARGET_O_SYNC           010000
+#endif
+#ifndef TARGET_O_DSYNC
+#define TARGET_O_DSYNC          010000
+#endif
+#ifndef TARGET_FASYNC
 #define TARGET_FASYNC           020000 /* fcntl, for BSD compatibility */
+#endif
+#ifndef TARGET_O_DIRECT
 #define TARGET_O_DIRECT         040000 /* direct disk access hint */
+#endif
+#ifndef TARGET_O_LARGEFILE
 #define TARGET_O_LARGEFILE     0100000
+#endif
+#ifndef TARGET_O_DIRECTORY
 #define TARGET_O_DIRECTORY     0200000 /* must be a directory */
+#endif
+#ifndef TARGET_O_NOFOLLOW
 #define TARGET_O_NOFOLLOW      0400000 /* don't follow links */
 #endif
+#ifndef TARGET_O_NOATIME
+#define TARGET_O_NOATIME      01000000
+#endif
+#ifndef TARGET_O_CLOEXEC
+#define TARGET_O_CLOEXEC      02000000
+#endif
+#ifndef TARGET___O_SYNC
+#define TARGET___O_SYNC       04000000
+#endif
+#ifndef TARGET_O_PATH
+#define TARGET_O_PATH        010000000
+#endif
+#ifndef TARGET_O_NDELAY
+#define TARGET_O_NDELAY  TARGET_O_NONBLOCK
+#endif
+#ifndef TARGET_O_SYNC
+#define TARGET_O_SYNC    (TARGET___O_SYNC | TARGET_O_DSYNC)
+#endif
 
 struct target_flock {
 	short l_type;
commit 6e06d515d401f0cff81cb81ef230b2b4b6543367
Author: Richard Henderson <rth at twiddle.net>
Date:   Fri Jun 1 09:08:21 2012 -0700

    alpha-linux-user: Handle TARGET_SSI_IEEE_RAISE_EXCEPTION properly
    
    We weren't aggregating the exceptions, nor raising signals properly.
    
    Reviewed-by: Peter Maydell <peter.maydell at linaro.org>
    Signed-off-by: Richard Henderson <rth at twiddle.net>

diff --git a/linux-user/syscall.c b/linux-user/syscall.c
index 630a455..6a8d094 100644
--- a/linux-user/syscall.c
+++ b/linux-user/syscall.c
@@ -7699,13 +7699,13 @@ abi_long do_syscall(void *cpu_env, int num, abi_long arg1,
         ret = -TARGET_EOPNOTSUPP;
         switch (arg1) {
           case TARGET_SSI_IEEE_FP_CONTROL:
-          case TARGET_SSI_IEEE_RAISE_EXCEPTION:
             {
                 uint64_t swcr, fpcr, orig_fpcr;
 
-                if (get_user_u64 (swcr, arg2))
+                if (get_user_u64 (swcr, arg2)) {
                     goto efault;
-                orig_fpcr = cpu_alpha_load_fpcr (cpu_env);
+                }
+                orig_fpcr = cpu_alpha_load_fpcr(cpu_env);
                 fpcr = orig_fpcr & FPCR_DYN_MASK;
 
                 /* Copied from linux ieee_swcr_to_fpcr.  */
@@ -7719,16 +7719,57 @@ abi_long do_syscall(void *cpu_env, int num, abi_long arg1,
                 fpcr |= (swcr & SWCR_MAP_UMZ ? FPCR_UNDZ | FPCR_UNFD : 0);
                 fpcr |= (~swcr & SWCR_TRAP_ENABLE_DNO) << 41;
 
-                cpu_alpha_store_fpcr (cpu_env, fpcr);
+                cpu_alpha_store_fpcr(cpu_env, fpcr);
                 ret = 0;
+            }
+            break;
+
+          case TARGET_SSI_IEEE_RAISE_EXCEPTION:
+            {
+                uint64_t exc, fpcr, orig_fpcr;
+                int si_code;
+
+                if (get_user_u64(exc, arg2)) {
+                    goto efault;
+                }
 
-                if (arg1 == TARGET_SSI_IEEE_RAISE_EXCEPTION) {
-                    /* Old exceptions are not signaled.  */
-                    fpcr &= ~(orig_fpcr & FPCR_STATUS_MASK);
+                orig_fpcr = cpu_alpha_load_fpcr(cpu_env);
 
-                    /* If any exceptions set by this call, and are unmasked,
-                       send a signal.  */
-                    /* ??? FIXME */
+                /* We only add to the exception status here.  */
+                fpcr = orig_fpcr | ((exc & SWCR_STATUS_MASK) << 35);
+
+                cpu_alpha_store_fpcr(cpu_env, fpcr);
+                ret = 0;
+
+                /* Old exceptions are not signaled.  */
+                fpcr &= ~(orig_fpcr & FPCR_STATUS_MASK);
+
+                /* If any exceptions set by this call,
+                   and are unmasked, send a signal.  */
+                si_code = 0;
+                if ((fpcr & (FPCR_INE | FPCR_INED)) == FPCR_INE) {
+                    si_code = TARGET_FPE_FLTRES;
+                }
+                if ((fpcr & (FPCR_UNF | FPCR_UNFD)) == FPCR_UNF) {
+                    si_code = TARGET_FPE_FLTUND;
+                }
+                if ((fpcr & (FPCR_OVF | FPCR_OVFD)) == FPCR_OVF) {
+                    si_code = TARGET_FPE_FLTOVF;
+                }
+                if ((fpcr & (FPCR_DZE | FPCR_DZED)) == FPCR_DZE) {
+                    si_code = TARGET_FPE_FLTDIV;
+                }
+                if ((fpcr & (FPCR_INV | FPCR_INVD)) == FPCR_INV) {
+                    si_code = TARGET_FPE_FLTINV;
+                }
+                if (si_code != 0) {
+                    target_siginfo_t info;
+                    info.si_signo = SIGFPE;
+                    info.si_errno = 0;
+                    info.si_code = si_code;
+                    info._sifields._sigfault._addr
+                        = ((CPUArchState *)cpu_env)->pc;
+                    queue_signal((CPUArchState *)cpu_env, info.si_signo, &info);
                 }
             }
             break;
commit 76393642ae65a613bc8232379b4cd347fe69e08a
Author: Richard Henderson <rth at twiddle.net>
Date:   Thu May 31 16:09:39 2012 -0700

    alpha-linux-user: Work around hosted mmap allocation problems
    
    Signed-off-by: Richard Henderson <rth at twiddle.net>

diff --git a/target-alpha/cpu.h b/target-alpha/cpu.h
index 99f9ee1..5689760 100644
--- a/target-alpha/cpu.h
+++ b/target-alpha/cpu.h
@@ -40,9 +40,20 @@
 
 #define TARGET_PAGE_BITS 13
 
+#ifdef CONFIG_USER_ONLY
+/* ??? The kernel likes to give addresses in high memory.  If the host has
+   more virtual address space than the guest, this can lead to impossible
+   allocations.  Honor the long-standing assumption that only kernel addrs
+   are negative, but otherwise allow allocations anywhere.  This could lead
+   to tricky emulation problems for programs doing tagged addressing, but
+   that's far fewer than encounter the impossible allocation problem.  */
+#define TARGET_PHYS_ADDR_SPACE_BITS  63
+#define TARGET_VIRT_ADDR_SPACE_BITS  63
+#else
 /* ??? EV4 has 34 phys addr bits, EV5 has 40, EV6 has 44.  */
-#define TARGET_PHYS_ADDR_SPACE_BITS	44
-#define TARGET_VIRT_ADDR_SPACE_BITS	(30 + TARGET_PAGE_BITS)
+#define TARGET_PHYS_ADDR_SPACE_BITS  44
+#define TARGET_VIRT_ADDR_SPACE_BITS  (30 + TARGET_PAGE_BITS)
+#endif
 
 /* Alpha major type */
 enum {
commit d0f204952a02a69bc853a1c274b2a5ee4acfd39f
Author: Richard Henderson <rth at twiddle.net>
Date:   Thu May 31 12:05:23 2012 -0700

    alpha-linux-user: Fix signal handling
    
    Proper signal numbers were not defined, and EXCP_INTERRUPT
    was unhandled, leading to all sorts of subtle confusion.
    
    Reviewed-by: Peter Maydell <peter.maydell at linaro.org>
    Signed-off-by: Richard Henderson <rth at twiddle.net>

diff --git a/linux-user/main.c b/linux-user/main.c
index 25eaa11..a21942c 100644
--- a/linux-user/main.c
+++ b/linux-user/main.c
@@ -2921,6 +2921,9 @@ void cpu_loop(CPUAlphaState *env)
         case EXCP_STQ_C:
             do_store_exclusive(env, env->error_code, trapnr - EXCP_STL_C);
             break;
+        case EXCP_INTERRUPT:
+            /* Just indicate that signals should be handled asap.  */
+            break;
         default:
             printf ("Unhandled trap: 0x%x\n", trapnr);
             cpu_dump_state(env, stderr, fprintf, 0);
diff --git a/linux-user/syscall_defs.h b/linux-user/syscall_defs.h
index cfece21..308831f 100644
--- a/linux-user/syscall_defs.h
+++ b/linux-user/syscall_defs.h
@@ -371,7 +371,46 @@ int do_sigaction(int sig, const struct target_sigaction *act,
 #define TARGET_SA_RESTORER	0x04000000
 #endif
 
-#if defined(TARGET_SPARC)
+#if defined(TARGET_ALPHA)
+
+#define TARGET_SIGHUP            1
+#define TARGET_SIGINT            2
+#define TARGET_SIGQUIT           3
+#define TARGET_SIGILL            4
+#define TARGET_SIGTRAP           5
+#define TARGET_SIGABRT           6
+#define TARGET_SIGSTKFLT         7 /* actually SIGEMT */
+#define TARGET_SIGFPE            8
+#define TARGET_SIGKILL           9
+#define TARGET_SIGBUS           10
+#define TARGET_SIGSEGV          11
+#define TARGET_SIGSYS           12
+#define TARGET_SIGPIPE          13
+#define TARGET_SIGALRM          14
+#define TARGET_SIGTERM          15
+#define TARGET_SIGURG           16
+#define TARGET_SIGSTOP          17
+#define TARGET_SIGTSTP          18
+#define TARGET_SIGCONT          19
+#define TARGET_SIGCHLD          20
+#define TARGET_SIGTTIN          21
+#define TARGET_SIGTTOU          22
+#define TARGET_SIGIO            23
+#define TARGET_SIGXCPU          24
+#define TARGET_SIGXFSZ          25
+#define TARGET_SIGVTALRM        26
+#define TARGET_SIGPROF          27
+#define TARGET_SIGWINCH         28
+#define TARGET_SIGPWR           29 /* actually SIGINFO */
+#define TARGET_SIGUSR1          30
+#define TARGET_SIGUSR2          31
+#define TARGET_SIGRTMIN         32
+
+#define TARGET_SIG_BLOCK         1
+#define TARGET_SIG_UNBLOCK       2
+#define TARGET_SIG_SETMASK       3
+
+#elif defined(TARGET_SPARC)
 
 #define TARGET_SIGHUP		 1
 #define TARGET_SIGINT		 2
commit 17a4ed8a5ebbbe8c3e7ea61b523571ddd20fa911
Author: Blue Swirl <blauwirbel at gmail.com>
Date:   Sun Jul 8 19:03:33 2012 +0000

    bitops: drop volatile qualifier
    
    Qualifier 'volatile' is not useful for applications, it's too strict
    for single threaded code but does not give the real atomicity guarantees
    needed for multithreaded code.
    
    Drop them and now useless casts.
    
    Signed-off-by: Blue Swirl <blauwirbel at gmail.com>

diff --git a/bitops.h b/bitops.h
index c456232..74e14e5 100644
--- a/bitops.h
+++ b/bitops.h
@@ -114,10 +114,10 @@ static inline unsigned long ffz(unsigned long word)
  * @nr: the bit to set
  * @addr: the address to start counting from
  */
-static inline void set_bit(int nr, volatile unsigned long *addr)
+static inline void set_bit(int nr, unsigned long *addr)
 {
 	unsigned long mask = BIT_MASK(nr);
-	unsigned long *p = ((unsigned long *)addr) + BIT_WORD(nr);
+        unsigned long *p = addr + BIT_WORD(nr);
 
 	*p  |= mask;
 }
@@ -127,10 +127,10 @@ static inline void set_bit(int nr, volatile unsigned long *addr)
  * @nr: Bit to clear
  * @addr: Address to start counting from
  */
-static inline void clear_bit(int nr, volatile unsigned long *addr)
+static inline void clear_bit(int nr, unsigned long *addr)
 {
 	unsigned long mask = BIT_MASK(nr);
-	unsigned long *p = ((unsigned long *)addr) + BIT_WORD(nr);
+        unsigned long *p = addr + BIT_WORD(nr);
 
 	*p &= ~mask;
 }
@@ -140,10 +140,10 @@ static inline void clear_bit(int nr, volatile unsigned long *addr)
  * @nr: Bit to change
  * @addr: Address to start counting from
  */
-static inline void change_bit(int nr, volatile unsigned long *addr)
+static inline void change_bit(int nr, unsigned long *addr)
 {
 	unsigned long mask = BIT_MASK(nr);
-	unsigned long *p = ((unsigned long *)addr) + BIT_WORD(nr);
+        unsigned long *p = addr + BIT_WORD(nr);
 
 	*p ^= mask;
 }
@@ -153,10 +153,10 @@ static inline void change_bit(int nr, volatile unsigned long *addr)
  * @nr: Bit to set
  * @addr: Address to count from
  */
-static inline int test_and_set_bit(int nr, volatile unsigned long *addr)
+static inline int test_and_set_bit(int nr, unsigned long *addr)
 {
 	unsigned long mask = BIT_MASK(nr);
-	unsigned long *p = ((unsigned long *)addr) + BIT_WORD(nr);
+        unsigned long *p = addr + BIT_WORD(nr);
 	unsigned long old = *p;
 
 	*p = old | mask;
@@ -168,10 +168,10 @@ static inline int test_and_set_bit(int nr, volatile unsigned long *addr)
  * @nr: Bit to clear
  * @addr: Address to count from
  */
-static inline int test_and_clear_bit(int nr, volatile unsigned long *addr)
+static inline int test_and_clear_bit(int nr, unsigned long *addr)
 {
 	unsigned long mask = BIT_MASK(nr);
-	unsigned long *p = ((unsigned long *)addr) + BIT_WORD(nr);
+        unsigned long *p = addr + BIT_WORD(nr);
 	unsigned long old = *p;
 
 	*p = old & ~mask;
@@ -183,10 +183,10 @@ static inline int test_and_clear_bit(int nr, volatile unsigned long *addr)
  * @nr: Bit to change
  * @addr: Address to count from
  */
-static inline int test_and_change_bit(int nr, volatile unsigned long *addr)
+static inline int test_and_change_bit(int nr, unsigned long *addr)
 {
 	unsigned long mask = BIT_MASK(nr);
-	unsigned long *p = ((unsigned long *)addr) + BIT_WORD(nr);
+        unsigned long *p = addr + BIT_WORD(nr);
 	unsigned long old = *p;
 
 	*p = old ^ mask;
@@ -198,7 +198,7 @@ static inline int test_and_change_bit(int nr, volatile unsigned long *addr)
  * @nr: bit number to test
  * @addr: Address to start counting from
  */
-static inline int test_bit(int nr, const volatile unsigned long *addr)
+static inline int test_bit(int nr, const unsigned long *addr)
 {
 	return 1UL & (addr[BIT_WORD(nr)] >> (nr & (BITS_PER_LONG-1)));
 }
commit 9b4c0b56b5f0b341ffa41238e3d2e96ec3b031d9
Author: Peter Maydell <peter.maydell at linaro.org>
Date:   Thu Aug 2 18:30:27 2012 +0100

    configure: Fix set-but-not-used warning in Xen 4.1 probe
    
    The Xen 4.1 probe never uses the return value from xc_interface_open(),
    so was provoking a compiler warning on newer gcc. Fix by not bothering
    to put the return value anywhere.
    
    Signed-off-by: Peter Maydell <peter.maydell at linaro.org>
    Signed-off-by: Blue Swirl <blauwirbel at gmail.com>

diff --git a/configure b/configure
index f05b837..280726c 100755
--- a/configure
+++ b/configure
@@ -1431,9 +1431,8 @@ EOF
 # error HVM_MAX_VCPUS not defined
 #endif
 int main(void) {
-  xc_interface *xc;
   xs_daemon_open();
-  xc = xc_interface_open(0, 0, 0);
+  xc_interface_open(0, 0, 0);
   xc_hvm_set_mem_type(0, 0, HVMMEM_ram_ro, 0, 0);
   xc_gnttab_open(NULL, 0);
   xc_domain_add_to_physmap(0, 0, XENMAPSPACE_gmfn, 0, 0);
commit 69deef089db0d2eb94b7adc6d6ac78a1cf0d5511
Author: Peter Maydell <peter.maydell at linaro.org>
Date:   Thu Aug 2 18:30:26 2012 +0100

    configure: Don't run Xen compile checks in subshells
    
    The Xen compile checks are currently run inside subshells. This
    is unnecessary and has the effect that if do_cc() exits with
    an error message then this only causes the subshell to exit,
    not the whole of configure, which is confusing. Remove the
    subshells, changing:
      if ( cat ; compile_prog ) ; then ...
    to
      if cat && compile_prog ; then ...
    
    Signed-off-by: Peter Maydell <peter.maydell at linaro.org>
    Signed-off-by: Blue Swirl <blauwirbel at gmail.com>

diff --git a/configure b/configure
index 3ca13a6..f05b837 100755
--- a/configure
+++ b/configure
@@ -1396,8 +1396,8 @@ EOF
     xen=no
 
   # Xen unstable
-  elif (
-      cat > $TMPC <<EOF
+  elif
+      cat > $TMPC <<EOF &&
 #include <xenctrl.h>
 #include <xenstore.h>
 #include <stdint.h>
@@ -1417,12 +1417,12 @@ int main(void) {
 }
 EOF
       compile_prog "" "$xen_libs"
-    ) ; then
+    then
     xen_ctrl_version=420
     xen=yes
 
-  elif (
-      cat > $TMPC <<EOF
+  elif
+      cat > $TMPC <<EOF &&
 #include <xenctrl.h>
 #include <xs.h>
 #include <stdint.h>
@@ -1441,13 +1441,13 @@ int main(void) {
 }
 EOF
       compile_prog "" "$xen_libs"
-    ) ; then
+    then
     xen_ctrl_version=410
     xen=yes
 
   # Xen 4.0.0
-  elif (
-      cat > $TMPC <<EOF
+  elif
+      cat > $TMPC <<EOF &&
 #include <xenctrl.h>
 #include <xs.h>
 #include <stdint.h>
@@ -1468,13 +1468,13 @@ int main(void) {
 }
 EOF
       compile_prog "" "$xen_libs"
-    ) ; then
+    then
     xen_ctrl_version=400
     xen=yes
 
   # Xen 3.4.0
-  elif (
-      cat > $TMPC <<EOF
+  elif
+      cat > $TMPC <<EOF &&
 #include <xenctrl.h>
 #include <xs.h>
 int main(void) {
@@ -1490,13 +1490,13 @@ int main(void) {
 }
 EOF
       compile_prog "" "$xen_libs"
-    ) ; then
+    then
     xen_ctrl_version=340
     xen=yes
 
   # Xen 3.3.0
-  elif (
-      cat > $TMPC <<EOF
+  elif
+      cat > $TMPC <<EOF &&
 #include <xenctrl.h>
 #include <xs.h>
 int main(void) {
@@ -1508,7 +1508,7 @@ int main(void) {
 }
 EOF
       compile_prog "" "$xen_libs"
-    ) ; then
+    then
     xen_ctrl_version=330
     xen=yes
 
commit ee785fed5dd035d4b12142cacec6d3c344426dec
Author: Chegu Vinod <chegu_vinod at hp.com>
Date:   Mon Jul 16 21:31:30 2012 -0700

    Fixes related to processing of qemu's -numa option
    
    The -numa option to qemu is used to create [fake] numa nodes
    and expose them to the guest OS instance.
    
    There are a couple of issues with the -numa option:
    
    a) Max VCPU's that can be specified for a guest while using
       the qemu's -numa option is 64. Due to a typecasting issue
       when the number of VCPUs is > 32 the VCPUs don't show up
       under the specified [fake] numa nodes.
    
    b) KVM currently has support for 160VCPUs per guest. The
       qemu's -numa option has only support for upto 64VCPUs
       per guest.
    This patch addresses these two issues.
    
    Below are examples of (a) and (b)
    
    a) >32 VCPUs are specified with the -numa option:
    
    /usr/local/bin/qemu-system-x86_64 \
    -enable-kvm \
    71:01:01 \
    -net tap,ifname=tap0,script=no,downscript=no \
    -vnc :4
    
    ...
    Upstream qemu :
    --------------
    
    QEMU 1.1.50 monitor - type 'help' for more information
    (qemu) info numa
    6 nodes
    node 0 cpus: 0 1 2 3 4 5 6 7 8 9 32 33 34 35 36 37 38 39 40 41
    node 0 size: 131072 MB
    node 1 cpus: 10 11 12 13 14 15 16 17 18 19 42 43 44 45 46 47 48 49 50 51
    node 1 size: 131072 MB
    node 2 cpus: 20 21 22 23 24 25 26 27 28 29 52 53 54 55 56 57 58 59
    node 2 size: 131072 MB
    node 3 cpus: 30
    node 3 size: 131072 MB
    node 4 cpus:
    node 4 size: 131072 MB
    node 5 cpus: 31
    node 5 size: 131072 MB
    
    With the patch applied :
    -----------------------
    
    QEMU 1.1.50 monitor - type 'help' for more information
    (qemu) info numa
    6 nodes
    node 0 cpus: 0 1 2 3 4 5 6 7 8 9
    node 0 size: 131072 MB
    node 1 cpus: 10 11 12 13 14 15 16 17 18 19
    node 1 size: 131072 MB
    node 2 cpus: 20 21 22 23 24 25 26 27 28 29
    node 2 size: 131072 MB
    node 3 cpus: 30 31 32 33 34 35 36 37 38 39
    node 3 size: 131072 MB
    node 4 cpus: 40 41 42 43 44 45 46 47 48 49
    node 4 size: 131072 MB
    node 5 cpus: 50 51 52 53 54 55 56 57 58 59
    node 5 size: 131072 MB
    
    b) >64 VCPUs specified with -numa option:
    
    /usr/local/bin/qemu-system-x86_64 \
    -enable-kvm \
    -cpu Westmere,+rdtscp,+pdpe1gb,+dca,+pdcm,+xtpr,+tm2,+est,+smx,+vmx,+ds_cpl,+monitor,+dtes64,+pclmuldq,+pbe,+tm,+ht,+ss,+acpi,+d-vnc :4
    
    ...
    
    Upstream qemu :
    --------------
    
    only 63 CPUs in NUMA mode supported.
    only 64 CPUs in NUMA mode supported.
    QEMU 1.1.50 monitor - type 'help' for more information
    (qemu) info numa
    8 nodes
    node 0 cpus: 6 7 8 9 38 39 40 41 70 71 72 73
    node 0 size: 65536 MB
    node 1 cpus: 10 11 12 13 14 15 16 17 18 19 42 43 44 45 46 47 48 49 50 51 74 75 76 77 78 79
    node 1 size: 65536 MB
    node 2 cpus: 20 21 22 23 24 25 26 27 28 29 52 53 54 55 56 57 58 59 60 61
    node 2 size: 65536 MB
    node 3 cpus: 30 62
    node 3 size: 65536 MB
    node 4 cpus:
    node 4 size: 65536 MB
    node 5 cpus:
    node 5 size: 65536 MB
    node 6 cpus: 31 63
    node 6 size: 65536 MB
    node 7 cpus: 0 1 2 3 4 5 32 33 34 35 36 37 64 65 66 67 68 69
    node 7 size: 65536 MB
    
    With the patch applied :
    -----------------------
    
    QEMU 1.1.50 monitor - type 'help' for more information
    (qemu) info numa
    8 nodes
    node 0 cpus: 0 1 2 3 4 5 6 7 8 9
    node 0 size: 65536 MB
    node 1 cpus: 10 11 12 13 14 15 16 17 18 19
    node 1 size: 65536 MB
    node 2 cpus: 20 21 22 23 24 25 26 27 28 29
    node 2 size: 65536 MB
    node 3 cpus: 30 31 32 33 34 35 36 37 38 39
    node 3 size: 65536 MB
    node 4 cpus: 40 41 42 43 44 45 46 47 48 49
    node 4 size: 65536 MB
    node 5 cpus: 50 51 52 53 54 55 56 57 58 59
    node 5 size: 65536 MB
    node 6 cpus: 60 61 62 63 64 65 66 67 68 69
    node 6 size: 65536 MB
    node 7 cpus: 70 71 72 73 74 75 76 77 78 79
    
    Signed-off-by: Chegu Vinod <chegu_vinod at hp.com>, Jim Hull <jim.hull at hp.com>, Craig Hada <craig.hada at hp.com>
    Tested-by: Eduardo Habkost <ehabkost at redhat.com>
    Reviewed-by: Eduardo Habkost <ehabkost at redhat.com>
    Signed-off-by: Blue Swirl <blauwirbel at gmail.com>

diff --git a/cpus.c b/cpus.c
index b61f60e..3de2e27 100644
--- a/cpus.c
+++ b/cpus.c
@@ -36,6 +36,7 @@
 #include "cpus.h"
 #include "qtest.h"
 #include "main-loop.h"
+#include "bitmap.h"
 
 #ifndef _WIN32
 #include "compatfd.h"
@@ -1159,7 +1160,7 @@ void set_numa_modes(void)
 
     for (env = first_cpu; env != NULL; env = env->next_cpu) {
         for (i = 0; i < nb_numa_nodes; i++) {
-            if (node_cpumask[i] & (1 << env->cpu_index)) {
+            if (test_bit(env->cpu_index, node_cpumask[i])) {
                 env->numa_node = i;
             }
         }
diff --git a/hw/pc.c b/hw/pc.c
index bd193f3..81c391c 100644
--- a/hw/pc.c
+++ b/hw/pc.c
@@ -49,6 +49,7 @@
 #include "memory.h"
 #include "exec-memory.h"
 #include "arch_init.h"
+#include "bitmap.h"
 
 /* output Bochs bios info messages */
 //#define DEBUG_BIOS
@@ -625,7 +626,7 @@ static void *bochs_bios_init(void)
     numa_fw_cfg[0] = cpu_to_le64(nb_numa_nodes);
     for (i = 0; i < max_cpus; i++) {
         for (j = 0; j < nb_numa_nodes; j++) {
-            if (node_cpumask[j] & (1 << i)) {
+            if (test_bit(i, node_cpumask[j])) {
                 numa_fw_cfg[i + 1] = cpu_to_le64(j);
                 break;
             }
diff --git a/sysemu.h b/sysemu.h
index 6540c79..4669348 100644
--- a/sysemu.h
+++ b/sysemu.h
@@ -134,9 +134,10 @@ extern uint8_t qemu_extra_params_fw[2];
 extern QEMUClock *rtc_clock;
 
 #define MAX_NODES 64
+#define MAX_CPUMASK_BITS 255
 extern int nb_numa_nodes;
 extern uint64_t node_mem[MAX_NODES];
-extern uint64_t node_cpumask[MAX_NODES];
+extern unsigned long *node_cpumask[MAX_NODES];
 
 #define MAX_OPTION_ROMS 16
 typedef struct QEMUOptionRom {
diff --git a/vl.c b/vl.c
index 6d2ce45..e71cb30 100644
--- a/vl.c
+++ b/vl.c
@@ -28,6 +28,7 @@
 #include <errno.h>
 #include <sys/time.h>
 #include <zlib.h>
+#include "bitmap.h"
 
 /* Needed early for CONFIG_BSD etc. */
 #include "config-host.h"
@@ -241,7 +242,7 @@ QTAILQ_HEAD(, FWBootEntry) fw_boot_order = QTAILQ_HEAD_INITIALIZER(fw_boot_order
 
 int nb_numa_nodes;
 uint64_t node_mem[MAX_NODES];
-uint64_t node_cpumask[MAX_NODES];
+unsigned long *node_cpumask[MAX_NODES];
 
 uint8_t qemu_uuid[16];
 
@@ -952,6 +953,8 @@ static void numa_add(const char *optarg)
     unsigned long long value, endvalue;
     int nodenr;
 
+    value = endvalue = 0ULL;
+
     optarg = get_opt_name(option, 128, optarg, ',') + 1;
     if (!strcmp(option, "node")) {
         if (get_param_value(option, 128, "nodeid", optarg) == 0) {
@@ -971,27 +974,22 @@ static void numa_add(const char *optarg)
             }
             node_mem[nodenr] = sval;
         }
-        if (get_param_value(option, 128, "cpus", optarg) == 0) {
-            node_cpumask[nodenr] = 0;
-        } else {
+        if (get_param_value(option, 128, "cpus", optarg) != 0) {
             value = strtoull(option, &endptr, 10);
-            if (value >= 64) {
-                value = 63;
-                fprintf(stderr, "only 64 CPUs in NUMA mode supported.\n");
+            if (*endptr == '-') {
+                endvalue = strtoull(endptr+1, &endptr, 10);
             } else {
-                if (*endptr == '-') {
-                    endvalue = strtoull(endptr+1, &endptr, 10);
-                    if (endvalue >= 63) {
-                        endvalue = 62;
-                        fprintf(stderr,
-                            "only 63 CPUs in NUMA mode supported.\n");
-                    }
-                    value = (2ULL << endvalue) - (1ULL << value);
-                } else {
-                    value = 1ULL << value;
-                }
+                endvalue = value;
+            }
+
+            if (!(endvalue < MAX_CPUMASK_BITS)) {
+                endvalue = MAX_CPUMASK_BITS - 1;
+                fprintf(stderr,
+                    "A max of %d CPUs are supported in a guest\n",
+                     MAX_CPUMASK_BITS);
             }
-            node_cpumask[nodenr] = value;
+
+            bitmap_set(node_cpumask[nodenr], value, endvalue-value+1);
         }
         nb_numa_nodes++;
     }
@@ -2331,7 +2329,7 @@ int main(int argc, char **argv, char **envp)
 
     for (i = 0; i < MAX_NODES; i++) {
         node_mem[i] = 0;
-        node_cpumask[i] = 0;
+        node_cpumask[i] = bitmap_new(MAX_CPUMASK_BITS);
     }
 
     nb_numa_nodes = 0;
@@ -3468,8 +3466,9 @@ int main(int argc, char **argv, char **envp)
         }
 
         for (i = 0; i < nb_numa_nodes; i++) {
-            if (node_cpumask[i] != 0)
+            if (!bitmap_empty(node_cpumask[i], MAX_CPUMASK_BITS)) {
                 break;
+            }
         }
         /* assigning the VCPUs round-robin is easier to implement, guest OSes
          * must cope with this anyway, because there are BIOSes out there in
@@ -3477,7 +3476,7 @@ int main(int argc, char **argv, char **envp)
          */
         if (i == nb_numa_nodes) {
             for (i = 0; i < max_cpus; i++) {
-                node_cpumask[i % nb_numa_nodes] |= 1 << i;
+                set_bit(i, node_cpumask[i % nb_numa_nodes]);
             }
         }
     }
commit 161abfb5f929184a68baa16701606015f5683722
Author: Dunrong Huang <riegamaths at gmail.com>
Date:   Sat Aug 4 19:29:55 2012 +0800

    build: Fix build breakage detected by buildbot
    
    More details:
    http://buildbot.b1-systems.de/qemu/builders/xen_unstable/builds/83/steps/compile/logs/stdio
    
    VLANState has been removed since commit a005d07, so "vlan id" should be
    fetched using net_hub_id_for_client().
    
    Signed-off-by: Dunrong Huang <riegamaths at gmail.com>
    Signed-off-by: Anthony Liguori <aliguori at us.ibm.com>

diff --git a/hw/xen_backend.h b/hw/xen_backend.h
index 3305630..fea86dd 100644
--- a/hw/xen_backend.h
+++ b/hw/xen_backend.h
@@ -4,6 +4,7 @@
 #include "xen_common.h"
 #include "sysemu.h"
 #include "net.h"
+#include "net/hub.h"
 
 /* ------------------------------------------------------------- */
 
diff --git a/hw/xen_devconfig.c b/hw/xen_devconfig.c
index 0928613..d83e8d0 100644
--- a/hw/xen_devconfig.c
+++ b/hw/xen_devconfig.c
@@ -123,19 +123,21 @@ int xen_config_dev_nic(NICInfo *nic)
 {
     char fe[256], be[256];
     char mac[20];
+    int vlan_id = -1;
 
+    net_hub_id_for_client(nic->netdev, &vlan_id);
     snprintf(mac, sizeof(mac), "%02x:%02x:%02x:%02x:%02x:%02x",
              nic->macaddr.a[0], nic->macaddr.a[1], nic->macaddr.a[2],
              nic->macaddr.a[3], nic->macaddr.a[4], nic->macaddr.a[5]);
-    xen_be_printf(NULL, 1, "config nic %d: mac=\"%s\"\n", nic->vlan->id, mac);
-    xen_config_dev_dirs("vif", "qnic", nic->vlan->id, fe, be, sizeof(fe));
+    xen_be_printf(NULL, 1, "config nic %d: mac=\"%s\"\n", vlan_id, mac);
+    xen_config_dev_dirs("vif", "qnic", vlan_id, fe, be, sizeof(fe));
 
     /* frontend */
-    xenstore_write_int(fe, "handle",     nic->vlan->id);
+    xenstore_write_int(fe, "handle",     vlan_id);
     xenstore_write_str(fe, "mac",        mac);
 
     /* backend */
-    xenstore_write_int(be, "handle",     nic->vlan->id);
+    xenstore_write_int(be, "handle",     vlan_id);
     xenstore_write_str(be, "mac",        mac);
 
     /* common stuff */
commit 70678b82274309e9df98b8ce359118f36697cadb
Author: Anthony Liguori <aliguori at us.ibm.com>
Date:   Fri Aug 3 18:28:37 2012 -0500

    fips: fix build on !Linux
    
    Commit 0f66998 makes -enable-fips conditional on Linux hosts but then uses it
    unconditionally in vl.c.
    
    Fix this by moving the fips handling to os-posix.c and adding a condition.
    
    Cc: Paul Moore <pmoore at redhat.com>
    Signed-off-by: Anthony Liguori <aliguori at us.ibm.com>

diff --git a/os-posix.c b/os-posix.c
index daf3d6f..79fa228 100644
--- a/os-posix.c
+++ b/os-posix.c
@@ -188,6 +188,11 @@ void os_parse_cmd_args(int index, const char *optarg)
     case QEMU_OPTION_daemonize:
         daemonize = 1;
         break;
+#if defined(CONFIG_LINUX)
+    case QEMU_OPTION_enablefips:
+        fips_set_state(true);
+        break;
+#endif
     }
     return;
 }
diff --git a/vl.c b/vl.c
index 8cda85f..6d2ce45 100644
--- a/vl.c
+++ b/vl.c
@@ -3199,9 +3199,6 @@ int main(int argc, char **argv, char **envp)
             case QEMU_OPTION_qtest_log:
                 qtest_log = optarg;
                 break;
-            case QEMU_OPTION_enablefips:
-                fips_set_state(true);
-                break;
             default:
                 os_parse_cmd_args(popt->index, optarg);
             }
commit 648cd33e73cbbbf19e278101e6a9e071cb154c05
Author: Anders Waldenborg <anders at 0x63.nu>
Date:   Fri Jul 13 22:54:17 2012 +0200

    slirp: Handle whole 127.0.0.0/8 network as local addresses.
    
    Changes so translation of remote address to the host's ip address in
    the virtual network happens for all addresses in the 127.0.0.0/8
    network, not just 127.0.0.1.
    
    This fixes so that hostfwd bound to addresses such as 127.0.0.2 works.
    
    Signed-off-by: Anders Waldenborg <anders at 0x63.nu>
    Signed-off-by: Jan Kiszka <jan.kiszka at siemens.com>

diff --git a/slirp/main.h b/slirp/main.h
index 028df4b..bf601e2 100644
--- a/slirp/main.h
+++ b/slirp/main.h
@@ -31,6 +31,7 @@ extern char *exec_shell;
 extern u_int curtime;
 extern fd_set *global_readfds, *global_writefds, *global_xfds;
 extern struct in_addr loopback_addr;
+extern in_addr_t loopback_mask;
 extern char *username;
 extern char *socket_path;
 extern int towrite_max;
diff --git a/slirp/slirp.c b/slirp/slirp.c
index 90473eb..9787104 100644
--- a/slirp/slirp.c
+++ b/slirp/slirp.c
@@ -29,6 +29,8 @@
 
 /* host loopback address */
 struct in_addr loopback_addr;
+/* host loopback network mask */
+in_addr_t loopback_mask;
 
 /* emulated hosts use the MAC addr 52:55:IP:IP:IP:IP */
 static const uint8_t special_ethaddr[ETH_ALEN] = {
@@ -191,6 +193,7 @@ static void slirp_init_once(void)
 #endif
 
     loopback_addr.s_addr = htonl(INADDR_LOOPBACK);
+    loopback_mask = htonl(IN_CLASSA_NET);
 }
 
 static void slirp_state_save(QEMUFile *f, void *opaque);
diff --git a/slirp/tcp_subr.c b/slirp/tcp_subr.c
index 0a545c4..025b374 100644
--- a/slirp/tcp_subr.c
+++ b/slirp/tcp_subr.c
@@ -435,8 +435,11 @@ tcp_connect(struct socket *inso)
 	so->so_fport = addr.sin_port;
 	so->so_faddr = addr.sin_addr;
 	/* Translate connections from localhost to the real hostname */
-	if (so->so_faddr.s_addr == 0 || so->so_faddr.s_addr == loopback_addr.s_addr)
-	   so->so_faddr = slirp->vhost_addr;
+        if (so->so_faddr.s_addr == 0 ||
+            (so->so_faddr.s_addr & loopback_mask) ==
+            (loopback_addr.s_addr & loopback_mask)) {
+            so->so_faddr = slirp->vhost_addr;
+        }
 
 	/* Close the accept() socket, set right state */
 	if (inso->so_state & SS_FACCEPTONCE) {
commit b34bd5e5c8f356ec206e5a306ee3a9b6f42c4315
Merge: 0f66998... e4b6526...
Author: Anthony Liguori <aliguori at us.ibm.com>
Date:   Fri Aug 3 15:46:17 2012 -0500

    Merge remote-tracking branch 'bonzini/scsi-next' into staging
    
    * bonzini/scsi-next:
      scsi: add support for ATA_PASSTHROUGH_xx scsi command
      esp: add missing const on TypeInfo structures
      esp: enable for all PCI machines
      Revert "megasas: disable due to build breakage"
      megasas: static SAS addresses
      scsi-disk: fix compilation with DEBUG_SCSI
      megasas: Update function megasys_scsi_uninit
      SCSI: STARTSTOPUNIT only eject/load media if powercondition is 0
      SCSI: Update the sense code for PREVENT REMOVAL errors

commit e4b65262a3b6633fe107e4ce7660b41a71a16e5f
Author: Cong Meng <mc at linux.vnet.ibm.com>
Date:   Fri Aug 3 12:02:19 2012 +0800

    scsi: add support for ATA_PASSTHROUGH_xx scsi command
    
    Correct the command names of opcode 0x85 and 0xa1, and calculate
    their xfer size from CDB.
    
    Signed-off-by: Cong Meng <mc at linux.vnet.ibm.com>
    Signed-off-by: Paolo Bonzini <pbonzini at redhat.com>

diff --git a/hw/scsi-bus.c b/hw/scsi-bus.c
index 68049f6..6120cc8 100644
--- a/hw/scsi-bus.c
+++ b/hw/scsi-bus.c
@@ -733,6 +733,72 @@ static int scsi_get_performance_length(int num_desc, int type, int data_type)
     }
 }
 
+static int ata_passthrough_xfer_unit(SCSIDevice *dev, uint8_t *buf)
+{
+    int byte_block = (buf[2] >> 2) & 0x1;
+    int type = (buf[2] >> 4) & 0x1;
+    int xfer_unit;
+
+    if (byte_block) {
+        if (type) {
+            xfer_unit = dev->blocksize;
+        } else {
+            xfer_unit = 512;
+        }
+    } else {
+        xfer_unit = 1;
+    }
+
+    return xfer_unit;
+}
+
+static int ata_passthrough_12_xfer_size(SCSIDevice *dev, uint8_t *buf)
+{
+    int length = buf[2] & 0x3;
+    int xfer;
+    int unit = ata_passthrough_xfer_unit(dev, buf);
+
+    switch (length) {
+    case 0:
+    case 3: /* USB-specific.  */
+        xfer = 0;
+        break;
+    case 1:
+        xfer = buf[3];
+        break;
+    case 2:
+        xfer = buf[4];
+        break;
+    }
+
+    return xfer * unit;
+}
+
+static int ata_passthrough_16_xfer_size(SCSIDevice *dev, uint8_t *buf)
+{
+    int extend = buf[1] & 0x1;
+    int length = buf[2] & 0x3;
+    int xfer;
+    int unit = ata_passthrough_xfer_unit(dev, buf);
+
+    switch (length) {
+    case 0:
+    case 3: /* USB-specific.  */
+        xfer = 0;
+        break;
+    case 1:
+        xfer = buf[4];
+        xfer |= (extend ? buf[3] << 8 : 0);
+        break;
+    case 2:
+        xfer = buf[6];
+        xfer |= (extend ? buf[5] << 8 : 0);
+        break;
+    }
+
+    return xfer * unit;
+}
+
 static int scsi_req_length(SCSICommand *cmd, SCSIDevice *dev, uint8_t *buf)
 {
     switch (buf[0] >> 5) {
@@ -867,6 +933,17 @@ static int scsi_req_length(SCSICommand *cmd, SCSIDevice *dev, uint8_t *buf)
             cmd->xfer = buf[9] | (buf[8] << 8);
         }
         break;
+    case ATA_PASSTHROUGH_12:
+        if (dev->type == TYPE_ROM) {
+            /* BLANK command of MMC */
+            cmd->xfer = 0;
+        } else {
+            cmd->xfer = ata_passthrough_12_xfer_size(dev, buf);
+        }
+        break;
+    case ATA_PASSTHROUGH_16:
+        cmd->xfer = ata_passthrough_16_xfer_size(dev, buf);
+        break;
     }
     return 0;
 }
@@ -996,9 +1073,14 @@ static void scsi_cmd_xfer_mode(SCSICommand *cmd)
     case SEND_DVD_STRUCTURE:
     case PERSISTENT_RESERVE_OUT:
     case MAINTENANCE_OUT:
-    case ATA_PASSTHROUGH:
         cmd->mode = SCSI_XFER_TO_DEV;
         break;
+    case ATA_PASSTHROUGH_12:
+    case ATA_PASSTHROUGH_16:
+        /* T_DIR */
+        cmd->mode = (cmd->buf[2] & 0x8) ?
+                   SCSI_XFER_FROM_DEV : SCSI_XFER_TO_DEV;
+        break;
     default:
         cmd->mode = SCSI_XFER_FROM_DEV;
         break;
@@ -1335,7 +1417,7 @@ static const char *scsi_command_name(uint8_t cmd)
         [ PERSISTENT_RESERVE_OUT   ] = "PERSISTENT_RESERVE_OUT",
         [ WRITE_FILEMARKS_16       ] = "WRITE_FILEMARKS_16",
         [ EXTENDED_COPY            ] = "EXTENDED_COPY",
-        [ ATA_PASSTHROUGH          ] = "ATA_PASSTHROUGH",
+        [ ATA_PASSTHROUGH_16       ] = "ATA_PASSTHROUGH_16",
         [ ACCESS_CONTROL_IN        ] = "ACCESS_CONTROL_IN",
         [ ACCESS_CONTROL_OUT       ] = "ACCESS_CONTROL_OUT",
         [ READ_16                  ] = "READ_16",
@@ -1352,7 +1434,7 @@ static const char *scsi_command_name(uint8_t cmd)
         [ SERVICE_ACTION_IN_16     ] = "SERVICE_ACTION_IN_16",
         [ WRITE_LONG_16            ] = "WRITE_LONG_16",
         [ REPORT_LUNS              ] = "REPORT_LUNS",
-        [ BLANK                    ] = "BLANK",
+        [ ATA_PASSTHROUGH_12       ] = "BLANK/ATA_PASSTHROUGH_12",
         [ MOVE_MEDIUM              ] = "MOVE_MEDIUM",
         [ EXCHANGE_MEDIUM          ] = "EXCHANGE MEDIUM",
         [ LOAD_UNLOAD              ] = "LOAD_UNLOAD",
diff --git a/hw/scsi-defs.h b/hw/scsi-defs.h
index 8a73f74..d7a4019 100644
--- a/hw/scsi-defs.h
+++ b/hw/scsi-defs.h
@@ -100,7 +100,7 @@
 #define READ_REVERSE_16       0x81
 #define ALLOW_OVERWRITE       0x82
 #define EXTENDED_COPY         0x83
-#define ATA_PASSTHROUGH       0x85
+#define ATA_PASSTHROUGH_16    0x85
 #define ACCESS_CONTROL_IN     0x86
 #define ACCESS_CONTROL_OUT    0x87
 #define READ_16               0x88
@@ -117,7 +117,7 @@
 #define SERVICE_ACTION_IN_16  0x9e
 #define WRITE_LONG_16         0x9f
 #define REPORT_LUNS           0xa0
-#define BLANK                 0xa1
+#define ATA_PASSTHROUGH_12    0xa1
 #define MAINTENANCE_IN        0xa3
 #define MAINTENANCE_OUT       0xa4
 #define MOVE_MEDIUM           0xa5
commit 0f66998ff6d5d2133b9b08471a44e13b11119e50
Author: Paul Moore <pmoore at redhat.com>
Date:   Fri Aug 3 14:39:21 2012 -0400

    vnc: disable VNC password authentication (security type 2) when in FIPS mode
    
    FIPS 140-2 requires disabling certain ciphers, including DES, which is used
    by VNC to obscure passwords when they are sent over the network.  The
    solution for FIPS users is to disable the use of VNC password auth when the
    host system is operating in FIPS compliance mode and the user has specified
    '-enable-fips' on the QEMU command line.
    
    This patch causes QEMU to emit a message to stderr when the host system is
    running in FIPS mode and a VNC password was specified on the commend line.
    If the system is not running in FIPS mode, or is running in FIPS mode but
    VNC password authentication was not requested, QEMU operates normally.
    
    Signed-off-by: Paul Moore <pmoore at redhat.com>
    Signed-off-by: Anthony Liguori <aliguori at us.ibm.com>

diff --git a/osdep.c b/osdep.c
index 03817f0..c07faf5 100644
--- a/osdep.c
+++ b/osdep.c
@@ -24,6 +24,7 @@
 #include <stdlib.h>
 #include <stdio.h>
 #include <stdarg.h>
+#include <stdbool.h>
 #include <string.h>
 #include <errno.h>
 #include <unistd.h>
@@ -48,6 +49,8 @@ extern int madvise(caddr_t, size_t, int);
 #include "trace.h"
 #include "qemu_socket.h"
 
+static bool fips_enabled = false;
+
 static const char *qemu_version = QEMU_VERSION;
 
 int socket_set_cork(int fd, int v)
@@ -253,3 +256,29 @@ const char *qemu_get_version(void)
 {
     return qemu_version;
 }
+
+void fips_set_state(bool requested)
+{
+#ifdef __linux__
+    if (requested) {
+        FILE *fds = fopen("/proc/sys/crypto/fips_enabled", "r");
+        if (fds != NULL) {
+            fips_enabled = (fgetc(fds) == '1');
+            fclose(fds);
+        }
+    }
+#else
+    fips_enabled = false;
+#endif /* __linux__ */
+
+#ifdef _FIPS_DEBUG
+    fprintf(stderr, "FIPS mode %s (requested %s)\n",
+	    (fips_enabled ? "enabled" : "disabled"),
+	    (requested ? "enabled" : "disabled"));
+#endif
+}
+
+bool fips_get_state(void)
+{
+    return fips_enabled;
+}
diff --git a/osdep.h b/osdep.h
index 1e15a4b..d4b887d 100644
--- a/osdep.h
+++ b/osdep.h
@@ -3,6 +3,7 @@
 
 #include <stdarg.h>
 #include <stddef.h>
+#include <stdbool.h>
 #ifdef __OpenBSD__
 #include <sys/types.h>
 #include <sys/signal.h>
@@ -154,4 +155,7 @@ void qemu_set_cloexec(int fd);
 void qemu_set_version(const char *);
 const char *qemu_get_version(void);
 
+void fips_set_state(bool requested);
+bool fips_get_state(void);
+
 #endif
diff --git a/qemu-doc.texi b/qemu-doc.texi
index a41448a..f32e9e2 100644
--- a/qemu-doc.texi
+++ b/qemu-doc.texi
@@ -1124,9 +1124,11 @@ the protocol limits passwords to 8 characters it should not be considered
 to provide high security. The password can be fairly easily brute-forced by
 a client making repeat connections. For this reason, a VNC server using password
 authentication should be restricted to only listen on the loopback interface
-or UNIX domain sockets. Password authentication is requested with the @code{password}
-option, and then once QEMU is running the password is set with the monitor. Until
-the monitor is used to set the password all clients will be rejected.
+or UNIX domain sockets. Password authentication is not supported when operating
+in FIPS 140-2 compliance mode as it requires the use of the DES cipher. Password
+authentication is requested with the @code{password} option, and then once QEMU
+is running the password is set with the monitor. Until the monitor is used to
+set the password all clients will be rejected.
 
 @example
 qemu-system-i386 [...OPTIONS...] -vnc :1,password -monitor stdio
diff --git a/qemu-options.hx b/qemu-options.hx
index 9277414..5e7d0dc 100644
--- a/qemu-options.hx
+++ b/qemu-options.hx
@@ -2787,6 +2787,17 @@ DEF("qtest-log", HAS_ARG, QEMU_OPTION_qtest_log,
     "-qtest-log LOG  specify tracing options\n",
     QEMU_ARCH_ALL)
 
+#ifdef __linux__
+DEF("enable-fips", 0, QEMU_OPTION_enablefips,
+    "-enable-fips    enable FIPS 140-2 compliance\n",
+    QEMU_ARCH_ALL)
+#endif
+STEXI
+ at item -enable-fips
+ at findex -enable-fips
+Enable FIPS 140-2 compliance mode.
+ETEXI
+
 HXCOMM This is the last statement. Insert new options before this line!
 STEXI
 @end table
diff --git a/ui/vnc.c b/ui/vnc.c
index cfc61a7..312ad7f 100644
--- a/ui/vnc.c
+++ b/ui/vnc.c
@@ -32,6 +32,7 @@
 #include "acl.h"
 #include "qemu-objects.h"
 #include "qmp-commands.h"
+#include "osdep.h"
 
 #define VNC_REFRESH_INTERVAL_BASE 30
 #define VNC_REFRESH_INTERVAL_INC  50
@@ -2875,6 +2876,15 @@ int vnc_display_open(DisplayState *ds, const char *display)
     while ((options = strchr(options, ','))) {
         options++;
         if (strncmp(options, "password", 8) == 0) {
+            if (fips_get_state()) {
+                fprintf(stderr,
+                        "VNC password auth disabled due to FIPS mode, "
+                        "consider using the VeNCrypt or SASL authentication "
+                        "methods as an alternative\n");
+                g_free(vs->display);
+                vs->display = NULL;
+                return -1;
+            }
             password = 1; /* Require password auth */
         } else if (strncmp(options, "reverse", 7) == 0) {
             reverse = 1;
diff --git a/vl.c b/vl.c
index 1fd1114..8cda85f 100644
--- a/vl.c
+++ b/vl.c
@@ -159,6 +159,7 @@ int main(int argc, char **argv)
 #include "qemu-queue.h"
 #include "cpus.h"
 #include "arch_init.h"
+#include "osdep.h"
 
 #include "ui/qemu-spice.h"
 
@@ -3198,6 +3199,9 @@ int main(int argc, char **argv, char **envp)
             case QEMU_OPTION_qtest_log:
                 qtest_log = optarg;
                 break;
+            case QEMU_OPTION_enablefips:
+                fips_set_state(true);
+                break;
             default:
                 os_parse_cmd_args(popt->index, optarg);
             }
commit 2ad728bd4bf26d8144190ca87d5d36d5f33cfae9
Merge: 9c936c8... 75115d9...
Author: Anthony Liguori <aliguori at us.ibm.com>
Date:   Fri Aug 3 14:28:26 2012 -0500

    Merge remote-tracking branch 'qmp/queue/qmp' into staging
    
    * qmp/queue/qmp:
      hmp: show the backing file depth
      block: Use bdrv_get_backing_file_depth()
      block: create bdrv_get_backing_file_depth()
      qapi: qapi.py: allow the "'" character to be escaped

commit 9c936c8667f15cf729ee602ae2a800658580fe47
Merge: ca9ba23... 216fc9a...
Author: Anthony Liguori <aliguori at us.ibm.com>
Date:   Fri Aug 3 13:56:39 2012 -0500

    Merge remote-tracking branch 'afaerber-or/qom-cpu-4' into staging
    
    * afaerber-or/qom-cpu-4:
      cpu: Move thread_kicked to CPUState
      cpu: Move thread field into CPUState
      cpu: Move CPU_COMMON_THREAD into CPUState
      qemu-thread: Let qemu_thread_is_self() return bool

commit ca9ba23ad3a151a6e73c9a786d141727b0b30b5b
Merge: f57fb88... 47fb65c...
Author: Anthony Liguori <aliguori at us.ibm.com>
Date:   Fri Aug 3 13:54:35 2012 -0500

    Merge remote-tracking branch 'sstabellini/xen-fixes-20120801' into staging
    
    * sstabellini/xen-fixes-20120801:
      fix Xen compilation
      configure: Fix xen probe with Xen 4.2 and later

commit f57fb88436464cf72a2a0c7372e2dc0af1870b5f
Merge: 3d0b7b5... 011de2b...
Author: Anthony Liguori <aliguori at us.ibm.com>
Date:   Fri Aug 3 13:54:05 2012 -0500

    Merge remote-tracking branch 'stefanha/net' into staging
    
    * stefanha/net:
      net: add the support for -netdev socket, listen
      net: fix the coding style
      hub: add the support for hub own flow control
      net: determine if packets can be sent before net queue deliver packets
      net: cleanup deliver/deliver_iov func pointers
      net: Make "info network" output more readable info
      net: Rename qemu_del_vlan_client() to qemu_del_net_client()
      net: Rename vc local variables to nc
      net: Rename VLANClientState to NetClientState
      net: Rename non_vlan_clients to net_clients
      net: Remove VLANState
      net: Remove vlan code from net.c
      net: Convert qdev_prop_vlan to peer with hub
      net: Drop vlan argument to qemu_new_net_client()
      hub: Check that hubs are configured correctly
      net: Look up 'vlan' net clients using hubs
      net: Use hubs for the vlan feature
      net: Add a hub net client
      net: Add interface to bridge when SIOCBRADDIF isn't available

commit 3d0b7b5203fb07847bf13aee567a9c9d7483876b
Merge: aeb01d5... c308efe...
Author: Anthony Liguori <aliguori at us.ibm.com>
Date:   Fri Aug 3 13:51:19 2012 -0500

    Merge remote-tracking branch 'stefanha/trivial-patches' into staging
    
    * stefanha/trivial-patches:
      exec.c: Remove out of date comment
      exec.c: Use subpages for large unaligned mappings
      exec.c: Fix off-by-one error in register_subpage
      socket: clean up redundant assignment
      qom: Clean libuser object and dependency files
      usb: Clean common object and dependency files

commit aeb01d5f2c9a89c557adb0fb40bca15238f93124
Merge: c8057f9... 4cdc078...
Author: Anthony Liguori <aliguori at us.ibm.com>
Date:   Fri Aug 3 13:50:41 2012 -0500

    Merge remote-tracking branch 'aneesh/for-upstream' into staging
    
    * aneesh/for-upstream:
      hw/9pfs: Fix assert when disabling migration
      configure: Fix build with capabilities

commit c308efe63a875eb0d839f7490e69e58e4595466c
Author: Peter Maydell <peter.maydell at linaro.org>
Date:   Wed Aug 1 14:35:47 2012 +0100

    exec.c: Remove out of date comment
    
    Remove an out of date comment: this comment used to be attached to
    cpu_register_physical_memory_log(), before commit 0f0cb164 accidentally
    inserted a couple of other functions between the comment and its function.
    It is in any case obsolete since (a) the function arguments it refers
    to have been replaced with a single MemoryRegionSection* argument and
    (b) the inability to handle regions whose offset_within_address_space
    and offset_within_region aren't equally aligned was fixed as part of
    the rewrite of this code.
    
    Signed-off-by: Peter Maydell <peter.maydell at linaro.org>
    Signed-off-by: Stefan Hajnoczi <stefanha at linux.vnet.ibm.com>

diff --git a/exec.c b/exec.c
index e6ac3e7..a42a0b5 100644
--- a/exec.c
+++ b/exec.c
@@ -2240,14 +2240,6 @@ static void phys_sections_clear(void)
     phys_sections_nb = 0;
 }
 
-/* register physical memory.
-   For RAM, 'size' must be a multiple of the target page size.
-   If (phys_offset & ~TARGET_PAGE_MASK) != 0, then it is an
-   io memory page.  The address used when calling the IO function is
-   the offset from the start of the region, plus region_offset.  Both
-   start_addr and region_offset are rounded down to a page boundary
-   before calculating this offset.  This should not be a problem unless
-   the low bits of start_addr and region_offset differ.  */
 static void register_subpage(MemoryRegionSection *section)
 {
     subpage_t *subpage;
commit 69b67646bc7ae7f3d28b278e6ae4435a767450ec
Author: Tyler Hall <tylerwhall at gmail.com>
Date:   Wed Jul 25 18:45:04 2012 -0400

    exec.c: Use subpages for large unaligned mappings
    
    Registering a multi-page memory region that is non-page-aligned results
    in a subpage from the start to the page boundary, some number of full
    pages, and possibly another subpage from the last page boundary to the
    end. The full pages will have a value for offset_within_region that is
    not a multiple of TARGET_PAGE_SIZE. Accesses through softmmu are unable
    to handle this and will segfault.
    
    Handling full pages through subpages is not optimal, but only
    non-page-aligned mappings take the penalty.
    
    Signed-off-by: Tyler Hall <tylerwhall at gmail.com>
    Reviewed-by: Peter Maydell <peter.maydell at linaro.org>
    Reviewed-by: Avi Kivity <avi at redhat.com>
    Signed-off-by: Stefan Hajnoczi <stefanha at linux.vnet.ibm.com>

diff --git a/exec.c b/exec.c
index 27b100c..e6ac3e7 100644
--- a/exec.c
+++ b/exec.c
@@ -2305,10 +2305,15 @@ void cpu_register_physical_memory_log(MemoryRegionSection *section,
         remain.offset_within_address_space += now.size;
         remain.offset_within_region += now.size;
     }
-    now = remain;
-    now.size &= TARGET_PAGE_MASK;
-    if (now.size) {
-        register_multipage(&now);
+    while (remain.size >= TARGET_PAGE_SIZE) {
+        now = remain;
+        if (remain.offset_within_region & ~TARGET_PAGE_MASK) {
+            now.size = TARGET_PAGE_SIZE;
+            register_subpage(&now);
+        } else {
+            now.size &= TARGET_PAGE_MASK;
+            register_multipage(&now);
+        }
         remain.size -= now.size;
         remain.offset_within_address_space += now.size;
         remain.offset_within_region += now.size;
commit adb2a9b5d4d5170f0b58b9f92f816048f6b8932b
Author: Tyler Hall <tylerwhall at gmail.com>
Date:   Wed Jul 25 18:45:03 2012 -0400

    exec.c: Fix off-by-one error in register_subpage
    
    subpage_register() expects "end" to be the last byte in the mapping.
    Registering a non-page-aligned memory region that extends up to or
    beyond a page boundary causes subpage_register() to silently fail
    through the (end >= PAGE_SIZE) check.
    
    This bug does not cause noticeable problems for mappings that do not
    extend to a page boundary, though they do register an extra byte.
    
    Signed-off-by: Tyler Hall <tylerwhall at gmail.com>
    Reviewed-by: Peter Maydell <peter.maydell at linaro.org>
    Reviewed-by: Avi Kivity <avi at redhat.com>
    Signed-off-by: Stefan Hajnoczi <stefanha at linux.vnet.ibm.com>

diff --git a/exec.c b/exec.c
index feb4795..27b100c 100644
--- a/exec.c
+++ b/exec.c
@@ -2271,7 +2271,7 @@ static void register_subpage(MemoryRegionSection *section)
         subpage = container_of(existing->mr, subpage_t, iomem);
     }
     start = section->offset_within_address_space & ~TARGET_PAGE_MASK;
-    end = start + section->size;
+    end = start + section->size - 1;
     subpage_register(subpage, start, end, phys_section_add(section));
 }
 
commit 8715fc1e4caee09bde28f8e6844ad1a3bfe52f0e
Author: Amos Kong <akong at redhat.com>
Date:   Fri Aug 3 11:06:22 2012 +0800

    socket: clean up redundant assignment
    
    Signed-off-by: Amos Kong <akong at redhat.com>
    Signed-off-by: Stefan Hajnoczi <stefanha at linux.vnet.ibm.com>

diff --git a/qemu-sockets.c b/qemu-sockets.c
index 668fa93..beb2bb6 100644
--- a/qemu-sockets.c
+++ b/qemu-sockets.c
@@ -284,7 +284,6 @@ int inet_connect_opts(QemuOpts *opts, Error **errp)
                         inet_strfamily(e->ai_family),
                         e->ai_canonname, uaddr, uport, strerror(errno));
             closesocket(sock);
-            sock = -1;
             continue;
         }
         freeaddrinfo(res);
commit 75115d9569164b99a52847450d5133af62f3d370
Author: Benoît Canet <benoit.canet at gmail.com>
Date:   Thu Aug 2 10:22:49 2012 +0200

    hmp: show the backing file depth
    
    Signed-off-by: Benoit Canet <benoit at irqsave.net>
    Reviewed-by: Eric Blake <eblake at redhat.com>
    Signed-off-by: Luiz Capitulino <lcapitulino at redhat.com>

diff --git a/hmp.c b/hmp.c
index 6b72a64..25688ab 100644
--- a/hmp.c
+++ b/hmp.c
@@ -227,6 +227,8 @@ void hmp_info_block(Monitor *mon)
             if (info->value->inserted->has_backing_file) {
                 monitor_printf(mon, " backing_file=");
                 monitor_print_filename(mon, info->value->inserted->backing_file);
+                monitor_printf(mon, " backing_file_depth=%" PRId64,
+                    info->value->inserted->backing_file_depth);
             }
             monitor_printf(mon, " ro=%d drv=%s encrypted=%d",
                            info->value->inserted->ro,
commit 2e3e331710faa8d0b7d70b73e87df1fb6d33d0d3
Author: Benoît Canet <benoit.canet at gmail.com>
Date:   Thu Aug 2 10:22:48 2012 +0200

    block: Use bdrv_get_backing_file_depth()
    
    Use the dedicated counting function in qmp_query_block in order to
    propagate the backing file depth to HMP and add backing_file_depth
    to qmp-commands.hx
    
    Signed-off-by: Benoit Canet <benoit at irqsave.net>
    Reviewed-by: Eric Blake <eblake at redhat.com>
    Signed-off-by: Luiz Capitulino <lcapitulino at redhat.com>

diff --git a/block.c b/block.c
index 1206bba..24323c1 100644
--- a/block.c
+++ b/block.c
@@ -2450,6 +2450,9 @@ BlockInfoList *qmp_query_block(Error **errp)
                 info->value->inserted->backing_file = g_strdup(bs->backing_file);
             }
 
+            info->value->inserted->backing_file_depth =
+                bdrv_get_backing_file_depth(bs);
+
             if (bs->io_limits_enabled) {
                 info->value->inserted->bps =
                                bs->io_limits.bps[BLOCK_IO_LIMIT_TOTAL];
diff --git a/qapi-schema.json b/qapi-schema.json
index bc55ed2..b58f5cd 100644
--- a/qapi-schema.json
+++ b/qapi-schema.json
@@ -398,6 +398,8 @@
 #
 # @backing_file: #optional the name of the backing file (for copy-on-write)
 #
+# @backing_file_depth: number of files in the backing file chain (since: 1.2)
+#
 # @encrypted: true if the backing device is encrypted
 #
 # @bps: total throughput limit in bytes per second is specified
@@ -418,9 +420,10 @@
 ##
 { 'type': 'BlockDeviceInfo',
   'data': { 'file': 'str', 'ro': 'bool', 'drv': 'str',
-            '*backing_file': 'str', 'encrypted': 'bool',
-            'bps': 'int', 'bps_rd': 'int', 'bps_wr': 'int',
-            'iops': 'int', 'iops_rd': 'int', 'iops_wr': 'int'} }
+            '*backing_file': 'str', 'backing_file_depth': 'int',
+            'encrypted': 'bool', 'bps': 'int', 'bps_rd': 'int',
+            'bps_wr': 'int', 'iops': 'int', 'iops_rd': 'int',
+            'iops_wr': 'int'} }
 
 ##
 # @BlockDeviceIoStatus:
diff --git a/qmp-commands.hx b/qmp-commands.hx
index e3cf3c5..ac46638 100644
--- a/qmp-commands.hx
+++ b/qmp-commands.hx
@@ -1317,6 +1317,7 @@ Each json-object contain the following:
                                 "nbd", "parallels", "qcow", "qcow2", "raw",
                                 "tftp", "vdi", "vmdk", "vpc", "vvfat"
          - "backing_file": backing file name (json-string, optional)
+         - "backing_file_depth": number of files in the backing file chain (json-int)
          - "encrypted": true if encrypted, false otherwise (json-bool)
          - "bps": limit total bytes per second (json-int)
          - "bps_rd": limit read bytes per second (json-int)
@@ -1345,6 +1346,7 @@ Example:
                "drv":"qcow2",
                "encrypted":false,
                "file":"disks/test.img",
+               "backing_file_depth":0,
                "bps":1000000,
                "bps_rd":0,
                "bps_wr":0,
commit f198fd1c9aedaae2fa78eb94e236e95ce4f2aedd
Author: Benoît Canet <benoit.canet at gmail.com>
Date:   Thu Aug 2 10:22:47 2012 +0200

    block: create bdrv_get_backing_file_depth()
    
    Create bdrv_get_backing_file_depth() in order to be able to show
    in QMP and HMP how many ancestors backing an image a block device
    have.
    
    Signed-off-by: Benoit Canet <benoit at irqsave.net>
    Reviewed-by: Eric Blake <eblake at redhat.com>
    Signed-off-by: Luiz Capitulino <lcapitulino at redhat.com>

diff --git a/block.c b/block.c
index b38940b..1206bba 100644
--- a/block.c
+++ b/block.c
@@ -2754,6 +2754,19 @@ BlockDriverState *bdrv_find_backing_image(BlockDriverState *bs,
     return NULL;
 }
 
+int bdrv_get_backing_file_depth(BlockDriverState *bs)
+{
+    if (!bs->drv) {
+        return 0;
+    }
+
+    if (!bs->backing_hd) {
+        return 0;
+    }
+
+    return 1 + bdrv_get_backing_file_depth(bs->backing_hd);
+}
+
 #define NB_SUFFIXES 4
 
 char *get_human_readable_size(char *buf, int buf_size, int64_t size)
diff --git a/block.h b/block.h
index c89590d..650d872 100644
--- a/block.h
+++ b/block.h
@@ -174,6 +174,7 @@ int coroutine_fn bdrv_co_is_allocated_above(BlockDriverState *top,
                                             int nb_sectors, int *pnum);
 BlockDriverState *bdrv_find_backing_image(BlockDriverState *bs,
     const char *backing_file);
+int bdrv_get_backing_file_depth(BlockDriverState *bs);
 int bdrv_truncate(BlockDriverState *bs, int64_t offset);
 int64_t bdrv_getlength(BlockDriverState *bs);
 int64_t bdrv_get_allocated_file_size(BlockDriverState *bs);
commit 536c86fbf85ba1ab1651b028a4670033e3dfc9ed
Author: Jan Kiszka <jan.kiszka at siemens.com>
Date:   Mon Jul 23 13:45:01 2012 +0200

    qom: Clean libuser object and dependency files
    
    Signed-off-by: Jan Kiszka <jan.kiszka at siemens.com>
    Signed-off-by: Stefan Hajnoczi <stefanha at linux.vnet.ibm.com>

diff --git a/Makefile b/Makefile
index d872d46..000b46c 100644
--- a/Makefile
+++ b/Makefile
@@ -215,7 +215,7 @@ clean:
 	rm -f *.o *.d *.a *.lo $(TOOLS) $(HELPERS-y) qemu-ga TAGS cscope.* *.pod *~ */*~
 	rm -Rf .libs
 	rm -f slirp/*.o slirp/*.d audio/*.o audio/*.d block/*.o block/*.d net/*.o net/*.d fsdev/*.o fsdev/*.d ui/*.o ui/*.d qapi/*.o qapi/*.d qga/*.o qga/*.d
-	rm -f qom/*.o qom/*.d
+	rm -f qom/*.o qom/*.d libuser/qom/*.o libuser/qom/*.d
 	rm -f hw/usb/*.o hw/usb/*.d hw/*.o hw/*.d
 	rm -f qemu-img-cmds.h
 	rm -f trace/*.o trace/*.d
commit 9ddea9499e522a2db73419153ad05d6f5879c97b
Author: Jan Kiszka <jan.kiszka at siemens.com>
Date:   Mon Jul 23 13:44:35 2012 +0200

    usb: Clean common object and dependency files
    
    Signed-off-by: Jan Kiszka <jan.kiszka at siemens.com>
    Signed-off-by: Stefan Hajnoczi <stefanha at linux.vnet.ibm.com>

diff --git a/Makefile b/Makefile
index 621cb86..d872d46 100644
--- a/Makefile
+++ b/Makefile
@@ -216,7 +216,7 @@ clean:
 	rm -Rf .libs
 	rm -f slirp/*.o slirp/*.d audio/*.o audio/*.d block/*.o block/*.d net/*.o net/*.d fsdev/*.o fsdev/*.d ui/*.o ui/*.d qapi/*.o qapi/*.d qga/*.o qga/*.d
 	rm -f qom/*.o qom/*.d
-	rm -f usb/*.o usb/*.d hw/*.o hw/*.d
+	rm -f hw/usb/*.o hw/usb/*.d hw/*.o hw/*.d
 	rm -f qemu-img-cmds.h
 	rm -f trace/*.o trace/*.d
 	rm -f trace-dtrace.dtrace trace-dtrace.dtrace-timestamp
commit 1f07730896f4a38a66bc3a6837704290ff2927f9
Author: Hervé Poussineau <hpoussin at reactos.org>
Date:   Thu Aug 2 10:40:30 2012 +0200

    esp: add missing const on TypeInfo structures
    
    Signed-off-by: Hervé Poussineau <hpoussin at reactos.org>
    Signed-off-by: Paolo Bonzini <pbonzini at redhat.com>

diff --git a/hw/esp.c b/hw/esp.c
index a011347..77f5707 100644
--- a/hw/esp.c
+++ b/hw/esp.c
@@ -816,7 +816,7 @@ static void sysbus_esp_class_init(ObjectClass *klass, void *data)
     dc->vmsd = &vmstate_sysbus_esp_scsi;
 }
 
-static TypeInfo sysbus_esp_info = {
+static const TypeInfo sysbus_esp_info = {
     .name          = "esp",
     .parent        = TYPE_SYS_BUS_DEVICE,
     .instance_size = sizeof(SysBusESPState),
@@ -1176,7 +1176,7 @@ static void esp_pci_class_init(ObjectClass *klass, void *data)
     dc->vmsd = &vmstate_esp_pci_scsi;
 }
 
-static TypeInfo esp_pci_info = {
+static const TypeInfo esp_pci_info = {
     .name = "am53c974",
     .parent = TYPE_PCI_DEVICE,
     .instance_size = sizeof(PCIESPState),
commit e7b2f53bd280fec199693e0dab6fc9748170e16e
Author: Paolo Bonzini <pbonzini at redhat.com>
Date:   Thu Aug 2 15:41:47 2012 +0200

    esp: enable for all PCI machines
    
    Signed-off-by: Paolo Bonzini <pbonzini at redhat.com>

diff --git a/default-configs/i386-softmmu.mak b/default-configs/i386-softmmu.mak
index fee8cde..2c78175 100644
--- a/default-configs/i386-softmmu.mak
+++ b/default-configs/i386-softmmu.mak
@@ -25,4 +25,3 @@ CONFIG_HPET=y
 CONFIG_APPLESMC=y
 CONFIG_I8259=y
 CONFIG_PFLASH_CFI01=y
-CONFIG_ESP=y
diff --git a/default-configs/pci.mak b/default-configs/pci.mak
index 4b49c00..9febb47 100644
--- a/default-configs/pci.mak
+++ b/default-configs/pci.mak
@@ -17,3 +17,4 @@ CONFIG_IDE_CORE=y
 CONFIG_IDE_QDEV=y
 CONFIG_IDE_PCI=y
 CONFIG_AHCI=y
+CONFIG_ESP=y
commit ca5481ed57f620c81a0636e3ddf49478a950d649
Author: Paolo Bonzini <pbonzini at redhat.com>
Date:   Wed Aug 1 12:56:17 2012 +0200

    Revert "megasas: disable due to build breakage"
    
    This reverts commit 92336855975805d88c7979f53bc05c2d47abab04.
    
    Signed-off-by: Paolo Bonzini <pbonzini at redhat.com>

diff --git a/default-configs/pci.mak b/default-configs/pci.mak
index 9d3e1db..4b49c00 100644
--- a/default-configs/pci.mak
+++ b/default-configs/pci.mak
@@ -10,6 +10,7 @@ CONFIG_EEPRO100_PCI=y
 CONFIG_PCNET_PCI=y
 CONFIG_PCNET_COMMON=y
 CONFIG_LSI_SCSI_PCI=y
+CONFIG_MEGASAS_SCSI_PCI=y
 CONFIG_RTL8139_PCI=y
 CONFIG_E1000_PCI=y
 CONFIG_IDE_CORE=y
commit 76b523db0074aaf489cb80ccd0943b69ea67e30b
Author: Hannes Reinecke <hare at suse.de>
Date:   Wed Aug 1 12:46:50 2012 +0200

    megasas: static SAS addresses
    
    This patch introduces a new property 'sas_address' which
    allows the user to specify the SAS address for the HBA.
    The default address is following the NAA locally assigned
    identifier format with the locally assigned address
    0x525400 as used eg for the MAC addresses.
    The lower bytes are set to the pci address which
    will ensure uniqueness for the local machine.
    
    The port addresses are now calculated based on the magic
    number 0x1221 (which is found in real hardware, too) plus
    the device number.
    
    Signed-off-by: Hannes Reinecke <hare at suse.de>
    Cc: Paolo Bonzini <pbonzini at redhat.com>
    Cc: Andreas Faerber <afaerber at suse.de>
    Cc: Anthony Liguori <anthony at codemonkey.ws>
    Cc: Alexander Graf <agraf at suse.de>
    Signed-off-by: Paolo Bonzini <pbonzini at redhat.com>

diff --git a/hw/megasas.c b/hw/megasas.c
index 8a4960f..c35a15d 100644
--- a/hw/megasas.c
+++ b/hw/megasas.c
@@ -38,6 +38,9 @@
 #define MEGASAS_MAX_SECTORS 0xFFFF      /* No real limit */
 #define MEGASAS_MAX_ARRAYS 128
 
+#define NAA_LOCALLY_ASSIGNED_ID 0x3ULL
+#define IEEE_COMPANY_LOCALLY_ASSIGNED 0x525400
+
 #define MEGASAS_FLAG_USE_JBOD      0
 #define MEGASAS_MASK_USE_JBOD      (1 << MEGASAS_FLAG_USE_JBOD)
 #define MEGASAS_FLAG_USE_MSIX      1
@@ -89,6 +92,8 @@ typedef struct MegasasState {
     int shutdown_event;
     int boot_event;
 
+    uint64_t sas_addr;
+
     uint64_t reply_queue_pa;
     void *reply_queue;
     int reply_queue_len;
@@ -372,14 +377,16 @@ static uint64_t megasas_fw_time(void)
     return bcd_time;
 }
 
-static uint64_t megasas_gen_sas_addr(uint64_t id)
+/*
+ * Default disk sata address
+ * 0x1221 is the magic number as
+ * present in real hardware,
+ * so use it here, too.
+ */
+static uint64_t megasas_get_sata_addr(uint16_t id)
 {
-    uint64_t addr;
-
-    addr = 0x5001a4aULL << 36;
-    addr |= id & 0xfffffffff;
-
-    return addr;
+    uint64_t addr = (0x1221ULL << 48);
+    return addr & (id << 24);
 }
 
 /*
@@ -652,10 +659,7 @@ static int megasas_ctrl_get_info(MegasasState *s, MegasasCmd *cmd)
     size_t dcmd_size = sizeof(info);
     BusChild *kid;
     int num_ld_disks = 0;
-
-    QTAILQ_FOREACH(kid, &s->bus.qbus.children, sibling) {
-        num_ld_disks++;
-    }
+    uint16_t sdev_id;
 
     memset(&info, 0x0, cmd->iov_size);
     if (cmd->iov_size < dcmd_size) {
@@ -669,10 +673,29 @@ static int megasas_ctrl_get_info(MegasasState *s, MegasasCmd *cmd)
     info.pci.subvendor = cpu_to_le16(PCI_VENDOR_ID_LSI_LOGIC);
     info.pci.subdevice = cpu_to_le16(0x1013);
 
-    info.host.type = MFI_INFO_HOST_PCIX;
+    /*
+     * For some reason the firmware supports
+     * only up to 8 device ports.
+     * Despite supporting a far larger number
+     * of devices for the physical devices.
+     * So just display the first 8 devices
+     * in the device port list, independent
+     * of how many logical devices are actually
+     * present.
+     */
+    info.host.type = MFI_INFO_HOST_PCIE;
     info.device.type = MFI_INFO_DEV_SAS3G;
-    info.device.port_count = 2;
-    info.device.port_addr[0] = cpu_to_le64(megasas_gen_sas_addr((uint64_t)s));
+    info.device.port_count = 8;
+    QTAILQ_FOREACH(kid, &s->bus.qbus.children, sibling) {
+        SCSIDevice *sdev = DO_UPCAST(SCSIDevice, qdev, kid->child);
+
+        if (num_ld_disks < 8) {
+            sdev_id = ((sdev->id & 0xFF) >> 8) | (sdev->lun & 0xFF);
+            info.device.port_addr[num_ld_disks] =
+                cpu_to_le64(megasas_get_sata_addr(sdev_id));
+        }
+        num_ld_disks++;
+    }
 
     memcpy(info.product_name, "MegaRAID SAS 8708EM2", 20);
     snprintf(info.serial_number, 32, "QEMU%08lx",
@@ -761,7 +784,7 @@ static int megasas_mfc_get_defaults(MegasasState *s, MegasasCmd *cmd)
         return MFI_STAT_INVALID_PARAMETER;
     }
 
-    info.sas_addr = cpu_to_le64(megasas_gen_sas_addr((uint64_t)s));
+    info.sas_addr = cpu_to_le64(s->sas_addr);
     info.stripe_size = 3;
     info.flush_time = 4;
     info.background_rate = 30;
@@ -891,7 +914,7 @@ static int megasas_dcmd_pd_get_list(MegasasState *s, MegasasCmd *cmd)
         info.addr[num_pd_disks].scsi_dev_type = sdev->type;
         info.addr[num_pd_disks].connect_port_bitmap = 0x1;
         info.addr[num_pd_disks].sas_addr[0] =
-            cpu_to_le64(megasas_gen_sas_addr((uint64_t)sdev));
+            cpu_to_le64(megasas_get_sata_addr(sdev_id));
         num_pd_disks++;
         offset += sizeof(struct mfi_pd_address);
     }
@@ -994,7 +1017,7 @@ static int megasas_pd_get_info_submit(SCSIDevice *sdev, int lun,
     info->slot_number = (sdev->id & 0xFF);
     info->path_info.count = 1;
     info->path_info.sas_addr[0] =
-        cpu_to_le64(megasas_gen_sas_addr((uint64_t)sdev));
+        cpu_to_le64(megasas_get_sata_addr(sdev_id));
     info->connected_port_bitmap = 0x1;
     info->device_speed = 1;
     info->link_speed = 1;
@@ -2102,6 +2125,13 @@ static int megasas_scsi_init(PCIDevice *dev)
         msix_vector_use(&s->dev, 0);
     }
 
+    if (!s->sas_addr) {
+        s->sas_addr = ((NAA_LOCALLY_ASSIGNED_ID << 24) |
+                       IEEE_COMPANY_LOCALLY_ASSIGNED) << 36;
+        s->sas_addr |= (pci_bus_num(dev->bus) << 16);
+        s->sas_addr |= (PCI_SLOT(dev->devfn) << 8);
+        s->sas_addr |= PCI_FUNC(dev->devfn);
+    }
     if (s->fw_sge >= MEGASAS_MAX_SGE - MFI_PASS_FRAME_SIZE) {
         s->fw_sge = MEGASAS_MAX_SGE - MFI_PASS_FRAME_SIZE;
     } else if (s->fw_sge >= 128 - MFI_PASS_FRAME_SIZE) {
@@ -2136,6 +2166,7 @@ static Property megasas_properties[] = {
                        MEGASAS_DEFAULT_SGE),
     DEFINE_PROP_UINT32("max_cmds", MegasasState, fw_cmds,
                        MEGASAS_DEFAULT_FRAMES),
+    DEFINE_PROP_HEX64("sas_address", MegasasState, sas_addr, 0),
 #ifdef USE_MSIX
     DEFINE_PROP_BIT("use_msix", MegasasState, flags,
                     MEGASAS_FLAG_USE_MSIX, false),
diff --git a/hw/mfi.h b/hw/mfi.h
index 3045d4e..436b690 100644
--- a/hw/mfi.h
+++ b/hw/mfi.h
@@ -656,6 +656,7 @@ struct mfi_info_device {
 #define MFI_INFO_DEV_SAS3G      0x02
 #define MFI_INFO_DEV_SATA1      0x04
 #define MFI_INFO_DEV_SATA3G     0x08
+#define MFI_INFO_DEV_PCIE       0x10
     uint8_t reserved[6];
     uint8_t port_count;
     uint64_t port_addr[8];
commit 79fb50bb95ff85fe388a40e4884080f5a0c1bb21
Author: Paolo Bonzini <pbonzini at redhat.com>
Date:   Tue Jul 31 16:10:23 2012 +0200

    scsi-disk: fix compilation with DEBUG_SCSI
    
    Reported-by: Gerhard Wiesinger <lists at wiesinger.com>
    Signed-off-by: Paolo Bonzini <pbonzini at redhat.com>

diff --git a/hw/scsi-disk.c b/hw/scsi-disk.c
index e2ec177..a9c7279 100644
--- a/hw/scsi-disk.c
+++ b/hw/scsi-disk.c
@@ -447,7 +447,7 @@ static void scsi_write_complete(void * opaque, int ret)
         return;
     } else {
         scsi_init_iovec(r, SCSI_DMA_BUF_SIZE);
-        DPRINTF("Write complete tag=0x%x more=%d\n", r->req.tag, r->qiov.size);
+        DPRINTF("Write complete tag=0x%x more=%zd\n", r->req.tag, r->qiov.size);
         scsi_req_data(&r->req, r->qiov.size);
     }
 
@@ -1277,7 +1277,7 @@ static void scsi_disk_emulate_read_data(SCSIRequest *req)
     int buflen = r->iov.iov_len;
 
     if (buflen) {
-        DPRINTF("Read buf_len=%zd\n", buflen);
+        DPRINTF("Read buf_len=%d\n", buflen);
         r->iov.iov_len = 0;
         r->started = true;
         scsi_req_data(&r->req, buflen);
@@ -1455,7 +1455,7 @@ static void scsi_disk_emulate_write_data(SCSIRequest *req)
 
     if (r->iov.iov_len) {
         int buflen = r->iov.iov_len;
-        DPRINTF("Write buf_len=%zd\n", buflen);
+        DPRINTF("Write buf_len=%d\n", buflen);
         r->iov.iov_len = 0;
         scsi_req_data(&r->req, buflen);
         return;
@@ -2093,23 +2093,24 @@ static SCSIRequest *scsi_new_request(SCSIDevice *d, uint32_t tag, uint32_t lun,
     const SCSIReqOps *ops;
     uint8_t command;
 
+    command = buf[0];
+    ops = scsi_disk_reqops_dispatch[command];
+    if (!ops) {
+        ops = &scsi_disk_emulate_reqops;
+    }
+    req = scsi_req_alloc(ops, &s->qdev, tag, lun, hba_private);
+
 #ifdef DEBUG_SCSI
-    DPRINTF("Command: lun=%d tag=0x%x data=0x%02x", lun, buf[0]);
+    DPRINTF("Command: lun=%d tag=0x%x data=0x%02x", lun, tag, buf[0]);
     {
         int i;
-        for (i = 1; i < r->req.cmd.len; i++) {
+        for (i = 1; i < req->cmd.len; i++) {
             printf(" 0x%02x", buf[i]);
         }
         printf("\n");
     }
 #endif
 
-    command = buf[0];
-    ops = scsi_disk_reqops_dispatch[command];
-    if (!ops) {
-        ops = &scsi_disk_emulate_reqops;
-    }
-    req = scsi_req_alloc(ops, &s->qdev, tag, lun, hba_private);
     return req;
 }
 
commit 18fc611b81d449827916f1cb27b3dbf0bcf364a8
Author: Stefan Weil <sw at weilnetz.de>
Date:   Tue Jul 31 07:54:57 2012 +0200

    megasas: Update function megasys_scsi_uninit
    
    Commit f90c2bcdbc69e41e575f868b984c3e2de8f51bac changed
    PCIUnregisterFunc, therefore the function prototype
    needs an update.
    
    megasas.o is currently not linked, so this bug was not
    detected by the buildbots.
    
    Signed-off-by: Stefan Weil <sw at weilnetz.de>
    Signed-off-by: Paolo Bonzini <pbonzini at redhat.com>

diff --git a/hw/megasas.c b/hw/megasas.c
index 9a0eab1..8a4960f 100644
--- a/hw/megasas.c
+++ b/hw/megasas.c
@@ -2040,7 +2040,7 @@ static const VMStateDescription vmstate_megasas = {
     }
 };
 
-static int megasas_scsi_uninit(PCIDevice *d)
+static void megasas_scsi_uninit(PCIDevice *d)
 {
     MegasasState *s = DO_UPCAST(MegasasState, dev, d);
 
@@ -2050,7 +2050,6 @@ static int megasas_scsi_uninit(PCIDevice *d)
     memory_region_destroy(&s->mmio_io);
     memory_region_destroy(&s->port_io);
     memory_region_destroy(&s->queue_io);
-    return 0;
 }
 
 static const struct SCSIBusInfo megasas_scsi_info = {
commit ae5708b36d34f72aa8c91e3dad56b266dfde73f1
Author: Ronnie Sahlberg <ronniesahlberg at gmail.com>
Date:   Sat Jul 28 11:14:53 2012 +1000

    SCSI: STARTSTOPUNIT only eject/load media if powercondition is 0
    
    The START STOP UNIT command will only eject/load media if
    power condition is zero.
    
    If power condition is !0 then LOEJ and START will be ignored.
    
    From MMC (sbc contains similar wordings too)
      The Power Conditions field requests the block device to be placed
      in the power condition defined in
      Table 558. If this field has a value other than 0h then the Start
      and LoEj bits shall be ignored.
    
    Signed-off-by: Ronnie Sahlberg <ronniesahlberg at gmail.com>
    Signed-off-by: Paolo Bonzini <pbonzini at redhat.com>

diff --git a/hw/scsi-disk.c b/hw/scsi-disk.c
index 84b63ff..e2ec177 100644
--- a/hw/scsi-disk.c
+++ b/hw/scsi-disk.c
@@ -1247,6 +1247,12 @@ static int scsi_disk_emulate_start_stop(SCSIDiskReq *r)
     SCSIDiskState *s = DO_UPCAST(SCSIDiskState, qdev, req->dev);
     bool start = req->cmd.buf[4] & 1;
     bool loej = req->cmd.buf[4] & 2; /* load on start, eject on !start */
+    int pwrcnd = req->cmd.buf[4] & 0xf0;
+
+    if (pwrcnd) {
+        /* eject/load only happens for power condition == 0 */
+        return 0;
+    }
 
     if ((s->features & (1 << SCSI_DISK_F_REMOVABLE)) && loej) {
         if (!start && !s->tray_open && s->tray_locked) {
commit 93161b69a53241be71e1aab7f792d78d9bfd19d3
Author: Ronnie Sahlberg <ronniesahlberg at gmail.com>
Date:   Mon Jul 30 07:52:03 2012 +1000

    SCSI: Update the sense code for PREVENT REMOVAL errors
    
    Change the sense codes for failures to eject a device that is locked
    by PREVENT_ALLOW_MEDIUM_REMOVAL from
    the generic MEDIA_LOAD_OR_EJECT_FAILED to the more specific
    MEDIUM_REMOVAL_PREVENTED.
    
    The second sense code is more accurate, and is also listed in MMC annex F
    for the recommended sense codes for MMC devices while the first sense code is not.
    
    Signed-off-by: Ronnie Sahlberg <ronniesahlberg at gmail.com>
    Signed-off-by: Paolo Bonzini <pbonzini at redhat.com>

diff --git a/hw/scsi-bus.c b/hw/scsi-bus.c
index e4ec19e..68049f6 100644
--- a/hw/scsi-bus.c
+++ b/hw/scsi-bus.c
@@ -1103,7 +1103,7 @@ const struct SCSISense sense_code_NO_MEDIUM = {
 
 /* LUN not ready, medium removal prevented */
 const struct SCSISense sense_code_NOT_READY_REMOVAL_PREVENTED = {
-    .key = NOT_READY, .asc = 0x53, .ascq = 0x00
+    .key = NOT_READY, .asc = 0x53, .ascq = 0x02
 };
 
 /* Hardware error, internal target failure */
@@ -1153,7 +1153,7 @@ const struct SCSISense sense_code_INCOMPATIBLE_FORMAT = {
 
 /* Illegal request, medium removal prevented */
 const struct SCSISense sense_code_ILLEGAL_REQ_REMOVAL_PREVENTED = {
-    .key = ILLEGAL_REQUEST, .asc = 0x53, .ascq = 0x00
+    .key = ILLEGAL_REQUEST, .asc = 0x53, .ascq = 0x02
 };
 
 /* Command aborted, I/O process terminated */
commit c8057f951d64de93bfd01569c0a725baa9f94372
Author: Peter Maydell <peter.maydell at linaro.org>
Date:   Thu Aug 2 13:45:54 2012 +0100

    Support 'help' as a synonym for '?' in command line options
    
    For command line options which permit '?' meaning 'please list the
    permitted values', add support for 'help' as a synonym, by abstracting
    the check out into a helper function.
    
    This change means that in some cases where we were being lazy in
    our string parsing, "?junk" will now be rejected as an invalid option
    rather than being (undocumentedly) treated the same way as "?".
    
    Update the documentation to use 'help' rather than '?', since '?'
    is a shell metacharacter and thus prone to fail confusingly if there
    is a single character filename in the current working directory and
    the '?' has not been escaped. It's therefore better to steer users
    towards 'help', though '?' is retained for backwards compatibility.
    
    We do not, however, update the output of the system emulator's -help
    (or any documentation autogenerated from the qemu-options.hx which
    is the source of the -help text) because libvirt parses our -help
    output and will break. At a later date when QEMU provides a better
    interface so libvirt can avoid having to do this, we can update the
    -help text too.
    
    Signed-off-by: Peter Maydell <peter.maydell at linaro.org>
    Signed-off-by: Anthony Liguori <aliguori at us.ibm.com>

diff --git a/arch_init.c b/arch_init.c
index 26f30ef..60823ba 100644
--- a/arch_init.c
+++ b/arch_init.c
@@ -680,7 +680,7 @@ void select_soundhw(const char *optarg)
 {
     struct soundhw *c;
 
-    if (*optarg == '?') {
+    if (is_help_option(optarg)) {
     show_valid_cards:
 
         printf("Valid sound card names (comma separated):\n");
@@ -688,7 +688,7 @@ void select_soundhw(const char *optarg)
             printf ("%-11s %s\n", c->name, c->descr);
         }
         printf("\n-soundhw all will enable all of the above\n");
-        exit(*optarg != '?');
+        exit(!is_help_option(optarg));
     }
     else {
         size_t l;
diff --git a/blockdev.c b/blockdev.c
index 3d75015..8669142 100644
--- a/blockdev.c
+++ b/blockdev.c
@@ -398,11 +398,11 @@ DriveInfo *drive_init(QemuOpts *opts, int default_to_scsi)
 #endif
 
     if ((buf = qemu_opt_get(opts, "format")) != NULL) {
-       if (strcmp(buf, "?") == 0) {
-           error_printf("Supported formats:");
-           bdrv_iterate_format(bdrv_format_print, NULL);
-           error_printf("\n");
-           return NULL;
+        if (is_help_option(buf)) {
+            error_printf("Supported formats:");
+            bdrv_iterate_format(bdrv_format_print, NULL);
+            error_printf("\n");
+            return NULL;
         }
         drv = bdrv_find_whitelisted_format(buf);
         if (!drv) {
diff --git a/bsd-user/main.c b/bsd-user/main.c
index cd33d65..095ae8e 100644
--- a/bsd-user/main.c
+++ b/bsd-user/main.c
@@ -681,7 +681,7 @@ static void usage(void)
            "-g port           wait gdb connection to port\n"
            "-L path           set the elf interpreter prefix (default=%s)\n"
            "-s size           set the stack size in bytes (default=%ld)\n"
-           "-cpu model        select CPU (-cpu ? for list)\n"
+           "-cpu model        select CPU (-cpu help for list)\n"
            "-drop-ld-preload  drop LD_PRELOAD for target process\n"
            "-E var=value      sets/modifies targets environment variable(s)\n"
            "-U var            unsets targets environment variable(s)\n"
@@ -825,7 +825,7 @@ int main(int argc, char **argv)
             qemu_uname_release = argv[optind++];
         } else if (!strcmp(r, "cpu")) {
             cpu_model = argv[optind++];
-            if (strcmp(cpu_model, "?") == 0) {
+            if (is_help_option(cpu_model)) {
 /* XXX: implement xxx_cpu_list for targets that still miss it */
 #if defined(cpu_list)
                     cpu_list(stdout, &fprintf);
diff --git a/hw/mips_jazz.c b/hw/mips_jazz.c
index bf1b799..db927f1 100644
--- a/hw/mips_jazz.c
+++ b/hw/mips_jazz.c
@@ -239,7 +239,7 @@ static void mips_jazz_init(MemoryRegion *address_space,
             dp83932_init(nd, 0x80001000, 2, get_system_memory(), rc4030[4],
                          rc4030_opaque, rc4030_dma_memory_rw);
             break;
-        } else if (strcmp(nd->model, "?") == 0) {
+        } else if (is_help_option(nd->model)) {
             fprintf(stderr, "qemu: Supported NICs: dp83932\n");
             exit(1);
         } else {
diff --git a/hw/qdev-monitor.c b/hw/qdev-monitor.c
index 7915b45..b22a37a 100644
--- a/hw/qdev-monitor.c
+++ b/hw/qdev-monitor.c
@@ -138,13 +138,13 @@ int qdev_device_help(QemuOpts *opts)
     ObjectClass *klass;
 
     driver = qemu_opt_get(opts, "driver");
-    if (driver && !strcmp(driver, "?")) {
+    if (driver && is_help_option(driver)) {
         bool show_no_user = false;
         object_class_foreach(qdev_print_devinfo, TYPE_DEVICE, false, &show_no_user);
         return 1;
     }
 
-    if (!driver || !qemu_opt_get(opts, "?")) {
+    if (!driver || !qemu_opt_has_help_opt(opts)) {
         return 0;
     }
 
diff --git a/hw/watchdog.c b/hw/watchdog.c
index a42124d..b52aced 100644
--- a/hw/watchdog.c
+++ b/hw/watchdog.c
@@ -55,7 +55,7 @@ int select_watchdog(const char *p)
     QemuOpts *opts;
 
     /* -watchdog ? lists available devices and exits cleanly. */
-    if (strcmp(p, "?") == 0) {
+    if (is_help_option(p)) {
         QLIST_FOREACH(model, &watchdog_list, entry) {
             fprintf(stderr, "\t%s\t%s\n",
                      model->wdt_name, model->wdt_description);
diff --git a/linux-user/main.c b/linux-user/main.c
index a0ab8e8..25eaa11 100644
--- a/linux-user/main.c
+++ b/linux-user/main.c
@@ -3140,7 +3140,7 @@ static void handle_arg_uname(const char *arg)
 static void handle_arg_cpu(const char *arg)
 {
     cpu_model = strdup(arg);
-    if (cpu_model == NULL || strcmp(cpu_model, "?") == 0) {
+    if (cpu_model == NULL || is_help_option(cpu_model)) {
         /* XXX: implement xxx_cpu_list for targets that still miss it */
 #if defined(cpu_list_id)
         cpu_list_id(stdout, &fprintf, "");
@@ -3231,7 +3231,7 @@ struct qemu_argument arg_table[] = {
     {"s",          "QEMU_STACK_SIZE",  true,  handle_arg_stack_size,
      "size",       "set the stack size to 'size' bytes"},
     {"cpu",        "QEMU_CPU",         true,  handle_arg_cpu,
-     "model",      "select CPU (-cpu ? for list)"},
+     "model",      "select CPU (-cpu help for list)"},
     {"E",          "QEMU_SET_ENV",     true,  handle_arg_set_env,
      "var=value",  "sets targets environment variable (see below)"},
     {"U",          "QEMU_UNSET_ENV",   true,  handle_arg_unset_env,
diff --git a/net.c b/net.c
index dbca77b..32ca50e 100644
--- a/net.c
+++ b/net.c
@@ -691,8 +691,9 @@ int qemu_show_nic_models(const char *arg, const char *const *models)
 {
     int i;
 
-    if (!arg || strcmp(arg, "?"))
+    if (!arg || !is_help_option(arg)) {
         return 0;
+    }
 
     fprintf(stderr, "qemu: Supported NIC models: ");
     for (i = 0 ; models[i]; i++)
diff --git a/qemu-common.h b/qemu-common.h
index d26ff39..dd91912 100644
--- a/qemu-common.h
+++ b/qemu-common.h
@@ -136,6 +136,24 @@ int qemu_main(int argc, char **argv, char **envp);
 void qemu_get_timedate(struct tm *tm, int offset);
 int qemu_timedate_diff(struct tm *tm);
 
+/**
+ * is_help_option:
+ * @s: string to test
+ *
+ * Check whether @s is one of the standard strings which indicate
+ * that the user is asking for a list of the valid values for a
+ * command option like -cpu or -M. The current accepted strings
+ * are 'help' and '?'. '?' is deprecated (it is a shell wildcard
+ * which makes it annoying to use in a reliable way) but provided
+ * for backwards compatibility.
+ *
+ * Returns: true if @s is a request for a list.
+ */
+static inline bool is_help_option(const char *s)
+{
+    return !strcmp(s, "?") || !strcmp(s, "help");
+}
+
 /* cutils.c */
 void pstrcpy(char *buf, int buf_size, const char *str);
 void strpadcpy(char *buf, int buf_size, const char *str, char pad);
diff --git a/qemu-doc.texi b/qemu-doc.texi
index 84dad19..a41448a 100644
--- a/qemu-doc.texi
+++ b/qemu-doc.texi
@@ -2390,7 +2390,7 @@ Set the x86 elf interpreter prefix (default=/usr/local/qemu-i386)
 @item -s size
 Set the x86 stack size in bytes (default=524288)
 @item -cpu model
-Select CPU model (-cpu ? for list and additional feature selection)
+Select CPU model (-cpu help for list and additional feature selection)
 @item -ignore-environment
 Start with an empty environment. Without this option,
 the initial environment is a copy of the caller's environment.
diff --git a/qemu-ga.c b/qemu-ga.c
index 8199da7..f1a39ec 100644
--- a/qemu-ga.c
+++ b/qemu-ga.c
@@ -736,7 +736,7 @@ int main(int argc, char **argv)
             break;
         case 'b': {
             char **list_head, **list;
-            if (*optarg == '?') {
+            if (is_help_option(optarg)) {
                 list_head = list = qmp_get_command_list();
                 while (*list != NULL) {
                     printf("%s\n", *list);
diff --git a/qemu-img.c b/qemu-img.c
index 80cfb9b..b866f80 100644
--- a/qemu-img.c
+++ b/qemu-img.c
@@ -350,7 +350,7 @@ static int img_create(int argc, char **argv)
         img_size = (uint64_t)sval;
     }
 
-    if (options && !strcmp(options, "?")) {
+    if (options && is_help_option(options)) {
         ret = print_block_option_help(filename, fmt);
         goto out;
     }
@@ -744,7 +744,7 @@ static int img_convert(int argc, char **argv)
     /* Initialize before goto out */
     qemu_progress_init(progress, 2.0);
 
-    if (options && !strcmp(options, "?")) {
+    if (options && is_help_option(options)) {
         ret = print_block_option_help(out_filename, out_fmt);
         goto out;
     }
diff --git a/qemu-option.c b/qemu-option.c
index 8334190..27891e7 100644
--- a/qemu-option.c
+++ b/qemu-option.c
@@ -529,6 +529,18 @@ const char *qemu_opt_get(QemuOpts *opts, const char *name)
     return opt ? opt->str : NULL;
 }
 
+bool qemu_opt_has_help_opt(QemuOpts *opts)
+{
+    QemuOpt *opt;
+
+    QTAILQ_FOREACH_REVERSE(opt, &opts->head, QemuOptHead, next) {
+        if (is_help_option(opt->name)) {
+            return true;
+        }
+    }
+    return false;
+}
+
 bool qemu_opt_get_bool(QemuOpts *opts, const char *name, bool defval)
 {
     QemuOpt *opt = qemu_opt_find(opts, name);
diff --git a/qemu-option.h b/qemu-option.h
index 951dec3..ca72986 100644
--- a/qemu-option.h
+++ b/qemu-option.h
@@ -107,6 +107,18 @@ struct QemuOptsList {
 };
 
 const char *qemu_opt_get(QemuOpts *opts, const char *name);
+/**
+ * qemu_opt_has_help_opt:
+ * @opts: options to search for a help request
+ *
+ * Check whether the options specified by @opts include one of the
+ * standard strings which indicate that the user is asking for a
+ * list of the valid values for a command line option (as defined
+ * by is_help_option()).
+ *
+ * Returns: true if @opts includes 'help' or equivalent.
+ */
+bool qemu_opt_has_help_opt(QemuOpts *opts);
 bool qemu_opt_get_bool(QemuOpts *opts, const char *name, bool defval);
 uint64_t qemu_opt_get_number(QemuOpts *opts, const char *name, uint64_t defval);
 uint64_t qemu_opt_get_size(QemuOpts *opts, const char *name, uint64_t defval);
diff --git a/qemu-options.hx b/qemu-options.hx
index dc68e15..9277414 100644
--- a/qemu-options.hx
+++ b/qemu-options.hx
@@ -6,6 +6,10 @@ HXCOMM construct option structures, enums and help message for specified
 HXCOMM architectures.
 HXCOMM HXCOMM can be used for comments, discarded from both texi and C
 
+HXCOMM TODO : when we are able to change -help output without breaking
+HXCOMM libvirt we should update the help options which refer to -cpu ?,
+HXCOMM -driver ?, etc to use the preferred -cpu help etc instead.
+
 DEFHEADING(Standard options:)
 STEXI
 @table @option
diff --git a/qemu-timer.c b/qemu-timer.c
index de98977..062fdf2 100644
--- a/qemu-timer.c
+++ b/qemu-timer.c
@@ -183,7 +183,7 @@ void configure_alarms(char const *opt)
     char *name;
     struct qemu_alarm_timer tmp;
 
-    if (!strcmp(opt, "?")) {
+    if (is_help_option(opt)) {
         show_available_alarms();
         exit(0);
     }
diff --git a/vl.c b/vl.c
index 9fea320..1fd1114 100644
--- a/vl.c
+++ b/vl.c
@@ -2086,7 +2086,7 @@ static QEMUMachine *machine_parse(const char *name)
         printf("%-20s %s%s\n", m->name, m->desc,
                m->is_default ? " (default)" : "");
     }
-    exit(!name || *name != '?');
+    exit(!name || !is_help_option(name));
 }
 
 static int tcg_init(void)
@@ -3216,7 +3216,7 @@ int main(int argc, char **argv, char **envp)
      */
     cpudef_init();
 
-    if (cpu_model && *cpu_model == '?') {
+    if (cpu_model && is_help_option(cpu_model)) {
         list_cpus(stdout, &fprintf, cpu_model);
         exit(0);
     }
commit 216fc9a44b939eecc9594f6a07fdbebdf717659e
Author: Andreas Färber <afaerber at suse.de>
Date:   Wed May 2 17:49:49 2012 +0200

    cpu: Move thread_kicked to CPUState
    
    Change field type to bool.
    
    Signed-off-by: Andreas Färber <afaerber at suse.de>

diff --git a/cpu-defs.h b/cpu-defs.h
index be89684..4018b88 100644
--- a/cpu-defs.h
+++ b/cpu-defs.h
@@ -209,7 +209,6 @@ typedef struct CPUWatchpoint {
     uint32_t stop;   /* Stop request */                                 \
     uint32_t stopped; /* Artificially stopped */                        \
     struct QemuCond *halt_cond;                                         \
-    int thread_kicked;                                                  \
     struct qemu_work_item *queued_work_first, *queued_work_last;        \
     const char *cpu_model_str;                                          \
     struct KVMState *kvm_state;                                         \
diff --git a/cpus.c b/cpus.c
index 565abb4..b61f60e 100644
--- a/cpus.c
+++ b/cpus.c
@@ -686,13 +686,15 @@ static void flush_queued_work(CPUArchState *env)
 
 static void qemu_wait_io_event_common(CPUArchState *env)
 {
+    CPUState *cpu = ENV_GET_CPU(env);
+
     if (env->stop) {
         env->stop = 0;
         env->stopped = 1;
         qemu_cond_signal(&qemu_pause_cond);
     }
     flush_queued_work(env);
-    env->thread_kicked = false;
+    cpu->thread_kicked = false;
 }
 
 static void qemu_tcg_wait_io_event(void)
@@ -866,11 +868,12 @@ static void qemu_cpu_kick_thread(CPUArchState *env)
 void qemu_cpu_kick(void *_env)
 {
     CPUArchState *env = _env;
+    CPUState *cpu = ENV_GET_CPU(env);
 
     qemu_cond_broadcast(env->halt_cond);
-    if (!tcg_enabled() && !env->thread_kicked) {
+    if (!tcg_enabled() && !cpu->thread_kicked) {
         qemu_cpu_kick_thread(env);
-        env->thread_kicked = true;
+        cpu->thread_kicked = true;
     }
 }
 
@@ -878,10 +881,11 @@ void qemu_cpu_kick_self(void)
 {
 #ifndef _WIN32
     assert(cpu_single_env);
+    CPUState *cpu_single_cpu = ENV_GET_CPU(cpu_single_env);
 
-    if (!cpu_single_env->thread_kicked) {
+    if (!cpu_single_cpu->thread_kicked) {
         qemu_cpu_kick_thread(cpu_single_env);
-        cpu_single_env->thread_kicked = true;
+        cpu_single_cpu->thread_kicked = true;
     }
 #else
     abort();
diff --git a/include/qemu/cpu.h b/include/qemu/cpu.h
index d20644b..ad706a6 100644
--- a/include/qemu/cpu.h
+++ b/include/qemu/cpu.h
@@ -66,6 +66,7 @@ struct CPUState {
 #ifdef _WIN32
     HANDLE hThread;
 #endif
+    bool thread_kicked;
 
     /* TODO Move common fields from CPUArchState here. */
 };
commit 814e612eaf1bfb93ee76097ec81e6d6a8855961b
Author: Andreas Färber <afaerber at suse.de>
Date:   Wed May 2 17:00:37 2012 +0200

    cpu: Move thread field into CPUState
    
    Signed-off-by: Andreas Färber <afaerber at suse.de>

diff --git a/cpu-defs.h b/cpu-defs.h
index d0dd781..be89684 100644
--- a/cpu-defs.h
+++ b/cpu-defs.h
@@ -208,7 +208,6 @@ typedef struct CPUWatchpoint {
     uint32_t created;                                                   \
     uint32_t stop;   /* Stop request */                                 \
     uint32_t stopped; /* Artificially stopped */                        \
-    struct QemuThread *thread;                                          \
     struct QemuCond *halt_cond;                                         \
     int thread_kicked;                                                  \
     struct qemu_work_item *queued_work_first, *queued_work_last;        \
diff --git a/cpus.c b/cpus.c
index 7042fb5..565abb4 100644
--- a/cpus.c
+++ b/cpus.c
@@ -728,10 +728,11 @@ static void qemu_kvm_wait_io_event(CPUArchState *env)
 static void *qemu_kvm_cpu_thread_fn(void *arg)
 {
     CPUArchState *env = arg;
+    CPUState *cpu = ENV_GET_CPU(env);
     int r;
 
     qemu_mutex_lock(&qemu_global_mutex);
-    qemu_thread_get_self(env->thread);
+    qemu_thread_get_self(cpu->thread);
     env->thread_id = qemu_get_thread_id();
     cpu_single_env = env;
 
@@ -767,11 +768,12 @@ static void *qemu_dummy_cpu_thread_fn(void *arg)
     exit(1);
 #else
     CPUArchState *env = arg;
+    CPUState *cpu = ENV_GET_CPU(env);
     sigset_t waitset;
     int r;
 
     qemu_mutex_lock_iothread();
-    qemu_thread_get_self(env->thread);
+    qemu_thread_get_self(cpu->thread);
     env->thread_id = qemu_get_thread_id();
 
     sigemptyset(&waitset);
@@ -807,9 +809,10 @@ static void tcg_exec_all(void);
 static void *qemu_tcg_cpu_thread_fn(void *arg)
 {
     CPUArchState *env = arg;
+    CPUState *cpu = ENV_GET_CPU(env);
 
     qemu_tcg_init_cpu_signals();
-    qemu_thread_get_self(env->thread);
+    qemu_thread_get_self(cpu->thread);
 
     /* signal CPU creation */
     qemu_mutex_lock(&qemu_global_mutex);
@@ -842,17 +845,17 @@ static void *qemu_tcg_cpu_thread_fn(void *arg)
 
 static void qemu_cpu_kick_thread(CPUArchState *env)
 {
+    CPUState *cpu = ENV_GET_CPU(env);
 #ifndef _WIN32
     int err;
 
-    err = pthread_kill(env->thread->thread, SIG_IPI);
+    err = pthread_kill(cpu->thread->thread, SIG_IPI);
     if (err) {
         fprintf(stderr, "qemu:%s: %s", __func__, strerror(err));
         exit(1);
     }
 #else /* _WIN32 */
     if (!qemu_cpu_is_self(env)) {
-        CPUState *cpu = ENV_GET_CPU(env);
         SuspendThread(cpu->hThread);
         cpu_signal(0);
         ResumeThread(cpu->hThread);
@@ -888,8 +891,9 @@ void qemu_cpu_kick_self(void)
 int qemu_cpu_is_self(void *_env)
 {
     CPUArchState *env = _env;
+    CPUState *cpu = ENV_GET_CPU(env);
 
-    return qemu_thread_is_self(env->thread);
+    return qemu_thread_is_self(cpu->thread);
 }
 
 void qemu_mutex_lock_iothread(void)
@@ -975,37 +979,37 @@ void resume_all_vcpus(void)
 static void qemu_tcg_init_vcpu(void *_env)
 {
     CPUArchState *env = _env;
-#ifdef _WIN32
     CPUState *cpu = ENV_GET_CPU(env);
-#endif
 
     /* share a single thread for all cpus with TCG */
     if (!tcg_cpu_thread) {
-        env->thread = g_malloc0(sizeof(QemuThread));
+        cpu->thread = g_malloc0(sizeof(QemuThread));
         env->halt_cond = g_malloc0(sizeof(QemuCond));
         qemu_cond_init(env->halt_cond);
         tcg_halt_cond = env->halt_cond;
-        qemu_thread_create(env->thread, qemu_tcg_cpu_thread_fn, env,
+        qemu_thread_create(cpu->thread, qemu_tcg_cpu_thread_fn, env,
                            QEMU_THREAD_JOINABLE);
 #ifdef _WIN32
-        cpu->hThread = qemu_thread_get_handle(env->thread);
+        cpu->hThread = qemu_thread_get_handle(cpu->thread);
 #endif
         while (env->created == 0) {
             qemu_cond_wait(&qemu_cpu_cond, &qemu_global_mutex);
         }
-        tcg_cpu_thread = env->thread;
+        tcg_cpu_thread = cpu->thread;
     } else {
-        env->thread = tcg_cpu_thread;
+        cpu->thread = tcg_cpu_thread;
         env->halt_cond = tcg_halt_cond;
     }
 }
 
 static void qemu_kvm_start_vcpu(CPUArchState *env)
 {
-    env->thread = g_malloc0(sizeof(QemuThread));
+    CPUState *cpu = ENV_GET_CPU(env);
+
+    cpu->thread = g_malloc0(sizeof(QemuThread));
     env->halt_cond = g_malloc0(sizeof(QemuCond));
     qemu_cond_init(env->halt_cond);
-    qemu_thread_create(env->thread, qemu_kvm_cpu_thread_fn, env,
+    qemu_thread_create(cpu->thread, qemu_kvm_cpu_thread_fn, env,
                        QEMU_THREAD_JOINABLE);
     while (env->created == 0) {
         qemu_cond_wait(&qemu_cpu_cond, &qemu_global_mutex);
@@ -1014,10 +1018,12 @@ static void qemu_kvm_start_vcpu(CPUArchState *env)
 
 static void qemu_dummy_start_vcpu(CPUArchState *env)
 {
-    env->thread = g_malloc0(sizeof(QemuThread));
+    CPUState *cpu = ENV_GET_CPU(env);
+
+    cpu->thread = g_malloc0(sizeof(QemuThread));
     env->halt_cond = g_malloc0(sizeof(QemuCond));
     qemu_cond_init(env->halt_cond);
-    qemu_thread_create(env->thread, qemu_dummy_cpu_thread_fn, env,
+    qemu_thread_create(cpu->thread, qemu_dummy_cpu_thread_fn, env,
                        QEMU_THREAD_JOINABLE);
     while (env->created == 0) {
         qemu_cond_wait(&qemu_cpu_cond, &qemu_global_mutex);
diff --git a/include/qemu/cpu.h b/include/qemu/cpu.h
index 5d52e1c..d20644b 100644
--- a/include/qemu/cpu.h
+++ b/include/qemu/cpu.h
@@ -62,6 +62,7 @@ struct CPUState {
     Object parent_obj;
     /*< public >*/
 
+    struct QemuThread *thread;
 #ifdef _WIN32
     HANDLE hThread;
 #endif
commit bcba2a72ed0e0620438929942cb486ad3d08d168
Author: Andreas Färber <afaerber at suse.de>
Date:   Wed May 2 15:24:40 2012 +0200

    cpu: Move CPU_COMMON_THREAD into CPUState
    
    CPU_COMMON_THREAD was only used for Windows, adding an hThread field
    to CPU_COMMON.
    
    Move the field into QOM CPUState and change its type to HANDLE,
    which it is assigned from. This requires Windows headers, pulled in
    through qemu-thread.h.
    
    Signed-off-by: Andreas Färber <afaerber at suse.de>

diff --git a/cpu-defs.h b/cpu-defs.h
index f49e950..d0dd781 100644
--- a/cpu-defs.h
+++ b/cpu-defs.h
@@ -151,14 +151,6 @@ typedef struct CPUWatchpoint {
     QTAILQ_ENTRY(CPUWatchpoint) entry;
 } CPUWatchpoint;
 
-#ifdef _WIN32
-#define CPU_COMMON_THREAD \
-    void *hThread;
-
-#else
-#define CPU_COMMON_THREAD
-#endif
-
 #define CPU_TEMP_BUF_NLONGS 128
 #define CPU_COMMON                                                      \
     struct TranslationBlock *current_tb; /* currently executing TB  */  \
@@ -217,7 +209,6 @@ typedef struct CPUWatchpoint {
     uint32_t stop;   /* Stop request */                                 \
     uint32_t stopped; /* Artificially stopped */                        \
     struct QemuThread *thread;                                          \
-    CPU_COMMON_THREAD                                                   \
     struct QemuCond *halt_cond;                                         \
     int thread_kicked;                                                  \
     struct qemu_work_item *queued_work_first, *queued_work_last;        \
diff --git a/cpus.c b/cpus.c
index 756e624..7042fb5 100644
--- a/cpus.c
+++ b/cpus.c
@@ -852,9 +852,10 @@ static void qemu_cpu_kick_thread(CPUArchState *env)
     }
 #else /* _WIN32 */
     if (!qemu_cpu_is_self(env)) {
-        SuspendThread(env->hThread);
+        CPUState *cpu = ENV_GET_CPU(env);
+        SuspendThread(cpu->hThread);
         cpu_signal(0);
-        ResumeThread(env->hThread);
+        ResumeThread(cpu->hThread);
     }
 #endif
 }
@@ -974,6 +975,9 @@ void resume_all_vcpus(void)
 static void qemu_tcg_init_vcpu(void *_env)
 {
     CPUArchState *env = _env;
+#ifdef _WIN32
+    CPUState *cpu = ENV_GET_CPU(env);
+#endif
 
     /* share a single thread for all cpus with TCG */
     if (!tcg_cpu_thread) {
@@ -984,7 +988,7 @@ static void qemu_tcg_init_vcpu(void *_env)
         qemu_thread_create(env->thread, qemu_tcg_cpu_thread_fn, env,
                            QEMU_THREAD_JOINABLE);
 #ifdef _WIN32
-        env->hThread = qemu_thread_get_handle(env->thread);
+        cpu->hThread = qemu_thread_get_handle(env->thread);
 #endif
         while (env->created == 0) {
             qemu_cond_wait(&qemu_cpu_cond, &qemu_global_mutex);
diff --git a/include/qemu/cpu.h b/include/qemu/cpu.h
index 78b65b3..5d52e1c 100644
--- a/include/qemu/cpu.h
+++ b/include/qemu/cpu.h
@@ -21,6 +21,7 @@
 #define QEMU_CPU_H
 
 #include "qemu/object.h"
+#include "qemu-thread.h"
 
 /**
  * SECTION:cpu
@@ -61,6 +62,10 @@ struct CPUState {
     Object parent_obj;
     /*< public >*/
 
+#ifdef _WIN32
+    HANDLE hThread;
+#endif
+
     /* TODO Move common fields from CPUArchState here. */
 };
 
commit 2d797b6520d38bc66827b2022e9c620058f18de3
Author: Andreas Färber <afaerber at suse.de>
Date:   Wed May 2 17:21:31 2012 +0200

    qemu-thread: Let qemu_thread_is_self() return bool
    
    qemu_cpu_is_self(), passing the return value through, will later be
    adapted to return bool as well.
    
    Signed-off-by: Andreas Färber <afaerber at suse.de>
    Reviewed-by: Stefan Weil <sw at weilnetz.de>

diff --git a/qemu-thread-posix.c b/qemu-thread-posix.c
index 9e1b5fb..8fbabda 100644
--- a/qemu-thread-posix.c
+++ b/qemu-thread-posix.c
@@ -151,7 +151,7 @@ void qemu_thread_get_self(QemuThread *thread)
     thread->thread = pthread_self();
 }
 
-int qemu_thread_is_self(QemuThread *thread)
+bool qemu_thread_is_self(QemuThread *thread)
 {
    return pthread_equal(pthread_self(), thread->thread);
 }
diff --git a/qemu-thread-win32.c b/qemu-thread-win32.c
index 3524c8b..177b398 100644
--- a/qemu-thread-win32.c
+++ b/qemu-thread-win32.c
@@ -330,7 +330,7 @@ HANDLE qemu_thread_get_handle(QemuThread *thread)
     return handle;
 }
 
-int qemu_thread_is_self(QemuThread *thread)
+bool qemu_thread_is_self(QemuThread *thread)
 {
     return GetCurrentThreadId() == thread->tid;
 }
diff --git a/qemu-thread.h b/qemu-thread.h
index a78a8f2..05fdaaf 100644
--- a/qemu-thread.h
+++ b/qemu-thread.h
@@ -2,6 +2,7 @@
 #define __QEMU_THREAD_H 1
 
 #include <inttypes.h>
+#include <stdbool.h>
 
 typedef struct QemuMutex QemuMutex;
 typedef struct QemuCond QemuCond;
@@ -42,7 +43,7 @@ void qemu_thread_create(QemuThread *thread,
                         void *arg, int mode);
 void *qemu_thread_join(QemuThread *thread);
 void qemu_thread_get_self(QemuThread *thread);
-int qemu_thread_is_self(QemuThread *thread);
+bool qemu_thread_is_self(QemuThread *thread);
 void qemu_thread_exit(void *retval);
 
 #endif
commit e0d45df7a5794b6821d2f8893a7f343109debab9
Author: Luiz Capitulino <lcapitulino at redhat.com>
Date:   Fri Jun 29 20:53:37 2012 -0300

    qapi: qapi.py: allow the "'" character to be escaped
    
    Support escaping the escape character, and make more robust (don't die
    for '', handle ' without matching '.
    
    Signed-off-by: Markus Armbruster <armbru at redhat.com>
    Reviewed-by: Peter Maydell <peter.maydell at linaro.org>
    Signed-off-by: Luiz Capitulino <lcapitulino at redhat.com>

diff --git a/scripts/qapi.py b/scripts/qapi.py
index 8082af3..d3b8b4d 100644
--- a/scripts/qapi.py
+++ b/scripts/qapi.py
@@ -13,18 +13,29 @@ from ordereddict import OrderedDict
 
 def tokenize(data):
     while len(data):
-        if data[0] in ['{', '}', ':', ',', '[', ']']:
-            yield data[0]
-            data = data[1:]
-        elif data[0] in ' \n':
-            data = data[1:]
-        elif data[0] == "'":
-            data = data[1:]
+        ch = data[0]
+        data = data[1:]
+        if ch in ['{', '}', ':', ',', '[', ']']:
+            yield ch
+        elif ch in ' \n':
+            None
+        elif ch == "'":
             string = ''
-            while data[0] != "'":
-                string += data[0]
+            esc = False
+            while True:
+                if (data == ''):
+                    raise Exception("Mismatched quotes")
+                ch = data[0]
                 data = data[1:]
-            data = data[1:]
+                if esc:
+                    string += ch
+                    esc = False
+                elif ch == "\\":
+                    esc = True
+                elif ch == "'":
+                    break
+                else:
+                    string += ch
             yield string
 
 def parse(tokens):
commit 02d2bd5d57812154cfb978bc2098cf49d551583d
Author: Richard W.M. Jones <rjones at redhat.com>
Date:   Thu Jul 5 03:32:44 2012 +0000

    Replace 'struct siginfo' with 'siginfo_t'.
    
    glibc 2.16 will remove the undocumented definition of 'struct siginfo'
    from <bits/siginfo.h>.
    
    This change is already present in glibc 2.15.90, so qemu compilation
    of certain targets (eg. cris-user) breaks.
    
    This struct was always typedef'd to be the same as 'siginfo_t' which
    is what POSIX documents, so use that instead.
    
    Signed-off-by: Richard W.M. Jones <rjones at redhat.com>
    Reviewed-by: Peter Maydell <peter.maydell at linaro.org>
    Signed-off-by: Anthony Liguori <aliguori at us.ibm.com>

diff --git a/linux-user/signal.c b/linux-user/signal.c
index 97f30d9..9be5ac0 100644
--- a/linux-user/signal.c
+++ b/linux-user/signal.c
@@ -2849,7 +2849,7 @@ static void setup_rt_frame(int sig, struct target_sigaction *ka,
     * Arguments to signal handler:
     *
     *   a0 = signal number
-    *   a1 = pointer to struct siginfo
+    *   a1 = pointer to siginfo_t
     *   a2 = pointer to struct ucontext
     *
     * $25 and PC point to the signal handler, $29 points to the
@@ -3255,7 +3255,7 @@ struct target_signal_frame {
 };
 
 struct rt_signal_frame {
-    struct siginfo info;
+    siginfo_t info;
     struct ucontext uc;
     uint32_t tramp[2];
 };
@@ -3474,9 +3474,9 @@ struct target_signal_frame {
 };
 
 struct rt_signal_frame {
-        struct siginfo *pinfo;
+        siginfo_t *pinfo;
         void *puc;
-        struct siginfo info;
+        siginfo_t info;
         struct ucontext uc;
         uint8_t retcode[8];       /* Trampoline code. */
 };
diff --git a/user-exec.c b/user-exec.c
index b2a4261..1a9c276 100644
--- a/user-exec.c
+++ b/user-exec.c
@@ -588,7 +588,7 @@ int cpu_signal_handler(int host_signum, void *pinfo,
 int cpu_signal_handler(int host_signum, void *pinfo,
                        void *puc)
 {
-    struct siginfo *info = pinfo;
+    siginfo_t *info = pinfo;
     struct ucontext *uc = puc;
     unsigned long pc = uc->uc_mcontext.sc_iaoq[0];
     uint32_t insn = *(uint32_t *)pc;
commit 65dee38052597b6285eb208125369f01b29ba6c1
Author: Igor Mammedov <imammedo at redhat.com>
Date:   Mon Jul 23 15:22:28 2012 +0200

    target-i386: move cpu_reset and reset callback to cpu.c
    
    Moving reset callback into cpu object from board level and
    resetting cpu at the end of x86_cpu_realize() will allow properly
    create cpu object during run-time (hotplug) without calling reset externaly.
    
    When reset over QOM hierarchy is implemented, reset callback
    should be removed.
    
    v2:
      - leave cpu_reset in pc_new_cpu() for now, it's to be cleaned up when APIC
        init is moved in cpu.c
    
    Signed-off-by: Igor Mammedov <imammedo at redhat.com>
    Signed-off-by: Anthony Liguori <aliguori at us.ibm.com>

diff --git a/hw/pc.c b/hw/pc.c
index a920686..bd193f3 100644
--- a/hw/pc.c
+++ b/hw/pc.c
@@ -904,12 +904,6 @@ void pc_acpi_smi_interrupt(void *opaque, int irq, int level)
     }
 }
 
-static void pc_cpu_reset(void *opaque)
-{
-    X86CPU *cpu = opaque;
-    cpu_reset(CPU(cpu));
-}
-
 static X86CPU *pc_new_cpu(const char *cpu_model)
 {
     X86CPU *cpu;
@@ -924,8 +918,7 @@ static X86CPU *pc_new_cpu(const char *cpu_model)
     if ((env->cpuid_features & CPUID_APIC) || smp_cpus > 1) {
         env->apic_state = apic_init(env, env->cpuid_apic_id);
     }
-    qemu_register_reset(pc_cpu_reset, cpu);
-    pc_cpu_reset(cpu);
+    cpu_reset(CPU(cpu));
     return cpu;
 }
 
diff --git a/target-i386/cpu.c b/target-i386/cpu.c
index 365c2ff..857b94e 100644
--- a/target-i386/cpu.c
+++ b/target-i386/cpu.c
@@ -31,6 +31,8 @@
 
 #include "hyperv.h"
 
+#include "hw/hw.h"
+
 /* feature flags taken from "Intel Processor Identification and the CPUID
  * Instruction" and AMD's "CPUID Specification".  In cases of disagreement
  * between feature naming conventions, aliases may be added.
@@ -1702,6 +1704,13 @@ bool cpu_is_bsp(X86CPU *cpu)
 {
     return cpu_get_apic_base(cpu->env.apic_state) & MSR_IA32_APICBASE_BSP;
 }
+
+/* TODO: remove me, when reset over QOM tree is implemented */
+static void x86_cpu_machine_reset_cb(void *opaque)
+{
+    X86CPU *cpu = opaque;
+    cpu_reset(CPU(cpu));
+}
 #endif
 
 static void mce_init(X86CPU *cpu)
@@ -1724,8 +1733,13 @@ void x86_cpu_realize(Object *obj, Error **errp)
 {
     X86CPU *cpu = X86_CPU(obj);
 
+#ifndef CONFIG_USER_ONLY
+    qemu_register_reset(x86_cpu_machine_reset_cb, cpu);
+#endif
+
     mce_init(cpu);
     qemu_init_vcpu(&cpu->env);
+    cpu_reset(CPU(cpu));
 }
 
 static void x86_cpu_initfn(Object *obj)
commit dd673288a8ff73ad77fcc1c255486d2466a772e1
Author: Igor Mammedov <imammedo at redhat.com>
Date:   Mon Jul 23 15:22:27 2012 +0200

    target-i386: move cpu halted decision into x86_cpu_reset
    
    MP initialization protocol differs between cpu families, and for P6 and
    onward models it is up to CPU to decide if it will be BSP using this
    protocol, so try to model this. However there is no point in implementing
    MP initialization protocol in qemu. Thus first CPU is always marked as BSP.
    
    This patch:
     - moves decision to designate BSP from board into cpu, making cpu
    self-sufficient in this regard. Later it will allow to cleanup hw/pc.c
    and remove cpu_reset and wrappers from there.
     - stores flag that CPU is BSP in IA32_APIC_BASE to model behavior
    described in Inted SDM vol 3a part 1 chapter 8.4.1
     - uses MSR_IA32_APICBASE_BSP flag in apic_base for checking if cpu is BSP
    
    patch is based on Jan Kiszka's proposal:
        http://thread.gmane.org/gmane.comp.emulators.qemu/100806
    
    Signed-off-by: Igor Mammedov <imammedo at redhat.com>
    Signed-off-by: Anthony Liguori <aliguori at us.ibm.com>

diff --git a/hw/apic.h b/hw/apic.h
index a89542b..1d48e02 100644
--- a/hw/apic.h
+++ b/hw/apic.h
@@ -21,9 +21,12 @@ void apic_sipi(DeviceState *s);
 void apic_handle_tpr_access_report(DeviceState *d, target_ulong ip,
                                    TPRAccess access);
 void apic_poll_irq(DeviceState *d);
+void apic_designate_bsp(DeviceState *d);
 
 /* pc.c */
-int cpu_is_bsp(CPUX86State *env);
 DeviceState *cpu_get_current_apic(void);
 
+/* cpu.c */
+bool cpu_is_bsp(X86CPU *cpu);
+
 #endif
diff --git a/hw/apic_common.c b/hw/apic_common.c
index 60b8259..58e63b0 100644
--- a/hw/apic_common.c
+++ b/hw/apic_common.c
@@ -43,8 +43,8 @@ uint64_t cpu_get_apic_base(DeviceState *d)
         trace_cpu_get_apic_base((uint64_t)s->apicbase);
         return s->apicbase;
     } else {
-        trace_cpu_get_apic_base(0);
-        return 0;
+        trace_cpu_get_apic_base(MSR_IA32_APICBASE_BSP);
+        return MSR_IA32_APICBASE_BSP;
     }
 }
 
@@ -201,13 +201,23 @@ void apic_init_reset(DeviceState *d)
     s->timer_expiry = -1;
 }
 
+void apic_designate_bsp(DeviceState *d)
+{
+    if (d == NULL) {
+        return;
+    }
+
+    APICCommonState *s = APIC_COMMON(d);
+    s->apicbase |= MSR_IA32_APICBASE_BSP;
+}
+
 static void apic_reset_common(DeviceState *d)
 {
     APICCommonState *s = DO_UPCAST(APICCommonState, busdev.qdev, d);
     APICCommonClass *info = APIC_COMMON_GET_CLASS(s);
     bool bsp;
 
-    bsp = cpu_is_bsp(s->cpu_env);
+    bsp = cpu_is_bsp(x86_env_get_cpu(s->cpu_env));
     s->apicbase = 0xfee00000 |
         (bsp ? MSR_IA32_APICBASE_BSP : 0) | MSR_IA32_APICBASE_ENABLE;
 
diff --git a/hw/pc.c b/hw/pc.c
index 598267a..a920686 100644
--- a/hw/pc.c
+++ b/hw/pc.c
@@ -857,12 +857,6 @@ void pc_init_ne2k_isa(ISABus *bus, NICInfo *nd)
     nb_ne2k++;
 }
 
-int cpu_is_bsp(CPUX86State *env)
-{
-    /* We hard-wire the BSP to the first CPU. */
-    return env->cpu_index == 0;
-}
-
 DeviceState *cpu_get_current_apic(void)
 {
     if (cpu_single_env) {
@@ -913,10 +907,7 @@ void pc_acpi_smi_interrupt(void *opaque, int irq, int level)
 static void pc_cpu_reset(void *opaque)
 {
     X86CPU *cpu = opaque;
-    CPUX86State *env = &cpu->env;
-
     cpu_reset(CPU(cpu));
-    env->halted = !cpu_is_bsp(env);
 }
 
 static X86CPU *pc_new_cpu(const char *cpu_model)
diff --git a/target-i386/cpu.c b/target-i386/cpu.c
index 6b9659f..365c2ff 100644
--- a/target-i386/cpu.c
+++ b/target-i386/cpu.c
@@ -1686,8 +1686,24 @@ static void x86_cpu_reset(CPUState *s)
     env->dr[7] = DR7_FIXED_1;
     cpu_breakpoint_remove_all(env, BP_CPU);
     cpu_watchpoint_remove_all(env, BP_CPU);
+
+#if !defined(CONFIG_USER_ONLY)
+    /* We hard-wire the BSP to the first CPU. */
+    if (env->cpu_index == 0) {
+        apic_designate_bsp(env->apic_state);
+    }
+
+    env->halted = !cpu_is_bsp(cpu);
+#endif
 }
 
+#ifndef CONFIG_USER_ONLY
+bool cpu_is_bsp(X86CPU *cpu)
+{
+    return cpu_get_apic_base(cpu->env.apic_state) & MSR_IA32_APICBASE_BSP;
+}
+#endif
+
 static void mce_init(X86CPU *cpu)
 {
     CPUX86State *cenv = &cpu->env;
diff --git a/target-i386/helper.c b/target-i386/helper.c
index d3af6ea..b748d90 100644
--- a/target-i386/helper.c
+++ b/target-i386/helper.c
@@ -1191,7 +1191,6 @@ void do_cpu_init(X86CPU *cpu)
     env->interrupt_request = sipi;
     env->pat = pat;
     apic_init_reset(env->apic_state);
-    env->halted = !cpu_is_bsp(env);
 }
 
 void do_cpu_sipi(X86CPU *cpu)
diff --git a/target-i386/kvm.c b/target-i386/kvm.c
index e53c2f6..4cfb3fa 100644
--- a/target-i386/kvm.c
+++ b/target-i386/kvm.c
@@ -584,11 +584,13 @@ int kvm_arch_init_vcpu(CPUX86State *env)
 
 void kvm_arch_reset_vcpu(CPUX86State *env)
 {
+    X86CPU *cpu = x86_env_get_cpu(env);
+
     env->exception_injected = -1;
     env->interrupt_injected = -1;
     env->xcr0 = 1;
     if (kvm_irqchip_in_kernel()) {
-        env->mp_state = cpu_is_bsp(env) ? KVM_MP_STATE_RUNNABLE :
+        env->mp_state = cpu_is_bsp(cpu) ? KVM_MP_STATE_RUNNABLE :
                                           KVM_MP_STATE_UNINITIALIZED;
     } else {
         env->mp_state = KVM_MP_STATE_RUNNABLE;
commit 47fb65ce3e15762064dd6d93834e3ce923ef6f89
Author: Stefano Stabellini <stefano.stabellini at eu.citrix.com>
Date:   Wed Aug 1 13:44:11 2012 +0000

    fix Xen compilation
    
    xen_pt_unregister_device is used as PCIUnregisterFunc, so it should
    match the type.
    
    Signed-off-by: Stefano Stabellini <stefano.stabellini at eu.citrix.com>
    Tested-by: Andreas Färber <afaerber at suse.de>

diff --git a/hw/xen_pt.c b/hw/xen_pt.c
index fdf68aa..307119a 100644
--- a/hw/xen_pt.c
+++ b/hw/xen_pt.c
@@ -764,7 +764,7 @@ out:
     return 0;
 }
 
-static int xen_pt_unregister_device(PCIDevice *d)
+static void xen_pt_unregister_device(PCIDevice *d)
 {
     XenPCIPassthroughState *s = DO_UPCAST(XenPCIPassthroughState, dev, d);
     uint8_t machine_irq = s->machine_irq;
@@ -814,8 +814,6 @@ static int xen_pt_unregister_device(PCIDevice *d)
     memory_listener_unregister(&s->memory_listener);
 
     xen_host_pci_device_put(&s->real_device);
-
-    return 0;
 }
 
 static Property xen_pci_passthrough_properties[] = {
commit fb5b0c6d5cea2d05a5e4e81390a4b6c4c70c6668
Author: Stefano Stabellini <stefano.stabellini at eu.citrix.com>
Date:   Wed Aug 1 11:19:09 2012 +0100

    fix Xen compilation
    
    xen_pt_unregister_device is used as PCIUnregisterFunc, so it should
    match the type.
    
    Signed-off-by: Stefano Stabellini <stefano.stabellini at eu.citrix.com>
    Signed-off-by: Anthony Liguori <aliguori at us.ibm.com>

diff --git a/hw/xen_pt.c b/hw/xen_pt.c
index fdf68aa..307119a 100644
--- a/hw/xen_pt.c
+++ b/hw/xen_pt.c
@@ -764,7 +764,7 @@ out:
     return 0;
 }
 
-static int xen_pt_unregister_device(PCIDevice *d)
+static void xen_pt_unregister_device(PCIDevice *d)
 {
     XenPCIPassthroughState *s = DO_UPCAST(XenPCIPassthroughState, dev, d);
     uint8_t machine_irq = s->machine_irq;
@@ -814,8 +814,6 @@ static int xen_pt_unregister_device(PCIDevice *d)
     memory_listener_unregister(&s->memory_listener);
 
     xen_host_pci_device_put(&s->real_device);
-
-    return 0;
 }
 
 static Property xen_pci_passthrough_properties[] = {
commit f6ccf1f45385c33ec0ea0463cdb0b1fba3bd7178
Author: Anthony PERARD <anthony.perard at citrix.com>
Date:   Wed Aug 1 13:42:44 2012 +0000

    configure: Fix xen probe with Xen 4.2 and later
    
    The xs.h header is now deprecated and produces a warning. This prevents the
    configure script from enabling Xen with xen-unstable whom will become 4.2. As
    this header is not anymore common to every version of Xen, we just remove it
    from the early probe for Xen.
    
    Signed-off-by: Anthony PERARD <anthony.perard at citrix.com>
    Acked-by: Stefano Stabellini <stefano.stabellini at eu.citrix.com>

diff --git a/configure b/configure
index 027a718..3ca13a6 100755
--- a/configure
+++ b/configure
@@ -1384,7 +1384,6 @@ if test "$xen" != "no" ; then
   # Xen (any)
   cat > $TMPC <<EOF
 #include <xenctrl.h>
-#include <xs.h>
 int main(void) {
   return 0;
 }
commit 011de2b512a83aa5e9f8899ed5bbf2f31995b90e
Author: Zhi Yong Wu <wuzhy at linux.vnet.ibm.com>
Date:   Fri Jul 20 14:25:53 2012 +0100

    net: add the support for -netdev socket, listen
    
    The -net socket,listen option does not work with the newer -netdev
    syntax:
     http://lists.gnu.org/archive/html/qemu-devel/2011-11/msg01508.html
    
    This patch makes it work now.
    
    For the case where one vlan has multiple listenning sockets,
    the patch will also provide the support.
    
    Supported syntax:
     1.) -net socket,listen=127.0.0.1:1234,vlan=0
     2.) -net socket,listen=127.0.0.1:1234,vlan=0 -net socket,listen=127.0.0.1:1235,vlan=0
     3.) -netdev socket,listen=127.0.0.1:1234,id=socket0
    
     Drop the NetSocketListenState struct and add a listen_fd field
    to NetSocketState.  When a -netdev socket,listen= instance is created
    there will be a NetSocketState with fd=-1 and a valid listen_fd.  The
    net_socket_accept() handler waits for listen_fd to become readable and
    then accepts the connection.  When this state transition happens, we no
    longer monitor listen_fd for incoming connections...until the client
    disconnects again.
    
    Signed-off-by: Zhi Yong Wu <wuzhy at linux.vnet.ibm.com>
    Signed-off-by: Stefan Hajnoczi <stefanha at linux.vnet.ibm.com>
    Reviewed-by: Laszlo Ersek <lersek at redhat.com>

diff --git a/net/socket.c b/net/socket.c
index 7857dcd..c172c24 100644
--- a/net/socket.c
+++ b/net/socket.c
@@ -35,6 +35,7 @@
 
 typedef struct NetSocketState {
     NetClientState nc;
+    int listen_fd;
     int fd;
     int state; /* 0 = getting length, 1 = getting data */
     unsigned int index;
@@ -43,12 +44,7 @@ typedef struct NetSocketState {
     struct sockaddr_in dgram_dst; /* contains inet host and port destination iff connectionless (SOCK_DGRAM) */
 } NetSocketState;
 
-typedef struct NetSocketListenState {
-    NetClientState *peer;
-    char *model;
-    char *name;
-    int fd;
-} NetSocketListenState;
+static void net_socket_accept(void *opaque);
 
 /* XXX: we consider we can send the whole packet without blocking */
 static ssize_t net_socket_receive(NetClientState *nc, const uint8_t *buf, size_t size)
@@ -86,7 +82,19 @@ static void net_socket_send(void *opaque)
         /* end of connection */
     eoc:
         qemu_set_fd_handler(s->fd, NULL, NULL, NULL);
+        if (s->listen_fd != -1) {
+            qemu_set_fd_handler(s->listen_fd, net_socket_accept, NULL, s);
+        }
         closesocket(s->fd);
+
+        s->fd = -1;
+        s->state = 0;
+        s->index = 0;
+        s->packet_len = 0;
+        s->nc.link_down = true;
+        memset(s->buf, 0, sizeof(s->buf));
+        memset(s->nc.info_str, 0, sizeof(s->nc.info_str));
+
         return;
     }
     buf = buf1;
@@ -234,8 +242,16 @@ fail:
 static void net_socket_cleanup(NetClientState *nc)
 {
     NetSocketState *s = DO_UPCAST(NetSocketState, nc, nc);
-    qemu_set_fd_handler(s->fd, NULL, NULL, NULL);
-    close(s->fd);
+    if (s->fd != -1) {
+        qemu_set_fd_handler(s->fd, NULL, NULL, NULL);
+        close(s->fd);
+        s->fd = -1;
+    }
+    if (s->listen_fd != -1) {
+        qemu_set_fd_handler(s->listen_fd, NULL, NULL, NULL);
+        closesocket(s->listen_fd);
+        s->listen_fd = -1;
+    }
 }
 
 static NetClientInfo net_dgram_socket_info = {
@@ -297,6 +313,7 @@ static NetSocketState *net_socket_fd_init_dgram(NetClientState *peer,
     s = DO_UPCAST(NetSocketState, nc, nc);
 
     s->fd = fd;
+    s->listen_fd = -1;
 
     qemu_set_fd_handler(s->fd, net_socket_send_dgram, NULL, s);
 
@@ -340,6 +357,7 @@ static NetSocketState *net_socket_fd_init_stream(NetClientState *peer,
     s = DO_UPCAST(NetSocketState, nc, nc);
 
     s->fd = fd;
+    s->listen_fd = -1;
 
     if (is_connected) {
         net_socket_connect(s);
@@ -377,27 +395,28 @@ static NetSocketState *net_socket_fd_init(NetClientState *peer,
 
 static void net_socket_accept(void *opaque)
 {
-    NetSocketListenState *s = opaque;
-    NetSocketState *s1;
+    NetSocketState *s = opaque;
     struct sockaddr_in saddr;
     socklen_t len;
     int fd;
 
     for(;;) {
         len = sizeof(saddr);
-        fd = qemu_accept(s->fd, (struct sockaddr *)&saddr, &len);
+        fd = qemu_accept(s->listen_fd, (struct sockaddr *)&saddr, &len);
         if (fd < 0 && errno != EINTR) {
             return;
         } else if (fd >= 0) {
+            qemu_set_fd_handler(s->listen_fd, NULL, NULL, NULL);
             break;
         }
     }
-    s1 = net_socket_fd_init(s->peer, s->model, s->name, fd, 1);
-    if (s1) {
-        snprintf(s1->nc.info_str, sizeof(s1->nc.info_str),
-                 "socket: connection from %s:%d",
-                 inet_ntoa(saddr.sin_addr), ntohs(saddr.sin_port));
-    }
+
+    s->fd = fd;
+    s->nc.link_down = false;
+    net_socket_connect(s);
+    snprintf(s->nc.info_str, sizeof(s->nc.info_str),
+             "socket: connection from %s:%d",
+             inet_ntoa(saddr.sin_addr), ntohs(saddr.sin_port));
 }
 
 static int net_socket_listen_init(NetClientState *peer,
@@ -405,19 +424,17 @@ static int net_socket_listen_init(NetClientState *peer,
                                   const char *name,
                                   const char *host_str)
 {
-    NetSocketListenState *s;
-    int fd, val, ret;
+    NetClientState *nc;
+    NetSocketState *s;
     struct sockaddr_in saddr;
+    int fd, val, ret;
 
     if (parse_host_port(&saddr, host_str) < 0)
         return -1;
 
-    s = g_malloc0(sizeof(NetSocketListenState));
-
     fd = qemu_socket(PF_INET, SOCK_STREAM, 0);
     if (fd < 0) {
         perror("socket");
-        g_free(s);
         return -1;
     }
     socket_set_nonblock(fd);
@@ -429,22 +446,23 @@ static int net_socket_listen_init(NetClientState *peer,
     ret = bind(fd, (struct sockaddr *)&saddr, sizeof(saddr));
     if (ret < 0) {
         perror("bind");
-        g_free(s);
         closesocket(fd);
         return -1;
     }
     ret = listen(fd, 0);
     if (ret < 0) {
         perror("listen");
-        g_free(s);
         closesocket(fd);
         return -1;
     }
-    s->peer = peer;
-    s->model = g_strdup(model);
-    s->name = name ? g_strdup(name) : NULL;
-    s->fd = fd;
-    qemu_set_fd_handler(fd, net_socket_accept, NULL, s);
+
+    nc = qemu_new_net_client(&net_socket_info, peer, model, name);
+    s = DO_UPCAST(NetSocketState, nc, nc);
+    s->fd = -1;
+    s->listen_fd = fd;
+    s->nc.link_down = true;
+
+    qemu_set_fd_handler(s->listen_fd, net_socket_accept, NULL, s);
     return 0;
 }
 
commit e34cde35e7c69efcf0bd53d2ff7c90f89a5fc6d0
Author: Zhi Yong Wu <wuzhy at linux.vnet.ibm.com>
Date:   Fri Jul 20 14:25:52 2012 +0100

    net: fix the coding style
    
    Signed-off-by: Zhi Yong Wu <wuzhy at linux.vnet.ibm.com>
    Signed-off-by: Stefan Hajnoczi <stefanha at linux.vnet.ibm.com>
    Reviewed-by: Laszlo Ersek <lersek at redhat.com>

diff --git a/net/socket.c b/net/socket.c
index 65828cd..7857dcd 100644
--- a/net/socket.c
+++ b/net/socket.c
@@ -301,7 +301,9 @@ static NetSocketState *net_socket_fd_init_dgram(NetClientState *peer,
     qemu_set_fd_handler(s->fd, net_socket_send_dgram, NULL, s);
 
     /* mcast: save bound address as dst */
-    if (is_connected) s->dgram_dst=saddr;
+    if (is_connected) {
+        s->dgram_dst = saddr;
+    }
 
     return s;
 
commit 52a3cb869f7e083d135b11da432a52788a25228e
Author: Zhi Yong Wu <wuzhy at linux.vnet.ibm.com>
Date:   Tue Jul 24 16:35:19 2012 +0100

    hub: add the support for hub own flow control
    
    Only when all other hub port's *peer* .can_receive() all return 1,
    the source hub port .can_receive() return 1.
    
    Reviewed-by: Paolo Bonzini <pbonzini at redhat.com>
    Signed-off-by: Zhi Yong Wu <wuzhy at linux.vnet.ibm.com>
    Signed-off-by: Stefan Hajnoczi <stefanha at linux.vnet.ibm.com>
    Reviewed-by: Laszlo Ersek <lersek at redhat.com>

diff --git a/net/hub.c b/net/hub.c
index 522fe99..ac157e3 100644
--- a/net/hub.c
+++ b/net/hub.c
@@ -15,6 +15,7 @@
 #include "monitor.h"
 #include "net.h"
 #include "hub.h"
+#include "iov.h"
 
 /*
  * A hub broadcasts incoming packets to all its ports except the source port.
@@ -59,16 +60,16 @@ static ssize_t net_hub_receive_iov(NetHub *hub, NetHubPort *source_port,
                                    const struct iovec *iov, int iovcnt)
 {
     NetHubPort *port;
-    ssize_t ret = 0;
+    ssize_t len = iov_size(iov, iovcnt);
 
     QLIST_FOREACH(port, &hub->ports, next) {
         if (port == source_port) {
             continue;
         }
 
-        ret = qemu_sendv_packet(&port->nc, iov, iovcnt);
+        qemu_sendv_packet(&port->nc, iov, iovcnt);
     }
-    return ret;
+    return len;
 }
 
 static NetHub *net_hub_new(int id)
@@ -85,6 +86,25 @@ static NetHub *net_hub_new(int id)
     return hub;
 }
 
+static int net_hub_port_can_receive(NetClientState *nc)
+{
+    NetHubPort *port;
+    NetHubPort *src_port = DO_UPCAST(NetHubPort, nc, nc);
+    NetHub *hub = src_port->hub;
+
+    QLIST_FOREACH(port, &hub->ports, next) {
+        if (port == src_port) {
+            continue;
+        }
+
+        if (!qemu_can_send_packet(&port->nc)) {
+            return 0;
+        }
+    }
+
+    return 1;
+}
+
 static ssize_t net_hub_port_receive(NetClientState *nc,
                                     const uint8_t *buf, size_t len)
 {
@@ -111,6 +131,7 @@ static void net_hub_port_cleanup(NetClientState *nc)
 static NetClientInfo net_hub_port_info = {
     .type = NET_CLIENT_OPTIONS_KIND_HUBPORT,
     .size = sizeof(NetHubPort),
+    .can_receive = net_hub_port_can_receive,
     .receive = net_hub_port_receive,
     .receive_iov = net_hub_port_receive_iov,
     .cleanup = net_hub_port_cleanup,
commit 691a4f3a953982d0af1896f5ab2832b7f19a980d
Author: Zhi Yong Wu <wuzhy at linux.vnet.ibm.com>
Date:   Tue Jul 24 16:35:18 2012 +0100

    net: determine if packets can be sent before net queue deliver packets
    
    Reviewed-by: Paolo Bonzini <pbonzini at redhat.com>
    Signed-off-by: Zhi Yong Wu <wuzhy at linux.vnet.ibm.com>
    Signed-off-by: Stefan Hajnoczi <stefanha at linux.vnet.ibm.com>
    Reviewed-by: Laszlo Ersek <lersek at redhat.com>

diff --git a/net/queue.c b/net/queue.c
index 0afd783..e8030aa 100644
--- a/net/queue.c
+++ b/net/queue.c
@@ -176,8 +176,8 @@ ssize_t qemu_net_queue_send(NetQueue *queue,
 {
     ssize_t ret;
 
-    if (queue->delivering) {
-        return qemu_net_queue_append(queue, sender, flags, data, size, NULL);
+    if (queue->delivering || !qemu_can_send_packet(sender)) {
+        return qemu_net_queue_append(queue, sender, flags, data, size, sent_cb);
     }
 
     ret = qemu_net_queue_deliver(queue, sender, flags, data, size);
@@ -200,8 +200,9 @@ ssize_t qemu_net_queue_send_iov(NetQueue *queue,
 {
     ssize_t ret;
 
-    if (queue->delivering) {
-        return qemu_net_queue_append_iov(queue, sender, flags, iov, iovcnt, NULL);
+    if (queue->delivering || !qemu_can_send_packet(sender)) {
+        return qemu_net_queue_append_iov(queue, sender, flags,
+                                         iov, iovcnt, sent_cb);
     }
 
     ret = qemu_net_queue_deliver_iov(queue, sender, flags, iov, iovcnt);
diff --git a/net/slirp.c b/net/slirp.c
index 9d5ca79..08adb97 100644
--- a/net/slirp.c
+++ b/net/slirp.c
@@ -97,13 +97,6 @@ static void slirp_smb_cleanup(SlirpState *s);
 static inline void slirp_smb_cleanup(SlirpState *s) { }
 #endif
 
-int slirp_can_output(void *opaque)
-{
-    SlirpState *s = opaque;
-
-    return qemu_can_send_packet(&s->nc);
-}
-
 void slirp_output(void *opaque, const uint8_t *pkt, int pkt_len)
 {
     SlirpState *s = opaque;
diff --git a/slirp/if.c b/slirp/if.c
index 096cf6f..533295d 100644
--- a/slirp/if.c
+++ b/slirp/if.c
@@ -177,11 +177,6 @@ void if_start(Slirp *slirp)
     }
 
     while (ifm_next) {
-        /* check if we can really output */
-        if (!slirp_can_output(slirp->opaque)) {
-            break;
-        }
-
         ifm = ifm_next;
         from_batchq = next_from_batchq;
 
diff --git a/slirp/libslirp.h b/slirp/libslirp.h
index 77527ad..9b471b5 100644
--- a/slirp/libslirp.h
+++ b/slirp/libslirp.h
@@ -25,7 +25,6 @@ void slirp_select_poll(fd_set *readfds, fd_set *writefds, fd_set *xfds,
 void slirp_input(Slirp *slirp, const uint8_t *pkt, int pkt_len);
 
 /* you must provide the following functions: */
-int slirp_can_output(void *opaque);
 void slirp_output(void *opaque, const uint8_t *pkt, int pkt_len);
 
 int slirp_add_hostfwd(Slirp *slirp, int is_udp,
commit 86a77c3858610a36f1409c657b1768727693d25b
Author: Zhi Yong Wu <wuzhy at linux.vnet.ibm.com>
Date:   Tue Jul 24 16:35:17 2012 +0100

    net: cleanup deliver/deliver_iov func pointers
    
    Reviewed-by: Paolo Bonzini <pbonzini at redhat.com>
    Signed-off-by: Zhi Yong Wu <wuzhy at linux.vnet.ibm.com>
    Signed-off-by: Stefan Hajnoczi <stefanha at linux.vnet.ibm.com>
    Reviewed-by: Laszlo Ersek <lersek at redhat.com>

diff --git a/net.c b/net.c
index 7edb52b..98109e5 100644
--- a/net.c
+++ b/net.c
@@ -184,17 +184,6 @@ static char *assign_name(NetClientState *nc1, const char *model)
     return g_strdup(buf);
 }
 
-static ssize_t qemu_deliver_packet(NetClientState *sender,
-                                   unsigned flags,
-                                   const uint8_t *data,
-                                   size_t size,
-                                   void *opaque);
-static ssize_t qemu_deliver_packet_iov(NetClientState *sender,
-                                       unsigned flags,
-                                       const struct iovec *iov,
-                                       int iovcnt,
-                                       void *opaque);
-
 NetClientState *qemu_new_net_client(NetClientInfo *info,
                                     NetClientState *peer,
                                     const char *model,
@@ -221,9 +210,7 @@ NetClientState *qemu_new_net_client(NetClientInfo *info,
     }
     QTAILQ_INSERT_TAIL(&net_clients, nc, next);
 
-    nc->send_queue = qemu_new_net_queue(qemu_deliver_packet,
-                                        qemu_deliver_packet_iov,
-                                        nc);
+    nc->send_queue = qemu_new_net_queue(nc);
 
     return nc;
 }
@@ -327,11 +314,11 @@ int qemu_can_send_packet(NetClientState *sender)
     return 1;
 }
 
-static ssize_t qemu_deliver_packet(NetClientState *sender,
-                                   unsigned flags,
-                                   const uint8_t *data,
-                                   size_t size,
-                                   void *opaque)
+ssize_t qemu_deliver_packet(NetClientState *sender,
+                            unsigned flags,
+                            const uint8_t *data,
+                            size_t size,
+                            void *opaque)
 {
     NetClientState *nc = opaque;
     ssize_t ret;
@@ -424,11 +411,11 @@ static ssize_t nc_sendv_compat(NetClientState *nc, const struct iovec *iov,
     return nc->info->receive(nc, buffer, offset);
 }
 
-static ssize_t qemu_deliver_packet_iov(NetClientState *sender,
-                                       unsigned flags,
-                                       const struct iovec *iov,
-                                       int iovcnt,
-                                       void *opaque)
+ssize_t qemu_deliver_packet_iov(NetClientState *sender,
+                                unsigned flags,
+                                const struct iovec *iov,
+                                int iovcnt,
+                                void *opaque)
 {
     NetClientState *nc = opaque;
 
diff --git a/net.h b/net.h
index adeef0c..2975056 100644
--- a/net.h
+++ b/net.h
@@ -100,6 +100,17 @@ void qemu_check_nic_model(NICInfo *nd, const char *model);
 int qemu_find_nic_model(NICInfo *nd, const char * const *models,
                         const char *default_model);
 
+ssize_t qemu_deliver_packet(NetClientState *sender,
+                            unsigned flags,
+                            const uint8_t *data,
+                            size_t size,
+                            void *opaque);
+ssize_t qemu_deliver_packet_iov(NetClientState *sender,
+                            unsigned flags,
+                            const struct iovec *iov,
+                            int iovcnt,
+                            void *opaque);
+
 void print_net_client(Monitor *mon, NetClientState *nc);
 void do_info_network(Monitor *mon);
 
diff --git a/net/queue.c b/net/queue.c
index 35c3463..0afd783 100644
--- a/net/queue.c
+++ b/net/queue.c
@@ -23,6 +23,7 @@
 
 #include "net/queue.h"
 #include "qemu-queue.h"
+#include "net.h"
 
 /* The delivery handler may only return zero if it will call
  * qemu_net_queue_flush() when it determines that it is once again able
@@ -48,8 +49,6 @@ struct NetPacket {
 };
 
 struct NetQueue {
-    NetPacketDeliver *deliver;
-    NetPacketDeliverIOV *deliver_iov;
     void *opaque;
 
     QTAILQ_HEAD(packets, NetPacket) packets;
@@ -57,16 +56,12 @@ struct NetQueue {
     unsigned delivering : 1;
 };
 
-NetQueue *qemu_new_net_queue(NetPacketDeliver *deliver,
-                             NetPacketDeliverIOV *deliver_iov,
-                             void *opaque)
+NetQueue *qemu_new_net_queue(void *opaque)
 {
     NetQueue *queue;
 
     queue = g_malloc0(sizeof(NetQueue));
 
-    queue->deliver = deliver;
-    queue->deliver_iov = deliver_iov;
     queue->opaque = opaque;
 
     QTAILQ_INIT(&queue->packets);
@@ -151,7 +146,7 @@ static ssize_t qemu_net_queue_deliver(NetQueue *queue,
     ssize_t ret = -1;
 
     queue->delivering = 1;
-    ret = queue->deliver(sender, flags, data, size, queue->opaque);
+    ret = qemu_deliver_packet(sender, flags, data, size, queue->opaque);
     queue->delivering = 0;
 
     return ret;
@@ -166,7 +161,7 @@ static ssize_t qemu_net_queue_deliver_iov(NetQueue *queue,
     ssize_t ret = -1;
 
     queue->delivering = 1;
-    ret = queue->deliver_iov(sender, flags, iov, iovcnt, queue->opaque);
+    ret = qemu_deliver_packet_iov(sender, flags, iov, iovcnt, queue->opaque);
     queue->delivering = 0;
 
     return ret;
diff --git a/net/queue.h b/net/queue.h
index d8eac0b..9d44a9b 100644
--- a/net/queue.h
+++ b/net/queue.h
@@ -31,24 +31,11 @@ typedef struct NetQueue NetQueue;
 
 typedef void (NetPacketSent) (NetClientState *sender, ssize_t ret);
 
-typedef ssize_t (NetPacketDeliver) (NetClientState *sender,
-                                    unsigned flags,
-                                    const uint8_t *buf,
-                                    size_t size,
-                                    void *opaque);
-
-typedef ssize_t (NetPacketDeliverIOV) (NetClientState *sender,
-                                       unsigned flags,
-                                       const struct iovec *iov,
-                                       int iovcnt,
-                                       void *opaque);
-
 #define QEMU_NET_PACKET_FLAG_NONE  0
 #define QEMU_NET_PACKET_FLAG_RAW  (1<<0)
 
-NetQueue *qemu_new_net_queue(NetPacketDeliver *deliver,
-                             NetPacketDeliverIOV *deliver_iov,
-                             void *opaque);
+NetQueue *qemu_new_net_queue(void *opaque);
+
 void qemu_del_net_queue(NetQueue *queue);
 
 ssize_t qemu_net_queue_send(NetQueue *queue,
commit 1a8595931ac6ffb76c2e10675ba3a39e807f02fd
Author: Zhi Yong Wu <wuzhy at linux.vnet.ibm.com>
Date:   Tue Jul 24 16:35:16 2012 +0100

    net: Make "info network" output more readable info
    
    Reviewed-by: Jan Kiszka  <jan.kiszka at siemens.com>
    Signed-off-by: Zhi Yong Wu <wuzhy at linux.vnet.ibm.com>
    Signed-off-by: Stefan Hajnoczi <stefanha at linux.vnet.ibm.com>
    Reviewed-by: Laszlo Ersek <lersek at redhat.com>

diff --git a/net.c b/net.c
index 88ccb2e..7edb52b 100644
--- a/net.c
+++ b/net.c
@@ -855,7 +855,7 @@ void qmp_netdev_del(const char *id, Error **errp)
     qemu_opts_del(qemu_opts_find(qemu_find_opts_err("netdev", errp), id));
 }
 
-static void print_net_client(Monitor *mon, NetClientState *nc)
+void print_net_client(Monitor *mon, NetClientState *nc)
 {
     monitor_printf(mon, "%s: type=%s,%s\n", nc->name,
                    NetClientOptionsKind_lookup[nc->info->type], nc->info_str);
@@ -866,20 +866,25 @@ void do_info_network(Monitor *mon)
     NetClientState *nc, *peer;
     NetClientOptionsKind type;
 
-    monitor_printf(mon, "Devices not on any VLAN:\n");
+    net_hub_info(mon);
+
     QTAILQ_FOREACH(nc, &net_clients, next) {
         peer = nc->peer;
         type = nc->info->type;
+
+        /* Skip if already printed in hub info */
+        if (net_hub_id_for_client(nc, NULL) == 0) {
+            continue;
+        }
+
         if (!peer || type == NET_CLIENT_OPTIONS_KIND_NIC) {
-            monitor_printf(mon, "  ");
             print_net_client(mon, nc);
         } /* else it's a netdev connected to a NIC, printed with the NIC */
         if (peer && type == NET_CLIENT_OPTIONS_KIND_NIC) {
-            monitor_printf(mon, "   \\ ");
+            monitor_printf(mon, " \\ ");
             print_net_client(mon, peer);
         }
     }
-    net_hub_info(mon);
 }
 
 void qmp_set_link(const char *name, bool up, Error **errp)
diff --git a/net.h b/net.h
index 7e629d3..adeef0c 100644
--- a/net.h
+++ b/net.h
@@ -100,6 +100,7 @@ void qemu_check_nic_model(NICInfo *nd, const char *model);
 int qemu_find_nic_model(NICInfo *nd, const char * const *models,
                         const char *default_model);
 
+void print_net_client(Monitor *mon, NetClientState *nc);
 void do_info_network(Monitor *mon);
 
 /* NIC info */
diff --git a/net/hub.c b/net/hub.c
index 900fa4e..522fe99 100644
--- a/net/hub.c
+++ b/net/hub.c
@@ -223,8 +223,10 @@ void net_hub_info(Monitor *mon)
     QLIST_FOREACH(hub, &hubs, next) {
         monitor_printf(mon, "hub %d\n", hub->id);
         QLIST_FOREACH(port, &hub->ports, next) {
-            monitor_printf(mon, "    port %d peer %s\n", port->id,
-                           port->nc.peer ? port->nc.peer->name : "<none>");
+            if (port->nc.peer) {
+                monitor_printf(mon, " \\ ");
+                print_net_client(mon, port->nc.peer);
+            }
         }
     }
 }
commit b20c6b9e47772b9162ed194e7b2884afa6a354ab
Author: Stefan Hajnoczi <stefanha at linux.vnet.ibm.com>
Date:   Tue Jul 24 16:35:15 2012 +0100

    net: Rename qemu_del_vlan_client() to qemu_del_net_client()
    
    Another step in moving the vlan feature out of net core.  Users only
    deal with NetClientState and therefore qemu_del_vlan_client() should be
    named qemu_del_net_client().
    
    Signed-off-by: Stefan Hajnoczi <stefanha at linux.vnet.ibm.com>
    Signed-off-by: Zhi Yong Wu <wuzhy at linux.vnet.ibm.com>
    Reviewed-by: Laszlo Ersek <lersek at redhat.com>

diff --git a/hw/e1000.c b/hw/e1000.c
index 531b69a..ae8a6c5 100644
--- a/hw/e1000.c
+++ b/hw/e1000.c
@@ -1201,7 +1201,7 @@ pci_e1000_uninit(PCIDevice *dev)
     qemu_free_timer(d->autoneg_timer);
     memory_region_destroy(&d->mmio);
     memory_region_destroy(&d->io);
-    qemu_del_vlan_client(&d->nic->nc);
+    qemu_del_net_client(&d->nic->nc);
 }
 
 static NetClientInfo net_e1000_info = {
diff --git a/hw/eepro100.c b/hw/eepro100.c
index c2b0a2d..50d117e 100644
--- a/hw/eepro100.c
+++ b/hw/eepro100.c
@@ -1847,7 +1847,7 @@ static void pci_nic_uninit(PCIDevice *pci_dev)
     memory_region_destroy(&s->flash_bar);
     vmstate_unregister(&pci_dev->qdev, s->vmstate, s);
     eeprom93xx_free(&pci_dev->qdev, s->eeprom);
-    qemu_del_vlan_client(&s->nic->nc);
+    qemu_del_net_client(&s->nic->nc);
 }
 
 static NetClientInfo net_eepro100_info = {
diff --git a/hw/ne2000.c b/hw/ne2000.c
index 2131770..15605c4 100644
--- a/hw/ne2000.c
+++ b/hw/ne2000.c
@@ -750,7 +750,7 @@ static void pci_ne2000_exit(PCIDevice *pci_dev)
     NE2000State *s = &d->ne2000;
 
     memory_region_destroy(&s->io);
-    qemu_del_vlan_client(&s->nic->nc);
+    qemu_del_net_client(&s->nic->nc);
 }
 
 static Property ne2000_properties[] = {
diff --git a/hw/pcnet-pci.c b/hw/pcnet-pci.c
index d58cffd..48fd447 100644
--- a/hw/pcnet-pci.c
+++ b/hw/pcnet-pci.c
@@ -279,7 +279,7 @@ static void pci_pcnet_uninit(PCIDevice *dev)
     memory_region_destroy(&d->io_bar);
     qemu_del_timer(d->state.poll_timer);
     qemu_free_timer(d->state.poll_timer);
-    qemu_del_vlan_client(&d->state.nic->nc);
+    qemu_del_net_client(&d->state.nic->nc);
 }
 
 static NetClientInfo net_pci_pcnet_info = {
diff --git a/hw/rtl8139.c b/hw/rtl8139.c
index 619e6c0..844f1b8 100644
--- a/hw/rtl8139.c
+++ b/hw/rtl8139.c
@@ -3450,7 +3450,7 @@ static void pci_rtl8139_uninit(PCIDevice *dev)
     }
     qemu_del_timer(s->timer);
     qemu_free_timer(s->timer);
-    qemu_del_vlan_client(&s->nic->nc);
+    qemu_del_net_client(&s->nic->nc);
 }
 
 static NetClientInfo net_rtl8139_info = {
diff --git a/hw/usb/dev-network.c b/hw/usb/dev-network.c
index 6c2edbe..c84892c 100644
--- a/hw/usb/dev-network.c
+++ b/hw/usb/dev-network.c
@@ -1309,7 +1309,7 @@ static void usb_net_handle_destroy(USBDevice *dev)
 
     /* TODO: remove the nd_table[] entry */
     rndis_clear_responsequeue(s);
-    qemu_del_vlan_client(&s->nic->nc);
+    qemu_del_net_client(&s->nic->nc);
 }
 
 static NetClientInfo net_usbnet_info = {
diff --git a/hw/virtio-net.c b/hw/virtio-net.c
index a83eade..b1998b2 100644
--- a/hw/virtio-net.c
+++ b/hw/virtio-net.c
@@ -1077,6 +1077,6 @@ void virtio_net_exit(VirtIODevice *vdev)
         qemu_bh_delete(n->tx_bh);
     }
 
-    qemu_del_vlan_client(&n->nic->nc);
+    qemu_del_net_client(&n->nic->nc);
     virtio_cleanup(&n->vdev);
 }
diff --git a/hw/xen_nic.c b/hw/xen_nic.c
index c81191d..8b79bfb 100644
--- a/hw/xen_nic.c
+++ b/hw/xen_nic.c
@@ -406,7 +406,7 @@ static void net_disconnect(struct XenDevice *xendev)
         netdev->rxs = NULL;
     }
     if (netdev->nic) {
-        qemu_del_vlan_client(&netdev->nic->nc);
+        qemu_del_net_client(&netdev->nic->nc);
         netdev->nic = NULL;
     }
 }
diff --git a/net.c b/net.c
index 8aebf8c..88ccb2e 100644
--- a/net.c
+++ b/net.c
@@ -249,7 +249,7 @@ NICState *qemu_new_nic(NetClientInfo *info,
     return nic;
 }
 
-static void qemu_cleanup_vlan_client(NetClientState *nc)
+static void qemu_cleanup_net_client(NetClientState *nc)
 {
     QTAILQ_REMOVE(&net_clients, nc, next);
 
@@ -258,7 +258,7 @@ static void qemu_cleanup_vlan_client(NetClientState *nc)
     }
 }
 
-static void qemu_free_vlan_client(NetClientState *nc)
+static void qemu_free_net_client(NetClientState *nc)
 {
     if (nc->send_queue) {
         qemu_del_net_queue(nc->send_queue);
@@ -271,7 +271,7 @@ static void qemu_free_vlan_client(NetClientState *nc)
     g_free(nc);
 }
 
-void qemu_del_vlan_client(NetClientState *nc)
+void qemu_del_net_client(NetClientState *nc)
 {
     /* If there is a peer NIC, delete and cleanup client, but do not free. */
     if (nc->peer && nc->peer->info->type == NET_CLIENT_OPTIONS_KIND_NIC) {
@@ -285,7 +285,7 @@ void qemu_del_vlan_client(NetClientState *nc)
         if (nc->peer->info->link_status_changed) {
             nc->peer->info->link_status_changed(nc->peer);
         }
-        qemu_cleanup_vlan_client(nc);
+        qemu_cleanup_net_client(nc);
         return;
     }
 
@@ -293,12 +293,12 @@ void qemu_del_vlan_client(NetClientState *nc)
     if (nc->peer && nc->info->type == NET_CLIENT_OPTIONS_KIND_NIC) {
         NICState *nic = DO_UPCAST(NICState, nc, nc);
         if (nic->peer_deleted) {
-            qemu_free_vlan_client(nc->peer);
+            qemu_free_net_client(nc->peer);
         }
     }
 
-    qemu_cleanup_vlan_client(nc);
-    qemu_free_vlan_client(nc);
+    qemu_cleanup_net_client(nc);
+    qemu_free_net_client(nc);
 }
 
 void qemu_foreach_nic(qemu_nic_foreach func, void *opaque)
@@ -803,7 +803,7 @@ void net_host_device_remove(Monitor *mon, const QDict *qdict)
         monitor_printf(mon, "invalid host network device %s\n", device);
         return;
     }
-    qemu_del_vlan_client(nc);
+    qemu_del_net_client(nc);
 }
 
 void netdev_add(QemuOpts *opts, Error **errp)
@@ -851,7 +851,7 @@ void qmp_netdev_del(const char *id, Error **errp)
         return;
     }
 
-    qemu_del_vlan_client(nc);
+    qemu_del_net_client(nc);
     qemu_opts_del(qemu_opts_find(qemu_find_opts_err("netdev", errp), id));
 }
 
@@ -920,7 +920,7 @@ void net_cleanup(void)
     NetClientState *nc, *next_vc;
 
     QTAILQ_FOREACH_SAFE(nc, &net_clients, next, next_vc) {
-        qemu_del_vlan_client(nc);
+        qemu_del_net_client(nc);
     }
 }
 
diff --git a/net.h b/net.h
index d368e24..7e629d3 100644
--- a/net.h
+++ b/net.h
@@ -77,7 +77,7 @@ NICState *qemu_new_nic(NetClientInfo *info,
                        const char *model,
                        const char *name,
                        void *opaque);
-void qemu_del_vlan_client(NetClientState *nc);
+void qemu_del_net_client(NetClientState *nc);
 NetClientState *qemu_find_vlan_client_by_name(Monitor *mon, int vlan_id,
                                               const char *client_str);
 typedef void (*qemu_nic_foreach)(NICState *nic, void *opaque);
diff --git a/net/slirp.c b/net/slirp.c
index 1bdad37..9d5ca79 100644
--- a/net/slirp.c
+++ b/net/slirp.c
@@ -275,7 +275,7 @@ static int net_slirp_init(NetClientState *peer, const char *model,
     return 0;
 
 error:
-    qemu_del_vlan_client(nc);
+    qemu_del_net_client(nc);
     return -1;
 }
 
commit 35277d14ece1a68dc45cbc8c5af8f469c5c49549
Author: Stefan Hajnoczi <stefanha at linux.vnet.ibm.com>
Date:   Tue Jul 24 16:35:14 2012 +0100

    net: Rename vc local variables to nc
    
    Now that VLANClientState has been renamed to NetClientState all 'vc'
    local variables should be 'nc'.  Much of the code already used 'nc' but
    there are places where 'vc' needs to be renamed.
    
    Signed-off-by: Stefan Hajnoczi <stefanha at linux.vnet.ibm.com>
    Signed-off-by: Zhi Yong Wu <wuzhy at linux.vnet.ibm.com>
    Reviewed-by: Laszlo Ersek <lersek at redhat.com>

diff --git a/hw/ne2000.h b/hw/ne2000.h
index 6c196a2..1e7ab07 100644
--- a/hw/ne2000.h
+++ b/hw/ne2000.h
@@ -31,5 +31,5 @@ typedef struct NE2000State {
 void ne2000_setup_io(NE2000State *s, unsigned size);
 extern const VMStateDescription vmstate_ne2000;
 void ne2000_reset(NE2000State *s);
-int ne2000_can_receive(NetClientState *vc);
-ssize_t ne2000_receive(NetClientState *vc, const uint8_t *buf, size_t size_);
+int ne2000_can_receive(NetClientState *nc);
+ssize_t ne2000_receive(NetClientState *nc, const uint8_t *buf, size_t size_);
diff --git a/hw/vhost_net.c b/hw/vhost_net.c
index 85a9a4e..ecaa22d 100644
--- a/hw/vhost_net.c
+++ b/hw/vhost_net.c
@@ -42,7 +42,7 @@ struct vhost_net {
     struct vhost_dev dev;
     struct vhost_virtqueue vqs[2];
     int backend;
-    NetClientState *vc;
+    NetClientState *nc;
 };
 
 unsigned vhost_net_get_features(struct vhost_net *net, unsigned features)
@@ -104,7 +104,7 @@ struct vhost_net *vhost_net_init(NetClientState *backend, int devfd,
     if (r < 0) {
         goto fail;
     }
-    net->vc = backend;
+    net->nc = backend;
     net->dev.backend_features = tap_has_vnet_hdr(backend) ? 0 :
         (1 << VHOST_NET_F_VIRTIO_NET_HDR);
     net->backend = r;
@@ -151,7 +151,7 @@ int vhost_net_start(struct vhost_net *net,
         goto fail_notifiers;
     }
     if (net->dev.acked_features & (1 << VIRTIO_NET_F_MRG_RXBUF)) {
-        tap_set_vnet_hdr_len(net->vc,
+        tap_set_vnet_hdr_len(net->nc,
                              sizeof(struct virtio_net_hdr_mrg_rxbuf));
     }
 
@@ -160,7 +160,7 @@ int vhost_net_start(struct vhost_net *net,
         goto fail_start;
     }
 
-    net->vc->info->poll(net->vc, false);
+    net->nc->info->poll(net->nc, false);
     qemu_set_fd_handler(net->backend, NULL, NULL, NULL);
     file.fd = net->backend;
     for (file.index = 0; file.index < net->dev.nvqs; ++file.index) {
@@ -177,10 +177,10 @@ fail:
         int r = ioctl(net->dev.control, VHOST_NET_SET_BACKEND, &file);
         assert(r >= 0);
     }
-    net->vc->info->poll(net->vc, true);
+    net->nc->info->poll(net->nc, true);
     vhost_dev_stop(&net->dev, dev);
     if (net->dev.acked_features & (1 << VIRTIO_NET_F_MRG_RXBUF)) {
-        tap_set_vnet_hdr_len(net->vc, sizeof(struct virtio_net_hdr));
+        tap_set_vnet_hdr_len(net->nc, sizeof(struct virtio_net_hdr));
     }
 fail_start:
     vhost_dev_disable_notifiers(&net->dev, dev);
@@ -197,10 +197,10 @@ void vhost_net_stop(struct vhost_net *net,
         int r = ioctl(net->dev.control, VHOST_NET_SET_BACKEND, &file);
         assert(r >= 0);
     }
-    net->vc->info->poll(net->vc, true);
+    net->nc->info->poll(net->nc, true);
     vhost_dev_stop(&net->dev, dev);
     if (net->dev.acked_features & (1 << VIRTIO_NET_F_MRG_RXBUF)) {
-        tap_set_vnet_hdr_len(net->vc, sizeof(struct virtio_net_hdr));
+        tap_set_vnet_hdr_len(net->nc, sizeof(struct virtio_net_hdr));
     }
     vhost_dev_disable_notifiers(&net->dev, dev);
 }
@@ -209,7 +209,7 @@ void vhost_net_cleanup(struct vhost_net *net)
 {
     vhost_dev_cleanup(&net->dev);
     if (net->dev.acked_features & (1 << VIRTIO_NET_F_MRG_RXBUF)) {
-        tap_set_vnet_hdr_len(net->vc, sizeof(struct virtio_net_hdr));
+        tap_set_vnet_hdr_len(net->nc, sizeof(struct virtio_net_hdr));
     }
     g_free(net);
 }
diff --git a/net.c b/net.c
index 33896fe..8aebf8c 100644
--- a/net.c
+++ b/net.c
@@ -132,11 +132,11 @@ int parse_host_port(struct sockaddr_in *saddr, const char *str)
     return 0;
 }
 
-void qemu_format_nic_info_str(NetClientState *vc, uint8_t macaddr[6])
+void qemu_format_nic_info_str(NetClientState *nc, uint8_t macaddr[6])
 {
-    snprintf(vc->info_str, sizeof(vc->info_str),
+    snprintf(nc->info_str, sizeof(nc->info_str),
              "model=%s,macaddr=%02x:%02x:%02x:%02x:%02x:%02x",
-             vc->model,
+             nc->model,
              macaddr[0], macaddr[1], macaddr[2],
              macaddr[3], macaddr[4], macaddr[5]);
 }
@@ -162,19 +162,19 @@ void qemu_macaddr_default_if_unset(MACAddr *macaddr)
  * Only net clients created with the legacy -net option need this.  Naming is
  * mandatory for net clients created with -netdev.
  */
-static char *assign_name(NetClientState *vc1, const char *model)
+static char *assign_name(NetClientState *nc1, const char *model)
 {
-    NetClientState *vc;
+    NetClientState *nc;
     char buf[256];
     int id = 0;
 
-    QTAILQ_FOREACH(vc, &net_clients, next) {
-        if (vc == vc1) {
+    QTAILQ_FOREACH(nc, &net_clients, next) {
+        if (nc == nc1) {
             continue;
         }
         /* For compatibility only bump id for net clients on a vlan */
-        if (strcmp(vc->model, model) == 0 &&
-            net_hub_id_for_client(vc, NULL) == 0) {
+        if (strcmp(nc->model, model) == 0 &&
+            net_hub_id_for_client(nc, NULL) == 0) {
             id++;
         }
     }
@@ -200,32 +200,32 @@ NetClientState *qemu_new_net_client(NetClientInfo *info,
                                     const char *model,
                                     const char *name)
 {
-    NetClientState *vc;
+    NetClientState *nc;
 
     assert(info->size >= sizeof(NetClientState));
 
-    vc = g_malloc0(info->size);
+    nc = g_malloc0(info->size);
 
-    vc->info = info;
-    vc->model = g_strdup(model);
+    nc->info = info;
+    nc->model = g_strdup(model);
     if (name) {
-        vc->name = g_strdup(name);
+        nc->name = g_strdup(name);
     } else {
-        vc->name = assign_name(vc, model);
+        nc->name = assign_name(nc, model);
     }
 
     if (peer) {
         assert(!peer->peer);
-        vc->peer = peer;
-        peer->peer = vc;
+        nc->peer = peer;
+        peer->peer = nc;
     }
-    QTAILQ_INSERT_TAIL(&net_clients, vc, next);
+    QTAILQ_INSERT_TAIL(&net_clients, nc, next);
 
-    vc->send_queue = qemu_new_net_queue(qemu_deliver_packet,
+    nc->send_queue = qemu_new_net_queue(qemu_deliver_packet,
                                         qemu_deliver_packet_iov,
-                                        vc);
+                                        nc);
 
-    return vc;
+    return nc;
 }
 
 NICState *qemu_new_nic(NetClientInfo *info,
@@ -249,56 +249,56 @@ NICState *qemu_new_nic(NetClientInfo *info,
     return nic;
 }
 
-static void qemu_cleanup_vlan_client(NetClientState *vc)
+static void qemu_cleanup_vlan_client(NetClientState *nc)
 {
-    QTAILQ_REMOVE(&net_clients, vc, next);
+    QTAILQ_REMOVE(&net_clients, nc, next);
 
-    if (vc->info->cleanup) {
-        vc->info->cleanup(vc);
+    if (nc->info->cleanup) {
+        nc->info->cleanup(nc);
     }
 }
 
-static void qemu_free_vlan_client(NetClientState *vc)
+static void qemu_free_vlan_client(NetClientState *nc)
 {
-    if (vc->send_queue) {
-        qemu_del_net_queue(vc->send_queue);
+    if (nc->send_queue) {
+        qemu_del_net_queue(nc->send_queue);
     }
-    if (vc->peer) {
-        vc->peer->peer = NULL;
+    if (nc->peer) {
+        nc->peer->peer = NULL;
     }
-    g_free(vc->name);
-    g_free(vc->model);
-    g_free(vc);
+    g_free(nc->name);
+    g_free(nc->model);
+    g_free(nc);
 }
 
-void qemu_del_vlan_client(NetClientState *vc)
+void qemu_del_vlan_client(NetClientState *nc)
 {
     /* If there is a peer NIC, delete and cleanup client, but do not free. */
-    if (vc->peer && vc->peer->info->type == NET_CLIENT_OPTIONS_KIND_NIC) {
-        NICState *nic = DO_UPCAST(NICState, nc, vc->peer);
+    if (nc->peer && nc->peer->info->type == NET_CLIENT_OPTIONS_KIND_NIC) {
+        NICState *nic = DO_UPCAST(NICState, nc, nc->peer);
         if (nic->peer_deleted) {
             return;
         }
         nic->peer_deleted = true;
         /* Let NIC know peer is gone. */
-        vc->peer->link_down = true;
-        if (vc->peer->info->link_status_changed) {
-            vc->peer->info->link_status_changed(vc->peer);
+        nc->peer->link_down = true;
+        if (nc->peer->info->link_status_changed) {
+            nc->peer->info->link_status_changed(nc->peer);
         }
-        qemu_cleanup_vlan_client(vc);
+        qemu_cleanup_vlan_client(nc);
         return;
     }
 
     /* If this is a peer NIC and peer has already been deleted, free it now. */
-    if (vc->peer && vc->info->type == NET_CLIENT_OPTIONS_KIND_NIC) {
-        NICState *nic = DO_UPCAST(NICState, nc, vc);
+    if (nc->peer && nc->info->type == NET_CLIENT_OPTIONS_KIND_NIC) {
+        NICState *nic = DO_UPCAST(NICState, nc, nc);
         if (nic->peer_deleted) {
-            qemu_free_vlan_client(vc->peer);
+            qemu_free_vlan_client(nc->peer);
         }
     }
 
-    qemu_cleanup_vlan_client(vc);
-    qemu_free_vlan_client(vc);
+    qemu_cleanup_vlan_client(nc);
+    qemu_free_vlan_client(nc);
 }
 
 void qemu_foreach_nic(qemu_nic_foreach func, void *opaque)
@@ -333,44 +333,44 @@ static ssize_t qemu_deliver_packet(NetClientState *sender,
                                    size_t size,
                                    void *opaque)
 {
-    NetClientState *vc = opaque;
+    NetClientState *nc = opaque;
     ssize_t ret;
 
-    if (vc->link_down) {
+    if (nc->link_down) {
         return size;
     }
 
-    if (vc->receive_disabled) {
+    if (nc->receive_disabled) {
         return 0;
     }
 
-    if (flags & QEMU_NET_PACKET_FLAG_RAW && vc->info->receive_raw) {
-        ret = vc->info->receive_raw(vc, data, size);
+    if (flags & QEMU_NET_PACKET_FLAG_RAW && nc->info->receive_raw) {
+        ret = nc->info->receive_raw(nc, data, size);
     } else {
-        ret = vc->info->receive(vc, data, size);
+        ret = nc->info->receive(nc, data, size);
     }
 
     if (ret == 0) {
-        vc->receive_disabled = 1;
+        nc->receive_disabled = 1;
     };
 
     return ret;
 }
 
-void qemu_purge_queued_packets(NetClientState *vc)
+void qemu_purge_queued_packets(NetClientState *nc)
 {
-    if (!vc->peer) {
+    if (!nc->peer) {
         return;
     }
 
-    qemu_net_queue_purge(vc->peer->send_queue, vc);
+    qemu_net_queue_purge(nc->peer->send_queue, nc);
 }
 
-void qemu_flush_queued_packets(NetClientState *vc)
+void qemu_flush_queued_packets(NetClientState *nc)
 {
-    vc->receive_disabled = 0;
+    nc->receive_disabled = 0;
 
-    qemu_net_queue_flush(vc->send_queue);
+    qemu_net_queue_flush(nc->send_queue);
 }
 
 static ssize_t qemu_send_packet_async_with_flags(NetClientState *sender,
@@ -402,18 +402,18 @@ ssize_t qemu_send_packet_async(NetClientState *sender,
                                              buf, size, sent_cb);
 }
 
-void qemu_send_packet(NetClientState *vc, const uint8_t *buf, int size)
+void qemu_send_packet(NetClientState *nc, const uint8_t *buf, int size)
 {
-    qemu_send_packet_async(vc, buf, size, NULL);
+    qemu_send_packet_async(nc, buf, size, NULL);
 }
 
-ssize_t qemu_send_packet_raw(NetClientState *vc, const uint8_t *buf, int size)
+ssize_t qemu_send_packet_raw(NetClientState *nc, const uint8_t *buf, int size)
 {
-    return qemu_send_packet_async_with_flags(vc, QEMU_NET_PACKET_FLAG_RAW,
+    return qemu_send_packet_async_with_flags(nc, QEMU_NET_PACKET_FLAG_RAW,
                                              buf, size, NULL);
 }
 
-static ssize_t vc_sendv_compat(NetClientState *vc, const struct iovec *iov,
+static ssize_t nc_sendv_compat(NetClientState *nc, const struct iovec *iov,
                                int iovcnt)
 {
     uint8_t buffer[4096];
@@ -421,7 +421,7 @@ static ssize_t vc_sendv_compat(NetClientState *vc, const struct iovec *iov,
 
     offset = iov_to_buf(iov, iovcnt, 0, buffer, sizeof(buffer));
 
-    return vc->info->receive(vc, buffer, offset);
+    return nc->info->receive(nc, buffer, offset);
 }
 
 static ssize_t qemu_deliver_packet_iov(NetClientState *sender,
@@ -430,16 +430,16 @@ static ssize_t qemu_deliver_packet_iov(NetClientState *sender,
                                        int iovcnt,
                                        void *opaque)
 {
-    NetClientState *vc = opaque;
+    NetClientState *nc = opaque;
 
-    if (vc->link_down) {
+    if (nc->link_down) {
         return iov_size(iov, iovcnt);
     }
 
-    if (vc->info->receive_iov) {
-        return vc->info->receive_iov(vc, iov, iovcnt);
+    if (nc->info->receive_iov) {
+        return nc->info->receive_iov(nc, iov, iovcnt);
     } else {
-        return vc_sendv_compat(vc, iov, iovcnt);
+        return nc_sendv_compat(nc, iov, iovcnt);
     }
 }
 
@@ -461,20 +461,20 @@ ssize_t qemu_sendv_packet_async(NetClientState *sender,
 }
 
 ssize_t
-qemu_sendv_packet(NetClientState *vc, const struct iovec *iov, int iovcnt)
+qemu_sendv_packet(NetClientState *nc, const struct iovec *iov, int iovcnt)
 {
-    return qemu_sendv_packet_async(vc, iov, iovcnt, NULL);
+    return qemu_sendv_packet_async(nc, iov, iovcnt, NULL);
 }
 
 NetClientState *qemu_find_netdev(const char *id)
 {
-    NetClientState *vc;
+    NetClientState *nc;
 
-    QTAILQ_FOREACH(vc, &net_clients, next) {
-        if (vc->info->type == NET_CLIENT_OPTIONS_KIND_NIC)
+    QTAILQ_FOREACH(nc, &net_clients, next) {
+        if (nc->info->type == NET_CLIENT_OPTIONS_KIND_NIC)
             continue;
-        if (!strcmp(vc->name, id)) {
-            return vc;
+        if (!strcmp(nc->name, id)) {
+            return nc;
         }
     }
 
@@ -791,19 +791,19 @@ void net_host_device_add(Monitor *mon, const QDict *qdict)
 
 void net_host_device_remove(Monitor *mon, const QDict *qdict)
 {
-    NetClientState *vc;
+    NetClientState *nc;
     int vlan_id = qdict_get_int(qdict, "vlan_id");
     const char *device = qdict_get_str(qdict, "device");
 
-    vc = net_hub_find_client_by_name(vlan_id, device);
-    if (!vc) {
+    nc = net_hub_find_client_by_name(vlan_id, device);
+    if (!nc) {
         return;
     }
-    if (!net_host_check_device(vc->model)) {
+    if (!net_host_check_device(nc->model)) {
         monitor_printf(mon, "invalid host network device %s\n", device);
         return;
     }
-    qemu_del_vlan_client(vc);
+    qemu_del_vlan_client(nc);
 }
 
 void netdev_add(QemuOpts *opts, Error **errp)
@@ -843,36 +843,36 @@ exit_err:
 
 void qmp_netdev_del(const char *id, Error **errp)
 {
-    NetClientState *vc;
+    NetClientState *nc;
 
-    vc = qemu_find_netdev(id);
-    if (!vc) {
+    nc = qemu_find_netdev(id);
+    if (!nc) {
         error_set(errp, QERR_DEVICE_NOT_FOUND, id);
         return;
     }
 
-    qemu_del_vlan_client(vc);
+    qemu_del_vlan_client(nc);
     qemu_opts_del(qemu_opts_find(qemu_find_opts_err("netdev", errp), id));
 }
 
-static void print_net_client(Monitor *mon, NetClientState *vc)
+static void print_net_client(Monitor *mon, NetClientState *nc)
 {
-    monitor_printf(mon, "%s: type=%s,%s\n", vc->name,
-                   NetClientOptionsKind_lookup[vc->info->type], vc->info_str);
+    monitor_printf(mon, "%s: type=%s,%s\n", nc->name,
+                   NetClientOptionsKind_lookup[nc->info->type], nc->info_str);
 }
 
 void do_info_network(Monitor *mon)
 {
-    NetClientState *vc, *peer;
+    NetClientState *nc, *peer;
     NetClientOptionsKind type;
 
     monitor_printf(mon, "Devices not on any VLAN:\n");
-    QTAILQ_FOREACH(vc, &net_clients, next) {
-        peer = vc->peer;
-        type = vc->info->type;
+    QTAILQ_FOREACH(nc, &net_clients, next) {
+        peer = nc->peer;
+        type = nc->info->type;
         if (!peer || type == NET_CLIENT_OPTIONS_KIND_NIC) {
             monitor_printf(mon, "  ");
-            print_net_client(mon, vc);
+            print_net_client(mon, nc);
         } /* else it's a netdev connected to a NIC, printed with the NIC */
         if (peer && type == NET_CLIENT_OPTIONS_KIND_NIC) {
             monitor_printf(mon, "   \\ ");
@@ -884,23 +884,23 @@ void do_info_network(Monitor *mon)
 
 void qmp_set_link(const char *name, bool up, Error **errp)
 {
-    NetClientState *vc = NULL;
+    NetClientState *nc = NULL;
 
-    QTAILQ_FOREACH(vc, &net_clients, next) {
-        if (!strcmp(vc->name, name)) {
+    QTAILQ_FOREACH(nc, &net_clients, next) {
+        if (!strcmp(nc->name, name)) {
             goto done;
         }
     }
 done:
-    if (!vc) {
+    if (!nc) {
         error_set(errp, QERR_DEVICE_NOT_FOUND, name);
         return;
     }
 
-    vc->link_down = !up;
+    nc->link_down = !up;
 
-    if (vc->info->link_status_changed) {
-        vc->info->link_status_changed(vc);
+    if (nc->info->link_status_changed) {
+        nc->info->link_status_changed(nc);
     }
 
     /* Notify peer. Don't update peer link status: this makes it possible to
@@ -910,23 +910,23 @@ done:
      * Current behaviour is compatible with qemu vlans where there could be
      * multiple clients that can still communicate with each other in
      * disconnected mode. For now maintain this compatibility. */
-    if (vc->peer && vc->peer->info->link_status_changed) {
-        vc->peer->info->link_status_changed(vc->peer);
+    if (nc->peer && nc->peer->info->link_status_changed) {
+        nc->peer->info->link_status_changed(nc->peer);
     }
 }
 
 void net_cleanup(void)
 {
-    NetClientState *vc, *next_vc;
+    NetClientState *nc, *next_vc;
 
-    QTAILQ_FOREACH_SAFE(vc, &net_clients, next, next_vc) {
-        qemu_del_vlan_client(vc);
+    QTAILQ_FOREACH_SAFE(nc, &net_clients, next, next_vc) {
+        qemu_del_vlan_client(nc);
     }
 }
 
 void net_check_clients(void)
 {
-    NetClientState *vc;
+    NetClientState *nc;
     int i;
 
     /* Don't warn about the default network setup that you get if
@@ -943,11 +943,11 @@ void net_check_clients(void)
 
     net_hub_check_clients();
 
-    QTAILQ_FOREACH(vc, &net_clients, next) {
-        if (!vc->peer) {
+    QTAILQ_FOREACH(nc, &net_clients, next) {
+        if (!nc->peer) {
             fprintf(stderr, "Warning: %s %s has no peer\n",
-                    vc->info->type == NET_CLIENT_OPTIONS_KIND_NIC ? "nic" : "netdev",
-                    vc->name);
+                    nc->info->type == NET_CLIENT_OPTIONS_KIND_NIC ?
+                    "nic" : "netdev", nc->name);
         }
     }
 
diff --git a/net.h b/net.h
index 5857e87..d368e24 100644
--- a/net.h
+++ b/net.h
@@ -77,23 +77,23 @@ NICState *qemu_new_nic(NetClientInfo *info,
                        const char *model,
                        const char *name,
                        void *opaque);
-void qemu_del_vlan_client(NetClientState *vc);
+void qemu_del_vlan_client(NetClientState *nc);
 NetClientState *qemu_find_vlan_client_by_name(Monitor *mon, int vlan_id,
                                               const char *client_str);
 typedef void (*qemu_nic_foreach)(NICState *nic, void *opaque);
 void qemu_foreach_nic(qemu_nic_foreach func, void *opaque);
-int qemu_can_send_packet(NetClientState *vc);
-ssize_t qemu_sendv_packet(NetClientState *vc, const struct iovec *iov,
+int qemu_can_send_packet(NetClientState *nc);
+ssize_t qemu_sendv_packet(NetClientState *nc, const struct iovec *iov,
                           int iovcnt);
-ssize_t qemu_sendv_packet_async(NetClientState *vc, const struct iovec *iov,
+ssize_t qemu_sendv_packet_async(NetClientState *nc, const struct iovec *iov,
                                 int iovcnt, NetPacketSent *sent_cb);
-void qemu_send_packet(NetClientState *vc, const uint8_t *buf, int size);
-ssize_t qemu_send_packet_raw(NetClientState *vc, const uint8_t *buf, int size);
-ssize_t qemu_send_packet_async(NetClientState *vc, const uint8_t *buf,
+void qemu_send_packet(NetClientState *nc, const uint8_t *buf, int size);
+ssize_t qemu_send_packet_raw(NetClientState *nc, const uint8_t *buf, int size);
+ssize_t qemu_send_packet_async(NetClientState *nc, const uint8_t *buf,
                                int size, NetPacketSent *sent_cb);
-void qemu_purge_queued_packets(NetClientState *vc);
-void qemu_flush_queued_packets(NetClientState *vc);
-void qemu_format_nic_info_str(NetClientState *vc, uint8_t macaddr[6]);
+void qemu_purge_queued_packets(NetClientState *nc);
+void qemu_flush_queued_packets(NetClientState *nc);
+void qemu_format_nic_info_str(NetClientState *nc, uint8_t macaddr[6]);
 void qemu_macaddr_default_if_unset(MACAddr *macaddr);
 int qemu_show_nic_models(const char *arg, const char *const *models);
 void qemu_check_nic_model(NICInfo *nd, const char *model);
diff --git a/net/tap-win32.c b/net/tap-win32.c
index dcc7a64..c0ea954 100644
--- a/net/tap-win32.c
+++ b/net/tap-win32.c
@@ -719,12 +719,12 @@ int net_init_tap(const NetClientOptions *opts, const char *name,
     return 0;
 }
 
-int tap_has_ufo(NetClientState *vc)
+int tap_has_ufo(NetClientState *nc)
 {
     return 0;
 }
 
-int tap_has_vnet_hdr(NetClientState *vc)
+int tap_has_vnet_hdr(NetClientState *nc)
 {
     return 0;
 }
@@ -738,11 +738,11 @@ void tap_fd_set_vnet_hdr_len(int fd, int len)
 {
 }
 
-void tap_using_vnet_hdr(NetClientState *vc, int using_vnet_hdr)
+void tap_using_vnet_hdr(NetClientState *nc, int using_vnet_hdr)
 {
 }
 
-void tap_set_offload(NetClientState *vc, int csum, int tso4,
+void tap_set_offload(NetClientState *nc, int csum, int tso4,
                      int tso6, int ecn, int ufo)
 {
 }
diff --git a/net/tap.h b/net/tap.h
index 1257404..0fb018c 100644
--- a/net/tap.h
+++ b/net/tap.h
@@ -39,12 +39,12 @@ int tap_open(char *ifname, int ifname_size, int *vnet_hdr, int vnet_hdr_required
 
 ssize_t tap_read_packet(int tapfd, uint8_t *buf, int maxlen);
 
-int tap_has_ufo(NetClientState *vc);
-int tap_has_vnet_hdr(NetClientState *vc);
-int tap_has_vnet_hdr_len(NetClientState *vc, int len);
-void tap_using_vnet_hdr(NetClientState *vc, int using_vnet_hdr);
-void tap_set_offload(NetClientState *vc, int csum, int tso4, int tso6, int ecn, int ufo);
-void tap_set_vnet_hdr_len(NetClientState *vc, int len);
+int tap_has_ufo(NetClientState *nc);
+int tap_has_vnet_hdr(NetClientState *nc);
+int tap_has_vnet_hdr_len(NetClientState *nc, int len);
+void tap_using_vnet_hdr(NetClientState *nc, int using_vnet_hdr);
+void tap_set_offload(NetClientState *nc, int csum, int tso4, int tso6, int ecn, int ufo);
+void tap_set_vnet_hdr_len(NetClientState *nc, int len);
 
 int tap_set_sndbuf(int fd, const NetdevTapOptions *tap);
 int tap_probe_vnet_hdr(int fd);
@@ -53,10 +53,10 @@ int tap_probe_has_ufo(int fd);
 void tap_fd_set_offload(int fd, int csum, int tso4, int tso6, int ecn, int ufo);
 void tap_fd_set_vnet_hdr_len(int fd, int len);
 
-int tap_get_fd(NetClientState *vc);
+int tap_get_fd(NetClientState *nc);
 
 struct vhost_net;
-struct vhost_net *tap_get_vhost_net(NetClientState *vc);
+struct vhost_net *tap_get_vhost_net(NetClientState *nc);
 
 int net_init_bridge(const NetClientOptions *opts, const char *name,
                     NetClientState *peer);
commit 4e68f7a0819f179c2ff90a60611806c789911cc2
Author: Stefan Hajnoczi <stefanha at linux.vnet.ibm.com>
Date:   Tue Jul 24 16:35:13 2012 +0100

    net: Rename VLANClientState to NetClientState
    
    The vlan feature is no longer part of net core.  Rename VLANClientState
    to NetClientState because net clients are not explicitly associated with
    a vlan at all, instead they have a peer net client to which they are
    connected.
    
    This patch is a mechanical search-and-replace except for a few
    whitespace fixups where changing VLANClientState to NetClientState
    misaligned whitespace.
    
    Signed-off-by: Stefan Hajnoczi <stefanha at linux.vnet.ibm.com>
    Signed-off-by: Zhi Yong Wu <wuzhy at linux.vnet.ibm.com>
    Reviewed-by: Laszlo Ersek <lersek at redhat.com>

diff --git a/hw/cadence_gem.c b/hw/cadence_gem.c
index a0f51de..967f625 100644
--- a/hw/cadence_gem.c
+++ b/hw/cadence_gem.c
@@ -405,7 +405,7 @@ static void phy_update_link(GemState *s)
     }
 }
 
-static int gem_can_receive(VLANClientState *nc)
+static int gem_can_receive(NetClientState *nc)
 {
     GemState *s;
 
@@ -602,7 +602,7 @@ static int gem_mac_address_filter(GemState *s, const uint8_t *packet)
  * gem_receive:
  * Fit a packet handed to us by QEMU into the receive descriptor ring.
  */
-static ssize_t gem_receive(VLANClientState *nc, const uint8_t *buf, size_t size)
+static ssize_t gem_receive(NetClientState *nc, const uint8_t *buf, size_t size)
 {
     unsigned    desc[2];
     target_phys_addr_t packet_desc_addr, last_desc_addr;
@@ -1146,7 +1146,7 @@ static const MemoryRegionOps gem_ops = {
     .endianness = DEVICE_LITTLE_ENDIAN,
 };
 
-static void gem_cleanup(VLANClientState *nc)
+static void gem_cleanup(NetClientState *nc)
 {
     GemState *s = DO_UPCAST(NICState, nc, nc)->opaque;
 
@@ -1154,7 +1154,7 @@ static void gem_cleanup(VLANClientState *nc)
     s->nic = NULL;
 }
 
-static void gem_set_link(VLANClientState *nc)
+static void gem_set_link(NetClientState *nc)
 {
     DB_PRINT("\n");
     phy_update_link(DO_UPCAST(NICState, nc, nc)->opaque);
diff --git a/hw/dp8393x.c b/hw/dp8393x.c
index ee1a481..4fa6ecc 100644
--- a/hw/dp8393x.c
+++ b/hw/dp8393x.c
@@ -673,7 +673,7 @@ static const MemoryRegionOps dp8393x_ops = {
     .endianness = DEVICE_NATIVE_ENDIAN,
 };
 
-static int nic_can_receive(VLANClientState *nc)
+static int nic_can_receive(NetClientState *nc)
 {
     dp8393xState *s = DO_UPCAST(NICState, nc, nc)->opaque;
 
@@ -722,7 +722,7 @@ static int receive_filter(dp8393xState *s, const uint8_t * buf, int size)
     return -1;
 }
 
-static ssize_t nic_receive(VLANClientState *nc, const uint8_t * buf, size_t size)
+static ssize_t nic_receive(NetClientState *nc, const uint8_t * buf, size_t size)
 {
     dp8393xState *s = DO_UPCAST(NICState, nc, nc)->opaque;
     uint16_t data[10];
@@ -858,7 +858,7 @@ static void nic_reset(void *opaque)
     dp8393x_update_irq(s);
 }
 
-static void nic_cleanup(VLANClientState *nc)
+static void nic_cleanup(NetClientState *nc)
 {
     dp8393xState *s = DO_UPCAST(NICState, nc, nc)->opaque;
 
diff --git a/hw/e1000.c b/hw/e1000.c
index 13a459c..531b69a 100644
--- a/hw/e1000.c
+++ b/hw/e1000.c
@@ -720,7 +720,7 @@ receive_filter(E1000State *s, const uint8_t *buf, int size)
 }
 
 static void
-e1000_set_link_status(VLANClientState *nc)
+e1000_set_link_status(NetClientState *nc)
 {
     E1000State *s = DO_UPCAST(NICState, nc, nc)->opaque;
     uint32_t old_status = s->mac_reg[STATUS];
@@ -754,7 +754,7 @@ static bool e1000_has_rxbufs(E1000State *s, size_t total_size)
 }
 
 static int
-e1000_can_receive(VLANClientState *nc)
+e1000_can_receive(NetClientState *nc)
 {
     E1000State *s = DO_UPCAST(NICState, nc, nc)->opaque;
 
@@ -770,7 +770,7 @@ static uint64_t rx_desc_base(E1000State *s)
 }
 
 static ssize_t
-e1000_receive(VLANClientState *nc, const uint8_t *buf, size_t size)
+e1000_receive(NetClientState *nc, const uint8_t *buf, size_t size)
 {
     E1000State *s = DO_UPCAST(NICState, nc, nc)->opaque;
     struct e1000_rx_desc desc;
@@ -1185,7 +1185,7 @@ e1000_mmio_setup(E1000State *d)
 }
 
 static void
-e1000_cleanup(VLANClientState *nc)
+e1000_cleanup(NetClientState *nc)
 {
     E1000State *s = DO_UPCAST(NICState, nc, nc)->opaque;
 
diff --git a/hw/eepro100.c b/hw/eepro100.c
index 6b9e7f8..c2b0a2d 100644
--- a/hw/eepro100.c
+++ b/hw/eepro100.c
@@ -1616,7 +1616,7 @@ static const MemoryRegionOps eepro100_ops = {
     .endianness = DEVICE_LITTLE_ENDIAN,
 };
 
-static int nic_can_receive(VLANClientState *nc)
+static int nic_can_receive(NetClientState *nc)
 {
     EEPRO100State *s = DO_UPCAST(NICState, nc, nc)->opaque;
     TRACE(RXTX, logout("%p\n", s));
@@ -1626,7 +1626,7 @@ static int nic_can_receive(VLANClientState *nc)
 #endif
 }
 
-static ssize_t nic_receive(VLANClientState *nc, const uint8_t * buf, size_t size)
+static ssize_t nic_receive(NetClientState *nc, const uint8_t * buf, size_t size)
 {
     /* TODO:
      * - Magic packets should set bit 30 in power management driver register.
@@ -1831,7 +1831,7 @@ static const VMStateDescription vmstate_eepro100 = {
     }
 };
 
-static void nic_cleanup(VLANClientState *nc)
+static void nic_cleanup(NetClientState *nc)
 {
     EEPRO100State *s = DO_UPCAST(NICState, nc, nc)->opaque;
 
diff --git a/hw/etraxfs_eth.c b/hw/etraxfs_eth.c
index 45fb40c..b124f5b 100644
--- a/hw/etraxfs_eth.c
+++ b/hw/etraxfs_eth.c
@@ -507,12 +507,12 @@ static int eth_match_groupaddr(struct fs_eth *eth, const unsigned char *sa)
 	return match;
 }
 
-static int eth_can_receive(VLANClientState *nc)
+static int eth_can_receive(NetClientState *nc)
 {
 	return 1;
 }
 
-static ssize_t eth_receive(VLANClientState *nc, const uint8_t *buf, size_t size)
+static ssize_t eth_receive(NetClientState *nc, const uint8_t *buf, size_t size)
 {
 	unsigned char sa_bcast[6] = {0xff, 0xff, 0xff, 0xff, 0xff, 0xff };
 	struct fs_eth *eth = DO_UPCAST(NICState, nc, nc)->opaque;
@@ -549,7 +549,7 @@ static int eth_tx_push(void *opaque, unsigned char *buf, int len, bool eop)
 	return len;
 }
 
-static void eth_set_link(VLANClientState *nc)
+static void eth_set_link(NetClientState *nc)
 {
 	struct fs_eth *eth = DO_UPCAST(NICState, nc, nc)->opaque;
 	D(printf("%s %d\n", __func__, nc->link_down));
@@ -566,7 +566,7 @@ static const MemoryRegionOps eth_ops = {
 	}
 };
 
-static void eth_cleanup(VLANClientState *nc)
+static void eth_cleanup(NetClientState *nc)
 {
 	struct fs_eth *eth = DO_UPCAST(NICState, nc, nc)->opaque;
 
diff --git a/hw/lan9118.c b/hw/lan9118.c
index 61f1c0e..ff0a50b 100644
--- a/hw/lan9118.c
+++ b/hw/lan9118.c
@@ -384,7 +384,7 @@ static void phy_update_link(lan9118_state *s)
     phy_update_irq(s);
 }
 
-static void lan9118_set_link(VLANClientState *nc)
+static void lan9118_set_link(NetClientState *nc)
 {
     phy_update_link(DO_UPCAST(NICState, nc, nc)->opaque);
 }
@@ -456,7 +456,7 @@ static void lan9118_reset(DeviceState *d)
     lan9118_reload_eeprom(s);
 }
 
-static int lan9118_can_receive(VLANClientState *nc)
+static int lan9118_can_receive(NetClientState *nc)
 {
     return 1;
 }
@@ -509,7 +509,7 @@ static int lan9118_filter(lan9118_state *s, const uint8_t *addr)
     }
 }
 
-static ssize_t lan9118_receive(VLANClientState *nc, const uint8_t *buf,
+static ssize_t lan9118_receive(NetClientState *nc, const uint8_t *buf,
                                size_t size)
 {
     lan9118_state *s = DO_UPCAST(NICState, nc, nc)->opaque;
@@ -1304,7 +1304,7 @@ static const MemoryRegionOps lan9118_16bit_mem_ops = {
     .endianness = DEVICE_NATIVE_ENDIAN,
 };
 
-static void lan9118_cleanup(VLANClientState *nc)
+static void lan9118_cleanup(NetClientState *nc)
 {
     lan9118_state *s = DO_UPCAST(NICState, nc, nc)->opaque;
 
diff --git a/hw/lance.c b/hw/lance.c
index 91c0e16..9b98bb8 100644
--- a/hw/lance.c
+++ b/hw/lance.c
@@ -85,7 +85,7 @@ static const MemoryRegionOps lance_mem_ops = {
     },
 };
 
-static void lance_cleanup(VLANClientState *nc)
+static void lance_cleanup(NetClientState *nc)
 {
     PCNetState *d = DO_UPCAST(NICState, nc, nc)->opaque;
 
diff --git a/hw/mcf_fec.c b/hw/mcf_fec.c
index 308a1b6..2fec5bc 100644
--- a/hw/mcf_fec.c
+++ b/hw/mcf_fec.c
@@ -351,13 +351,13 @@ static void mcf_fec_write(void *opaque, target_phys_addr_t addr,
     mcf_fec_update(s);
 }
 
-static int mcf_fec_can_receive(VLANClientState *nc)
+static int mcf_fec_can_receive(NetClientState *nc)
 {
     mcf_fec_state *s = DO_UPCAST(NICState, nc, nc)->opaque;
     return s->rx_enabled;
 }
 
-static ssize_t mcf_fec_receive(VLANClientState *nc, const uint8_t *buf, size_t size)
+static ssize_t mcf_fec_receive(NetClientState *nc, const uint8_t *buf, size_t size)
 {
     mcf_fec_state *s = DO_UPCAST(NICState, nc, nc)->opaque;
     mcf_fec_bd bd;
@@ -439,7 +439,7 @@ static const MemoryRegionOps mcf_fec_ops = {
     .endianness = DEVICE_NATIVE_ENDIAN,
 };
 
-static void mcf_fec_cleanup(VLANClientState *nc)
+static void mcf_fec_cleanup(NetClientState *nc)
 {
     mcf_fec_state *s = DO_UPCAST(NICState, nc, nc)->opaque;
 
diff --git a/hw/milkymist-minimac2.c b/hw/milkymist-minimac2.c
index 3924b83..b483a02 100644
--- a/hw/milkymist-minimac2.c
+++ b/hw/milkymist-minimac2.c
@@ -278,7 +278,7 @@ static void update_rx_interrupt(MilkymistMinimac2State *s)
     }
 }
 
-static ssize_t minimac2_rx(VLANClientState *nc, const uint8_t *buf, size_t size)
+static ssize_t minimac2_rx(NetClientState *nc, const uint8_t *buf, size_t size)
 {
     MilkymistMinimac2State *s = DO_UPCAST(NICState, nc, nc)->opaque;
 
@@ -408,7 +408,7 @@ static const MemoryRegionOps minimac2_ops = {
     .endianness = DEVICE_NATIVE_ENDIAN,
 };
 
-static int minimac2_can_rx(VLANClientState *nc)
+static int minimac2_can_rx(NetClientState *nc)
 {
     MilkymistMinimac2State *s = DO_UPCAST(NICState, nc, nc)->opaque;
 
@@ -422,7 +422,7 @@ static int minimac2_can_rx(VLANClientState *nc)
     return 0;
 }
 
-static void minimac2_cleanup(VLANClientState *nc)
+static void minimac2_cleanup(NetClientState *nc)
 {
     MilkymistMinimac2State *s = DO_UPCAST(NICState, nc, nc)->opaque;
 
diff --git a/hw/mipsnet.c b/hw/mipsnet.c
index 3385be7..28063b1 100644
--- a/hw/mipsnet.c
+++ b/hw/mipsnet.c
@@ -62,7 +62,7 @@ static int mipsnet_buffer_full(MIPSnetState *s)
     return 0;
 }
 
-static int mipsnet_can_receive(VLANClientState *nc)
+static int mipsnet_can_receive(NetClientState *nc)
 {
     MIPSnetState *s = DO_UPCAST(NICState, nc, nc)->opaque;
 
@@ -71,7 +71,7 @@ static int mipsnet_can_receive(VLANClientState *nc)
     return !mipsnet_buffer_full(s);
 }
 
-static ssize_t mipsnet_receive(VLANClientState *nc, const uint8_t *buf, size_t size)
+static ssize_t mipsnet_receive(NetClientState *nc, const uint8_t *buf, size_t size)
 {
     MIPSnetState *s = DO_UPCAST(NICState, nc, nc)->opaque;
 
@@ -209,7 +209,7 @@ static const VMStateDescription vmstate_mipsnet = {
     }
 };
 
-static void mipsnet_cleanup(VLANClientState *nc)
+static void mipsnet_cleanup(NetClientState *nc)
 {
     MIPSnetState *s = DO_UPCAST(NICState, nc, nc)->opaque;
 
diff --git a/hw/musicpal.c b/hw/musicpal.c
index 448897f..ad725b5 100644
--- a/hw/musicpal.c
+++ b/hw/musicpal.c
@@ -182,12 +182,12 @@ static void eth_rx_desc_get(uint32_t addr, mv88w8618_rx_desc *desc)
     le32_to_cpus(&desc->next);
 }
 
-static int eth_can_receive(VLANClientState *nc)
+static int eth_can_receive(NetClientState *nc)
 {
     return 1;
 }
 
-static ssize_t eth_receive(VLANClientState *nc, const uint8_t *buf, size_t size)
+static ssize_t eth_receive(NetClientState *nc, const uint8_t *buf, size_t size)
 {
     mv88w8618_eth_state *s = DO_UPCAST(NICState, nc, nc)->opaque;
     uint32_t desc_addr;
@@ -366,7 +366,7 @@ static const MemoryRegionOps mv88w8618_eth_ops = {
     .endianness = DEVICE_NATIVE_ENDIAN,
 };
 
-static void eth_cleanup(VLANClientState *nc)
+static void eth_cleanup(NetClientState *nc)
 {
     mv88w8618_eth_state *s = DO_UPCAST(NICState, nc, nc)->opaque;
 
diff --git a/hw/ne2000-isa.c b/hw/ne2000-isa.c
index 99ed965..69982a9 100644
--- a/hw/ne2000-isa.c
+++ b/hw/ne2000-isa.c
@@ -36,7 +36,7 @@ typedef struct ISANE2000State {
     NE2000State ne2000;
 } ISANE2000State;
 
-static void isa_ne2000_cleanup(VLANClientState *nc)
+static void isa_ne2000_cleanup(NetClientState *nc)
 {
     NE2000State *s = DO_UPCAST(NICState, nc, nc)->opaque;
 
diff --git a/hw/ne2000.c b/hw/ne2000.c
index 399d340..2131770 100644
--- a/hw/ne2000.c
+++ b/hw/ne2000.c
@@ -165,7 +165,7 @@ static int ne2000_buffer_full(NE2000State *s)
     return 0;
 }
 
-int ne2000_can_receive(VLANClientState *nc)
+int ne2000_can_receive(NetClientState *nc)
 {
     NE2000State *s = DO_UPCAST(NICState, nc, nc)->opaque;
 
@@ -176,7 +176,7 @@ int ne2000_can_receive(VLANClientState *nc)
 
 #define MIN_BUF_SIZE 60
 
-ssize_t ne2000_receive(VLANClientState *nc, const uint8_t *buf, size_t size_)
+ssize_t ne2000_receive(NetClientState *nc, const uint8_t *buf, size_t size_)
 {
     NE2000State *s = DO_UPCAST(NICState, nc, nc)->opaque;
     int size = size_;
@@ -703,7 +703,7 @@ void ne2000_setup_io(NE2000State *s, unsigned size)
     memory_region_init_io(&s->io, &ne2000_ops, s, "ne2000", size);
 }
 
-static void ne2000_cleanup(VLANClientState *nc)
+static void ne2000_cleanup(NetClientState *nc)
 {
     NE2000State *s = DO_UPCAST(NICState, nc, nc)->opaque;
 
diff --git a/hw/ne2000.h b/hw/ne2000.h
index 5fee052..6c196a2 100644
--- a/hw/ne2000.h
+++ b/hw/ne2000.h
@@ -31,5 +31,5 @@ typedef struct NE2000State {
 void ne2000_setup_io(NE2000State *s, unsigned size);
 extern const VMStateDescription vmstate_ne2000;
 void ne2000_reset(NE2000State *s);
-int ne2000_can_receive(VLANClientState *vc);
-ssize_t ne2000_receive(VLANClientState *vc, const uint8_t *buf, size_t size_);
+int ne2000_can_receive(NetClientState *vc);
+ssize_t ne2000_receive(NetClientState *vc, const uint8_t *buf, size_t size_);
diff --git a/hw/opencores_eth.c b/hw/opencores_eth.c
index f4498d4..8c15969 100644
--- a/hw/opencores_eth.c
+++ b/hw/opencores_eth.c
@@ -311,7 +311,7 @@ static void open_eth_int_source_write(OpenEthState *s,
             s->regs[INT_SOURCE] & s->regs[INT_MASK]);
 }
 
-static void open_eth_set_link_status(VLANClientState *nc)
+static void open_eth_set_link_status(NetClientState *nc)
 {
     OpenEthState *s = DO_UPCAST(NICState, nc, nc)->opaque;
 
@@ -342,7 +342,7 @@ static void open_eth_reset(void *opaque)
     open_eth_set_link_status(&s->nic->nc);
 }
 
-static int open_eth_can_receive(VLANClientState *nc)
+static int open_eth_can_receive(NetClientState *nc)
 {
     OpenEthState *s = DO_UPCAST(NICState, nc, nc)->opaque;
 
@@ -351,7 +351,7 @@ static int open_eth_can_receive(VLANClientState *nc)
         (rx_desc(s)->len_flags & RXD_E);
 }
 
-static ssize_t open_eth_receive(VLANClientState *nc,
+static ssize_t open_eth_receive(NetClientState *nc,
         const uint8_t *buf, size_t size)
 {
     OpenEthState *s = DO_UPCAST(NICState, nc, nc)->opaque;
@@ -462,7 +462,7 @@ static ssize_t open_eth_receive(VLANClientState *nc,
     return size;
 }
 
-static void open_eth_cleanup(VLANClientState *nc)
+static void open_eth_cleanup(NetClientState *nc)
 {
 }
 
diff --git a/hw/pcnet-pci.c b/hw/pcnet-pci.c
index 31eb1a8..d58cffd 100644
--- a/hw/pcnet-pci.c
+++ b/hw/pcnet-pci.c
@@ -264,7 +264,7 @@ static void pci_physical_memory_read(void *dma_opaque, target_phys_addr_t addr,
     pci_dma_read(dma_opaque, addr, buf, len);
 }
 
-static void pci_pcnet_cleanup(VLANClientState *nc)
+static void pci_pcnet_cleanup(NetClientState *nc)
 {
     PCNetState *d = DO_UPCAST(NICState, nc, nc)->opaque;
 
diff --git a/hw/pcnet.c b/hw/pcnet.c
index d769b08..40820b3 100644
--- a/hw/pcnet.c
+++ b/hw/pcnet.c
@@ -1004,7 +1004,7 @@ static int pcnet_tdte_poll(PCNetState *s)
     return !!(CSR_CXST(s) & 0x8000);
 }
 
-int pcnet_can_receive(VLANClientState *nc)
+int pcnet_can_receive(NetClientState *nc)
 {
     PCNetState *s = DO_UPCAST(NICState, nc, nc)->opaque;
     if (CSR_STOP(s) || CSR_SPND(s))
@@ -1015,7 +1015,7 @@ int pcnet_can_receive(VLANClientState *nc)
 
 #define MIN_BUF_SIZE 60
 
-ssize_t pcnet_receive(VLANClientState *nc, const uint8_t *buf, size_t size_)
+ssize_t pcnet_receive(NetClientState *nc, const uint8_t *buf, size_t size_)
 {
     PCNetState *s = DO_UPCAST(NICState, nc, nc)->opaque;
     int is_padr = 0, is_bcast = 0, is_ladr = 0;
@@ -1197,7 +1197,7 @@ ssize_t pcnet_receive(VLANClientState *nc, const uint8_t *buf, size_t size_)
     return size_;
 }
 
-void pcnet_set_link_status(VLANClientState *nc)
+void pcnet_set_link_status(NetClientState *nc)
 {
     PCNetState *d = DO_UPCAST(NICState, nc, nc)->opaque;
 
diff --git a/hw/pcnet.h b/hw/pcnet.h
index 803a2cc..d0af54a 100644
--- a/hw/pcnet.h
+++ b/hw/pcnet.h
@@ -57,9 +57,9 @@ uint32_t pcnet_ioport_readw(void *opaque, uint32_t addr);
 void pcnet_ioport_writel(void *opaque, uint32_t addr, uint32_t val);
 uint32_t pcnet_ioport_readl(void *opaque, uint32_t addr);
 uint32_t pcnet_bcr_readw(PCNetState *s, uint32_t rap);
-int pcnet_can_receive(VLANClientState *nc);
-ssize_t pcnet_receive(VLANClientState *nc, const uint8_t *buf, size_t size_);
-void pcnet_set_link_status(VLANClientState *nc);
+int pcnet_can_receive(NetClientState *nc);
+ssize_t pcnet_receive(NetClientState *nc, const uint8_t *buf, size_t size_);
+void pcnet_set_link_status(NetClientState *nc);
 void pcnet_common_cleanup(PCNetState *d);
 int pcnet_common_init(DeviceState *dev, PCNetState *s, NetClientInfo *info);
 extern const VMStateDescription vmstate_pcnet;
diff --git a/hw/qdev-properties.c b/hw/qdev-properties.c
index 726f6d7..8aca0d4 100644
--- a/hw/qdev-properties.c
+++ b/hw/qdev-properties.c
@@ -584,7 +584,7 @@ PropertyInfo qdev_prop_chr = {
 
 static int parse_netdev(DeviceState *dev, const char *str, void **ptr)
 {
-    VLANClientState *netdev = qemu_find_netdev(str);
+    NetClientState *netdev = qemu_find_netdev(str);
 
     if (netdev == NULL) {
         return -ENOENT;
@@ -598,7 +598,7 @@ static int parse_netdev(DeviceState *dev, const char *str, void **ptr)
 
 static const char *print_netdev(void *ptr)
 {
-    VLANClientState *netdev = ptr;
+    NetClientState *netdev = ptr;
 
     return netdev->name ? netdev->name : "";
 }
@@ -625,7 +625,7 @@ PropertyInfo qdev_prop_netdev = {
 
 static int print_vlan(DeviceState *dev, Property *prop, char *dest, size_t len)
 {
-    VLANClientState **ptr = qdev_get_prop_ptr(dev, prop);
+    NetClientState **ptr = qdev_get_prop_ptr(dev, prop);
 
     if (*ptr) {
         int id;
@@ -642,7 +642,7 @@ static void get_vlan(Object *obj, Visitor *v, void *opaque,
 {
     DeviceState *dev = DEVICE(obj);
     Property *prop = opaque;
-    VLANClientState **ptr = qdev_get_prop_ptr(dev, prop);
+    NetClientState **ptr = qdev_get_prop_ptr(dev, prop);
     int32_t id = -1;
 
     if (*ptr) {
@@ -660,10 +660,10 @@ static void set_vlan(Object *obj, Visitor *v, void *opaque,
 {
     DeviceState *dev = DEVICE(obj);
     Property *prop = opaque;
-    VLANClientState **ptr = qdev_get_prop_ptr(dev, prop);
+    NetClientState **ptr = qdev_get_prop_ptr(dev, prop);
     Error *local_err = NULL;
     int32_t id;
-    VLANClientState *hubport;
+    NetClientState *hubport;
 
     if (dev->state != DEV_STATE_CREATED) {
         error_set(errp, QERR_PERMISSION_DENIED);
@@ -1186,7 +1186,7 @@ void qdev_prop_set_chr(DeviceState *dev, const char *name, CharDriverState *valu
     assert_no_error(errp);
 }
 
-void qdev_prop_set_netdev(DeviceState *dev, const char *name, VLANClientState *value)
+void qdev_prop_set_netdev(DeviceState *dev, const char *name, NetClientState *value)
 {
     Error *errp = NULL;
     assert(!value || value->name);
diff --git a/hw/qdev.h b/hw/qdev.h
index 7386ecd..d699194 100644
--- a/hw/qdev.h
+++ b/hw/qdev.h
@@ -289,9 +289,9 @@ extern PropertyInfo qdev_prop_pci_host_devaddr;
 #define DEFINE_PROP_STRING(_n, _s, _f)             \
     DEFINE_PROP(_n, _s, _f, qdev_prop_string, char*)
 #define DEFINE_PROP_NETDEV(_n, _s, _f)             \
-    DEFINE_PROP(_n, _s, _f, qdev_prop_netdev, VLANClientState*)
+    DEFINE_PROP(_n, _s, _f, qdev_prop_netdev, NetClientState*)
 #define DEFINE_PROP_VLAN(_n, _s, _f)             \
-    DEFINE_PROP(_n, _s, _f, qdev_prop_vlan, VLANClientState*)
+    DEFINE_PROP(_n, _s, _f, qdev_prop_vlan, NetClientState*)
 #define DEFINE_PROP_DRIVE(_n, _s, _f) \
     DEFINE_PROP(_n, _s, _f, qdev_prop_drive, BlockDriverState *)
 #define DEFINE_PROP_MACADDR(_n, _s, _f)         \
@@ -320,7 +320,7 @@ void qdev_prop_set_int32(DeviceState *dev, const char *name, int32_t value);
 void qdev_prop_set_uint64(DeviceState *dev, const char *name, uint64_t value);
 void qdev_prop_set_string(DeviceState *dev, const char *name, const char *value);
 void qdev_prop_set_chr(DeviceState *dev, const char *name, CharDriverState *value);
-void qdev_prop_set_netdev(DeviceState *dev, const char *name, VLANClientState *value);
+void qdev_prop_set_netdev(DeviceState *dev, const char *name, NetClientState *value);
 int qdev_prop_set_drive(DeviceState *dev, const char *name, BlockDriverState *value) QEMU_WARN_UNUSED_RESULT;
 void qdev_prop_set_drive_nofail(DeviceState *dev, const char *name, BlockDriverState *value);
 void qdev_prop_set_macaddr(DeviceState *dev, const char *name, uint8_t *value);
diff --git a/hw/rtl8139.c b/hw/rtl8139.c
index 7b78f40..619e6c0 100644
--- a/hw/rtl8139.c
+++ b/hw/rtl8139.c
@@ -788,7 +788,7 @@ static bool rtl8139_cp_rx_valid(RTL8139State *s)
     return !(s->RxRingAddrLO == 0 && s->RxRingAddrHI == 0);
 }
 
-static int rtl8139_can_receive(VLANClientState *nc)
+static int rtl8139_can_receive(NetClientState *nc)
 {
     RTL8139State *s = DO_UPCAST(NICState, nc, nc)->opaque;
     int avail;
@@ -810,7 +810,7 @@ static int rtl8139_can_receive(VLANClientState *nc)
     }
 }
 
-static ssize_t rtl8139_do_receive(VLANClientState *nc, const uint8_t *buf, size_t size_, int do_interrupt)
+static ssize_t rtl8139_do_receive(NetClientState *nc, const uint8_t *buf, size_t size_, int do_interrupt)
 {
     RTL8139State *s = DO_UPCAST(NICState, nc, nc)->opaque;
     /* size is the length of the buffer passed to the driver */
@@ -1187,7 +1187,7 @@ static ssize_t rtl8139_do_receive(VLANClientState *nc, const uint8_t *buf, size_
     return size_;
 }
 
-static ssize_t rtl8139_receive(VLANClientState *nc, const uint8_t *buf, size_t size)
+static ssize_t rtl8139_receive(NetClientState *nc, const uint8_t *buf, size_t size)
 {
     return rtl8139_do_receive(nc, buf, size, 1);
 }
@@ -3431,7 +3431,7 @@ static void rtl8139_timer(void *opaque)
     rtl8139_set_next_tctr_time(s, qemu_get_clock_ns(vm_clock));
 }
 
-static void rtl8139_cleanup(VLANClientState *nc)
+static void rtl8139_cleanup(NetClientState *nc)
 {
     RTL8139State *s = DO_UPCAST(NICState, nc, nc)->opaque;
 
diff --git a/hw/smc91c111.c b/hw/smc91c111.c
index 451ede0..d6ef302 100644
--- a/hw/smc91c111.c
+++ b/hw/smc91c111.c
@@ -628,7 +628,7 @@ static uint32_t smc91c111_readl(void *opaque, target_phys_addr_t offset)
     return val;
 }
 
-static int smc91c111_can_receive(VLANClientState *nc)
+static int smc91c111_can_receive(NetClientState *nc)
 {
     smc91c111_state *s = DO_UPCAST(NICState, nc, nc)->opaque;
 
@@ -639,7 +639,7 @@ static int smc91c111_can_receive(VLANClientState *nc)
     return 1;
 }
 
-static ssize_t smc91c111_receive(VLANClientState *nc, const uint8_t *buf, size_t size)
+static ssize_t smc91c111_receive(NetClientState *nc, const uint8_t *buf, size_t size)
 {
     smc91c111_state *s = DO_UPCAST(NICState, nc, nc)->opaque;
     int status;
@@ -728,7 +728,7 @@ static const MemoryRegionOps smc91c111_mem_ops = {
     .endianness = DEVICE_NATIVE_ENDIAN,
 };
 
-static void smc91c111_cleanup(VLANClientState *nc)
+static void smc91c111_cleanup(NetClientState *nc)
 {
     smc91c111_state *s = DO_UPCAST(NICState, nc, nc)->opaque;
 
diff --git a/hw/spapr_llan.c b/hw/spapr_llan.c
index d54f933..01e54f3 100644
--- a/hw/spapr_llan.c
+++ b/hw/spapr_llan.c
@@ -83,14 +83,14 @@ typedef struct VIOsPAPRVLANDevice {
     target_ulong rxq_ptr;
 } VIOsPAPRVLANDevice;
 
-static int spapr_vlan_can_receive(VLANClientState *nc)
+static int spapr_vlan_can_receive(NetClientState *nc)
 {
     VIOsPAPRVLANDevice *dev = DO_UPCAST(NICState, nc, nc)->opaque;
 
     return (dev->isopen && dev->rx_bufs > 0);
 }
 
-static ssize_t spapr_vlan_receive(VLANClientState *nc, const uint8_t *buf,
+static ssize_t spapr_vlan_receive(NetClientState *nc, const uint8_t *buf,
                                   size_t size)
 {
     VIOsPAPRDevice *sdev = DO_UPCAST(NICState, nc, nc)->opaque;
diff --git a/hw/stellaris_enet.c b/hw/stellaris_enet.c
index b593cd0..bc97280 100644
--- a/hw/stellaris_enet.c
+++ b/hw/stellaris_enet.c
@@ -78,7 +78,7 @@ static void stellaris_enet_update(stellaris_enet_state *s)
 }
 
 /* TODO: Implement MAC address filtering.  */
-static ssize_t stellaris_enet_receive(VLANClientState *nc, const uint8_t *buf, size_t size)
+static ssize_t stellaris_enet_receive(NetClientState *nc, const uint8_t *buf, size_t size)
 {
     stellaris_enet_state *s = DO_UPCAST(NICState, nc, nc)->opaque;
     int n;
@@ -120,7 +120,7 @@ static ssize_t stellaris_enet_receive(VLANClientState *nc, const uint8_t *buf, s
     return size;
 }
 
-static int stellaris_enet_can_receive(VLANClientState *nc)
+static int stellaris_enet_can_receive(NetClientState *nc)
 {
     stellaris_enet_state *s = DO_UPCAST(NICState, nc, nc)->opaque;
 
@@ -381,7 +381,7 @@ static int stellaris_enet_load(QEMUFile *f, void *opaque, int version_id)
     return 0;
 }
 
-static void stellaris_enet_cleanup(VLANClientState *nc)
+static void stellaris_enet_cleanup(NetClientState *nc)
 {
     stellaris_enet_state *s = DO_UPCAST(NICState, nc, nc)->opaque;
 
diff --git a/hw/usb/dev-network.c b/hw/usb/dev-network.c
index f40c349..6c2edbe 100644
--- a/hw/usb/dev-network.c
+++ b/hw/usb/dev-network.c
@@ -1247,7 +1247,7 @@ static int usb_net_handle_data(USBDevice *dev, USBPacket *p)
     return ret;
 }
 
-static ssize_t usbnet_receive(VLANClientState *nc, const uint8_t *buf, size_t size)
+static ssize_t usbnet_receive(NetClientState *nc, const uint8_t *buf, size_t size)
 {
     USBNetState *s = DO_UPCAST(NICState, nc, nc)->opaque;
     struct rndis_packet_msg_type *msg;
@@ -1285,7 +1285,7 @@ static ssize_t usbnet_receive(VLANClientState *nc, const uint8_t *buf, size_t si
     return size;
 }
 
-static int usbnet_can_receive(VLANClientState *nc)
+static int usbnet_can_receive(NetClientState *nc)
 {
     USBNetState *s = DO_UPCAST(NICState, nc, nc)->opaque;
 
@@ -1296,7 +1296,7 @@ static int usbnet_can_receive(VLANClientState *nc)
     return !s->in_len;
 }
 
-static void usbnet_cleanup(VLANClientState *nc)
+static void usbnet_cleanup(NetClientState *nc)
 {
     USBNetState *s = DO_UPCAST(NICState, nc, nc)->opaque;
 
diff --git a/hw/vhost_net.c b/hw/vhost_net.c
index 75f8211..85a9a4e 100644
--- a/hw/vhost_net.c
+++ b/hw/vhost_net.c
@@ -42,7 +42,7 @@ struct vhost_net {
     struct vhost_dev dev;
     struct vhost_virtqueue vqs[2];
     int backend;
-    VLANClientState *vc;
+    NetClientState *vc;
 };
 
 unsigned vhost_net_get_features(struct vhost_net *net, unsigned features)
@@ -80,7 +80,7 @@ void vhost_net_ack_features(struct vhost_net *net, unsigned features)
     }
 }
 
-static int vhost_net_get_fd(VLANClientState *backend)
+static int vhost_net_get_fd(NetClientState *backend)
 {
     switch (backend->info->type) {
     case NET_CLIENT_OPTIONS_KIND_TAP:
@@ -91,7 +91,7 @@ static int vhost_net_get_fd(VLANClientState *backend)
     }
 }
 
-struct vhost_net *vhost_net_init(VLANClientState *backend, int devfd,
+struct vhost_net *vhost_net_init(NetClientState *backend, int devfd,
                                  bool force)
 {
     int r;
@@ -214,7 +214,7 @@ void vhost_net_cleanup(struct vhost_net *net)
     g_free(net);
 }
 #else
-struct vhost_net *vhost_net_init(VLANClientState *backend, int devfd,
+struct vhost_net *vhost_net_init(NetClientState *backend, int devfd,
                                  bool force)
 {
     error_report("vhost-net support is not compiled in");
diff --git a/hw/vhost_net.h b/hw/vhost_net.h
index 91e40b1..a9db234 100644
--- a/hw/vhost_net.h
+++ b/hw/vhost_net.h
@@ -6,7 +6,7 @@
 struct vhost_net;
 typedef struct vhost_net VHostNetState;
 
-VHostNetState *vhost_net_init(VLANClientState *backend, int devfd, bool force);
+VHostNetState *vhost_net_init(NetClientState *backend, int devfd, bool force);
 
 bool vhost_net_query(VHostNetState *net, VirtIODevice *dev);
 int vhost_net_start(VHostNetState *net, VirtIODevice *dev);
diff --git a/hw/virtio-net.c b/hw/virtio-net.c
index df20499..a83eade 100644
--- a/hw/virtio-net.c
+++ b/hw/virtio-net.c
@@ -163,7 +163,7 @@ static void virtio_net_set_status(struct VirtIODevice *vdev, uint8_t status)
     }
 }
 
-static void virtio_net_set_link_status(VLANClientState *nc)
+static void virtio_net_set_link_status(NetClientState *nc)
 {
     VirtIONet *n = DO_UPCAST(NICState, nc, nc)->opaque;
     uint16_t old_status = n->status;
@@ -453,7 +453,7 @@ static void virtio_net_handle_rx(VirtIODevice *vdev, VirtQueue *vq)
     qemu_notify_event();
 }
 
-static int virtio_net_can_receive(VLANClientState *nc)
+static int virtio_net_can_receive(NetClientState *nc)
 {
     VirtIONet *n = DO_UPCAST(NICState, nc, nc)->opaque;
     if (!n->vdev.vm_running) {
@@ -593,7 +593,7 @@ static int receive_filter(VirtIONet *n, const uint8_t *buf, int size)
     return 0;
 }
 
-static ssize_t virtio_net_receive(VLANClientState *nc, const uint8_t *buf, size_t size)
+static ssize_t virtio_net_receive(NetClientState *nc, const uint8_t *buf, size_t size)
 {
     VirtIONet *n = DO_UPCAST(NICState, nc, nc)->opaque;
     struct virtio_net_hdr_mrg_rxbuf *mhdr = NULL;
@@ -690,7 +690,7 @@ static ssize_t virtio_net_receive(VLANClientState *nc, const uint8_t *buf, size_
 
 static int32_t virtio_net_flush_tx(VirtIONet *n, VirtQueue *vq);
 
-static void virtio_net_tx_complete(VLANClientState *nc, ssize_t len)
+static void virtio_net_tx_complete(NetClientState *nc, ssize_t len)
 {
     VirtIONet *n = DO_UPCAST(NICState, nc, nc)->opaque;
 
@@ -980,7 +980,7 @@ static int virtio_net_load(QEMUFile *f, void *opaque, int version_id)
     return 0;
 }
 
-static void virtio_net_cleanup(VLANClientState *nc)
+static void virtio_net_cleanup(NetClientState *nc)
 {
     VirtIONet *n = DO_UPCAST(NICState, nc, nc)->opaque;
 
diff --git a/hw/xen_nic.c b/hw/xen_nic.c
index 5c3c1c6..c81191d 100644
--- a/hw/xen_nic.c
+++ b/hw/xen_nic.c
@@ -233,7 +233,7 @@ static void net_rx_response(struct XenNetDev *netdev,
 
 #define NET_IP_ALIGN 2
 
-static int net_rx_ok(VLANClientState *nc)
+static int net_rx_ok(NetClientState *nc)
 {
     struct XenNetDev *netdev = DO_UPCAST(NICState, nc, nc)->opaque;
     RING_IDX rc, rp;
@@ -254,7 +254,7 @@ static int net_rx_ok(VLANClientState *nc)
     return 1;
 }
 
-static ssize_t net_rx_packet(VLANClientState *nc, const uint8_t *buf, size_t size)
+static ssize_t net_rx_packet(NetClientState *nc, const uint8_t *buf, size_t size)
 {
     struct XenNetDev *netdev = DO_UPCAST(NICState, nc, nc)->opaque;
     netif_rx_request_t rxreq;
diff --git a/hw/xgmac.c b/hw/xgmac.c
index e539681..a91ef60 100644
--- a/hw/xgmac.c
+++ b/hw/xgmac.c
@@ -308,7 +308,7 @@ static const MemoryRegionOps enet_mem_ops = {
     .endianness = DEVICE_LITTLE_ENDIAN,
 };
 
-static int eth_can_rx(VLANClientState *nc)
+static int eth_can_rx(NetClientState *nc)
 {
     struct XgmacState *s = DO_UPCAST(NICState, nc, nc)->opaque;
 
@@ -316,7 +316,7 @@ static int eth_can_rx(VLANClientState *nc)
     return s->regs[DMA_CONTROL] & DMA_CONTROL_SR;
 }
 
-static ssize_t eth_rx(VLANClientState *nc, const uint8_t *buf, size_t size)
+static ssize_t eth_rx(NetClientState *nc, const uint8_t *buf, size_t size)
 {
     struct XgmacState *s = DO_UPCAST(NICState, nc, nc)->opaque;
     static const unsigned char sa_bcast[6] = {0xff, 0xff, 0xff,
@@ -364,7 +364,7 @@ out:
     return ret;
 }
 
-static void eth_cleanup(VLANClientState *nc)
+static void eth_cleanup(NetClientState *nc)
 {
     struct XgmacState *s = DO_UPCAST(NICState, nc, nc)->opaque;
     s->nic = NULL;
diff --git a/hw/xilinx_axienet.c b/hw/xilinx_axienet.c
index e948505..adfaf2c 100644
--- a/hw/xilinx_axienet.c
+++ b/hw/xilinx_axienet.c
@@ -612,7 +612,7 @@ static const MemoryRegionOps enet_ops = {
     .endianness = DEVICE_LITTLE_ENDIAN,
 };
 
-static int eth_can_rx(VLANClientState *nc)
+static int eth_can_rx(NetClientState *nc)
 {
     struct XilinxAXIEnet *s = DO_UPCAST(NICState, nc, nc)->opaque;
 
@@ -635,7 +635,7 @@ static int enet_match_addr(const uint8_t *buf, uint32_t f0, uint32_t f1)
     return match;
 }
 
-static ssize_t eth_rx(VLANClientState *nc, const uint8_t *buf, size_t size)
+static ssize_t eth_rx(NetClientState *nc, const uint8_t *buf, size_t size)
 {
     struct XilinxAXIEnet *s = DO_UPCAST(NICState, nc, nc)->opaque;
     static const unsigned char sa_bcast[6] = {0xff, 0xff, 0xff,
@@ -780,7 +780,7 @@ static ssize_t eth_rx(VLANClientState *nc, const uint8_t *buf, size_t size)
     return size;
 }
 
-static void eth_cleanup(VLANClientState *nc)
+static void eth_cleanup(NetClientState *nc)
 {
     /* FIXME.  */
     struct XilinxAXIEnet *s = DO_UPCAST(NICState, nc, nc)->opaque;
diff --git a/hw/xilinx_ethlite.c b/hw/xilinx_ethlite.c
index 9006322..56ca620 100644
--- a/hw/xilinx_ethlite.c
+++ b/hw/xilinx_ethlite.c
@@ -160,7 +160,7 @@ static const MemoryRegionOps eth_ops = {
     }
 };
 
-static int eth_can_rx(VLANClientState *nc)
+static int eth_can_rx(NetClientState *nc)
 {
     struct xlx_ethlite *s = DO_UPCAST(NICState, nc, nc)->opaque;
     int r;
@@ -168,7 +168,7 @@ static int eth_can_rx(VLANClientState *nc)
     return r;
 }
 
-static ssize_t eth_rx(VLANClientState *nc, const uint8_t *buf, size_t size)
+static ssize_t eth_rx(NetClientState *nc, const uint8_t *buf, size_t size)
 {
     struct xlx_ethlite *s = DO_UPCAST(NICState, nc, nc)->opaque;
     unsigned int rxbase = s->rxbuf * (0x800 / 4);
@@ -194,7 +194,7 @@ static ssize_t eth_rx(VLANClientState *nc, const uint8_t *buf, size_t size)
     return size;
 }
 
-static void eth_cleanup(VLANClientState *nc)
+static void eth_cleanup(NetClientState *nc)
 {
     struct xlx_ethlite *s = DO_UPCAST(NICState, nc, nc)->opaque;
 
diff --git a/net.c b/net.c
index 65b45bb..33896fe 100644
--- a/net.c
+++ b/net.c
@@ -47,7 +47,7 @@
 # define CONFIG_NET_BRIDGE
 #endif
 
-static QTAILQ_HEAD(, VLANClientState) net_clients;
+static QTAILQ_HEAD(, NetClientState) net_clients;
 
 int default_net = 1;
 
@@ -132,7 +132,7 @@ int parse_host_port(struct sockaddr_in *saddr, const char *str)
     return 0;
 }
 
-void qemu_format_nic_info_str(VLANClientState *vc, uint8_t macaddr[6])
+void qemu_format_nic_info_str(NetClientState *vc, uint8_t macaddr[6])
 {
     snprintf(vc->info_str, sizeof(vc->info_str),
              "model=%s,macaddr=%02x:%02x:%02x:%02x:%02x:%02x",
@@ -162,9 +162,9 @@ void qemu_macaddr_default_if_unset(MACAddr *macaddr)
  * Only net clients created with the legacy -net option need this.  Naming is
  * mandatory for net clients created with -netdev.
  */
-static char *assign_name(VLANClientState *vc1, const char *model)
+static char *assign_name(NetClientState *vc1, const char *model)
 {
-    VLANClientState *vc;
+    NetClientState *vc;
     char buf[256];
     int id = 0;
 
@@ -184,25 +184,25 @@ static char *assign_name(VLANClientState *vc1, const char *model)
     return g_strdup(buf);
 }
 
-static ssize_t qemu_deliver_packet(VLANClientState *sender,
+static ssize_t qemu_deliver_packet(NetClientState *sender,
                                    unsigned flags,
                                    const uint8_t *data,
                                    size_t size,
                                    void *opaque);
-static ssize_t qemu_deliver_packet_iov(VLANClientState *sender,
+static ssize_t qemu_deliver_packet_iov(NetClientState *sender,
                                        unsigned flags,
                                        const struct iovec *iov,
                                        int iovcnt,
                                        void *opaque);
 
-VLANClientState *qemu_new_net_client(NetClientInfo *info,
-                                     VLANClientState *peer,
-                                     const char *model,
-                                     const char *name)
+NetClientState *qemu_new_net_client(NetClientInfo *info,
+                                    NetClientState *peer,
+                                    const char *model,
+                                    const char *name)
 {
-    VLANClientState *vc;
+    NetClientState *vc;
 
-    assert(info->size >= sizeof(VLANClientState));
+    assert(info->size >= sizeof(NetClientState));
 
     vc = g_malloc0(info->size);
 
@@ -234,7 +234,7 @@ NICState *qemu_new_nic(NetClientInfo *info,
                        const char *name,
                        void *opaque)
 {
-    VLANClientState *nc;
+    NetClientState *nc;
     NICState *nic;
 
     assert(info->type == NET_CLIENT_OPTIONS_KIND_NIC);
@@ -249,7 +249,7 @@ NICState *qemu_new_nic(NetClientInfo *info,
     return nic;
 }
 
-static void qemu_cleanup_vlan_client(VLANClientState *vc)
+static void qemu_cleanup_vlan_client(NetClientState *vc)
 {
     QTAILQ_REMOVE(&net_clients, vc, next);
 
@@ -258,7 +258,7 @@ static void qemu_cleanup_vlan_client(VLANClientState *vc)
     }
 }
 
-static void qemu_free_vlan_client(VLANClientState *vc)
+static void qemu_free_vlan_client(NetClientState *vc)
 {
     if (vc->send_queue) {
         qemu_del_net_queue(vc->send_queue);
@@ -271,7 +271,7 @@ static void qemu_free_vlan_client(VLANClientState *vc)
     g_free(vc);
 }
 
-void qemu_del_vlan_client(VLANClientState *vc)
+void qemu_del_vlan_client(NetClientState *vc)
 {
     /* If there is a peer NIC, delete and cleanup client, but do not free. */
     if (vc->peer && vc->peer->info->type == NET_CLIENT_OPTIONS_KIND_NIC) {
@@ -303,7 +303,7 @@ void qemu_del_vlan_client(VLANClientState *vc)
 
 void qemu_foreach_nic(qemu_nic_foreach func, void *opaque)
 {
-    VLANClientState *nc;
+    NetClientState *nc;
 
     QTAILQ_FOREACH(nc, &net_clients, next) {
         if (nc->info->type == NET_CLIENT_OPTIONS_KIND_NIC) {
@@ -312,7 +312,7 @@ void qemu_foreach_nic(qemu_nic_foreach func, void *opaque)
     }
 }
 
-int qemu_can_send_packet(VLANClientState *sender)
+int qemu_can_send_packet(NetClientState *sender)
 {
     if (!sender->peer) {
         return 1;
@@ -327,13 +327,13 @@ int qemu_can_send_packet(VLANClientState *sender)
     return 1;
 }
 
-static ssize_t qemu_deliver_packet(VLANClientState *sender,
+static ssize_t qemu_deliver_packet(NetClientState *sender,
                                    unsigned flags,
                                    const uint8_t *data,
                                    size_t size,
                                    void *opaque)
 {
-    VLANClientState *vc = opaque;
+    NetClientState *vc = opaque;
     ssize_t ret;
 
     if (vc->link_down) {
@@ -357,7 +357,7 @@ static ssize_t qemu_deliver_packet(VLANClientState *sender,
     return ret;
 }
 
-void qemu_purge_queued_packets(VLANClientState *vc)
+void qemu_purge_queued_packets(NetClientState *vc)
 {
     if (!vc->peer) {
         return;
@@ -366,14 +366,14 @@ void qemu_purge_queued_packets(VLANClientState *vc)
     qemu_net_queue_purge(vc->peer->send_queue, vc);
 }
 
-void qemu_flush_queued_packets(VLANClientState *vc)
+void qemu_flush_queued_packets(NetClientState *vc)
 {
     vc->receive_disabled = 0;
 
     qemu_net_queue_flush(vc->send_queue);
 }
 
-static ssize_t qemu_send_packet_async_with_flags(VLANClientState *sender,
+static ssize_t qemu_send_packet_async_with_flags(NetClientState *sender,
                                                  unsigned flags,
                                                  const uint8_t *buf, int size,
                                                  NetPacketSent *sent_cb)
@@ -394,7 +394,7 @@ static ssize_t qemu_send_packet_async_with_flags(VLANClientState *sender,
     return qemu_net_queue_send(queue, sender, flags, buf, size, sent_cb);
 }
 
-ssize_t qemu_send_packet_async(VLANClientState *sender,
+ssize_t qemu_send_packet_async(NetClientState *sender,
                                const uint8_t *buf, int size,
                                NetPacketSent *sent_cb)
 {
@@ -402,18 +402,18 @@ ssize_t qemu_send_packet_async(VLANClientState *sender,
                                              buf, size, sent_cb);
 }
 
-void qemu_send_packet(VLANClientState *vc, const uint8_t *buf, int size)
+void qemu_send_packet(NetClientState *vc, const uint8_t *buf, int size)
 {
     qemu_send_packet_async(vc, buf, size, NULL);
 }
 
-ssize_t qemu_send_packet_raw(VLANClientState *vc, const uint8_t *buf, int size)
+ssize_t qemu_send_packet_raw(NetClientState *vc, const uint8_t *buf, int size)
 {
     return qemu_send_packet_async_with_flags(vc, QEMU_NET_PACKET_FLAG_RAW,
                                              buf, size, NULL);
 }
 
-static ssize_t vc_sendv_compat(VLANClientState *vc, const struct iovec *iov,
+static ssize_t vc_sendv_compat(NetClientState *vc, const struct iovec *iov,
                                int iovcnt)
 {
     uint8_t buffer[4096];
@@ -424,13 +424,13 @@ static ssize_t vc_sendv_compat(VLANClientState *vc, const struct iovec *iov,
     return vc->info->receive(vc, buffer, offset);
 }
 
-static ssize_t qemu_deliver_packet_iov(VLANClientState *sender,
+static ssize_t qemu_deliver_packet_iov(NetClientState *sender,
                                        unsigned flags,
                                        const struct iovec *iov,
                                        int iovcnt,
                                        void *opaque)
 {
-    VLANClientState *vc = opaque;
+    NetClientState *vc = opaque;
 
     if (vc->link_down) {
         return iov_size(iov, iovcnt);
@@ -443,7 +443,7 @@ static ssize_t qemu_deliver_packet_iov(VLANClientState *sender,
     }
 }
 
-ssize_t qemu_sendv_packet_async(VLANClientState *sender,
+ssize_t qemu_sendv_packet_async(NetClientState *sender,
                                 const struct iovec *iov, int iovcnt,
                                 NetPacketSent *sent_cb)
 {
@@ -461,14 +461,14 @@ ssize_t qemu_sendv_packet_async(VLANClientState *sender,
 }
 
 ssize_t
-qemu_sendv_packet(VLANClientState *vc, const struct iovec *iov, int iovcnt)
+qemu_sendv_packet(NetClientState *vc, const struct iovec *iov, int iovcnt)
 {
     return qemu_sendv_packet_async(vc, iov, iovcnt, NULL);
 }
 
-VLANClientState *qemu_find_netdev(const char *id)
+NetClientState *qemu_find_netdev(const char *id)
 {
-    VLANClientState *vc;
+    NetClientState *vc;
 
     QTAILQ_FOREACH(vc, &net_clients, next) {
         if (vc->info->type == NET_CLIENT_OPTIONS_KIND_NIC)
@@ -553,7 +553,7 @@ int net_handle_fd_param(Monitor *mon, const char *param)
 }
 
 static int net_init_nic(const NetClientOptions *opts, const char *name,
-                        VLANClientState *peer)
+                        NetClientState *peer)
 {
     int idx;
     NICInfo *nd;
@@ -619,7 +619,7 @@ static int net_init_nic(const NetClientOptions *opts, const char *name,
 static int (* const net_client_init_fun[NET_CLIENT_OPTIONS_KIND_MAX])(
     const NetClientOptions *opts,
     const char *name,
-    VLANClientState *peer) = {
+    NetClientState *peer) = {
         [NET_CLIENT_OPTIONS_KIND_NIC]       = net_init_nic,
 #ifdef CONFIG_SLIRP
         [NET_CLIENT_OPTIONS_KIND_USER]      = net_init_slirp,
@@ -679,7 +679,7 @@ static int net_client_init1(const void *object, int is_netdev, Error **errp)
     }
 
     if (net_client_init_fun[opts->kind]) {
-        VLANClientState *peer = NULL;
+        NetClientState *peer = NULL;
 
         /* Do not add to a vlan if it's a -netdev or a nic with a netdev=
          * parameter. */
@@ -791,7 +791,7 @@ void net_host_device_add(Monitor *mon, const QDict *qdict)
 
 void net_host_device_remove(Monitor *mon, const QDict *qdict)
 {
-    VLANClientState *vc;
+    NetClientState *vc;
     int vlan_id = qdict_get_int(qdict, "vlan_id");
     const char *device = qdict_get_str(qdict, "device");
 
@@ -843,7 +843,7 @@ exit_err:
 
 void qmp_netdev_del(const char *id, Error **errp)
 {
-    VLANClientState *vc;
+    NetClientState *vc;
 
     vc = qemu_find_netdev(id);
     if (!vc) {
@@ -855,7 +855,7 @@ void qmp_netdev_del(const char *id, Error **errp)
     qemu_opts_del(qemu_opts_find(qemu_find_opts_err("netdev", errp), id));
 }
 
-static void print_net_client(Monitor *mon, VLANClientState *vc)
+static void print_net_client(Monitor *mon, NetClientState *vc)
 {
     monitor_printf(mon, "%s: type=%s,%s\n", vc->name,
                    NetClientOptionsKind_lookup[vc->info->type], vc->info_str);
@@ -863,7 +863,7 @@ static void print_net_client(Monitor *mon, VLANClientState *vc)
 
 void do_info_network(Monitor *mon)
 {
-    VLANClientState *vc, *peer;
+    NetClientState *vc, *peer;
     NetClientOptionsKind type;
 
     monitor_printf(mon, "Devices not on any VLAN:\n");
@@ -884,7 +884,7 @@ void do_info_network(Monitor *mon)
 
 void qmp_set_link(const char *name, bool up, Error **errp)
 {
-    VLANClientState *vc = NULL;
+    NetClientState *vc = NULL;
 
     QTAILQ_FOREACH(vc, &net_clients, next) {
         if (!strcmp(vc->name, name)) {
@@ -892,7 +892,6 @@ void qmp_set_link(const char *name, bool up, Error **errp)
         }
     }
 done:
-
     if (!vc) {
         error_set(errp, QERR_DEVICE_NOT_FOUND, name);
         return;
@@ -918,7 +917,7 @@ done:
 
 void net_cleanup(void)
 {
-    VLANClientState *vc, *next_vc;
+    NetClientState *vc, *next_vc;
 
     QTAILQ_FOREACH_SAFE(vc, &net_clients, next, next_vc) {
         qemu_del_vlan_client(vc);
@@ -927,7 +926,7 @@ void net_cleanup(void)
 
 void net_check_clients(void)
 {
-    VLANClientState *vc;
+    NetClientState *vc;
     int i;
 
     /* Don't warn about the default network setup that you get if
diff --git a/net.h b/net.h
index 4e0217a..5857e87 100644
--- a/net.h
+++ b/net.h
@@ -17,7 +17,7 @@ struct MACAddr {
 
 typedef struct NICConf {
     MACAddr macaddr;
-    VLANClientState *peer;
+    NetClientState *peer;
     int32_t bootindex;
 } NICConf;
 
@@ -27,14 +27,14 @@ typedef struct NICConf {
     DEFINE_PROP_NETDEV("netdev", _state, _conf.peer),                   \
     DEFINE_PROP_INT32("bootindex", _state, _conf.bootindex, -1)
 
-/* VLANs support */
+/* Net clients */
 
-typedef void (NetPoll)(VLANClientState *, bool enable);
-typedef int (NetCanReceive)(VLANClientState *);
-typedef ssize_t (NetReceive)(VLANClientState *, const uint8_t *, size_t);
-typedef ssize_t (NetReceiveIOV)(VLANClientState *, const struct iovec *, int);
-typedef void (NetCleanup) (VLANClientState *);
-typedef void (LinkStatusChanged)(VLANClientState *);
+typedef void (NetPoll)(NetClientState *, bool enable);
+typedef int (NetCanReceive)(NetClientState *);
+typedef ssize_t (NetReceive)(NetClientState *, const uint8_t *, size_t);
+typedef ssize_t (NetReceiveIOV)(NetClientState *, const struct iovec *, int);
+typedef void (NetCleanup) (NetClientState *);
+typedef void (LinkStatusChanged)(NetClientState *);
 
 typedef struct NetClientInfo {
     NetClientOptionsKind type;
@@ -48,11 +48,11 @@ typedef struct NetClientInfo {
     NetPoll *poll;
 } NetClientInfo;
 
-struct VLANClientState {
+struct NetClientState {
     NetClientInfo *info;
     int link_down;
-    QTAILQ_ENTRY(VLANClientState) next;
-    VLANClientState *peer;
+    QTAILQ_ENTRY(NetClientState) next;
+    NetClientState *peer;
     NetQueue *send_queue;
     char *model;
     char *name;
@@ -61,39 +61,39 @@ struct VLANClientState {
 };
 
 typedef struct NICState {
-    VLANClientState nc;
+    NetClientState nc;
     NICConf *conf;
     void *opaque;
     bool peer_deleted;
 } NICState;
 
-VLANClientState *qemu_find_netdev(const char *id);
-VLANClientState *qemu_new_net_client(NetClientInfo *info,
-                                     VLANClientState *peer,
-                                     const char *model,
-                                     const char *name);
+NetClientState *qemu_find_netdev(const char *id);
+NetClientState *qemu_new_net_client(NetClientInfo *info,
+                                    NetClientState *peer,
+                                    const char *model,
+                                    const char *name);
 NICState *qemu_new_nic(NetClientInfo *info,
                        NICConf *conf,
                        const char *model,
                        const char *name,
                        void *opaque);
-void qemu_del_vlan_client(VLANClientState *vc);
-VLANClientState *qemu_find_vlan_client_by_name(Monitor *mon, int vlan_id,
-                                               const char *client_str);
+void qemu_del_vlan_client(NetClientState *vc);
+NetClientState *qemu_find_vlan_client_by_name(Monitor *mon, int vlan_id,
+                                              const char *client_str);
 typedef void (*qemu_nic_foreach)(NICState *nic, void *opaque);
 void qemu_foreach_nic(qemu_nic_foreach func, void *opaque);
-int qemu_can_send_packet(VLANClientState *vc);
-ssize_t qemu_sendv_packet(VLANClientState *vc, const struct iovec *iov,
+int qemu_can_send_packet(NetClientState *vc);
+ssize_t qemu_sendv_packet(NetClientState *vc, const struct iovec *iov,
                           int iovcnt);
-ssize_t qemu_sendv_packet_async(VLANClientState *vc, const struct iovec *iov,
+ssize_t qemu_sendv_packet_async(NetClientState *vc, const struct iovec *iov,
                                 int iovcnt, NetPacketSent *sent_cb);
-void qemu_send_packet(VLANClientState *vc, const uint8_t *buf, int size);
-ssize_t qemu_send_packet_raw(VLANClientState *vc, const uint8_t *buf, int size);
-ssize_t qemu_send_packet_async(VLANClientState *vc, const uint8_t *buf,
+void qemu_send_packet(NetClientState *vc, const uint8_t *buf, int size);
+ssize_t qemu_send_packet_raw(NetClientState *vc, const uint8_t *buf, int size);
+ssize_t qemu_send_packet_async(NetClientState *vc, const uint8_t *buf,
                                int size, NetPacketSent *sent_cb);
-void qemu_purge_queued_packets(VLANClientState *vc);
-void qemu_flush_queued_packets(VLANClientState *vc);
-void qemu_format_nic_info_str(VLANClientState *vc, uint8_t macaddr[6]);
+void qemu_purge_queued_packets(NetClientState *vc);
+void qemu_flush_queued_packets(NetClientState *vc);
+void qemu_format_nic_info_str(NetClientState *vc, uint8_t macaddr[6]);
 void qemu_macaddr_default_if_unset(MACAddr *macaddr);
 int qemu_show_nic_models(const char *arg, const char *const *models);
 void qemu_check_nic_model(NICInfo *nd, const char *model);
@@ -111,7 +111,7 @@ struct NICInfo {
     char *model;
     char *name;
     char *devaddr;
-    VLANClientState *netdev;
+    NetClientState *netdev;
     int used;         /* is this slot in nd_table[] being used? */
     int instantiated; /* does this NICInfo correspond to an instantiated NIC? */
     int nvectors;
diff --git a/net/dump.c b/net/dump.c
index 69d5abe..004231d 100644
--- a/net/dump.c
+++ b/net/dump.c
@@ -30,7 +30,7 @@
 #include "hub.h"
 
 typedef struct DumpState {
-    VLANClientState nc;
+    NetClientState nc;
     int64_t start_ts;
     int fd;
     int pcap_caplen;
@@ -57,7 +57,7 @@ struct pcap_sf_pkthdr {
     uint32_t len;
 };
 
-static ssize_t dump_receive(VLANClientState *nc, const uint8_t *buf, size_t size)
+static ssize_t dump_receive(NetClientState *nc, const uint8_t *buf, size_t size)
 {
     DumpState *s = DO_UPCAST(DumpState, nc, nc);
     struct pcap_sf_pkthdr hdr;
@@ -86,7 +86,7 @@ static ssize_t dump_receive(VLANClientState *nc, const uint8_t *buf, size_t size
     return size;
 }
 
-static void dump_cleanup(VLANClientState *nc)
+static void dump_cleanup(NetClientState *nc)
 {
     DumpState *s = DO_UPCAST(DumpState, nc, nc);
 
@@ -100,11 +100,11 @@ static NetClientInfo net_dump_info = {
     .cleanup = dump_cleanup,
 };
 
-static int net_dump_init(VLANClientState *peer, const char *device,
+static int net_dump_init(NetClientState *peer, const char *device,
                          const char *name, const char *filename, int len)
 {
     struct pcap_file_hdr hdr;
-    VLANClientState *nc;
+    NetClientState *nc;
     DumpState *s;
     struct tm tm;
     int fd;
@@ -146,7 +146,7 @@ static int net_dump_init(VLANClientState *peer, const char *device,
 }
 
 int net_init_dump(const NetClientOptions *opts, const char *name,
-                  VLANClientState *peer)
+                  NetClientState *peer)
 {
     int len;
     const char *file;
diff --git a/net/dump.h b/net/dump.h
index 9d70195..33f152b 100644
--- a/net/dump.h
+++ b/net/dump.h
@@ -28,6 +28,6 @@
 #include "qapi-types.h"
 
 int net_init_dump(const NetClientOptions *opts, const char *name,
-                  VLANClientState *peer);
+                  NetClientState *peer);
 
 #endif /* QEMU_NET_DUMP_H */
diff --git a/net/hub.c b/net/hub.c
index e80d131..900fa4e 100644
--- a/net/hub.c
+++ b/net/hub.c
@@ -25,7 +25,7 @@
 typedef struct NetHub NetHub;
 
 typedef struct NetHubPort {
-    VLANClientState nc;
+    NetClientState nc;
     QLIST_ENTRY(NetHubPort) next;
     NetHub *hub;
     int id;
@@ -85,7 +85,7 @@ static NetHub *net_hub_new(int id)
     return hub;
 }
 
-static ssize_t net_hub_port_receive(VLANClientState *nc,
+static ssize_t net_hub_port_receive(NetClientState *nc,
                                     const uint8_t *buf, size_t len)
 {
     NetHubPort *port = DO_UPCAST(NetHubPort, nc, nc);
@@ -93,7 +93,7 @@ static ssize_t net_hub_port_receive(VLANClientState *nc,
     return net_hub_receive(port->hub, port, buf, len);
 }
 
-static ssize_t net_hub_port_receive_iov(VLANClientState *nc,
+static ssize_t net_hub_port_receive_iov(NetClientState *nc,
                                         const struct iovec *iov, int iovcnt)
 {
     NetHubPort *port = DO_UPCAST(NetHubPort, nc, nc);
@@ -101,7 +101,7 @@ static ssize_t net_hub_port_receive_iov(VLANClientState *nc,
     return net_hub_receive_iov(port->hub, port, iov, iovcnt);
 }
 
-static void net_hub_port_cleanup(VLANClientState *nc)
+static void net_hub_port_cleanup(NetClientState *nc)
 {
     NetHubPort *port = DO_UPCAST(NetHubPort, nc, nc);
 
@@ -118,7 +118,7 @@ static NetClientInfo net_hub_port_info = {
 
 static NetHubPort *net_hub_port_new(NetHub *hub, const char *name)
 {
-    VLANClientState *nc;
+    NetClientState *nc;
     NetHubPort *port;
     int id = hub->num_ports++;
     char default_name[128];
@@ -145,7 +145,7 @@ static NetHubPort *net_hub_port_new(NetHub *hub, const char *name)
  *
  * If there is no existing hub with the given id then a new hub is created.
  */
-VLANClientState *net_hub_add_port(int hub_id, const char *name)
+NetClientState *net_hub_add_port(int hub_id, const char *name)
 {
     NetHub *hub;
     NetHubPort *port;
@@ -167,11 +167,11 @@ VLANClientState *net_hub_add_port(int hub_id, const char *name)
 /**
  * Find a specific client on a hub
  */
-VLANClientState *net_hub_find_client_by_name(int hub_id, const char *name)
+NetClientState *net_hub_find_client_by_name(int hub_id, const char *name)
 {
     NetHub *hub;
     NetHubPort *port;
-    VLANClientState *peer;
+    NetClientState *peer;
 
     QLIST_FOREACH(hub, &hubs, next) {
         if (hub->id == hub_id) {
@@ -190,11 +190,11 @@ VLANClientState *net_hub_find_client_by_name(int hub_id, const char *name)
 /**
  * Find a available port on a hub; otherwise create one new port
  */
-VLANClientState *net_hub_port_find(int hub_id)
+NetClientState *net_hub_port_find(int hub_id)
 {
     NetHub *hub;
     NetHubPort *port;
-    VLANClientState *nc;
+    NetClientState *nc;
 
     QLIST_FOREACH(hub, &hubs, next) {
         if (hub->id == hub_id) {
@@ -234,7 +234,7 @@ void net_hub_info(Monitor *mon)
  *
  * @id              Pointer for hub id output, may be NULL
  */
-int net_hub_id_for_client(VLANClientState *nc, int *id)
+int net_hub_id_for_client(NetClientState *nc, int *id)
 {
     NetHubPort *port;
 
@@ -254,7 +254,7 @@ int net_hub_id_for_client(VLANClientState *nc, int *id)
 }
 
 int net_init_hubport(const NetClientOptions *opts, const char *name,
-                     VLANClientState *peer)
+                     NetClientState *peer)
 {
     const NetdevHubPortOptions *hubport;
 
@@ -277,7 +277,7 @@ void net_hub_check_clients(void)
 {
     NetHub *hub;
     NetHubPort *port;
-    VLANClientState *peer;
+    NetClientState *peer;
 
     QLIST_FOREACH(hub, &hubs, next) {
         int has_nic = 0, has_host_dev = 0;
diff --git a/net/hub.h b/net/hub.h
index 3906df2..26a1ade 100644
--- a/net/hub.h
+++ b/net/hub.h
@@ -18,12 +18,12 @@
 #include "qemu-common.h"
 
 int net_init_hubport(const NetClientOptions *opts, const char *name,
-                     VLANClientState *peer);
-VLANClientState *net_hub_add_port(int hub_id, const char *name);
-VLANClientState *net_hub_find_client_by_name(int hub_id, const char *name);
+                     NetClientState *peer);
+NetClientState *net_hub_add_port(int hub_id, const char *name);
+NetClientState *net_hub_find_client_by_name(int hub_id, const char *name);
 void net_hub_info(Monitor *mon);
-int net_hub_id_for_client(VLANClientState *nc, int *id);
+int net_hub_id_for_client(NetClientState *nc, int *id);
 void net_hub_check_clients(void);
-VLANClientState *net_hub_port_find(int hub_id);
+NetClientState *net_hub_port_find(int hub_id);
 
 #endif /* NET_HUB_H */
diff --git a/net/queue.c b/net/queue.c
index 1ab5247..35c3463 100644
--- a/net/queue.c
+++ b/net/queue.c
@@ -40,7 +40,7 @@
 
 struct NetPacket {
     QTAILQ_ENTRY(NetPacket) entry;
-    VLANClientState *sender;
+    NetClientState *sender;
     unsigned flags;
     int size;
     NetPacketSent *sent_cb;
@@ -89,7 +89,7 @@ void qemu_del_net_queue(NetQueue *queue)
 }
 
 static ssize_t qemu_net_queue_append(NetQueue *queue,
-                                     VLANClientState *sender,
+                                     NetClientState *sender,
                                      unsigned flags,
                                      const uint8_t *buf,
                                      size_t size,
@@ -110,7 +110,7 @@ static ssize_t qemu_net_queue_append(NetQueue *queue,
 }
 
 static ssize_t qemu_net_queue_append_iov(NetQueue *queue,
-                                         VLANClientState *sender,
+                                         NetClientState *sender,
                                          unsigned flags,
                                          const struct iovec *iov,
                                          int iovcnt,
@@ -143,7 +143,7 @@ static ssize_t qemu_net_queue_append_iov(NetQueue *queue,
 }
 
 static ssize_t qemu_net_queue_deliver(NetQueue *queue,
-                                      VLANClientState *sender,
+                                      NetClientState *sender,
                                       unsigned flags,
                                       const uint8_t *data,
                                       size_t size)
@@ -158,7 +158,7 @@ static ssize_t qemu_net_queue_deliver(NetQueue *queue,
 }
 
 static ssize_t qemu_net_queue_deliver_iov(NetQueue *queue,
-                                          VLANClientState *sender,
+                                          NetClientState *sender,
                                           unsigned flags,
                                           const struct iovec *iov,
                                           int iovcnt)
@@ -173,7 +173,7 @@ static ssize_t qemu_net_queue_deliver_iov(NetQueue *queue,
 }
 
 ssize_t qemu_net_queue_send(NetQueue *queue,
-                            VLANClientState *sender,
+                            NetClientState *sender,
                             unsigned flags,
                             const uint8_t *data,
                             size_t size,
@@ -197,7 +197,7 @@ ssize_t qemu_net_queue_send(NetQueue *queue,
 }
 
 ssize_t qemu_net_queue_send_iov(NetQueue *queue,
-                                VLANClientState *sender,
+                                NetClientState *sender,
                                 unsigned flags,
                                 const struct iovec *iov,
                                 int iovcnt,
@@ -220,7 +220,7 @@ ssize_t qemu_net_queue_send_iov(NetQueue *queue,
     return ret;
 }
 
-void qemu_net_queue_purge(NetQueue *queue, VLANClientState *from)
+void qemu_net_queue_purge(NetQueue *queue, NetClientState *from)
 {
     NetPacket *packet, *next;
 
diff --git a/net/queue.h b/net/queue.h
index a31958e..d8eac0b 100644
--- a/net/queue.h
+++ b/net/queue.h
@@ -29,15 +29,15 @@
 typedef struct NetPacket NetPacket;
 typedef struct NetQueue NetQueue;
 
-typedef void (NetPacketSent) (VLANClientState *sender, ssize_t ret);
+typedef void (NetPacketSent) (NetClientState *sender, ssize_t ret);
 
-typedef ssize_t (NetPacketDeliver) (VLANClientState *sender,
+typedef ssize_t (NetPacketDeliver) (NetClientState *sender,
                                     unsigned flags,
                                     const uint8_t *buf,
                                     size_t size,
                                     void *opaque);
 
-typedef ssize_t (NetPacketDeliverIOV) (VLANClientState *sender,
+typedef ssize_t (NetPacketDeliverIOV) (NetClientState *sender,
                                        unsigned flags,
                                        const struct iovec *iov,
                                        int iovcnt,
@@ -52,20 +52,20 @@ NetQueue *qemu_new_net_queue(NetPacketDeliver *deliver,
 void qemu_del_net_queue(NetQueue *queue);
 
 ssize_t qemu_net_queue_send(NetQueue *queue,
-                            VLANClientState *sender,
+                            NetClientState *sender,
                             unsigned flags,
                             const uint8_t *data,
                             size_t size,
                             NetPacketSent *sent_cb);
 
 ssize_t qemu_net_queue_send_iov(NetQueue *queue,
-                                VLANClientState *sender,
+                                NetClientState *sender,
                                 unsigned flags,
                                 const struct iovec *iov,
                                 int iovcnt,
                                 NetPacketSent *sent_cb);
 
-void qemu_net_queue_purge(NetQueue *queue, VLANClientState *from);
+void qemu_net_queue_purge(NetQueue *queue, NetClientState *from);
 void qemu_net_queue_flush(NetQueue *queue);
 
 #endif /* QEMU_NET_QUEUE_H */
diff --git a/net/slirp.c b/net/slirp.c
index 85d6fb4..1bdad37 100644
--- a/net/slirp.c
+++ b/net/slirp.c
@@ -68,7 +68,7 @@ struct slirp_config_str {
 };
 
 typedef struct SlirpState {
-    VLANClientState nc;
+    NetClientState nc;
     QTAILQ_ENTRY(SlirpState) entry;
     Slirp *slirp;
 #ifndef _WIN32
@@ -111,7 +111,7 @@ void slirp_output(void *opaque, const uint8_t *pkt, int pkt_len)
     qemu_send_packet(&s->nc, pkt, pkt_len);
 }
 
-static ssize_t net_slirp_receive(VLANClientState *nc, const uint8_t *buf, size_t size)
+static ssize_t net_slirp_receive(NetClientState *nc, const uint8_t *buf, size_t size)
 {
     SlirpState *s = DO_UPCAST(SlirpState, nc, nc);
 
@@ -120,7 +120,7 @@ static ssize_t net_slirp_receive(VLANClientState *nc, const uint8_t *buf, size_t
     return size;
 }
 
-static void net_slirp_cleanup(VLANClientState *nc)
+static void net_slirp_cleanup(NetClientState *nc)
 {
     SlirpState *s = DO_UPCAST(SlirpState, nc, nc);
 
@@ -136,7 +136,7 @@ static NetClientInfo net_slirp_info = {
     .cleanup = net_slirp_cleanup,
 };
 
-static int net_slirp_init(VLANClientState *peer, const char *model,
+static int net_slirp_init(NetClientState *peer, const char *model,
                           const char *name, int restricted,
                           const char *vnetwork, const char *vhost,
                           const char *vhostname, const char *tftp_export,
@@ -153,7 +153,7 @@ static int net_slirp_init(VLANClientState *peer, const char *model,
 #ifndef _WIN32
     struct in_addr smbsrv = { .s_addr = 0 };
 #endif
-    VLANClientState *nc;
+    NetClientState *nc;
     SlirpState *s;
     char buf[20];
     uint32_t addr;
@@ -284,7 +284,7 @@ static SlirpState *slirp_lookup(Monitor *mon, const char *vlan,
 {
 
     if (vlan) {
-        VLANClientState *nc;
+        NetClientState *nc;
         nc = net_hub_find_client_by_name(strtol(vlan, NULL, 0), stack);
         if (!nc) {
             return NULL;
@@ -706,7 +706,7 @@ net_init_slirp_configs(const StringList *fwd, int flags)
 }
 
 int net_init_slirp(const NetClientOptions *opts, const char *name,
-                   VLANClientState *peer)
+                   NetClientState *peer)
 {
     struct slirp_config_str *config;
     char *vnet;
diff --git a/net/slirp.h b/net/slirp.h
index 1ff21b0..5f685c4 100644
--- a/net/slirp.h
+++ b/net/slirp.h
@@ -32,7 +32,7 @@
 #ifdef CONFIG_SLIRP
 
 int net_init_slirp(const NetClientOptions *opts, const char *name,
-                   VLANClientState *peer);
+                   NetClientState *peer);
 
 void net_slirp_hostfwd_add(Monitor *mon, const QDict *qdict);
 void net_slirp_hostfwd_remove(Monitor *mon, const QDict *qdict);
diff --git a/net/socket.c b/net/socket.c
index 31bbb30..65828cd 100644
--- a/net/socket.c
+++ b/net/socket.c
@@ -34,7 +34,7 @@
 #include "qemu_socket.h"
 
 typedef struct NetSocketState {
-    VLANClientState nc;
+    NetClientState nc;
     int fd;
     int state; /* 0 = getting length, 1 = getting data */
     unsigned int index;
@@ -44,14 +44,14 @@ typedef struct NetSocketState {
 } NetSocketState;
 
 typedef struct NetSocketListenState {
-    VLANClientState *peer;
+    NetClientState *peer;
     char *model;
     char *name;
     int fd;
 } NetSocketListenState;
 
 /* XXX: we consider we can send the whole packet without blocking */
-static ssize_t net_socket_receive(VLANClientState *nc, const uint8_t *buf, size_t size)
+static ssize_t net_socket_receive(NetClientState *nc, const uint8_t *buf, size_t size)
 {
     NetSocketState *s = DO_UPCAST(NetSocketState, nc, nc);
     uint32_t len;
@@ -61,7 +61,7 @@ static ssize_t net_socket_receive(VLANClientState *nc, const uint8_t *buf, size_
     return send_all(s->fd, buf, size);
 }
 
-static ssize_t net_socket_receive_dgram(VLANClientState *nc, const uint8_t *buf, size_t size)
+static ssize_t net_socket_receive_dgram(NetClientState *nc, const uint8_t *buf, size_t size)
 {
     NetSocketState *s = DO_UPCAST(NetSocketState, nc, nc);
 
@@ -231,7 +231,7 @@ fail:
     return -1;
 }
 
-static void net_socket_cleanup(VLANClientState *nc)
+static void net_socket_cleanup(NetClientState *nc)
 {
     NetSocketState *s = DO_UPCAST(NetSocketState, nc, nc);
     qemu_set_fd_handler(s->fd, NULL, NULL, NULL);
@@ -245,7 +245,7 @@ static NetClientInfo net_dgram_socket_info = {
     .cleanup = net_socket_cleanup,
 };
 
-static NetSocketState *net_socket_fd_init_dgram(VLANClientState *peer,
+static NetSocketState *net_socket_fd_init_dgram(NetClientState *peer,
                                                 const char *model,
                                                 const char *name,
                                                 int fd, int is_connected)
@@ -253,7 +253,7 @@ static NetSocketState *net_socket_fd_init_dgram(VLANClientState *peer,
     struct sockaddr_in saddr;
     int newfd;
     socklen_t saddr_len;
-    VLANClientState *nc;
+    NetClientState *nc;
     NetSocketState *s;
 
     /* fd passed: multicast: "learn" dgram_dst address from bound address and save it
@@ -323,12 +323,12 @@ static NetClientInfo net_socket_info = {
     .cleanup = net_socket_cleanup,
 };
 
-static NetSocketState *net_socket_fd_init_stream(VLANClientState *peer,
+static NetSocketState *net_socket_fd_init_stream(NetClientState *peer,
                                                  const char *model,
                                                  const char *name,
                                                  int fd, int is_connected)
 {
-    VLANClientState *nc;
+    NetClientState *nc;
     NetSocketState *s;
 
     nc = qemu_new_net_client(&net_socket_info, peer, model, name);
@@ -347,7 +347,7 @@ static NetSocketState *net_socket_fd_init_stream(VLANClientState *peer,
     return s;
 }
 
-static NetSocketState *net_socket_fd_init(VLANClientState *peer,
+static NetSocketState *net_socket_fd_init(NetClientState *peer,
                                           const char *model, const char *name,
                                           int fd, int is_connected)
 {
@@ -398,7 +398,7 @@ static void net_socket_accept(void *opaque)
     }
 }
 
-static int net_socket_listen_init(VLANClientState *peer,
+static int net_socket_listen_init(NetClientState *peer,
                                   const char *model,
                                   const char *name,
                                   const char *host_str)
@@ -446,7 +446,7 @@ static int net_socket_listen_init(VLANClientState *peer,
     return 0;
 }
 
-static int net_socket_connect_init(VLANClientState *peer,
+static int net_socket_connect_init(NetClientState *peer,
                                    const char *model,
                                    const char *name,
                                    const char *host_str)
@@ -496,7 +496,7 @@ static int net_socket_connect_init(VLANClientState *peer,
     return 0;
 }
 
-static int net_socket_mcast_init(VLANClientState *peer,
+static int net_socket_mcast_init(NetClientState *peer,
                                  const char *model,
                                  const char *name,
                                  const char *host_str,
@@ -535,7 +535,7 @@ static int net_socket_mcast_init(VLANClientState *peer,
 
 }
 
-static int net_socket_udp_init(VLANClientState *peer,
+static int net_socket_udp_init(NetClientState *peer,
                                  const char *model,
                                  const char *name,
                                  const char *rhost,
@@ -587,7 +587,7 @@ static int net_socket_udp_init(VLANClientState *peer,
 }
 
 int net_init_socket(const NetClientOptions *opts, const char *name,
-                    VLANClientState *peer)
+                    NetClientState *peer)
 {
     const NetdevSocketOptions *sock;
 
diff --git a/net/socket.h b/net/socket.h
index 82b4d16..3f8a092 100644
--- a/net/socket.h
+++ b/net/socket.h
@@ -28,6 +28,6 @@
 #include "qapi-types.h"
 
 int net_init_socket(const NetClientOptions *opts, const char *name,
-                    VLANClientState *peer);
+                    NetClientState *peer);
 
 #endif /* QEMU_NET_SOCKET_H */
diff --git a/net/tap-win32.c b/net/tap-win32.c
index c4c98aa..dcc7a64 100644
--- a/net/tap-win32.c
+++ b/net/tap-win32.c
@@ -630,11 +630,11 @@ static int tap_win32_open(tap_win32_overlapped_t **phandle,
 /********************************************/
 
  typedef struct TAPState {
-     VLANClientState nc;
+     NetClientState nc;
      tap_win32_overlapped_t *handle;
  } TAPState;
 
-static void tap_cleanup(VLANClientState *nc)
+static void tap_cleanup(NetClientState *nc)
 {
     TAPState *s = DO_UPCAST(TAPState, nc, nc);
 
@@ -645,7 +645,7 @@ static void tap_cleanup(VLANClientState *nc)
     */
 }
 
-static ssize_t tap_receive(VLANClientState *nc, const uint8_t *buf, size_t size)
+static ssize_t tap_receive(NetClientState *nc, const uint8_t *buf, size_t size)
 {
     TAPState *s = DO_UPCAST(TAPState, nc, nc);
 
@@ -673,10 +673,10 @@ static NetClientInfo net_tap_win32_info = {
     .cleanup = tap_cleanup,
 };
 
-static int tap_win32_init(VLANClientState *peer, const char *model,
+static int tap_win32_init(NetClientState *peer, const char *model,
                           const char *name, const char *ifname)
 {
-    VLANClientState *nc;
+    NetClientState *nc;
     TAPState *s;
     tap_win32_overlapped_t *handle;
 
@@ -700,7 +700,7 @@ static int tap_win32_init(VLANClientState *peer, const char *model,
 }
 
 int net_init_tap(const NetClientOptions *opts, const char *name,
-                 VLANClientState *peer)
+                 NetClientState *peer)
 {
     const NetdevTapOptions *tap;
 
@@ -719,12 +719,12 @@ int net_init_tap(const NetClientOptions *opts, const char *name,
     return 0;
 }
 
-int tap_has_ufo(VLANClientState *vc)
+int tap_has_ufo(NetClientState *vc)
 {
     return 0;
 }
 
-int tap_has_vnet_hdr(VLANClientState *vc)
+int tap_has_vnet_hdr(NetClientState *vc)
 {
     return 0;
 }
@@ -738,16 +738,16 @@ void tap_fd_set_vnet_hdr_len(int fd, int len)
 {
 }
 
-void tap_using_vnet_hdr(VLANClientState *vc, int using_vnet_hdr)
+void tap_using_vnet_hdr(NetClientState *vc, int using_vnet_hdr)
 {
 }
 
-void tap_set_offload(VLANClientState *vc, int csum, int tso4,
+void tap_set_offload(NetClientState *vc, int csum, int tso4,
                      int tso6, int ecn, int ufo)
 {
 }
 
-struct vhost_net *tap_get_vhost_net(VLANClientState *nc)
+struct vhost_net *tap_get_vhost_net(NetClientState *nc)
 {
     return NULL;
 }
diff --git a/net/tap.c b/net/tap.c
index 10ae98d..1971525 100644
--- a/net/tap.c
+++ b/net/tap.c
@@ -50,7 +50,7 @@
 #define TAP_BUFSIZE (4096 + 65536)
 
 typedef struct TAPState {
-    VLANClientState nc;
+    NetClientState nc;
     int fd;
     char down_script[1024];
     char down_script_arg[128];
@@ -115,7 +115,7 @@ static ssize_t tap_write_packet(TAPState *s, const struct iovec *iov, int iovcnt
     return len;
 }
 
-static ssize_t tap_receive_iov(VLANClientState *nc, const struct iovec *iov,
+static ssize_t tap_receive_iov(NetClientState *nc, const struct iovec *iov,
                                int iovcnt)
 {
     TAPState *s = DO_UPCAST(TAPState, nc, nc);
@@ -134,7 +134,7 @@ static ssize_t tap_receive_iov(VLANClientState *nc, const struct iovec *iov,
     return tap_write_packet(s, iovp, iovcnt);
 }
 
-static ssize_t tap_receive_raw(VLANClientState *nc, const uint8_t *buf, size_t size)
+static ssize_t tap_receive_raw(NetClientState *nc, const uint8_t *buf, size_t size)
 {
     TAPState *s = DO_UPCAST(TAPState, nc, nc);
     struct iovec iov[2];
@@ -154,7 +154,7 @@ static ssize_t tap_receive_raw(VLANClientState *nc, const uint8_t *buf, size_t s
     return tap_write_packet(s, iov, iovcnt);
 }
 
-static ssize_t tap_receive(VLANClientState *nc, const uint8_t *buf, size_t size)
+static ssize_t tap_receive(NetClientState *nc, const uint8_t *buf, size_t size)
 {
     TAPState *s = DO_UPCAST(TAPState, nc, nc);
     struct iovec iov[1];
@@ -183,7 +183,7 @@ ssize_t tap_read_packet(int tapfd, uint8_t *buf, int maxlen)
 }
 #endif
 
-static void tap_send_completed(VLANClientState *nc, ssize_t len)
+static void tap_send_completed(NetClientState *nc, ssize_t len)
 {
     TAPState *s = DO_UPCAST(TAPState, nc, nc);
     tap_read_poll(s, 1);
@@ -214,7 +214,7 @@ static void tap_send(void *opaque)
     } while (size > 0 && qemu_can_send_packet(&s->nc));
 }
 
-int tap_has_ufo(VLANClientState *nc)
+int tap_has_ufo(NetClientState *nc)
 {
     TAPState *s = DO_UPCAST(TAPState, nc, nc);
 
@@ -223,7 +223,7 @@ int tap_has_ufo(VLANClientState *nc)
     return s->has_ufo;
 }
 
-int tap_has_vnet_hdr(VLANClientState *nc)
+int tap_has_vnet_hdr(NetClientState *nc)
 {
     TAPState *s = DO_UPCAST(TAPState, nc, nc);
 
@@ -232,7 +232,7 @@ int tap_has_vnet_hdr(VLANClientState *nc)
     return !!s->host_vnet_hdr_len;
 }
 
-int tap_has_vnet_hdr_len(VLANClientState *nc, int len)
+int tap_has_vnet_hdr_len(NetClientState *nc, int len)
 {
     TAPState *s = DO_UPCAST(TAPState, nc, nc);
 
@@ -241,7 +241,7 @@ int tap_has_vnet_hdr_len(VLANClientState *nc, int len)
     return tap_probe_vnet_hdr_len(s->fd, len);
 }
 
-void tap_set_vnet_hdr_len(VLANClientState *nc, int len)
+void tap_set_vnet_hdr_len(NetClientState *nc, int len)
 {
     TAPState *s = DO_UPCAST(TAPState, nc, nc);
 
@@ -253,7 +253,7 @@ void tap_set_vnet_hdr_len(VLANClientState *nc, int len)
     s->host_vnet_hdr_len = len;
 }
 
-void tap_using_vnet_hdr(VLANClientState *nc, int using_vnet_hdr)
+void tap_using_vnet_hdr(NetClientState *nc, int using_vnet_hdr)
 {
     TAPState *s = DO_UPCAST(TAPState, nc, nc);
 
@@ -265,7 +265,7 @@ void tap_using_vnet_hdr(VLANClientState *nc, int using_vnet_hdr)
     s->using_vnet_hdr = using_vnet_hdr;
 }
 
-void tap_set_offload(VLANClientState *nc, int csum, int tso4,
+void tap_set_offload(NetClientState *nc, int csum, int tso4,
                      int tso6, int ecn, int ufo)
 {
     TAPState *s = DO_UPCAST(TAPState, nc, nc);
@@ -276,7 +276,7 @@ void tap_set_offload(VLANClientState *nc, int csum, int tso4,
     tap_fd_set_offload(s->fd, csum, tso4, tso6, ecn, ufo);
 }
 
-static void tap_cleanup(VLANClientState *nc)
+static void tap_cleanup(NetClientState *nc)
 {
     TAPState *s = DO_UPCAST(TAPState, nc, nc);
 
@@ -296,14 +296,14 @@ static void tap_cleanup(VLANClientState *nc)
     s->fd = -1;
 }
 
-static void tap_poll(VLANClientState *nc, bool enable)
+static void tap_poll(NetClientState *nc, bool enable)
 {
     TAPState *s = DO_UPCAST(TAPState, nc, nc);
     tap_read_poll(s, enable);
     tap_write_poll(s, enable);
 }
 
-int tap_get_fd(VLANClientState *nc)
+int tap_get_fd(NetClientState *nc)
 {
     TAPState *s = DO_UPCAST(TAPState, nc, nc);
     assert(nc->info->type == NET_CLIENT_OPTIONS_KIND_TAP);
@@ -322,13 +322,13 @@ static NetClientInfo net_tap_info = {
     .cleanup = tap_cleanup,
 };
 
-static TAPState *net_tap_fd_init(VLANClientState *peer,
+static TAPState *net_tap_fd_init(NetClientState *peer,
                                  const char *model,
                                  const char *name,
                                  int fd,
                                  int vnet_hdr)
 {
-    VLANClientState *nc;
+    NetClientState *nc;
     TAPState *s;
 
     nc = qemu_new_net_client(&net_tap_info, peer, model, name);
@@ -514,7 +514,7 @@ static int net_bridge_run_helper(const char *helper, const char *bridge)
 }
 
 int net_init_bridge(const NetClientOptions *opts, const char *name,
-                    VLANClientState *peer)
+                    NetClientState *peer)
 {
     const NetdevBridgeOptions *bridge;
     const char *helper, *br;
@@ -587,7 +587,7 @@ static int net_tap_init(const NetdevTapOptions *tap, int *vnet_hdr,
 }
 
 int net_init_tap(const NetClientOptions *opts, const char *name,
-                 VLANClientState *peer)
+                 NetClientState *peer)
 {
     const NetdevTapOptions *tap;
 
@@ -708,7 +708,7 @@ int net_init_tap(const NetClientOptions *opts, const char *name,
     return 0;
 }
 
-VHostNetState *tap_get_vhost_net(VLANClientState *nc)
+VHostNetState *tap_get_vhost_net(NetClientState *nc)
 {
     TAPState *s = DO_UPCAST(TAPState, nc, nc);
     assert(nc->info->type == NET_CLIENT_OPTIONS_KIND_TAP);
diff --git a/net/tap.h b/net/tap.h
index 113906f..1257404 100644
--- a/net/tap.h
+++ b/net/tap.h
@@ -33,18 +33,18 @@
 #define DEFAULT_NETWORK_DOWN_SCRIPT "/etc/qemu-ifdown"
 
 int net_init_tap(const NetClientOptions *opts, const char *name,
-                 VLANClientState *peer);
+                 NetClientState *peer);
 
 int tap_open(char *ifname, int ifname_size, int *vnet_hdr, int vnet_hdr_required);
 
 ssize_t tap_read_packet(int tapfd, uint8_t *buf, int maxlen);
 
-int tap_has_ufo(VLANClientState *vc);
-int tap_has_vnet_hdr(VLANClientState *vc);
-int tap_has_vnet_hdr_len(VLANClientState *vc, int len);
-void tap_using_vnet_hdr(VLANClientState *vc, int using_vnet_hdr);
-void tap_set_offload(VLANClientState *vc, int csum, int tso4, int tso6, int ecn, int ufo);
-void tap_set_vnet_hdr_len(VLANClientState *vc, int len);
+int tap_has_ufo(NetClientState *vc);
+int tap_has_vnet_hdr(NetClientState *vc);
+int tap_has_vnet_hdr_len(NetClientState *vc, int len);
+void tap_using_vnet_hdr(NetClientState *vc, int using_vnet_hdr);
+void tap_set_offload(NetClientState *vc, int csum, int tso4, int tso6, int ecn, int ufo);
+void tap_set_vnet_hdr_len(NetClientState *vc, int len);
 
 int tap_set_sndbuf(int fd, const NetdevTapOptions *tap);
 int tap_probe_vnet_hdr(int fd);
@@ -53,12 +53,12 @@ int tap_probe_has_ufo(int fd);
 void tap_fd_set_offload(int fd, int csum, int tso4, int tso6, int ecn, int ufo);
 void tap_fd_set_vnet_hdr_len(int fd, int len);
 
-int tap_get_fd(VLANClientState *vc);
+int tap_get_fd(NetClientState *vc);
 
 struct vhost_net;
-struct vhost_net *tap_get_vhost_net(VLANClientState *vc);
+struct vhost_net *tap_get_vhost_net(NetClientState *vc);
 
 int net_init_bridge(const NetClientOptions *opts, const char *name,
-                    VLANClientState *peer);
+                    NetClientState *peer);
 
 #endif /* QEMU_NET_TAP_H */
diff --git a/net/vde.c b/net/vde.c
index a1480d7..b91a6c7 100644
--- a/net/vde.c
+++ b/net/vde.c
@@ -33,7 +33,7 @@
 #include "qemu-option.h"
 
 typedef struct VDEState {
-    VLANClientState nc;
+    NetClientState nc;
     VDECONN *vde;
 } VDEState;
 
@@ -49,7 +49,7 @@ static void vde_to_qemu(void *opaque)
     }
 }
 
-static ssize_t vde_receive(VLANClientState *nc, const uint8_t *buf, size_t size)
+static ssize_t vde_receive(NetClientState *nc, const uint8_t *buf, size_t size)
 {
     VDEState *s = DO_UPCAST(VDEState, nc, nc);
     ssize_t ret;
@@ -61,7 +61,7 @@ static ssize_t vde_receive(VLANClientState *nc, const uint8_t *buf, size_t size)
     return ret;
 }
 
-static void vde_cleanup(VLANClientState *nc)
+static void vde_cleanup(NetClientState *nc)
 {
     VDEState *s = DO_UPCAST(VDEState, nc, nc);
     qemu_set_fd_handler(vde_datafd(s->vde), NULL, NULL, NULL);
@@ -75,11 +75,11 @@ static NetClientInfo net_vde_info = {
     .cleanup = vde_cleanup,
 };
 
-static int net_vde_init(VLANClientState *peer, const char *model,
+static int net_vde_init(NetClientState *peer, const char *model,
                         const char *name, const char *sock,
                         int port, const char *group, int mode)
 {
-    VLANClientState *nc;
+    NetClientState *nc;
     VDEState *s;
     VDECONN *vde;
     char *init_group = (char *)group;
@@ -111,7 +111,7 @@ static int net_vde_init(VLANClientState *peer, const char *model,
 }
 
 int net_init_vde(const NetClientOptions *opts, const char *name,
-                 VLANClientState *peer)
+                 NetClientState *peer)
 {
     const NetdevVdeOptions *vde;
 
diff --git a/net/vde.h b/net/vde.h
index d6f7af4..6ce6698 100644
--- a/net/vde.h
+++ b/net/vde.h
@@ -30,7 +30,7 @@
 #ifdef CONFIG_VDE
 
 int net_init_vde(const NetClientOptions *opts, const char *name,
-                 VLANClientState *peer);
+                 NetClientState *peer);
 
 #endif /* CONFIG_VDE */
 
diff --git a/qemu-common.h b/qemu-common.h
index 7d7fbec..ea0fe21 100644
--- a/qemu-common.h
+++ b/qemu-common.h
@@ -234,7 +234,7 @@ typedef struct TextConsole TextConsole;
 typedef TextConsole QEMUConsole;
 typedef struct CharDriverState CharDriverState;
 typedef struct MACAddr MACAddr;
-typedef struct VLANClientState VLANClientState;
+typedef struct NetClientState NetClientState;
 typedef struct i2c_bus i2c_bus;
 typedef struct ISABus ISABus;
 typedef struct ISADevice ISADevice;
commit 94878994dcd5d7c2d9c3fe689d6841f6e7ddc2c2
Author: Stefan Hajnoczi <stefanha at linux.vnet.ibm.com>
Date:   Tue Jul 24 16:35:12 2012 +0100

    net: Rename non_vlan_clients to net_clients
    
    There is no longer a distinction between vlan clients and non-vlan
    clients in the net core.  The net core only knows about point-to-point
    clients which are connected to a peer.  It's time to rename the global
    list of net clients since it no longer refers to vlans at all.
    
    Signed-off-by: Stefan Hajnoczi <stefanha at linux.vnet.ibm.com>
    Signed-off-by: Zhi Yong Wu <wuzhy at linux.vnet.ibm.com>
    Reviewed-by: Laszlo Ersek <lersek at redhat.com>

diff --git a/net.c b/net.c
index ee75e0e..65b45bb 100644
--- a/net.c
+++ b/net.c
@@ -47,7 +47,7 @@
 # define CONFIG_NET_BRIDGE
 #endif
 
-static QTAILQ_HEAD(, VLANClientState) non_vlan_clients;
+static QTAILQ_HEAD(, VLANClientState) net_clients;
 
 int default_net = 1;
 
@@ -168,7 +168,7 @@ static char *assign_name(VLANClientState *vc1, const char *model)
     char buf[256];
     int id = 0;
 
-    QTAILQ_FOREACH(vc, &non_vlan_clients, next) {
+    QTAILQ_FOREACH(vc, &net_clients, next) {
         if (vc == vc1) {
             continue;
         }
@@ -219,7 +219,7 @@ VLANClientState *qemu_new_net_client(NetClientInfo *info,
         vc->peer = peer;
         peer->peer = vc;
     }
-    QTAILQ_INSERT_TAIL(&non_vlan_clients, vc, next);
+    QTAILQ_INSERT_TAIL(&net_clients, vc, next);
 
     vc->send_queue = qemu_new_net_queue(qemu_deliver_packet,
                                         qemu_deliver_packet_iov,
@@ -251,7 +251,7 @@ NICState *qemu_new_nic(NetClientInfo *info,
 
 static void qemu_cleanup_vlan_client(VLANClientState *vc)
 {
-    QTAILQ_REMOVE(&non_vlan_clients, vc, next);
+    QTAILQ_REMOVE(&net_clients, vc, next);
 
     if (vc->info->cleanup) {
         vc->info->cleanup(vc);
@@ -305,7 +305,7 @@ void qemu_foreach_nic(qemu_nic_foreach func, void *opaque)
 {
     VLANClientState *nc;
 
-    QTAILQ_FOREACH(nc, &non_vlan_clients, next) {
+    QTAILQ_FOREACH(nc, &net_clients, next) {
         if (nc->info->type == NET_CLIENT_OPTIONS_KIND_NIC) {
             func(DO_UPCAST(NICState, nc, nc), opaque);
         }
@@ -470,7 +470,7 @@ VLANClientState *qemu_find_netdev(const char *id)
 {
     VLANClientState *vc;
 
-    QTAILQ_FOREACH(vc, &non_vlan_clients, next) {
+    QTAILQ_FOREACH(vc, &net_clients, next) {
         if (vc->info->type == NET_CLIENT_OPTIONS_KIND_NIC)
             continue;
         if (!strcmp(vc->name, id)) {
@@ -867,7 +867,7 @@ void do_info_network(Monitor *mon)
     NetClientOptionsKind type;
 
     monitor_printf(mon, "Devices not on any VLAN:\n");
-    QTAILQ_FOREACH(vc, &non_vlan_clients, next) {
+    QTAILQ_FOREACH(vc, &net_clients, next) {
         peer = vc->peer;
         type = vc->info->type;
         if (!peer || type == NET_CLIENT_OPTIONS_KIND_NIC) {
@@ -886,7 +886,7 @@ void qmp_set_link(const char *name, bool up, Error **errp)
 {
     VLANClientState *vc = NULL;
 
-    QTAILQ_FOREACH(vc, &non_vlan_clients, next) {
+    QTAILQ_FOREACH(vc, &net_clients, next) {
         if (!strcmp(vc->name, name)) {
             goto done;
         }
@@ -920,7 +920,7 @@ void net_cleanup(void)
 {
     VLANClientState *vc, *next_vc;
 
-    QTAILQ_FOREACH_SAFE(vc, &non_vlan_clients, next, next_vc) {
+    QTAILQ_FOREACH_SAFE(vc, &net_clients, next, next_vc) {
         qemu_del_vlan_client(vc);
     }
 }
@@ -944,7 +944,7 @@ void net_check_clients(void)
 
     net_hub_check_clients();
 
-    QTAILQ_FOREACH(vc, &non_vlan_clients, next) {
+    QTAILQ_FOREACH(vc, &net_clients, next) {
         if (!vc->peer) {
             fprintf(stderr, "Warning: %s %s has no peer\n",
                     vc->info->type == NET_CLIENT_OPTIONS_KIND_NIC ? "nic" : "netdev",
@@ -1008,7 +1008,7 @@ int net_init_clients(void)
 #endif
     }
 
-    QTAILQ_INIT(&non_vlan_clients);
+    QTAILQ_INIT(&net_clients);
 
     if (qemu_opts_foreach(qemu_find_opts("netdev"), net_init_netdev, NULL, 1) == -1)
         return -1;
commit a005d0732fb1c8e419e506c94ea2527287fe4204
Author: Stefan Hajnoczi <stefanha at linux.vnet.ibm.com>
Date:   Tue Jul 24 16:35:11 2012 +0100

    net: Remove VLANState
    
    VLANState is no longer used and can be removed.
    
    Signed-off-by: Stefan Hajnoczi <stefanha at linux.vnet.ibm.com>
    Signed-off-by: Zhi Yong Wu <wuzhy at linux.vnet.ibm.com>
    Reviewed-by: Laszlo Ersek <lersek at redhat.com>

diff --git a/hw/dp8393x.c b/hw/dp8393x.c
index 756d630..ee1a481 100644
--- a/hw/dp8393x.c
+++ b/hw/dp8393x.c
@@ -899,7 +899,6 @@ void dp83932_init(NICInfo *nd, target_phys_addr_t base, int it_shift,
     s->regs[SONIC_SR] = 0x0004; /* only revision recognized by Linux */
 
     s->conf.macaddr = nd->macaddr;
-    s->conf.vlan = nd->vlan;
     s->conf.peer = nd->netdev;
 
     s->nic = qemu_new_nic(&net_dp83932_info, &s->conf, nd->model, nd->name, s);
diff --git a/hw/exynos4_boards.c b/hw/exynos4_boards.c
index e5c2a5f..4bb0a60 100644
--- a/hw/exynos4_boards.c
+++ b/hw/exynos4_boards.c
@@ -81,7 +81,7 @@ static void lan9215_init(uint32_t base, qemu_irq irq)
     SysBusDevice *s;
 
     /* This should be a 9215 but the 9118 is close enough */
-    if (nd_table[0].vlan) {
+    if (nd_table[0].used) {
         qemu_check_nic_model(&nd_table[0], "lan9118");
         dev = qdev_create(NULL, "lan9118");
         qdev_set_nic_properties(dev, &nd_table[0]);
diff --git a/hw/highbank.c b/hw/highbank.c
index 4bdea5d..11aa131 100644
--- a/hw/highbank.c
+++ b/hw/highbank.c
@@ -284,7 +284,7 @@ static void highbank_init(ram_addr_t ram_size,
 
     sysbus_create_simple("sysbus-ahci", 0xffe08000, pic[83]);
 
-    if (nd_table[0].vlan) {
+    if (nd_table[0].used) {
         qemu_check_nic_model(&nd_table[0], "xgmac");
         dev = qdev_create(NULL, "xgmac");
         qdev_set_nic_properties(dev, &nd_table[0]);
diff --git a/hw/integratorcp.c b/hw/integratorcp.c
index deacbf4..d0e2e90 100644
--- a/hw/integratorcp.c
+++ b/hw/integratorcp.c
@@ -493,7 +493,7 @@ static void integratorcp_init(ram_addr_t ram_size,
     sysbus_create_simple("pl050_keyboard", 0x18000000, pic[3]);
     sysbus_create_simple("pl050_mouse", 0x19000000, pic[4]);
     sysbus_create_varargs("pl181", 0x1c000000, pic[23], pic[24], NULL);
-    if (nd_table[0].vlan)
+    if (nd_table[0].used)
         smc91c111_init(&nd_table[0], 0xc8000000, pic[27]);
 
     sysbus_create_simple("pl110", 0xc0000000, pic[22]);
diff --git a/hw/kzm.c b/hw/kzm.c
index 08aaf43..6a5e9df 100644
--- a/hw/kzm.c
+++ b/hw/kzm.c
@@ -121,7 +121,7 @@ static void kzm_init(ram_addr_t ram_size,
     imx_timerp_create(0x53f98000, qdev_get_gpio_in(dev, 27), ccm);
     imx_timerg_create(0x53f90000, qdev_get_gpio_in(dev, 29), ccm);
 
-    if (nd_table[0].vlan) {
+    if (nd_table[0].used) {
         lan9118_init(&nd_table[0], 0xb6000000, qdev_get_gpio_in(dev, 52));
     }
 
diff --git a/hw/mcf5208.c b/hw/mcf5208.c
index d3ebe8d..ee25b1b 100644
--- a/hw/mcf5208.c
+++ b/hw/mcf5208.c
@@ -236,7 +236,7 @@ static void mcf5208evb_init(ram_addr_t ram_size,
         fprintf(stderr, "Too many NICs\n");
         exit(1);
     }
-    if (nd_table[0].vlan)
+    if (nd_table[0].used)
         mcf_fec_init(address_space_mem, &nd_table[0],
                      0xfc030000, pic + 36);
 
diff --git a/hw/mcf_fec.c b/hw/mcf_fec.c
index 4ab4ff5..308a1b6 100644
--- a/hw/mcf_fec.c
+++ b/hw/mcf_fec.c
@@ -472,7 +472,6 @@ void mcf_fec_init(MemoryRegion *sysmem, NICInfo *nd,
     memory_region_add_subregion(sysmem, base, &s->iomem);
 
     s->conf.macaddr = nd->macaddr;
-    s->conf.vlan = nd->vlan;
     s->conf.peer = nd->netdev;
 
     s->nic = qemu_new_nic(&net_mcf_fec_info, &s->conf, nd->model, nd->name, s);
diff --git a/hw/mips_mipssim.c b/hw/mips_mipssim.c
index eb03047..830f635 100644
--- a/hw/mips_mipssim.c
+++ b/hw/mips_mipssim.c
@@ -217,7 +217,7 @@ mips_mipssim_init (ram_addr_t ram_size,
     if (serial_hds[0])
         serial_init(0x3f8, env->irq[4], 115200, serial_hds[0]);
 
-    if (nd_table[0].vlan)
+    if (nd_table[0].used)
         /* MIPSnet uses the MIPS CPU INT0, which is interrupt 2. */
         mipsnet_init(0x4200, env->irq[2], &nd_table[0]);
 }
diff --git a/hw/mips_r4k.c b/hw/mips_r4k.c
index d685999..967a76e 100644
--- a/hw/mips_r4k.c
+++ b/hw/mips_r4k.c
@@ -283,7 +283,7 @@ void mips_r4k_init (ram_addr_t ram_size,
 
     isa_vga_init(isa_bus);
 
-    if (nd_table[0].vlan)
+    if (nd_table[0].used)
         isa_ne2000_init(isa_bus, 0x300, 9, &nd_table[0]);
 
     ide_drive_get(hd, MAX_IDE_BUS);
diff --git a/hw/openrisc_sim.c b/hw/openrisc_sim.c
index f07f7fc..55e97f0 100644
--- a/hw/openrisc_sim.c
+++ b/hw/openrisc_sim.c
@@ -126,7 +126,7 @@ static void openrisc_sim_init(ram_addr_t ram_size,
     serial_mm_init(get_system_memory(), 0x90000000, 0, cpu->env.irq[2],
                    115200, serial_hds[0], DEVICE_NATIVE_ENDIAN);
 
-    if (nd_table[0].vlan) {
+    if (nd_table[0].used) {
         openrisc_sim_net_init(get_system_memory(), 0x92000000,
                               0x92000400, cpu->env.irq[4], nd_table);
     }
diff --git a/hw/qdev-properties.c b/hw/qdev-properties.c
index 7cc3eb7..726f6d7 100644
--- a/hw/qdev-properties.c
+++ b/hw/qdev-properties.c
@@ -1195,13 +1195,6 @@ void qdev_prop_set_netdev(DeviceState *dev, const char *name, VLANClientState *v
     assert_no_error(errp);
 }
 
-void qdev_prop_set_vlan(DeviceState *dev, const char *name, VLANState *value)
-{
-    Error *errp = NULL;
-    object_property_set_int(OBJECT(dev), value ? value->id : -1, name, &errp);
-    assert_no_error(errp);
-}
-
 void qdev_prop_set_macaddr(DeviceState *dev, const char *name, uint8_t *value)
 {
     Error *errp = NULL;
diff --git a/hw/qdev.c b/hw/qdev.c
index af54467..b5b74b9 100644
--- a/hw/qdev.c
+++ b/hw/qdev.c
@@ -320,8 +320,6 @@ void qdev_connect_gpio_out(DeviceState * dev, int n, qemu_irq pin)
 void qdev_set_nic_properties(DeviceState *dev, NICInfo *nd)
 {
     qdev_prop_set_macaddr(dev, "mac", nd->macaddr.a);
-    if (nd->vlan)
-        qdev_prop_set_vlan(dev, "vlan", nd->vlan);
     if (nd->netdev)
         qdev_prop_set_netdev(dev, "netdev", nd->netdev);
     if (nd->nvectors != DEV_NVECTORS_UNSPECIFIED &&
diff --git a/hw/qdev.h b/hw/qdev.h
index ef430a0..7386ecd 100644
--- a/hw/qdev.h
+++ b/hw/qdev.h
@@ -321,7 +321,6 @@ void qdev_prop_set_uint64(DeviceState *dev, const char *name, uint64_t value);
 void qdev_prop_set_string(DeviceState *dev, const char *name, const char *value);
 void qdev_prop_set_chr(DeviceState *dev, const char *name, CharDriverState *value);
 void qdev_prop_set_netdev(DeviceState *dev, const char *name, VLANClientState *value);
-void qdev_prop_set_vlan(DeviceState *dev, const char *name, VLANState *value);
 int qdev_prop_set_drive(DeviceState *dev, const char *name, BlockDriverState *value) QEMU_WARN_UNUSED_RESULT;
 void qdev_prop_set_drive_nofail(DeviceState *dev, const char *name, BlockDriverState *value);
 void qdev_prop_set_macaddr(DeviceState *dev, const char *name, uint8_t *value);
diff --git a/hw/vexpress.c b/hw/vexpress.c
index b2dc8a5..b615844 100644
--- a/hw/vexpress.c
+++ b/hw/vexpress.c
@@ -427,7 +427,7 @@ static void vexpress_common_init(const VEDBoardInfo *daughterboard,
     memory_region_add_subregion(sysmem, map[VE_VIDEORAM], vram);
 
     /* 0x4e000000 LAN9118 Ethernet */
-    if (nd_table[0].vlan) {
+    if (nd_table[0].used) {
         lan9118_init(&nd_table[0], map[VE_ETHERNET], pic[15]);
     }
 
diff --git a/hw/xtensa_lx60.c b/hw/xtensa_lx60.c
index 152eed9..c4f616f 100644
--- a/hw/xtensa_lx60.c
+++ b/hw/xtensa_lx60.c
@@ -201,7 +201,7 @@ static void lx_init(const LxBoardDesc *board,
     memory_region_init(system_io, "lx60.io", 224 * 1024 * 1024);
     memory_region_add_subregion(system_memory, 0xf0000000, system_io);
     lx60_fpga_init(system_io, 0x0d020000);
-    if (nd_table[0].vlan) {
+    if (nd_table[0].used) {
         lx60_net_init(system_io, 0x0d030000, 0x0d030400, 0x0d800000,
                 xtensa_get_extint(env, 1), nd_table);
     }
diff --git a/net.c b/net.c
index 819fff7..ee75e0e 100644
--- a/net.c
+++ b/net.c
@@ -47,7 +47,6 @@
 # define CONFIG_NET_BRIDGE
 #endif
 
-static QTAILQ_HEAD(, VLANState) vlans;
 static QTAILQ_HEAD(, VLANClientState) non_vlan_clients;
 
 int default_net = 1;
@@ -252,11 +251,7 @@ NICState *qemu_new_nic(NetClientInfo *info,
 
 static void qemu_cleanup_vlan_client(VLANClientState *vc)
 {
-    if (vc->vlan) {
-        QTAILQ_REMOVE(&vc->vlan->clients, vc, next);
-    } else {
-        QTAILQ_REMOVE(&non_vlan_clients, vc, next);
-    }
+    QTAILQ_REMOVE(&non_vlan_clients, vc, next);
 
     if (vc->info->cleanup) {
         vc->info->cleanup(vc);
@@ -265,13 +260,11 @@ static void qemu_cleanup_vlan_client(VLANClientState *vc)
 
 static void qemu_free_vlan_client(VLANClientState *vc)
 {
-    if (!vc->vlan) {
-        if (vc->send_queue) {
-            qemu_del_net_queue(vc->send_queue);
-        }
-        if (vc->peer) {
-            vc->peer->peer = NULL;
-        }
+    if (vc->send_queue) {
+        qemu_del_net_queue(vc->send_queue);
+    }
+    if (vc->peer) {
+        vc->peer->peer = NULL;
     }
     g_free(vc->name);
     g_free(vc->model);
@@ -281,7 +274,7 @@ static void qemu_free_vlan_client(VLANClientState *vc)
 void qemu_del_vlan_client(VLANClientState *vc)
 {
     /* If there is a peer NIC, delete and cleanup client, but do not free. */
-    if (!vc->vlan && vc->peer && vc->peer->info->type == NET_CLIENT_OPTIONS_KIND_NIC) {
+    if (vc->peer && vc->peer->info->type == NET_CLIENT_OPTIONS_KIND_NIC) {
         NICState *nic = DO_UPCAST(NICState, nc, vc->peer);
         if (nic->peer_deleted) {
             return;
@@ -297,7 +290,7 @@ void qemu_del_vlan_client(VLANClientState *vc)
     }
 
     /* If this is a peer NIC and peer has already been deleted, free it now. */
-    if (!vc->vlan && vc->peer && vc->info->type == NET_CLIENT_OPTIONS_KIND_NIC) {
+    if (vc->peer && vc->info->type == NET_CLIENT_OPTIONS_KIND_NIC) {
         NICState *nic = DO_UPCAST(NICState, nc, vc);
         if (nic->peer_deleted) {
             qemu_free_vlan_client(vc->peer);
@@ -311,52 +304,25 @@ void qemu_del_vlan_client(VLANClientState *vc)
 void qemu_foreach_nic(qemu_nic_foreach func, void *opaque)
 {
     VLANClientState *nc;
-    VLANState *vlan;
 
     QTAILQ_FOREACH(nc, &non_vlan_clients, next) {
         if (nc->info->type == NET_CLIENT_OPTIONS_KIND_NIC) {
             func(DO_UPCAST(NICState, nc, nc), opaque);
         }
     }
-
-    QTAILQ_FOREACH(vlan, &vlans, next) {
-        QTAILQ_FOREACH(nc, &vlan->clients, next) {
-            if (nc->info->type == NET_CLIENT_OPTIONS_KIND_NIC) {
-                func(DO_UPCAST(NICState, nc, nc), opaque);
-            }
-        }
-    }
 }
 
 int qemu_can_send_packet(VLANClientState *sender)
 {
-    VLANState *vlan = sender->vlan;
-    VLANClientState *vc;
-
-    if (sender->peer) {
-        if (sender->peer->receive_disabled) {
-            return 0;
-        } else if (sender->peer->info->can_receive &&
-                   !sender->peer->info->can_receive(sender->peer)) {
-            return 0;
-        } else {
-            return 1;
-        }
-    }
-
-    if (!sender->vlan) {
+    if (!sender->peer) {
         return 1;
     }
 
-    QTAILQ_FOREACH(vc, &vlan->clients, next) {
-        if (vc == sender) {
-            continue;
-        }
-
-        /* no can_receive() handler, they can always receive */
-        if (vc->info->can_receive && !vc->info->can_receive(vc)) {
-            return 0;
-        }
+    if (sender->peer->receive_disabled) {
+        return 0;
+    } else if (sender->peer->info->can_receive &&
+               !sender->peer->info->can_receive(sender->peer)) {
+        return 0;
     }
     return 1;
 }
@@ -393,34 +359,18 @@ static ssize_t qemu_deliver_packet(VLANClientState *sender,
 
 void qemu_purge_queued_packets(VLANClientState *vc)
 {
-    NetQueue *queue;
-
-    if (!vc->peer && !vc->vlan) {
+    if (!vc->peer) {
         return;
     }
 
-    if (vc->peer) {
-        queue = vc->peer->send_queue;
-    } else {
-        queue = vc->vlan->send_queue;
-    }
-
-    qemu_net_queue_purge(queue, vc);
+    qemu_net_queue_purge(vc->peer->send_queue, vc);
 }
 
 void qemu_flush_queued_packets(VLANClientState *vc)
 {
-    NetQueue *queue;
-
     vc->receive_disabled = 0;
 
-    if (vc->vlan) {
-        queue = vc->vlan->send_queue;
-    } else {
-        queue = vc->send_queue;
-    }
-
-    qemu_net_queue_flush(queue);
+    qemu_net_queue_flush(vc->send_queue);
 }
 
 static ssize_t qemu_send_packet_async_with_flags(VLANClientState *sender,
@@ -435,15 +385,11 @@ static ssize_t qemu_send_packet_async_with_flags(VLANClientState *sender,
     hex_dump(stdout, buf, size);
 #endif
 
-    if (sender->link_down || (!sender->peer && !sender->vlan)) {
+    if (sender->link_down || !sender->peer) {
         return size;
     }
 
-    if (sender->peer) {
-        queue = sender->peer->send_queue;
-    } else {
-        queue = sender->vlan->send_queue;
-    }
+    queue = sender->peer->send_queue;
 
     return qemu_net_queue_send(queue, sender, flags, buf, size, sent_cb);
 }
@@ -503,15 +449,11 @@ ssize_t qemu_sendv_packet_async(VLANClientState *sender,
 {
     NetQueue *queue;
 
-    if (sender->link_down || (!sender->peer && !sender->vlan)) {
+    if (sender->link_down || !sender->peer) {
         return iov_size(iov, iovcnt);
     }
 
-    if (sender->peer) {
-        queue = sender->peer->send_queue;
-    } else {
-        queue = sender->vlan->send_queue;
-    }
+    queue = sender->peer->send_queue;
 
     return qemu_net_queue_send_iov(queue, sender,
                                    QEMU_NET_PACKET_FLAG_NONE,
@@ -921,18 +863,9 @@ static void print_net_client(Monitor *mon, VLANClientState *vc)
 
 void do_info_network(Monitor *mon)
 {
-    VLANState *vlan;
     VLANClientState *vc, *peer;
     NetClientOptionsKind type;
 
-    QTAILQ_FOREACH(vlan, &vlans, next) {
-        monitor_printf(mon, "VLAN %d devices:\n", vlan->id);
-
-        QTAILQ_FOREACH(vc, &vlan->clients, next) {
-            monitor_printf(mon, "  ");
-            print_net_client(mon, vc);
-        }
-    }
     monitor_printf(mon, "Devices not on any VLAN:\n");
     QTAILQ_FOREACH(vc, &non_vlan_clients, next) {
         peer = vc->peer;
@@ -951,16 +884,8 @@ void do_info_network(Monitor *mon)
 
 void qmp_set_link(const char *name, bool up, Error **errp)
 {
-    VLANState *vlan;
     VLANClientState *vc = NULL;
 
-    QTAILQ_FOREACH(vlan, &vlans, next) {
-        QTAILQ_FOREACH(vc, &vlan->clients, next) {
-            if (strcmp(vc->name, name) == 0) {
-                goto done;
-            }
-        }
-    }
     QTAILQ_FOREACH(vc, &non_vlan_clients, next) {
         if (!strcmp(vc->name, name)) {
             goto done;
@@ -993,15 +918,8 @@ done:
 
 void net_cleanup(void)
 {
-    VLANState *vlan;
     VLANClientState *vc, *next_vc;
 
-    QTAILQ_FOREACH(vlan, &vlans, next) {
-        QTAILQ_FOREACH_SAFE(vc, &vlan->clients, next, next_vc) {
-            qemu_del_vlan_client(vc);
-        }
-    }
-
     QTAILQ_FOREACH_SAFE(vc, &non_vlan_clients, next, next_vc) {
         qemu_del_vlan_client(vc);
     }
@@ -1090,7 +1008,6 @@ int net_init_clients(void)
 #endif
     }
 
-    QTAILQ_INIT(&vlans);
     QTAILQ_INIT(&non_vlan_clients);
 
     if (qemu_opts_foreach(qemu_find_opts("netdev"), net_init_netdev, NULL, 1) == -1)
diff --git a/net.h b/net.h
index 9393e4d..4e0217a 100644
--- a/net.h
+++ b/net.h
@@ -17,7 +17,6 @@ struct MACAddr {
 
 typedef struct NICConf {
     MACAddr macaddr;
-    VLANState *vlan;
     VLANClientState *peer;
     int32_t bootindex;
 } NICConf;
@@ -53,7 +52,6 @@ struct VLANClientState {
     NetClientInfo *info;
     int link_down;
     QTAILQ_ENTRY(VLANClientState) next;
-    struct VLANState *vlan;
     VLANClientState *peer;
     NetQueue *send_queue;
     char *model;
@@ -69,13 +67,6 @@ typedef struct NICState {
     bool peer_deleted;
 } NICState;
 
-struct VLANState {
-    int id;
-    QTAILQ_HEAD(, VLANClientState) clients;
-    QTAILQ_ENTRY(VLANState) next;
-    NetQueue *send_queue;
-};
-
 VLANClientState *qemu_find_netdev(const char *id);
 VLANClientState *qemu_new_net_client(NetClientInfo *info,
                                      VLANClientState *peer,
@@ -120,7 +111,6 @@ struct NICInfo {
     char *model;
     char *name;
     char *devaddr;
-    VLANState *vlan;
     VLANClientState *netdev;
     int used;         /* is this slot in nd_table[] being used? */
     int instantiated; /* does this NICInfo correspond to an instantiated NIC? */
diff --git a/qemu-common.h b/qemu-common.h
index d26ff39..7d7fbec 100644
--- a/qemu-common.h
+++ b/qemu-common.h
@@ -234,7 +234,6 @@ typedef struct TextConsole TextConsole;
 typedef TextConsole QEMUConsole;
 typedef struct CharDriverState CharDriverState;
 typedef struct MACAddr MACAddr;
-typedef struct VLANState VLANState;
 typedef struct VLANClientState VLANClientState;
 typedef struct i2c_bus i2c_bus;
 typedef struct ISABus ISABus;
commit ec8b1f6cc8d0a5921fba93cd180b05328e537170
Author: Stefan Hajnoczi <stefanha at linux.vnet.ibm.com>
Date:   Tue Jul 24 16:35:10 2012 +0100

    net: Remove vlan code from net.c
    
    The vlan implementation in net.c has been replaced by hubs so we can
    remove the code.
    
    Signed-off-by: Stefan Hajnoczi <stefanha at linux.vnet.ibm.com>
    Signed-off-by: Zhi Yong Wu <wuzhy at linux.vnet.ibm.com>
    Reviewed-by: Laszlo Ersek <lersek at redhat.com>

diff --git a/hw/xen_nic.c b/hw/xen_nic.c
index 593a572..5c3c1c6 100644
--- a/hw/xen_nic.c
+++ b/hw/xen_nic.c
@@ -325,7 +325,6 @@ static int net_init(struct XenDevice *xendev)
         return -1;
     }
 
-    netdev->conf.vlan = qemu_find_vlan(netdev->xendev.dev, 1);
     netdev->conf.peer = NULL;
 
     netdev->nic = qemu_new_nic(&net_xen_info, &netdev->conf,
diff --git a/net.c b/net.c
index 274f3bd..819fff7 100644
--- a/net.c
+++ b/net.c
@@ -391,50 +391,6 @@ static ssize_t qemu_deliver_packet(VLANClientState *sender,
     return ret;
 }
 
-static ssize_t qemu_vlan_deliver_packet(VLANClientState *sender,
-                                        unsigned flags,
-                                        const uint8_t *buf,
-                                        size_t size,
-                                        void *opaque)
-{
-    VLANState *vlan = opaque;
-    VLANClientState *vc;
-    ssize_t ret = -1;
-
-    QTAILQ_FOREACH(vc, &vlan->clients, next) {
-        ssize_t len;
-
-        if (vc == sender) {
-            continue;
-        }
-
-        if (vc->link_down) {
-            ret = size;
-            continue;
-        }
-
-        if (vc->receive_disabled) {
-            ret = 0;
-            continue;
-        }
-
-        if (flags & QEMU_NET_PACKET_FLAG_RAW && vc->info->receive_raw) {
-            len = vc->info->receive_raw(vc, buf, size);
-        } else {
-            len = vc->info->receive(vc, buf, size);
-        }
-
-        if (len == 0) {
-            vc->receive_disabled = 1;
-        }
-
-        ret = (ret >= 0) ? ret : len;
-
-    }
-
-    return ret;
-}
-
 void qemu_purge_queued_packets(VLANClientState *vc)
 {
     NetQueue *queue;
@@ -541,42 +497,6 @@ static ssize_t qemu_deliver_packet_iov(VLANClientState *sender,
     }
 }
 
-static ssize_t qemu_vlan_deliver_packet_iov(VLANClientState *sender,
-                                            unsigned flags,
-                                            const struct iovec *iov,
-                                            int iovcnt,
-                                            void *opaque)
-{
-    VLANState *vlan = opaque;
-    VLANClientState *vc;
-    ssize_t ret = -1;
-
-    QTAILQ_FOREACH(vc, &vlan->clients, next) {
-        ssize_t len;
-
-        if (vc == sender) {
-            continue;
-        }
-
-        if (vc->link_down) {
-            ret = iov_size(iov, iovcnt);
-            continue;
-        }
-
-        assert(!(flags & QEMU_NET_PACKET_FLAG_RAW));
-
-        if (vc->info->receive_iov) {
-            len = vc->info->receive_iov(vc, iov, iovcnt);
-        } else {
-            len = vc_sendv_compat(vc, iov, iovcnt);
-        }
-
-        ret = (ret >= 0) ? ret : len;
-    }
-
-    return ret;
-}
-
 ssize_t qemu_sendv_packet_async(VLANClientState *sender,
                                 const struct iovec *iov, int iovcnt,
                                 NetPacketSent *sent_cb)
@@ -604,34 +524,6 @@ qemu_sendv_packet(VLANClientState *vc, const struct iovec *iov, int iovcnt)
     return qemu_sendv_packet_async(vc, iov, iovcnt, NULL);
 }
 
-/* find or alloc a new VLAN */
-VLANState *qemu_find_vlan(int id, int allocate)
-{
-    VLANState *vlan;
-
-    QTAILQ_FOREACH(vlan, &vlans, next) {
-        if (vlan->id == id) {
-            return vlan;
-        }
-    }
-
-    if (!allocate) {
-        return NULL;
-    }
-
-    vlan = g_malloc0(sizeof(VLANState));
-    vlan->id = id;
-    QTAILQ_INIT(&vlan->clients);
-
-    vlan->send_queue = qemu_new_net_queue(qemu_vlan_deliver_packet,
-                                          qemu_vlan_deliver_packet_iov,
-                                          vlan);
-
-    QTAILQ_INSERT_TAIL(&vlans, vlan, next);
-
-    return vlan;
-}
-
 VLANClientState *qemu_find_netdev(const char *id)
 {
     VLANClientState *vc;
diff --git a/net.h b/net.h
index 4bccead..9393e4d 100644
--- a/net.h
+++ b/net.h
@@ -76,7 +76,6 @@ struct VLANState {
     NetQueue *send_queue;
 };
 
-VLANState *qemu_find_vlan(int id, int allocate);
 VLANClientState *qemu_find_netdev(const char *id);
 VLANClientState *qemu_new_net_client(NetClientInfo *info,
                                      VLANClientState *peer,
commit 606c10e2bd5877e01f0ff1812d9abebf40fb522b
Author: Zhi Yong Wu <wuzhy at linux.vnet.ibm.com>
Date:   Tue Jul 24 16:35:09 2012 +0100

    net: Convert qdev_prop_vlan to peer with hub
    
    Instead of using VLANState use net/hub.h to support the vlan qdev
    property.  The vlan qdev property becomes an alias for the peer qdev
    property but is represented as a VLAN ID number.  When a VLAN ID is
    selected the device will really peer with a hub port.
    
    Signed-off-by: Zhi Yong Wu <wuzhy at linux.vnet.ibm.com>
    Signed-off-by: Stefan Hajnoczi <stefanha at linux.vnet.ibm.com>
    Reviewed-by: Laszlo Ersek <lersek at redhat.com>

diff --git a/hw/qdev-properties.c b/hw/qdev-properties.c
index 24b39e8..7cc3eb7 100644
--- a/hw/qdev-properties.c
+++ b/hw/qdev-properties.c
@@ -3,6 +3,7 @@
 #include "qerror.h"
 #include "blockdev.h"
 #include "hw/block-common.h"
+#include "net/hub.h"
 
 void *qdev_get_prop_ptr(DeviceState *dev, Property *prop)
 {
@@ -624,13 +625,16 @@ PropertyInfo qdev_prop_netdev = {
 
 static int print_vlan(DeviceState *dev, Property *prop, char *dest, size_t len)
 {
-    VLANState **ptr = qdev_get_prop_ptr(dev, prop);
+    VLANClientState **ptr = qdev_get_prop_ptr(dev, prop);
 
     if (*ptr) {
-        return snprintf(dest, len, "%d", (*ptr)->id);
-    } else {
-        return snprintf(dest, len, "<null>");
+        int id;
+        if (!net_hub_id_for_client(*ptr, &id)) {
+            return snprintf(dest, len, "%d", id);
+        }
     }
+
+    return snprintf(dest, len, "<null>");
 }
 
 static void get_vlan(Object *obj, Visitor *v, void *opaque,
@@ -638,11 +642,17 @@ static void get_vlan(Object *obj, Visitor *v, void *opaque,
 {
     DeviceState *dev = DEVICE(obj);
     Property *prop = opaque;
-    VLANState **ptr = qdev_get_prop_ptr(dev, prop);
-    int64_t id;
+    VLANClientState **ptr = qdev_get_prop_ptr(dev, prop);
+    int32_t id = -1;
 
-    id = *ptr ? (*ptr)->id : -1;
-    visit_type_int64(v, &id, name, errp);
+    if (*ptr) {
+        int hub_id;
+        if (!net_hub_id_for_client(*ptr, &hub_id)) {
+            id = hub_id;
+        }
+    }
+
+    visit_type_int32(v, &id, name, errp);
 }
 
 static void set_vlan(Object *obj, Visitor *v, void *opaque,
@@ -650,17 +660,17 @@ static void set_vlan(Object *obj, Visitor *v, void *opaque,
 {
     DeviceState *dev = DEVICE(obj);
     Property *prop = opaque;
-    VLANState **ptr = qdev_get_prop_ptr(dev, prop);
+    VLANClientState **ptr = qdev_get_prop_ptr(dev, prop);
     Error *local_err = NULL;
-    int64_t id;
-    VLANState *vlan;
+    int32_t id;
+    VLANClientState *hubport;
 
     if (dev->state != DEV_STATE_CREATED) {
         error_set(errp, QERR_PERMISSION_DENIED);
         return;
     }
 
-    visit_type_int64(v, &id, name, &local_err);
+    visit_type_int32(v, &id, name, &local_err);
     if (local_err) {
         error_propagate(errp, local_err);
         return;
@@ -669,13 +679,14 @@ static void set_vlan(Object *obj, Visitor *v, void *opaque,
         *ptr = NULL;
         return;
     }
-    vlan = qemu_find_vlan(id, 1);
-    if (!vlan) {
+
+    hubport = net_hub_port_find(id);
+    if (!hubport) {
         error_set(errp, QERR_INVALID_PARAMETER_VALUE,
                   name, prop->info->name);
         return;
     }
-    *ptr = vlan;
+    *ptr = hubport;
 }
 
 PropertyInfo qdev_prop_vlan = {
diff --git a/hw/qdev.h b/hw/qdev.h
index a2cbd9d..ef430a0 100644
--- a/hw/qdev.h
+++ b/hw/qdev.h
@@ -291,7 +291,7 @@ extern PropertyInfo qdev_prop_pci_host_devaddr;
 #define DEFINE_PROP_NETDEV(_n, _s, _f)             \
     DEFINE_PROP(_n, _s, _f, qdev_prop_netdev, VLANClientState*)
 #define DEFINE_PROP_VLAN(_n, _s, _f)             \
-    DEFINE_PROP(_n, _s, _f, qdev_prop_vlan, VLANState*)
+    DEFINE_PROP(_n, _s, _f, qdev_prop_vlan, VLANClientState*)
 #define DEFINE_PROP_DRIVE(_n, _s, _f) \
     DEFINE_PROP(_n, _s, _f, qdev_prop_drive, BlockDriverState *)
 #define DEFINE_PROP_MACADDR(_n, _s, _f)         \
diff --git a/net.h b/net.h
index e9c92b2..4bccead 100644
--- a/net.h
+++ b/net.h
@@ -24,7 +24,7 @@ typedef struct NICConf {
 
 #define DEFINE_NIC_PROPERTIES(_state, _conf)                            \
     DEFINE_PROP_MACADDR("mac",   _state, _conf.macaddr),                \
-    DEFINE_PROP_VLAN("vlan",     _state, _conf.vlan),                   \
+    DEFINE_PROP_VLAN("vlan",     _state, _conf.peer),                   \
     DEFINE_PROP_NETDEV("netdev", _state, _conf.peer),                   \
     DEFINE_PROP_INT32("bootindex", _state, _conf.bootindex, -1)
 
diff --git a/net/hub.c b/net/hub.c
index 97198a2..e80d131 100644
--- a/net/hub.c
+++ b/net/hub.c
@@ -188,6 +188,31 @@ VLANClientState *net_hub_find_client_by_name(int hub_id, const char *name)
 }
 
 /**
+ * Find a available port on a hub; otherwise create one new port
+ */
+VLANClientState *net_hub_port_find(int hub_id)
+{
+    NetHub *hub;
+    NetHubPort *port;
+    VLANClientState *nc;
+
+    QLIST_FOREACH(hub, &hubs, next) {
+        if (hub->id == hub_id) {
+            QLIST_FOREACH(port, &hub->ports, next) {
+                nc = port->nc.peer;
+                if (!nc) {
+                    return &(port->nc);
+                }
+            }
+            break;
+        }
+    }
+
+    nc = net_hub_add_port(hub_id, NULL);
+    return nc;
+}
+
+/**
  * Print hub configuration
  */
 void net_hub_info(Monitor *mon)
diff --git a/net/hub.h b/net/hub.h
index 9973da3..3906df2 100644
--- a/net/hub.h
+++ b/net/hub.h
@@ -24,5 +24,6 @@ VLANClientState *net_hub_find_client_by_name(int hub_id, const char *name);
 void net_hub_info(Monitor *mon);
 int net_hub_id_for_client(VLANClientState *nc, int *id);
 void net_hub_check_clients(void);
+VLANClientState *net_hub_port_find(int hub_id);
 
 #endif /* NET_HUB_H */
commit ab5f3f84c4362c3014b1ecdb450f430d01b96f19
Author: Stefan Hajnoczi <stefanha at linux.vnet.ibm.com>
Date:   Tue Jul 24 16:35:08 2012 +0100

    net: Drop vlan argument to qemu_new_net_client()
    
    Since hubs are now used to implement the 'vlan' feature and the vlan
    argument is always NULL, remove the argument entirely and update all net
    clients that use qemu_new_net_client().
    
    Signed-off-by: Stefan Hajnoczi <stefanha at linux.vnet.ibm.com>
    Signed-off-by: Zhi Yong Wu <wuzhy at linux.vnet.ibm.com>
    Reviewed-by: Laszlo Ersek <lersek at redhat.com>

diff --git a/net.c b/net.c
index 413dac4..274f3bd 100644
--- a/net.c
+++ b/net.c
@@ -197,7 +197,6 @@ static ssize_t qemu_deliver_packet_iov(VLANClientState *sender,
                                        void *opaque);
 
 VLANClientState *qemu_new_net_client(NetClientInfo *info,
-                                     VLANState *vlan,
                                      VLANClientState *peer,
                                      const char *model,
                                      const char *name)
@@ -216,22 +215,16 @@ VLANClientState *qemu_new_net_client(NetClientInfo *info,
         vc->name = assign_name(vc, model);
     }
 
-    if (vlan) {
-        assert(!peer);
-        vc->vlan = vlan;
-        QTAILQ_INSERT_TAIL(&vc->vlan->clients, vc, next);
-    } else {
-        if (peer) {
-            assert(!peer->peer);
-            vc->peer = peer;
-            peer->peer = vc;
-        }
-        QTAILQ_INSERT_TAIL(&non_vlan_clients, vc, next);
-
-        vc->send_queue = qemu_new_net_queue(qemu_deliver_packet,
-                                            qemu_deliver_packet_iov,
-                                            vc);
+    if (peer) {
+        assert(!peer->peer);
+        vc->peer = peer;
+        peer->peer = vc;
     }
+    QTAILQ_INSERT_TAIL(&non_vlan_clients, vc, next);
+
+    vc->send_queue = qemu_new_net_queue(qemu_deliver_packet,
+                                        qemu_deliver_packet_iov,
+                                        vc);
 
     return vc;
 }
@@ -248,7 +241,7 @@ NICState *qemu_new_nic(NetClientInfo *info,
     assert(info->type == NET_CLIENT_OPTIONS_KIND_NIC);
     assert(info->size >= sizeof(NICState));
 
-    nc = qemu_new_net_client(info, conf->vlan, conf->peer, model, name);
+    nc = qemu_new_net_client(info, conf->peer, model, name);
 
     nic = DO_UPCAST(NICState, nc, nc);
     nic->conf = conf;
diff --git a/net.h b/net.h
index b0b8c7a..e9c92b2 100644
--- a/net.h
+++ b/net.h
@@ -79,7 +79,6 @@ struct VLANState {
 VLANState *qemu_find_vlan(int id, int allocate);
 VLANClientState *qemu_find_netdev(const char *id);
 VLANClientState *qemu_new_net_client(NetClientInfo *info,
-                                     VLANState *vlan,
                                      VLANClientState *peer,
                                      const char *model,
                                      const char *name);
diff --git a/net/dump.c b/net/dump.c
index 9d7bf3b..69d5abe 100644
--- a/net/dump.c
+++ b/net/dump.c
@@ -129,7 +129,7 @@ static int net_dump_init(VLANClientState *peer, const char *device,
         return -1;
     }
 
-    nc = qemu_new_net_client(&net_dump_info, NULL, peer, device, name);
+    nc = qemu_new_net_client(&net_dump_info, peer, device, name);
 
     snprintf(nc->info_str, sizeof(nc->info_str),
              "dump to %s (len=%d)", filename, len);
diff --git a/net/hub.c b/net/hub.c
index 5cdd8c9..97198a2 100644
--- a/net/hub.c
+++ b/net/hub.c
@@ -129,7 +129,7 @@ static NetHubPort *net_hub_port_new(NetHub *hub, const char *name)
         name = default_name;
     }
 
-    nc = qemu_new_net_client(&net_hub_port_info, NULL, NULL, "hub", name);
+    nc = qemu_new_net_client(&net_hub_port_info, NULL, "hub", name);
     port = DO_UPCAST(NetHubPort, nc, nc);
     port->id = id;
     port->hub = hub;
diff --git a/net/slirp.c b/net/slirp.c
index 7682ac7..85d6fb4 100644
--- a/net/slirp.c
+++ b/net/slirp.c
@@ -239,7 +239,7 @@ static int net_slirp_init(VLANClientState *peer, const char *model,
     }
 #endif
 
-    nc = qemu_new_net_client(&net_slirp_info, NULL, peer, model, name);
+    nc = qemu_new_net_client(&net_slirp_info, peer, model, name);
 
     snprintf(nc->info_str, sizeof(nc->info_str),
              "net=%s,restrict=%s", inet_ntoa(net),
diff --git a/net/socket.c b/net/socket.c
index 09bdc66..31bbb30 100644
--- a/net/socket.c
+++ b/net/socket.c
@@ -287,7 +287,7 @@ static NetSocketState *net_socket_fd_init_dgram(VLANClientState *peer,
         }
     }
 
-    nc = qemu_new_net_client(&net_dgram_socket_info, NULL, peer, model, name);
+    nc = qemu_new_net_client(&net_dgram_socket_info, peer, model, name);
 
     snprintf(nc->info_str, sizeof(nc->info_str),
             "socket: fd=%d (%s mcast=%s:%d)",
@@ -331,7 +331,7 @@ static NetSocketState *net_socket_fd_init_stream(VLANClientState *peer,
     VLANClientState *nc;
     NetSocketState *s;
 
-    nc = qemu_new_net_client(&net_socket_info, NULL, peer, model, name);
+    nc = qemu_new_net_client(&net_socket_info, peer, model, name);
 
     snprintf(nc->info_str, sizeof(nc->info_str), "socket: fd=%d", fd);
 
diff --git a/net/tap-win32.c b/net/tap-win32.c
index 0e3b883..c4c98aa 100644
--- a/net/tap-win32.c
+++ b/net/tap-win32.c
@@ -685,7 +685,7 @@ static int tap_win32_init(VLANClientState *peer, const char *model,
         return -1;
     }
 
-    nc = qemu_new_net_client(&net_tap_win32_info, NULL, peer, model, name);
+    nc = qemu_new_net_client(&net_tap_win32_info, peer, model, name);
 
     s = DO_UPCAST(TAPState, nc, nc);
 
diff --git a/net/tap.c b/net/tap.c
index 43c3fcd..10ae98d 100644
--- a/net/tap.c
+++ b/net/tap.c
@@ -331,7 +331,7 @@ static TAPState *net_tap_fd_init(VLANClientState *peer,
     VLANClientState *nc;
     TAPState *s;
 
-    nc = qemu_new_net_client(&net_tap_info, NULL, peer, model, name);
+    nc = qemu_new_net_client(&net_tap_info, peer, model, name);
 
     s = DO_UPCAST(TAPState, nc, nc);
 
diff --git a/net/vde.c b/net/vde.c
index 302a022..a1480d7 100644
--- a/net/vde.c
+++ b/net/vde.c
@@ -96,7 +96,7 @@ static int net_vde_init(VLANClientState *peer, const char *model,
         return -1;
     }
 
-    nc = qemu_new_net_client(&net_vde_info, NULL, peer, model, name);
+    nc = qemu_new_net_client(&net_vde_info, peer, model, name);
 
     snprintf(nc->info_str, sizeof(nc->info_str), "sock=%s,fd=%d",
              sock, vde_datafd(vde));
commit 81017645e45bcb0b4d985e900c501f92f2c6fb60
Author: Stefan Hajnoczi <stefanha at linux.vnet.ibm.com>
Date:   Tue Jul 24 16:35:07 2012 +0100

    hub: Check that hubs are configured correctly
    
    Checks can be performed to make sure that hubs have at least one NIC and
    one host device, warning the user if this is not the case.
    Configurations which do not meet this rule tend to be broken but just
    emit a warning.  This patch preserves compatibility with the checks
    performed by net core on vlans.
    
    Signed-off-by: Stefan Hajnoczi <stefanha at linux.vnet.ibm.com>
    Signed-off-by: Zhi Yong Wu <wuzhy at linux.vnet.ibm.com>
    Reviewed-by: Laszlo Ersek <lersek at redhat.com>

diff --git a/net.c b/net.c
index f88d38d..413dac4 100644
--- a/net.c
+++ b/net.c
@@ -1124,7 +1124,6 @@ void net_cleanup(void)
 
 void net_check_clients(void)
 {
-    VLANState *vlan;
     VLANClientState *vc;
     int i;
 
@@ -1140,30 +1139,8 @@ void net_check_clients(void)
         return;
     }
 
-    QTAILQ_FOREACH(vlan, &vlans, next) {
-        int has_nic = 0, has_host_dev = 0;
+    net_hub_check_clients();
 
-        QTAILQ_FOREACH(vc, &vlan->clients, next) {
-            switch (vc->info->type) {
-            case NET_CLIENT_OPTIONS_KIND_NIC:
-                has_nic = 1;
-                break;
-            case NET_CLIENT_OPTIONS_KIND_USER:
-            case NET_CLIENT_OPTIONS_KIND_TAP:
-            case NET_CLIENT_OPTIONS_KIND_SOCKET:
-            case NET_CLIENT_OPTIONS_KIND_VDE:
-                has_host_dev = 1;
-                break;
-            default: ;
-            }
-        }
-        if (has_host_dev && !has_nic)
-            fprintf(stderr, "Warning: vlan %d with no nics\n", vlan->id);
-        if (has_nic && !has_host_dev)
-            fprintf(stderr,
-                    "Warning: vlan %d is not connected to host network\n",
-                    vlan->id);
-    }
     QTAILQ_FOREACH(vc, &non_vlan_clients, next) {
         if (!vc->peer) {
             fprintf(stderr, "Warning: %s %s has no peer\n",
diff --git a/net/hub.c b/net/hub.c
index 9806a59..5cdd8c9 100644
--- a/net/hub.c
+++ b/net/hub.c
@@ -244,3 +244,48 @@ int net_init_hubport(const NetClientOptions *opts, const char *name,
     net_hub_add_port(hubport->hubid, name);
     return 0;
 }
+
+/**
+ * Warn if hub configurations are likely wrong
+ */
+void net_hub_check_clients(void)
+{
+    NetHub *hub;
+    NetHubPort *port;
+    VLANClientState *peer;
+
+    QLIST_FOREACH(hub, &hubs, next) {
+        int has_nic = 0, has_host_dev = 0;
+
+        QLIST_FOREACH(port, &hub->ports, next) {
+            peer = port->nc.peer;
+            if (!peer) {
+                fprintf(stderr, "Warning: hub port %s has no peer\n",
+                        port->nc.name);
+                continue;
+            }
+
+            switch (peer->info->type) {
+            case NET_CLIENT_OPTIONS_KIND_NIC:
+                has_nic = 1;
+                break;
+            case NET_CLIENT_OPTIONS_KIND_USER:
+            case NET_CLIENT_OPTIONS_KIND_TAP:
+            case NET_CLIENT_OPTIONS_KIND_SOCKET:
+            case NET_CLIENT_OPTIONS_KIND_VDE:
+                has_host_dev = 1;
+                break;
+            default:
+                break;
+            }
+        }
+        if (has_host_dev && !has_nic) {
+            fprintf(stderr, "Warning: vlan %d with no nics\n", hub->id);
+        }
+        if (has_nic && !has_host_dev) {
+            fprintf(stderr,
+                    "Warning: vlan %d is not connected to host network\n",
+                    hub->id);
+        }
+    }
+}
diff --git a/net/hub.h b/net/hub.h
index 6770850..9973da3 100644
--- a/net/hub.h
+++ b/net/hub.h
@@ -23,5 +23,6 @@ VLANClientState *net_hub_add_port(int hub_id, const char *name);
 VLANClientState *net_hub_find_client_by_name(int hub_id, const char *name);
 void net_hub_info(Monitor *mon);
 int net_hub_id_for_client(VLANClientState *nc, int *id);
+void net_hub_check_clients(void);
 
 #endif /* NET_HUB_H */
commit 90d87a33c700e0634bc4343fa7a034f909662254
Author: Stefan Hajnoczi <stefanha at linux.vnet.ibm.com>
Date:   Tue Jul 24 16:35:06 2012 +0100

    net: Look up 'vlan' net clients using hubs
    
    Signed-off-by: Stefan Hajnoczi <stefanha at linux.vnet.ibm.com>
    Signed-off-by: Zhi Yong Wu <wuzhy at linux.vnet.ibm.com>
    Reviewed-by: Laszlo Ersek <lersek at redhat.com>

diff --git a/net.c b/net.c
index 4feca6c..f88d38d 100644
--- a/net.c
+++ b/net.c
@@ -315,32 +315,6 @@ void qemu_del_vlan_client(VLANClientState *vc)
     qemu_free_vlan_client(vc);
 }
 
-VLANClientState *
-qemu_find_vlan_client_by_name(Monitor *mon, int vlan_id,
-                              const char *client_str)
-{
-    VLANState *vlan;
-    VLANClientState *vc;
-
-    vlan = qemu_find_vlan(vlan_id, 0);
-    if (!vlan) {
-        monitor_printf(mon, "unknown VLAN %d\n", vlan_id);
-        return NULL;
-    }
-
-    QTAILQ_FOREACH(vc, &vlan->clients, next) {
-        if (!strcmp(vc->name, client_str)) {
-            break;
-        }
-    }
-    if (!vc) {
-        monitor_printf(mon, "can't find device %s on VLAN %d\n",
-                       client_str, vlan_id);
-    }
-
-    return vc;
-}
-
 void qemu_foreach_nic(qemu_nic_foreach func, void *opaque)
 {
     VLANClientState *nc;
@@ -994,7 +968,7 @@ void net_host_device_remove(Monitor *mon, const QDict *qdict)
     int vlan_id = qdict_get_int(qdict, "vlan_id");
     const char *device = qdict_get_str(qdict, "device");
 
-    vc = qemu_find_vlan_client_by_name(mon, vlan_id, device);
+    vc = net_hub_find_client_by_name(vlan_id, device);
     if (!vc) {
         return;
     }
diff --git a/net/hub.c b/net/hub.c
index ee9d878..9806a59 100644
--- a/net/hub.c
+++ b/net/hub.c
@@ -165,6 +165,29 @@ VLANClientState *net_hub_add_port(int hub_id, const char *name)
 }
 
 /**
+ * Find a specific client on a hub
+ */
+VLANClientState *net_hub_find_client_by_name(int hub_id, const char *name)
+{
+    NetHub *hub;
+    NetHubPort *port;
+    VLANClientState *peer;
+
+    QLIST_FOREACH(hub, &hubs, next) {
+        if (hub->id == hub_id) {
+            QLIST_FOREACH(port, &hub->ports, next) {
+                peer = port->nc.peer;
+
+                if (peer && strcmp(peer->name, name) == 0) {
+                    return peer;
+                }
+            }
+        }
+    }
+    return NULL;
+}
+
+/**
  * Print hub configuration
  */
 void net_hub_info(Monitor *mon)
diff --git a/net/hub.h b/net/hub.h
index a5fa2ba..6770850 100644
--- a/net/hub.h
+++ b/net/hub.h
@@ -20,6 +20,7 @@
 int net_init_hubport(const NetClientOptions *opts, const char *name,
                      VLANClientState *peer);
 VLANClientState *net_hub_add_port(int hub_id, const char *name);
+VLANClientState *net_hub_find_client_by_name(int hub_id, const char *name);
 void net_hub_info(Monitor *mon);
 int net_hub_id_for_client(VLANClientState *nc, int *id);
 
diff --git a/net/slirp.c b/net/slirp.c
index 97e380c..7682ac7 100644
--- a/net/slirp.c
+++ b/net/slirp.c
@@ -30,6 +30,7 @@
 #include <sys/wait.h>
 #endif
 #include "net.h"
+#include "net/hub.h"
 #include "monitor.h"
 #include "qemu_socket.h"
 #include "slirp/libslirp.h"
@@ -284,7 +285,7 @@ static SlirpState *slirp_lookup(Monitor *mon, const char *vlan,
 
     if (vlan) {
         VLANClientState *nc;
-        nc = qemu_find_vlan_client_by_name(mon, strtol(vlan, NULL, 0), stack);
+        nc = net_hub_find_client_by_name(strtol(vlan, NULL, 0), stack);
         if (!nc) {
             return NULL;
         }
@@ -679,8 +680,10 @@ void do_info_usernet(Monitor *mon)
     SlirpState *s;
 
     QTAILQ_FOREACH(s, &slirp_stacks, entry) {
+        int id;
+        bool got_vlan_id = net_hub_id_for_client(&s->nc, &id) == 0;
         monitor_printf(mon, "VLAN %d (%s):\n",
-                       s->nc.vlan ? s->nc.vlan->id : -1,
+                       got_vlan_id ? id : -1,
                        s->nc.name);
         slirp_connection_info(s->slirp, mon);
     }
commit d33d93b2c40b820c2cfab1e2e6da631f12091957
Author: Stefan Hajnoczi <stefanha at linux.vnet.ibm.com>
Date:   Tue Jul 24 16:35:05 2012 +0100

    net: Use hubs for the vlan feature
    
    Stop using the special-case vlan code in net.c.  Instead use the hub net
    client to implement the vlan feature.  The next patch will remove vlan
    code from net.c completely.
    
    Signed-off-by: Stefan Hajnoczi <stefanha at linux.vnet.ibm.com>
    Signed-off-by: Zhi Yong Wu <wuzhy at linux.vnet.ibm.com>
    Reviewed-by: Laszlo Ersek <lersek at redhat.com>

diff --git a/net.c b/net.c
index e7a8d81..4feca6c 100644
--- a/net.c
+++ b/net.c
@@ -157,23 +157,25 @@ void qemu_macaddr_default_if_unset(MACAddr *macaddr)
     macaddr->a[5] = 0x56 + index++;
 }
 
+/**
+ * Generate a name for net client
+ *
+ * Only net clients created with the legacy -net option need this.  Naming is
+ * mandatory for net clients created with -netdev.
+ */
 static char *assign_name(VLANClientState *vc1, const char *model)
 {
-    VLANState *vlan;
     VLANClientState *vc;
     char buf[256];
     int id = 0;
 
-    QTAILQ_FOREACH(vlan, &vlans, next) {
-        QTAILQ_FOREACH(vc, &vlan->clients, next) {
-            if (vc != vc1 && strcmp(vc->model, model) == 0) {
-                id++;
-            }
-        }
-    }
-
     QTAILQ_FOREACH(vc, &non_vlan_clients, next) {
-        if (vc != vc1 && strcmp(vc->model, model) == 0) {
+        if (vc == vc1) {
+            continue;
+        }
+        /* For compatibility only bump id for net clients on a vlan */
+        if (strcmp(vc->model, model) == 0 &&
+            net_hub_id_for_client(vc, NULL) == 0) {
             id++;
         }
     }
@@ -750,7 +752,7 @@ int net_handle_fd_param(Monitor *mon, const char *param)
 }
 
 static int net_init_nic(const NetClientOptions *opts, const char *name,
-                        VLANState *vlan)
+                        VLANClientState *peer)
 {
     int idx;
     NICInfo *nd;
@@ -776,8 +778,8 @@ static int net_init_nic(const NetClientOptions *opts, const char *name,
             return -1;
         }
     } else {
-        assert(vlan);
-        nd->vlan = vlan;
+        assert(peer);
+        nd->netdev = peer;
     }
     if (name) {
         nd->name = g_strdup(name);
@@ -816,7 +818,7 @@ static int net_init_nic(const NetClientOptions *opts, const char *name,
 static int (* const net_client_init_fun[NET_CLIENT_OPTIONS_KIND_MAX])(
     const NetClientOptions *opts,
     const char *name,
-    VLANState *vlan) = {
+    VLANClientState *peer) = {
         [NET_CLIENT_OPTIONS_KIND_NIC]       = net_init_nic,
 #ifdef CONFIG_SLIRP
         [NET_CLIENT_OPTIONS_KIND_USER]      = net_init_slirp,
@@ -876,17 +878,17 @@ static int net_client_init1(const void *object, int is_netdev, Error **errp)
     }
 
     if (net_client_init_fun[opts->kind]) {
-        VLANState *vlan = NULL;
+        VLANClientState *peer = NULL;
 
         /* Do not add to a vlan if it's a -netdev or a nic with a netdev=
          * parameter. */
         if (!is_netdev &&
             (opts->kind != NET_CLIENT_OPTIONS_KIND_NIC ||
              !opts->nic->has_netdev)) {
-            vlan = qemu_find_vlan(u.net->has_vlan ? u.net->vlan : 0, true);
+            peer = net_hub_add_port(u.net->has_vlan ? u.net->vlan : 0, NULL);
         }
 
-        if (net_client_init_fun[opts->kind](opts, name, vlan) < 0) {
+        if (net_client_init_fun[opts->kind](opts, name, peer) < 0) {
             /* TODO push error reporting into init() methods */
             error_set(errp, QERR_DEVICE_INIT_FAILED,
                       NetClientOptionsKind_lookup[opts->kind]);
@@ -1085,6 +1087,7 @@ void do_info_network(Monitor *mon)
             print_net_client(mon, peer);
         }
     }
+    net_hub_info(mon);
 }
 
 void qmp_set_link(const char *name, bool up, Error **errp)
diff --git a/net/dump.c b/net/dump.c
index b575430..9d7bf3b 100644
--- a/net/dump.c
+++ b/net/dump.c
@@ -27,6 +27,7 @@
 #include "qemu-error.h"
 #include "qemu-log.h"
 #include "qemu-timer.h"
+#include "hub.h"
 
 typedef struct DumpState {
     VLANClientState nc;
@@ -99,7 +100,7 @@ static NetClientInfo net_dump_info = {
     .cleanup = dump_cleanup,
 };
 
-static int net_dump_init(VLANState *vlan, const char *device,
+static int net_dump_init(VLANClientState *peer, const char *device,
                          const char *name, const char *filename, int len)
 {
     struct pcap_file_hdr hdr;
@@ -128,7 +129,7 @@ static int net_dump_init(VLANState *vlan, const char *device,
         return -1;
     }
 
-    nc = qemu_new_net_client(&net_dump_info, vlan, NULL, device, name);
+    nc = qemu_new_net_client(&net_dump_info, NULL, peer, device, name);
 
     snprintf(nc->info_str, sizeof(nc->info_str),
              "dump to %s (len=%d)", filename, len);
@@ -145,7 +146,7 @@ static int net_dump_init(VLANState *vlan, const char *device,
 }
 
 int net_init_dump(const NetClientOptions *opts, const char *name,
-                  VLANState *vlan)
+                  VLANClientState *peer)
 {
     int len;
     const char *file;
@@ -155,12 +156,18 @@ int net_init_dump(const NetClientOptions *opts, const char *name,
     assert(opts->kind == NET_CLIENT_OPTIONS_KIND_DUMP);
     dump = opts->dump;
 
-    assert(vlan);
+    assert(peer);
 
     if (dump->has_file) {
         file = dump->file;
     } else {
-        snprintf(def_file, sizeof(def_file), "qemu-vlan%d.pcap", vlan->id);
+        int id;
+        int ret;
+
+        ret = net_hub_id_for_client(peer, &id);
+        assert(ret == 0); /* peer must be on a hub */
+
+        snprintf(def_file, sizeof(def_file), "qemu-vlan%d.pcap", id);
         file = def_file;
     }
 
@@ -174,5 +181,5 @@ int net_init_dump(const NetClientOptions *opts, const char *name,
         len = 65536;
     }
 
-    return net_dump_init(vlan, "dump", name, file, len);
+    return net_dump_init(peer, "dump", name, file, len);
 }
diff --git a/net/dump.h b/net/dump.h
index 0fa2dd7..9d70195 100644
--- a/net/dump.h
+++ b/net/dump.h
@@ -28,6 +28,6 @@
 #include "qapi-types.h"
 
 int net_init_dump(const NetClientOptions *opts, const char *name,
-                  VLANState *vlan);
+                  VLANClientState *peer);
 
 #endif /* QEMU_NET_DUMP_H */
diff --git a/net/hub.c b/net/hub.c
index be6e014..ee9d878 100644
--- a/net/hub.c
+++ b/net/hub.c
@@ -206,15 +206,15 @@ int net_hub_id_for_client(VLANClientState *nc, int *id)
 }
 
 int net_init_hubport(const NetClientOptions *opts, const char *name,
-                     VLANState *vlan)
+                     VLANClientState *peer)
 {
     const NetdevHubPortOptions *hubport;
 
     assert(opts->kind == NET_CLIENT_OPTIONS_KIND_HUBPORT);
     hubport = opts->hubport;
 
-    /* The hub is a "vlan" so this option makes no sense. */
-    if (vlan) {
+    /* Treat hub port like a backend, NIC must be the one to peer */
+    if (peer) {
         return -EINVAL;
     }
 
diff --git a/net/hub.h b/net/hub.h
index f0d98f2..a5fa2ba 100644
--- a/net/hub.h
+++ b/net/hub.h
@@ -18,7 +18,7 @@
 #include "qemu-common.h"
 
 int net_init_hubport(const NetClientOptions *opts, const char *name,
-                     VLANState *vlan);
+                     VLANClientState *peer);
 VLANClientState *net_hub_add_port(int hub_id, const char *name);
 void net_hub_info(Monitor *mon);
 int net_hub_id_for_client(VLANClientState *nc, int *id);
diff --git a/net/slirp.c b/net/slirp.c
index 5c2e6b2..97e380c 100644
--- a/net/slirp.c
+++ b/net/slirp.c
@@ -135,7 +135,7 @@ static NetClientInfo net_slirp_info = {
     .cleanup = net_slirp_cleanup,
 };
 
-static int net_slirp_init(VLANState *vlan, const char *model,
+static int net_slirp_init(VLANClientState *peer, const char *model,
                           const char *name, int restricted,
                           const char *vnetwork, const char *vhost,
                           const char *vhostname, const char *tftp_export,
@@ -238,7 +238,7 @@ static int net_slirp_init(VLANState *vlan, const char *model,
     }
 #endif
 
-    nc = qemu_new_net_client(&net_slirp_info, vlan, NULL, model, name);
+    nc = qemu_new_net_client(&net_slirp_info, NULL, peer, model, name);
 
     snprintf(nc->info_str, sizeof(nc->info_str),
              "net=%s,restrict=%s", inet_ntoa(net),
@@ -703,7 +703,7 @@ net_init_slirp_configs(const StringList *fwd, int flags)
 }
 
 int net_init_slirp(const NetClientOptions *opts, const char *name,
-                   VLANState *vlan)
+                   VLANClientState *peer)
 {
     struct slirp_config_str *config;
     char *vnet;
@@ -722,7 +722,7 @@ int net_init_slirp(const NetClientOptions *opts, const char *name,
     net_init_slirp_configs(user->hostfwd, SLIRP_CFG_HOSTFWD);
     net_init_slirp_configs(user->guestfwd, 0);
 
-    ret = net_slirp_init(vlan, "user", name, user->restrict, vnet, user->host,
+    ret = net_slirp_init(peer, "user", name, user->restrict, vnet, user->host,
                          user->hostname, user->tftp, user->bootfile,
                          user->dhcpstart, user->dns, user->smb,
                          user->smbserver);
diff --git a/net/slirp.h b/net/slirp.h
index e2c71ee..1ff21b0 100644
--- a/net/slirp.h
+++ b/net/slirp.h
@@ -32,7 +32,7 @@
 #ifdef CONFIG_SLIRP
 
 int net_init_slirp(const NetClientOptions *opts, const char *name,
-                   VLANState *vlan);
+                   VLANClientState *peer);
 
 void net_slirp_hostfwd_add(Monitor *mon, const QDict *qdict);
 void net_slirp_hostfwd_remove(Monitor *mon, const QDict *qdict);
diff --git a/net/socket.c b/net/socket.c
index 600c287..09bdc66 100644
--- a/net/socket.c
+++ b/net/socket.c
@@ -44,7 +44,7 @@ typedef struct NetSocketState {
 } NetSocketState;
 
 typedef struct NetSocketListenState {
-    VLANState *vlan;
+    VLANClientState *peer;
     char *model;
     char *name;
     int fd;
@@ -245,7 +245,7 @@ static NetClientInfo net_dgram_socket_info = {
     .cleanup = net_socket_cleanup,
 };
 
-static NetSocketState *net_socket_fd_init_dgram(VLANState *vlan,
+static NetSocketState *net_socket_fd_init_dgram(VLANClientState *peer,
                                                 const char *model,
                                                 const char *name,
                                                 int fd, int is_connected)
@@ -287,7 +287,7 @@ static NetSocketState *net_socket_fd_init_dgram(VLANState *vlan,
         }
     }
 
-    nc = qemu_new_net_client(&net_dgram_socket_info, vlan, NULL, model, name);
+    nc = qemu_new_net_client(&net_dgram_socket_info, NULL, peer, model, name);
 
     snprintf(nc->info_str, sizeof(nc->info_str),
             "socket: fd=%d (%s mcast=%s:%d)",
@@ -323,7 +323,7 @@ static NetClientInfo net_socket_info = {
     .cleanup = net_socket_cleanup,
 };
 
-static NetSocketState *net_socket_fd_init_stream(VLANState *vlan,
+static NetSocketState *net_socket_fd_init_stream(VLANClientState *peer,
                                                  const char *model,
                                                  const char *name,
                                                  int fd, int is_connected)
@@ -331,7 +331,7 @@ static NetSocketState *net_socket_fd_init_stream(VLANState *vlan,
     VLANClientState *nc;
     NetSocketState *s;
 
-    nc = qemu_new_net_client(&net_socket_info, vlan, NULL, model, name);
+    nc = qemu_new_net_client(&net_socket_info, NULL, peer, model, name);
 
     snprintf(nc->info_str, sizeof(nc->info_str), "socket: fd=%d", fd);
 
@@ -347,7 +347,7 @@ static NetSocketState *net_socket_fd_init_stream(VLANState *vlan,
     return s;
 }
 
-static NetSocketState *net_socket_fd_init(VLANState *vlan,
+static NetSocketState *net_socket_fd_init(VLANClientState *peer,
                                           const char *model, const char *name,
                                           int fd, int is_connected)
 {
@@ -362,13 +362,13 @@ static NetSocketState *net_socket_fd_init(VLANState *vlan,
     }
     switch(so_type) {
     case SOCK_DGRAM:
-        return net_socket_fd_init_dgram(vlan, model, name, fd, is_connected);
+        return net_socket_fd_init_dgram(peer, model, name, fd, is_connected);
     case SOCK_STREAM:
-        return net_socket_fd_init_stream(vlan, model, name, fd, is_connected);
+        return net_socket_fd_init_stream(peer, model, name, fd, is_connected);
     default:
         /* who knows ... this could be a eg. a pty, do warn and continue as stream */
         fprintf(stderr, "qemu: warning: socket type=%d for fd=%d is not SOCK_DGRAM or SOCK_STREAM\n", so_type, fd);
-        return net_socket_fd_init_stream(vlan, model, name, fd, is_connected);
+        return net_socket_fd_init_stream(peer, model, name, fd, is_connected);
     }
     return NULL;
 }
@@ -390,7 +390,7 @@ static void net_socket_accept(void *opaque)
             break;
         }
     }
-    s1 = net_socket_fd_init(s->vlan, s->model, s->name, fd, 1);
+    s1 = net_socket_fd_init(s->peer, s->model, s->name, fd, 1);
     if (s1) {
         snprintf(s1->nc.info_str, sizeof(s1->nc.info_str),
                  "socket: connection from %s:%d",
@@ -398,7 +398,7 @@ static void net_socket_accept(void *opaque)
     }
 }
 
-static int net_socket_listen_init(VLANState *vlan,
+static int net_socket_listen_init(VLANClientState *peer,
                                   const char *model,
                                   const char *name,
                                   const char *host_str)
@@ -438,7 +438,7 @@ static int net_socket_listen_init(VLANState *vlan,
         closesocket(fd);
         return -1;
     }
-    s->vlan = vlan;
+    s->peer = peer;
     s->model = g_strdup(model);
     s->name = name ? g_strdup(name) : NULL;
     s->fd = fd;
@@ -446,7 +446,7 @@ static int net_socket_listen_init(VLANState *vlan,
     return 0;
 }
 
-static int net_socket_connect_init(VLANState *vlan,
+static int net_socket_connect_init(VLANClientState *peer,
                                    const char *model,
                                    const char *name,
                                    const char *host_str)
@@ -487,7 +487,7 @@ static int net_socket_connect_init(VLANState *vlan,
             break;
         }
     }
-    s = net_socket_fd_init(vlan, model, name, fd, connected);
+    s = net_socket_fd_init(peer, model, name, fd, connected);
     if (!s)
         return -1;
     snprintf(s->nc.info_str, sizeof(s->nc.info_str),
@@ -496,7 +496,7 @@ static int net_socket_connect_init(VLANState *vlan,
     return 0;
 }
 
-static int net_socket_mcast_init(VLANState *vlan,
+static int net_socket_mcast_init(VLANClientState *peer,
                                  const char *model,
                                  const char *name,
                                  const char *host_str,
@@ -522,7 +522,7 @@ static int net_socket_mcast_init(VLANState *vlan,
     if (fd < 0)
         return -1;
 
-    s = net_socket_fd_init(vlan, model, name, fd, 0);
+    s = net_socket_fd_init(peer, model, name, fd, 0);
     if (!s)
         return -1;
 
@@ -535,7 +535,7 @@ static int net_socket_mcast_init(VLANState *vlan,
 
 }
 
-static int net_socket_udp_init(VLANState *vlan,
+static int net_socket_udp_init(VLANClientState *peer,
                                  const char *model,
                                  const char *name,
                                  const char *rhost,
@@ -573,7 +573,7 @@ static int net_socket_udp_init(VLANState *vlan,
         return -1;
     }
 
-    s = net_socket_fd_init(vlan, model, name, fd, 0);
+    s = net_socket_fd_init(peer, model, name, fd, 0);
     if (!s) {
         return -1;
     }
@@ -587,7 +587,7 @@ static int net_socket_udp_init(VLANState *vlan,
 }
 
 int net_init_socket(const NetClientOptions *opts, const char *name,
-                    VLANState *vlan)
+                    VLANClientState *peer)
 {
     const NetdevSocketOptions *sock;
 
@@ -610,21 +610,21 @@ int net_init_socket(const NetClientOptions *opts, const char *name,
         int fd;
 
         fd = net_handle_fd_param(cur_mon, sock->fd);
-        if (fd == -1 || !net_socket_fd_init(vlan, "socket", name, fd, 1)) {
+        if (fd == -1 || !net_socket_fd_init(peer, "socket", name, fd, 1)) {
             return -1;
         }
         return 0;
     }
 
     if (sock->has_listen) {
-        if (net_socket_listen_init(vlan, "socket", name, sock->listen) == -1) {
+        if (net_socket_listen_init(peer, "socket", name, sock->listen) == -1) {
             return -1;
         }
         return 0;
     }
 
     if (sock->has_connect) {
-        if (net_socket_connect_init(vlan, "socket", name, sock->connect) ==
+        if (net_socket_connect_init(peer, "socket", name, sock->connect) ==
             -1) {
             return -1;
         }
@@ -634,7 +634,7 @@ int net_init_socket(const NetClientOptions *opts, const char *name,
     if (sock->has_mcast) {
         /* if sock->localaddr is missing, it has been initialized to "all bits
          * zero" */
-        if (net_socket_mcast_init(vlan, "socket", name, sock->mcast,
+        if (net_socket_mcast_init(peer, "socket", name, sock->mcast,
             sock->localaddr) == -1) {
             return -1;
         }
@@ -646,7 +646,7 @@ int net_init_socket(const NetClientOptions *opts, const char *name,
         error_report("localaddr= is mandatory with udp=");
         return -1;
     }
-    if (net_socket_udp_init(vlan, "udp", name, sock->udp, sock->localaddr) ==
+    if (net_socket_udp_init(peer, "udp", name, sock->udp, sock->localaddr) ==
         -1) {
         return -1;
     }
diff --git a/net/socket.h b/net/socket.h
index c4809ad..82b4d16 100644
--- a/net/socket.h
+++ b/net/socket.h
@@ -28,6 +28,6 @@
 #include "qapi-types.h"
 
 int net_init_socket(const NetClientOptions *opts, const char *name,
-                    VLANState *vlan);
+                    VLANClientState *peer);
 
 #endif /* QEMU_NET_SOCKET_H */
diff --git a/net/tap-win32.c b/net/tap-win32.c
index 2328072..0e3b883 100644
--- a/net/tap-win32.c
+++ b/net/tap-win32.c
@@ -673,7 +673,7 @@ static NetClientInfo net_tap_win32_info = {
     .cleanup = tap_cleanup,
 };
 
-static int tap_win32_init(VLANState *vlan, const char *model,
+static int tap_win32_init(VLANClientState *peer, const char *model,
                           const char *name, const char *ifname)
 {
     VLANClientState *nc;
@@ -685,7 +685,7 @@ static int tap_win32_init(VLANState *vlan, const char *model,
         return -1;
     }
 
-    nc = qemu_new_net_client(&net_tap_win32_info, vlan, NULL, model, name);
+    nc = qemu_new_net_client(&net_tap_win32_info, NULL, peer, model, name);
 
     s = DO_UPCAST(TAPState, nc, nc);
 
@@ -700,7 +700,7 @@ static int tap_win32_init(VLANState *vlan, const char *model,
 }
 
 int net_init_tap(const NetClientOptions *opts, const char *name,
-                 VLANState *vlan)
+                 VLANClientState *peer)
 {
     const NetdevTapOptions *tap;
 
@@ -712,7 +712,7 @@ int net_init_tap(const NetClientOptions *opts, const char *name,
         return -1;
     }
 
-    if (tap_win32_init(vlan, "tap", name, tap->ifname) == -1) {
+    if (tap_win32_init(peer, "tap", name, tap->ifname) == -1) {
         return -1;
     }
 
diff --git a/net/tap.c b/net/tap.c
index 7206227..43c3fcd 100644
--- a/net/tap.c
+++ b/net/tap.c
@@ -322,7 +322,7 @@ static NetClientInfo net_tap_info = {
     .cleanup = tap_cleanup,
 };
 
-static TAPState *net_tap_fd_init(VLANState *vlan,
+static TAPState *net_tap_fd_init(VLANClientState *peer,
                                  const char *model,
                                  const char *name,
                                  int fd,
@@ -331,7 +331,7 @@ static TAPState *net_tap_fd_init(VLANState *vlan,
     VLANClientState *nc;
     TAPState *s;
 
-    nc = qemu_new_net_client(&net_tap_info, vlan, NULL, model, name);
+    nc = qemu_new_net_client(&net_tap_info, NULL, peer, model, name);
 
     s = DO_UPCAST(TAPState, nc, nc);
 
@@ -514,7 +514,7 @@ static int net_bridge_run_helper(const char *helper, const char *bridge)
 }
 
 int net_init_bridge(const NetClientOptions *opts, const char *name,
-                    VLANState *vlan)
+                    VLANClientState *peer)
 {
     const NetdevBridgeOptions *bridge;
     const char *helper, *br;
@@ -537,7 +537,7 @@ int net_init_bridge(const NetClientOptions *opts, const char *name,
 
     vnet_hdr = tap_probe_vnet_hdr(fd);
 
-    s = net_tap_fd_init(vlan, "bridge", name, fd, vnet_hdr);
+    s = net_tap_fd_init(peer, "bridge", name, fd, vnet_hdr);
     if (!s) {
         close(fd);
         return -1;
@@ -587,7 +587,7 @@ static int net_tap_init(const NetdevTapOptions *tap, int *vnet_hdr,
 }
 
 int net_init_tap(const NetClientOptions *opts, const char *name,
-                 VLANState *vlan)
+                 VLANClientState *peer)
 {
     const NetdevTapOptions *tap;
 
@@ -650,7 +650,7 @@ int net_init_tap(const NetClientOptions *opts, const char *name,
         model = "tap";
     }
 
-    s = net_tap_fd_init(vlan, model, name, fd, vnet_hdr);
+    s = net_tap_fd_init(peer, model, name, fd, vnet_hdr);
     if (!s) {
         close(fd);
         return -1;
diff --git a/net/tap.h b/net/tap.h
index 19dea58..113906f 100644
--- a/net/tap.h
+++ b/net/tap.h
@@ -33,7 +33,7 @@
 #define DEFAULT_NETWORK_DOWN_SCRIPT "/etc/qemu-ifdown"
 
 int net_init_tap(const NetClientOptions *opts, const char *name,
-                 VLANState *vlan);
+                 VLANClientState *peer);
 
 int tap_open(char *ifname, int ifname_size, int *vnet_hdr, int vnet_hdr_required);
 
@@ -59,6 +59,6 @@ struct vhost_net;
 struct vhost_net *tap_get_vhost_net(VLANClientState *vc);
 
 int net_init_bridge(const NetClientOptions *opts, const char *name,
-                    VLANState *vlan);
+                    VLANClientState *peer);
 
 #endif /* QEMU_NET_TAP_H */
diff --git a/net/vde.c b/net/vde.c
index ee19f5c..302a022 100644
--- a/net/vde.c
+++ b/net/vde.c
@@ -75,7 +75,7 @@ static NetClientInfo net_vde_info = {
     .cleanup = vde_cleanup,
 };
 
-static int net_vde_init(VLANState *vlan, const char *model,
+static int net_vde_init(VLANClientState *peer, const char *model,
                         const char *name, const char *sock,
                         int port, const char *group, int mode)
 {
@@ -96,7 +96,7 @@ static int net_vde_init(VLANState *vlan, const char *model,
         return -1;
     }
 
-    nc = qemu_new_net_client(&net_vde_info, vlan, NULL, model, name);
+    nc = qemu_new_net_client(&net_vde_info, NULL, peer, model, name);
 
     snprintf(nc->info_str, sizeof(nc->info_str), "sock=%s,fd=%d",
              sock, vde_datafd(vde));
@@ -111,7 +111,7 @@ static int net_vde_init(VLANState *vlan, const char *model,
 }
 
 int net_init_vde(const NetClientOptions *opts, const char *name,
-                 VLANState *vlan)
+                 VLANClientState *peer)
 {
     const NetdevVdeOptions *vde;
 
@@ -119,7 +119,7 @@ int net_init_vde(const NetClientOptions *opts, const char *name,
     vde = opts->vde;
 
     /* missing optional values have been initialized to "all bits zero" */
-    if (net_vde_init(vlan, "vde", name, vde->sock, vde->port, vde->group,
+    if (net_vde_init(peer, "vde", name, vde->sock, vde->port, vde->group,
                      vde->has_mode ? vde->mode : 0700) == -1) {
         return -1;
     }
diff --git a/net/vde.h b/net/vde.h
index ad502ef..d6f7af4 100644
--- a/net/vde.h
+++ b/net/vde.h
@@ -30,7 +30,7 @@
 #ifdef CONFIG_VDE
 
 int net_init_vde(const NetClientOptions *opts, const char *name,
-                 VLANState *vlan);
+                 VLANClientState *peer);
 
 #endif /* CONFIG_VDE */
 
commit f6c874e3002b944f83d887b84051654e5c5b7821
Author: Stefan Hajnoczi <stefanha at linux.vnet.ibm.com>
Date:   Tue Jul 24 16:35:04 2012 +0100

    net: Add a hub net client
    
    The vlan feature can be implemented in terms of hubs.  By introducing a
    hub net client it becomes possible to remove the special case vlan code
    from net.c and push the vlan feature out of generic networking code.
    
    Signed-off-by: Stefan Hajnoczi <stefanha at linux.vnet.ibm.com>
    Signed-off-by: Zhi Yong Wu <wuzhy at linux.vnet.ibm.com>
    Reviewed-by: Laszlo Ersek <lersek at redhat.com>

diff --git a/net.c b/net.c
index dbca77b..e7a8d81 100644
--- a/net.c
+++ b/net.c
@@ -30,6 +30,7 @@
 #include "net/dump.h"
 #include "net/slirp.h"
 #include "net/vde.h"
+#include "net/hub.h"
 #include "net/util.h"
 #include "monitor.h"
 #include "qemu-common.h"
@@ -816,19 +817,20 @@ static int (* const net_client_init_fun[NET_CLIENT_OPTIONS_KIND_MAX])(
     const NetClientOptions *opts,
     const char *name,
     VLANState *vlan) = {
-        [NET_CLIENT_OPTIONS_KIND_NIC]    = net_init_nic,
+        [NET_CLIENT_OPTIONS_KIND_NIC]       = net_init_nic,
 #ifdef CONFIG_SLIRP
-        [NET_CLIENT_OPTIONS_KIND_USER]   = net_init_slirp,
+        [NET_CLIENT_OPTIONS_KIND_USER]      = net_init_slirp,
 #endif
-        [NET_CLIENT_OPTIONS_KIND_TAP]    = net_init_tap,
-        [NET_CLIENT_OPTIONS_KIND_SOCKET] = net_init_socket,
+        [NET_CLIENT_OPTIONS_KIND_TAP]       = net_init_tap,
+        [NET_CLIENT_OPTIONS_KIND_SOCKET]    = net_init_socket,
 #ifdef CONFIG_VDE
-        [NET_CLIENT_OPTIONS_KIND_VDE]    = net_init_vde,
+        [NET_CLIENT_OPTIONS_KIND_VDE]       = net_init_vde,
 #endif
-        [NET_CLIENT_OPTIONS_KIND_DUMP]   = net_init_dump,
+        [NET_CLIENT_OPTIONS_KIND_DUMP]      = net_init_dump,
 #ifdef CONFIG_NET_BRIDGE
-        [NET_CLIENT_OPTIONS_KIND_BRIDGE] = net_init_bridge,
+        [NET_CLIENT_OPTIONS_KIND_BRIDGE]    = net_init_bridge,
 #endif
+        [NET_CLIENT_OPTIONS_KIND_HUBPORT]   = net_init_hubport,
 };
 
 
@@ -858,6 +860,7 @@ static int net_client_init1(const void *object, int is_netdev, Error **errp)
 #ifdef CONFIG_NET_BRIDGE
         case NET_CLIENT_OPTIONS_KIND_BRIDGE:
 #endif
+        case NET_CLIENT_OPTIONS_KIND_HUBPORT:
             break;
 
         default:
diff --git a/net/Makefile.objs b/net/Makefile.objs
index 72f50bc..cf04187 100644
--- a/net/Makefile.objs
+++ b/net/Makefile.objs
@@ -1,4 +1,4 @@
-common-obj-y = queue.o checksum.o util.o
+common-obj-y = queue.o checksum.o util.o hub.o
 common-obj-y += socket.o
 common-obj-y += dump.o
 common-obj-$(CONFIG_POSIX) += tap.o
diff --git a/net/hub.c b/net/hub.c
new file mode 100644
index 0000000..be6e014
--- /dev/null
+++ b/net/hub.c
@@ -0,0 +1,223 @@
+/*
+ * Hub net client
+ *
+ * Copyright IBM, Corp. 2012
+ *
+ * Authors:
+ *  Stefan Hajnoczi   <stefanha at linux.vnet.ibm.com>
+ *  Zhi Yong Wu       <wuzhy at linux.vnet.ibm.com>
+ *
+ * This work is licensed under the terms of the GNU LGPL, version 2 or later.
+ * See the COPYING.LIB file in the top-level directory.
+ *
+ */
+
+#include "monitor.h"
+#include "net.h"
+#include "hub.h"
+
+/*
+ * A hub broadcasts incoming packets to all its ports except the source port.
+ * Hubs can be used to provide independent network segments, also confusingly
+ * named the QEMU 'vlan' feature.
+ */
+
+typedef struct NetHub NetHub;
+
+typedef struct NetHubPort {
+    VLANClientState nc;
+    QLIST_ENTRY(NetHubPort) next;
+    NetHub *hub;
+    int id;
+} NetHubPort;
+
+struct NetHub {
+    int id;
+    QLIST_ENTRY(NetHub) next;
+    int num_ports;
+    QLIST_HEAD(, NetHubPort) ports;
+};
+
+static QLIST_HEAD(, NetHub) hubs = QLIST_HEAD_INITIALIZER(&hubs);
+
+static ssize_t net_hub_receive(NetHub *hub, NetHubPort *source_port,
+                               const uint8_t *buf, size_t len)
+{
+    NetHubPort *port;
+
+    QLIST_FOREACH(port, &hub->ports, next) {
+        if (port == source_port) {
+            continue;
+        }
+
+        qemu_send_packet(&port->nc, buf, len);
+    }
+    return len;
+}
+
+static ssize_t net_hub_receive_iov(NetHub *hub, NetHubPort *source_port,
+                                   const struct iovec *iov, int iovcnt)
+{
+    NetHubPort *port;
+    ssize_t ret = 0;
+
+    QLIST_FOREACH(port, &hub->ports, next) {
+        if (port == source_port) {
+            continue;
+        }
+
+        ret = qemu_sendv_packet(&port->nc, iov, iovcnt);
+    }
+    return ret;
+}
+
+static NetHub *net_hub_new(int id)
+{
+    NetHub *hub;
+
+    hub = g_malloc(sizeof(*hub));
+    hub->id = id;
+    hub->num_ports = 0;
+    QLIST_INIT(&hub->ports);
+
+    QLIST_INSERT_HEAD(&hubs, hub, next);
+
+    return hub;
+}
+
+static ssize_t net_hub_port_receive(VLANClientState *nc,
+                                    const uint8_t *buf, size_t len)
+{
+    NetHubPort *port = DO_UPCAST(NetHubPort, nc, nc);
+
+    return net_hub_receive(port->hub, port, buf, len);
+}
+
+static ssize_t net_hub_port_receive_iov(VLANClientState *nc,
+                                        const struct iovec *iov, int iovcnt)
+{
+    NetHubPort *port = DO_UPCAST(NetHubPort, nc, nc);
+
+    return net_hub_receive_iov(port->hub, port, iov, iovcnt);
+}
+
+static void net_hub_port_cleanup(VLANClientState *nc)
+{
+    NetHubPort *port = DO_UPCAST(NetHubPort, nc, nc);
+
+    QLIST_REMOVE(port, next);
+}
+
+static NetClientInfo net_hub_port_info = {
+    .type = NET_CLIENT_OPTIONS_KIND_HUBPORT,
+    .size = sizeof(NetHubPort),
+    .receive = net_hub_port_receive,
+    .receive_iov = net_hub_port_receive_iov,
+    .cleanup = net_hub_port_cleanup,
+};
+
+static NetHubPort *net_hub_port_new(NetHub *hub, const char *name)
+{
+    VLANClientState *nc;
+    NetHubPort *port;
+    int id = hub->num_ports++;
+    char default_name[128];
+
+    if (!name) {
+        snprintf(default_name, sizeof(default_name),
+                 "hub%dport%d", hub->id, id);
+        name = default_name;
+    }
+
+    nc = qemu_new_net_client(&net_hub_port_info, NULL, NULL, "hub", name);
+    port = DO_UPCAST(NetHubPort, nc, nc);
+    port->id = id;
+    port->hub = hub;
+
+    QLIST_INSERT_HEAD(&hub->ports, port, next);
+
+    return port;
+}
+
+/**
+ * Create a port on a given hub
+ * @name: Net client name or NULL for default name.
+ *
+ * If there is no existing hub with the given id then a new hub is created.
+ */
+VLANClientState *net_hub_add_port(int hub_id, const char *name)
+{
+    NetHub *hub;
+    NetHubPort *port;
+
+    QLIST_FOREACH(hub, &hubs, next) {
+        if (hub->id == hub_id) {
+            break;
+        }
+    }
+
+    if (!hub) {
+        hub = net_hub_new(hub_id);
+    }
+
+    port = net_hub_port_new(hub, name);
+    return &port->nc;
+}
+
+/**
+ * Print hub configuration
+ */
+void net_hub_info(Monitor *mon)
+{
+    NetHub *hub;
+    NetHubPort *port;
+
+    QLIST_FOREACH(hub, &hubs, next) {
+        monitor_printf(mon, "hub %d\n", hub->id);
+        QLIST_FOREACH(port, &hub->ports, next) {
+            monitor_printf(mon, "    port %d peer %s\n", port->id,
+                           port->nc.peer ? port->nc.peer->name : "<none>");
+        }
+    }
+}
+
+/**
+ * Get the hub id that a client is connected to
+ *
+ * @id              Pointer for hub id output, may be NULL
+ */
+int net_hub_id_for_client(VLANClientState *nc, int *id)
+{
+    NetHubPort *port;
+
+    if (nc->info->type == NET_CLIENT_OPTIONS_KIND_HUBPORT) {
+        port = DO_UPCAST(NetHubPort, nc, nc);
+    } else if (nc->peer != NULL && nc->peer->info->type ==
+            NET_CLIENT_OPTIONS_KIND_HUBPORT) {
+        port = DO_UPCAST(NetHubPort, nc, nc->peer);
+    } else {
+        return -ENOENT;
+    }
+
+    if (id) {
+        *id = port->hub->id;
+    }
+    return 0;
+}
+
+int net_init_hubport(const NetClientOptions *opts, const char *name,
+                     VLANState *vlan)
+{
+    const NetdevHubPortOptions *hubport;
+
+    assert(opts->kind == NET_CLIENT_OPTIONS_KIND_HUBPORT);
+    hubport = opts->hubport;
+
+    /* The hub is a "vlan" so this option makes no sense. */
+    if (vlan) {
+        return -EINVAL;
+    }
+
+    net_hub_add_port(hubport->hubid, name);
+    return 0;
+}
diff --git a/net/hub.h b/net/hub.h
new file mode 100644
index 0000000..f0d98f2
--- /dev/null
+++ b/net/hub.h
@@ -0,0 +1,26 @@
+/*
+ * Hub net client
+ *
+ * Copyright IBM, Corp. 2012
+ *
+ * Authors:
+ *  Stefan Hajnoczi   <stefanha at linux.vnet.ibm.com>
+ *  Zhi Yong Wu       <wuzhy at linux.vnet.ibm.com>
+ *
+ * This work is licensed under the terms of the GNU LGPL, version 2 or later.
+ * See the COPYING.LIB file in the top-level directory.
+ *
+ */
+
+#ifndef NET_HUB_H
+#define NET_HUB_H
+
+#include "qemu-common.h"
+
+int net_init_hubport(const NetClientOptions *opts, const char *name,
+                     VLANState *vlan);
+VLANClientState *net_hub_add_port(int hub_id, const char *name);
+void net_hub_info(Monitor *mon);
+int net_hub_id_for_client(VLANClientState *nc, int *id);
+
+#endif /* NET_HUB_H */
diff --git a/qapi-schema.json b/qapi-schema.json
index bc55ed2..e4a19cf 100644
--- a/qapi-schema.json
+++ b/qapi-schema.json
@@ -2094,6 +2094,19 @@
     '*helper': 'str' } }
 
 ##
+# @NetdevHubPortOptions
+#
+# Connect two or more net clients through a software hub.
+#
+# @hubid: hub identifier number
+#
+# Since 1.2
+##
+{ 'type': 'NetdevHubPortOptions',
+  'data': {
+    'hubid':     'int32' } }
+
+##
 # @NetClientOptions
 #
 # A discriminated record of network device traits.
@@ -2102,14 +2115,15 @@
 ##
 { 'union': 'NetClientOptions',
   'data': {
-    'none':   'NetdevNoneOptions',
-    'nic':    'NetLegacyNicOptions',
-    'user':   'NetdevUserOptions',
-    'tap':    'NetdevTapOptions',
-    'socket': 'NetdevSocketOptions',
-    'vde':    'NetdevVdeOptions',
-    'dump':   'NetdevDumpOptions',
-    'bridge': 'NetdevBridgeOptions' } }
+    'none':     'NetdevNoneOptions',
+    'nic':      'NetLegacyNicOptions',
+    'user':     'NetdevUserOptions',
+    'tap':      'NetdevTapOptions',
+    'socket':   'NetdevSocketOptions',
+    'vde':      'NetdevVdeOptions',
+    'dump':     'NetdevDumpOptions',
+    'bridge':   'NetdevBridgeOptions',
+    'hubport':  'NetdevHubPortOptions' } }
 
 ##
 # @NetLegacy
commit 34309d2b12bf379814b1635850bf1ed3557337d7
Author: Corey Bryant <coreyb at linux.vnet.ibm.com>
Date:   Thu Jul 12 09:24:31 2012 -0400

    net: Add interface to bridge when SIOCBRADDIF isn't available
    
    The bridge helper uses the SIOCBRADDIF ioctl to add an inteface to
    a bridge.  SIOCBRADDIF is not available on old Linux versions.  This
    patch adds support to use the SIOCDEVPRIVATE ioctl with BRCTL_ADD_IF
    if SIOCBRADDIF is not available.
    
    Reported-by: Fabien Chouteau <chouteau at adacore.com>
    Signed-off-by: Corey Bryant <coreyb at linux.vnet.ibm.com>
    Signed-off-by: Stefan Hajnoczi <stefanha at linux.vnet.ibm.com>

diff --git a/qemu-bridge-helper.c b/qemu-bridge-helper.c
index aec5008..652eec9 100644
--- a/qemu-bridge-helper.c
+++ b/qemu-bridge-helper.c
@@ -35,6 +35,10 @@
 
 #include <linux/sockios.h>
 
+#ifndef SIOCBRADDIF
+#include <linux/if_bridge.h>
+#endif
+
 #include "qemu-queue.h"
 
 #include "net/tap-linux.h"
@@ -221,6 +225,10 @@ static int drop_privileges(void)
 int main(int argc, char **argv)
 {
     struct ifreq ifr;
+#ifndef SIOCBRADDIF
+    unsigned long ifargs[4];
+#endif
+    int ifindex;
     int fd, ctlfd, unixfd = -1;
     int use_vnet = 0;
     int mtu;
@@ -361,9 +369,19 @@ int main(int argc, char **argv)
 
     /* add the interface to the bridge */
     prep_ifreq(&ifr, bridge);
-    ifr.ifr_ifindex = if_nametoindex(iface);
-
-    if (ioctl(ctlfd, SIOCBRADDIF, &ifr) == -1) {
+    ifindex = if_nametoindex(iface);
+#ifndef SIOCBRADDIF
+    ifargs[0] = BRCTL_ADD_IF;
+    ifargs[1] = ifindex;
+    ifargs[2] = 0;
+    ifargs[3] = 0;
+    ifr.ifr_data = (void *)ifargs;
+    ret = ioctl(ctlfd, SIOCDEVPRIVATE, &ifr);
+#else
+    ifr.ifr_ifindex = ifindex;
+    ret = ioctl(ctlfd, SIOCBRADDIF, &ifr);
+#endif
+    if (ret == -1) {
         fprintf(stderr, "failed to add interface `%s' to bridge `%s': %s\n",
                 iface, bridge, strerror(errno));
         ret = EXIT_FAILURE;
commit 0b22ef0f57a8910d849602bef0940edcd0553d2c
Author: Peter Maydell <peter.maydell at linaro.org>
Date:   Wed Jul 18 15:10:27 2012 +0100

    configure: -I\$(SRC_PATH) goes in QEMU_INCLUDES not QEMU_CFLAGS
    
    If the smartcard configure check passes, add '-I\$(SRC_PATH)/libcacard'
    to QEMU_INCLUDES, not QEMU_CFLAGS. Otherwise the unexpanded SRC_PATH
    will cause a warning in every following configure test.
    
    Signed-off-by: Peter Maydell <peter.maydell at linaro.org>
    Signed-off-by: Blue Swirl <blauwirbel at gmail.com>

diff --git a/configure b/configure
index 288f1a2..027a718 100755
--- a/configure
+++ b/configure
@@ -2658,7 +2658,7 @@ if test "$smartcard" != "no" ; then
 #include <pk11pub.h>
 int main(void) { PK11_FreeSlot(0); return 0; }
 EOF
-        smartcard_cflags="-I\$(SRC_PATH)/libcacard"
+        smartcard_includes="-I\$(SRC_PATH)/libcacard"
         libcacard_libs="$($pkg_config --libs nss 2>/dev/null) $glib_libs"
         libcacard_cflags="$($pkg_config --cflags nss 2>/dev/null) $glib_cflags"
         test_cflags="$libcacard_cflags"
@@ -2672,7 +2672,8 @@ EOF
         if $pkg_config --atleast-version=3.12.8 nss >/dev/null 2>&1 && \
           compile_prog "$test_cflags" "$libcacard_libs"; then
             smartcard_nss="yes"
-            QEMU_CFLAGS="$QEMU_CFLAGS $smartcard_cflags $libcacard_cflags"
+            QEMU_CFLAGS="$QEMU_CFLAGS $libcacard_cflags"
+            QEMU_INCLUDES="$QEMU_INCLUDES $smartcard_includes"
             libs_softmmu="$libcacard_libs $libs_softmmu"
         else
             if test "$smartcard_nss" = "yes"; then
commit 3014ee001d5da6c8a6e907901def5704947d513a
Author: Peter Maydell <peter.maydell at linaro.org>
Date:   Wed Jul 18 15:10:26 2012 +0100

    configure: Fix compile warning in utimensat/futimens test
    
    Fix compile warning in the utimensat/futimens test ("implicit
    declaration of function 'utimensat'", ditto futimens) by
    adding a missing include.
    
    Signed-off-by: Peter Maydell <peter.maydell at linaro.org>
    Reviewed-by: Stefan Weil <sw at weilnetz.de>
    Signed-off-by: Blue Swirl <blauwirbel at gmail.com>

diff --git a/configure b/configure
index d19e645..288f1a2 100755
--- a/configure
+++ b/configure
@@ -2343,6 +2343,7 @@ cat > $TMPC << EOF
 #define _ATFILE_SOURCE
 #include <stddef.h>
 #include <fcntl.h>
+#include <sys/stat.h>
 
 int main(void)
 {
commit fea08e0803f9cf2fc888c5b9fc0fd9b93a2272e7
Author: Peter Maydell <peter.maydell at linaro.org>
Date:   Wed Jul 18 15:10:25 2012 +0100

    configure: Fix warnings in VDE library probe
    
    Fix compile warnings in the VDE library probe ("passing argument 1 of
    'vde_open_real' discards 'const' qualifier from pointer target type",
    ditto argument 2).
    
    Signed-off-by: Peter Maydell <peter.maydell at linaro.org>
    Signed-off-by: Blue Swirl <blauwirbel at gmail.com>

diff --git a/configure b/configure
index b29cdd3..d19e645 100755
--- a/configure
+++ b/configure
@@ -1822,7 +1822,8 @@ if test "$vde" != "no" ; then
 int main(void)
 {
     struct vde_open_args a = {0, 0, 0};
-    vde_open("", "", &a);
+    char s[] = "";
+    vde_open(s, s, &a);
     return 0;
 }
 EOF
commit 7edc3fed5e48bf59744f67d319e32e2cca0cfa8e
Author: Peter Maydell <peter.maydell at linaro.org>
Date:   Wed Jul 18 15:10:24 2012 +0100

    configure: Fix compile warning in PNG test
    
    Fix compile warning (variable 'png_ptr' set but not used) in the
    PNG detection test code.
    
    Signed-off-by: Peter Maydell <peter.maydell at linaro.org>
    Reviewed-by: Stefan Weil <sw at weilnetz.de>
    Signed-off-by: Blue Swirl <blauwirbel at gmail.com>

diff --git a/configure b/configure
index 8a8ad27..b29cdd3 100755
--- a/configure
+++ b/configure
@@ -1729,7 +1729,7 @@ cat > $TMPC <<EOF
 int main(void) {
     png_structp png_ptr;
     png_ptr = png_create_write_struct(PNG_LIBPNG_VER_STRING, NULL, NULL, NULL);
-    return 0;
+    return png_ptr != 0;
 }
 EOF
   if $pkg_config libpng --modversion >/dev/null 2>&1; then
commit 7ace252a6af1a05aa1ee3d08cf093a46f8a00ad0
Author: Stefan Weil <sw at weilnetz.de>
Date:   Wed Jul 18 15:10:23 2012 +0100

    configure: Fix errors in test for__sync_fetch_and_and
    
    The old test code raises two compiler warnings which are errors since
    commit 417c9d72d48275d19c60861896efd4962d21aca2.
    
    These errors could result in compilations with compiler flag
    -march486 (so all nice features of newer processors got lost).
    
    Signed-off-by: Stefan Weil <sw at weilnetz.de>
    Reviewed-by: Peter Maydell <peter.maydell at linaro.org>
    Signed-off-by: Blue Swirl <blauwirbel at gmail.com>

diff --git a/configure b/configure
index ab17b40..8a8ad27 100755
--- a/configure
+++ b/configure
@@ -2799,7 +2799,7 @@ fi
 # specification is necessary
 if test "$vhost_net" = "yes" && test "$cpu" = "i386"; then
   cat > $TMPC << EOF
-int sfaa(unsigned *ptr)
+static int sfaa(int *ptr)
 {
   return __sync_fetch_and_and(ptr, 0);
 }
commit caa50971f2e14b4c2c67bf2c40edd50be15679c2
Author: Peter Maydell <peter.maydell at linaro.org>
Date:   Wed Jul 18 15:10:22 2012 +0100

    configure: -march=i486 belongs in QEMU_CFLAGS, not CFLAGS
    
    The distinction between QEMU_CFLAGS and CFLAGS is that the
    former is for flags without which QEMU can't compile, whereas
    the latter is for flags like "-g -O2" which the user can
    safely override. "-march=i486" is in the former category, and
    so belongs in QEMU_CFLAGS.
    
    Signed-off-by: Peter Maydell <peter.maydell at linaro.org>
    Signed-off-by: Blue Swirl <blauwirbel at gmail.com>

diff --git a/configure b/configure
index f74bf0f..ab17b40 100755
--- a/configure
+++ b/configure
@@ -2812,7 +2812,7 @@ int main(int argc, char **argv)
 }
 EOF
   if ! compile_prog "" "" ; then
-    CFLAGS="-march=i486 $CFLAGS"
+    QEMU_CFLAGS="-march=i486 $QEMU_CFLAGS"
   fi
 fi
 
commit 1e845c78c7f1e121b3ce55bc34739f1c7aa2bf68
Author: Stefan Weil <sw at weilnetz.de>
Date:   Wed Jul 18 15:10:21 2012 +0100

    configure: Replace bash code by standard shell code
    
    "+=" does not work with dash and other simple /bin/sh implementations.
    
    The new code prepends the flag while the old code either did not work
    (it continued after an error message which typically was not read) or
    appended the flag. That difference should not matter here.
    
    Reported-by: Olaf Hering <olaf at aepfle.de>
    Signed-off-by: Stefan Weil <sw at weilnetz.de>
    Reviewed-by: Peter Maydell <peter.maydell at linaro.org>
    Signed-off-by: Blue Swirl <blauwirbel at gmail.com>

diff --git a/configure b/configure
index ec95819..f74bf0f 100755
--- a/configure
+++ b/configure
@@ -2812,7 +2812,7 @@ int main(int argc, char **argv)
 }
 EOF
   if ! compile_prog "" "" ; then
-    CFLAGS+="-march=i486"
+    CFLAGS="-march=i486 $CFLAGS"
   fi
 fi
 
commit cc9397435f725b1fc23b96c98e3642e23419a274
Author: Stefan Weil <sw at weilnetz.de>
Date:   Wed Jul 18 15:10:20 2012 +0100

    configure: Fix build with capabilities
    
    Since commit 417c9d72d48275d19c60861896efd4962d21aca2 all configure tests
    normally run with -Werror. Some of these tests now fail because they
    raised a compiler warning.
    
    This patch fixes support for capabilities.
    
    Signed-off-by: Stefan Weil <sw at weilnetz.de>
    Reviewed-by: Peter Maydell <peter.maydell at linaro.org>
    Signed-off-by: Blue Swirl <blauwirbel at gmail.com>

diff --git a/configure b/configure
index 0a2226b..ec95819 100755
--- a/configure
+++ b/configure
@@ -2085,7 +2085,7 @@ if test "$cap" != "no" ; then
   cat > $TMPC <<EOF
 #include <stdio.h>
 #include <sys/capability.h>
-int main(void) { cap_t caps; caps = cap_init(); }
+int main(void) { cap_t caps; caps = cap_init(); return caps != NULL; }
 EOF
   if compile_prog "" "-lcap" ; then
     cap=yes
commit e35bcb0cab89a039317b9ed18cffcd52032affc0
Author: Stefan Weil <sw at weilnetz.de>
Date:   Wed Jul 18 15:10:19 2012 +0100

    configure: Fix build with ALSA audio driver
    
    Since commit 417c9d72d48275d19c60861896efd4962d21aca2,
    all configure tests normally run with -Werror.
    
    Some of these tests now fail because they raised a compiler warning.
    
    Here a build breakage for ALSA (configure --audio-drv-list=alsa) is fixed.
    
    Signed-off-by: Stefan Weil <sw at weilnetz.de>
    Reviewed-by: Peter Maydell <peter.maydell at linaro.org>
    Signed-off-by: Blue Swirl <blauwirbel at gmail.com>

diff --git a/configure b/configure
index 136d9ec..0a2226b 100755
--- a/configure
+++ b/configure
@@ -1891,7 +1891,7 @@ for drv in $audio_drv_list; do
     case $drv in
     alsa)
     audio_drv_probe $drv alsa/asoundlib.h -lasound \
-        "snd_pcm_t **handle; return snd_pcm_close(*handle);"
+        "return snd_pcm_close((snd_pcm_t *)0);"
     libs_softmmu="-lasound $libs_softmmu"
     ;;
 
commit 6ca026cb376f1ac5d228c7980201b8a6c678ae67
Author: Peter Maydell <peter.maydell at linaro.org>
Date:   Wed Jul 18 15:10:18 2012 +0100

    configure: Don't run configure tests with -Werror enabled
    
    Don't run configure tests with -Werror in the compiler flags. The idea
    of -Werror is that it makes problems very obvious to developers, so
    they get fixed quickly. However, when running configure tests, failures
    due to -Werror are far from obvious -- they simply result in the test
    quietly failing when it should have passed. Not using -Werror is in
    line with recommended practice in the Autoconf world.
    
    This commit is essentially backing out the changes in commit 417c9d72.
    Instead we fix the problem that commit was trying to address in a
    different way: we add -Werror only for the test of the nss headers,
    with a comment that this is specifically intended to detect a bug
    in some releases of nss.
    
    We also have to clean up a bug in the smartcard test where it was
    trying to include smartcard_cflags in the test compile flags: this
    would always result in a failure with -Werror, because they include
    an escaped "$(SRC_PATH)" which is only valid when used in the final
    makefile.
    
    Signed-off-by: Peter Maydell <peter.maydell at linaro.org>
    Reviewed-by: Stefan Weil <sw at weilnetz.de>
    Signed-off-by: Blue Swirl <blauwirbel at gmail.com>

diff --git a/configure b/configure
index 1d713de..136d9ec 100755
--- a/configure
+++ b/configure
@@ -1158,9 +1158,10 @@ gcc_flags="-Wold-style-declaration -Wold-style-definition -Wtype-limits"
 gcc_flags="-Wformat-security -Wformat-y2k -Winit-self -Wignored-qualifiers $gcc_flags"
 gcc_flags="-Wmissing-include-dirs -Wempty-body -Wnested-externs $gcc_flags"
 gcc_flags="-fstack-protector-all -Wendif-labels $gcc_flags"
-if test "$werror" = "yes" ; then
-    gcc_flags="-Werror $gcc_flags"
-fi
+# Note that we do not add -Werror to gcc_flags here, because that would
+# enable it for all configure tests. If a configure test failed due
+# to -Werror this would just silently disable some features,
+# so it's too error prone.
 cat > $TMPC << EOF
 int main(void) { return 0; }
 EOF
@@ -2658,8 +2659,16 @@ EOF
         smartcard_cflags="-I\$(SRC_PATH)/libcacard"
         libcacard_libs="$($pkg_config --libs nss 2>/dev/null) $glib_libs"
         libcacard_cflags="$($pkg_config --cflags nss 2>/dev/null) $glib_cflags"
+        test_cflags="$libcacard_cflags"
+        # The header files in nss < 3.13.3 have a bug which causes them to
+        # emit a warning. If we're going to compile QEMU with -Werror, then
+        # test that the headers don't have this bug. Otherwise we would pass
+        # the configure test but fail to compile QEMU later.
+        if test "$werror" = "yes"; then
+            test_cflags="-Werror $test_cflags"
+        fi
         if $pkg_config --atleast-version=3.12.8 nss >/dev/null 2>&1 && \
-          compile_prog "$smartcard_cflags $libcacard_cflags" "$libcacard_libs"; then
+          compile_prog "$test_cflags" "$libcacard_libs"; then
             smartcard_nss="yes"
             QEMU_CFLAGS="$QEMU_CFLAGS $smartcard_cflags $libcacard_cflags"
             libs_softmmu="$libcacard_libs $libs_softmmu"
@@ -2936,6 +2945,11 @@ if test -z "$zero_malloc" ; then
     fi
 fi
 
+# Now we've finished running tests it's OK to add -Werror to the compiler flags
+if test "$werror" = "yes"; then
+    QEMU_CFLAGS="-Werror $QEMU_CFLAGS"
+fi
+
 if test "$solaris" = "no" ; then
     if $ld --version 2>/dev/null | grep "GNU ld" >/dev/null 2>/dev/null ; then
         LDFLAGS="-Wl,--warn-common $LDFLAGS"
commit 06d71fa1487fdef03e713b9e1aed50f7dceff27b
Author: Peter Maydell <peter.maydell at linaro.org>
Date:   Mon Jul 30 16:13:07 2012 +0100

    configure: Split valgrind test into pragma test and valgrind.h test
    
    Split the configure test that checks for valgrind into two, one
    part checking whether we have the gcc pragma to disable unused-but-set
    variables, and the other part checking for the existence of valgrind.h.
    The first of these has to be compiled with -Werror and the second
    does not and shouldn't generate any warnings.
    
    This (a) allows us to enable "make errors in configure tests be
    build failures" and (b) enables use of valgrind on systems with
    a gcc which doesn't know about -Wunused-but-set-varibale, like
    Debian squeeze.
    
    Signed-off-by: Peter Maydell <peter.maydell at linaro.org>
    Signed-off-by: Blue Swirl <blauwirbel at gmail.com>

diff --git a/configure b/configure
index c65b5f6..1d713de 100755
--- a/configure
+++ b/configure
@@ -2873,14 +2873,29 @@ if compile_prog "" "" ; then
 fi
 
 ########################################
+# check whether we can disable the -Wunused-but-set-variable
+# option with a pragma (this is needed to silence a warning in
+# some versions of the valgrind VALGRIND_STACK_DEREGISTER macro.)
+# This test has to be compiled with -Werror as otherwise an
+# unknown pragma is only a warning.
+pragma_disable_unused_but_set=no
+cat > $TMPC << EOF
+#pragma GCC diagnostic ignored "-Wunused-but-set-variable"
+int main(void) {
+    return 0;
+}
+EOF
+if compile_prog "-Werror" "" ; then
+    pragma_disable_unused_but_set=yes
+fi
+
+########################################
 # check if we have valgrind/valgrind.h
 
 valgrind_h=no
 cat > $TMPC << EOF
 #include <valgrind/valgrind.h>
-#pragma GCC diagnostic ignored "-Wunused-but-set-variable"
 int main(void) {
-  VALGRIND_STACK_DEREGISTER(0);
   return 0;
 }
 EOF
@@ -3397,6 +3412,10 @@ if test "$linux_magic_h" = "yes" ; then
   echo "CONFIG_LINUX_MAGIC_H=y" >> $config_host_mak
 fi
 
+if test "$pragma_disable_unused_but_set" = "yes" ; then
+  echo "CONFIG_PRAGMA_DISABLE_UNUSED_BUT_SET=y" >> $config_host_mak
+fi
+
 if test "$valgrind_h" = "yes" ; then
   echo "CONFIG_VALGRIND_H=y" >> $config_host_mak
 fi
diff --git a/coroutine-ucontext.c b/coroutine-ucontext.c
index e3c450b..784081a 100644
--- a/coroutine-ucontext.c
+++ b/coroutine-ucontext.c
@@ -200,14 +200,18 @@ Coroutine *qemu_coroutine_new(void)
 }
 
 #ifdef CONFIG_VALGRIND_H
+#ifdef CONFIG_PRAGMA_DISABLE_UNUSED_BUT_SET
 /* Work around an unused variable in the valgrind.h macro... */
 #pragma GCC diagnostic ignored "-Wunused-but-set-variable"
+#endif
 static inline void valgrind_stack_deregister(CoroutineUContext *co)
 {
     VALGRIND_STACK_DEREGISTER(co->valgrind_stack_id);
 }
+#ifdef CONFIG_PRAGMA_DISABLE_UNUSED_BUT_SET
 #pragma GCC diagnostic error "-Wunused-but-set-variable"
 #endif
+#endif
 
 void qemu_coroutine_delete(Coroutine *co_)
 {
commit 4cdc0789ec17ce1ce48506cae62035310e932a2e
Author: Aneesh Kumar K.V <aneesh.kumar at linux.vnet.ibm.com>
Date:   Tue Jul 31 12:53:18 2012 +0530

    hw/9pfs: Fix assert when disabling migration
    
    For 9p we can get the attach request multiple times for the
    same export. So don't adding migration blocker for every
    attach request.
    
    Signed-off-by: Aneesh Kumar K.V <aneesh.kumar at linux.vnet.ibm.com>

diff --git a/hw/9pfs/virtio-9p.c b/hw/9pfs/virtio-9p.c
index f4a7026..4b52540 100644
--- a/hw/9pfs/virtio-9p.c
+++ b/hw/9pfs/virtio-9p.c
@@ -983,11 +983,16 @@ static void v9fs_attach(void *opaque)
     err += offset;
     trace_v9fs_attach_return(pdu->tag, pdu->id,
                              qid.type, qid.version, qid.path);
-    s->root_fid = fid;
-    /* disable migration */
-    error_set(&s->migration_blocker, QERR_VIRTFS_FEATURE_BLOCKS_MIGRATION,
-              s->ctx.fs_root ? s->ctx.fs_root : "NULL", s->tag);
-    migrate_add_blocker(s->migration_blocker);
+    /*
+     * disable migration if we haven't done already.
+     * attach could get called multiple times for the same export.
+     */
+    if (!s->migration_blocker) {
+        s->root_fid = fid;
+        error_set(&s->migration_blocker, QERR_VIRTFS_FEATURE_BLOCKS_MIGRATION,
+                  s->ctx.fs_root ? s->ctx.fs_root : "NULL", s->tag);
+        migrate_add_blocker(s->migration_blocker);
+    }
 out:
     put_fid(pdu, fidp);
 out_nofid:
commit b7d28d25fd1344d4a260d5e9a250fa9bdb519ac6
Author: Stefan Weil <sw at weilnetz.de>
Date:   Wed Jul 18 15:10:20 2012 +0100

    configure: Fix build with capabilities
    
    Since commit 417c9d72d48275d19c60861896efd4962d21aca2 all configure tests
    normally run with -Werror. Some of these tests now fail because they
    raised a compiler warning.
    
    This patch fixes support for capabilities.
    
    Signed-off-by: Stefan Weil <sw at weilnetz.de>
    Reviewed-by: Peter Maydell <peter.maydell at linaro.org>
    Signed-off-by: Aneesh Kumar K.V <aneesh.kumar at linux.vnet.ibm.com>

diff --git a/configure b/configure
index c65b5f6..309aeac 100755
--- a/configure
+++ b/configure
@@ -2084,7 +2084,7 @@ if test "$cap" != "no" ; then
   cat > $TMPC <<EOF
 #include <stdio.h>
 #include <sys/capability.h>
-int main(void) { cap_t caps; caps = cap_init(); }
+int main(void) { cap_t caps; caps = cap_init(); return caps != NULL; }
 EOF
   if compile_prog "" "-lcap" ; then
     cap=yes
commit 5e3bc7144edd6e4fa2824944e5eb16c28197dd5a
Merge: 4dd533a... 5e59b02...
Author: Anthony Liguori <aliguori at us.ibm.com>
Date:   Mon Jul 30 10:00:48 2012 -0500

    Merge remote-tracking branch 'mst/tags/for_anthony' into staging
    
    * mst/tags/for_anthony:
      msi/msix: added API to set MSI message address and data
      pci: Add INTx routing notifier
      pci: Add pci_device_route_intx_to_irq
      pci: Unregister BARs before device exit
      pci: convert PCIUnregisterFunc to void
      msix: Switch msix_uninit to return void
      msix: Allow full specification of MSIX layout
      msix: Split PBA into it's own MemoryRegion
      msix: Note endian TODO item
      msix: Move msix_mmio_read
      virtio: Convert to msix_init_exclusive_bar() interface
      ivshmem: Convert to msix_init_exclusive_bar() interface
      msix: Add simple BAR allocation MSIX setup functions
      msix: fix PCIDevice naming inconsistency
      msix: drop unused msix_bar_size, require valid bar_size

commit 4dd533aa03d6844f61e95558d75d8dbec72d899c
Merge: d4a06f4... 39a5235...
Author: Anthony Liguori <aliguori at us.ibm.com>
Date:   Mon Jul 30 09:59:38 2012 -0500

    Merge remote-tracking branch 'bonzini/nbd-next' into staging
    
    * bonzini/nbd-next:
      qemu-nbd: add --cache and --aio options
      qemu-nbd: reorganize help message

commit d4a06f466ac476fedc927c8355c6a3e0a1c6ca42
Merge: e6a7671... 4c205d0...
Author: Anthony Liguori <aliguori at us.ibm.com>
Date:   Mon Jul 30 09:59:23 2012 -0500

    Merge remote-tracking branch 'bonzini/scsi-next' into staging
    
    * bonzini/scsi-next: (32 commits)
      virtio-scsi: enable MSI-X support
      virtio-scsi: add ioeventfd support
      virtio-scsi: report parameter change events
      virtio-scsi: do not report dropped events after reset
      virtio-scsi: Report missed events
      virtio-scsi: Implement hotplug support for virtio-scsi
      scsi: report parameter changes to HBA drivers
      scsi-disk: report resized disk via sense codes
      scsi: establish precedence levels for unit attention
      scsi: introduce hotplug() and hot_unplug() interfaces for SCSI bus
      scsi: add tracepoint for scsi_req_cancel
      scsi-disk: removable hard disks support load/eject
      scsi-disk: Fail medium writes with proper sense for readonly LUNs
      scsi-disk: improve the lba-out-of-range tests for read/write/verify
      scsi-disk: rd/wr/vr-protect !=0 is an error
      scsi-disk: support toggling the write cache
      scsi-disk: parse MODE SELECT commands and parameters
      scsi-disk: fix changeable values for MODE_PAGE_R_W_ERROR
      scsi-disk: adjust offsets in MODE SENSE by 2
      scsi-disk: support emulated TO_DEV requests
      ...

commit e6a76719987e5fcd63da552f7cf32d837b0a5cea
Merge: 7162ab2... 6c779f2...
Author: Anthony Liguori <aliguori at us.ibm.com>
Date:   Mon Jul 30 09:58:41 2012 -0500

    Merge commit 'quintela/migration-next-v5' into staging
    
    * commit '6c779f22a93cc6e4565b940ef616e3efc5b50ba5':
      Change ram_save_block to return -1 if there are no more changes
      ram: save_live_setup() we don't need to synchronize the dirty bitmap.
      ram: iterate phase
      ram: save_live_complete() only do one loop
      ram: save_live_setup() don't need to sent pages
      savevm: split save_live into stage2 and stage3
      savevm: split save_live_setup from save_live_state
      savevm: introduce is_active method
      savevm: Refactor cancel operation in its own operation
      savevm: remove SaveLiveStateHandler
      savevm: remove SaveSetParamsHandler
      savevm: Live migration handlers register the struct directly
      savevm: Use a struct to pass all handlers

commit 5e59b024351f827f903f98ae522687ea53dc4f23
Merge: 7162ab2... 932d4a4...
Author: Michael S. Tsirkin <mst at redhat.com>
Date:   Sun Jul 29 17:03:19 2012 +0300

    Merge branch pci into master
    
    Merge master and pci branch, resolve build breakage in hw/esp.c
    introduced by f90c2bcd.
    
    Conflicts:
    	hw/esp.c

diff --cc hw/esp.c
index c6422ad,8d73e56..a011347
--- a/hw/esp.c
+++ b/hw/esp.c
@@@ -811,378 -763,17 +811,376 @@@ static void sysbus_esp_class_init(Objec
      DeviceClass *dc = DEVICE_CLASS(klass);
      SysBusDeviceClass *k = SYS_BUS_DEVICE_CLASS(klass);
  
 -    k->init = esp_init1;
 -    dc->reset = esp_hard_reset;
 -    dc->vmsd = &vmstate_esp;
 -    dc->props = esp_properties;
 +    k->init = sysbus_esp_init;
 +    dc->reset = sysbus_esp_hard_reset;
 +    dc->vmsd = &vmstate_sysbus_esp_scsi;
  }
  
 -static TypeInfo esp_info = {
 +static TypeInfo sysbus_esp_info = {
      .name          = "esp",
      .parent        = TYPE_SYS_BUS_DEVICE,
 -    .instance_size = sizeof(ESPState),
 -    .class_init    = esp_class_init,
 +    .instance_size = sizeof(SysBusESPState),
 +    .class_init    = sysbus_esp_class_init,
 +};
 +
 +#define DMA_CMD   0x0
 +#define DMA_STC   0x1
 +#define DMA_SPA   0x2
 +#define DMA_WBC   0x3
 +#define DMA_WAC   0x4
 +#define DMA_STAT  0x5
 +#define DMA_SMDLA 0x6
 +#define DMA_WMAC  0x7
 +
 +#define DMA_CMD_MASK   0x03
 +#define DMA_CMD_DIAG   0x04
 +#define DMA_CMD_MDL    0x10
 +#define DMA_CMD_INTE_P 0x20
 +#define DMA_CMD_INTE_D 0x40
 +#define DMA_CMD_DIR    0x80
 +
 +#define DMA_STAT_PWDN    0x01
 +#define DMA_STAT_ERROR   0x02
 +#define DMA_STAT_ABORT   0x04
 +#define DMA_STAT_DONE    0x08
 +#define DMA_STAT_SCSIINT 0x10
 +#define DMA_STAT_BCMBLT  0x20
 +
 +#define SBAC_STATUS 0x1000
 +
 +typedef struct PCIESPState {
 +    PCIDevice dev;
 +    MemoryRegion io;
 +    uint32_t dma_regs[8];
 +    uint32_t sbac;
 +    ESPState esp;
 +} PCIESPState;
 +
 +static void esp_pci_handle_idle(PCIESPState *pci, uint32_t val)
 +{
 +    trace_esp_pci_dma_idle(val);
 +    esp_dma_enable(&pci->esp, 0, 0);
 +}
 +
 +static void esp_pci_handle_blast(PCIESPState *pci, uint32_t val)
 +{
 +    trace_esp_pci_dma_blast(val);
 +    qemu_log_mask(LOG_UNIMP, "am53c974: cmd BLAST not implemented\n");
 +}
 +
 +static void esp_pci_handle_abort(PCIESPState *pci, uint32_t val)
 +{
 +    trace_esp_pci_dma_abort(val);
 +    if (pci->esp.current_req) {
 +        scsi_req_cancel(pci->esp.current_req);
 +    }
 +}
 +
 +static void esp_pci_handle_start(PCIESPState *pci, uint32_t val)
 +{
 +    trace_esp_pci_dma_start(val);
 +
 +    pci->dma_regs[DMA_WBC] = pci->dma_regs[DMA_STC];
 +    pci->dma_regs[DMA_WAC] = pci->dma_regs[DMA_SPA];
 +    pci->dma_regs[DMA_WMAC] = pci->dma_regs[DMA_SMDLA];
 +
 +    pci->dma_regs[DMA_STAT] &= ~(DMA_STAT_BCMBLT | DMA_STAT_SCSIINT
 +                               | DMA_STAT_DONE | DMA_STAT_ABORT
 +                               | DMA_STAT_ERROR | DMA_STAT_PWDN);
 +
 +    esp_dma_enable(&pci->esp, 0, 1);
 +}
 +
 +static void esp_pci_dma_write(PCIESPState *pci, uint32_t saddr, uint32_t val)
 +{
 +    trace_esp_pci_dma_write(saddr, pci->dma_regs[saddr], val);
 +    switch (saddr) {
 +    case DMA_CMD:
 +        pci->dma_regs[saddr] = val;
 +        switch (val & DMA_CMD_MASK) {
 +        case 0x0: /* IDLE */
 +            esp_pci_handle_idle(pci, val);
 +            break;
 +        case 0x1: /* BLAST */
 +            esp_pci_handle_blast(pci, val);
 +            break;
 +        case 0x2: /* ABORT */
 +            esp_pci_handle_abort(pci, val);
 +            break;
 +        case 0x3: /* START */
 +            esp_pci_handle_start(pci, val);
 +            break;
 +        default: /* can't happen */
 +            abort();
 +        }
 +        break;
 +    case DMA_STC:
 +    case DMA_SPA:
 +    case DMA_SMDLA:
 +        pci->dma_regs[saddr] = val;
 +        break;
 +    case DMA_STAT:
 +        if (!(pci->sbac & SBAC_STATUS)) {
 +            /* clear some bits on write */
 +            uint32_t mask = DMA_STAT_ERROR | DMA_STAT_ABORT | DMA_STAT_DONE;
 +            pci->dma_regs[DMA_STAT] &= ~(val & mask);
 +        }
 +        break;
 +    default:
 +        trace_esp_pci_error_invalid_write_dma(val, saddr);
 +        return;
 +    }
 +}
 +
 +static uint32_t esp_pci_dma_read(PCIESPState *pci, uint32_t saddr)
 +{
 +    uint32_t val;
 +
 +    val = pci->dma_regs[saddr];
 +    if (saddr == DMA_STAT) {
 +        if (pci->esp.rregs[ESP_RSTAT] & STAT_INT) {
 +            val |= DMA_STAT_SCSIINT;
 +        }
 +        if (pci->sbac & SBAC_STATUS) {
 +            pci->dma_regs[DMA_STAT] &= ~(DMA_STAT_ERROR | DMA_STAT_ABORT |
 +                                         DMA_STAT_DONE);
 +        }
 +    }
 +
 +    trace_esp_pci_dma_read(saddr, val);
 +    return val;
 +}
 +
 +static void esp_pci_io_write(void *opaque, target_phys_addr_t addr,
 +                             uint64_t val, unsigned int size)
 +{
 +    PCIESPState *pci = opaque;
 +
 +    if (size < 4 || addr & 3) {
 +        /* need to upgrade request: we only support 4-bytes accesses */
 +        uint32_t current = 0, mask;
 +        int shift;
 +
 +        if (addr < 0x40) {
 +            current = pci->esp.wregs[addr >> 2];
 +        } else if (addr < 0x60) {
 +            current = pci->dma_regs[(addr - 0x40) >> 2];
 +        } else if (addr < 0x74) {
 +            current = pci->sbac;
 +        }
 +
 +        shift = (4 - size) * 8;
 +        mask = (~(uint32_t)0 << shift) >> shift;
 +
 +        shift = ((4 - (addr & 3)) & 3) * 8;
 +        val <<= shift;
 +        val |= current & ~(mask << shift);
 +        addr &= ~3;
 +        size = 4;
 +    }
 +
 +    if (addr < 0x40) {
 +        /* SCSI core reg */
 +        esp_reg_write(&pci->esp, addr >> 2, val);
 +    } else if (addr < 0x60) {
 +        /* PCI DMA CCB */
 +        esp_pci_dma_write(pci, (addr - 0x40) >> 2, val);
 +    } else if (addr == 0x70) {
 +        /* DMA SCSI Bus and control */
 +        trace_esp_pci_sbac_write(pci->sbac, val);
 +        pci->sbac = val;
 +    } else {
 +        trace_esp_pci_error_invalid_write((int)addr);
 +    }
 +}
 +
 +static uint64_t esp_pci_io_read(void *opaque, target_phys_addr_t addr,
 +                                unsigned int size)
 +{
 +    PCIESPState *pci = opaque;
 +    uint32_t ret;
 +
 +    if (addr < 0x40) {
 +        /* SCSI core reg */
 +        ret = esp_reg_read(&pci->esp, addr >> 2);
 +    } else if (addr < 0x60) {
 +        /* PCI DMA CCB */
 +        ret = esp_pci_dma_read(pci, (addr - 0x40) >> 2);
 +    } else if (addr == 0x70) {
 +        /* DMA SCSI Bus and control */
 +        trace_esp_pci_sbac_read(pci->sbac);
 +        ret = pci->sbac;
 +    } else {
 +        /* Invalid region */
 +        trace_esp_pci_error_invalid_read((int)addr);
 +        ret = 0;
 +    }
 +
 +    /* give only requested data */
 +    ret >>= (addr & 3) * 8;
 +    ret &= ~(~(uint64_t)0 << (8 * size));
 +
 +    return ret;
 +}
 +
 +static void esp_pci_dma_memory_rw(PCIESPState *pci, uint8_t *buf, int len,
 +                                  DMADirection dir)
 +{
 +    dma_addr_t addr;
 +    DMADirection expected_dir;
 +
 +    if (pci->dma_regs[DMA_CMD] & DMA_CMD_DIR) {
 +        expected_dir = DMA_DIRECTION_FROM_DEVICE;
 +    } else {
 +        expected_dir = DMA_DIRECTION_TO_DEVICE;
 +    }
 +
 +    if (dir != expected_dir) {
 +        trace_esp_pci_error_invalid_dma_direction();
 +        return;
 +    }
 +
 +    if (pci->dma_regs[DMA_STAT] & DMA_CMD_MDL) {
 +        qemu_log_mask(LOG_UNIMP, "am53c974: MDL transfer not implemented\n");
 +    }
 +
 +    addr = pci->dma_regs[DMA_SPA];
 +    if (pci->dma_regs[DMA_WBC] < len) {
 +        len = pci->dma_regs[DMA_WBC];
 +    }
 +
 +    pci_dma_rw(&pci->dev, addr, buf, len, dir);
 +
 +    /* update status registers */
 +    pci->dma_regs[DMA_WBC] -= len;
 +    pci->dma_regs[DMA_WAC] += len;
 +}
 +
 +static void esp_pci_dma_memory_read(void *opaque, uint8_t *buf, int len)
 +{
 +    PCIESPState *pci = opaque;
 +    esp_pci_dma_memory_rw(pci, buf, len, DMA_DIRECTION_TO_DEVICE);
 +}
 +
 +static void esp_pci_dma_memory_write(void *opaque, uint8_t *buf, int len)
 +{
 +    PCIESPState *pci = opaque;
 +    esp_pci_dma_memory_rw(pci, buf, len, DMA_DIRECTION_FROM_DEVICE);
 +}
 +
 +static const MemoryRegionOps esp_pci_io_ops = {
 +    .read = esp_pci_io_read,
 +    .write = esp_pci_io_write,
 +    .endianness = DEVICE_LITTLE_ENDIAN,
 +    .impl = {
 +        .min_access_size = 1,
 +        .max_access_size = 4,
 +    },
 +};
 +
 +static void esp_pci_hard_reset(DeviceState *dev)
 +{
 +    PCIESPState *pci = DO_UPCAST(PCIESPState, dev.qdev, dev);
 +    esp_hard_reset(&pci->esp);
 +    pci->dma_regs[DMA_CMD] &= ~(DMA_CMD_DIR | DMA_CMD_INTE_D | DMA_CMD_INTE_P
 +                              | DMA_CMD_MDL | DMA_CMD_DIAG | DMA_CMD_MASK);
 +    pci->dma_regs[DMA_WBC] &= ~0xffff;
 +    pci->dma_regs[DMA_WAC] = 0xffffffff;
 +    pci->dma_regs[DMA_STAT] &= ~(DMA_STAT_BCMBLT | DMA_STAT_SCSIINT
 +                               | DMA_STAT_DONE | DMA_STAT_ABORT
 +                               | DMA_STAT_ERROR);
 +    pci->dma_regs[DMA_WMAC] = 0xfffffffd;
 +}
 +
 +static const VMStateDescription vmstate_esp_pci_scsi = {
 +    .name = "pciespscsi",
 +    .version_id = 0,
 +    .minimum_version_id = 0,
 +    .minimum_version_id_old = 0,
 +    .fields = (VMStateField[]) {
 +        VMSTATE_PCI_DEVICE(dev, PCIESPState),
 +        VMSTATE_BUFFER_UNSAFE(dma_regs, PCIESPState, 0, 8 * sizeof(uint32_t)),
 +        VMSTATE_STRUCT(esp, PCIESPState, 0, vmstate_esp, ESPState),
 +        VMSTATE_END_OF_LIST()
 +    }
 +};
 +
 +static void esp_pci_command_complete(SCSIRequest *req, uint32_t status,
 +                                     size_t resid)
 +{
 +    ESPState *s = req->hba_private;
 +    PCIESPState *pci = container_of(s, PCIESPState, esp);
 +
 +    esp_command_complete(req, status, resid);
 +    pci->dma_regs[DMA_WBC] = 0;
 +    pci->dma_regs[DMA_STAT] |= DMA_STAT_DONE;
 +}
 +
 +static const struct SCSIBusInfo esp_pci_scsi_info = {
 +    .tcq = false,
 +    .max_target = ESP_MAX_DEVS,
 +    .max_lun = 7,
 +
 +    .transfer_data = esp_transfer_data,
 +    .complete = esp_pci_command_complete,
 +    .cancel = esp_request_cancelled,
 +};
 +
 +static int esp_pci_scsi_init(PCIDevice *dev)
 +{
 +    PCIESPState *pci = DO_UPCAST(PCIESPState, dev, dev);
 +    ESPState *s = &pci->esp;
 +    uint8_t *pci_conf;
 +
 +    pci_conf = pci->dev.config;
 +
 +    /* Interrupt pin A */
 +    pci_conf[PCI_INTERRUPT_PIN] = 0x01;
 +
 +    s->dma_memory_read = esp_pci_dma_memory_read;
 +    s->dma_memory_write = esp_pci_dma_memory_write;
 +    s->dma_opaque = pci;
 +    s->chip_id = TCHI_AM53C974;
 +    memory_region_init_io(&pci->io, &esp_pci_io_ops, pci, "esp-io", 0x80);
 +
 +    pci_register_bar(&pci->dev, 0, PCI_BASE_ADDRESS_SPACE_IO, &pci->io);
 +    s->irq = pci->dev.irq[0];
 +
 +    scsi_bus_new(&s->bus, &dev->qdev, &esp_pci_scsi_info);
 +    if (!dev->qdev.hotplugged) {
 +        return scsi_bus_legacy_handle_cmdline(&s->bus);
 +    }
 +    return 0;
 +}
 +
- static int esp_pci_scsi_uninit(PCIDevice *d)
++static void esp_pci_scsi_uninit(PCIDevice *d)
 +{
 +    PCIESPState *pci = DO_UPCAST(PCIESPState, dev, d);
 +
 +    memory_region_destroy(&pci->io);
- 
-     return 0;
 +}
 +
 +static void esp_pci_class_init(ObjectClass *klass, void *data)
 +{
 +    DeviceClass *dc = DEVICE_CLASS(klass);
 +    PCIDeviceClass *k = PCI_DEVICE_CLASS(klass);
 +
 +    k->init = esp_pci_scsi_init;
 +    k->exit = esp_pci_scsi_uninit;
 +    k->vendor_id = PCI_VENDOR_ID_AMD;
 +    k->device_id = PCI_DEVICE_ID_AMD_SCSI;
 +    k->revision = 0x10;
 +    k->class_id = PCI_CLASS_STORAGE_SCSI;
 +    dc->desc = "AMD Am53c974 PCscsi-PCI SCSI adapter";
 +    dc->reset = esp_pci_hard_reset;
 +    dc->vmsd = &vmstate_esp_pci_scsi;
 +}
 +
 +static TypeInfo esp_pci_info = {
 +    .name = "am53c974",
 +    .parent = TYPE_PCI_DEVICE,
 +    .instance_size = sizeof(PCIESPState),
 +    .class_init = esp_pci_class_init,
  };
  
  static void esp_register_types(void)
commit 7162ab21fe8e82f924002951cd8e87f69358f8b5
Author: Vitaly Chipounov <vitaly.chipounov at epfl.ch>
Date:   Tue Jul 3 00:20:49 2012 +0200

    x86: Fixed incorrect segment base address addition in 64-bits mode
    
    According to the Intel manual
    "Intel® 64 and IA-32 Architectures Software Developer’s Manual
    Volume 3", "3.4.4 Segment Loading Instructions in IA-32e Mode":
    
    "When in compatibility mode, FS and GS overrides operate as defined by
    32-bit mode behavior regardless of the value loaded into the upper 32
    linear-address bits of the hidden descriptor register base field.
    Compatibility mode ignores the upper 32 bits when calculating an effective address."
    
    However, the code misses the 64-bit mode case, where an instruction with
    address and segment size override would be translated incorrectly. For example,
    inc dword ptr gs:260h[ebx*4] gets incorrectly translated to:
    
    (uint32_t)(gs.base + ebx * 4 + 0x260)
    instead of
    gs.base + (uint32_t)(ebx * 4 + 0x260)
    
    Signed-off-by: Vitaly Chipounov <vitaly.chipounov at epfl.ch>
    Reviewed-by: Max Filippov <jcmvbkbc at gmail.com>
    Signed-off-by: Blue Swirl <blauwirbel at gmail.com>

diff --git a/target-i386/translate.c b/target-i386/translate.c
index 1988dae..2b11333 100644
--- a/target-i386/translate.c
+++ b/target-i386/translate.c
@@ -459,12 +459,19 @@ static inline void gen_op_movl_A0_seg(int reg)
     tcg_gen_ld32u_tl(cpu_A0, cpu_env, offsetof(CPUX86State, segs[reg].base) + REG_L_OFFSET);
 }
 
-static inline void gen_op_addl_A0_seg(int reg)
+static inline void gen_op_addl_A0_seg(DisasContext *s, int reg)
 {
     tcg_gen_ld_tl(cpu_tmp0, cpu_env, offsetof(CPUX86State, segs[reg].base));
-    tcg_gen_add_tl(cpu_A0, cpu_A0, cpu_tmp0);
 #ifdef TARGET_X86_64
-    tcg_gen_andi_tl(cpu_A0, cpu_A0, 0xffffffff);
+    if (CODE64(s)) {
+        tcg_gen_andi_tl(cpu_A0, cpu_A0, 0xffffffff);
+        tcg_gen_add_tl(cpu_A0, cpu_A0, cpu_tmp0);
+    } else {
+        tcg_gen_add_tl(cpu_A0, cpu_A0, cpu_tmp0);
+        tcg_gen_andi_tl(cpu_A0, cpu_A0, 0xffffffff);
+    }
+#else
+    tcg_gen_add_tl(cpu_A0, cpu_A0, cpu_tmp0);
 #endif
 }
 
@@ -620,7 +627,7 @@ static inline void gen_string_movl_A0_ESI(DisasContext *s)
             override = R_DS;
         gen_op_movl_A0_reg(R_ESI);
         gen_op_andl_A0_ffff();
-        gen_op_addl_A0_seg(override);
+        gen_op_addl_A0_seg(s, override);
     }
 }
 
@@ -641,7 +648,7 @@ static inline void gen_string_movl_A0_EDI(DisasContext *s)
     } else {
         gen_op_movl_A0_reg(R_EDI);
         gen_op_andl_A0_ffff();
-        gen_op_addl_A0_seg(R_ES);
+        gen_op_addl_A0_seg(s, R_ES);
     }
 }
 
@@ -2066,7 +2073,7 @@ static void gen_lea_modrm(DisasContext *s, int modrm, int *reg_ptr, int *offset_
             } else
 #endif
             {
-                gen_op_addl_A0_seg(override);
+                gen_op_addl_A0_seg(s, override);
             }
         }
     } else {
@@ -2133,7 +2140,7 @@ static void gen_lea_modrm(DisasContext *s, int modrm, int *reg_ptr, int *offset_
                 else
                     override = R_DS;
             }
-            gen_op_addl_A0_seg(override);
+            gen_op_addl_A0_seg(s, override);
         }
     }
 
@@ -2210,7 +2217,7 @@ static void gen_add_A0_ds_seg(DisasContext *s)
         } else
 #endif
         {
-            gen_op_addl_A0_seg(override);
+            gen_op_addl_A0_seg(s, override);
         }
     }
 }
@@ -2463,12 +2470,12 @@ static void gen_push_T0(DisasContext *s)
         if (s->ss32) {
             if (s->addseg) {
                 tcg_gen_mov_tl(cpu_T[1], cpu_A0);
-                gen_op_addl_A0_seg(R_SS);
+                gen_op_addl_A0_seg(s, R_SS);
             }
         } else {
             gen_op_andl_A0_ffff();
             tcg_gen_mov_tl(cpu_T[1], cpu_A0);
-            gen_op_addl_A0_seg(R_SS);
+            gen_op_addl_A0_seg(s, R_SS);
         }
         gen_op_st_T0_A0(s->dflag + 1 + s->mem_index);
         if (s->ss32 && !s->addseg)
@@ -2503,11 +2510,11 @@ static void gen_push_T1(DisasContext *s)
             gen_op_addl_A0_im(-4);
         if (s->ss32) {
             if (s->addseg) {
-                gen_op_addl_A0_seg(R_SS);
+                gen_op_addl_A0_seg(s, R_SS);
             }
         } else {
             gen_op_andl_A0_ffff();
-            gen_op_addl_A0_seg(R_SS);
+            gen_op_addl_A0_seg(s, R_SS);
         }
         gen_op_st_T1_A0(s->dflag + 1 + s->mem_index);
 
@@ -2531,10 +2538,10 @@ static void gen_pop_T0(DisasContext *s)
         gen_op_movl_A0_reg(R_ESP);
         if (s->ss32) {
             if (s->addseg)
-                gen_op_addl_A0_seg(R_SS);
+                gen_op_addl_A0_seg(s, R_SS);
         } else {
             gen_op_andl_A0_ffff();
-            gen_op_addl_A0_seg(R_SS);
+            gen_op_addl_A0_seg(s, R_SS);
         }
         gen_op_ld_T0_A0(s->dflag + 1 + s->mem_index);
     }
@@ -2559,7 +2566,7 @@ static void gen_stack_A0(DisasContext *s)
         gen_op_andl_A0_ffff();
     tcg_gen_mov_tl(cpu_T[1], cpu_A0);
     if (s->addseg)
-        gen_op_addl_A0_seg(R_SS);
+        gen_op_addl_A0_seg(s, R_SS);
 }
 
 /* NOTE: wrap around in 16 bit not fully handled */
@@ -2572,7 +2579,7 @@ static void gen_pusha(DisasContext *s)
         gen_op_andl_A0_ffff();
     tcg_gen_mov_tl(cpu_T[1], cpu_A0);
     if (s->addseg)
-        gen_op_addl_A0_seg(R_SS);
+        gen_op_addl_A0_seg(s, R_SS);
     for(i = 0;i < 8; i++) {
         gen_op_mov_TN_reg(OT_LONG, 0, 7 - i);
         gen_op_st_T0_A0(OT_WORD + s->dflag + s->mem_index);
@@ -2591,7 +2598,7 @@ static void gen_popa(DisasContext *s)
     tcg_gen_mov_tl(cpu_T[1], cpu_A0);
     tcg_gen_addi_tl(cpu_T[1], cpu_T[1], 16 <<  s->dflag);
     if (s->addseg)
-        gen_op_addl_A0_seg(R_SS);
+        gen_op_addl_A0_seg(s, R_SS);
     for(i = 0;i < 8; i++) {
         /* ESP is not reloaded */
         if (i != 3) {
@@ -2641,7 +2648,7 @@ static void gen_enter(DisasContext *s, int esp_addend, int level)
             gen_op_andl_A0_ffff();
         tcg_gen_mov_tl(cpu_T[1], cpu_A0);
         if (s->addseg)
-            gen_op_addl_A0_seg(R_SS);
+            gen_op_addl_A0_seg(s, R_SS);
         /* push bp */
         gen_op_mov_TN_reg(OT_LONG, 0, R_EBP);
         gen_op_st_T0_A0(ot + s->mem_index);
commit e6d91ab66bad2bce9319fe8b0011f765042a7bb2
Author: Paolo Bonzini <pbonzini at redhat.com>
Date:   Mon Jul 9 11:08:39 2012 +0200

    place qemu-sockets.c contributions since 2012-01-13 under GPLv2+
    
    Past contributions since 2012-01-13 were only made by Red Hat people,
    so they are already available under GPLv2+.
    
    Signed-off-by: Paolo Bonzini <pbonzini at redhat.com>
    Reviewed-by: Stefan Weil <sw at weilnetz.de>
    Signed-off-by: Blue Swirl <blauwirbel at gmail.com>

diff --git a/qemu-sockets.c b/qemu-sockets.c
index 2ae715d..668fa93 100644
--- a/qemu-sockets.c
+++ b/qemu-sockets.c
@@ -11,6 +11,9 @@
  *  but WITHOUT ANY WARRANTY; without even the implied warranty of
  *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
  *  GNU General Public License for more details.
+ *
+ * Contributions after 2012-01-13 are licensed under the terms of the
+ * GNU GPL, version 2 or (at your option) any later version.
  */
 #include <stdio.h>
 #include <stdlib.h>
commit 54c2e50205711a4dc5134d07079174e3e8be10a7
Author: Dunrong Huang <riegamaths at gmail.com>
Date:   Sun Jul 29 03:11:24 2012 +0800

    build: Fix linking failure for qemu-ga
    
    This patch will fix the following linking failed:
    
      LINK  qemu-ga
    gcc: error: qga/../qapi-generated/qga-qapi-types.o: No such file or directory
    gcc: error: qga/../qapi-generated/qga-qapi-visit.o: No such file or directory
    gcc: error: qga/../qapi-generated/qga-qmp-marshal.o: No such file or directory
    make: *** [qemu-ga] Error 1
    
    Commit cdc976b040f2760103ce2fb49f4d504093a7163f changes the
    dependencies of qemu-ga to depend "../qapi-generated/qga-qapi-types.o",
    which will be expanded to "qga/../qapi-generated/qga-qapi-types.o" when
    building qemu-ga.
    
    In top-level Makefile, we defined a target "qapi-generated/qga-qapi-types.o"
    which was not equal to "qga/../qapi-generated/qga-qapi-types" in the
    Makefile world. So "No such file" error happened when qemu-ga was linking.
    
    The easy approach to fix is to change the target name to
    "qga/../qapi-generated/qga-qapi-types.o", but it is weird.
    
    So, in order to solve it more graciously, I move those temporary
    files(qga-qapi-*.{c,h}) qemu-ga depends on to qemu-ga/qapi-generated,
    this makes dependencies more clearer.
    
    Signed-off-by: Dunrong Huang <riegamaths at gmail.com>
    Signed-off-by: Blue Swirl <blauwirbel at gmail.com>

diff --git a/Makefile b/Makefile
index a1195ff..621cb86 100644
--- a/Makefile
+++ b/Makefile
@@ -173,7 +173,7 @@ qemu-img-cmds.h: $(SRC_PATH)/qemu-img-cmds.hx
 	$(call quiet-command,sh $(SRC_PATH)/scripts/hxtool -h < $< > $@,"  GEN   $@")
 
 qemu-ga$(EXESUF): LIBS = $(LIBS_QGA)
-qemu-ga$(EXESUF): QEMU_CFLAGS += -I qapi-generated
+qemu-ga$(EXESUF): QEMU_CFLAGS += -I qga/qapi-generated
 
 gen-out-type = $(subst .,-,$(suffix $@))
 
@@ -181,15 +181,15 @@ ifneq ($(wildcard config-host.mak),)
 include $(SRC_PATH)/tests/Makefile
 endif
 
-qapi-generated/qga-qapi-types.c qapi-generated/qga-qapi-types.h :\
+qga/qapi-generated/qga-qapi-types.c qga/qapi-generated/qga-qapi-types.h :\
 $(SRC_PATH)/qapi-schema-guest.json $(SRC_PATH)/scripts/qapi-types.py
-	$(call quiet-command,$(PYTHON) $(SRC_PATH)/scripts/qapi-types.py $(gen-out-type) -o qapi-generated -p "qga-" < $<, "  GEN   $@")
-qapi-generated/qga-qapi-visit.c qapi-generated/qga-qapi-visit.h :\
+	$(call quiet-command,$(PYTHON) $(SRC_PATH)/scripts/qapi-types.py $(gen-out-type) -o qga/qapi-generated -p "qga-" < $<, "  GEN   $@")
+qga/qapi-generated/qga-qapi-visit.c qga/qapi-generated/qga-qapi-visit.h :\
 $(SRC_PATH)/qapi-schema-guest.json $(SRC_PATH)/scripts/qapi-visit.py
-	$(call quiet-command,$(PYTHON) $(SRC_PATH)/scripts/qapi-visit.py $(gen-out-type) -o qapi-generated -p "qga-" < $<, "  GEN   $@")
-qapi-generated/qga-qmp-commands.h qapi-generated/qga-qmp-marshal.c :\
+	$(call quiet-command,$(PYTHON) $(SRC_PATH)/scripts/qapi-visit.py $(gen-out-type) -o qga/qapi-generated -p "qga-" < $<, "  GEN   $@")
+qga/qapi-generated/qga-qmp-commands.h qga/qapi-generated/qga-qmp-marshal.c :\
 $(SRC_PATH)/qapi-schema-guest.json $(SRC_PATH)/scripts/qapi-commands.py
-	$(call quiet-command,$(PYTHON) $(SRC_PATH)/scripts/qapi-commands.py $(gen-out-type) -o qapi-generated -p "qga-" < $<, "  GEN   $@")
+	$(call quiet-command,$(PYTHON) $(SRC_PATH)/scripts/qapi-commands.py $(gen-out-type) -o qga/qapi-generated -p "qga-" < $<, "  GEN   $@")
 
 qapi-types.c qapi-types.h :\
 $(SRC_PATH)/qapi-schema.json $(SRC_PATH)/scripts/qapi-types.py
@@ -201,9 +201,7 @@ qmp-commands.h qmp-marshal.c :\
 $(SRC_PATH)/qapi-schema.json $(SRC_PATH)/scripts/qapi-commands.py
 	$(call quiet-command,$(PYTHON) $(SRC_PATH)/scripts/qapi-commands.py $(gen-out-type) -m -o "." < $<, "  GEN   $@")
 
-QGALIB_OBJ=$(addprefix qapi-generated/, qga-qapi-types.o qga-qapi-visit.o qga-qmp-marshal.o)
-QGALIB_GEN=$(addprefix qapi-generated/, qga-qapi-types.h qga-qapi-visit.h qga-qmp-commands.h)
-$(QGALIB_OBJ): $(QGALIB_GEN)
+QGALIB_GEN=$(addprefix qga/qapi-generated/, qga-qapi-types.h qga-qapi-visit.h qga-qmp-commands.h)
 $(qga-obj-y) qemu-ga.o: $(QGALIB_GEN)
 
 qemu-ga$(EXESUF): qemu-ga.o $(qga-obj-y) $(tools-obj-y) $(qapi-obj-y) $(qobject-obj-y) $(version-obj-y)
@@ -227,6 +225,7 @@ clean:
 	rm -f $(foreach f,$(GENERATED_HEADERS),$(f) $(f)-timestamp)
 	rm -f $(foreach f,$(GENERATED_SOURCES),$(f) $(f)-timestamp)
 	rm -rf qapi-generated
+	rm -rf qga/qapi-generated
 	$(MAKE) -C tests/tcg clean
 	for d in $(ALL_SUBDIRS) $(QEMULIBS) libcacard; do \
 	if test -d $$d; then $(MAKE) -C $$d $@ || exit 1; fi; \
diff --git a/qga/Makefile.objs b/qga/Makefile.objs
index b54b9b1..cd3e135 100644
--- a/qga/Makefile.objs
+++ b/qga/Makefile.objs
@@ -1,5 +1,5 @@
 qga-obj-y = commands.o guest-agent-command-state.o
 qga-obj-$(CONFIG_POSIX) += commands-posix.o channel-posix.o
 qga-obj-$(CONFIG_WIN32) += commands-win32.o channel-win32.o service-win32.o
-qga-obj-y += ../qapi-generated/qga-qapi-types.o ../qapi-generated/qga-qapi-visit.o
-qga-obj-y += ../qapi-generated/qga-qmp-marshal.o
+qga-obj-y += qapi-generated/qga-qapi-types.o qapi-generated/qga-qapi-visit.o
+qga-obj-y += qapi-generated/qga-qmp-marshal.o
commit b595c14a7bd3d4d47a44d064d7efbaaf45b4321b
Author: Blue Swirl <blauwirbel at gmail.com>
Date:   Sun Jul 8 07:00:50 2012 +0000

    Avoid redefining inline
    
    System headers (e.g. gutils.h) may define 'inline', #undefine it
    before #defining.
    
    Signed-off-by: Blue Swirl <blauwirbel at gmail.com>

diff --git a/osdep.h b/osdep.h
index 3ea4af0..1e15a4b 100644
--- a/osdep.h
+++ b/osdep.h
@@ -70,10 +70,12 @@ typedef signed int              int_fast16_t;
 #ifndef always_inline
 #if !((__GNUC__ < 3) || defined(__APPLE__))
 #ifdef __OPTIMIZE__
+#undef inline
 #define inline __attribute__ (( always_inline )) __inline__
 #endif
 #endif
 #else
+#undef inline
 #define inline always_inline
 #endif
 
commit 0ed8b6f67f26acc2e88dfc6be4954e63f943bd28
Author: Blue Swirl <blauwirbel at gmail.com>
Date:   Sun Jul 8 06:56:53 2012 +0000

    Avoid returning void
    
    It's silly and non-conforming to standards to return void,
    don't do it.
    
    Signed-off-by: Blue Swirl <blauwirbel at gmail.com>

diff --git a/block.c b/block.c
index ce7eb8f..b38940b 100644
--- a/block.c
+++ b/block.c
@@ -2609,7 +2609,7 @@ void bdrv_debug_event(BlockDriverState *bs, BlkDebugEvent event)
         return;
     }
 
-    return drv->bdrv_debug_event(bs, event);
+    drv->bdrv_debug_event(bs, event);
 
 }
 
diff --git a/dma.h b/dma.h
index acacf1b..f35c4b6 100644
--- a/dma.h
+++ b/dma.h
@@ -196,9 +196,9 @@ static inline void dma_memory_unmap(DMAContext *dma,
                                     DMADirection dir, dma_addr_t access_len)
 {
     if (!dma_has_iommu(dma)) {
-        return cpu_physical_memory_unmap(buffer, (target_phys_addr_t)len,
-                                         dir == DMA_DIRECTION_FROM_DEVICE,
-                                         access_len);
+        cpu_physical_memory_unmap(buffer, (target_phys_addr_t)len,
+                                  dir == DMA_DIRECTION_FROM_DEVICE,
+                                  access_len);
     } else {
         iommu_dma_memory_unmap(dma, buffer, len, dir, access_len);
     }
diff --git a/hw/bt-l2cap.c b/hw/bt-l2cap.c
index 2ccba60..cb43ee7 100644
--- a/hw/bt-l2cap.c
+++ b/hw/bt-l2cap.c
@@ -1000,7 +1000,8 @@ static void l2cap_iframe_in(struct l2cap_chan_s *ch, uint16_t cid,
             /* TODO: Signal an error? */
             return;
         }
-        return l2cap_sframe_in(ch, le16_to_cpup((void *) hdr->data));
+        l2cap_sframe_in(ch, le16_to_cpup((void *) hdr->data));
+        return;
     }
 
     switch (hdr->data[1] >> 6) {	/* SAR */
@@ -1010,7 +1011,8 @@ static void l2cap_iframe_in(struct l2cap_chan_s *ch, uint16_t cid,
         if (len - 4 > ch->mps)
             goto len_error;
 
-        return ch->params.sdu_in(ch->params.opaque, hdr->data + 2, len - 4);
+        ch->params.sdu_in(ch->params.opaque, hdr->data + 2, len - 4);
+        break;
 
     case L2CAP_SAR_START:
         if (ch->len_total || len < 6)
@@ -1033,7 +1035,8 @@ static void l2cap_iframe_in(struct l2cap_chan_s *ch, uint16_t cid,
             goto len_error;
 
         memcpy(ch->sdu + ch->len_cur, hdr->data + 2, len - 4);
-        return ch->params.sdu_in(ch->params.opaque, ch->sdu, ch->len_total);
+        ch->params.sdu_in(ch->params.opaque, ch->sdu, ch->len_total);
+        break;
 
     case L2CAP_SAR_CONT:
         if (!ch->len_total || ch->len_cur + len - 4 >= ch->len_total)
@@ -1136,7 +1139,7 @@ static void l2cap_bframe_submit(struct bt_l2cap_conn_params_s *parms)
 {
     struct l2cap_chan_s *chan = (struct l2cap_chan_s *) parms;
 
-    return l2cap_pdu_submit(chan->l2cap);
+    l2cap_pdu_submit(chan->l2cap);
 }
 
 #if 0
diff --git a/hw/eepro100.c b/hw/eepro100.c
index f343685..e083e0e 100644
--- a/hw/eepro100.c
+++ b/hw/eepro100.c
@@ -1596,10 +1596,17 @@ static void eepro100_write(void *opaque, target_phys_addr_t addr,
     EEPRO100State *s = opaque;
 
     switch (size) {
-    case 1: return eepro100_write1(s, addr, data);
-    case 2: return eepro100_write2(s, addr, data);
-    case 4: return eepro100_write4(s, addr, data);
-    default: abort();
+    case 1:
+        eepro100_write1(s, addr, data);
+        break;
+    case 2:
+        eepro100_write2(s, addr, data);
+        break;
+    case 4:
+        eepro100_write4(s, addr, data);
+        break;
+    default:
+        abort();
     }
 }
 
diff --git a/hw/ide/cmd646.c b/hw/ide/cmd646.c
index bf8ece4..087b4f9 100644
--- a/hw/ide/cmd646.c
+++ b/hw/ide/cmd646.c
@@ -94,12 +94,12 @@ static void cmd646_data_write(void *opaque, target_phys_addr_t addr,
     CMD646BAR *cmd646bar = opaque;
 
     if (size == 1) {
-        return ide_ioport_write(cmd646bar->bus, addr, data);
+        ide_ioport_write(cmd646bar->bus, addr, data);
     } else if (addr == 0) {
         if (size == 2) {
-            return ide_data_writew(cmd646bar->bus, addr, data);
+            ide_data_writew(cmd646bar->bus, addr, data);
         } else {
-            return ide_data_writel(cmd646bar->bus, addr, data);
+            ide_data_writel(cmd646bar->bus, addr, data);
         }
     }
 }
diff --git a/hw/ide/piix.c b/hw/ide/piix.c
index f5a74c2..6652761 100644
--- a/hw/ide/piix.c
+++ b/hw/ide/piix.c
@@ -73,7 +73,8 @@ static void bmdma_write(void *opaque, target_phys_addr_t addr,
 #endif
     switch(addr & 3) {
     case 0:
-        return bmdma_cmd_writeb(bm, val);
+        bmdma_cmd_writeb(bm, val);
+        break;
     case 2:
         bm->status = (val & 0x60) | (bm->status & 1) | (bm->status & ~val & 0x06);
         break;
diff --git a/hw/ide/via.c b/hw/ide/via.c
index eec5136..a17f2e2 100644
--- a/hw/ide/via.c
+++ b/hw/ide/via.c
@@ -74,7 +74,8 @@ static void bmdma_write(void *opaque, target_phys_addr_t addr,
 #endif
     switch (addr & 3) {
     case 0:
-        return bmdma_cmd_writeb(bm, val);
+        bmdma_cmd_writeb(bm, val);
+        break;
     case 2:
         bm->status = (val & 0x60) | (bm->status & 1) | (bm->status & ~val & 0x06);
         break;
diff --git a/hw/lan9118.c b/hw/lan9118.c
index 40fb765..61f1c0e 100644
--- a/hw/lan9118.c
+++ b/hw/lan9118.c
@@ -1166,9 +1166,11 @@ static void lan9118_16bit_mode_write(void *opaque, target_phys_addr_t offset,
 {
     switch (size) {
     case 2:
-        return lan9118_writew(opaque, offset, (uint32_t)val);
+        lan9118_writew(opaque, offset, (uint32_t)val);
+        return;
     case 4:
-        return lan9118_writel(opaque, offset, val, size);
+        lan9118_writel(opaque, offset, val, size);
+        return;
     }
 
     hw_error("lan9118_write: Bad size 0x%x\n", size);
diff --git a/hw/ne2000.c b/hw/ne2000.c
index 760ed29..ae561e6 100644
--- a/hw/ne2000.c
+++ b/hw/ne2000.c
@@ -677,15 +677,15 @@ static void ne2000_write(void *opaque, target_phys_addr_t addr,
     NE2000State *s = opaque;
 
     if (addr < 0x10 && size == 1) {
-        return ne2000_ioport_write(s, addr, data);
+        ne2000_ioport_write(s, addr, data);
     } else if (addr == 0x10) {
         if (size <= 2) {
-            return ne2000_asic_ioport_write(s, addr, data);
+            ne2000_asic_ioport_write(s, addr, data);
         } else {
-            return ne2000_asic_ioport_writel(s, addr, data);
+            ne2000_asic_ioport_writel(s, addr, data);
         }
     } else if (addr == 0x1f && size == 1) {
-        return ne2000_reset_ioport_write(s, addr, data);
+        ne2000_reset_ioport_write(s, addr, data);
     }
 }
 
diff --git a/hw/vmware_vga.c b/hw/vmware_vga.c
index 476dc89..f5e4f44 100644
--- a/hw/vmware_vga.c
+++ b/hw/vmware_vga.c
@@ -1150,11 +1150,14 @@ static void vmsvga_io_write(void *opaque, target_phys_addr_t addr,
 
     switch (addr) {
     case SVGA_IO_MUL * SVGA_INDEX_PORT:
-        return vmsvga_index_write(s, addr, data);
+        vmsvga_index_write(s, addr, data);
+        break;
     case SVGA_IO_MUL * SVGA_VALUE_PORT:
-        return vmsvga_value_write(s, addr, data);
+        vmsvga_value_write(s, addr, data);
+        break;
     case SVGA_IO_MUL * SVGA_BIOS_PORT:
-        return vmsvga_bios_write(s, addr, data);
+        vmsvga_bios_write(s, addr, data);
+        break;
     }
 }
 
diff --git a/ui/vnc-auth-vencrypt.c b/ui/vnc-auth-vencrypt.c
index 674ba97..c59b188 100644
--- a/ui/vnc-auth-vencrypt.c
+++ b/ui/vnc-auth-vencrypt.c
@@ -47,7 +47,8 @@ static void start_auth_vencrypt_subauth(VncState *vs)
     case VNC_AUTH_VENCRYPT_TLSSASL:
     case VNC_AUTH_VENCRYPT_X509SASL:
       VNC_DEBUG("Start TLS auth SASL\n");
-      return start_auth_sasl(vs);
+      start_auth_sasl(vs);
+      break;
 #endif /* CONFIG_VNC_SASL */
 
     default: /* Should not be possible, but just in case */
diff --git a/ui/vnc.c b/ui/vnc.c
index cf1cae2..cfc61a7 100644
--- a/ui/vnc.c
+++ b/ui/vnc.c
@@ -3089,5 +3089,5 @@ void vnc_display_add_client(DisplayState *ds, int csock, int skipauth)
 {
     VncDisplay *vs = ds ? (VncDisplay *)ds->opaque : vnc_display;
 
-    return vnc_connect(vs, csock, skipauth);
+    vnc_connect(vs, csock, skipauth);
 }
commit 16fd921bd3a266d321071739cf40785abce4bcb1
Author: Peter Maydell <peter.maydell at linaro.org>
Date:   Tue Jul 24 15:10:27 2012 +0100

    hw/escc: Drop duplicate definition of 'disabled' property
    
    Drop a duplicate definition of the 'disabled' property from
    the escc qdev property list: this redefinition is currently
    effectively ignored but will become an error. (The duplication
    was inadvertently introduced in 2009 in commit ec02f7dec2.)
    
    Signed-off-by: Peter Maydell <peter.maydell at linaro.org>
    Acked-by: Andreas Färber <afaerber at suse.de>
    Signed-off-by: Blue Swirl <blauwirbel at gmail.com>

diff --git a/hw/escc.c b/hw/escc.c
index 4d8a8e8..e1f5e73 100644
--- a/hw/escc.c
+++ b/hw/escc.c
@@ -905,7 +905,6 @@ static Property escc_properties[] = {
     DEFINE_PROP_UINT32("frequency", SerialState, frequency,   0),
     DEFINE_PROP_UINT32("it_shift",  SerialState, it_shift,    0),
     DEFINE_PROP_UINT32("disabled",  SerialState, disabled,    0),
-    DEFINE_PROP_UINT32("disabled",  SerialState, disabled,    0),
     DEFINE_PROP_UINT32("chnBtype",  SerialState, chn[0].type, 0),
     DEFINE_PROP_UINT32("chnAtype",  SerialState, chn[1].type, 0),
     DEFINE_PROP_CHR("chrB", SerialState, chn[0].chr),
commit 1435ddb89c303c38ff23ff977dfb81953f32eb96
Author: Paolo Bonzini <pbonzini at redhat.com>
Date:   Wed Jul 11 16:40:21 2012 +0200

    build: get dependency file directories from object file names
    
    After commit dcff25f2cd8c11a9368cc2369aeb0319c32d9e26, Dependency file
    are taken from the directories that have a Makefile.objs file.  This is
    not enough, since files can be included from other directories.
    So, pick them from directories that have an object file in them.
    
    Signed-off-by: Paolo Bonzini <pbonzini at redhat.com>
    Signed-off-by: Blue Swirl <blauwirbel at gmail.com>

diff --git a/Makefile b/Makefile
index a200503..a1195ff 100644
--- a/Makefile
+++ b/Makefile
@@ -403,5 +403,5 @@ qemu-doc.dvi qemu-doc.html qemu-doc.info qemu-doc.pdf: \
 Makefile: $(GENERATED_HEADERS)
 
 # Include automatically generated dependency files
-# All subdir dependencies come automatically from our recursive subdir rules
--include $(wildcard *.d)
+# Dependencies in Makefile.objs files come from our recursive subdir rules
+-include $(wildcard *.d tests/*.d)
diff --git a/Makefile.dis b/Makefile.dis
index 09060f0..2cfec6a 100644
--- a/Makefile.dis
+++ b/Makefile.dis
@@ -18,6 +18,3 @@ all: $(libdis-y)
 
 clean:
 	rm -f *.o *.d *.a *~
-
-# Include automatically generated dependency files
--include $(wildcard *.d)
diff --git a/Makefile.hw b/Makefile.hw
index 28fe100..59f5b48 100644
--- a/Makefile.hw
+++ b/Makefile.hw
@@ -21,6 +21,3 @@ all: $(hw-obj-y)
 clean:
 	rm -f $(addsuffix *.o, $(sort $(dir $(hw-obj-y))))
 	rm -f $(addsuffix *.d, $(sort $(dir $(hw-obj-y))))
-
-# Include automatically generated dependency files
--include $(patsubst %.o, %.d, $(hw-obj-y))
diff --git a/Makefile.target b/Makefile.target
index 74f7a4a..7892a8d 100644
--- a/Makefile.target
+++ b/Makefile.target
@@ -214,6 +214,3 @@ endif
 
 GENERATED_HEADERS += config-target.h
 Makefile: $(GENERATED_HEADERS)
-
-# Include automatically generated dependency files
--include $(wildcard *.d fpu/*.d tcg/*.d)
diff --git a/Makefile.user b/Makefile.user
index 1783b2a..9302d33 100644
--- a/Makefile.user
+++ b/Makefile.user
@@ -22,6 +22,3 @@ clean:
 	for d in . trace; do \
 	rm -f $$d/*.o $$d/*.d $$d/*.a $$d/*~; \
 	done
-
-# Include automatically generated dependency files
--include $(wildcard *.d)
diff --git a/rules.mak b/rules.mak
index 60f3e96..a284946 100644
--- a/rules.mak
+++ b/rules.mak
@@ -94,7 +94,6 @@ define unnest-dir
 $(foreach var,$(nested-vars),$(call push-var,$(var),$1/))
 $(eval obj := $(obj)/$1)
 $(eval include $(SRC_PATH)/$1/Makefile.objs)
-$(eval -include $(wildcard $1/*.d))
 $(eval obj := $(patsubst %/$1,%,$(obj)))
 $(foreach var,$(nested-vars),$(call pop-var,$(var),$1/))
 endef
@@ -113,4 +112,6 @@ define unnest-vars
 $(call unnest-vars-1)
 $(foreach var,$(nested-vars),$(eval $(var) := $(filter-out %/, $($(var)))))
 $(shell mkdir -p $(sort $(foreach var,$(nested-vars),$(dir $($(var))))))
+$(foreach var,$(nested-vars), $(eval \
+  -include $(addsuffix *.d, $(sort $(dir $($(var)))))))
 endef
commit cdc976b040f2760103ce2fb49f4d504093a7163f
Author: Paolo Bonzini <pbonzini at redhat.com>
Date:   Wed Jul 11 16:40:20 2012 +0200

    build: include qapi-generated/ files in qga/Makefile.objs
    
    No reason to leave them out, and it will ensure that the dependencies
    are picked up.  Later we can perhaps move the files to another
    directory to avoid ../ usage.
    
    Signed-off-by: Paolo Bonzini <pbonzini at redhat.com>
    Reviewed-by: Michael Roth <mdroth at linux.vnet.ibm.com>
    Signed-off-by: Blue Swirl <blauwirbel at gmail.com>

diff --git a/Makefile b/Makefile
index ab82ef3..a200503 100644
--- a/Makefile
+++ b/Makefile
@@ -206,7 +206,7 @@ QGALIB_GEN=$(addprefix qapi-generated/, qga-qapi-types.h qga-qapi-visit.h qga-qm
 $(QGALIB_OBJ): $(QGALIB_GEN)
 $(qga-obj-y) qemu-ga.o: $(QGALIB_GEN)
 
-qemu-ga$(EXESUF): qemu-ga.o $(qga-obj-y) $(tools-obj-y) $(qapi-obj-y) $(qobject-obj-y) $(version-obj-y) $(QGALIB_OBJ)
+qemu-ga$(EXESUF): qemu-ga.o $(qga-obj-y) $(tools-obj-y) $(qapi-obj-y) $(qobject-obj-y) $(version-obj-y)
 
 QEMULIBS=libhw32 libhw64 libuser libdis libdis-user
 
diff --git a/qga/Makefile.objs b/qga/Makefile.objs
index 6a4d843..b54b9b1 100644
--- a/qga/Makefile.objs
+++ b/qga/Makefile.objs
@@ -1,3 +1,5 @@
 qga-obj-y = commands.o guest-agent-command-state.o
 qga-obj-$(CONFIG_POSIX) += commands-posix.o channel-posix.o
 qga-obj-$(CONFIG_WIN32) += commands-win32.o channel-win32.o service-win32.o
+qga-obj-y += ../qapi-generated/qga-qapi-types.o ../qapi-generated/qga-qapi-visit.o
+qga-obj-y += ../qapi-generated/qga-qmp-marshal.o
commit 14117c7ba1f2b70a167cb8e4546ee5ec24af3cc9
Author: Eduardo Habkost <ehabkost at redhat.com>
Date:   Wed Jul 18 14:22:27 2012 -0300

    tests: Makefile: include dependency files
    
    Otherwise 'make check' won't recompile files that need to be recompiled
    because of header changes.
    
    To reproduce the bug, run:
    
     $ make check  # succeeds
     $ echo B0RKED > hw/mc146818rtc_regs.h
     $ make check  # is supposed to try to rebuild tests/rtc-test.o and fail
    
    Signed-off-by: Eduardo Habkost <ehabkost at redhat.com>
    Acked-by: Paolo Bonzini <pbonzini at redhat.com>
    Signed-off-by: Blue Swirl <blauwirbel at gmail.com>

diff --git a/tests/Makefile b/tests/Makefile
index 9675ba7..f3f4159 100644
--- a/tests/Makefile
+++ b/tests/Makefile
@@ -147,3 +147,5 @@ check-qtest: $(patsubst %,check-qtest-%, $(QTEST_TARGETS))
 check-unit: $(patsubst %,check-%, $(check-unit-y))
 check-block: $(patsubst %,check-%, $(check-block-y))
 check: check-unit check-qtest
+
+-include $(wildcard tests/*.d)
commit 52d06136bd534d3984fc33497334fd7d808ef2bd
Author: Peter Maydell <peter.maydell at linaro.org>
Date:   Mon Jul 9 04:28:30 2012 +0000

    vl.c: Don't print errno after failed qemu_chr_new()
    
    The qemu_chr_new() function doesn't set errno on failure, so
    don't print strerror(errno) on the error handling path when
    dealing with the -serial, -parallel and -virtioconsole arguments.
    This avoids nonsensical error messages like:
      $ ./arm-softmmu/qemu-system-arm -serial wombat
      qemu: could not open serial device 'wombat': Success
    
    We also rephrase the message slightly to make it a little clearer
    that we're expecting the name of a QEMU chr backend rather than
    a host or guest serial/parallel/etc device.
    
    Reported-by: Christian Müller <christian.mueller at heig-vd.ch>
    Signed-off-by: Peter Maydell <peter.maydell at linaro.org>
    Signed-off-by: Blue Swirl <blauwirbel at gmail.com>

diff --git a/vl.c b/vl.c
index 8904db1..c18bb80 100644
--- a/vl.c
+++ b/vl.c
@@ -1984,8 +1984,8 @@ static int serial_parse(const char *devname)
     snprintf(label, sizeof(label), "serial%d", index);
     serial_hds[index] = qemu_chr_new(label, devname, NULL);
     if (!serial_hds[index]) {
-        fprintf(stderr, "qemu: could not open serial device '%s': %s\n",
-                devname, strerror(errno));
+        fprintf(stderr, "qemu: could not connect serial device"
+                " to character backend '%s'\n", devname);
         return -1;
     }
     index++;
@@ -2006,8 +2006,8 @@ static int parallel_parse(const char *devname)
     snprintf(label, sizeof(label), "parallel%d", index);
     parallel_hds[index] = qemu_chr_new(label, devname, NULL);
     if (!parallel_hds[index]) {
-        fprintf(stderr, "qemu: could not open parallel device '%s': %s\n",
-                devname, strerror(errno));
+        fprintf(stderr, "qemu: could not connect parallel device"
+                " to character backend '%s'\n", devname);
         return -1;
     }
     index++;
@@ -2041,8 +2041,8 @@ static int virtcon_parse(const char *devname)
     snprintf(label, sizeof(label), "virtcon%d", index);
     virtcon_hds[index] = qemu_chr_new(label, devname, NULL);
     if (!virtcon_hds[index]) {
-        fprintf(stderr, "qemu: could not open virtio console '%s': %s\n",
-                devname, strerror(errno));
+        fprintf(stderr, "qemu: could not connect virtio console"
+                " to character backend '%s'\n", devname);
         return -1;
     }
     qemu_opt_set(dev_opts, "chardev", label);
commit 7ff7563fc1c3c57914aafec1753219604346fe18
Author: Max Filippov <jcmvbkbc at gmail.com>
Date:   Tue Jul 17 23:45:23 2012 +0400

    target-xtensa: fix big-endian BBS/BBC implementation
    
    Quote from ISA, 2.1:
    
    For most Xtensa instructions, bit numbering is irrelevant; only the BBC
    and BBS instructions assign bit numbers to values on which the processor
    operates. The BBC/BBS instructions use big-endian bit ordering (0 is the
    most-significant bit) on a big-endian processor configuration.
    
    Signed-off-by: Max Filippov <jcmvbkbc at gmail.com>
    Signed-off-by: Blue Swirl <blauwirbel at gmail.com>

diff --git a/target-xtensa/translate.c b/target-xtensa/translate.c
index b883e6b..1900bd5 100644
--- a/target-xtensa/translate.c
+++ b/target-xtensa/translate.c
@@ -2366,10 +2366,18 @@ static void disas_xtensa_insn(DisasContext *dc)
             case 5: /*BBC*/ /*BBS*/
                 gen_window_check2(dc, RRI8_S, RRI8_T);
                 {
-                    TCGv_i32 bit = tcg_const_i32(1);
+#ifdef TARGET_WORDS_BIGENDIAN
+                    TCGv_i32 bit = tcg_const_i32(0x80000000);
+#else
+                    TCGv_i32 bit = tcg_const_i32(0x00000001);
+#endif
                     TCGv_i32 tmp = tcg_temp_new_i32();
                     tcg_gen_andi_i32(tmp, cpu_R[RRI8_T], 0x1f);
+#ifdef TARGET_WORDS_BIGENDIAN
+                    tcg_gen_shr_i32(bit, bit, tmp);
+#else
                     tcg_gen_shl_i32(bit, bit, tmp);
+#endif
                     tcg_gen_and_i32(tmp, cpu_R[RRI8_S], bit);
                     gen_brcondi(dc, eq_ne, tmp, 0, 4 + RRI8_IMM8_SE);
                     tcg_temp_free(tmp);
@@ -2383,7 +2391,11 @@ static void disas_xtensa_insn(DisasContext *dc)
                 {
                     TCGv_i32 tmp = tcg_temp_new_i32();
                     tcg_gen_andi_i32(tmp, cpu_R[RRI8_S],
-                            1 << (((RRI8_R & 1) << 4) | RRI8_T));
+#ifdef TARGET_WORDS_BIGENDIAN
+                            0x80000000 >> (((RRI8_R & 1) << 4) | RRI8_T));
+#else
+                            0x00000001 << (((RRI8_R & 1) << 4) | RRI8_T));
+#endif
                     gen_brcondi(dc, eq_ne, tmp, 0, 4 + RRI8_IMM8_SE);
                     tcg_temp_free(tmp);
                 }
commit d901eff3e6da96d34be33b307aa6cea75098c180
Author: Jia Liu <proljc at gmail.com>
Date:   Fri Jul 20 15:50:53 2012 +0800

    target-or32: Add testcases
    
    Add testcases for OpenRISC.
    
    Signed-off-by: Jia Liu <proljc at gmail.com>
    Signed-off-by: Blue Swirl <blauwirbel at gmail.com>

diff --git a/tests/tcg/openrisc/Makefile b/tests/tcg/openrisc/Makefile
new file mode 100644
index 0000000..7e65888
--- /dev/null
+++ b/tests/tcg/openrisc/Makefile
@@ -0,0 +1,71 @@
+-include ../../config-host.mak
+
+CROSS = or32-linux-
+
+SIM = qemu-or32
+
+CC = $(CROSS)gcc
+
+TESTCASES = test_add.tst
+TESTCASES += test_sub.tst
+TESTCASES += test_addc.tst
+TESTCASES += test_addi.tst
+TESTCASES += test_addic.tst
+TESTCASES += test_and_or.tst
+TESTCASES += test_bf.tst
+TESTCASES += test_bnf.tst
+TESTCASES += test_div.tst
+TESTCASES += test_divu.tst
+TESTCASES += test_extx.tst
+TESTCASES += test_fx.tst
+TESTCASES += test_jal.tst
+TESTCASES += test_j.tst
+TESTCASES += test_lf_div.tst
+TESTCASES += test_lf_eqs.tst
+TESTCASES += test_lf_ges.tst
+TESTCASES += test_lf_gts.tst
+TESTCASES += test_lf_les.tst
+TESTCASES += test_lf_lts.tst
+TESTCASES += test_lf_mul.tst
+TESTCASES += test_lf_nes.tst
+TESTCASES += test_lf_rem.tst
+TESTCASES += test_lf_sub.tst
+TESTCASES += test_lf_add.tst
+TESTCASES += test_logic.tst
+TESTCASES += test_lx.tst
+TESTCASES += test_movhi.tst
+TESTCASES += test_mul.tst
+TESTCASES += test_mulu.tst
+TESTCASES += test_muli.tst
+TESTCASES += test_sfeq.tst
+TESTCASES += test_sfeqi.tst
+TESTCASES += test_sfges.tst
+TESTCASES += test_sfgesi.tst
+TESTCASES += test_sfgeu.tst
+TESTCASES += test_sfgeui.tst
+TESTCASES += test_sfgts.tst
+TESTCASES += test_sfgtsi.tst
+TESTCASES += test_sfgtu.tst
+TESTCASES += test_sfgtui.tst
+TESTCASES += test_sfles.tst
+TESTCASES += test_sflesi.tst
+TESTCASES += test_sfleu.tst
+TESTCASES += test_sfleui.tst
+TESTCASES += test_sflts.tst
+TESTCASES += test_sfltsi.tst
+TESTCASES += test_sfltu.tst
+TESTCASES += test_sfltui.tst
+TESTCASES += test_sfne.tst
+TESTCASES += test_sfnei.tst
+
+all: $(TESTCASES)
+
+%.tst: %.c
+	$(CC) -static $< -o $@
+
+
+check: $(TESTCASES)
+	@for case in $(TESTCASES); do $(SIM) $$case; echo $$case pass!; sleep 0.2; done
+
+clean:
+	$(RM) -rf $(TESTCASES)
diff --git a/tests/tcg/openrisc/test_add.c b/tests/tcg/openrisc/test_add.c
new file mode 100644
index 0000000..3d23592
--- /dev/null
+++ b/tests/tcg/openrisc/test_add.c
@@ -0,0 +1,43 @@
+#include <stdio.h>
+
+int main(void)
+{
+    int a, b, d;
+    int result;
+
+    a = 0x100;
+    b = 0x100;
+    result = 0x200;
+    __asm
+    ("l.add %0, %0, %1\n\t"
+     : "+r"(a)
+     : "r"(b)
+    );
+    if (a != result) {
+        printf("add error\n");
+        return -1;
+    }
+
+    a = 0xffff;
+    b = 0x1;
+    result = 0x10000;
+    __asm
+    ("l.add %0, %0, %1\n\t"
+     : "+r"(a)
+     : "r"(b)
+    );
+    if (a != result) {
+        printf("add error\n");
+        return -1;
+    }
+
+    a = 0x7fffffff;
+    b = 0x1;
+    __asm
+    ("l.add %0, %1, %2\n\t"
+     : "=r"(d)
+     : "r"(b), "r"(a)
+    );
+
+    return 0;
+}
diff --git a/tests/tcg/openrisc/test_addc.c b/tests/tcg/openrisc/test_addc.c
new file mode 100644
index 0000000..05d18f8
--- /dev/null
+++ b/tests/tcg/openrisc/test_addc.c
@@ -0,0 +1,38 @@
+#include <stdio.h>
+
+int main(void)
+{
+    int a, b, c;
+    int result;
+
+    b = 0x01;
+    c = 0xffffffff;
+    result = 1;
+    __asm
+    ("l.addc   %0, %1, %2\n\t"
+     : "=r"(a)
+     : "r"(b), "r"(c)
+    );
+    if (a != result) {
+        printf("first addc error\n");
+        return -1;
+    }
+
+    b = 0x01;
+    c = 0xffffffff;
+    result = 0x80000001;
+    __asm
+    ("l.addc   %0, %1, %2\n\t"
+     "l.movhi  %2, 0x7fff\n\t"
+     "l.ori    %2, %2, 0xffff\n\t"
+     "l.addc   %0, %1, %2\n\t"
+     : "=r"(a)
+     : "r"(b), "r"(c)
+    );
+    if (a != result) {
+        printf("addc error\n");
+        return -1;
+    }
+
+    return 0;
+}
diff --git a/tests/tcg/openrisc/test_addi.c b/tests/tcg/openrisc/test_addi.c
new file mode 100644
index 0000000..bbf5a5f
--- /dev/null
+++ b/tests/tcg/openrisc/test_addi.c
@@ -0,0 +1,33 @@
+#include <stdio.h>
+
+int main(void)
+{
+    int a, b;
+    int result;
+
+    b = 0x01;
+    result = 0x00;
+    __asm
+    ("l.addi  %0, %1, 0xffff\n\t"
+     : "=r"(a)
+     : "r"(b)
+    );
+    if (a != result) {
+        printf("addi error\n\t");
+        return -1;
+    }
+
+    b = 0x010000;
+    result = 0xffff;
+    __asm
+    ("l.addi  %0, %1, 0xffff\n\t"
+     : "=r"(a)
+     : "r"(b)
+    );
+    if (a != result) {
+        printf("addi error\n");
+        return -1;
+    }
+
+    return 0;
+}
diff --git a/tests/tcg/openrisc/test_addic.c b/tests/tcg/openrisc/test_addic.c
new file mode 100644
index 0000000..4ba7432
--- /dev/null
+++ b/tests/tcg/openrisc/test_addic.c
@@ -0,0 +1,33 @@
+#include <stdio.h>
+
+int main(void)
+{
+    int a, b, c;
+    int result;
+
+    a = 1;
+    result = 0x1;
+    __asm
+    ("l.addic %0, %0, 0xffff\n\t"
+     : "+r"(a)
+    );
+    if (a != result) {
+        printf("first addic error\n");
+        return -1;
+   }
+
+    a = 0x1;
+    result = 0x201;
+    __asm
+    ("l.addic %0, %0, 0xffff\n\t"
+     "l.ori   %0, r0, 0x100\n\t"
+     "l.addic %0, %0, 0x100\n\t"
+     : "+r"(a)
+    );
+    if (a != result) {
+        printf("second addic error\n");
+        return -1;
+    }
+
+    return 0;
+}
diff --git a/tests/tcg/openrisc/test_and_or.c b/tests/tcg/openrisc/test_and_or.c
new file mode 100644
index 0000000..810d868
--- /dev/null
+++ b/tests/tcg/openrisc/test_and_or.c
@@ -0,0 +1,65 @@
+#include <stdio.h>
+
+int main(void)
+{
+    int a, b, c;
+    int result;
+
+    b = 0x2;
+    c = 0x1;
+    result = 0;
+    __asm
+    ("l.and  %0, %1, %2\n\t"
+     : "=r"(a)
+     : "r"(b), "r"(c)
+    );
+    if (a != result) {
+        printf("and error\n");
+        return -1;
+    }
+
+    result = 0x2;
+    __asm
+    ("l.andi  %0, %1, 0x3\n\t"
+     : "=r"(a)
+     : "r"(b)
+    );
+    if (a != result) {
+        printf("andi error %x\n", a);
+        return -1;
+    }
+
+    result = 0x3;
+    __asm
+    ("l.or   %0, %1, %2\n\t"
+     : "=r"(a)
+     : "r"(b), "r"(c)
+    );
+    if (a != result) {
+        printf("or error\n");
+        return -1;
+    }
+
+    result = 0x3;
+    __asm
+    ("l.xor  %0, %1, %2\n\t"
+     : "=r"(a)
+     : "r"(b), "r"(c)
+    );
+    if (a != result) {
+        printf("xor error\n");
+        return -1;
+    }
+
+    __asm
+    ("l.xori  %0, %1, 0x1\n\t"
+     : "=r"(a)
+     : "r"(b)
+    );
+    if (a != result) {
+        printf("xori error\n");
+        return -1;
+    }
+
+    return 0;
+}
diff --git a/tests/tcg/openrisc/test_bf.c b/tests/tcg/openrisc/test_bf.c
new file mode 100644
index 0000000..79f3fb9
--- /dev/null
+++ b/tests/tcg/openrisc/test_bf.c
@@ -0,0 +1,47 @@
+#include <stdio.h>
+
+int main(void)
+{
+    int a, b, c;
+    int result;
+
+    a = 0;
+    b = 10;
+    c = 11;
+    result = 0x2;
+    __asm
+    ("1:\n\t"
+     "l.addi %1, %1, 0x01\n\t"
+     "l.addi %0, %0, 0x01\n\t"
+     "l.sfeq %1, %2\n\t"
+     "l.bf   1b\n\t"
+     "l.nop\n\t"
+     : "+r"(a)
+     : "r"(b), "r"(c)
+    );
+    if (a != result) {
+        printf("sfeq error\n");
+        return -1;
+    }
+
+    a = 0x00;
+    b = 0x11;
+    c = 0x11;
+    result = 0x01;
+    __asm
+    ("1:\n\t"
+     "l.addi %1, %1, 0x01\n\t"
+     "l.addi %0, %0, 0x01\n\t"
+     "l.sfeq %1, %2\n\t"
+     "l.bf   1b\n\t"
+     "l.nop\n\t"
+     : "+r"(a)
+     : "r"(b), "r"(c)
+    );
+    if (a != result) {
+        printf("sfeq error\n");
+        return -1;
+    }
+
+    return 0;
+}
diff --git a/tests/tcg/openrisc/test_bnf.c b/tests/tcg/openrisc/test_bnf.c
new file mode 100644
index 0000000..f716215
--- /dev/null
+++ b/tests/tcg/openrisc/test_bnf.c
@@ -0,0 +1,51 @@
+#include <stdio.h>
+
+int main(void)
+{
+    int a, b;
+    int result;
+
+    a = 0;
+    b = 0;
+    result = 0x3;
+    __asm
+    ("l.sfeqi %1, 0x0\n\t"
+     "l.bnf 1f\n\t"
+     "l.nop\n\t"
+     "\n\t"
+     "l.addi %0, %0, 0x1\n\t"
+     "l.addi %0, %0, 0x1\n\t"
+     "\n\t"
+     "1:\n\t"
+     "l.addi %0, %0, 0x1\n\t"
+     : "+r"(a)
+     : "r"(b)
+    );
+    if (a != result) {
+        printf("l.bnf error\n");
+        return -1;
+    }
+
+    a = 0;
+    b = 0;
+    result = 1;
+    __asm
+    ("l.sfeqi %1, 0x1\n\t"
+     "l.bnf 1f\n\t"
+     "l.nop\n\t"
+     "\n\t"
+     "l.addi %0, %0, 0x1\n\t"
+     "l.addi %0, %0, 0x1\n\t"
+     "\n\t"
+     "1:\n\t"
+     "l.addi %0, %0, 0x1\n\t"
+     : "+r"(a)
+     : "r"(b)
+    );
+    if (a != result) {
+        printf("l.bnf error\n");
+        return -1;
+    }
+
+    return 0;
+}
diff --git a/tests/tcg/openrisc/test_div.c b/tests/tcg/openrisc/test_div.c
new file mode 100644
index 0000000..9b65f6e
--- /dev/null
+++ b/tests/tcg/openrisc/test_div.c
@@ -0,0 +1,54 @@
+#include <stdio.h>
+
+int main(void)
+{
+    int a, b, c;
+    int result;
+
+    b = 0x120;
+    c = 0x4;
+    result = 0x48;
+    __asm
+    ("l.div  %0, %1, %2\n\t"
+     : "=r"(a)
+     : "r"(b), "r"(c)
+    );
+    if (a != result) {
+        printf("div error\n");
+        return -1;
+    }
+
+    result = 0x4;
+    __asm
+    ("l.div %0, %1, %0\n\t"
+     : "+r"(a)
+     : "r"(b)
+    );
+    if (a != result) {
+        printf("div error\n");
+        return -1;
+    }
+
+    b = 0xffffffff;
+    c = 0x80000000;
+    result = 0;
+    __asm
+    ("l.div %0, %1, %2\n\t"
+     : "=r"(a)
+     : "r"(b), "r"(c)
+    );
+    if (a != result) {
+        printf("div error\n");
+        return -1;
+    }
+
+    b = 0x80000000;
+    c = 0xffffffff;
+    __asm
+    ("l.div %0, %1, %2\n\t"
+     : "=r"(a)
+     : "r"(b), "r"(c)
+    );
+
+    return 0;
+}
diff --git a/tests/tcg/openrisc/test_divu.c b/tests/tcg/openrisc/test_divu.c
new file mode 100644
index 0000000..bff9e3e
--- /dev/null
+++ b/tests/tcg/openrisc/test_divu.c
@@ -0,0 +1,34 @@
+#include <stdio.h>
+
+int main(void)
+{
+    int a, b, c;
+    int result;
+
+    b = 0x120;
+    c = 0x4;
+    result = 0x48;
+
+    __asm
+    ("l.divu  %0, %1, %2\n\t"
+     : "=r"(a)
+     : "r"(b), "r"(c)
+    );
+    if (a != result) {
+        printf("divu error\n");
+        return -1;
+    }
+
+    result = 0x4;
+    __asm
+    ("l.divu %0, %1, %0\n\t"
+     : "+r"(a)
+     : "r"(b)
+    );
+    if (a != result) {
+        printf("divu error\n");
+        return -1;
+    }
+
+    return 0;
+}
diff --git a/tests/tcg/openrisc/test_extx.c b/tests/tcg/openrisc/test_extx.c
new file mode 100644
index 0000000..0922148
--- /dev/null
+++ b/tests/tcg/openrisc/test_extx.c
@@ -0,0 +1,78 @@
+#include <stdio.h>
+
+int main(void)
+{
+    int a, b;
+    int result;
+
+    b = 0x83;
+    result = 0xffffff83;
+    __asm
+    ("l.extbs  %0, %1\n\t"
+     : "=r"(a)
+     : "r"(b)
+    );
+    if (a != result) {
+        printf("extbs error\n");
+        return -1;
+    }
+
+    result = 0x83;
+    __asm
+    ("l.extbz  %0, %1\n\t"
+     : "=r"(a)
+     : "r"(b)
+    );
+    if (a != result) {
+        printf("extbz error\n");
+        return -1;
+    }
+
+    b = 0x8083;
+    result = 0xffff8083;
+    __asm
+    ("l.exths  %0, %1\n\t"
+     : "=r"(a)
+     : "r"(b)
+    );
+    if (a != result) {
+        printf("exths error\n");
+        return -1;
+    }
+
+    result = 0x8083;
+    __asm
+    ("l.exthz  %0, %1\n\t"
+     : "=r"(a)
+     : "r"(b)
+    );
+    if (a != result) {
+        printf("exthz error\n");
+        return -1;
+    }
+
+    b = 0x11;
+    result = 0x11;
+    __asm
+    ("l.extws  %0, %1\n\t"
+     : "=r"(a)
+     : "r"(b)
+    );
+
+    if (a != result) {
+        printf("extws error\n");
+        return -1;
+    }
+
+    __asm
+    ("l.extwz  %0, %1\n\t"
+     : "=r"(a)
+     : "r"(b)
+    );
+    if (a != result) {
+        printf("extwz error\n");
+        return -1;
+    }
+
+    return 0;
+}
diff --git a/tests/tcg/openrisc/test_fx.c b/tests/tcg/openrisc/test_fx.c
new file mode 100644
index 0000000..df86000
--- /dev/null
+++ b/tests/tcg/openrisc/test_fx.c
@@ -0,0 +1,57 @@
+#include <stdio.h>
+
+int main(void)
+{
+    int a, b;
+    int result;
+
+    b = 0x123;
+    result = 1;
+    __asm
+    ("l.ff1 %0, %1\n\t"
+     : "=r"(a)
+     : "r"(b)
+    );
+    if (a != result) {
+        printf("ff1 error\n");
+        return -1;
+    }
+
+    b = 0x0;
+    result = 0;
+    __asm
+    ("l.ff1 %0, %1\n\t"
+     : "=r"(a)
+     : "r"(b)
+    );
+    if (a != result) {
+        printf("ff1 error\n");
+        return -1;
+    }
+
+    b = 0x123;
+    result = 9;
+    __asm
+    ("l.fl1 %0, %1\n\t"
+     : "=r"(a)
+     : "r"(b)
+    );
+    if (a != result) {
+        printf("fl1 error\n");
+        return -1;
+    }
+
+    b = 0x0;
+    result = 0;
+    __asm
+    ("l.fl1 %0, %1\n\t"
+     : "=r"(a)
+     : "r"(b)
+    );
+    if (a != result) {
+        printf("fl1 error\n");
+        return -1;
+    }
+
+    return 0;
+}
diff --git a/tests/tcg/openrisc/test_j.c b/tests/tcg/openrisc/test_j.c
new file mode 100644
index 0000000..9ddf8bf
--- /dev/null
+++ b/tests/tcg/openrisc/test_j.c
@@ -0,0 +1,26 @@
+#include <stdio.h>
+
+int main(void)
+{
+    int a;
+    int result;
+
+    a = 0;
+    result = 2;
+    __asm
+    ("l.addi %0, %0, 1\n\t"
+     "l.j j\n\t"
+     "l.nop\n\t"
+     "l.addi %0, %0, 1\n\t"
+     "l.nop\n\t"
+     "j:\n\t"
+     "l.addi %0, %0, 1\n\t"
+     : "+r"(a)
+    );
+    if (a != result) {
+        printf("j error\n");
+        return -1;
+    }
+
+    return 0;
+}
diff --git a/tests/tcg/openrisc/test_jal.c b/tests/tcg/openrisc/test_jal.c
new file mode 100644
index 0000000..7e2da40
--- /dev/null
+++ b/tests/tcg/openrisc/test_jal.c
@@ -0,0 +1,26 @@
+#include <stdio.h>
+
+int main(void)
+{
+    int a;
+    int result;
+
+    a = 0;
+    result = 2;
+    __asm
+    ("l.addi %0, %0, 1\n\t"
+     "l.jal jal\n\t"
+     "l.nop\n\t"
+     "l.addi %0, %0, 1\n\t"
+     "l.nop\n\t"
+     "jal:\n\t"
+     "l.addi %0, %0, 1\n\t"
+     : "+r"(a)
+    );
+    if (a != result) {
+        printf("jal error\n");
+        return -1;
+    }
+
+    return 0;
+}
diff --git a/tests/tcg/openrisc/test_lf_add.c b/tests/tcg/openrisc/test_lf_add.c
new file mode 100644
index 0000000..e00212d
--- /dev/null
+++ b/tests/tcg/openrisc/test_lf_add.c
@@ -0,0 +1,39 @@
+#include <stdio.h>
+
+int main(void)
+{
+    float a, b;
+    float res2;
+
+    a = 1.5;
+    b = 2.5;
+    res2 = 4.0;
+    __asm
+    ("lf.add.s  %0, %0, %1\n\t"
+     : "+r"(a)
+     : "r"(b)
+    );
+    if (a != res2) {
+        printf("lf.add.s error, %f\n", a);
+        return -1;
+    }
+
+/*    double c, d;
+    double res1;
+
+    c = 1.5;
+    d = 1.5;
+    res1 = 3.00;
+    __asm
+    ("lf.add.d  %0, %1, %2\n\t"
+     : "+r"(c)
+     : "r"(d)
+    );
+
+    if ((e - res1) > 0.002) {
+        printf("lf.add.d error, %f\n", e - res1);
+        return -1;
+    }*/
+
+    return 0;
+}
diff --git a/tests/tcg/openrisc/test_lf_div.c b/tests/tcg/openrisc/test_lf_div.c
new file mode 100644
index 0000000..70b5d1c
--- /dev/null
+++ b/tests/tcg/openrisc/test_lf_div.c
@@ -0,0 +1,37 @@
+#include <stdio.h>
+
+int main(void)
+{
+    float a, b, c;
+    float result;
+
+    b = 1.5;
+    c = 0.5;
+    result = 3.0;
+    __asm
+    ("lf.div.s    %0, %1, %2\n\t"
+     : "=r"(a)
+     : "r"(b), "r"(c)
+    );
+    if (a != result) {
+        printf("lf.div.s error\n");
+        return -1;
+    }
+
+/*    double a, b, c, res;
+
+    b = 0x80000000;
+    c = 0x40;
+    result = 0x2000000;
+    __asm
+    ("lf.div.d    %0, %1, %2\n\t"
+     : "=r"(a)
+     : "r"(b), "r"(c)
+    );
+    if (a != result) {
+        printf("lf.div.d error\n");
+        return -1;
+    }*/
+
+    return 0;
+}
diff --git a/tests/tcg/openrisc/test_lf_eqs.c b/tests/tcg/openrisc/test_lf_eqs.c
new file mode 100644
index 0000000..a176bd6
--- /dev/null
+++ b/tests/tcg/openrisc/test_lf_eqs.c
@@ -0,0 +1,88 @@
+#include <stdio.h>
+
+int main(void)
+{
+    int a, result;
+    float b, c;
+
+    a = 0x1;
+    b = 122.5;
+    c = 123.5;
+    result = 0x3;
+    __asm
+    ("lfeqd:\n\t"
+     "l.addi    %0, %0, 0x1\n\t"
+     "lf.sfeq.s %1, %2\n\t"
+     "l.bf      lfeqd\n\t"
+     "l.nop\n\t"
+     "l.addi    %0, %0, 0x1\n\t"
+     : "+r"(a)
+     : "r"(b), "r"(c)
+    );
+    if (a != result) {
+        printf("lf.sfeq.s error\n");
+        return -1;
+    }
+
+    b = 13.5;
+    c = 13.5;
+    result = 0x3;
+    __asm
+    ("lf.sfeq.s %1, %2\n\t"
+     "l.bf      1f\n\t"
+     "l.nop\n\t"
+     "l.addi    r4, r4, 0x1\n\t"
+     "1:\n\t"
+     : "+r"(a)
+     : "r"(b), "r"(c)
+    );
+    if (a != result) {
+        printf("lf.sfeq.s error\n");
+        return -1;
+    }
+
+/*    double b, c;
+    double result;
+    int a;
+
+    a = 0x1;
+    b = 122.5;
+    c = 133.5;
+    result = 0x3;
+
+    __asm
+    ("lfeqd:\n\t"
+     "l.addi %0, %0, 0x1\n\t"
+     "lf.sfeq.d %1, %2\n\t"
+     "l.bf      lfeqd\n\t"
+     "l.nop\n\t"
+     "l.addi    %0, %0, 0x1\n\t"
+     : "+r"(a)
+     : "r"(b), "r"(c)
+    );
+    if (a != result) {
+        printf("lf.sfeq.d error\n");
+        return -1;
+    }
+
+    double c, d, res;
+    int e = 0;
+    c = 11.5;
+    d = 11.5;
+    res = 1;
+    __asm
+    ("lf.sfeq.d %1, %2\n\t"
+     "l.bf      1f\n\t"
+     "l.nop\n\t"
+     "l.addi    %0, %0, 0x1\n\t"
+     "1:\n\t"
+     : "+r"(e)
+     : "r"(c), "r"(d)
+    );
+    if (e != res) {
+        printf("lf.sfeq.d error\n");
+        return -1;
+    }*/
+
+    return 0;
+}
diff --git a/tests/tcg/openrisc/test_lf_ges.c b/tests/tcg/openrisc/test_lf_ges.c
new file mode 100644
index 0000000..98e7f50
--- /dev/null
+++ b/tests/tcg/openrisc/test_lf_ges.c
@@ -0,0 +1,88 @@
+#include <stdio.h>
+
+int main(void)
+{
+    int a, result;
+    float b, c;
+
+    a = 0;
+    b = 122.5;
+    c = 123.5;
+    result = 0x1;
+    __asm
+    ("lfges:\n\t"
+     "l.addi    %0, %0, 0x1\n\t"
+     "lf.sfge.s %1, %2\n\t"
+     "l.bf      lfges\n\t"
+     "l.nop\n\t"
+     : "+r"(a)
+     : "r"(b), "r"(c)
+    );
+    if (a != result) {
+        printf("lf.sfge.s error\n");
+        return -1;
+    }
+
+    b = 133.5;
+    c = 13.5;
+    result = 0x3;
+    __asm
+    ("l.addi    %0, %0, 0x1\n\t"
+     "l.addi    %0, %0, 0x1\n\t"
+     "lf.sfge.s %1, %2\n\t"
+     "l.bf      1f\n\t"
+     "l.nop\n\t"
+     "l.addi    %0, %0, 0x1\n\t"
+     "l.addi    %0, %0, 0x1\n\t"
+     "1:\n\t"
+     : "+r"(a)
+     : "r"(b), "r"(c)
+    );
+    if (a != result) {
+        printf("lf.sfge.s error\n");
+        return -1;
+    }
+
+/*    int a, result;
+    double b, c;
+
+    a = 0x1;
+    b = 122.5;
+    c = 123.5;
+    result = 0x2;
+    __asm
+    ("lfged:\n\t"
+     "l.addi    %0, %0, 0x1\n\t"
+     "lf.sfge.d %1, %2\n\t"
+     "l.bf      lfged\n\t"
+     "l.nop\n\t"
+     : "+r"(a)
+     : "r"(b), "r"(c)
+    );
+    if (a != result) {
+        printf("lf.sfge.d error\n");
+        return -1;
+    }
+
+    b = 133.5;
+    c = 13.5;
+    result = 0x4;
+    __asm
+    ("lf.sfge.d %1, %2\n\t"
+     "l.bf      1f\n\t"
+     "l.nop\n\t"
+     "l.addi    %0, %0, 0x1\n\t"
+     "l.addi    %0, %0, 0x1\n\t"
+     "1:\n\t"
+     "l.addi    %0, %0, 0x1\n\t"
+     "l.addi    %0, %0, 0x1\n\t"
+     : "+r"(a)
+     : "r"(b), "r"(c)
+    );
+    if (a != result) {
+        printf("lf.sfge.d error\n");
+        return -1;
+    }*/
+
+    return 0;
+}
diff --git a/tests/tcg/openrisc/test_lf_gts.c b/tests/tcg/openrisc/test_lf_gts.c
new file mode 100644
index 0000000..f3df279
--- /dev/null
+++ b/tests/tcg/openrisc/test_lf_gts.c
@@ -0,0 +1,86 @@
+#include <stdio.h>
+
+int main(void)
+{
+    int a, result;
+    float b, c;
+
+    a = 0;
+    b = 122.5;
+    c = 123.5;
+    result = 0x1;
+    __asm
+    ("lfgts:\n\t"
+     "l.addi    %0, %0, 0x1\n\t"
+     "lf.sfgt.s %1, %2\n\t"
+     "l.bf      lfgts\n\t"
+     "l.nop\n\t"
+     : "+r"(a)
+     : "r"(b), "r"(c)
+    );
+    if (a != result) {
+        printf("lf.sfgt.s error\n");
+        return -1;
+    }
+
+    b = 133.5;
+    c = 13.5;
+    result = 0x1;
+    __asm
+    ("lf.sfgt.s %1, %2\n\t"
+     "l.bf      1f\n\t"
+     "l.nop\n\t"
+     "l.addi    %0, %0, 0x1\n\t"
+     "l.addi    %0, %0, 0x1\n\t"
+     "1:\n\t"
+     : "+r"(a)
+     : "r"(b), "r"(c)
+    );
+    if (a != result) {
+        printf("lf.sfgt.s error\n");
+        return -1;
+    }
+
+/*    int a, result;
+    double b, c;
+
+    a = 0;
+    b = 122.5;
+    c = 123.5;
+    result = 0x1;
+    __asm
+    ("lfgtd:\n\t"
+     "l.addi    %0, %0, 0x1\n\t"
+     "lf.sfgt.d %1, %2\n\t"
+     "l.bf      lfgtd\n\t"
+     "l.nop\n\t"
+     : "+r"(a)
+     : "r"(b), "r"(c)
+    );
+    if (a != result) {
+        printf("lf.sfgt.d error\n");
+        return -1;
+    }
+
+    b = 133.5;
+    c = 13.5;
+    result = 0x3;
+    __asm
+    ("l.addi    %0, %0, 0x1\n\t"
+     "l.addi    %0, %0, 0x1\n\t"
+     "lf.sfgt.d %1, %2\n\t"
+     "l.bf      1f\n\t"
+     "l.nop\n\t"
+     "l.addi    %0, %0, 0x1\n\t"
+     "l.addi    %0, %0, 0x1\n\t"
+     "1:\n\t"
+     : "+r"(a)
+     : "r"(b), "r"(c)
+    );
+    if (a != result) {
+        printf("lf.sfgt.d error, %x\n", a);
+        return -1;
+    }*/
+
+    return 0;
+}
diff --git a/tests/tcg/openrisc/test_lf_les.c b/tests/tcg/openrisc/test_lf_les.c
new file mode 100644
index 0000000..046c511
--- /dev/null
+++ b/tests/tcg/openrisc/test_lf_les.c
@@ -0,0 +1,88 @@
+#include <stdio.h>
+
+int main(void)
+{
+    int a;
+    float b, c;
+    int result;
+
+    a = 0;
+    b = 1234.2;
+    c = 12.4;
+    result = 0x1;
+    __asm
+    ("lfles:\n\t"
+     "l.addi    %0, %0, 0x1\n\t"
+     "lf.sfle.s %1, %2\n\t"
+     "l.bf      lfles\n\t"
+     "l.nop\n\t"
+     : "+r"(a)
+     : "r"(b), "r"(c)
+    );
+    if (a != result) {
+        printf("lf.sfle.s error\n");
+        return -1;
+    }
+
+    b = 1.1;
+    c = 19.4;
+    result = 0x3;
+    __asm
+    ("l.addi    %0, %0, 0x1\n\t"
+     "l.addi    %0, %0, 0x1\n\t"
+     "lf.sfle.s %1, %2\n\t"
+     "l.bf      1f\n\t"
+     "l.nop\n\t"
+     "l.addi    %0, %0, 0x1\n\t"
+     "l.addi    %0, %0, 0x1\n\t"
+     "1:\n\t"
+     : "+r"(a)
+     : "r"(b), "r"(c)
+    );
+    if (a != result) {
+        printf("lf.sfle.s error\n");
+        return -1;
+    }
+
+/*    int a;
+    double b, c;
+    int result;
+
+    a = 0;
+    b = 1212.5;
+    c = 123.5;
+    result = 0x1;
+    __asm
+    ("lfled:\n\t"
+     "l.addi    %0, %0, 0x1\n\t"
+     "lf.sfle.d %1, %2\n\t"
+     "l.bf      lfled\n\t"
+     "l.nop\n\t"
+     : "+r"(a)
+     : "r"(b), "r"(c)
+    );
+    if (a != result) {
+        printf("lf.sfle.d error\n");
+        return -1;
+    }
+
+    b = 13.5;
+    c = 113.5;
+    result = 0x2;
+    __asm
+    ("l.addi    %0, %0, 0x1\n\t"
+     "lf.sfle.d %1, %2\n\t"
+     "l.bf      1f\n\t"
+     "l.nop\n\t"
+     "l.addi    %0, %0, 0x1\n\t"
+     "1:\n\t"
+     : "+r"(a)
+     : "r"(b), "r"(c)
+    );
+    if (a != result) {
+        printf("lf.sfle.d error\n");
+        return -1;
+    }*/
+
+    return 0;
+}
diff --git a/tests/tcg/openrisc/test_lf_lts.c b/tests/tcg/openrisc/test_lf_lts.c
new file mode 100644
index 0000000..fa56721
--- /dev/null
+++ b/tests/tcg/openrisc/test_lf_lts.c
@@ -0,0 +1,92 @@
+#include <stdio.h>
+
+int main(void)
+{
+    int a;
+    float b, c, d;
+    int result;
+
+    a = 0;
+    b = 124.5;
+    c = 1.4;
+    result = 1;
+    __asm
+    ("lfltd:\n\t"
+     "l.addi    %0, %0, 0x1\n\t"
+     "lf.sflt.s %1, %2\n\t"
+     "l.bf      lfltd\n\t"
+     "l.nop\n\t"
+     : "+r"(a)
+     : "r"(b), "r"(c)
+    );
+    if (a != result) {
+        printf("lf.sflt.s error\n");
+        return -1;
+    }
+
+    a = 0;
+    b = 11.1;
+    c = 13.1;
+    d = 1.0;
+    result = 2;
+    __asm
+    ("1:\n\t"
+     "lf.add.s  %1, %1, %3\n\t"
+     "l.addi    %0, %0, 1\n\t"
+     "lf.sflt.s %1, %2\n\t"
+     "l.bf      1b\n\t"
+     "l.nop\n\t"
+     : "+r"(a)
+     : "r"(b), "r"(c), "r"(d)
+    );
+    if (a != result) {
+        printf("lf.sflt.s error\n");
+        return -1;
+    }
+
+/*    int a;
+    double b, c;
+    int result;
+
+    a = 0;
+    b = 1432.1;
+    c = 2.4;
+    result = 0x1;
+    __asm
+    ("lfltd:\n\t"
+     "l.addi    %0, %0, 0x1\n\t"
+     "lf.sflt.d %1, %2\n\t"
+     "l.bf      lfltd\n\t"
+     "l.nop\n\t"
+     : "+r"(a)
+     : "r"(b), "r"(c)
+    );
+    if (a != result) {
+        printf("lf.sflt.d error\n");
+        return -1;
+    }
+
+    a = 0;
+    b = 1.1;
+    c = 19.7;
+    result = 2;
+    __asm
+    ("lf.sflt.d %1, %2\n\t"
+     "l.bf      1f\n\t"
+     "l.nop\n\t"
+     "l.addi %0, %0, 1\n\t"
+     "l.addi %0, %0, 1\n\t"
+     "l.addi %0, %0, 1\n\t"
+     "1:\n\t"
+     "l.addi %0, %0, 1\n\t"
+     "l.addi %0, %0, 1\n\t"
+     : "+r"(a), "+r"(b)
+     : "r"(c)
+    );
+    if (a != result) {
+        printf("lf.sflt.d error\n");
+        return -1;
+    }*/
+
+    return 0;
+}
diff --git a/tests/tcg/openrisc/test_lf_mul.c b/tests/tcg/openrisc/test_lf_mul.c
new file mode 100644
index 0000000..bc8ad80
--- /dev/null
+++ b/tests/tcg/openrisc/test_lf_mul.c
@@ -0,0 +1,22 @@
+#include <stdio.h>
+
+int main(void)
+{
+    float a, b, c;
+    float result;
+
+    b = 1.5;
+    c = 4.0;
+    result = 6.0;
+    __asm
+    ("lf.mul.s   %0, %1, %2\n\t"
+     : "=r"(a)
+     : "r"(b), "r"(c)
+    );
+    if (a != result) {
+        printf("lf.mul.s error\n");
+        return -1;
+    }
+
+    return 0;
+}
diff --git a/tests/tcg/openrisc/test_lf_nes.c b/tests/tcg/openrisc/test_lf_nes.c
new file mode 100644
index 0000000..6136310
--- /dev/null
+++ b/tests/tcg/openrisc/test_lf_nes.c
@@ -0,0 +1,89 @@
+#include <stdio.h>
+
+int main(void)
+{
+    int a;
+    float b, c;
+    int result;
+
+    a = 0;
+    b = 23.1;
+    c = 23.1;
+    result = 0x1;
+    __asm
+    ("lfnes:\n\t"
+     "l.addi    %0, %0, 0x1\n\t"
+     "lf.sfne.s %1, %2\n\t"
+     "l.bf      lfnes\n\t"
+     "l.nop\n\t"
+     : "+r"(a)
+     : "r"(b), "r"(c)
+    );
+    if (a != result) {
+        printf("lf.sfne.s error");
+        return -1;
+    }
+
+    b = 12.4;
+    c = 7.8;
+    result = 0x3;
+    __asm
+    ("l.addi    %0, %0, 0x1\n\t"
+     "l.addi    %0, %0, 0x1\n\t"
+     "lf.sfne.s %1, %2\n\t"
+     "l.bf      1f\n\t"
+     "l.nop\n\t"
+     "l.addi    %0, %0, 0x1\n\t"
+     "l.addi    %0, %0, 0x1\n\t"
+     "1:\n\t"
+     : "+r"(a)
+     : "r"(b), "r"(c)
+    );
+    if (a != result) {
+        printf("lf.sfne.s error\n");
+        return -1;
+    }
+/*    int a;
+    double b, c;
+    int result;
+
+    a = 0;
+    b = 124.3;
+    c = 124.3;
+    result = 0x1;
+    __asm
+    ("lfned:\n\t"
+     "l.addi    %0, %0, 0x1\n\t"
+     "lf.sfne.d %1, %2\n\t"
+     "l.bf      lfned\n\t"
+     "l.nop\n\t"
+     : "+r"(a)
+     : "r"(b), "r"(c)
+    );
+    if (a != result) {
+        printf("lf.sfne.d error\n");
+        return -1;
+    }
+
+    b = 11.5;
+    c = 16.7;
+    result = 0x3;
+    __asm
+    ("l.addi    %0, %0, 0x1\n\t"
+     "l.addi    %0, %0, 0x1\n\t"
+     "lf.sfne.d %1, %2\n\t"
+     "l.bf      1f\n\t"
+     "l.nop\n\t"
+     "l.addi    r4, r4, 0x1\n\t"
+     "l.addi    r4, r4, 0x1\n\t"
+     "1:\n\t"
+     : "+r"(a)
+     : "r"(b), "r"(c)
+    );
+    if (a != result) {
+        printf("lf.sfne.d error\n");
+        return -1;
+    }*/
+
+    return 0;
+}
diff --git a/tests/tcg/openrisc/test_lf_rem.c b/tests/tcg/openrisc/test_lf_rem.c
new file mode 100644
index 0000000..bd6090d
--- /dev/null
+++ b/tests/tcg/openrisc/test_lf_rem.c
@@ -0,0 +1,32 @@
+#include <stdio.h>
+
+int main(void)
+{
+    float a, b, c;
+    float result;
+
+    b = 101.5;
+    c = 10;
+    result = 1.5;
+/*    __asm
+    ("lf.rem.d      %0, %1, %2\n\t"
+     : "=r"(a)
+     : "r"(b), "r"(c)
+    );
+    if (a != result) {
+        printf("lf.rem.d error\n");
+        return -1;
+    }*/
+
+    __asm
+    ("lf.rem.s      %0, %1, %2\n\t"
+     : "=r"(a)
+     : "r"(b), "r"(c)
+    );
+    if (a != result) {
+        printf("lf.rem.s error\n");
+        return -1;
+    }
+
+    return 0;
+}
diff --git a/tests/tcg/openrisc/test_lf_sub.c b/tests/tcg/openrisc/test_lf_sub.c
new file mode 100644
index 0000000..5ee9b03
--- /dev/null
+++ b/tests/tcg/openrisc/test_lf_sub.c
@@ -0,0 +1,35 @@
+#include <stdio.h>
+
+int main(void)
+{
+    float a, b, c;
+    float result;
+
+    b = 10.5;
+    c = 1.5;
+    result = 9.0;
+    __asm
+    ("lf.sub.s  %0, %1, %2\n\t"
+     : "=r"(a)
+     : "r"(b), "r"(c)
+    );
+    if (a != result) {
+        printf("lf.sub.s error\n");
+        return -1;
+    }
+
+/*    b = 0x999;
+    c = 0x654;
+    result = 0x345;
+    __asm
+    ("lf.sub.d  %0, %1, %2\n\t"
+     : "=r"(a)
+     : "r"(b), "r"(c)
+    );
+    if (a != result) {
+        printf("lf.sub.d error\n");
+        return -1;
+    }*/
+
+    return 0;
+}
diff --git a/tests/tcg/openrisc/test_logic.c b/tests/tcg/openrisc/test_logic.c
new file mode 100644
index 0000000..46d173f
--- /dev/null
+++ b/tests/tcg/openrisc/test_logic.c
@@ -0,0 +1,105 @@
+#include <stdio.h>
+
+int main(void)
+{
+    int a, b, c;
+    int result;
+
+    b = 0x9743;
+    c = 0x2;
+    result = 0x25d0c;
+    __asm
+    ("l.sll    %0, %1, %2\n\t"
+     : "=r"(a)
+     : "r"(b), "r"(c)
+    );
+    if (a != result) {
+        printf("sll error\n");
+        return -1;
+    }
+
+    b = 0x9743;
+    result = 0x25d0c;
+    __asm
+    ("l.slli   %0, %1, 0x2\n\t"
+     : "=r"(a)
+     : "r"(b)
+    );
+    if (a != result) {
+        printf("slli error\n");
+        return -1;
+    }
+
+    b = 0x7654;
+    c = 0x03;
+    result = 0xeca;
+    __asm
+    ("l.srl    %0, %1, %2\n\t"
+     : "=r"(a)
+     : "r"(b), "r"(c)
+    );
+
+    b = 0x7654;
+    result = 0xeca;
+    __asm
+    ("l.srli   %0, %1, 0x3\n\t"
+     : "=r"(a)
+     : "r"(b)
+    );
+    if (a != result) {
+        printf("srli error\n");
+        return -1;
+    }
+
+    b = 0x80000001;
+    c = 0x4;
+    result = 0x18000000;
+    __asm
+    ("l.ror    %0, %1, %2\n\t"
+     : "=r"(a)
+     : "r"(b), "r"(c)
+    );
+    if (a != result) {
+        printf("ror error\n");
+        return -1;
+    }
+
+    b = 0x80000001;
+    result = 0x18000000;
+    __asm
+    ("l.rori   %0, %1, 0x4\n\t"
+     : "=r"(a)
+     : "r"(b)
+    );
+    if (a != result) {
+        printf("rori error\n");
+        return -1;
+    }
+
+    b = 0x80000001;
+    c = 0x03;
+    result = 0xf0000000;
+    __asm
+    ("l.sra    %0, %1, %2\n\t"
+     : "=r"(a)
+     : "r"(b), "r"(c)
+    );
+    if (a != result) {
+        printf("sra error\n");
+        return -1;
+    }
+
+    b = 0x80000001;
+    result = 0xf0000000;
+    __asm
+    ("l.srai   %0, %1, 0x3\n\t"
+     : "=r"(a)
+     : "r"(b)
+    );
+    if (a != result) {
+        printf("srai error\n");
+        return -1;
+    }
+
+    return 0;
+}
diff --git a/tests/tcg/openrisc/test_lx.c b/tests/tcg/openrisc/test_lx.c
new file mode 100644
index 0000000..792e3d5
--- /dev/null
+++ b/tests/tcg/openrisc/test_lx.c
@@ -0,0 +1,84 @@
+#include <stdio.h>
+
+int main(void)
+{
+    int a;
+    int p[50];
+    int result;
+
+    result = 0x23;
+    __asm
+    ("l.ori r8, r0, 0x123\n\t"
+     "l.sb  0x4 + %1, r8\n\t"
+     "\n\t"
+     "l.lbz %0, 0x4 + %1\n\t"
+     : "=r"(a), "+m"(*p)
+    );
+    if (a != result) {
+        printf("lbz error, %x\n", a);
+        return -1;
+    }
+
+    result = 0x23;
+    __asm
+    ("l.lbs %0, 0x4 + %1\n\t"
+     : "=r"(a)
+     : "m"(*p)
+    );
+    if (a != result) {
+        printf("lbs error\n");
+        return -1;
+    }
+
+    result = 0x1111;
+    __asm
+    ("l.ori r8, r0, 0x1111\n\t"
+     "l.sh  0x20 + %1, r8\n\t"
+     "\n\t"
+     "l.lhs %0, 0x20 + %1\n\t"
+     : "=r"(a), "=m"(*p)
+    );
+    if (a != result) {
+        printf("lhs error, %x\n", a);
+        return -1;
+    }
+
+    result = 0x1111;
+    __asm
+    ("l.lhz %0, 0x20 + %1\n\t"
+     : "=r"(a)
+     : "m"(*p)
+    );
+    if (a != result) {
+        printf("lhz error\n");
+        return -1;
+    }
+
+    result = 0x1111233;
+    __asm
+    ("l.ori r8, r0, 0x1233\n\t"
+     "l.movhi r1, 0x111\n\t"
+     "l.or  r8, r8, r1\n\t"
+     "l.sw  0x123 + %1, r8\n\t"
+     "\n\t"
+     "l.lws %0, 0x123 + %1\n\t"
+     : "=r"(a), "+m"(*p)
+    );
+    if (a != result) {
+        printf("lws error, %x\n", a);
+        return -1;
+    }
+
+    result = 0x1111233;
+    __asm
+    ("l.lwz %0, 0x123 + %1\n\t"
+     : "=r"(a)
+     : "m"(*p)
+    );
+    if (a != result) {
+        printf("lwz error\n");
+        return -1;
+    }
+
+    return 0;
+}
diff --git a/tests/tcg/openrisc/test_movhi.c b/tests/tcg/openrisc/test_movhi.c
new file mode 100644
index 0000000..737f75b
--- /dev/null
+++ b/tests/tcg/openrisc/test_movhi.c
@@ -0,0 +1,31 @@
+#include <stdio.h>
+
+int main(void)
+{
+    int a;
+    int result;
+
+    result = 0x1222;
+    __asm
+    ("l.movhi r3, 0x1222\n\t"
+     "l.srli   %0, r3, 16\n\t"
+     : "=r"(a)
+    );
+    if (a != result) {
+        printf("movhi error\n");
+        return -1;
+    }
+
+    result = 0x1111;
+    __asm
+    ("l.movhi r8, 0x1111\n\t"
+     "l.srli   %0, r8, 16\n\t"
+     : "=r"(a)
+    );
+    if (a != result) {
+        printf("movhi error\n");
+        return -1;
+    }
+
+    return 0;
+}
diff --git a/tests/tcg/openrisc/test_mul.c b/tests/tcg/openrisc/test_mul.c
new file mode 100644
index 0000000..130101f
--- /dev/null
+++ b/tests/tcg/openrisc/test_mul.c
@@ -0,0 +1,61 @@
+#include <stdio.h>
+
+int main(void)
+{
+    int a, b, c;
+    int result;
+
+    b = 0x4;
+    c = 0x1;
+    result = 0x4;
+    __asm
+    ("l.mul    %0, %1, %2\n\t"
+     : "=r"(a)
+     : "r"(b), "r"(c)
+    );
+    if (a != result) {
+        printf("mul error\n");
+        return -1;
+    }
+
+    b = 0x1;
+    c = 0x0;
+    result = 0x0;
+    __asm
+    ("l.mul    %0, %1, %2\n\t"
+     : "=r"(a)
+     : "r"(b), "r"(c)
+    );
+    if (a != result) {
+        printf("mul error\n");
+        return -1;
+    }
+
+    b = 0x1;
+    c = 0xff;
+    result = 0xff;
+    __asm
+    ("l.mul    %0, %1, %2\n\t"
+     : "=r"(a)
+     : "r"(b), "r"(c)
+    );
+    if (a != result) {
+        printf("mul error\n");
+        return -1;
+    }
+
+    b = 0x7fffffff;
+    c = 0x2;
+    result = 0xfffffffe;
+    __asm
+    ("l.mul    %0, %1, %2\n\t"
+     : "=r"(a)
+     : "r"(b), "r"(c)
+    );
+    if (a != result) {
+        printf("mul error\n");
+        return -1;
+    }
+
+    return 0;
+}
diff --git a/tests/tcg/openrisc/test_muli.c b/tests/tcg/openrisc/test_muli.c
new file mode 100644
index 0000000..f1042e9
--- /dev/null
+++ b/tests/tcg/openrisc/test_muli.c
@@ -0,0 +1,48 @@
+#include <stdio.h>
+
+int main(void)
+{
+    int a, b, c;
+    int result;
+
+    b = 0x4;
+    c = 0x1;
+    result = 0x4;
+    __asm
+    ("l.muli    %0, %1, 0x1\n\t"
+     : "=r"(a)
+     : "r"(b)
+    );
+    if (a != result) {
+        printf("muli error\n");
+        return -1;
+    }
+
+    b = 0x1;
+    c = 0x0;
+    result = 0x0;
+    __asm
+    ("l.muli    %0, %1, 0x0\n\t"
+     : "=r"(a)
+     : "r"(b)
+    );
+    if (a != result) {
+        printf("muli error\n");
+        return -1;
+    }
+
+    b = 0x1;
+    c = 0xff;
+    result = 0xff;
+    __asm
+    ("l.muli    %0, %1, 0xff\n\t"
+     : "=r"(a)
+     : "r"(b)
+    );
+    if (a != result) {
+        printf("muli error\n");
+        return -1;
+    }
+
+    return 0;
+}
diff --git a/tests/tcg/openrisc/test_mulu.c b/tests/tcg/openrisc/test_mulu.c
new file mode 100644
index 0000000..2d1e97d
--- /dev/null
+++ b/tests/tcg/openrisc/test_mulu.c
@@ -0,0 +1,48 @@
+#include <stdio.h>
+
+int main(void)
+{
+    int a, b, c;
+    int result;
+
+    b = 0x4;
+    c = 0x1;
+    result = 0x4;
+    __asm
+    ("l.mulu    %0, %1, %2\n\t"
+     : "=r"(a)
+     : "r"(b), "r"(c)
+    );
+    if (a != result) {
+        printf("mulu error\n");
+        return -1;
+    }
+
+    b = 0x1;
+    c = 0x0;
+    result = 0x0;
+    __asm
+    ("l.mulu    %0, %1, %2\n\t"
+     : "=r"(a)
+     : "r"(b), "r"(c)
+    );
+    if (a != result) {
+        printf("mulu error\n");
+        return -1;
+    }
+
+    b = 0x1;
+    c = 0xff;
+    result = 0xff;
+    __asm
+    ("l.mulu    %0, %1, %2\n\t"
+     : "=r"(a)
+     : "r"(b), "r"(c)
+    );
+    if (a != result) {
+        printf("mulu error\n");
+        return -1;
+    }
+
+    return 0;
+}
diff --git a/tests/tcg/openrisc/test_sfeq.c b/tests/tcg/openrisc/test_sfeq.c
new file mode 100644
index 0000000..bd7f875
--- /dev/null
+++ b/tests/tcg/openrisc/test_sfeq.c
@@ -0,0 +1,43 @@
+#include <stdio.h>
+
+int main(void)
+{
+    int a, b;
+    int result;
+
+    a = 0x1;
+    b = 0x80;
+    result = 0x2;
+    __asm
+    ("1:\n\t"
+     "l.addi   %0, %0, 0x1\n\t"
+     "l.sfeq   %0, %1\n\t"
+     "l.bf     1b\n\t"
+     "l.nop\n\t"
+     : "+r"(a)
+     : "r"(b)
+    );
+    if (a != result) {
+        printf("sfeq error\n");
+        return -1;
+    }
+
+    a = 0x7f;
+    b = 0x80;
+    result = 0x81;
+    __asm
+    ("2:\n\t"
+     "l.addi   %0, %0, 0x1\n\t"
+     "l.sfeq   %0, %1\n\t"
+     "l.bf     2b\n\t"
+     "l.nop\n\t"
+     : "+r"(a)
+     : "r"(b)
+    );
+    if (a != result) {
+        printf("sfeq error\n");
+        return -1;
+    }
+
+    return 0;
+}
diff --git a/tests/tcg/openrisc/test_sfeqi.c b/tests/tcg/openrisc/test_sfeqi.c
new file mode 100644
index 0000000..5742613
--- /dev/null
+++ b/tests/tcg/openrisc/test_sfeqi.c
@@ -0,0 +1,39 @@
+#include <stdio.h>
+
+int main(void)
+{
+    int a;
+    int result;
+
+    a = 1;
+    result = 2;
+    __asm
+    ("1:\n\t"
+     "l.addi    %0, %0, 0x1\n\t"
+     "l.sfeqi   %0, 0x80\n\t"
+     "l.bf      1b\n\t"
+     "l.nop\n\t"
+     : "+r"(a)
+    );
+    if (a != result) {
+        printf("sfeqi error\n");
+        return -1;
+    }
+
+    a = 0x7f;
+    result = 0x81;
+    __asm
+    ("2:\n\t"
+     "l.addi    %0, %0, 0x1\n\t"
+     "l.sfeqi   %0, 0x80\n\t"
+     "l.bf      2b\n\t"
+     "l.nop\n\t"
+     : "+r"(a)
+    );
+    if (a != result) {
+        printf("sfeqi error\n");
+        return -1;
+    }
+
+    return 0;
+}
diff --git a/tests/tcg/openrisc/test_sfges.c b/tests/tcg/openrisc/test_sfges.c
new file mode 100644
index 0000000..23761d7
--- /dev/null
+++ b/tests/tcg/openrisc/test_sfges.c
@@ -0,0 +1,44 @@
+#include <stdio.h>
+
+int main(void)
+{
+    int a, b, c;
+    int result;
+
+    a = 0;
+    b = 3;
+    result = 1;
+    __asm
+    ("1:\n\t"
+     "l.addi   %0, %0, 1\n\t"
+     "l.sfges  %0, %1\n\t"
+     "l.bf 1b\n\t"
+     "l.nop\n\t"
+     : "+r"(a)
+     : "r"(b)
+    );
+    if (a != result) {
+        printf("sfges error\n");
+        return -1;
+    }
+
+    a = 0xff;
+    b = 3;
+    c = 0x1;
+    result = 2;
+    __asm
+    ("1:\n\t"
+     "l.sub    %0, %0, %2\n\t"
+     "l.sfges  %0, %1\n\t"
+     "l.bf 1b\n\t"
+     "l.nop\n\t"
+     : "+r"(a)
+     : "r"(b), "r"(c)
+    );
+    if (a != result) {
+        printf("sfges error\n");
+        return -1;
+    }
+
+    return 0;
+}
diff --git a/tests/tcg/openrisc/test_sfgesi.c b/tests/tcg/openrisc/test_sfgesi.c
new file mode 100644
index 0000000..54a2d51
--- /dev/null
+++ b/tests/tcg/openrisc/test_sfgesi.c
@@ -0,0 +1,40 @@
+#include <stdio.h>
+int main(void)
+{
+    int a, b;
+    int result;
+
+    a = 0;
+    result = 1;
+    __asm
+    ("1:\n\t"
+     "l.addi   %0, %0, 1\n\t"
+     "l.sfgesi %0, 0x3\n\t"
+     "l.bf 1b\n\t"
+     "l.nop\n\t"
+     : "+r"(a)
+    );
+    if (a != result) {
+        printf("sfgesi error\n");
+        return -1;
+    }
+
+    a = 0xff;
+    b = 1;
+    result = 2;
+    __asm
+    ("1:\n\t"
+     "l.sub    %0, %0, %1\n\t"
+     "l.sfgesi %0, 0x3\n\t"
+     "l.bf 1b\n\t"
+     "l.nop\n\t"
+     : "+r"(a)
+     : "r"(b)
+    );
+    if (a != result) {
+        printf("sfgesi error\n");
+        return -1;
+    }
+
+    return 0;
+}
diff --git a/tests/tcg/openrisc/test_sfgeu.c b/tests/tcg/openrisc/test_sfgeu.c
new file mode 100644
index 0000000..2a491d9
--- /dev/null
+++ b/tests/tcg/openrisc/test_sfgeu.c
@@ -0,0 +1,44 @@
+#include <stdio.h>
+
+int main(void)
+{
+    int a, b, c;
+    int result;
+
+    a = 0;
+    b = 3;
+    result = 1;
+    __asm
+    ("1:\n\t"
+     "l.addi   %0, %0, 1\n\t"
+     "l.sfgeu  %0, %1\n\t"
+     "l.bf 1b\n\t"
+     "l.nop\n\t"
+     : "+r"(a)
+     : "r"(b)
+    );
+    if (a != result) {
+        printf("sfgeu error\n");
+        return -1;
+    }
+
+    a = 0xff;
+    b = 3;
+    c = 1;
+    result = 2;
+    __asm
+    ("1:\n\t"
+     "l.sub    %0, %0, %2\n\t"
+     "l.sfgeu  %0, %1\n\t"
+     "l.bf 1b\n\t"
+     "l.nop\n\t"
+     : "+r"(a)
+     : "r"(b), "r"(c)
+    );
+    if (a != result) {
+        printf("sfgeu error\n");
+        return -1;
+    }
+
+    return 0;
+}
diff --git a/tests/tcg/openrisc/test_sfgeui.c b/tests/tcg/openrisc/test_sfgeui.c
new file mode 100644
index 0000000..40af35c
--- /dev/null
+++ b/tests/tcg/openrisc/test_sfgeui.c
@@ -0,0 +1,41 @@
+#include <stdio.h>
+
+int main(void)
+{
+    int a, b;
+    int result;
+
+    a = 0;
+    result = 1;
+    __asm
+    ("1:\n\t"
+     "l.addi   %0, %0, 1\n\t"
+     "l.sfgeui %0, 0x3\n\t"
+     "l.bf 1b\n\t"
+     "l.nop\n\t"
+     : "+r"(a)
+    );
+    if (a != result) {
+        printf("sfgeui error\n");
+        return -1;
+    }
+
+    a = 0xff;
+    b = 1;
+    result = 2;
+    __asm
+    ("1:\n\t"
+     "l.sub    %0, %0, %1\n\t"
+     "l.sfgeui %0, 0x3\n\t"
+     "l.bf 1b\n\t"
+     "l.nop\n\t"
+     : "+r"(a)
+     : "r"(b)
+    );
+    if (a != result) {
+        printf("sfgeui error\n");
+        return -1;
+    }
+
+    return 0;
+}
diff --git a/tests/tcg/openrisc/test_sfgts.c b/tests/tcg/openrisc/test_sfgts.c
new file mode 100644
index 0000000..4481a9c
--- /dev/null
+++ b/tests/tcg/openrisc/test_sfgts.c
@@ -0,0 +1,45 @@
+#include <stdio.h>
+
+int main(void)
+{
+    int a, b, c;
+    int result;
+
+    a = 0;
+    b = 3;
+    result = 1;
+    __asm
+    ("1:\n\t"
+     "l.addi   %0, %0, 1\n\t"
+     "l.sfgts  %0, %1\n\t"
+     "l.bf 1b\n\t"
+     "l.nop\n\t"
+     : "+r"(a)
+     : "r"(b)
+    );
+    if (a != result) {
+        printf("sfgts error\n");
+        return -1;
+    }
+
+
+    a = 0xff;
+    b = 3;
+    c = 1;
+    result = 3;
+    __asm
+    ("1:\n\t"
+     "l.sub    %0, %0, %2\n\t"
+     "l.sfgts  %0, %1\n\t"
+     "l.bf 1b\n\t"
+     "l.nop\n\t"
+     : "+r"(a)
+     : "r"(b), "r"(c)
+    );
+    if (a != result) {
+        printf("sfgts error\n");
+        return -1;
+    }
+
+    return 0;
+}
diff --git a/tests/tcg/openrisc/test_sfgtsi.c b/tests/tcg/openrisc/test_sfgtsi.c
new file mode 100644
index 0000000..7366e12
--- /dev/null
+++ b/tests/tcg/openrisc/test_sfgtsi.c
@@ -0,0 +1,41 @@
+#include <stdio.h>
+
+int main(void)
+{
+    int a, b;
+    int result;
+
+    a = 0;
+    result = 1;
+    __asm
+    ("1:\n\t"
+     "l.addi   %0, %0, 1\n\t"
+     "l.sfgtsi %0, 0x3\n\t"
+     "l.bf 1b\n\t"
+     "l.nop\n\t"
+     : "+r"(a)
+    );
+    if (a != result) {
+        printf("sfgtsi error\n");
+        return -1;
+    }
+
+    a = 0xff;
+    b = 1;
+    result = 3;
+    __asm
+    ("1:\n\t"
+     "l.sub    %0, %0, %1\n\t"
+     "l.sfgtsi %0, 0x3\n\t"
+     "l.bf 1b\n\t"
+     "l.nop\n\t"
+     : "+r"(a)
+     : "r"(b)
+    );
+    if (a != result) {
+        printf("sfgtsi error\n");
+        return -1;
+    }
+
+    return 0;
+}
diff --git a/tests/tcg/openrisc/test_sfgtu.c b/tests/tcg/openrisc/test_sfgtu.c
new file mode 100644
index 0000000..da28689
--- /dev/null
+++ b/tests/tcg/openrisc/test_sfgtu.c
@@ -0,0 +1,43 @@
+#include <stdio.h>
+int main(void)
+{
+    int a, b, c;
+    int result;
+
+    a = 0;
+    b = 3;
+    result = 1;
+    __asm
+    ("1:\n\t"
+     "l.addi %0, %0, 1\n\t"
+     "l.sfgtu %0, %1\n\t"
+     "l.bf 1b\n\t"
+     "l.nop\n\t"
+     : "+r"(a)
+     : "r"(b)
+    );
+    if (a != result) {
+        printf("sfgtu error\n");
+        return -1;
+    }
+
+    a = 0xff;
+    b = 3;
+    c = 1;
+    result = 3;
+    __asm
+    ("1:\n\t"
+     "l.sub    %0, %0, %2\n\t"
+     "l.sfgtu  %0, %1\n\t"
+     "l.bf 1b\n\t"
+     "l.nop\n\t"
+     : "+r"(a)
+     : "r"(b), "r"(c)
+    );
+    if (a != result) {
+        printf("sfgtu error\n");
+        return -1;
+    }
+
+    return 0;
+}
diff --git a/tests/tcg/openrisc/test_sfgtui.c b/tests/tcg/openrisc/test_sfgtui.c
new file mode 100644
index 0000000..565d44f
--- /dev/null
+++ b/tests/tcg/openrisc/test_sfgtui.c
@@ -0,0 +1,42 @@
+#include <stdio.h>
+
+int main(void)
+{
+    int a, b;
+    int result;
+
+    a = 0;
+    result = 1;
+    __asm
+    ("1:\n\t"
+     "l.addi   %0, %0, 1\n\t"
+     "l.sfgtui %0, 0x3\n\t"
+     "l.bf 1b\n\t"
+     "l.nop\n\t"
+     : "+r"(a)
+    );
+    if (a != result) {
+        printf("sfgtui error\n");
+        return -1;
+    }
+
+
+    a = 0xff;
+    b = 1;
+    result = 3;
+    __asm
+    ("1:\n\t"
+     "l.sub     %0, %0, %1\n\t"
+     "l.sfgtui  %0, 0x3\n\t"
+     "l.bf 1b\n\t"
+     "l.nop\n\t"
+     : "+r"(a)
+     : "r"(b)
+    );
+    if (a != result) {
+        printf("sfgtui error\n");
+        return -1;
+    }
+
+    return 0;
+}
diff --git a/tests/tcg/openrisc/test_sfles.c b/tests/tcg/openrisc/test_sfles.c
new file mode 100644
index 0000000..f573522
--- /dev/null
+++ b/tests/tcg/openrisc/test_sfles.c
@@ -0,0 +1,26 @@
+#include <stdio.h>
+
+int main(void)
+{
+    int a, b;
+    int result;
+
+    a = 0;
+    b = 3;
+    result = 4;
+    __asm
+    ("1:\n\t"
+     "l.addi   %0, %0, 4\n\t"
+     "l.sfles  %0, %1\n\t"
+     "l.bf 1b\n\t"
+     "l.nop\n\t"
+     : "+r"(a)
+     : "r"(b)
+    );
+    if (a != result) {
+        printf("sfles error\n");
+        return -1;
+    }
+
+    return 0;
+}
diff --git a/tests/tcg/openrisc/test_sflesi.c b/tests/tcg/openrisc/test_sflesi.c
new file mode 100644
index 0000000..16fe605
--- /dev/null
+++ b/tests/tcg/openrisc/test_sflesi.c
@@ -0,0 +1,39 @@
+#include <stdio.h>
+
+int main(void)
+{
+    int a;
+    int result;
+
+    a = 0;
+    result = 4;
+    __asm
+    ("1:\n\t"
+     "l.addi   %0, %0, 4\n\t"
+     "l.sflesi %0, 0x3\n\t"
+     "l.bf 1b\n\t"
+     "l.nop\n\t"
+     : "+r"(a)
+    );
+    if (a != result) {
+        printf("sflesi error\n");
+        return -1;
+    }
+
+    a = 0;
+    result = 4;
+    __asm
+    ("1:\n\t"
+     "l.addi   %0, %0, 1\n\t"
+     "l.sflesi %0, 0x3\n\t"
+     "l.bf 1b\n\t"
+     "l.nop\n\t"
+     : "+r"(a)
+    );
+    if (a != result) {
+        printf("sflesi error\n");
+        return -1;
+    }
+
+    return 0;
+}
diff --git a/tests/tcg/openrisc/test_sfleu.c b/tests/tcg/openrisc/test_sfleu.c
new file mode 100644
index 0000000..be0a3c3
--- /dev/null
+++ b/tests/tcg/openrisc/test_sfleu.c
@@ -0,0 +1,43 @@
+#include <stdio.h>
+
+int main(void)
+{
+    int a, b;
+    int result;
+
+    a = 0;
+    b = 3;
+    result = 4;
+    __asm
+    ("1:\n\t"
+     "l.addi   %0, %0, 4\n\t"
+     "l.sfleu  %0, %1\n\t"
+     "l.bf 1b\n\t"
+     "l.nop\n\t"
+     : "+r"(a)
+     : "r"(b)
+    );
+    if (a != result) {
+        printf("sfleu error\n");
+        return -1;
+    }
+
+    a = 0;
+    b = 3;
+    result = 4;
+    __asm
+    ("1:\n\t"
+     "l.addi   %0, %0, 1\n\t"
+     "l.sfleu  %0, %1\n\t"
+     "l.bf 1b\n\t"
+     "l.nop\n\t"
+     : "+r"(a)
+     : "r"(b)
+    );
+    if (a != result) {
+        printf("sfleu error\n");
+        return -1;
+    }
+
+    return 0;
+}
diff --git a/tests/tcg/openrisc/test_sfleui.c b/tests/tcg/openrisc/test_sfleui.c
new file mode 100644
index 0000000..38d3c89
--- /dev/null
+++ b/tests/tcg/openrisc/test_sfleui.c
@@ -0,0 +1,39 @@
+#include <stdio.h>
+
+int main(void)
+{
+    int a;
+    int result;
+
+    a = 0;
+    result = 4;
+    __asm
+    ("1:\n\t"
+     "l.addi   %0, %0, 4\n\t"
+     "l.sfleui %0, 0x3\n\t"
+     "l.bf 1b\n\t"
+     "l.nop\n\t"
+     : "+r"(a)
+    );
+    if (a != result) {
+        printf("sfleui error\n");
+        return -1;
+    }
+
+    a = 0;
+    result = 4;
+    __asm
+    ("1:\n\t"
+     "l.addi   %0, %0, 1\n\t"
+     "l.sfleui %0, 0x3\n\t"
+     "l.bf 1b\n\t"
+     "l.nop\n\t"
+     : "+r"(a)
+    );
+    if (a != result) {
+        printf("sfleui error\n");
+        return -1;
+    }
+
+    return 0;
+}
diff --git a/tests/tcg/openrisc/test_sflts.c b/tests/tcg/openrisc/test_sflts.c
new file mode 100644
index 0000000..7deeb48
--- /dev/null
+++ b/tests/tcg/openrisc/test_sflts.c
@@ -0,0 +1,43 @@
+#include <stdio.h>
+
+int main(void)
+{
+    int a, b;
+    int result;
+
+    a = 0;
+    b = 3;
+    result = 4;
+    __asm
+    ("1:\n\t"
+     "l.addi   %0, %0, 4\n\t"
+     "l.sflts  %0, %1\n\t"
+     "l.bf 1b\n\t"
+     "l.nop\n\t"
+     : "+r"(a)
+     : "r"(b)
+    );
+    if (a != result) {
+        printf("sflts error\n");
+        return -1;
+    }
+
+    a = 0;
+    b = 3;
+    result = 3;
+    __asm
+    ("1:\n\t"
+     "l.addi    %0, %0, 1\n\t"
+     "l.sflts   %0, %1\n\t"
+     "l.bf 1b\n\t"
+     "l.nop\n\t"
+     : "+r"(a)
+     : "r"(b)
+    );
+    if (a != result) {
+        printf("sflts error\n");
+        return -1;
+    }
+
+    return 0;
+}
diff --git a/tests/tcg/openrisc/test_sfltsi.c b/tests/tcg/openrisc/test_sfltsi.c
new file mode 100644
index 0000000..3cb1f02
--- /dev/null
+++ b/tests/tcg/openrisc/test_sfltsi.c
@@ -0,0 +1,39 @@
+#include <stdio.h>
+
+int main(void)
+{
+    int a;
+    int result;
+
+    a = 0;
+    result = 4;
+    __asm
+    ("1:\n\t"
+     "l.addi   %0, %0, 4\n\t"
+     "l.sfltsi %0, 0x3\n\t"
+     "l.bf 1b\n\t"
+     "l.nop\n\t"
+     : "+r"(a)
+    );
+    if (a != result) {
+        printf("sfltsi error\n");
+        return -1;
+    }
+
+    a = 0;
+    result = 3;
+    __asm
+    ("1:\n\t"
+     "l.addi    %0, %0, 1\n\t"
+     "l.sfltsi  %0, 0x3\n\t"
+     "l.bf 1b\n\t"
+     "l.nop\n\t"
+     : "+r"(a)
+    );
+    if (a != result) {
+        printf("sfltsi error\n");
+        return -1;
+    }
+
+    return 0;
+}
diff --git a/tests/tcg/openrisc/test_sfltu.c b/tests/tcg/openrisc/test_sfltu.c
new file mode 100644
index 0000000..7ed3b26
--- /dev/null
+++ b/tests/tcg/openrisc/test_sfltu.c
@@ -0,0 +1,43 @@
+#include <stdio.h>
+
+int main(void)
+{
+    int a, b;
+    int result;
+
+    a = 0;
+    b = 3;
+    result = 4;
+    __asm
+    ("1:\n\t"
+     "l.addi   %0, %0, 4\n\t"
+     "l.sfltu  %0, %1\n\t"
+     "l.bf 1b\n\t"
+     "l.nop\n\t"
+     : "+r"(a)
+     : "r"(b)
+    );
+    if (a != result) {
+        printf("sfltu error\n");
+        return -1;
+    }
+
+    a = 0;
+    b = 3;
+    result = 3;
+    __asm
+    ("1:\n\t"
+     "l.addi    %0, %0, 1\n\t"
+     "l.sfltu  %0, %1\n\t"
+     "l.bf 1b\n\t"
+     "l.nop\n\t"
+     : "+r"(a)
+     : "r"(b)
+    );
+    if (a != result) {
+        printf("sfltu error\n");
+        return -1;
+    }
+
+    return 0;
+}
diff --git a/tests/tcg/openrisc/test_sfltui.c b/tests/tcg/openrisc/test_sfltui.c
new file mode 100644
index 0000000..a5cb9f6
--- /dev/null
+++ b/tests/tcg/openrisc/test_sfltui.c
@@ -0,0 +1,39 @@
+#include <stdio.h>
+
+int main(void)
+{
+    int a;
+    int result;
+
+    a = 0;
+    result = 4;
+    __asm
+    ("1:\n\t"
+     "l.addi   %0, %0, 4\n\t"
+     "l.sfltsi %0, 0x3\n\t"
+     "l.bf 1b\n\t"
+     "l.nop\n\t"
+     : "+r"(a)
+    );
+    if (a != result) {
+        printf("sfltui error\n");
+        return -1;
+    }
+
+    a = 0;
+    result = 3;
+    __asm
+    ("1:\n\t"
+     "l.addi    %0, %0, 1\n\t"
+     "l.sfltsi %0, 0x3\n\t"
+     "l.bf 1b\n\t"
+     "l.nop\n\t"
+     : "+r"(a)
+    );
+    if (a != result) {
+        printf("sfltui error\n");
+        return -1;
+    }
+
+    return 0;
+}
diff --git a/tests/tcg/openrisc/test_sfne.c b/tests/tcg/openrisc/test_sfne.c
new file mode 100644
index 0000000..b33a35c
--- /dev/null
+++ b/tests/tcg/openrisc/test_sfne.c
@@ -0,0 +1,43 @@
+#include <stdio.h>
+
+int main(void)
+{
+    int a, b;
+    int result;
+
+    a = 0;
+    b = 3;
+    result = 3;
+    __asm
+    ("1:\n\t"
+     "l.addi   %0, %0, 3\n\t"
+     "l.sfne   %0, %1\n\t"
+     "l.bf 1b\n\t"
+     "l.nop\n\t"
+     : "+r"(a)
+     : "r"(b)
+    );
+    if (a != result) {
+        printf("sfne error\n");
+        return -1;
+    }
+
+    a = 0;
+    b = 3;
+    result = 3;
+    __asm
+    ("1:\n\t"
+     "l.addi   %0, %0, 1\n\t"
+     "l.sfne   %0, %1\n\t"
+     "l.bf 1b\n\t"
+     "l.nop\n\t"
+     : "+r"(a)
+     : "r"(b)
+    );
+    if (a != result) {
+        printf("sfne error\n");
+        return -1;
+    }
+
+    return 0;
+}
diff --git a/tests/tcg/openrisc/test_sfnei.c b/tests/tcg/openrisc/test_sfnei.c
new file mode 100644
index 0000000..d311c9e
--- /dev/null
+++ b/tests/tcg/openrisc/test_sfnei.c
@@ -0,0 +1,39 @@
+#include <stdio.h>
+
+int main(void)
+{
+    int a;
+    int result;
+
+    a = 0;
+    result = 3;
+    __asm
+    ("1:\n\t"
+     "l.addi   %0, %0, 3\n\t"
+     "l.sfnei  %0, 0x3\n\t"
+     "l.bf 1b\n\t"
+     "l.nop\n\t"
+     : "+r"(a)
+    );
+    if (a != result) {
+        printf("sfnei error\n");
+        return -1;
+    }
+
+    a = 0;
+    result = 3;
+    __asm
+    ("1:\n\t"
+     "l.addi   %0, %0, 1\n\t"
+     "l.sfnei  %0, 0x3\n\t"
+     "l.bf 1b\n\t"
+     "l.nop\n\t"
+     : "+r"(a)
+    );
+    if (a != result) {
+        printf("sfnei error\n");
+        return -1;
+    }
+
+    return 0;
+}
diff --git a/tests/tcg/openrisc/test_sub.c b/tests/tcg/openrisc/test_sub.c
new file mode 100644
index 0000000..474ec60
--- /dev/null
+++ b/tests/tcg/openrisc/test_sub.c
@@ -0,0 +1,35 @@
+#include <stdio.h>
+
+int main(void)
+{
+    int a, b;
+    int result;
+
+    a = 0x100;
+    b = 0x100;
+    result = 0x0;
+    __asm
+    ("l.sub %0, %0, %1\n\t"
+     : "+r"(a)
+     : "r"(b)
+    );
+    if (a != result) {
+        printf("sub error\n");
+        return -1;
+    }
+
+    a = 0xffff;
+    b = 0x1;
+    result = 0xfffe;
+    __asm
+    ("l.sub %0, %0, %1\n\t"
+     : "+r"(a)
+     : "r"(b)
+    );
+    if (a != result) {
+        printf("sub error\n");
+        return -1;
+    }
+
+    return 0;
+}
commit d962783e9849acf8eb329abd319a5baab28e4f62
Author: Jia Liu <proljc at gmail.com>
Date:   Fri Jul 20 15:50:52 2012 +0800

    target-or32: Add linux user support
    
    Add QEMU OpenRISC linux user support.
    
    Signed-off-by: Jia Liu <proljc at gmail.com>
    Signed-off-by: Blue Swirl <blauwirbel at gmail.com>

diff --git a/configure b/configure
index ec8b049..c65b5f6 100755
--- a/configure
+++ b/configure
@@ -951,6 +951,7 @@ microblaze-linux-user \
 microblazeel-linux-user \
 mips-linux-user \
 mipsel-linux-user \
+or32-linux-user \
 ppc-linux-user \
 ppc64-linux-user \
 ppc64abi32-linux-user \
diff --git a/default-configs/or32-linux-user.mak b/default-configs/or32-linux-user.mak
new file mode 100644
index 0000000..808c1f9
--- /dev/null
+++ b/default-configs/or32-linux-user.mak
@@ -0,0 +1 @@
+# Default configuration for or32-linux-user
diff --git a/linux-user/elfload.c b/linux-user/elfload.c
index f3b1552..6b622d4 100644
--- a/linux-user/elfload.c
+++ b/linux-user/elfload.c
@@ -787,6 +787,47 @@ static void elf_core_copy_regs(target_elf_gregset_t *regs, const CPUMBState *env
 
 #endif /* TARGET_MICROBLAZE */
 
+#ifdef TARGET_OPENRISC
+
+#define ELF_START_MMAP 0x08000000
+
+#define elf_check_arch(x) ((x) == EM_OPENRISC)
+
+#define ELF_ARCH EM_OPENRISC
+#define ELF_CLASS ELFCLASS32
+#define ELF_DATA  ELFDATA2MSB
+
+static inline void init_thread(struct target_pt_regs *regs,
+                               struct image_info *infop)
+{
+    regs->pc = infop->entry;
+    regs->gpr[1] = infop->start_stack;
+}
+
+#define USE_ELF_CORE_DUMP
+#define ELF_EXEC_PAGESIZE 8192
+
+/* See linux kernel arch/openrisc/include/asm/elf.h.  */
+#define ELF_NREG 34 /* gprs and pc, sr */
+typedef target_elf_greg_t target_elf_gregset_t[ELF_NREG];
+
+static void elf_core_copy_regs(target_elf_gregset_t *regs,
+                               const CPUOpenRISCState *env)
+{
+    int i;
+
+    for (i = 0; i < 32; i++) {
+        (*regs)[i] = tswapl(env->gpr[i]);
+    }
+
+    (*regs)[32] = tswapl(env->pc);
+    (*regs)[33] = tswapl(env->sr);
+}
+#define ELF_HWCAP 0
+#define ELF_PLATFORM NULL
+
+#endif /* TARGET_OPENRISC */
+
 #ifdef TARGET_SH4
 
 #define ELF_START_MMAP 0x80000000
diff --git a/linux-user/main.c b/linux-user/main.c
index d0e0e4f..a0ab8e8 100644
--- a/linux-user/main.c
+++ b/linux-user/main.c
@@ -2306,6 +2306,93 @@ done_syscall:
 }
 #endif
 
+#ifdef TARGET_OPENRISC
+
+void cpu_loop(CPUOpenRISCState *env)
+{
+    int trapnr, gdbsig;
+
+    for (;;) {
+        trapnr = cpu_exec(env);
+        gdbsig = 0;
+
+        switch (trapnr) {
+        case EXCP_RESET:
+            qemu_log("\nReset request, exit, pc is %#x\n", env->pc);
+            exit(1);
+            break;
+        case EXCP_BUSERR:
+            qemu_log("\nBus error, exit, pc is %#x\n", env->pc);
+            gdbsig = SIGBUS;
+            break;
+        case EXCP_DPF:
+        case EXCP_IPF:
+            cpu_dump_state(env, stderr, fprintf, 0);
+            gdbsig = TARGET_SIGSEGV;
+            break;
+        case EXCP_TICK:
+            qemu_log("\nTick time interrupt pc is %#x\n", env->pc);
+            break;
+        case EXCP_ALIGN:
+            qemu_log("\nAlignment pc is %#x\n", env->pc);
+            gdbsig = SIGBUS;
+            break;
+        case EXCP_ILLEGAL:
+            qemu_log("\nIllegal instructionpc is %#x\n", env->pc);
+            gdbsig = SIGILL;
+            break;
+        case EXCP_INT:
+            qemu_log("\nExternal interruptpc is %#x\n", env->pc);
+            break;
+        case EXCP_DTLBMISS:
+        case EXCP_ITLBMISS:
+            qemu_log("\nTLB miss\n");
+            break;
+        case EXCP_RANGE:
+            qemu_log("\nRange\n");
+            gdbsig = SIGSEGV;
+            break;
+        case EXCP_SYSCALL:
+            env->pc += 4;   /* 0xc00; */
+            env->gpr[11] = do_syscall(env,
+                                      env->gpr[11], /* return value       */
+                                      env->gpr[3],  /* r3 - r7 are params */
+                                      env->gpr[4],
+                                      env->gpr[5],
+                                      env->gpr[6],
+                                      env->gpr[7],
+                                      env->gpr[8], 0, 0);
+            break;
+        case EXCP_FPE:
+            qemu_log("\nFloating point error\n");
+            break;
+        case EXCP_TRAP:
+            qemu_log("\nTrap\n");
+            gdbsig = SIGTRAP;
+            break;
+        case EXCP_NR:
+            qemu_log("\nNR\n");
+            break;
+        default:
+            qemu_log("\nqemu: unhandled CPU exception %#x - aborting\n",
+                     trapnr);
+            cpu_dump_state(env, stderr, fprintf, 0);
+            gdbsig = TARGET_SIGILL;
+            break;
+        }
+        if (gdbsig) {
+            gdb_handlesig(env, gdbsig);
+            if (gdbsig != TARGET_SIGTRAP) {
+                exit(1);
+            }
+        }
+
+        process_pending_signals(env);
+    }
+}
+
+#endif /* TARGET_OPENRISC */
+
 #ifdef TARGET_SH4
 void cpu_loop(CPUSH4State *env)
 {
@@ -3386,6 +3473,8 @@ int main(int argc, char **argv, char **envp)
 #else
         cpu_model = "24Kf";
 #endif
+#elif defined TARGET_OPENRISC
+        cpu_model = "or1200";
 #elif defined(TARGET_PPC)
 #ifdef TARGET_PPC64
         cpu_model = "970fx";
@@ -3788,6 +3877,17 @@ int main(int argc, char **argv, char **envp)
             env->hflags |= MIPS_HFLAG_M16;
         }
     }
+#elif defined(TARGET_OPENRISC)
+    {
+        int i;
+
+        for (i = 0; i < 32; i++) {
+            env->gpr[i] = regs->gpr[i];
+        }
+
+        env->sr = regs->sr;
+        env->pc = regs->pc;
+    }
 #elif defined(TARGET_SH4)
     {
         int i;
diff --git a/linux-user/signal.c b/linux-user/signal.c
index 43346dc..97f30d9 100644
--- a/linux-user/signal.c
+++ b/linux-user/signal.c
@@ -3629,6 +3629,235 @@ long do_rt_sigreturn(CPUCRISState *env)
     return -TARGET_ENOSYS;
 }
 
+#elif defined(TARGET_OPENRISC)
+
+struct target_sigcontext {
+    struct target_pt_regs regs;
+    abi_ulong oldmask;
+    abi_ulong usp;
+};
+
+struct target_ucontext {
+    abi_ulong tuc_flags;
+    abi_ulong tuc_link;
+    target_stack_t tuc_stack;
+    struct target_sigcontext tuc_mcontext;
+    target_sigset_t tuc_sigmask;   /* mask last for extensibility */
+};
+
+struct target_rt_sigframe {
+    abi_ulong pinfo;
+    uint64_t puc;
+    struct target_siginfo info;
+    struct target_sigcontext sc;
+    struct target_ucontext uc;
+    unsigned char retcode[16];  /* trampoline code */
+};
+
+/* This is the asm-generic/ucontext.h version */
+#if 0
+static int restore_sigcontext(CPUOpenRISCState *regs,
+                              struct target_sigcontext *sc)
+{
+    unsigned int err = 0;
+    unsigned long old_usp;
+
+    /* Alwys make any pending restarted system call return -EINTR */
+    current_thread_info()->restart_block.fn = do_no_restart_syscall;
+
+    /* restore the regs from &sc->regs (same as sc, since regs is first)
+     * (sc is already checked for VERIFY_READ since the sigframe was
+     *  checked in sys_sigreturn previously)
+     */
+
+    if (copy_from_user(regs, &sc, sizeof(struct target_pt_regs))) {
+        goto badframe;
+    }
+
+    /* make sure the U-flag is set so user-mode cannot fool us */
+
+    regs->sr &= ~SR_SM;
+
+    /* restore the old USP as it was before we stacked the sc etc.
+     * (we cannot just pop the sigcontext since we aligned the sp and
+     *  stuff after pushing it)
+     */
+
+    err |= __get_user(old_usp, &sc->usp);
+    phx_signal("old_usp 0x%lx", old_usp);
+
+    __PHX__ REALLY           /* ??? */
+    wrusp(old_usp);
+    regs->gpr[1] = old_usp;
+
+    /* TODO: the other ports use regs->orig_XX to disable syscall checks
+     * after this completes, but we don't use that mechanism. maybe we can
+     * use it now ?
+     */
+
+    return err;
+
+badframe:
+    return 1;
+}
+#endif
+
+/* Set up a signal frame.  */
+
+static int setup_sigcontext(struct target_sigcontext *sc,
+                            CPUOpenRISCState *regs,
+                            unsigned long mask)
+{
+    int err = 0;
+    unsigned long usp = regs->gpr[1];
+
+    /* copy the regs. they are first in sc so we can use sc directly */
+
+    /*err |= copy_to_user(&sc, regs, sizeof(struct target_pt_regs));*/
+
+    /* Set the frametype to CRIS_FRAME_NORMAL for the execution of
+       the signal handler. The frametype will be restored to its previous
+       value in restore_sigcontext. */
+    /*regs->frametype = CRIS_FRAME_NORMAL;*/
+
+    /* then some other stuff */
+    err |= __put_user(mask, &sc->oldmask);
+    err |= __put_user(usp, &sc->usp); return err;
+}
+
+static inline unsigned long align_sigframe(unsigned long sp)
+{
+    unsigned long i;
+    i = sp & ~3UL;
+    return i;
+}
+
+static inline abi_ulong get_sigframe(struct target_sigaction *ka,
+                                     CPUOpenRISCState *regs,
+                                     size_t frame_size)
+{
+    unsigned long sp = regs->gpr[1];
+    int onsigstack = on_sig_stack(sp);
+
+    /* redzone */
+    /* This is the X/Open sanctioned signal stack switching.  */
+    if ((ka->sa_flags & SA_ONSTACK) != 0 && !onsigstack) {
+        sp = target_sigaltstack_used.ss_sp + target_sigaltstack_used.ss_size;
+    }
+
+    sp = align_sigframe(sp - frame_size);
+
+    /*
+     * If we are on the alternate signal stack and would overflow it, don't.
+     * Return an always-bogus address instead so we will die with SIGSEGV.
+     */
+
+    if (onsigstack && !likely(on_sig_stack(sp))) {
+        return -1L;
+    }
+
+    return sp;
+}
+
+static void setup_frame(int sig, struct target_sigaction *ka,
+                        target_sigset_t *set, CPUOpenRISCState *env)
+{
+    qemu_log("Not implement.\n");
+}
+
+static void setup_rt_frame(int sig, struct target_sigaction *ka,
+                           target_siginfo_t *info,
+                           target_sigset_t *set, CPUOpenRISCState *env)
+{
+    int err = 0;
+    abi_ulong frame_addr;
+    unsigned long return_ip;
+    struct target_rt_sigframe *frame;
+    abi_ulong info_addr, uc_addr;
+
+    frame_addr = get_sigframe(ka, env, sizeof *frame);
+
+    frame_addr = get_sigframe(ka, env, sizeof(*frame));
+    if (!lock_user_struct(VERIFY_WRITE, frame, frame_addr, 0)) {
+        goto give_sigsegv;
+    }
+
+    info_addr = frame_addr + offsetof(struct target_rt_sigframe, info);
+    err |= __put_user(info_addr, &frame->pinfo);
+    uc_addr = frame_addr + offsetof(struct target_rt_sigframe, uc);
+    err |= __put_user(uc_addr, &frame->puc);
+
+    if (ka->sa_flags & SA_SIGINFO) {
+        err |= copy_siginfo_to_user(&frame->info, info);
+    }
+    if (err) {
+        goto give_sigsegv;
+    }
+
+    /*err |= __clear_user(&frame->uc, offsetof(struct ucontext, uc_mcontext));*/
+    err |= __put_user(0, &frame->uc.tuc_flags);
+    err |= __put_user(0, &frame->uc.tuc_link);
+    err |= __put_user(target_sigaltstack_used.ss_sp,
+                      &frame->uc.tuc_stack.ss_sp);
+    err |= __put_user(sas_ss_flags(env->gpr[1]), &frame->uc.tuc_stack.ss_flags);
+    err |= __put_user(target_sigaltstack_used.ss_size,
+                      &frame->uc.tuc_stack.ss_size);
+    err |= setup_sigcontext(&frame->sc, env, set->sig[0]);
+
+    /*err |= copy_to_user(frame->uc.tuc_sigmask, set, sizeof(*set));*/
+
+    if (err) {
+        goto give_sigsegv;
+    }
+
+    /* trampoline - the desired return ip is the retcode itself */
+    return_ip = (unsigned long)&frame->retcode;
+    /* This is l.ori r11,r0,__NR_sigreturn, l.sys 1 */
+    err |= __put_user(0xa960, (short *)(frame->retcode + 0));
+    err |= __put_user(TARGET_NR_rt_sigreturn, (short *)(frame->retcode + 2));
+    err |= __put_user(0x20000001, (unsigned long *)(frame->retcode + 4));
+    err |= __put_user(0x15000000, (unsigned long *)(frame->retcode + 8));
+
+    if (err) {
+        goto give_sigsegv;
+    }
+
+    /* TODO what is the current->exec_domain stuff and invmap ? */
+
+    /* Set up registers for signal handler */
+    env->pc = (unsigned long)ka->_sa_handler; /* what we enter NOW */
+    env->gpr[9] = (unsigned long)return_ip;     /* what we enter LATER */
+    env->gpr[3] = (unsigned long)sig;           /* arg 1: signo */
+    env->gpr[4] = (unsigned long)&frame->info;  /* arg 2: (siginfo_t*) */
+    env->gpr[5] = (unsigned long)&frame->uc;    /* arg 3: ucontext */
+
+    /* actually move the usp to reflect the stacked frame */
+    env->gpr[1] = (unsigned long)frame;
+
+    return;
+
+give_sigsegv:
+    unlock_user_struct(frame, frame_addr, 1);
+    if (sig == TARGET_SIGSEGV) {
+        ka->_sa_handler = TARGET_SIG_DFL;
+    }
+    force_sig(TARGET_SIGSEGV);
+}
+
+long do_sigreturn(CPUOpenRISCState *env)
+{
+
+    qemu_log("do_sigreturn: not implemented\n");
+    return -TARGET_ENOSYS;
+}
+
+long do_rt_sigreturn(CPUOpenRISCState *env)
+{
+    qemu_log("do_rt_sigreturn: not implemented\n");
+    return -TARGET_ENOSYS;
+}
+/* TARGET_OPENRISC */
+
 #elif defined(TARGET_S390X)
 
 #define __NUM_GPRS 16
diff --git a/linux-user/syscall.c b/linux-user/syscall.c
index 539af3f..630a455 100644
--- a/linux-user/syscall.c
+++ b/linux-user/syscall.c
@@ -7377,7 +7377,7 @@ abi_long do_syscall(void *cpu_env, int num, abi_long arg1,
     case TARGET_NR_sigaltstack:
 #if defined(TARGET_I386) || defined(TARGET_ARM) || defined(TARGET_MIPS) || \
     defined(TARGET_SPARC) || defined(TARGET_PPC) || defined(TARGET_ALPHA) || \
-    defined(TARGET_M68K) || defined(TARGET_S390X)
+    defined(TARGET_M68K) || defined(TARGET_S390X) || defined(TARGET_OPENRISC)
         ret = do_sigaltstack(arg1, arg2, get_sp_from_cpustate((CPUArchState *)cpu_env));
         break;
 #else
diff --git a/linux-user/syscall_defs.h b/linux-user/syscall_defs.h
index a79b67d..cfece21 100644
--- a/linux-user/syscall_defs.h
+++ b/linux-user/syscall_defs.h
@@ -59,7 +59,7 @@
 
 #if defined(TARGET_I386) || defined(TARGET_ARM) || defined(TARGET_SH4) \
     || defined(TARGET_M68K) || defined(TARGET_CRIS) || defined(TARGET_UNICORE32) \
-    || defined(TARGET_S390X)
+    || defined(TARGET_S390X) || defined(TARGET_OPENRISC)
 
 #define TARGET_IOC_SIZEBITS	14
 #define TARGET_IOC_DIRBITS	2
@@ -323,7 +323,7 @@ int do_sigaction(int sig, const struct target_sigaction *act,
     || defined(TARGET_PPC) || defined(TARGET_MIPS) || defined(TARGET_SH4) \
     || defined(TARGET_M68K) || defined(TARGET_ALPHA) || defined(TARGET_CRIS) \
     || defined(TARGET_MICROBLAZE) || defined(TARGET_UNICORE32) \
-    || defined(TARGET_S390X)
+    || defined(TARGET_S390X) || defined(TARGET_OPENRISC)
 
 #if defined(TARGET_SPARC)
 #define TARGET_SA_NOCLDSTOP    8u
@@ -344,6 +344,14 @@ int do_sigaction(int sig, const struct target_sigaction *act,
 #if !defined(TARGET_ABI_MIPSN32) && !defined(TARGET_ABI_MIPSN64)
 #define TARGET_SA_RESTORER	0x04000000	/* Only for O32 */
 #endif
+#elif defined(TARGET_OPENRISC)
+#define TARGET_SA_NOCLDSTOP    0x00000001
+#define TARGET_SA_NOCLDWAIT    0x00000002
+#define TARGET_SA_SIGINFO      0x00000004
+#define TARGET_SA_ONSTACK      0x08000000
+#define TARGET_SA_RESTART      0x10000000
+#define TARGET_SA_NODEFER      0x40000000
+#define TARGET_SA_RESETHAND    0x80000000
 #elif defined(TARGET_ALPHA)
 #define TARGET_SA_ONSTACK	0x00000001
 #define TARGET_SA_RESTART	0x00000002
@@ -448,6 +456,7 @@ int do_sigaction(int sig, const struct target_sigaction *act,
 
 #else
 
+/* OpenRISC Using the general signals */
 #define TARGET_SIGHUP		 1
 #define TARGET_SIGINT		 2
 #define TARGET_SIGQUIT		 3
@@ -1086,7 +1095,8 @@ struct target_winsize {
 #endif
 
 #if (defined(TARGET_I386) && defined(TARGET_ABI32)) || defined(TARGET_ARM) \
-    || defined(TARGET_CRIS) || defined(TARGET_UNICORE32)
+    || defined(TARGET_CRIS) || defined(TARGET_UNICORE32) \
+    || defined(TARGET_OPENRISC)
 struct target_stat {
 	unsigned short st_dev;
 	unsigned short __pad1;
@@ -1783,6 +1793,30 @@ struct target_stat {
     abi_long       st_blocks;
     abi_ulong  __unused[3];
 };
+#elif defined(TARGET_OPENRISC)
+struct target_stat {
+    abi_ulong st_dev;
+    abi_ulong st_ino;
+    abi_ulong st_nlink;
+
+    unsigned int st_mode;
+    unsigned int st_uid;
+    unsigned int st_gid;
+    unsigned int __pad0;
+    abi_ulong st_rdev;
+    abi_long st_size;
+    abi_long st_blksize;
+    abi_long st_blocks;    /* Number 512-byte blocks allocated. */
+
+    abi_ulong target_st_atime;
+    abi_ulong target_st_atime_nsec;
+    abi_ulong target_st_mtime;
+    abi_ulong target_st_mtime_nsec;
+    abi_ulong target_st_ctime;
+    abi_ulong target_st_ctime_nsec;
+
+    abi_long __unused[3];
+};
 #else
 #error unsupported CPU
 #endif
diff --git a/target-openrisc/cpu.h b/target-openrisc/cpu.h
index 6506665..de21a87 100644
--- a/target-openrisc/cpu.h
+++ b/target-openrisc/cpu.h
@@ -367,11 +367,13 @@ void openrisc_translate_init(void);
 int cpu_openrisc_handle_mmu_fault(CPUOpenRISCState *env,
                                   target_ulong address,
                                   int rw, int mmu_idx);
+int cpu_openrisc_signal_handler(int host_signum, void *pinfo, void *puc);
 
 #define cpu_list cpu_openrisc_list
 #define cpu_exec cpu_openrisc_exec
 #define cpu_gen_code cpu_openrisc_gen_code
 #define cpu_handle_mmu_fault cpu_openrisc_handle_mmu_fault
+#define cpu_signal_handler cpu_openrisc_signal_handler
 
 #ifndef CONFIG_USER_ONLY
 /* hw/openrisc_pic.c */
@@ -404,6 +406,16 @@ static inline CPUOpenRISCState *cpu_init(const char *cpu_model)
     return NULL;
 }
 
+#if defined(CONFIG_USER_ONLY)
+static inline void cpu_clone_regs(CPUOpenRISCState *env, target_ulong newsp)
+{
+    if (newsp) {
+        env->gpr[1] = newsp;
+    }
+    env->gpr[2] = 0;
+}
+#endif
+
 #include "cpu-all.h"
 
 static inline void cpu_get_tb_cpu_state(CPUOpenRISCState *env,
commit a8720299f1aa5dcf7b83e78644b0f6502958e973
Author: Jia Liu <proljc at gmail.com>
Date:   Fri Jul 20 15:50:51 2012 +0800

    target-or32: Add linux syscall, signal and termbits
    
    Add OpenRISC linux syscall, signal and termbits.
    
    Signed-off-by: Jia Liu <proljc at gmail.com>
    Signed-off-by: Blue Swirl <blauwirbel at gmail.com>

diff --git a/linux-user/openrisc/syscall.h b/linux-user/openrisc/syscall.h
new file mode 100644
index 0000000..bdbb577
--- /dev/null
+++ b/linux-user/openrisc/syscall.h
@@ -0,0 +1,24 @@
+struct target_pt_regs {
+    union {
+        struct {
+            /* Named registers */
+            uint32_t sr;       /* Stored in place of r0 */
+            target_ulong sp;   /* r1 */
+        };
+        struct {
+            /* Old style */
+            target_ulong offset[2];
+            target_ulong gprs[30];
+        };
+        struct {
+            /* New style */
+            target_ulong gpr[32];
+        };
+    };
+    target_ulong pc;
+    target_ulong orig_gpr11;   /* For restarting system calls */
+    uint32_t syscallno;        /* Syscall number (used by strace) */
+    target_ulong dummy;     /* Cheap alignment fix */
+};
+
+#define UNAME_MACHINE "openrisc"
diff --git a/linux-user/openrisc/syscall_nr.h b/linux-user/openrisc/syscall_nr.h
new file mode 100644
index 0000000..f4ac91e
--- /dev/null
+++ b/linux-user/openrisc/syscall_nr.h
@@ -0,0 +1,506 @@
+#define TARGET_NR_io_setup 0
+#define TARGET_NR_io_destroy 1
+#define TARGET_NR_io_submit 2
+#define TARGET_NR_io_cancel 3
+#define TARGET_NR_io_getevents 4
+
+/* fs/xattr.c */
+#define TARGET_NR_setxattr 5
+#define TARGET_NR_lsetxattr 6
+#define TARGET_NR_fsetxattr 7
+#define TARGET_NR_getxattr 8
+#define TARGET_NR_lgetxattr 9
+#define TARGET_NR_fgetxattr 10
+#define TARGET_NR_listxattr 11
+#define TARGET_NR_llistxattr 12
+#define TARGET_NR_flistxattr 13
+#define TARGET_NR_removexattr 14
+#define TARGET_NR_lremovexattr 15
+#define TARGET_NR_fremovexattr 16
+
+/* fs/dcache.c */
+#define TARGET_NR_getcwd 17
+
+/* fs/cookies.c */
+#define TARGET_NR_lookup_dcookie 18
+
+/* fs/eventfd.c */
+#define TARGET_NR_eventfd2 19
+
+/* fs/eventpoll.c */
+#define TARGET_NR_epoll_create1 20
+#define TARGET_NR_epoll_ctl 21
+#define TARGET_NR_epoll_pwait 22
+
+/* fs/fcntl.c */
+#define TARGET_NR_dup 23
+#define TARGET_NR_dup3 24
+#define TARGET_NR_3264_fcntl 25
+
+/* fs/inotify_user.c */
+#define TARGET_NR_inotify_init1 26
+#define TARGET_NR_inotify_add_watch 27
+#define TARGET_NR_inotify_rm_watch 28
+
+/* fs/ioctl.c */
+#define TARGET_NR_ioctl 29
+
+/* fs/ioprio.c */
+#define TARGET_NR_ioprio_set 30
+#define TARGET_NR_ioprio_get 31
+
+/* fs/locks.c */
+#define TARGET_NR_flock 32
+
+/* fs/namei.c */
+#define TARGET_NR_mknodat 33
+#define TARGET_NR_mkdirat 34
+#define TARGET_NR_unlinkat 35
+#define TARGET_NR_symlinkat 36
+#define TARGET_NR_linkat 37
+#define TARGET_NR_renameat 38
+
+/* fs/namespace.c */
+#define TARGET_NR_umount2 39
+#define TARGET_NR_mount 40
+#define TARGET_NR_pivot_root 41
+
+/* fs/nfsctl.c */
+#define TARGET_NR_nfsservctl 42
+
+/* fs/open.c */
+#define TARGET_NR_3264_statfs 43
+#define TARGET_NR_3264_fstatfs 44
+#define TARGET_NR_3264_truncate 45
+#define TARGET_NR_3264_ftruncate 46
+
+#define TARGET_NR_fallocate 47
+#define TARGET_NR_faccessat 48
+#define TARGET_NR_chdir 49
+#define TARGET_NR_fchdir 50
+#define TARGET_NR_chroot 51
+#define TARGET_NR_fchmod 52
+#define TARGET_NR_fchmodat 53
+#define TARGET_NR_fchownat 54
+#define TARGET_NR_fchown 55
+#define TARGET_NR_openat 56
+#define TARGET_NR_close 57
+#define TARGET_NR_vhangup 58
+
+/* fs/pipe.c */
+#define TARGET_NR_pipe2 59
+
+/* fs/quota.c */
+#define TARGET_NR_quotactl 60
+
+/* fs/readdir.c */
+#define TARGET_NR_getdents64 61
+
+/* fs/read_write.c */
+#define TARGET_NR_3264_lseek 62
+#define TARGET_NR_read 63
+#define TARGET_NR_write 64
+#define TARGET_NR_readv 65
+#define TARGET_NR_writev 66
+#define TARGET_NR_pread64 67
+#define TARGET_NR_pwrite64 68
+#define TARGET_NR_preadv 69
+#define TARGET_NR_pwritev 70
+
+/* fs/sendfile.c */
+#define TARGET_NR_3264_sendfile 71
+
+/* fs/select.c */
+#define TARGET_NR_pselect6 72
+#define TARGET_NR_ppoll 73
+
+/* fs/signalfd.c */
+#define TARGET_NR_signalfd4 74
+
+/* fs/splice.c */
+#define TARGET_NR_vmsplice 75
+#define TARGET_NR_splice 76
+#define TARGET_NR_tee 77
+
+/* fs/stat.c */
+#define TARGET_NR_readlinkat 78
+#define TARGET_NR_3264_fstatat 79
+#define TARGET_NR_3264_fstat 80
+
+/* fs/sync.c */
+#define TARGET_NR_sync 81
+#define TARGET_NR_fsync 82
+#define TARGET_NR_fdatasync 83
+
+#ifdef __ARCH_WANT_SYNC_FILE_RANGE2
+#define TARGET_NR_sync_file_range2 84
+#else
+#define TARGET_NR_sync_file_range 84
+#endif
+
+/* fs/timerfd.c */
+#define TARGET_NR_timerfd_create 85
+#define TARGET_NR_timerfd_settime 86
+#define TARGET_NR_timerfd_gettime 87
+
+/* fs/utimes.c */
+#define TARGET_NR_utimensat 88
+
+/* kernel/acct.c */
+#define TARGET_NR_acct 89
+
+/* kernel/capability.c */
+#define TARGET_NR_capget 90
+#define TARGET_NR_capset 91
+
+/* kernel/exec_domain.c */
+#define TARGET_NR_personality 92
+
+/* kernel/exit.c */
+#define TARGET_NR_exit 93
+#define TARGET_NR_exit_group 94
+#define TARGET_NR_waitid 95
+
+/* kernel/fork.c */
+#define TARGET_NR_set_tid_address 96
+#define TARGET_NR_unshare 97
+
+/* kernel/futex.c */
+#define TARGET_NR_futex 98
+#define TARGET_NR_set_robust_list 99
+#define TARGET_NR_get_robust_list 100
+
+/* kernel/hrtimer.c */
+#define TARGET_NR_nanosleep 101
+
+/* kernel/itimer.c */
+#define TARGET_NR_getitimer 102
+#define TARGET_NR_setitimer 103
+
+/* kernel/kexec.c */
+#define TARGET_NR_kexec_load 104
+
+/* kernel/module.c */
+#define TARGET_NR_init_module 105
+#define TARGET_NR_delete_module 106
+
+/* kernel/posix-timers.c */
+#define TARGET_NR_timer_create 107
+#define TARGET_NR_timer_gettime 108
+#define TARGET_NR_timer_getoverrun 109
+#define TARGET_NR_timer_settime 110
+#define TARGET_NR_timer_delete 111
+#define TARGET_NR_clock_settime 112
+#define TARGET_NR_clock_gettime 113
+#define TARGET_NR_clock_getres 114
+#define TARGET_NR_clock_nanosleep 115
+
+/* kernel/printk.c */
+#define TARGET_NR_syslog 116
+
+/* kernel/ptrace.c */
+#define TARGET_NR_ptrace 117
+
+/* kernel/sched.c */
+#define TARGET_NR_sched_setparam 118
+#define TARGET_NR_sched_setscheduler 119
+#define TARGET_NR_sched_getscheduler 120
+#define TARGET_NR_sched_getparam 121
+#define TARGET_NR_sched_setaffinity 122
+#define TARGET_NR_sched_getaffinity 123
+#define TARGET_NR_sched_yield 124
+#define TARGET_NR_sched_get_priority_max 125
+#define TARGET_NR_sched_get_priority_min 126
+#define TARGET_NR_sched_rr_get_interval 127
+
+/* kernel/signal.c */
+#define TARGET_NR_restart_syscall 128
+#define TARGET_NR_kill 129
+#define TARGET_NR_tkill 130
+#define TARGET_NR_tgkill 131
+#define TARGET_NR_sigaltstack 132
+#define TARGET_NR_rt_sigsuspend 133
+#define TARGET_NR_rt_sigaction 134
+#define TARGET_NR_rt_sigprocmask 135
+#define TARGET_NR_rt_sigpending 136
+#define TARGET_NR_rt_sigtimedwait 137
+#define TARGET_NR_rt_sigqueueinfo 138
+#define TARGET_NR_rt_sigreturn 139
+
+/* kernel/sys.c */
+#define TARGET_NR_setpriority 140
+#define TARGET_NR_getpriority 141
+#define TARGET_NR_reboot 142
+#define TARGET_NR_setregid 143
+#define TARGET_NR_setgid 144
+#define TARGET_NR_setreuid 145
+#define TARGET_NR_setuid 146
+#define TARGET_NR_setresuid 147
+#define TARGET_NR_getresuid 148
+#define TARGET_NR_setresgid 149
+#define TARGET_NR_getresgid 150
+#define TARGET_NR_setfsuid 151
+#define TARGET_NR_setfsgid 152
+#define TARGET_NR_times 153
+#define TARGET_NR_setpgid 154
+#define TARGET_NR_getpgid 155
+#define TARGET_NR_getsid 156
+#define TARGET_NR_setsid 157
+#define TARGET_NR_getgroups 158
+#define TARGET_NR_setgroups 159
+#define TARGET_NR_uname 160
+#define TARGET_NR_sethostname 161
+#define TARGET_NR_setdomainname 162
+#define TARGET_NR_getrlimit 163
+#define TARGET_NR_setrlimit 164
+#define TARGET_NR_getrusage 165
+#define TARGET_NR_umask 166
+#define TARGET_NR_prctl 167
+#define TARGET_NR_getcpu 168
+
+/* kernel/time.c */
+#define TARGET_NR_gettimeofday 169
+#define TARGET_NR_settimeofday 170
+#define TARGET_NR_adjtimex 171
+
+/* kernel/timer.c */
+#define TARGET_NR_getpid 172
+#define TARGET_NR_getppid 173
+#define TARGET_NR_getuid 174
+#define TARGET_NR_geteuid 175
+#define TARGET_NR_getgid 176
+#define TARGET_NR_getegid 177
+#define TARGET_NR_gettid 178
+#define TARGET_NR_sysinfo 179
+
+/* ipc/mqueue.c */
+#define TARGET_NR_mq_open 180
+#define TARGET_NR_mq_unlink 181
+#define TARGET_NR_mq_timedsend 182
+#define TARGET_NR_mq_timedreceive 183
+#define TARGET_NR_mq_notify 184
+#define TARGET_NR_mq_getsetattr 185
+
+/* ipc/msg.c */
+#define TARGET_NR_msgget 186
+#define TARGET_NR_msgctl 187
+#define TARGET_NR_msgrcv 188
+#define TARGET_NR_msgsnd 189
+
+/* ipc/sem.c */
+#define TARGET_NR_semget 190
+#define TARGET_NR_semctl 191
+#define TARGET_NR_semtimedop 192
+#define TARGET_NR_semop 193
+
+/* ipc/shm.c */
+#define TARGET_NR_shmget 194
+#define TARGET_NR_shmctl 195
+#define TARGET_NR_shmat 196
+#define TARGET_NR_shmdt 197
+
+/* net/socket.c */
+#define TARGET_NR_socket 198
+#define TARGET_NR_socketpair 199
+#define TARGET_NR_bind 200
+#define TARGET_NR_listen 201
+#define TARGET_NR_accept 202
+#define TARGET_NR_connect 203
+#define TARGET_NR_getsockname 204
+#define TARGET_NR_getpeername 205
+#define TARGET_NR_sendto 206
+#define TARGET_NR_recvfrom 207
+#define TARGET_NR_setsockopt 208
+#define TARGET_NR_getsockopt 209
+#define TARGET_NR_shutdown 210
+#define TARGET_NR_sendmsg 211
+#define TARGET_NR_recvmsg 212
+
+/* mm/filemap.c */
+#define TARGET_NR_readahead 213
+
+/* mm/nommu.c, also with MMU */
+#define TARGET_NR_brk 214
+#define TARGET_NR_munmap 215
+#define TARGET_NR_mremap 216
+
+/* security/keys/keyctl.c */
+#define TARGET_NR_add_key 217
+#define TARGET_NR_request_key 218
+#define TARGET_NR_keyctl 219
+
+/* arch/example/kernel/sys_example.c */
+#define TARGET_NR_clone 220
+#define TARGET_NR_execve 221
+
+#define TARGET_NR_3264_mmap 222
+/* mm/fadvise.c */
+#define TARGET_NR_3264_fadvise64 223
+
+/* mm/, CONFIG_MMU only */
+#ifndef __ARCH_NOMMU
+#define TARGET_NR_swapon 224
+#define TARGET_NR_swapoff 225
+#define TARGET_NR_mprotect 226
+#define TARGET_NR_msync 227
+#define TARGET_NR_mlock 228
+#define TARGET_NR_munlock 229
+#define TARGET_NR_mlockall 230
+#define TARGET_NR_munlockall 231
+#define TARGET_NR_mincore 232
+#define TARGET_NR_madvise 233
+#define TARGET_NR_remap_file_pages 234
+#define TARGET_NR_mbind 235
+#define TARGET_NR_get_mempolicy 236
+#define TARGET_NR_set_mempolicy 237
+#define TARGET_NR_migrate_pages 238
+#define TARGET_NR_move_pages 239
+#endif
+
+#define TARGET_NR_rt_tgsigqueueinfo 240
+#define TARGET_NR_perf_event_open 241
+#define TARGET_NR_accept4 242
+#define TARGET_NR_recvmmsg 243
+
+/*
+ * Architectures may provide up to 16 syscalls of their own
+ * starting with this value.
+ */
+#define TARGET_NR_arch_specific_syscall 244
+
+#define TARGET_NR_wait4 260
+#define TARGET_NR_prlimit64 261
+#define TARGET_NR_fanotify_init 262
+#define TARGET_NR_fanotify_mark 263
+#define TARGET_NR_name_to_handle_at         264
+#define TARGET_NR_open_by_handle_at         265
+#define TARGET_NR_clock_adjtime 266
+#define TARGET_NR_syncfs 267
+#define TARGET_NR_setns 268
+#define TARGET_NR_sendmmsg 269
+
+#undef TARGET_NR_syscalls
+#define TARGET_NR_syscalls 270
+
+/*
+ * All syscalls below here should go away really,
+ * these are provided for both review and as a porting
+ * help for the C library version.
+*
+ * Last chance: are any of these important enough to
+ * enable by default?
+ */
+#define TARGET_NR_open 1024
+#define TARGET_NR_link 1025
+#define TARGET_NR_unlink 1026
+#define TARGET_NR_mknod 1027
+#define TARGET_NR_chmod 1028
+#define TARGET_NR_chown 1029
+#define TARGET_NR_mkdir 1030
+#define TARGET_NR_rmdir 1031
+#define TARGET_NR_lchown 1032
+#define TARGET_NR_access 1033
+#define TARGET_NR_rename 1034
+#define TARGET_NR_readlink 1035
+#define TARGET_NR_symlink 1036
+#define TARGET_NR_utimes 1037
+#define TARGET_NR_3264_stat 1038
+#define TARGET_NR_3264_lstat 1039
+
+#undef TARGET_NR_syscalls
+#define TARGET_NR_syscalls (TARGET_NR_3264_lstat+1)
+
+#define TARGET_NR_pipe 1040
+#define TARGET_NR_dup2 1041
+#define TARGET_NR_epoll_create 1042
+#define TARGET_NR_inotify_init 1043
+#define TARGET_NR_eventfd 1044
+#define TARGET_NR_signalfd 1045
+
+#undef TARGET_NR_syscalls
+#define TARGET_NR_syscalls (TARGET_NR_signalfd+1)
+
+
+#define TARGET_NR_sendfile 1046
+#define TARGET_NR_ftruncate 1047
+#define TARGET_NR_truncate 1048
+#define TARGET_NR_stat 1049
+#define TARGET_NR_lstat 1050
+#define TARGET_NR_fstat 1051
+#define TARGET_NR_fcntl 1052
+#define TARGET_NR_fadvise64 1053
+#define __ARCH_WANT_SYS_FADVISE64
+#define TARGET_NR_newfstatat 1054
+#define __ARCH_WANT_SYS_NEWFSTATAT
+#define TARGET_NR_fstatfs 1055
+#define TARGET_NR_statfs 1056
+#define TARGET_NR_lseek 1057
+#define TARGET_NR_mmap 1058
+
+#undef TARGET_NR_syscalls
+#define TARGET_NR_syscalls (TARGET_NR_mmap+1)
+
+#define TARGET_NR_alarm 1059
+#define __ARCH_WANT_SYS_ALARM
+#define TARGET_NR_getpgrp 1060
+#define __ARCH_WANT_SYS_GETPGRP
+#define TARGET_NR_pause 1061
+#define __ARCH_WANT_SYS_PAUSE
+#define TARGET_NR_time 1062
+#define __ARCH_WANT_SYS_TIME
+#define __ARCH_WANT_COMPAT_SYS_TIME
+#define TARGET_NR_utime 1063
+#define __ARCH_WANT_SYS_UTIME
+
+#define TARGET_NR_creat 1064
+#define TARGET_NR_getdents 1065
+#define __ARCH_WANT_SYS_GETDENTS
+#define TARGET_NR_futimesat 1066
+#define TARGET_NR_select 1067
+#define __ARCH_WANT_SYS_SELECT
+#define TARGET_NR_poll 1068
+#define TARGET_NR_epoll_wait 1069
+#define TARGET_NR_ustat 1070
+#define TARGET_NR_vfork 1071
+#define TARGET_NR_oldwait4 1072
+#define TARGET_NR_recv 1073
+#define TARGET_NR_send 1074
+#define TARGET_NR_bdflush 1075
+#define TARGET_NR_umount 1076
+#define __ARCH_WANT_SYS_OLDUMOUNT
+#define TARGET_NR_uselib 1077
+#define TARGET_NR__sysctl 1078
+
+#define TARGET_NR_fork 1079
+
+#undef TARGET_NR_syscalls
+#define TARGET_NR_syscalls (TARGET_NR_fork+1)
+
+
+/*
+ * 32 bit systems traditionally used different
+ * syscalls for off_t and loff_t arguments, while
+ * 64 bit systems only need the off_t version.
+ * For new 32 bit platforms, there is no need to
+ * implement the old 32 bit off_t syscalls, so
+ * they take different names.
+ * Here we map the numbers so that both versions
+ * use the same syscall table layout.
+ */
+
+#define TARGET_NR_fcntl64 TARGET_NR_3264_fcntl
+#define TARGET_NR_statfs64 TARGET_NR_3264_statfs
+#define TARGET_NR_fstatfs64 TARGET_NR_3264_fstatfs
+#define TARGET_NR_truncate64 TARGET_NR_3264_truncate
+#define TARGET_NR_ftruncate64 TARGET_NR_3264_ftruncate
+#define TARGET_NR_llseek TARGET_NR_3264_lseek
+#define TARGET_NR_sendfile64 TARGET_NR_3264_sendfile
+#define TARGET_NR_fstatat64 TARGET_NR_3264_fstatat
+#define TARGET_NR_fstat64 TARGET_NR_3264_fstat
+#define TARGET_NR_mmap2 TARGET_NR_3264_mmap
+#define TARGET_NR_fadvise64_64 TARGET_NR_3264_fadvise64
+
+#ifdef TARGET_NR_3264_stat
+#define TARGET_NR_stat64 TARGET_NR_3264_stat
+#define TARGET_NR_lstat64 TARGET_NR_3264_lstat
+#endif
diff --git a/linux-user/openrisc/target_signal.h b/linux-user/openrisc/target_signal.h
new file mode 100644
index 0000000..964aed6
--- /dev/null
+++ b/linux-user/openrisc/target_signal.h
@@ -0,0 +1,26 @@
+#ifndef TARGET_SIGNAL_H
+#define TARGET_SIGNAL_H
+
+#include "cpu.h"
+
+/* this struct defines a stack used during syscall handling */
+
+typedef struct target_sigaltstack {
+    abi_long ss_sp;
+    abi_ulong ss_size;
+    abi_long ss_flags;
+} target_stack_t;
+
+/* sigaltstack controls  */
+#define TARGET_SS_ONSTACK     1
+#define TARGET_SS_DISABLE     2
+
+#define TARGET_MINSIGSTKSZ    2048
+#define TARGET_SIGSTKSZ       8192
+
+static inline abi_ulong get_sp_from_cpustate(CPUOpenRISCState *state)
+{
+    return state->gpr[1];
+}
+
+#endif /* TARGET_SIGNAL_H */
diff --git a/linux-user/openrisc/termbits.h b/linux-user/openrisc/termbits.h
new file mode 100644
index 0000000..373af77
--- /dev/null
+++ b/linux-user/openrisc/termbits.h
@@ -0,0 +1,294 @@
+typedef unsigned char   target_openrisc_cc;        /*cc_t*/
+typedef unsigned int    target_openrisc_speed;     /*speed_t*/
+typedef unsigned int    target_openrisc_tcflag;    /*tcflag_t*/
+
+#define TARGET_NCCS 19
+struct target_termios {
+    target_openrisc_tcflag c_iflag;               /* input mode flags */
+    target_openrisc_tcflag c_oflag;               /* output mode flags */
+    target_openrisc_tcflag c_cflag;               /* control mode flags */
+    target_openrisc_tcflag c_lflag;               /* local mode flags */
+    target_openrisc_cc c_line;                    /* line discipline */
+    target_openrisc_cc c_cc[TARGET_NCCS];         /* control characters */
+};
+
+struct target_termios2 {
+    target_openrisc_tcflag c_iflag;               /* input mode flags */
+    target_openrisc_tcflag c_oflag;               /* output mode flags */
+    target_openrisc_tcflag c_cflag;               /* control mode flags */
+    target_openrisc_tcflag c_lflag;               /* local mode flags */
+    target_openrisc_cc c_line;                    /* line discipline */
+    target_openrisc_cc c_cc[TARGET_NCCS];         /* control characters */
+    target_openrisc_speed c_ispeed;               /* input speed */
+    target_openrisc_speed c_ospeed;               /* output speed */
+};
+
+struct target_termios3 {
+    target_openrisc_tcflag c_iflag;               /* input mode flags */
+    target_openrisc_tcflag c_oflag;               /* output mode flags */
+    target_openrisc_tcflag c_cflag;               /* control mode flags */
+    target_openrisc_tcflag c_lflag;               /* local mode flags */
+    target_openrisc_cc c_line;                    /* line discipline */
+    target_openrisc_cc c_cc[TARGET_NCCS];         /* control characters */
+    target_openrisc_speed c_ispeed;               /* input speed */
+    target_openrisc_speed c_ospeed;               /* output speed */
+};
+
+/* c_cc characters */
+#define TARGET_VINTR 0
+#define TARGET_VQUIT 1
+#define TARGET_VERASE 2
+#define TARGET_VKILL 3
+#define TARGET_VEOF 4
+#define TARGET_VTIME 5
+#define TARGET_VMIN 6
+#define TARGET_VSWTC 7
+#define TARGET_VSTART 8
+#define TARGET_VSTOP 9
+#define TARGET_VSUSP 10
+#define TARGET_VEOL 11
+#define TARGET_VREPRINT 12
+#define TARGET_VDISCARD 13
+#define TARGET_VWERASE 14
+#define TARGET_VLNEXT 15
+#define TARGET_VEOL2 16
+
+/* c_iflag bits */
+#define TARGET_IGNBRK  0000001
+#define TARGET_BRKINT  0000002
+#define TARGET_IGNPAR  0000004
+#define TARGET_PARMRK  0000010
+#define TARGET_INPCK   0000020
+#define TARGET_ISTRIP  0000040
+#define TARGET_INLCR   0000100
+#define TARGET_IGNCR   0000200
+#define TARGET_ICRNL   0000400
+#define TARGET_IUCLC   0001000
+#define TARGET_IXON    0002000
+#define TARGET_IXANY   0004000
+#define TARGET_IXOFF   0010000
+#define TARGET_IMAXBEL 0020000
+#define TARGET_IUTF8   0040000
+
+/* c_oflag bits */
+#define TARGET_OPOST   0000001
+#define TARGET_OLCUC   0000002
+#define TARGET_ONLCR   0000004
+#define TARGET_OCRNL   0000010
+#define TARGET_ONOCR   0000020
+#define TARGET_ONLRET  0000040
+#define TARGET_OFILL   0000100
+#define TARGET_OFDEL   0000200
+#define TARGET_NLDLY   0000400
+#define TARGET_NL0     0000000
+#define TARGET_NL1     0000400
+#define TARGET_CRDLY   0003000
+#define TARGET_CR0     0000000
+#define TARGET_CR1     0001000
+#define TARGET_CR2     0002000
+#define TARGET_CR3     0003000
+#define TARGET_TABDLY  0014000
+#define TARGET_TAB0    0000000
+#define TARGET_TAB1    0004000
+#define TARGET_TAB2    0010000
+#define TARGET_TAB3    0014000
+#define TARGET_XTABS   0014000
+#define TARGET_BSDLY   0020000
+#define TARGET_BS0     0000000
+#define TARGET_BS1     0020000
+#define TARGET_VTDLY   0040000
+#define TARGET_VT0     0000000
+#define TARGET_VT1     0040000
+#define TARGET_FFDLY   0100000
+#define TARGET_FF0     0000000
+#define TARGET_FF1     0100000
+
+/* c_cflag bit meaning */
+#define TARGET_CBAUD    0010017
+#define TARGET_B0       0000000                /* hang up */
+#define TARGET_B50      0000001
+#define TARGET_B75      0000002
+#define TARGET_B110     0000003
+#define TARGET_B134     0000004
+#define TARGET_B150     0000005
+#define TARGET_B200     0000006
+#define TARGET_B300     0000007
+#define TARGET_B600     0000010
+#define TARGET_B1200    0000011
+#define TARGET_B1800    0000012
+#define TARGET_B2400    0000013
+#define TARGET_B4800    0000014
+#define TARGET_B9600    0000015
+#define TARGET_B19200   0000016
+#define TARGET_B38400   0000017
+#define TARGET_EXTA     B19200
+#define TARGET_EXTB     B38400
+#define TARGET_CSIZE    0000060
+#define TARGET_CS5      0000000
+#define TARGET_CS6      0000020
+#define TARGET_CS7      0000040
+#define TARGET_CS8      0000060
+#define TARGET_CSTOPB   0000100
+#define TARGET_CREAD    0000200
+#define TARGET_PARENB   0000400
+#define TARGET_PARODD   0001000
+#define TARGET_HUPCL    0002000
+#define TARGET_CLOCAL   0004000
+#define TARGET_CBAUDEX  0010000
+#define TARGET_BOTHER   0010000
+#define TARGET_B57600   0010001
+#define TARGET_B115200  0010002
+#define TARGET_B230400  0010003
+#define TARGET_B460800  0010004
+#define TARGET_B500000  0010005
+#define TARGET_B576000  0010006
+#define TARGET_B921600  0010007
+#define TARGET_B1000000 0010010
+#define TARGET_B1152000 0010011
+#define TARGET_B1500000 0010012
+#define TARGET_B2000000 0010013
+#define TARGET_B2500000 0010014
+#define TARGET_B3000000 0010015
+#define TARGET_B3500000 0010016
+#define TARGET_B4000000 0010017
+#define TARGET_CIBAUD   002003600000   /* input baud rate */
+#define TARGET_CMSPAR   010000000000   /* mark or space (stick) parity */
+#define TARGET_CRTSCTS  020000000000   /* flow control */
+
+#define TARGET_IBSHIFT   16            /* Shift from CBAUD to CIBAUD */
+
+/* c_lflag bits */
+#define TARGET_ISIG    0000001
+#define TARGET_ICANON  0000002
+#define TARGET_XCASE   0000004
+#define TARGET_ECHO    0000010
+#define TARGET_ECHOE   0000020
+#define TARGET_ECHOK   0000040
+#define TARGET_ECHONL  0000100
+#define TARGET_NOFLSH  0000200
+#define TARGET_TOSTOP  0000400
+#define TARGET_ECHOCTL 0001000
+#define TARGET_ECHOPRT 0002000
+#define TARGET_ECHOKE  0004000
+#define TARGET_FLUSHO  0010000
+#define TARGET_PENDIN  0040000
+#define TARGET_IEXTEN  0100000
+#define TARGET_EXTPROC 0200000
+
+/* tcflow() and TCXONC use these */
+#define TARGET_TCOOFF          0
+#define TARGET_TCOON           1
+#define TARGET_TCIOFF          2
+#define TARGET_TCION           3
+
+/* tcflush() and TCFLSH use these */
+#define TARGET_TCIFLUSH        0
+#define TARGET_TCOFLUSH        1
+#define TARGET_TCIOFLUSH       2
+
+/* tcsetattr uses these */
+#define TARGET_TCSANOW         0
+#define TARGET_TCSADRAIN       1
+#define TARGET_TCSAFLUSH       2
+
+/* ioctls */
+#define TARGET_TCGETS          0x5401
+#define TARGET_TCSETS          0x5402
+#define TARGET_TCSETSW         0x5403
+#define TARGET_TCSETSF         0x5404
+#define TARGET_TCGETA          0x5405
+#define TARGET_TCSETA          0x5406
+#define TARGET_TCSETAW         0x5407
+#define TARGET_TCSETAF         0x5408
+#define TARGET_TCSBRK          0x5409
+#define TARGET_TCXONC          0x540A
+#define TARGET_TCFLSH          0x540B
+#define TARGET_TIOCEXCL        0x540C
+#define TARGET_TIOCNXCL        0x540D
+#define TARGET_TIOCSCTTY       0x540E
+#define TARGET_TIOCGPGRP       0x540F
+#define TARGET_TIOCSPGRP       0x5410
+#define TARGET_TIOCOUTQ        0x5411
+#define TARGET_TIOCSTI         0x5412
+#define TARGET_TIOCGWINSZ      0x5413
+#define TARGET_TIOCSWINSZ      0x5414
+#define TARGET_TIOCMGET        0x5415
+#define TARGET_TIOCMBIS        0x5416
+#define TARGET_TIOCMBIC        0x5417
+#define TARGET_TIOCMSET        0x5418
+#define TARGET_TIOCGSOFTCAR    0x5419
+#define TARGET_TIOCSSOFTCAR    0x541A
+#define TARGET_FIONREAD        0x541B
+#define TARGET_TIOCINQ         FIONREAD
+#define TARGET_TIOCLINUX       0x541C
+#define TARGET_TIOCCONS        0x541D
+#define TARGET_TIOCGSERIAL     0x541E
+#define TARGET_TIOCSSERIAL     0x541F
+#define TARGET_TIOCPKT         0x5420
+#define TARGET_FIONBIO         0x5421
+#define TARGET_TIOCNOTTY       0x5422
+#define TARGET_TIOCSETD        0x5423
+#define TARGET_TIOCGETD        0x5424
+#define TARGET_TCSBRKP         0x5425  /* Needed for POSIX tcsendbreak() */
+#define TARGET_TIOCSBRK        0x5427  /* BSD compatibility */
+#define TARGET_TIOCCBRK        0x5428  /* BSD compatibility */
+#define TARGET_TIOCGSID        0x5429  /* Return the session ID of FD */
+#define TARGET_TCGETS2         TARGET_IOR('T', 0x2A, struct termios2)
+#define TARGET_TCSETS2         TARGET_IOW('T', 0x2B, struct termios2)
+#define TARGET_TCSETSW2        TARGET_IOW('T', 0x2C, struct termios2)
+#define TARGET_TCSETSF2        TARGET_IOW('T', 0x2D, struct termios2)
+#define TARGET_TIOCGRS485      0x542E
+#ifndef TARGET_TIOCSRS485
+#define TARGET_TIOCSRS485      0x542F
+#endif
+/* Get Pty Number (of pty-mux device) */
+#define TARGET_TIOCGPTN        TARGET_IOR('T', 0x30, unsigned int)
+/* Lock/unlock Pty */
+#define TARGET_TIOCSPTLCK      TARGET_IOW('T', 0x31, int)
+/* Get primary device node of /dev/console */
+#define TARGET_TIOCGDEV        TARGET_IOR('T', 0x32, unsigned int)
+#define TARGET_TCGETX          0x5432 /* SYS5 TCGETX compatibility */
+#define TARGET_TCSETX          0x5433
+#define TARGET_TCSETXF         0x5434
+#define TARGET_TCSETXW         0x5435
+/* pty: generate signal */
+#define TARGET_TIOCSIG         TARGET_IOW('T', 0x36, int)
+#define TARGET_TIOCVHANGUP     0x5437
+
+#define TARGET_FIONCLEX        0x5450
+#define TARGET_FIOCLEX         0x5451
+#define TARGET_FIOASYNC        0x5452
+#define TARGET_TIOCSERCONFIG   0x5453
+#define TARGET_TIOCSERGWILD    0x5454
+#define TARGET_TIOCSERSWILD    0x5455
+#define TARGET_TIOCGLCKTRMIOS  0x5456
+#define TARGET_TIOCSLCKTRMIOS  0x5457
+#define TARGET_TIOCSERGSTRUCT  0x5458 /* For debugging only */
+#define TARGET_TIOCSERGETLSR   0x5459 /* Get line status register */
+#define TARGET_TIOCSERGETMULTI 0x545A /* Get multiport config  */
+#define TARGET_TIOCSERSETMULTI 0x545B /* Set multiport config */
+
+/* wait for a change on serial input line(s) */
+#define TARGET_TIOCMIWAIT      0x545C
+/* read serial port inline interrupt counts */
+#define TARGET_TIOCGICOUNT     0x545D
+
+/*
+ * Some arches already define TARGET_FIOQSIZE due to a historical
+ * conflict with a Hayes modem-specific ioctl value.
+ */
+#ifndef TARGET_FIOQSIZE
+#define TARGET_FIOQSIZE        0x5460
+#endif
+
+/* Used for packet mode */
+#define TARGET_TIOCPKT_DATA             0
+#define TARGET_TIOCPKT_FLUSHREAD        1
+#define TARGET_TIOCPKT_FLUSHWRITE       2
+#define TARGET_TIOCPKT_STOP             4
+#define TARGET_TIOCPKT_START            8
+#define TARGET_TIOCPKT_NOSTOP          16
+#define TARGET_TIOCPKT_DOSTOP          32
+#define TARGET_TIOCPKT_IOCTL           64
+
+#define TARGET_TIOCSER_TEMT    0x01    /* Transmitter physically empty */
commit fc04355bb86c77ef9dae28ecda44d6e15221d48b
Author: Jia Liu <proljc at gmail.com>
Date:   Fri Jul 20 15:50:50 2012 +0800

    target-or32: Add gdb stub support
    
    Add OpenRISC gdb stub support.
    
    Signed-off-by: Jia Liu <proljc at gmail.com>
    Signed-off-by: Blue Swirl <blauwirbel at gmail.com>

diff --git a/gdbstub.c b/gdbstub.c
index 08cf864..5d37dd9 100644
--- a/gdbstub.c
+++ b/gdbstub.c
@@ -1155,6 +1155,68 @@ static int cpu_gdb_write_register(CPUMIPSState *env, uint8_t *mem_buf, int n)
 
     return sizeof(target_ulong);
 }
+#elif defined(TARGET_OPENRISC)
+
+#define NUM_CORE_REGS (32 + 3)
+
+static int cpu_gdb_read_register(CPUOpenRISCState *env, uint8_t *mem_buf, int n)
+{
+    if (n < 32) {
+        GET_REG32(env->gpr[n]);
+    } else {
+        switch (n) {
+        case 32:    /* PPC */
+            GET_REG32(env->ppc);
+            break;
+
+        case 33:    /* NPC */
+            GET_REG32(env->npc);
+            break;
+
+        case 34:    /* SR */
+            GET_REG32(env->sr);
+            break;
+
+        default:
+            break;
+        }
+    }
+    return 0;
+}
+
+static int cpu_gdb_write_register(CPUOpenRISCState *env,
+                                  uint8_t *mem_buf, int n)
+{
+    uint32_t tmp;
+
+    if (n > NUM_CORE_REGS) {
+        return 0;
+    }
+
+    tmp = ldl_p(mem_buf);
+
+    if (n < 32) {
+        env->gpr[n] = tmp;
+    } else {
+        switch (n) {
+        case 32: /* PPC */
+            env->ppc = tmp;
+            break;
+
+        case 33: /* NPC */
+            env->npc = tmp;
+            break;
+
+        case 34: /* SR */
+            env->sr = tmp;
+            break;
+
+        default:
+            break;
+        }
+    }
+    return 4;
+}
 #elif defined (TARGET_SH4)
 
 /* Hint: Use "set architecture sh4" in GDB to see fpu registers */
@@ -1924,6 +1986,8 @@ static void gdb_set_cpu_pc(GDBState *s, target_ulong pc)
     }
 #elif defined (TARGET_MICROBLAZE)
     s->c_cpu->sregs[SR_PC] = pc;
+#elif defined(TARGET_OPENRISC)
+    s->c_cpu->pc = pc;
 #elif defined (TARGET_CRIS)
     s->c_cpu->pc = pc;
 #elif defined (TARGET_ALPHA)
commit 4dd044c6ba8b957899f0f308ab43ad61a27d26d4
Author: Jia Liu <proljc at gmail.com>
Date:   Fri Jul 20 15:50:49 2012 +0800

    target-or32: Add system instructions
    
    Add OpenRISC system instructions.
    
    Signed-off-by: Jia Liu <proljc at gmail.com>
    Signed-off-by: Blue Swirl <blauwirbel at gmail.com>

diff --git a/target-openrisc/Makefile.objs b/target-openrisc/Makefile.objs
index 926fc2f..44dc539 100644
--- a/target-openrisc/Makefile.objs
+++ b/target-openrisc/Makefile.objs
@@ -1,4 +1,4 @@
 obj-$(CONFIG_SOFTMMU) += machine.o
 obj-y += cpu.o exception.o interrupt.o mmu.o translate.o
 obj-y += exception_helper.o fpu_helper.o int_helper.o \
-         interrupt_helper.o mmu_helper.o
+         interrupt_helper.o mmu_helper.o sys_helper.o
diff --git a/target-openrisc/cpu.h b/target-openrisc/cpu.h
index df07eaf..6506665 100644
--- a/target-openrisc/cpu.h
+++ b/target-openrisc/cpu.h
@@ -80,6 +80,9 @@ enum {
                                       (reg) |= ((v & 0x1f) << 2);\
                                   } while (0)
 
+/* Version Register */
+#define SPR_VR 0xFFFF003F
+
 /* Internal flags, delay slot flag */
 #define D_FLAG    1
 
diff --git a/target-openrisc/helper.h b/target-openrisc/helper.h
index 635c69c..404d464 100644
--- a/target-openrisc/helper.h
+++ b/target-openrisc/helper.h
@@ -63,4 +63,8 @@ DEF_HELPER_FLAGS_3(mul32, 0, i32, env, i32, i32)
 /* interrupt */
 DEF_HELPER_FLAGS_1(rfe, 0, void, env)
 
+/* sys */
+DEF_HELPER_FLAGS_4(mtspr, 0, void, env, tl, tl, tl)
+DEF_HELPER_FLAGS_4(mfspr, 0, tl, env, tl, tl, tl)
+
 #include "def-helper.h"
diff --git a/target-openrisc/sys_helper.c b/target-openrisc/sys_helper.c
new file mode 100644
index 0000000..f160dc3
--- /dev/null
+++ b/target-openrisc/sys_helper.c
@@ -0,0 +1,287 @@
+/*
+ * OpenRISC system instructions helper routines
+ *
+ * Copyright (c) 2011-2012 Jia Liu <proljc at gmail.com>
+ *                         Zhizhou Zhang <etouzh at gmail.com>
+ *
+ * This library is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Lesser General Public
+ * License as published by the Free Software Foundation; either
+ * version 2 of the License, or (at your option) any later version.
+ *
+ * This library is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
+ * Lesser General Public License for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public
+ * License along with this library; if not, see <http://www.gnu.org/licenses/>.
+ */
+
+#include "cpu.h"
+#include "helper.h"
+
+#define TO_SPR(group, number) (((group) << 11) + (number))
+
+void HELPER(mtspr)(CPUOpenRISCState *env,
+                   target_ulong ra, target_ulong rb, target_ulong offset)
+{
+#ifndef CONFIG_USER_ONLY
+    int spr = (ra | offset);
+    int idx;
+
+    OpenRISCCPU *cpu = OPENRISC_CPU(ENV_GET_CPU(env));
+
+    switch (spr) {
+    case TO_SPR(0, 0): /* VR */
+        env->vr = rb;
+        break;
+
+    case TO_SPR(0, 16): /* NPC */
+        env->npc = rb;
+        break;
+
+    case TO_SPR(0, 17): /* SR */
+        if ((env->sr & (SR_IME | SR_DME | SR_SM)) ^
+            (rb & (SR_IME | SR_DME | SR_SM))) {
+            tlb_flush(env, 1);
+        }
+        env->sr = rb;
+        env->sr |= SR_FO;      /* FO is const equal to 1 */
+        if (env->sr & SR_DME) {
+            env->tlb->cpu_openrisc_map_address_data =
+                &cpu_openrisc_get_phys_data;
+        } else {
+            env->tlb->cpu_openrisc_map_address_data =
+                &cpu_openrisc_get_phys_nommu;
+        }
+
+        if (env->sr & SR_IME) {
+            env->tlb->cpu_openrisc_map_address_code =
+                &cpu_openrisc_get_phys_code;
+        } else {
+            env->tlb->cpu_openrisc_map_address_code =
+                &cpu_openrisc_get_phys_nommu;
+        }
+        break;
+
+    case TO_SPR(0, 18): /* PPC */
+        env->ppc = rb;
+        break;
+
+    case TO_SPR(0, 32): /* EPCR */
+        env->epcr = rb;
+        break;
+
+    case TO_SPR(0, 48): /* EEAR */
+        env->eear = rb;
+        break;
+
+    case TO_SPR(0, 64): /* ESR */
+        env->esr = rb;
+        break;
+    case TO_SPR(1, 512) ... TO_SPR(1, 639): /* DTLBW0MR 0-127 */
+        idx = spr - TO_SPR(1, 512);
+        if (!(rb & 1)) {
+            tlb_flush_page(env, env->tlb->dtlb[0][idx].mr & TARGET_PAGE_MASK);
+        }
+        env->tlb->dtlb[0][idx].mr = rb;
+        break;
+
+    case TO_SPR(1, 640) ... TO_SPR(1, 767): /* DTLBW0TR 0-127 */
+        idx = spr - TO_SPR(1, 640);
+        env->tlb->dtlb[0][idx].tr = rb;
+        break;
+    case TO_SPR(1, 768) ... TO_SPR(1, 895):   /* DTLBW1MR 0-127 */
+    case TO_SPR(1, 896) ... TO_SPR(1, 1023):  /* DTLBW1TR 0-127 */
+    case TO_SPR(1, 1024) ... TO_SPR(1, 1151): /* DTLBW2MR 0-127 */
+    case TO_SPR(1, 1152) ... TO_SPR(1, 1279): /* DTLBW2TR 0-127 */
+    case TO_SPR(1, 1280) ... TO_SPR(1, 1407): /* DTLBW3MR 0-127 */
+    case TO_SPR(1, 1408) ... TO_SPR(1, 1535): /* DTLBW3TR 0-127 */
+        break;
+    case TO_SPR(2, 512) ... TO_SPR(2, 639):   /* ITLBW0MR 0-127 */
+        idx = spr - TO_SPR(2, 512);
+        if (!(rb & 1)) {
+            tlb_flush_page(env, env->tlb->itlb[0][idx].mr & TARGET_PAGE_MASK);
+        }
+        env->tlb->itlb[0][idx].mr = rb;
+        break;
+
+    case TO_SPR(2, 640) ... TO_SPR(2, 767): /* ITLBW0TR 0-127 */
+        idx = spr - TO_SPR(2, 640);
+        env->tlb->itlb[0][idx].tr = rb;
+        break;
+    case TO_SPR(2, 768) ... TO_SPR(2, 895):   /* ITLBW1MR 0-127 */
+    case TO_SPR(2, 896) ... TO_SPR(2, 1023):  /* ITLBW1TR 0-127 */
+    case TO_SPR(2, 1024) ... TO_SPR(2, 1151): /* ITLBW2MR 0-127 */
+    case TO_SPR(2, 1152) ... TO_SPR(2, 1279): /* ITLBW2TR 0-127 */
+    case TO_SPR(2, 1280) ... TO_SPR(2, 1407): /* ITLBW3MR 0-127 */
+    case TO_SPR(2, 1408) ... TO_SPR(2, 1535): /* ITLBW3TR 0-127 */
+        break;
+    case TO_SPR(9, 0):  /* PICMR */
+        env->picmr |= rb;
+        break;
+    case TO_SPR(9, 2):  /* PICSR */
+        env->picsr &= ~rb;
+        break;
+    case TO_SPR(10, 0): /* TTMR */
+        {
+            int ip = env->ttmr & TTMR_IP;
+
+            if (rb & TTMR_IP) {    /* Keep IP bit.  */
+                env->ttmr = (rb & ~TTMR_IP) + ip;
+            } else {    /* Clear IP bit.  */
+                env->ttmr = rb & ~TTMR_IP;
+                env->interrupt_request &= ~CPU_INTERRUPT_TIMER;
+            }
+
+            cpu_openrisc_count_update(cpu);
+
+            switch (env->ttmr & TTMR_M) {
+            case TIMER_NONE:
+                cpu_openrisc_count_stop(cpu);
+                break;
+            case TIMER_INTR:
+                cpu_openrisc_count_start(cpu);
+                break;
+            case TIMER_SHOT:
+                cpu_openrisc_count_start(cpu);
+                break;
+            case TIMER_CONT:
+                cpu_openrisc_count_start(cpu);
+                break;
+            default:
+                break;
+            }
+        }
+        break;
+
+    case TO_SPR(10, 1): /* TTCR */
+        env->ttcr = rb;
+        if (env->ttmr & TIMER_NONE) {
+            return;
+        }
+        cpu_openrisc_count_start(cpu);
+        break;
+    default:
+
+        break;
+    }
+#endif
+}
+
+target_ulong HELPER(mfspr)(CPUOpenRISCState *env,
+                           target_ulong rd, target_ulong ra, uint32_t offset)
+{
+#ifndef CONFIG_USER_ONLY
+    int spr = (ra | offset);
+    int idx;
+
+    OpenRISCCPU *cpu = OPENRISC_CPU(ENV_GET_CPU(env));
+
+    switch (spr) {
+    case TO_SPR(0, 0): /* VR */
+        return env->vr & SPR_VR;
+
+    case TO_SPR(0, 1): /* UPR */
+        return env->upr;    /* TT, DM, IM, UP present */
+
+    case TO_SPR(0, 2): /* CPUCFGR */
+        return env->cpucfgr;
+
+    case TO_SPR(0, 3): /* DMMUCFGR */
+        return env->dmmucfgr;    /* 1Way, 64 entries */
+
+    case TO_SPR(0, 4): /* IMMUCFGR */
+        return env->immucfgr;
+
+    case TO_SPR(0, 16): /* NPC */
+        return env->npc;
+
+    case TO_SPR(0, 17): /* SR */
+        return env->sr;
+
+    case TO_SPR(0, 18): /* PPC */
+        return env->ppc;
+
+    case TO_SPR(0, 32): /* EPCR */
+        return env->epcr;
+
+    case TO_SPR(0, 48): /* EEAR */
+        return env->eear;
+
+    case TO_SPR(0, 64): /* ESR */
+        return env->esr;
+
+    case TO_SPR(1, 512) ... TO_SPR(1, 639): /* DTLBW0MR 0-127 */
+        idx = spr - TO_SPR(1, 512);
+        return env->tlb->dtlb[0][idx].mr;
+
+    case TO_SPR(1, 640) ... TO_SPR(1, 767): /* DTLBW0TR 0-127 */
+        idx = spr - TO_SPR(1, 640);
+        return env->tlb->dtlb[0][idx].tr;
+
+    case TO_SPR(1, 768) ... TO_SPR(1, 895):   /* DTLBW1MR 0-127 */
+    case TO_SPR(1, 896) ... TO_SPR(1, 1023):  /* DTLBW1TR 0-127 */
+    case TO_SPR(1, 1024) ... TO_SPR(1, 1151): /* DTLBW2MR 0-127 */
+    case TO_SPR(1, 1152) ... TO_SPR(1, 1279): /* DTLBW2TR 0-127 */
+    case TO_SPR(1, 1280) ... TO_SPR(1, 1407): /* DTLBW3MR 0-127 */
+    case TO_SPR(1, 1408) ... TO_SPR(1, 1535): /* DTLBW3TR 0-127 */
+        break;
+
+    case TO_SPR(2, 512) ... TO_SPR(2, 639): /* ITLBW0MR 0-127 */
+        idx = spr - TO_SPR(2, 512);
+        return env->tlb->itlb[0][idx].mr;
+
+    case TO_SPR(2, 640) ... TO_SPR(2, 767): /* ITLBW0TR 0-127 */
+        idx = spr - TO_SPR(2, 640);
+        return env->tlb->itlb[0][idx].tr;
+
+    case TO_SPR(2, 768) ... TO_SPR(2, 895):   /* ITLBW1MR 0-127 */
+    case TO_SPR(2, 896) ... TO_SPR(2, 1023):  /* ITLBW1TR 0-127 */
+    case TO_SPR(2, 1024) ... TO_SPR(2, 1151): /* ITLBW2MR 0-127 */
+    case TO_SPR(2, 1152) ... TO_SPR(2, 1279): /* ITLBW2TR 0-127 */
+    case TO_SPR(2, 1280) ... TO_SPR(2, 1407): /* ITLBW3MR 0-127 */
+    case TO_SPR(2, 1408) ... TO_SPR(2, 1535): /* ITLBW3TR 0-127 */
+        break;
+
+    case TO_SPR(9, 0):  /* PICMR */
+        return env->picmr;
+
+    case TO_SPR(9, 2):  /* PICSR */
+        return env->picsr;
+
+    case TO_SPR(10, 0): /* TTMR */
+        return env->ttmr;
+
+    case TO_SPR(10, 1): /* TTCR */
+        cpu_openrisc_count_update(cpu);
+        return env->ttcr;
+
+    default:
+        break;
+    }
+#endif
+
+/*If we later need to add tracepoints (or debug printfs) for the return
+value, it may be useful to structure the code like this:
+
+target_ulong ret = 0;
+
+switch() {
+case x:
+ ret = y;
+ break;
+case z:
+ ret = 42;
+ break;
+...
+}
+
+later something like trace_spr_read(ret);
+
+return ret;*/
+
+    /* for rd is passed in, if rd unchanged, just keep it back.  */
+    return rd;
+}
diff --git a/target-openrisc/translate.c b/target-openrisc/translate.c
index a17455d..325ba09 100644
--- a/target-openrisc/translate.c
+++ b/target-openrisc/translate.c
@@ -997,10 +997,36 @@ static void dec_misc(DisasContext *dc, uint32_t insn)
 
     case 0x2d:    /* l.mfspr */
         LOG_DIS("l.mfspr r%d, r%d, %d\n", rd, ra, I16);
+        {
+#if defined(CONFIG_USER_ONLY)
+            return;
+#else
+            TCGv_i32 ti = tcg_const_i32(I16);
+            if (dc->mem_idx == MMU_USER_IDX) {
+                gen_illegal_exception(dc);
+                return;
+            }
+            gen_helper_mfspr(cpu_R[rd], cpu_env, cpu_R[rd], cpu_R[ra], ti);
+            tcg_temp_free_i32(ti);
+#endif
+        }
         break;
 
     case 0x30:    /* l.mtspr */
         LOG_DIS("l.mtspr %d, r%d, r%d, %d\n", I5, ra, rb, I11);
+        {
+#if defined(CONFIG_USER_ONLY)
+            return;
+#else
+            TCGv_i32 im = tcg_const_i32(tmp);
+            if (dc->mem_idx == MMU_USER_IDX) {
+                gen_illegal_exception(dc);
+                return;
+            }
+            gen_helper_mtspr(cpu_env, cpu_R[ra], cpu_R[rb], im);
+            tcg_temp_free_i32(im);
+#endif
+        }
         break;
 
 /* not used yet, open it when we need or64.  */
commit ce6e1e9ec9b54811a942d6aece92fab3f5ace88d
Author: Jia Liu <proljc at gmail.com>
Date:   Fri Jul 20 15:50:48 2012 +0800

    target-or32: Add a IIS dummy board
    
    Add a IIS dummy board.
    
    Signed-off-by: Jia Liu <proljc at gmail.com>
    Signed-off-by: Blue Swirl <blauwirbel at gmail.com>

diff --git a/hw/openrisc/Makefile.objs b/hw/openrisc/Makefile.objs
index 1c541a5..38ff8f5 100644
--- a/hw/openrisc/Makefile.objs
+++ b/hw/openrisc/Makefile.objs
@@ -1,3 +1,3 @@
-obj-y = openrisc_pic.o openrisc_timer.o
+obj-y = openrisc_pic.o openrisc_sim.o openrisc_timer.o
 
 obj-y := $(addprefix ../,$(obj-y))
diff --git a/hw/openrisc_sim.c b/hw/openrisc_sim.c
new file mode 100644
index 0000000..f07f7fc
--- /dev/null
+++ b/hw/openrisc_sim.c
@@ -0,0 +1,150 @@
+/*
+ * OpenRISC simulator for use as an IIS.
+ *
+ * Copyright (c) 2011-2012 Jia Liu <proljc at gmail.com>
+ *                         Feng Gao <gf91597 at gmail.com>
+ *
+ * This library is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Lesser General Public
+ * License as published by the Free Software Foundation; either
+ * version 2 of the License, or (at your option) any later version.
+ *
+ * This library is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
+ * Lesser General Public License for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public
+ * License along with this library; if not, see <http://www.gnu.org/licenses/>.
+ */
+
+#include "hw.h"
+#include "boards.h"
+#include "elf.h"
+#include "pc.h"
+#include "loader.h"
+#include "exec-memory.h"
+#include "sysemu.h"
+#include "sysbus.h"
+#include "qtest.h"
+
+#define KERNEL_LOAD_ADDR 0x100
+
+static void main_cpu_reset(void *opaque)
+{
+    OpenRISCCPU *cpu = opaque;
+
+    cpu_reset(CPU(cpu));
+}
+
+static void openrisc_sim_net_init(MemoryRegion *address_space,
+                                  target_phys_addr_t base,
+                                  target_phys_addr_t descriptors,
+                                  qemu_irq irq, NICInfo *nd)
+{
+    DeviceState *dev;
+    SysBusDevice *s;
+
+    dev = qdev_create(NULL, "open_eth");
+    qdev_set_nic_properties(dev, nd);
+    qdev_init_nofail(dev);
+
+    s = sysbus_from_qdev(dev);
+    sysbus_connect_irq(s, 0, irq);
+    memory_region_add_subregion(address_space, base,
+                                sysbus_mmio_get_region(s, 0));
+    memory_region_add_subregion(address_space, descriptors,
+                                sysbus_mmio_get_region(s, 1));
+}
+
+static void cpu_openrisc_load_kernel(ram_addr_t ram_size,
+                                     const char *kernel_filename,
+                                     OpenRISCCPU *cpu)
+{
+    long kernel_size;
+    uint64_t elf_entry;
+    target_phys_addr_t entry;
+
+    if (kernel_filename && !qtest_enabled()) {
+        kernel_size = load_elf(kernel_filename, NULL, NULL,
+                               &elf_entry, NULL, NULL, 1, ELF_MACHINE, 1);
+        entry = elf_entry;
+        if (kernel_size < 0) {
+            kernel_size = load_uimage(kernel_filename,
+                                      &entry, NULL, NULL);
+        }
+        if (kernel_size < 0) {
+            kernel_size = load_image_targphys(kernel_filename,
+                                              KERNEL_LOAD_ADDR,
+                                              ram_size - KERNEL_LOAD_ADDR);
+            entry = KERNEL_LOAD_ADDR;
+        }
+
+        if (kernel_size < 0) {
+            qemu_log("QEMU: couldn't load the kernel '%s'\n",
+                    kernel_filename);
+            exit(1);
+        }
+    }
+
+    cpu->env.pc = entry;
+}
+
+static void openrisc_sim_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)
+{
+   OpenRISCCPU *cpu = NULL;
+    MemoryRegion *ram;
+    int n;
+
+    if (!cpu_model) {
+        cpu_model = "or1200";
+    }
+
+    for (n = 0; n < smp_cpus; n++) {
+        cpu = cpu_openrisc_init(cpu_model);
+        if (cpu == NULL) {
+            qemu_log("Unable to find CPU defineition!\n");
+            exit(1);
+        }
+        qemu_register_reset(main_cpu_reset, cpu);
+        main_cpu_reset(cpu);
+    }
+
+    ram = g_malloc(sizeof(*ram));
+    memory_region_init_ram(ram, "openrisc.ram", ram_size);
+    vmstate_register_ram_global(ram);
+    memory_region_add_subregion(get_system_memory(), 0, ram);
+
+    cpu_openrisc_pic_init(cpu);
+    cpu_openrisc_clock_init(cpu);
+
+    serial_mm_init(get_system_memory(), 0x90000000, 0, cpu->env.irq[2],
+                   115200, serial_hds[0], DEVICE_NATIVE_ENDIAN);
+
+    if (nd_table[0].vlan) {
+        openrisc_sim_net_init(get_system_memory(), 0x92000000,
+                              0x92000400, cpu->env.irq[4], nd_table);
+    }
+
+    cpu_openrisc_load_kernel(ram_size, kernel_filename, cpu);
+}
+
+static QEMUMachine openrisc_sim_machine = {
+    .name = "or32-sim",
+    .desc = "or32 simulation",
+    .init = openrisc_sim_init,
+    .max_cpus = 1,
+    .is_default = 1,
+};
+
+static void openrisc_sim_machine_init(void)
+{
+    qemu_register_machine(&openrisc_sim_machine);
+}
+
+machine_init(openrisc_sim_machine_init);
commit 99f575edccdd81e0f17863814c5867867ba67846
Author: Jia Liu <proljc at gmail.com>
Date:   Fri Jul 20 15:50:47 2012 +0800

    target-or32: Add timer support
    
    Add OpenRISC timer support.
    
    Signed-off-by: Jia Liu <proljc at gmail.com>
    Signed-off-by: Blue Swirl <blauwirbel at gmail.com>

diff --git a/hw/openrisc/Makefile.objs b/hw/openrisc/Makefile.objs
index 98900aa..1c541a5 100644
--- a/hw/openrisc/Makefile.objs
+++ b/hw/openrisc/Makefile.objs
@@ -1,3 +1,3 @@
-obj-y = openrisc_pic.o
+obj-y = openrisc_pic.o openrisc_timer.o
 
 obj-y := $(addprefix ../,$(obj-y))
diff --git a/hw/openrisc_timer.c b/hw/openrisc_timer.c
new file mode 100644
index 0000000..7916e61
--- /dev/null
+++ b/hw/openrisc_timer.c
@@ -0,0 +1,101 @@
+/*
+ * QEMU OpenRISC timer support
+ *
+ * Copyright (c) 2011-2012 Jia Liu <proljc at gmail.com>
+ *                         Zhizhou Zhang <etouzh at gmail.com>
+ *
+ * This library is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Lesser General Public
+ * License as published by the Free Software Foundation; either
+ * version 2 of the License, or (at your option) any later version.
+ *
+ * This library is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
+ * Lesser General Public License for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public
+ * License along with this library; if not, see <http://www.gnu.org/licenses/>.
+ */
+
+#include "cpu.h"
+#include "hw.h"
+#include "qemu-timer.h"
+
+#define TIMER_FREQ    (20 * 1000 * 1000)    /* 20MHz */
+
+/* The time when TTCR changes */
+static uint64_t last_clk;
+static int is_counting;
+
+void cpu_openrisc_count_update(OpenRISCCPU *cpu)
+{
+    uint64_t now, next;
+    uint32_t wait;
+
+    now = qemu_get_clock_ns(vm_clock);
+    if (!is_counting) {
+        qemu_del_timer(cpu->env.timer);
+        last_clk = now;
+        return;
+    }
+
+    cpu->env.ttcr += (uint32_t)muldiv64(now - last_clk, TIMER_FREQ,
+                                        get_ticks_per_sec());
+    last_clk = now;
+
+    if ((cpu->env.ttmr & TTMR_TP) <= (cpu->env.ttcr & TTMR_TP)) {
+        wait = TTMR_TP - (cpu->env.ttcr & TTMR_TP) + 1;
+        wait += cpu->env.ttmr & TTMR_TP;
+    } else {
+        wait = (cpu->env.ttmr & TTMR_TP) - (cpu->env.ttcr & TTMR_TP);
+    }
+
+    next = now + muldiv64(wait, get_ticks_per_sec(), TIMER_FREQ);
+    qemu_mod_timer(cpu->env.timer, next);
+}
+
+void cpu_openrisc_count_start(OpenRISCCPU *cpu)
+{
+    is_counting = 1;
+    cpu_openrisc_count_update(cpu);
+}
+
+void cpu_openrisc_count_stop(OpenRISCCPU *cpu)
+{
+    is_counting = 0;
+    cpu_openrisc_count_update(cpu);
+}
+
+static void openrisc_timer_cb(void *opaque)
+{
+    OpenRISCCPU *cpu = opaque;
+
+    if ((cpu->env.ttmr & TTMR_IE) &&
+         qemu_timer_expired(cpu->env.timer, qemu_get_clock_ns(vm_clock))) {
+        cpu->env.ttmr |= TTMR_IP;
+        cpu->env.interrupt_request |= CPU_INTERRUPT_TIMER;
+    }
+
+    switch (cpu->env.ttmr & TTMR_M) {
+    case TIMER_NONE:
+        break;
+    case TIMER_INTR:
+        cpu->env.ttcr = 0;
+        cpu_openrisc_count_start(cpu);
+        break;
+    case TIMER_SHOT:
+        cpu_openrisc_count_stop(cpu);
+        break;
+    case TIMER_CONT:
+        cpu_openrisc_count_start(cpu);
+        break;
+    }
+}
+
+void cpu_openrisc_clock_init(OpenRISCCPU *cpu)
+{
+    cpu->env.timer = qemu_new_timer_ns(vm_clock, &openrisc_timer_cb, cpu);
+    cpu->env.ttmr = 0x00000000;
+    cpu->env.ttcr = 0x00000000;
+}
diff --git a/target-openrisc/cpu.h b/target-openrisc/cpu.h
index 419c31a..df07eaf 100644
--- a/target-openrisc/cpu.h
+++ b/target-openrisc/cpu.h
@@ -220,6 +220,22 @@ enum {
     OPENRISC_FEATURE_OV64S = (1 << 9),
 };
 
+/* Tick Timer Mode Register */
+enum {
+    TTMR_TP = (0xfffffff),
+    TTMR_IP = (1 << 28),
+    TTMR_IE = (1 << 29),
+    TTMR_M  = (3 << 30),
+};
+
+/* Timer Mode */
+enum {
+    TIMER_NONE = (0 << 30),
+    TIMER_INTR = (1 << 30),
+    TIMER_SHOT = (2 << 30),
+    TIMER_CONT = (3 << 30),
+};
+
 /* TLB size */
 enum {
     DTLB_WAYS = 1,
@@ -358,6 +374,12 @@ int cpu_openrisc_handle_mmu_fault(CPUOpenRISCState *env,
 /* hw/openrisc_pic.c */
 void cpu_openrisc_pic_init(OpenRISCCPU *cpu);
 
+/* hw/openrisc_timer.c */
+void cpu_openrisc_clock_init(OpenRISCCPU *cpu);
+void cpu_openrisc_count_update(OpenRISCCPU *cpu);
+void cpu_openrisc_count_start(OpenRISCCPU *cpu);
+void cpu_openrisc_count_stop(OpenRISCCPU *cpu);
+
 void cpu_openrisc_mmu_init(OpenRISCCPU *cpu);
 int cpu_openrisc_get_phys_nommu(OpenRISCCPU *cpu,
                                 target_phys_addr_t *physical,
commit dd29c7fb0189cb2415bee3f411afcfcf9290e466
Author: Jia Liu <proljc at gmail.com>
Date:   Fri Jul 20 15:50:46 2012 +0800

    target-or32: Add PIC support
    
    Add OpenRISC Programmable Interrupt Controller support.
    
    Signed-off-by: Jia Liu <proljc at gmail.com>
    Signed-off-by: Blue Swirl <blauwirbel at gmail.com>

diff --git a/hw/openrisc/Makefile.objs b/hw/openrisc/Makefile.objs
index bfead21..98900aa 100644
--- a/hw/openrisc/Makefile.objs
+++ b/hw/openrisc/Makefile.objs
@@ -1 +1,3 @@
+obj-y = openrisc_pic.o
+
 obj-y := $(addprefix ../,$(obj-y))
diff --git a/hw/openrisc_pic.c b/hw/openrisc_pic.c
new file mode 100644
index 0000000..aaeb9a9
--- /dev/null
+++ b/hw/openrisc_pic.c
@@ -0,0 +1,60 @@
+/*
+ * OpenRISC Programmable Interrupt Controller support.
+ *
+ * Copyright (c) 2011-2012 Jia Liu <proljc at gmail.com>
+ *                         Feng Gao <gf91597 at gmail.com>
+ *
+ * This library is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Lesser General Public
+ * License as published by the Free Software Foundation; either
+ * version 2 of the License, or (at your option) any later version.
+ *
+ * This library is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
+ * Lesser General Public License for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public
+ * License along with this library; if not, see <http://www.gnu.org/licenses/>.
+ */
+
+#include "hw.h"
+#include "cpu.h"
+
+/* OpenRISC pic handler */
+static void openrisc_pic_cpu_handler(void *opaque, int irq, int level)
+{
+    OpenRISCCPU *cpu = (OpenRISCCPU *)opaque;
+    int i;
+    uint32_t irq_bit = 1 << irq;
+
+    if (irq > 31 || irq < 0) {
+        return;
+    }
+
+    if (level) {
+        cpu->env.picsr |= irq_bit;
+    } else {
+        cpu->env.picsr &= ~irq_bit;
+    }
+
+    for (i = 0; i < 32; i++) {
+        if ((cpu->env.picsr && (1 << i)) && (cpu->env.picmr && (1 << i))) {
+            cpu_interrupt(&cpu->env, CPU_INTERRUPT_HARD);
+        } else {
+            cpu_reset_interrupt(&cpu->env, CPU_INTERRUPT_HARD);
+            cpu->env.picsr &= ~(1 << i);
+        }
+    }
+}
+
+void cpu_openrisc_pic_init(OpenRISCCPU *cpu)
+{
+    int i;
+    qemu_irq *qi;
+    qi = qemu_allocate_irqs(openrisc_pic_cpu_handler, cpu, NR_IRQS);
+
+    for (i = 0; i < NR_IRQS; i++) {
+        cpu->env.irq[i] = qi[i];
+    }
+}
diff --git a/target-openrisc/cpu.h b/target-openrisc/cpu.h
index 51013f3..419c31a 100644
--- a/target-openrisc/cpu.h
+++ b/target-openrisc/cpu.h
@@ -355,6 +355,9 @@ int cpu_openrisc_handle_mmu_fault(CPUOpenRISCState *env,
 #define cpu_handle_mmu_fault cpu_openrisc_handle_mmu_fault
 
 #ifndef CONFIG_USER_ONLY
+/* hw/openrisc_pic.c */
+void cpu_openrisc_pic_init(OpenRISCCPU *cpu);
+
 void cpu_openrisc_mmu_init(OpenRISCCPU *cpu);
 int cpu_openrisc_get_phys_nommu(OpenRISCCPU *cpu,
                                 target_phys_addr_t *physical,
commit bbe418f25d070745fd350ab71c3bfca58ea5e62c
Author: Jia Liu <proljc at gmail.com>
Date:   Fri Jul 20 15:50:45 2012 +0800

    target-or32: Add instruction translation
    
    Add OpenRISC instruction tanslation routines.
    
    Signed-off-by: Jia Liu <proljc at gmail.com>
    Signed-off-by: Blue Swirl <blauwirbel at gmail.com>

diff --git a/target-openrisc/translate.c b/target-openrisc/translate.c
index a2b9b4f..a17455d 100644
--- a/target-openrisc/translate.c
+++ b/target-openrisc/translate.c
@@ -25,6 +25,11 @@
 #include "qemu-common.h"
 #include "qemu-log.h"
 #include "config.h"
+#include "bitops.h"
+
+#include "helper.h"
+#define GEN_HELPER 1
+#include "helper.h"
 
 #define OPENRISC_DISAS
 
@@ -34,14 +39,1743 @@
 #  define LOG_DIS(...) do { } while (0)
 #endif
 
+typedef struct DisasContext {
+    TranslationBlock *tb;
+    target_ulong pc, ppc, npc;
+    uint32_t tb_flags, synced_flags, flags;
+    uint32_t is_jmp;
+    uint32_t mem_idx;
+    int singlestep_enabled;
+    uint32_t delayed_branch;
+} DisasContext;
+
+static TCGv_ptr cpu_env;
+static TCGv cpu_sr;
+static TCGv cpu_R[32];
+static TCGv cpu_pc;
+static TCGv jmp_pc;            /* l.jr/l.jalr temp pc */
+static TCGv cpu_npc;
+static TCGv cpu_ppc;
+static TCGv_i32 env_btaken;    /* bf/bnf , F flag taken */
+static TCGv_i32 fpcsr;
+static TCGv machi, maclo;
+static TCGv fpmaddhi, fpmaddlo;
+static TCGv_i32 env_flags;
+#include "gen-icount.h"
+
 void openrisc_translate_init(void)
 {
+    static const char * const regnames[] = {
+        "r0", "r1", "r2", "r3", "r4", "r5", "r6", "r7",
+        "r8", "r9", "r10", "r11", "r12", "r13", "r14", "r15",
+        "r16", "r17", "r18", "r19", "r20", "r21", "r22", "r23",
+        "r24", "r25", "r26", "r27", "r28", "r29", "r30", "r31",
+    };
+    int i;
+
+    cpu_env = tcg_global_reg_new_ptr(TCG_AREG0, "env");
+    cpu_sr = tcg_global_mem_new(TCG_AREG0,
+                                offsetof(CPUOpenRISCState, sr), "sr");
+    env_flags = tcg_global_mem_new_i32(TCG_AREG0,
+                                       offsetof(CPUOpenRISCState, flags),
+                                       "flags");
+    cpu_pc = tcg_global_mem_new(TCG_AREG0,
+                                offsetof(CPUOpenRISCState, pc), "pc");
+    cpu_npc = tcg_global_mem_new(TCG_AREG0,
+                                 offsetof(CPUOpenRISCState, npc), "npc");
+    cpu_ppc = tcg_global_mem_new(TCG_AREG0,
+                                 offsetof(CPUOpenRISCState, ppc), "ppc");
+    jmp_pc = tcg_global_mem_new(TCG_AREG0,
+                                offsetof(CPUOpenRISCState, jmp_pc), "jmp_pc");
+    env_btaken = tcg_global_mem_new_i32(TCG_AREG0,
+                                        offsetof(CPUOpenRISCState, btaken),
+                                        "btaken");
+    fpcsr = tcg_global_mem_new_i32(TCG_AREG0,
+                                   offsetof(CPUOpenRISCState, fpcsr),
+                                   "fpcsr");
+    machi = tcg_global_mem_new(TCG_AREG0,
+                               offsetof(CPUOpenRISCState, machi),
+                               "machi");
+    maclo = tcg_global_mem_new(TCG_AREG0,
+                               offsetof(CPUOpenRISCState, maclo),
+                               "maclo");
+    fpmaddhi = tcg_global_mem_new(TCG_AREG0,
+                                  offsetof(CPUOpenRISCState, fpmaddhi),
+                                  "fpmaddhi");
+    fpmaddlo = tcg_global_mem_new(TCG_AREG0,
+                                  offsetof(CPUOpenRISCState, fpmaddlo),
+                                  "fpmaddlo");
+    for (i = 0; i < 32; i++) {
+        cpu_R[i] = tcg_global_mem_new(TCG_AREG0,
+                                      offsetof(CPUOpenRISCState, gpr[i]),
+                                      regnames[i]);
+    }
+#define GEN_HELPER 2
+#include "helper.h"
+}
+
+/* Writeback SR_F transaltion-space to execution-space.  */
+static inline void wb_SR_F(void)
+{
+    int label;
+
+    label = gen_new_label();
+    tcg_gen_andi_tl(cpu_sr, cpu_sr, ~SR_F);
+    tcg_gen_brcondi_tl(TCG_COND_EQ, env_btaken, 0, label);
+    tcg_gen_ori_tl(cpu_sr, cpu_sr, SR_F);
+    gen_set_label(label);
+}
+
+static inline int zero_extend(unsigned int val, int width)
+{
+    return val & ((1 << width) - 1);
+}
+
+static inline int sign_extend(unsigned int val, int width)
+{
+    int sval;
+
+    /* LSL */
+    val <<= TARGET_LONG_BITS - width;
+    sval = val;
+    /* ASR.  */
+    sval >>= TARGET_LONG_BITS - width;
+    return sval;
+}
+
+static inline void gen_sync_flags(DisasContext *dc)
+{
+    /* Sync the tb dependent flag between translate and runtime.  */
+    if (dc->tb_flags != dc->synced_flags) {
+        tcg_gen_movi_tl(env_flags, dc->tb_flags);
+        dc->synced_flags = dc->tb_flags;
+    }
+}
+
+static void gen_exception(DisasContext *dc, unsigned int excp)
+{
+    TCGv_i32 tmp = tcg_const_i32(excp);
+    gen_helper_exception(cpu_env, tmp);
+    tcg_temp_free_i32(tmp);
+}
+
+static void gen_illegal_exception(DisasContext *dc)
+{
+    tcg_gen_movi_tl(cpu_pc, dc->pc);
+    gen_exception(dc, EXCP_ILLEGAL);
+    dc->is_jmp = DISAS_UPDATE;
+}
+
+/* not used yet, open it when we need or64.  */
+/*#ifdef TARGET_OPENRISC64
+static void check_ob64s(DisasContext *dc)
+{
+    if (!(dc->flags & CPUCFGR_OB64S)) {
+        gen_illegal_exception(dc);
+    }
+}
+
+static void check_of64s(DisasContext *dc)
+{
+    if (!(dc->flags & CPUCFGR_OF64S)) {
+        gen_illegal_exception(dc);
+    }
+}
+
+static void check_ov64s(DisasContext *dc)
+{
+    if (!(dc->flags & CPUCFGR_OV64S)) {
+        gen_illegal_exception(dc);
+    }
+}
+#endif*/
+
+static void gen_goto_tb(DisasContext *dc, int n, target_ulong dest)
+{
+    TranslationBlock *tb;
+    tb = dc->tb;
+    if ((tb->pc & TARGET_PAGE_MASK) == (dest & TARGET_PAGE_MASK) &&
+                                       likely(!dc->singlestep_enabled)) {
+        tcg_gen_movi_tl(cpu_pc, dest);
+        tcg_gen_goto_tb(n);
+        tcg_gen_exit_tb((tcg_target_long)tb + n);
+    } else {
+        tcg_gen_movi_tl(cpu_pc, dest);
+        if (dc->singlestep_enabled) {
+            gen_exception(dc, EXCP_DEBUG);
+        }
+        tcg_gen_exit_tb(0);
+    }
+}
+
+static void gen_jump(DisasContext *dc, uint32_t imm, uint32_t reg, uint32_t op0)
+{
+    target_ulong tmp_pc;
+    int lab = gen_new_label();
+    TCGv sr_f = tcg_temp_new();
+    /* N26, 26bits imm */
+    tmp_pc = sign_extend((imm<<2), 26) + dc->pc;
+    tcg_gen_andi_tl(sr_f, cpu_sr, SR_F);
+
+    if (op0 == 0x00) {    /* l.j */
+        tcg_gen_movi_tl(jmp_pc, tmp_pc);
+    } else if (op0 == 0x01) {    /* l.jal */
+        tcg_gen_movi_tl(cpu_R[9], (dc->pc + 8));
+        tcg_gen_movi_tl(jmp_pc, tmp_pc);
+    } else if (op0 == 0x03) {    /* l.bnf */
+        tcg_gen_movi_tl(jmp_pc, dc->pc+8);
+        tcg_gen_brcondi_i32(TCG_COND_EQ, sr_f, SR_F, lab);
+        tcg_gen_movi_tl(jmp_pc, tmp_pc);
+        gen_set_label(lab);
+    } else if (op0 == 0x04) {    /* l.bf */
+        tcg_gen_movi_tl(jmp_pc, dc->pc+8);
+        tcg_gen_brcondi_i32(TCG_COND_NE, sr_f, SR_F, lab);
+        tcg_gen_movi_tl(jmp_pc, tmp_pc);
+        gen_set_label(lab);
+    } else if (op0 == 0x11) {    /* l.jr */
+        tcg_gen_mov_tl(jmp_pc, cpu_R[reg]);
+    } else if (op0 == 0x12) {    /* l.jalr */
+        tcg_gen_movi_tl(cpu_R[9], (dc->pc + 8));
+        tcg_gen_mov_tl(jmp_pc, cpu_R[reg]);
+    } else {
+        gen_illegal_exception(dc);
+    }
+
+    tcg_temp_free(sr_f);
+    dc->delayed_branch = 2;
+    dc->tb_flags |= D_FLAG;
+    gen_sync_flags(dc);
+}
+
+static void dec_calc(DisasContext *dc, uint32_t insn)
+{
+    uint32_t op0, op1, op2;
+    uint32_t ra, rb, rd;
+    op0 = extract32(insn, 0, 4);
+    op1 = extract32(insn, 8, 2);
+    op2 = extract32(insn, 6, 2);
+    ra = extract32(insn, 16, 5);
+    rb = extract32(insn, 11, 5);
+    rd = extract32(insn, 21, 5);
+
+    switch (op0) {
+    case 0x0000:
+        switch (op1) {
+        case 0x00:    /* l.add */
+            LOG_DIS("l.add r%d, r%d, r%d\n", rd, ra, rb);
+            {
+                int lab = gen_new_label();
+                TCGv_i64 ta = tcg_temp_new_i64();
+                TCGv_i64 tb = tcg_temp_new_i64();
+                TCGv_i64 td = tcg_temp_local_new_i64();
+                TCGv_i32 res = tcg_temp_local_new_i32();
+                TCGv_i32 sr_ove = tcg_temp_local_new_i32();
+                tcg_gen_extu_i32_i64(ta, cpu_R[ra]);
+                tcg_gen_extu_i32_i64(tb, cpu_R[rb]);
+                tcg_gen_add_i64(td, ta, tb);
+                tcg_gen_trunc_i64_i32(res, td);
+                tcg_gen_shri_i64(td, td, 31);
+                tcg_gen_andi_i64(td, td, 0x3);
+                /* Jump to lab when no overflow.  */
+                tcg_gen_brcondi_i64(TCG_COND_EQ, td, 0x0, lab);
+                tcg_gen_brcondi_i64(TCG_COND_EQ, td, 0x3, lab);
+                tcg_gen_ori_i32(cpu_sr, cpu_sr, (SR_OV | SR_CY));
+                tcg_gen_andi_i32(sr_ove, cpu_sr, SR_OVE);
+                tcg_gen_brcondi_i32(TCG_COND_NE, sr_ove, SR_OVE, lab);
+                gen_exception(dc, EXCP_RANGE);
+                gen_set_label(lab);
+                tcg_gen_mov_i32(cpu_R[rd], res);
+                tcg_temp_free_i64(ta);
+                tcg_temp_free_i64(tb);
+                tcg_temp_free_i64(td);
+                tcg_temp_free_i32(res);
+                tcg_temp_free_i32(sr_ove);
+            }
+            break;
+        default:
+            gen_illegal_exception(dc);
+            break;
+        }
+        break;
+
+    case 0x0001:    /* l.addc */
+        switch (op1) {
+        case 0x00:
+            LOG_DIS("l.addc r%d, r%d, r%d\n", rd, ra, rb);
+            {
+                int lab = gen_new_label();
+                TCGv_i64 ta = tcg_temp_new_i64();
+                TCGv_i64 tb = tcg_temp_new_i64();
+                TCGv_i64 tcy = tcg_temp_local_new_i64();
+                TCGv_i64 td = tcg_temp_local_new_i64();
+                TCGv_i32 res = tcg_temp_local_new_i32();
+                TCGv_i32 sr_cy = tcg_temp_local_new_i32();
+                TCGv_i32 sr_ove = tcg_temp_local_new_i32();
+                tcg_gen_extu_i32_i64(ta, cpu_R[ra]);
+                tcg_gen_extu_i32_i64(tb, cpu_R[rb]);
+                tcg_gen_andi_i32(sr_cy, cpu_sr, SR_CY);
+                tcg_gen_extu_i32_i64(tcy, sr_cy);
+                tcg_gen_shri_i64(tcy, tcy, 10);
+                tcg_gen_add_i64(td, ta, tb);
+                tcg_gen_add_i64(td, td, tcy);
+                tcg_gen_trunc_i64_i32(res, td);
+                tcg_gen_shri_i64(td, td, 32);
+                tcg_gen_andi_i64(td, td, 0x3);
+                /* Jump to lab when no overflow.  */
+                tcg_gen_brcondi_i64(TCG_COND_EQ, td, 0x0, lab);
+                tcg_gen_brcondi_i64(TCG_COND_EQ, td, 0x3, lab);
+                tcg_gen_ori_i32(cpu_sr, cpu_sr, (SR_OV | SR_CY));
+                tcg_gen_andi_i32(sr_ove, cpu_sr, SR_OVE);
+                tcg_gen_brcondi_i32(TCG_COND_NE, sr_ove, SR_OVE, lab);
+                gen_exception(dc, EXCP_RANGE);
+                gen_set_label(lab);
+                tcg_gen_mov_i32(cpu_R[rd], res);
+                tcg_temp_free_i64(ta);
+                tcg_temp_free_i64(tb);
+                tcg_temp_free_i64(tcy);
+                tcg_temp_free_i64(td);
+                tcg_temp_free_i32(res);
+                tcg_temp_free_i32(sr_cy);
+                tcg_temp_free_i32(sr_ove);
+            }
+            break;
+        default:
+            gen_illegal_exception(dc);
+            break;
+        }
+        break;
+
+    case 0x0002:    /* l.sub */
+        switch (op1) {
+        case 0x00:
+            LOG_DIS("l.sub r%d, r%d, r%d\n", rd, ra, rb);
+            {
+                int lab = gen_new_label();
+                TCGv_i64 ta = tcg_temp_new_i64();
+                TCGv_i64 tb = tcg_temp_new_i64();
+                TCGv_i64 td = tcg_temp_local_new_i64();
+                TCGv_i32 res = tcg_temp_local_new_i32();
+                TCGv_i32 sr_ove = tcg_temp_local_new_i32();
+
+                tcg_gen_extu_i32_i64(ta, cpu_R[ra]);
+                tcg_gen_extu_i32_i64(tb, cpu_R[rb]);
+                tcg_gen_sub_i64(td, ta, tb);
+                tcg_gen_trunc_i64_i32(res, td);
+                tcg_gen_shri_i64(td, td, 31);
+                tcg_gen_andi_i64(td, td, 0x3);
+                /* Jump to lab when no overflow.  */
+                tcg_gen_brcondi_i64(TCG_COND_EQ, td, 0x0, lab);
+                tcg_gen_brcondi_i64(TCG_COND_EQ, td, 0x3, lab);
+                tcg_gen_ori_i32(cpu_sr, cpu_sr, (SR_OV | SR_CY));
+                tcg_gen_andi_i32(sr_ove, cpu_sr, SR_OVE);
+                tcg_gen_brcondi_i32(TCG_COND_NE, sr_ove, SR_OVE, lab);
+                gen_exception(dc, EXCP_RANGE);
+                gen_set_label(lab);
+                tcg_gen_mov_i32(cpu_R[rd], res);
+                tcg_temp_free_i64(ta);
+                tcg_temp_free_i64(tb);
+                tcg_temp_free_i64(td);
+                tcg_temp_free_i32(res);
+                tcg_temp_free_i32(sr_ove);
+            }
+            break;
+        default:
+            gen_illegal_exception(dc);
+            break;
+        }
+        break;
+
+    case 0x0003:    /* l.and */
+        switch (op1) {
+        case 0x00:
+            LOG_DIS("l.and r%d, r%d, r%d\n", rd, ra, rb);
+            tcg_gen_and_tl(cpu_R[rd], cpu_R[ra], cpu_R[rb]);
+            break;
+        default:
+            gen_illegal_exception(dc);
+            break;
+        }
+        break;
+
+    case 0x0004:    /* l.or */
+        switch (op1) {
+        case 0x00:
+            LOG_DIS("l.or r%d, r%d, r%d\n", rd, ra, rb);
+            tcg_gen_or_tl(cpu_R[rd], cpu_R[ra], cpu_R[rb]);
+            break;
+        default:
+            gen_illegal_exception(dc);
+            break;
+        }
+        break;
+
+    case 0x0005:
+        switch (op1) {
+        case 0x00:    /* l.xor */
+            LOG_DIS("l.xor r%d, r%d, r%d\n", rd, ra, rb);
+            tcg_gen_xor_tl(cpu_R[rd], cpu_R[ra], cpu_R[rb]);
+            break;
+        default:
+            gen_illegal_exception(dc);
+            break;
+        }
+        break;
+
+    case 0x0006:
+        switch (op1) {
+        case 0x03:    /* l.mul */
+            LOG_DIS("l.mul r%d, r%d, r%d\n", rd, ra, rb);
+            if (ra != 0 && rb != 0) {
+                gen_helper_mul32(cpu_R[rd], cpu_env, cpu_R[ra], cpu_R[rb]);
+            } else {
+                tcg_gen_movi_tl(cpu_R[rd], 0x0);
+            }
+            break;
+        default:
+            gen_illegal_exception(dc);
+            break;
+        }
+        break;
+
+    case 0x0009:
+        switch (op1) {
+        case 0x03:    /* l.div */
+            LOG_DIS("l.div r%d, r%d, r%d\n", rd, ra, rb);
+            {
+                int lab0 = gen_new_label();
+                int lab1 = gen_new_label();
+                int lab2 = gen_new_label();
+                int lab3 = gen_new_label();
+                TCGv_i32 sr_ove = tcg_temp_local_new_i32();
+                if (rb == 0) {
+                    tcg_gen_ori_tl(cpu_sr, cpu_sr, (SR_OV | SR_CY));
+                    tcg_gen_andi_tl(sr_ove, cpu_sr, SR_OVE);
+                    tcg_gen_brcondi_tl(TCG_COND_NE, sr_ove, SR_OVE, lab0);
+                    gen_exception(dc, EXCP_RANGE);
+                    gen_set_label(lab0);
+                } else {
+                    tcg_gen_brcondi_tl(TCG_COND_EQ, cpu_R[rb],
+                                       0x00000000, lab1);
+                    tcg_gen_brcondi_tl(TCG_COND_NE, cpu_R[ra],
+                                       0x80000000, lab2);
+                    tcg_gen_brcondi_tl(TCG_COND_NE, cpu_R[rb],
+                                       0xffffffff, lab2);
+                    gen_set_label(lab1);
+                    tcg_gen_ori_tl(cpu_sr, cpu_sr, (SR_OV | SR_CY));
+                    tcg_gen_andi_tl(sr_ove, cpu_sr, SR_OVE);
+                    tcg_gen_brcondi_tl(TCG_COND_NE, sr_ove, SR_OVE, lab3);
+                    gen_exception(dc, EXCP_RANGE);
+                    gen_set_label(lab2);
+                    tcg_gen_div_tl(cpu_R[rd], cpu_R[ra], cpu_R[rb]);
+                    gen_set_label(lab3);
+                }
+                tcg_temp_free_i32(sr_ove);
+            }
+            break;
+
+        default:
+            gen_illegal_exception(dc);
+            break;
+        }
+        break;
+
+    case 0x000a:
+        switch (op1) {
+        case 0x03:    /* l.divu */
+            LOG_DIS("l.divu r%d, r%d, r%d\n", rd, ra, rb);
+            {
+                int lab0 = gen_new_label();
+                int lab1 = gen_new_label();
+                int lab2 = gen_new_label();
+                TCGv_i32 sr_ove = tcg_temp_local_new_i32();
+                if (rb == 0) {
+                    tcg_gen_ori_tl(cpu_sr, cpu_sr, (SR_OV | SR_CY));
+                    tcg_gen_andi_tl(sr_ove, cpu_sr, SR_OVE);
+                    tcg_gen_brcondi_tl(TCG_COND_NE, sr_ove, SR_OVE, lab0);
+                    gen_exception(dc, EXCP_RANGE);
+                    gen_set_label(lab0);
+                } else {
+                    tcg_gen_brcondi_tl(TCG_COND_NE, cpu_R[rb],
+                                       0x00000000, lab1);
+                    tcg_gen_ori_tl(cpu_sr, cpu_sr, (SR_OV | SR_CY));
+                    tcg_gen_andi_tl(sr_ove, cpu_sr, SR_OVE);
+                    tcg_gen_brcondi_tl(TCG_COND_NE, sr_ove, SR_OVE, lab2);
+                    gen_exception(dc, EXCP_RANGE);
+                    gen_set_label(lab1);
+                    tcg_gen_divu_tl(cpu_R[rd], cpu_R[ra], cpu_R[rb]);
+                    gen_set_label(lab2);
+                }
+                tcg_temp_free_i32(sr_ove);
+            }
+            break;
+
+        default:
+            gen_illegal_exception(dc);
+            break;
+        }
+        break;
+
+    case 0x000b:
+        switch (op1) {
+        case 0x03:    /* l.mulu */
+            LOG_DIS("l.mulu r%d, r%d, r%d\n", rd, ra, rb);
+            if (rb != 0 && ra != 0) {
+                TCGv_i64 result = tcg_temp_local_new_i64();
+                TCGv_i64 tra = tcg_temp_local_new_i64();
+                TCGv_i64 trb = tcg_temp_local_new_i64();
+                TCGv_i64 high = tcg_temp_new_i64();
+                TCGv_i32 sr_ove = tcg_temp_local_new_i32();
+                int lab = gen_new_label();
+                /* Calculate the each result.  */
+                tcg_gen_extu_i32_i64(tra, cpu_R[ra]);
+                tcg_gen_extu_i32_i64(trb, cpu_R[rb]);
+                tcg_gen_mul_i64(result, tra, trb);
+                tcg_temp_free_i64(tra);
+                tcg_temp_free_i64(trb);
+                tcg_gen_shri_i64(high, result, TARGET_LONG_BITS);
+                /* Overflow or not.  */
+                tcg_gen_brcondi_i64(TCG_COND_EQ, high, 0x00000000, lab);
+                tcg_gen_ori_tl(cpu_sr, cpu_sr, (SR_OV | SR_CY));
+                tcg_gen_andi_tl(sr_ove, cpu_sr, SR_OVE);
+                tcg_gen_brcondi_tl(TCG_COND_NE, sr_ove, SR_OVE, lab);
+                gen_exception(dc, EXCP_RANGE);
+                gen_set_label(lab);
+                tcg_temp_free_i64(high);
+                tcg_gen_trunc_i64_tl(cpu_R[rd], result);
+                tcg_temp_free_i64(result);
+                tcg_temp_free_i32(sr_ove);
+            } else {
+                tcg_gen_movi_tl(cpu_R[rd], 0);
+            }
+            break;
+
+        default:
+            gen_illegal_exception(dc);
+            break;
+        }
+        break;
+
+    case 0x000e:
+        switch (op1) {
+        case 0x00:    /* l.cmov */
+            LOG_DIS("l.cmov r%d, r%d, r%d\n", rd, ra, rb);
+            {
+                int lab = gen_new_label();
+                TCGv res = tcg_temp_local_new();
+                TCGv sr_f = tcg_temp_new();
+                tcg_gen_andi_tl(sr_f, cpu_sr, SR_F);
+                tcg_gen_mov_tl(res, cpu_R[rb]);
+                tcg_gen_brcondi_tl(TCG_COND_NE, sr_f, SR_F, lab);
+                tcg_gen_mov_tl(res, cpu_R[ra]);
+                gen_set_label(lab);
+                tcg_gen_mov_tl(cpu_R[rd], res);
+                tcg_temp_free(sr_f);
+                tcg_temp_free(res);
+            }
+            break;
+
+        default:
+            gen_illegal_exception(dc);
+            break;
+        }
+        break;
+
+    case 0x000f:
+        switch (op1) {
+        case 0x00:    /* l.ff1 */
+            LOG_DIS("l.ff1 r%d, r%d, r%d\n", rd, ra, rb);
+            gen_helper_ff1(cpu_R[rd], cpu_R[ra]);
+            break;
+        case 0x01:    /* l.fl1 */
+            LOG_DIS("l.fl1 r%d, r%d, r%d\n", rd, ra, rb);
+            gen_helper_fl1(cpu_R[rd], cpu_R[ra]);
+            break;
+
+        default:
+            gen_illegal_exception(dc);
+            break;
+        }
+        break;
+
+    case 0x0008:
+        switch (op1) {
+        case 0x00:
+            switch (op2) {
+            case 0x00:    /* l.sll */
+                LOG_DIS("l.sll r%d, r%d, r%d\n", rd, ra, rb);
+                tcg_gen_shl_tl(cpu_R[rd], cpu_R[ra], cpu_R[rb]);
+                break;
+            case 0x01:    /* l.srl */
+                LOG_DIS("l.srl r%d, r%d, r%d\n", rd, ra, rb);
+                tcg_gen_shr_tl(cpu_R[rd], cpu_R[ra], cpu_R[rb]);
+                break;
+            case 0x02:    /* l.sra */
+                LOG_DIS("l.sra r%d, r%d, r%d\n", rd, ra, rb);
+                tcg_gen_sar_tl(cpu_R[rd], cpu_R[ra], cpu_R[rb]);
+                break;
+            case 0x03:    /* l.ror */
+                LOG_DIS("l.ror r%d, r%d, r%d\n", rd, ra, rb);
+                tcg_gen_rotr_tl(cpu_R[rd], cpu_R[ra], cpu_R[rb]);
+                break;
+
+            default:
+                gen_illegal_exception(dc);
+                break;
+            }
+            break;
+
+        default:
+            gen_illegal_exception(dc);
+            break;
+        }
+        break;
+
+    case 0x000c:
+        switch (op1) {
+        case 0x00:
+            switch (op2) {
+            case 0x00:    /* l.exths */
+                LOG_DIS("l.exths r%d, r%d\n", rd, ra);
+                tcg_gen_ext16s_tl(cpu_R[rd], cpu_R[ra]);
+                break;
+            case 0x01:    /* l.extbs */
+                LOG_DIS("l.extbs r%d, r%d\n", rd, ra);
+                tcg_gen_ext8s_tl(cpu_R[rd], cpu_R[ra]);
+                break;
+            case 0x02:    /* l.exthz */
+                LOG_DIS("l.exthz r%d, r%d\n", rd, ra);
+                tcg_gen_ext16u_tl(cpu_R[rd], cpu_R[ra]);
+                break;
+            case 0x03:    /* l.extbz */
+                LOG_DIS("l.extbz r%d, r%d\n", rd, ra);
+                tcg_gen_ext8u_tl(cpu_R[rd], cpu_R[ra]);
+                break;
+
+            default:
+                gen_illegal_exception(dc);
+                break;
+            }
+            break;
+
+        default:
+            gen_illegal_exception(dc);
+            break;
+        }
+        break;
+
+    case 0x000d:
+        switch (op1) {
+        case 0x00:
+            switch (op2) {
+            case 0x00:    /* l.extws */
+                LOG_DIS("l.extws r%d, r%d\n", rd, ra);
+                tcg_gen_ext32s_tl(cpu_R[rd], cpu_R[ra]);
+                break;
+            case 0x01:    /* l.extwz */
+                LOG_DIS("l.extwz r%d, r%d\n", rd, ra);
+                tcg_gen_ext32u_tl(cpu_R[rd], cpu_R[ra]);
+                break;
+
+            default:
+                gen_illegal_exception(dc);
+                break;
+            }
+            break;
+
+        default:
+            gen_illegal_exception(dc);
+            break;
+        }
+        break;
+
+    default:
+        gen_illegal_exception(dc);
+        break;
+    }
+}
+
+static void dec_misc(DisasContext *dc, uint32_t insn)
+{
+    uint32_t op0, op1;
+    uint32_t ra, rb, rd;
+#ifdef OPENRISC_DISAS
+    uint32_t L6, K5;
+#endif
+    uint32_t I16, I5, I11, N26, tmp;
+    op0 = extract32(insn, 26, 6);
+    op1 = extract32(insn, 24, 2);
+    ra = extract32(insn, 16, 5);
+    rb = extract32(insn, 11, 5);
+    rd = extract32(insn, 21, 5);
+#ifdef OPENRISC_DISAS
+    L6 = extract32(insn, 5, 6);
+    K5 = extract32(insn, 0, 5);
+#endif
+    I16 = extract32(insn, 0, 16);
+    I5 = extract32(insn, 21, 5);
+    I11 = extract32(insn, 0, 11);
+    N26 = extract32(insn, 0, 26);
+    tmp = (I5<<11) + I11;
+
+    switch (op0) {
+    case 0x00:    /* l.j */
+        LOG_DIS("l.j %d\n", N26);
+        gen_jump(dc, N26, 0, op0);
+        break;
+
+    case 0x01:    /* l.jal */
+        LOG_DIS("l.jal %d\n", N26);
+        gen_jump(dc, N26, 0, op0);
+        break;
+
+    case 0x03:    /* l.bnf */
+        LOG_DIS("l.bnf %d\n", N26);
+        gen_jump(dc, N26, 0, op0);
+        break;
+
+    case 0x04:    /* l.bf */
+        LOG_DIS("l.bf %d\n", N26);
+        gen_jump(dc, N26, 0, op0);
+        break;
+
+    case 0x05:
+        switch (op1) {
+        case 0x01:    /* l.nop */
+            LOG_DIS("l.nop %d\n", I16);
+            break;
+
+        default:
+            gen_illegal_exception(dc);
+            break;
+        }
+        break;
+
+    case 0x11:    /* l.jr */
+        LOG_DIS("l.jr r%d\n", rb);
+         gen_jump(dc, 0, rb, op0);
+         break;
+
+    case 0x12:    /* l.jalr */
+        LOG_DIS("l.jalr r%d\n", rb);
+        gen_jump(dc, 0, rb, op0);
+        break;
+
+    case 0x13:    /* l.maci */
+        LOG_DIS("l.maci %d, r%d, %d\n", I5, ra, I11);
+        {
+            TCGv_i64 t1 = tcg_temp_new_i64();
+            TCGv_i64 t2 = tcg_temp_new_i64();
+            TCGv_i32 dst = tcg_temp_new_i32();
+            TCGv ttmp = tcg_const_tl(tmp);
+            tcg_gen_mul_tl(dst, cpu_R[ra], ttmp);
+            tcg_gen_ext_i32_i64(t1, dst);
+            tcg_gen_concat_i32_i64(t2, maclo, machi);
+            tcg_gen_add_i64(t2, t2, t1);
+            tcg_gen_trunc_i64_i32(maclo, t2);
+            tcg_gen_shri_i64(t2, t2, 32);
+            tcg_gen_trunc_i64_i32(machi, t2);
+            tcg_temp_free_i32(dst);
+            tcg_temp_free(ttmp);
+            tcg_temp_free_i64(t1);
+            tcg_temp_free_i64(t2);
+        }
+        break;
+
+    case 0x09:    /* l.rfe */
+        LOG_DIS("l.rfe\n");
+        {
+#if defined(CONFIG_USER_ONLY)
+            return;
+#else
+            if (dc->mem_idx == MMU_USER_IDX) {
+                gen_illegal_exception(dc);
+                return;
+            }
+            gen_helper_rfe(cpu_env);
+            dc->is_jmp = DISAS_UPDATE;
+#endif
+        }
+        break;
+
+    case 0x1c:    /* l.cust1 */
+        LOG_DIS("l.cust1\n");
+        break;
+
+    case 0x1d:    /* l.cust2 */
+        LOG_DIS("l.cust2\n");
+        break;
+
+    case 0x1e:    /* l.cust3 */
+        LOG_DIS("l.cust3\n");
+        break;
+
+    case 0x1f:    /* l.cust4 */
+        LOG_DIS("l.cust4\n");
+        break;
+
+    case 0x3c:    /* l.cust5 */
+        LOG_DIS("l.cust5 r%d, r%d, r%d, %d, %d\n", rd, ra, rb, L6, K5);
+        break;
+
+    case 0x3d:    /* l.cust6 */
+        LOG_DIS("l.cust6\n");
+        break;
+
+    case 0x3e:    /* l.cust7 */
+        LOG_DIS("l.cust7\n");
+        break;
+
+    case 0x3f:    /* l.cust8 */
+        LOG_DIS("l.cust8\n");
+        break;
+
+/* not used yet, open it when we need or64.  */
+/*#ifdef TARGET_OPENRISC64
+    case 0x20:     l.ld
+        LOG_DIS("l.ld r%d, r%d, %d\n", rd, ra, I16);
+        {
+            check_ob64s(dc);
+            TCGv_i64 t0 = tcg_temp_new_i64();
+            tcg_gen_addi_i64(t0, cpu_R[ra], sign_extend(I16, 16));
+            tcg_gen_qemu_ld64(cpu_R[rd], t0, dc->mem_idx);
+            tcg_temp_free_i64(t0);
+        }
+        break;
+#endif*/
+
+    case 0x21:    /* l.lwz */
+        LOG_DIS("l.lwz r%d, r%d, %d\n", rd, ra, I16);
+        {
+            TCGv t0 = tcg_temp_new();
+            tcg_gen_addi_tl(t0, cpu_R[ra], sign_extend(I16, 16));
+            tcg_gen_qemu_ld32u(cpu_R[rd], t0, dc->mem_idx);
+            tcg_temp_free(t0);
+        }
+        break;
+
+    case 0x22:    /* l.lws */
+        LOG_DIS("l.lws r%d, r%d, %d\n", rd, ra, I16);
+        {
+            TCGv t0 = tcg_temp_new();
+            tcg_gen_addi_tl(t0, cpu_R[ra], sign_extend(I16, 16));
+            tcg_gen_qemu_ld32s(cpu_R[rd], t0, dc->mem_idx);
+            tcg_temp_free(t0);
+        }
+        break;
+
+    case 0x23:    /* l.lbz */
+        LOG_DIS("l.lbz r%d, r%d, %d\n", rd, ra, I16);
+        {
+            TCGv t0 = tcg_temp_new();
+            tcg_gen_addi_tl(t0, cpu_R[ra], sign_extend(I16, 16));
+            tcg_gen_qemu_ld8u(cpu_R[rd], t0, dc->mem_idx);
+            tcg_temp_free(t0);
+        }
+        break;
+
+    case 0x24:    /* l.lbs */
+        LOG_DIS("l.lbs r%d, r%d, %d\n", rd, ra, I16);
+        {
+            TCGv t0 = tcg_temp_new();
+            tcg_gen_addi_tl(t0, cpu_R[ra], sign_extend(I16, 16));
+            tcg_gen_qemu_ld8s(cpu_R[rd], t0, dc->mem_idx);
+            tcg_temp_free(t0);
+        }
+        break;
+
+    case 0x25:    /* l.lhz */
+        LOG_DIS("l.lhz r%d, r%d, %d\n", rd, ra, I16);
+        {
+            TCGv t0 = tcg_temp_new();
+            tcg_gen_addi_tl(t0, cpu_R[ra], sign_extend(I16, 16));
+            tcg_gen_qemu_ld16u(cpu_R[rd], t0, dc->mem_idx);
+            tcg_temp_free(t0);
+        }
+        break;
+
+    case 0x26:    /* l.lhs */
+        LOG_DIS("l.lhs r%d, r%d, %d\n", rd, ra, I16);
+        {
+            TCGv t0 = tcg_temp_new();
+            tcg_gen_addi_tl(t0, cpu_R[ra], sign_extend(I16, 16));
+            tcg_gen_qemu_ld16s(cpu_R[rd], t0, dc->mem_idx);
+            tcg_temp_free(t0);
+        }
+        break;
+
+    case 0x27:    /* l.addi */
+        LOG_DIS("l.addi r%d, r%d, %d\n", rd, ra, I16);
+        {
+            int lab = gen_new_label();
+            TCGv_i64 ta = tcg_temp_new_i64();
+            TCGv_i64 td = tcg_temp_local_new_i64();
+            TCGv_i32 res = tcg_temp_local_new_i32();
+            TCGv_i32 sr_ove = tcg_temp_local_new_i32();
+            tcg_gen_extu_i32_i64(ta, cpu_R[ra]);
+            tcg_gen_addi_i64(td, ta, sign_extend(I16, 16));
+            tcg_gen_trunc_i64_i32(res, td);
+            tcg_gen_shri_i64(td, td, 32);
+            tcg_gen_andi_i64(td, td, 0x3);
+            /* Jump to lab when no overflow.  */
+            tcg_gen_brcondi_i64(TCG_COND_EQ, td, 0x0, lab);
+            tcg_gen_brcondi_i64(TCG_COND_EQ, td, 0x3, lab);
+            tcg_gen_ori_i32(cpu_sr, cpu_sr, (SR_OV | SR_CY));
+            tcg_gen_andi_i32(sr_ove, cpu_sr, SR_OVE);
+            tcg_gen_brcondi_i32(TCG_COND_NE, sr_ove, SR_OVE, lab);
+            gen_exception(dc, EXCP_RANGE);
+            gen_set_label(lab);
+            tcg_gen_mov_i32(cpu_R[rd], res);
+            tcg_temp_free_i64(ta);
+            tcg_temp_free_i64(td);
+            tcg_temp_free_i32(res);
+            tcg_temp_free_i32(sr_ove);
+        }
+        break;
+
+    case 0x28:    /* l.addic */
+        LOG_DIS("l.addic r%d, r%d, %d\n", rd, ra, I16);
+        {
+            int lab = gen_new_label();
+            TCGv_i64 ta = tcg_temp_new_i64();
+            TCGv_i64 td = tcg_temp_local_new_i64();
+            TCGv_i64 tcy = tcg_temp_local_new_i64();
+            TCGv_i32 res = tcg_temp_local_new_i32();
+            TCGv_i32 sr_cy = tcg_temp_local_new_i32();
+            TCGv_i32 sr_ove = tcg_temp_local_new_i32();
+            tcg_gen_extu_i32_i64(ta, cpu_R[ra]);
+            tcg_gen_andi_i32(sr_cy, cpu_sr, SR_CY);
+            tcg_gen_shri_i32(sr_cy, sr_cy, 10);
+            tcg_gen_extu_i32_i64(tcy, sr_cy);
+            tcg_gen_addi_i64(td, ta, sign_extend(I16, 16));
+            tcg_gen_add_i64(td, td, tcy);
+            tcg_gen_trunc_i64_i32(res, td);
+            tcg_gen_shri_i64(td, td, 32);
+            tcg_gen_andi_i64(td, td, 0x3);
+            /* Jump to lab when no overflow.  */
+            tcg_gen_brcondi_i64(TCG_COND_EQ, td, 0x0, lab);
+            tcg_gen_brcondi_i64(TCG_COND_EQ, td, 0x3, lab);
+            tcg_gen_ori_i32(cpu_sr, cpu_sr, (SR_OV | SR_CY));
+            tcg_gen_andi_i32(sr_ove, cpu_sr, SR_OVE);
+            tcg_gen_brcondi_i32(TCG_COND_NE, sr_ove, SR_OVE, lab);
+            gen_exception(dc, EXCP_RANGE);
+            gen_set_label(lab);
+            tcg_gen_mov_i32(cpu_R[rd], res);
+            tcg_temp_free_i64(ta);
+            tcg_temp_free_i64(td);
+            tcg_temp_free_i64(tcy);
+            tcg_temp_free_i32(res);
+            tcg_temp_free_i32(sr_cy);
+            tcg_temp_free_i32(sr_ove);
+        }
+        break;
+
+    case 0x29:    /* l.andi */
+        LOG_DIS("l.andi r%d, r%d, %d\n", rd, ra, I16);
+        tcg_gen_andi_tl(cpu_R[rd], cpu_R[ra], zero_extend(I16, 16));
+        break;
+
+    case 0x2a:    /* l.ori */
+        LOG_DIS("l.ori r%d, r%d, %d\n", rd, ra, I16);
+        tcg_gen_ori_tl(cpu_R[rd], cpu_R[ra], zero_extend(I16, 16));
+        break;
+
+    case 0x2b:    /* l.xori */
+        LOG_DIS("l.xori r%d, r%d, %d\n", rd, ra, I16);
+        tcg_gen_xori_tl(cpu_R[rd], cpu_R[ra], sign_extend(I16, 16));
+        break;
+
+    case 0x2c:    /* l.muli */
+        LOG_DIS("l.muli r%d, r%d, %d\n", rd, ra, I16);
+        if (ra != 0 && I16 != 0) {
+            TCGv_i32 im = tcg_const_i32(I16);
+            gen_helper_mul32(cpu_R[rd], cpu_env, cpu_R[ra], im);
+            tcg_temp_free_i32(im);
+        } else {
+            tcg_gen_movi_tl(cpu_R[rd], 0x0);
+        }
+        break;
+
+    case 0x2d:    /* l.mfspr */
+        LOG_DIS("l.mfspr r%d, r%d, %d\n", rd, ra, I16);
+        break;
+
+    case 0x30:    /* l.mtspr */
+        LOG_DIS("l.mtspr %d, r%d, r%d, %d\n", I5, ra, rb, I11);
+        break;
+
+/* not used yet, open it when we need or64.  */
+/*#ifdef TARGET_OPENRISC64
+    case 0x34:     l.sd
+        LOG_DIS("l.sd %d, r%d, r%d, %d\n", I5, ra, rb, I11);
+        {
+            check_ob64s(dc);
+            TCGv_i64 t0 = tcg_temp_new_i64();
+            tcg_gen_addi_tl(t0, cpu_R[ra], sign_extend(tmp, 16));
+            tcg_gen_qemu_st64(cpu_R[rb], t0, dc->mem_idx);
+            tcg_temp_free_i64(t0);
+        }
+        break;
+#endif*/
+
+    case 0x35:    /* l.sw */
+        LOG_DIS("l.sw %d, r%d, r%d, %d\n", I5, ra, rb, I11);
+        {
+            TCGv t0 = tcg_temp_new();
+            tcg_gen_addi_tl(t0, cpu_R[ra], sign_extend(tmp, 16));
+            tcg_gen_qemu_st32(cpu_R[rb], t0, dc->mem_idx);
+            tcg_temp_free(t0);
+        }
+        break;
+
+    case 0x36:    /* l.sb */
+        LOG_DIS("l.sb %d, r%d, r%d, %d\n", I5, ra, rb, I11);
+        {
+            TCGv t0 = tcg_temp_new();
+            tcg_gen_addi_tl(t0, cpu_R[ra], sign_extend(tmp, 16));
+            tcg_gen_qemu_st8(cpu_R[rb], t0, dc->mem_idx);
+            tcg_temp_free(t0);
+        }
+        break;
+
+    case 0x37:    /* l.sh */
+        LOG_DIS("l.sh %d, r%d, r%d, %d\n", I5, ra, rb, I11);
+        {
+            TCGv t0 = tcg_temp_new();
+            tcg_gen_addi_tl(t0, cpu_R[ra], sign_extend(tmp, 16));
+            tcg_gen_qemu_st16(cpu_R[rb], t0, dc->mem_idx);
+            tcg_temp_free(t0);
+        }
+        break;
+
+    default:
+        gen_illegal_exception(dc);
+        break;
+    }
+}
+
+static void dec_mac(DisasContext *dc, uint32_t insn)
+{
+    uint32_t op0;
+    uint32_t ra, rb;
+    op0 = extract32(insn, 0, 4);
+    ra = extract32(insn, 16, 5);
+    rb = extract32(insn, 11, 5);
+
+    switch (op0) {
+    case 0x0001:    /* l.mac */
+        LOG_DIS("l.mac r%d, r%d\n", ra, rb);
+        {
+            TCGv_i32 t0 = tcg_temp_new_i32();
+            TCGv_i64 t1 = tcg_temp_new_i64();
+            TCGv_i64 t2 = tcg_temp_new_i64();
+            tcg_gen_mul_tl(t0, cpu_R[ra], cpu_R[rb]);
+            tcg_gen_ext_i32_i64(t1, t0);
+            tcg_gen_concat_i32_i64(t2, maclo, machi);
+            tcg_gen_add_i64(t2, t2, t1);
+            tcg_gen_trunc_i64_i32(maclo, t2);
+            tcg_gen_shri_i64(t2, t2, 32);
+            tcg_gen_trunc_i64_i32(machi, t2);
+            tcg_temp_free_i32(t0);
+            tcg_temp_free_i64(t1);
+            tcg_temp_free_i64(t2);
+        }
+        break;
+
+    case 0x0002:    /* l.msb */
+        LOG_DIS("l.msb r%d, r%d\n", ra, rb);
+        {
+            TCGv_i32 t0 = tcg_temp_new_i32();
+            TCGv_i64 t1 = tcg_temp_new_i64();
+            TCGv_i64 t2 = tcg_temp_new_i64();
+            tcg_gen_mul_tl(t0, cpu_R[ra], cpu_R[rb]);
+            tcg_gen_ext_i32_i64(t1, t0);
+            tcg_gen_concat_i32_i64(t2, maclo, machi);
+            tcg_gen_sub_i64(t2, t2, t1);
+            tcg_gen_trunc_i64_i32(maclo, t2);
+            tcg_gen_shri_i64(t2, t2, 32);
+            tcg_gen_trunc_i64_i32(machi, t2);
+            tcg_temp_free_i32(t0);
+            tcg_temp_free_i64(t1);
+            tcg_temp_free_i64(t2);
+        }
+        break;
+
+    default:
+        gen_illegal_exception(dc);
+        break;
+   }
+}
+
+static void dec_logic(DisasContext *dc, uint32_t insn)
+{
+    uint32_t op0;
+    uint32_t rd, ra, L6;
+    op0 = extract32(insn, 6, 2);
+    rd = extract32(insn, 21, 5);
+    ra = extract32(insn, 16, 5);
+    L6 = extract32(insn, 0, 6);
+
+    switch (op0) {
+    case 0x00:    /* l.slli */
+        LOG_DIS("l.slli r%d, r%d, %d\n", rd, ra, L6);
+        tcg_gen_shli_tl(cpu_R[rd], cpu_R[ra], (L6 & 0x1f));
+        break;
+
+    case 0x01:    /* l.srli */
+        LOG_DIS("l.srli r%d, r%d, %d\n", rd, ra, L6);
+        tcg_gen_shri_tl(cpu_R[rd], cpu_R[ra], (L6 & 0x1f));
+        break;
+
+    case 0x02:    /* l.srai */
+        LOG_DIS("l.srai r%d, r%d, %d\n", rd, ra, L6);
+        tcg_gen_sari_tl(cpu_R[rd], cpu_R[ra], (L6 & 0x1f)); break;
+
+    case 0x03:    /* l.rori */
+        LOG_DIS("l.rori r%d, r%d, %d\n", rd, ra, L6);
+        tcg_gen_rotri_tl(cpu_R[rd], cpu_R[ra], (L6 & 0x1f));
+        break;
+
+    default:
+        gen_illegal_exception(dc);
+        break;
+    }
+}
+
+static void dec_M(DisasContext *dc, uint32_t insn)
+{
+    uint32_t op0;
+    uint32_t rd;
+    uint32_t K16;
+    op0 = extract32(insn, 16, 1);
+    rd = extract32(insn, 21, 5);
+    K16 = extract32(insn, 0, 16);
+
+    switch (op0) {
+    case 0x0:    /* l.movhi */
+        LOG_DIS("l.movhi  r%d, %d\n", rd, K16);
+        tcg_gen_movi_tl(cpu_R[rd], (K16 << 16));
+        break;
+
+    case 0x1:    /* l.macrc */
+        LOG_DIS("l.macrc  r%d\n", rd);
+        tcg_gen_mov_tl(cpu_R[rd], maclo);
+        tcg_gen_movi_tl(maclo, 0x0);
+        tcg_gen_movi_tl(machi, 0x0);
+        break;
+
+    default:
+        gen_illegal_exception(dc);
+        break;
+    }
+}
+
+static void dec_comp(DisasContext *dc, uint32_t insn)
+{
+    uint32_t op0;
+    uint32_t ra, rb;
+
+    op0 = extract32(insn, 21, 5);
+    ra = extract32(insn, 16, 5);
+    rb = extract32(insn, 11, 5);
+
+    tcg_gen_movi_i32(env_btaken, 0x0);
+    /* unsigned integers  */
+    tcg_gen_ext32u_tl(cpu_R[ra], cpu_R[ra]);
+    tcg_gen_ext32u_tl(cpu_R[rb], cpu_R[rb]);
+
+    switch (op0) {
+    case 0x0:    /* l.sfeq */
+        LOG_DIS("l.sfeq  r%d, r%d\n", ra, rb);
+        tcg_gen_setcond_tl(TCG_COND_EQ, env_btaken, cpu_R[ra], cpu_R[rb]);
+        break;
+
+    case 0x1:    /* l.sfne */
+        LOG_DIS("l.sfne  r%d, r%d\n", ra, rb);
+        tcg_gen_setcond_tl(TCG_COND_NE, env_btaken, cpu_R[ra], cpu_R[rb]);
+        break;
+
+    case 0x2:    /* l.sfgtu */
+        LOG_DIS("l.sfgtu  r%d, r%d\n", ra, rb);
+        tcg_gen_setcond_tl(TCG_COND_GTU, env_btaken, cpu_R[ra], cpu_R[rb]);
+        break;
+
+    case 0x3:    /* l.sfgeu */
+        LOG_DIS("l.sfgeu  r%d, r%d\n", ra, rb);
+        tcg_gen_setcond_tl(TCG_COND_GEU, env_btaken, cpu_R[ra], cpu_R[rb]);
+        break;
+
+    case 0x4:    /* l.sfltu */
+        LOG_DIS("l.sfltu  r%d, r%d\n", ra, rb);
+        tcg_gen_setcond_tl(TCG_COND_LTU, env_btaken, cpu_R[ra], cpu_R[rb]);
+        break;
+
+    case 0x5:    /* l.sfleu */
+        LOG_DIS("l.sfleu  r%d, r%d\n", ra, rb);
+        tcg_gen_setcond_tl(TCG_COND_LEU, env_btaken, cpu_R[ra], cpu_R[rb]);
+        break;
+
+    case 0xa:    /* l.sfgts */
+        LOG_DIS("l.sfgts  r%d, r%d\n", ra, rb);
+        tcg_gen_setcond_tl(TCG_COND_GT, env_btaken, cpu_R[ra], cpu_R[rb]);
+        break;
+
+    case 0xb:    /* l.sfges */
+        LOG_DIS("l.sfges  r%d, r%d\n", ra, rb);
+        tcg_gen_setcond_tl(TCG_COND_GE, env_btaken, cpu_R[ra], cpu_R[rb]);
+        break;
+
+    case 0xc:    /* l.sflts */
+        LOG_DIS("l.sflts  r%d, r%d\n", ra, rb);
+        tcg_gen_setcond_tl(TCG_COND_LT, env_btaken, cpu_R[ra], cpu_R[rb]);
+        break;
+
+    case 0xd:    /* l.sfles */
+        LOG_DIS("l.sfles  r%d, r%d\n", ra, rb);
+        tcg_gen_setcond_tl(TCG_COND_LE, env_btaken, cpu_R[ra], cpu_R[rb]);
+        break;
+
+    default:
+        gen_illegal_exception(dc);
+        break;
+    }
+    wb_SR_F();
+}
+
+static void dec_compi(DisasContext *dc, uint32_t insn)
+{
+    uint32_t op0;
+    uint32_t ra, I16;
+
+    op0 = extract32(insn, 21, 5);
+    ra = extract32(insn, 16, 5);
+    I16 = extract32(insn, 0, 16);
+
+    tcg_gen_movi_i32(env_btaken, 0x0);
+    I16 = sign_extend(I16, 16);
+
+    switch (op0) {
+    case 0x0:    /* l.sfeqi */
+        LOG_DIS("l.sfeqi  r%d, %d\n", ra, I16);
+        tcg_gen_setcondi_tl(TCG_COND_EQ, env_btaken, cpu_R[ra], I16);
+        break;
+
+    case 0x1:    /* l.sfnei */
+        LOG_DIS("l.sfnei  r%d, %d\n", ra, I16);
+        tcg_gen_setcondi_tl(TCG_COND_NE, env_btaken, cpu_R[ra], I16);
+        break;
+
+    case 0x2:    /* l.sfgtui */
+        LOG_DIS("l.sfgtui  r%d, %d\n", ra, I16);
+        tcg_gen_setcondi_tl(TCG_COND_GTU, env_btaken, cpu_R[ra], I16);
+        break;
+
+    case 0x3:    /* l.sfgeui */
+        LOG_DIS("l.sfgeui  r%d, %d\n", ra, I16);
+        tcg_gen_setcondi_tl(TCG_COND_GEU, env_btaken, cpu_R[ra], I16);
+        break;
+
+    case 0x4:    /* l.sfltui */
+        LOG_DIS("l.sfltui  r%d, %d\n", ra, I16);
+        tcg_gen_setcondi_tl(TCG_COND_LTU, env_btaken, cpu_R[ra], I16);
+        break;
+
+    case 0x5:    /* l.sfleui */
+        LOG_DIS("l.sfleui  r%d, %d\n", ra, I16);
+        tcg_gen_setcondi_tl(TCG_COND_LEU, env_btaken, cpu_R[ra], I16);
+        break;
+
+    case 0xa:    /* l.sfgtsi */
+        LOG_DIS("l.sfgtsi  r%d, %d\n", ra, I16);
+        tcg_gen_setcondi_tl(TCG_COND_GT, env_btaken, cpu_R[ra], I16);
+        break;
+
+    case 0xb:    /* l.sfgesi */
+        LOG_DIS("l.sfgesi  r%d, %d\n", ra, I16);
+        tcg_gen_setcondi_tl(TCG_COND_GE, env_btaken, cpu_R[ra], I16);
+        break;
+
+    case 0xc:    /* l.sfltsi */
+        LOG_DIS("l.sfltsi  r%d, %d\n", ra, I16);
+        tcg_gen_setcondi_tl(TCG_COND_LT, env_btaken, cpu_R[ra], I16);
+        break;
+
+    case 0xd:    /* l.sflesi */
+        LOG_DIS("l.sflesi  r%d, %d\n", ra, I16);
+        tcg_gen_setcondi_tl(TCG_COND_LE, env_btaken, cpu_R[ra], I16);
+        break;
+
+    default:
+        gen_illegal_exception(dc);
+        break;
+    }
+    wb_SR_F();
+}
+
+static void dec_sys(DisasContext *dc, uint32_t insn)
+{
+    uint32_t op0;
+#ifdef OPENRISC_DISAS
+    uint32_t K16;
+#endif
+    op0 = extract32(insn, 16, 8);
+#ifdef OPENRISC_DISAS
+    K16 = extract32(insn, 0, 16);
+#endif
+
+    switch (op0) {
+    case 0x000:    /* l.sys */
+        LOG_DIS("l.sys %d\n", K16);
+        tcg_gen_movi_tl(cpu_pc, dc->pc);
+        gen_exception(dc, EXCP_SYSCALL);
+        dc->is_jmp = DISAS_UPDATE;
+        break;
+
+    case 0x100:    /* l.trap */
+        LOG_DIS("l.trap %d\n", K16);
+#if defined(CONFIG_USER_ONLY)
+        return;
+#else
+        if (dc->mem_idx == MMU_USER_IDX) {
+            gen_illegal_exception(dc);
+            return;
+        }
+        tcg_gen_movi_tl(cpu_pc, dc->pc);
+        gen_exception(dc, EXCP_TRAP);
+#endif
+        break;
+
+    case 0x300:    /* l.csync */
+        LOG_DIS("l.csync\n");
+#if defined(CONFIG_USER_ONLY)
+        return;
+#else
+        if (dc->mem_idx == MMU_USER_IDX) {
+            gen_illegal_exception(dc);
+            return;
+        }
+#endif
+        break;
+
+    case 0x200:    /* l.msync */
+        LOG_DIS("l.msync\n");
+#if defined(CONFIG_USER_ONLY)
+        return;
+#else
+        if (dc->mem_idx == MMU_USER_IDX) {
+            gen_illegal_exception(dc);
+            return;
+        }
+#endif
+        break;
+
+    case 0x270:    /* l.psync */
+        LOG_DIS("l.psync\n");
+#if defined(CONFIG_USER_ONLY)
+        return;
+#else
+        if (dc->mem_idx == MMU_USER_IDX) {
+            gen_illegal_exception(dc);
+            return;
+        }
+#endif
+        break;
+
+    default:
+        gen_illegal_exception(dc);
+        break;
+    }
+}
+
+static void dec_float(DisasContext *dc, uint32_t insn)
+{
+    uint32_t op0;
+    uint32_t ra, rb, rd;
+    op0 = extract32(insn, 0, 8);
+    ra = extract32(insn, 16, 5);
+    rb = extract32(insn, 11, 5);
+    rd = extract32(insn, 21, 5);
+
+    switch (op0) {
+    case 0x00:    /* lf.add.s */
+        LOG_DIS("lf.add.s r%d, r%d, r%d\n", rd, ra, rb);
+        gen_helper_float_add_s(cpu_R[rd], cpu_env, cpu_R[ra], cpu_R[rb]);
+        break;
+
+    case 0x01:    /* lf.sub.s */
+        LOG_DIS("lf.sub.s r%d, r%d, r%d\n", rd, ra, rb);
+        gen_helper_float_sub_s(cpu_R[rd], cpu_env, cpu_R[ra], cpu_R[rb]);
+        break;
+
+
+    case 0x02:    /* lf.mul.s */
+        LOG_DIS("lf.mul.s r%d, r%d, r%d\n", rd, ra, rb);
+        if (ra != 0 && rb != 0) {
+            gen_helper_float_mul_s(cpu_R[rd], cpu_env, cpu_R[ra], cpu_R[rb]);
+        } else {
+            tcg_gen_ori_tl(fpcsr, fpcsr, FPCSR_ZF);
+            tcg_gen_movi_i32(cpu_R[rd], 0x0);
+        }
+        break;
+
+    case 0x03:    /* lf.div.s */
+        LOG_DIS("lf.div.s r%d, r%d, r%d\n", rd, ra, rb);
+        gen_helper_float_div_s(cpu_R[rd], cpu_env, cpu_R[ra], cpu_R[rb]);
+        break;
+
+    case 0x04:    /* lf.itof.s */
+        LOG_DIS("lf.itof r%d, r%d\n", rd, ra);
+        gen_helper_itofs(cpu_R[rd], cpu_env, cpu_R[ra]);
+        break;
+
+    case 0x05:    /* lf.ftoi.s */
+        LOG_DIS("lf.ftoi r%d, r%d\n", rd, ra);
+        gen_helper_ftois(cpu_R[rd], cpu_env, cpu_R[ra]);
+        break;
+
+    case 0x06:    /* lf.rem.s */
+        LOG_DIS("lf.rem.s r%d, r%d, r%d\n", rd, ra, rb);
+        gen_helper_float_rem_s(cpu_R[rd], cpu_env, cpu_R[ra], cpu_R[rb]);
+        break;
+
+    case 0x07:    /* lf.madd.s */
+        LOG_DIS("lf.madd.s r%d, r%d, r%d\n", rd, ra, rb);
+        gen_helper_float_muladd_s(cpu_R[rd], cpu_env, cpu_R[ra], cpu_R[rb]);
+        break;
+
+    case 0x08:    /* lf.sfeq.s */
+        LOG_DIS("lf.sfeq.s r%d, r%d\n", ra, rb);
+        gen_helper_float_eq_s(env_btaken, cpu_env, cpu_R[ra], cpu_R[rb]);
+        break;
+
+    case 0x09:    /* lf.sfne.s */
+        LOG_DIS("lf.sfne.s r%d, r%d\n", ra, rb);
+        gen_helper_float_ne_s(env_btaken, cpu_env, cpu_R[ra], cpu_R[rb]);
+        break;
+
+    case 0x0a:    /* lf.sfgt.s */
+        LOG_DIS("lf.sfgt.s r%d, r%d\n", ra, rb);
+        gen_helper_float_gt_s(env_btaken, cpu_env, cpu_R[ra], cpu_R[rb]);
+        break;
+
+    case 0x0b:    /* lf.sfge.s */
+        LOG_DIS("lf.sfge.s r%d, r%d\n", ra, rb);
+        gen_helper_float_ge_s(env_btaken, cpu_env, cpu_R[ra], cpu_R[rb]);
+        break;
+
+    case 0x0c:    /* lf.sflt.s */
+        LOG_DIS("lf.sflt.s r%d, r%d\n", ra, rb);
+        gen_helper_float_lt_s(env_btaken, cpu_env, cpu_R[ra], cpu_R[rb]);
+        break;
+
+    case 0x0d:    /* lf.sfle.s */
+        LOG_DIS("lf.sfle.s r%d, r%d\n", ra, rb);
+        gen_helper_float_le_s(env_btaken, cpu_env, cpu_R[ra], cpu_R[rb]);
+        break;
+
+/* not used yet, open it when we need or64.  */
+/*#ifdef TARGET_OPENRISC64
+    case 0x10:     lf.add.d
+        LOG_DIS("lf.add.d r%d, r%d, r%d\n", rd, ra, rb);
+        check_of64s(dc);
+        gen_helper_float_add_d(cpu_R[rd], cpu_env, cpu_R[ra], cpu_R[rb]);
+        break;
+
+    case 0x11:     lf.sub.d
+        LOG_DIS("lf.sub.d r%d, r%d, r%d\n", rd, ra, rb);
+        check_of64s(dc);
+        gen_helper_float_sub_d(cpu_R[rd], cpu_env, cpu_R[ra], cpu_R[rb]);
+        break;
+
+    case 0x12:     lf.mul.d
+        LOG_DIS("lf.mul.d r%d, r%d, r%d\n", rd, ra, rb);
+        check_of64s(dc);
+        if (ra != 0 && rb != 0) {
+            gen_helper_float_mul_d(cpu_R[rd], cpu_env, cpu_R[ra], cpu_R[rb]);
+        } else {
+            tcg_gen_ori_tl(fpcsr, fpcsr, FPCSR_ZF);
+            tcg_gen_movi_i64(cpu_R[rd], 0x0);
+        }
+        break;
+
+    case 0x13:     lf.div.d
+        LOG_DIS("lf.div.d r%d, r%d, r%d\n", rd, ra, rb);
+        check_of64s(dc);
+        gen_helper_float_div_d(cpu_R[rd], cpu_env, cpu_R[ra], cpu_R[rb]);
+        break;
+
+    case 0x14:     lf.itof.d
+        LOG_DIS("lf.itof r%d, r%d\n", rd, ra);
+        check_of64s(dc);
+        gen_helper_itofd(cpu_R[rd], cpu_env, cpu_R[ra]);
+        break;
+
+    case 0x15:     lf.ftoi.d
+        LOG_DIS("lf.ftoi r%d, r%d\n", rd, ra);
+        check_of64s(dc);
+        gen_helper_ftoid(cpu_R[rd], cpu_env, cpu_R[ra]);
+        break;
+
+    case 0x16:     lf.rem.d
+        LOG_DIS("lf.rem.d r%d, r%d, r%d\n", rd, ra, rb);
+        check_of64s(dc);
+        gen_helper_float_rem_d(cpu_R[rd], cpu_env, cpu_R[ra], cpu_R[rb]);
+        break;
+
+    case 0x17:     lf.madd.d
+        LOG_DIS("lf.madd.d r%d, r%d, r%d\n", rd, ra, rb);
+        check_of64s(dc);
+        gen_helper_float_muladd_d(cpu_R[rd], cpu_env, cpu_R[ra], cpu_R[rb]);
+        break;
+
+    case 0x18:     lf.sfeq.d
+        LOG_DIS("lf.sfeq.d r%d, r%d\n", ra, rb);
+        check_of64s(dc);
+        gen_helper_float_eq_d(env_btaken, cpu_env, cpu_R[ra], cpu_R[rb]);
+        break;
+
+    case 0x1a:     lf.sfgt.d
+        LOG_DIS("lf.sfgt.d r%d, r%d\n", ra, rb);
+        check_of64s(dc);
+        gen_helper_float_gt_d(env_btaken, cpu_env, cpu_R[ra], cpu_R[rb]);
+        break;
+
+    case 0x1b:     lf.sfge.d
+        LOG_DIS("lf.sfge.d r%d, r%d\n", ra, rb);
+        check_of64s(dc);
+        gen_helper_float_ge_d(env_btaken, cpu_env, cpu_R[ra], cpu_R[rb]);
+        break;
+
+    case 0x19:     lf.sfne.d
+        LOG_DIS("lf.sfne.d r%d, r%d\n", ra, rb);
+        check_of64s(dc);
+        gen_helper_float_ne_d(env_btaken, cpu_env, cpu_R[ra], cpu_R[rb]);
+        break;
+
+    case 0x1c:     lf.sflt.d
+        LOG_DIS("lf.sflt.d r%d, r%d\n", ra, rb);
+        check_of64s(dc);
+        gen_helper_float_lt_d(env_btaken, cpu_env, cpu_R[ra], cpu_R[rb]);
+        break;
+
+    case 0x1d:     lf.sfle.d
+        LOG_DIS("lf.sfle.d r%d, r%d\n", ra, rb);
+        check_of64s(dc);
+        gen_helper_float_le_d(env_btaken, cpu_env, cpu_R[ra], cpu_R[rb]);
+        break;
+#endif*/
+
+    default:
+        gen_illegal_exception(dc);
+        break;
+    }
+    wb_SR_F();
+}
+
+static void disas_openrisc_insn(DisasContext *dc, OpenRISCCPU *cpu)
+{
+    uint32_t op0;
+    uint32_t insn;
+    insn = cpu_ldl_code(&cpu->env, dc->pc);
+    op0 = extract32(insn, 26, 6);
+
+    switch (op0) {
+    case 0x06:
+        dec_M(dc, insn);
+        break;
+
+    case 0x08:
+        dec_sys(dc, insn);
+        break;
+
+    case 0x2e:
+        dec_logic(dc, insn);
+        break;
+
+    case 0x2f:
+        dec_compi(dc, insn);
+        break;
+
+    case 0x31:
+        dec_mac(dc, insn);
+        break;
+
+    case 0x32:
+        dec_float(dc, insn);
+        break;
+
+    case 0x38:
+        dec_calc(dc, insn);
+        break;
+
+    case 0x39:
+        dec_comp(dc, insn);
+        break;
+
+    default:
+        dec_misc(dc, insn);
+        break;
+    }
+}
+
+static void check_breakpoint(OpenRISCCPU *cpu, DisasContext *dc)
+{
+    CPUBreakpoint *bp;
+
+    if (unlikely(!QTAILQ_EMPTY(&cpu->env.breakpoints))) {
+        QTAILQ_FOREACH(bp, &cpu->env.breakpoints, entry) {
+            if (bp->pc == dc->pc) {
+                tcg_gen_movi_tl(cpu_pc, dc->pc);
+                gen_exception(dc, EXCP_DEBUG);
+                dc->is_jmp = DISAS_UPDATE;
+            }
+        }
+    }
 }
 
 static inline void gen_intermediate_code_internal(OpenRISCCPU *cpu,
                                                   TranslationBlock *tb,
                                                   int search_pc)
 {
+    struct DisasContext ctx, *dc = &ctx;
+    uint16_t *gen_opc_end;
+    uint32_t pc_start;
+    int j, k;
+    uint32_t next_page_start;
+    int num_insns;
+    int max_insns;
+
+    qemu_log_try_set_file(stderr);
+
+    pc_start = tb->pc;
+    dc->tb = tb;
+
+    gen_opc_end = gen_opc_buf + OPC_MAX_SIZE;
+    dc->is_jmp = DISAS_NEXT;
+    dc->ppc = pc_start;
+    dc->pc = pc_start;
+    dc->flags = cpu->env.cpucfgr;
+    dc->mem_idx = cpu_mmu_index(&cpu->env);
+    dc->synced_flags = dc->tb_flags = tb->flags;
+    dc->delayed_branch = !!(dc->tb_flags & D_FLAG);
+    dc->singlestep_enabled = cpu->env.singlestep_enabled;
+    if (qemu_loglevel_mask(CPU_LOG_TB_IN_ASM)) {
+        qemu_log("-----------------------------------------\n");
+        log_cpu_state(&cpu->env, 0);
+    }
+
+    next_page_start = (pc_start & TARGET_PAGE_MASK) + TARGET_PAGE_SIZE;
+    k = -1;
+    num_insns = 0;
+    max_insns = tb->cflags & CF_COUNT_MASK;
+
+    if (max_insns == 0) {
+        max_insns = CF_COUNT_MASK;
+    }
+
+    gen_icount_start();
+
+    do {
+        check_breakpoint(cpu, dc);
+        if (search_pc) {
+            j = gen_opc_ptr - gen_opc_buf;
+            if (k < j) {
+                k++;
+                while (k < j) {
+                    gen_opc_instr_start[k++] = 0;
+                }
+            }
+            gen_opc_pc[k] = dc->pc;
+            gen_opc_instr_start[k] = 1;
+            gen_opc_icount[k] = num_insns;
+        }
+
+        if (unlikely(qemu_loglevel_mask(CPU_LOG_TB_OP))) {
+            tcg_gen_debug_insn_start(dc->pc);
+        }
+
+        if (num_insns + 1 == max_insns && (tb->cflags & CF_LAST_IO)) {
+            gen_io_start();
+        }
+        dc->ppc = dc->pc - 4;
+        dc->npc = dc->pc + 4;
+        tcg_gen_movi_tl(cpu_ppc, dc->ppc);
+        tcg_gen_movi_tl(cpu_npc, dc->npc);
+        disas_openrisc_insn(dc, cpu);
+        dc->pc = dc->npc;
+        num_insns++;
+        /* delay slot */
+        if (dc->delayed_branch) {
+            dc->delayed_branch--;
+            if (!dc->delayed_branch) {
+                dc->tb_flags &= ~D_FLAG;
+                gen_sync_flags(dc);
+                tcg_gen_mov_tl(cpu_pc, jmp_pc);
+                tcg_gen_mov_tl(cpu_npc, jmp_pc);
+                tcg_gen_movi_tl(jmp_pc, 0);
+                tcg_gen_exit_tb(0);
+                dc->is_jmp = DISAS_JUMP;
+                break;
+            }
+        }
+    } while (!dc->is_jmp
+             && gen_opc_ptr < gen_opc_end
+             && !cpu->env.singlestep_enabled
+             && !singlestep
+             && (dc->pc < next_page_start)
+             && num_insns < max_insns);
+
+    if (tb->cflags & CF_LAST_IO) {
+        gen_io_end();
+    }
+    if (dc->is_jmp == DISAS_NEXT) {
+        dc->is_jmp = DISAS_UPDATE;
+        tcg_gen_movi_tl(cpu_pc, dc->pc);
+    }
+    if (unlikely(cpu->env.singlestep_enabled)) {
+        if (dc->is_jmp == DISAS_NEXT) {
+            tcg_gen_movi_tl(cpu_pc, dc->pc);
+        }
+        gen_exception(dc, EXCP_DEBUG);
+    } else {
+        switch (dc->is_jmp) {
+        case DISAS_NEXT:
+            gen_goto_tb(dc, 0, dc->pc);
+            break;
+        default:
+        case DISAS_JUMP:
+            break;
+        case DISAS_UPDATE:
+            /* indicate that the hash table must be used
+               to find the next TB */
+            tcg_gen_exit_tb(0);
+            break;
+        case DISAS_TB_JUMP:
+            /* nothing more to generate */
+            break;
+        }
+    }
+
+    gen_icount_end(tb, num_insns);
+    *gen_opc_ptr = INDEX_op_end;
+    if (search_pc) {
+        j = gen_opc_ptr - gen_opc_buf;
+        k++;
+        while (k <= j) {
+            gen_opc_instr_start[k++] = 0;
+        }
+    } else {
+        tb->size = dc->pc - pc_start;
+        tb->icount = num_insns;
+    }
+
+#ifdef DEBUG_DISAS
+    if (qemu_loglevel_mask(CPU_LOG_TB_IN_ASM)) {
+        qemu_log("\n");
+        log_target_disas(pc_start, dc->pc - pc_start, 0);
+        qemu_log("\nisize=%d osize=%td\n",
+            dc->pc - pc_start, gen_opc_ptr - gen_opc_buf);
+    }
+#endif
 }
 
 void gen_intermediate_code(CPUOpenRISCState *env, struct TranslationBlock *tb)
commit 5b5695073b1d8eda14f8253a1750193d98a42ae8
Author: Jia Liu <proljc at gmail.com>
Date:   Fri Jul 20 15:50:44 2012 +0800

    target-or32: Add float instruction helpers
    
    Add OpenRISC float instruction helpers.
    
    Signed-off-by: Jia Liu <proljc at gmail.com>
    Signed-off-by: Blue Swirl <blauwirbel at gmail.com>

diff --git a/target-openrisc/Makefile.objs b/target-openrisc/Makefile.objs
index e2a3715..926fc2f 100644
--- a/target-openrisc/Makefile.objs
+++ b/target-openrisc/Makefile.objs
@@ -1,3 +1,4 @@
 obj-$(CONFIG_SOFTMMU) += machine.o
 obj-y += cpu.o exception.o interrupt.o mmu.o translate.o
-obj-y += exception_helper.o int_helper.o interrupt_helper.o mmu_helper.o
+obj-y += exception_helper.o fpu_helper.o int_helper.o \
+         interrupt_helper.o mmu_helper.o
diff --git a/target-openrisc/fpu_helper.c b/target-openrisc/fpu_helper.c
new file mode 100644
index 0000000..b184d5e
--- /dev/null
+++ b/target-openrisc/fpu_helper.c
@@ -0,0 +1,300 @@
+/*
+ * OpenRISC float helper routines
+ *
+ * Copyright (c) 2011-2012 Jia Liu <proljc at gmail.com>
+ *                         Feng Gao <gf91597 at gmail.com>
+ *
+ * This library is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Lesser General Public
+ * License as published by the Free Software Foundation; either
+ * version 2 of the License, or (at your option) any later version.
+ *
+ * This library is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
+ * Lesser General Public License for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public
+ * License along with this library; if not, see <http://www.gnu.org/licenses/>.
+ */
+
+#include "cpu.h"
+#include "helper.h"
+#include "exception.h"
+
+static inline uint32_t ieee_ex_to_openrisc(OpenRISCCPU *cpu, int fexcp)
+{
+    int ret = 0;
+    if (fexcp) {
+        if (fexcp & float_flag_invalid) {
+            cpu->env.fpcsr |= FPCSR_IVF;
+            ret = 1;
+        }
+        if (fexcp & float_flag_overflow) {
+            cpu->env.fpcsr |= FPCSR_OVF;
+            ret = 1;
+        }
+        if (fexcp & float_flag_underflow) {
+            cpu->env.fpcsr |= FPCSR_UNF;
+            ret = 1;
+        }
+        if (fexcp & float_flag_divbyzero) {
+            cpu->env.fpcsr |= FPCSR_DZF;
+            ret = 1;
+        }
+        if (fexcp & float_flag_inexact) {
+            cpu->env.fpcsr |= FPCSR_IXF;
+            ret = 1;
+        }
+    }
+
+    return ret;
+}
+
+static inline void update_fpcsr(OpenRISCCPU *cpu)
+{
+    int tmp = ieee_ex_to_openrisc(cpu,
+                              get_float_exception_flags(&cpu->env.fp_status));
+
+    SET_FP_CAUSE(cpu->env.fpcsr, tmp);
+    if ((GET_FP_ENABLE(cpu->env.fpcsr) & tmp) &&
+        (cpu->env.fpcsr & FPCSR_FPEE)) {
+        helper_exception(&cpu->env, EXCP_FPE);
+    } else {
+        UPDATE_FP_FLAGS(cpu->env.fpcsr, tmp);
+    }
+}
+
+uint64_t HELPER(itofd)(CPUOpenRISCState *env, uint64_t val)
+{
+    uint64_t itofd;
+    OpenRISCCPU *cpu = OPENRISC_CPU(ENV_GET_CPU(env));
+
+    set_float_exception_flags(0, &cpu->env.fp_status);
+    itofd = int32_to_float64(val, &cpu->env.fp_status);
+    update_fpcsr(cpu);
+
+    return itofd;
+}
+
+uint32_t HELPER(itofs)(CPUOpenRISCState *env, uint32_t val)
+{
+    uint32_t itofs;
+    OpenRISCCPU *cpu = OPENRISC_CPU(ENV_GET_CPU(env));
+
+    set_float_exception_flags(0, &cpu->env.fp_status);
+    itofs = int32_to_float32(val, &cpu->env.fp_status);
+    update_fpcsr(cpu);
+
+    return itofs;
+}
+
+uint64_t HELPER(ftoid)(CPUOpenRISCState *env, uint64_t val)
+{
+    uint64_t ftoid;
+    OpenRISCCPU *cpu = OPENRISC_CPU(ENV_GET_CPU(env));
+
+    set_float_exception_flags(0, &cpu->env.fp_status);
+    ftoid = float32_to_int64(val, &cpu->env.fp_status);
+    update_fpcsr(cpu);
+
+    return ftoid;
+}
+
+uint32_t HELPER(ftois)(CPUOpenRISCState *env, uint32_t val)
+{
+    uint32_t ftois;
+    OpenRISCCPU *cpu = OPENRISC_CPU(ENV_GET_CPU(env));
+
+    set_float_exception_flags(0, &cpu->env.fp_status);
+    ftois = float32_to_int32(val, &cpu->env.fp_status);
+    update_fpcsr(cpu);
+
+    return ftois;
+}
+
+#define FLOAT_OP(name, p) void helper_float_##_##p(void)
+
+#define FLOAT_CALC(name)                                                  \
+uint64_t helper_float_ ## name ## _d(CPUOpenRISCState *env,               \
+                                     uint64_t fdt0, uint64_t fdt1)        \
+{                                                                         \
+    uint64_t result;                                                      \
+    OpenRISCCPU *cpu = OPENRISC_CPU(ENV_GET_CPU(env));                    \
+    set_float_exception_flags(0, &cpu->env.fp_status);                    \
+    result = float64_ ## name(fdt0, fdt1, &cpu->env.fp_status);           \
+    update_fpcsr(cpu);                                                    \
+    return result;                                                        \
+}                                                                         \
+                                                                          \
+uint32_t helper_float_ ## name ## _s(CPUOpenRISCState *env,               \
+                                     uint32_t fdt0, uint32_t fdt1)        \
+{                                                                         \
+    uint32_t result;                                                      \
+    OpenRISCCPU *cpu = OPENRISC_CPU(ENV_GET_CPU(env));                    \
+    set_float_exception_flags(0, &cpu->env.fp_status);                    \
+    result = float32_ ## name(fdt0, fdt1, &cpu->env.fp_status);           \
+    update_fpcsr(cpu);                                                    \
+    return result;                                                        \
+}                                                                         \
+
+FLOAT_CALC(add)
+FLOAT_CALC(sub)
+FLOAT_CALC(mul)
+FLOAT_CALC(div)
+FLOAT_CALC(rem)
+#undef FLOAT_CALC
+
+#define FLOAT_TERNOP(name1, name2)                                        \
+uint64_t helper_float_ ## name1 ## name2 ## _d(CPUOpenRISCState *env,     \
+                                               uint64_t fdt0,             \
+                                               uint64_t fdt1)             \
+{                                                                         \
+    uint64_t result, temp, hi, lo;                                        \
+    uint32_t val1, val2;                                                  \
+    OpenRISCCPU *cpu = OPENRISC_CPU(ENV_GET_CPU(env));                    \
+    hi = env->fpmaddhi;                                                   \
+    lo = env->fpmaddlo;                                                   \
+    set_float_exception_flags(0, &cpu->env.fp_status);                    \
+    result = float64_ ## name1(fdt0, fdt1, &cpu->env.fp_status);          \
+    lo &= 0xffffffff;                                                     \
+    hi &= 0xffffffff;                                                     \
+    temp = (hi << 32) | lo;                                               \
+    result = float64_ ## name2(result, temp, &cpu->env.fp_status);        \
+    val1 = result >> 32;                                                  \
+    val2 = (uint32_t) (result & 0xffffffff);                              \
+    update_fpcsr(cpu);                                                    \
+    cpu->env.fpmaddlo = val2;                                             \
+    cpu->env.fpmaddhi = val1;                                             \
+    return 0;                                                             \
+}                                                                         \
+                                                                          \
+uint32_t helper_float_ ## name1 ## name2 ## _s(CPUOpenRISCState *env,     \
+                                            uint32_t fdt0, uint32_t fdt1) \
+{                                                                         \
+    uint64_t result, temp, hi, lo;                                        \
+    uint32_t val1, val2;                                                  \
+    OpenRISCCPU *cpu = OPENRISC_CPU(ENV_GET_CPU(env));                    \
+    hi = cpu->env.fpmaddhi;                                               \
+    lo = cpu->env.fpmaddlo;                                               \
+    set_float_exception_flags(0, &cpu->env.fp_status);                    \
+    result = float64_ ## name1(fdt0, fdt1, &cpu->env.fp_status);          \
+    temp = (hi << 32) | lo;                                               \
+    result = float64_ ## name2(result, temp, &cpu->env.fp_status);        \
+    val1 = result >> 32;                                                  \
+    val2 = (uint32_t) (result & 0xffffffff);                              \
+    update_fpcsr(cpu);                                                    \
+    cpu->env.fpmaddlo = val2;                                             \
+    cpu->env.fpmaddhi = val1;                                             \
+    return 0;                                                             \
+}
+
+FLOAT_TERNOP(mul, add)
+#undef FLOAT_TERNOP
+
+
+#define FLOAT_CMP(name)                                                   \
+uint64_t helper_float_ ## name ## _d(CPUOpenRISCState *env,               \
+                                     uint64_t fdt0, uint64_t fdt1)        \
+{                                                                         \
+    int res;                                                              \
+    OpenRISCCPU *cpu = OPENRISC_CPU(ENV_GET_CPU(env));                    \
+    set_float_exception_flags(0, &cpu->env.fp_status);                    \
+    res = float64_ ## name(fdt0, fdt1, &cpu->env.fp_status);              \
+    update_fpcsr(cpu);                                                    \
+    return res;                                                           \
+}                                                                         \
+                                                                          \
+uint32_t helper_float_ ## name ## _s(CPUOpenRISCState *env,               \
+                                             uint32_t fdt0, uint32_t fdt1)\
+{                                                                         \
+    int res;                                                              \
+    OpenRISCCPU *cpu = OPENRISC_CPU(ENV_GET_CPU(env));                    \
+    set_float_exception_flags(0, &cpu->env.fp_status);                    \
+    res = float32_ ## name(fdt0, fdt1, &cpu->env.fp_status);              \
+    update_fpcsr(cpu);                                                    \
+    return res;                                                           \
+}
+
+FLOAT_CMP(le)
+FLOAT_CMP(eq)
+FLOAT_CMP(lt)
+#undef FLOAT_CMP
+
+
+#define FLOAT_CMPNE(name)                                                 \
+uint64_t helper_float_ ## name ## _d(CPUOpenRISCState *env,               \
+                                     uint64_t fdt0, uint64_t fdt1)        \
+{                                                                         \
+    int res;                                                              \
+    OpenRISCCPU *cpu = OPENRISC_CPU(ENV_GET_CPU(env));                    \
+    set_float_exception_flags(0, &cpu->env.fp_status);                    \
+    res = !float64_eq_quiet(fdt0, fdt1, &cpu->env.fp_status);             \
+    update_fpcsr(cpu);                                                    \
+    return res;                                                           \
+}                                                                         \
+                                                                          \
+uint32_t helper_float_ ## name ## _s(CPUOpenRISCState *env,               \
+                                     uint32_t fdt0, uint32_t fdt1)        \
+{                                                                         \
+    int res;                                                              \
+    OpenRISCCPU *cpu = OPENRISC_CPU(ENV_GET_CPU(env));                    \
+    set_float_exception_flags(0, &cpu->env.fp_status);                    \
+    res = !float32_eq_quiet(fdt0, fdt1, &cpu->env.fp_status);             \
+    update_fpcsr(cpu);                                                    \
+    return res;                                                           \
+}
+
+FLOAT_CMPNE(ne)
+#undef FLOAT_CMPNE
+
+#define FLOAT_CMPGT(name)                                                 \
+uint64_t helper_float_ ## name ## _d(CPUOpenRISCState *env,               \
+                                     uint64_t fdt0, uint64_t fdt1)        \
+{                                                                         \
+    int res;                                                              \
+    OpenRISCCPU *cpu = OPENRISC_CPU(ENV_GET_CPU(env));                    \
+    set_float_exception_flags(0, &cpu->env.fp_status);                    \
+    res = !float64_le(fdt0, fdt1, &cpu->env.fp_status);                   \
+    update_fpcsr(cpu);                                                    \
+    return res;                                                           \
+}                                                                         \
+                                                                          \
+uint32_t helper_float_ ## name ## _s(CPUOpenRISCState *env,               \
+                                     uint32_t fdt0, uint32_t fdt1)        \
+{                                                                         \
+    int res;                                                              \
+    OpenRISCCPU *cpu = OPENRISC_CPU(ENV_GET_CPU(env));                    \
+    set_float_exception_flags(0, &cpu->env.fp_status);                    \
+    res = !float32_le(fdt0, fdt1, &cpu->env.fp_status);                   \
+    update_fpcsr(cpu);                                                    \
+    return res;                                                           \
+}
+FLOAT_CMPGT(gt)
+#undef FLOAT_CMPGT
+
+#define FLOAT_CMPGE(name)                                                 \
+uint64_t helper_float_ ## name ## _d(CPUOpenRISCState *env,               \
+                                     uint64_t fdt0, uint64_t fdt1)        \
+{                                                                         \
+    int res;                                                              \
+    OpenRISCCPU *cpu = OPENRISC_CPU(ENV_GET_CPU(env));                    \
+    set_float_exception_flags(0, &cpu->env.fp_status);                    \
+    res = !float64_lt(fdt0, fdt1, &cpu->env.fp_status);                   \
+    update_fpcsr(cpu);                                                    \
+    return res;                                                           \
+}                                                                         \
+                                                                          \
+uint32_t helper_float_ ## name ## _s(CPUOpenRISCState *env,               \
+                                     uint32_t fdt0, uint32_t fdt1)        \
+{                                                                         \
+    int res;                                                              \
+    OpenRISCCPU *cpu = OPENRISC_CPU(ENV_GET_CPU(env));                    \
+    set_float_exception_flags(0, &cpu->env.fp_status);                    \
+    res = !float32_lt(fdt0, fdt1, &cpu->env.fp_status);                   \
+    update_fpcsr(cpu);                                                    \
+    return res;                                                           \
+}
+
+FLOAT_CMPGE(ge)
+#undef FLOAT_CMPGE
diff --git a/target-openrisc/helper.h b/target-openrisc/helper.h
index b4128ac..635c69c 100644
--- a/target-openrisc/helper.h
+++ b/target-openrisc/helper.h
@@ -22,6 +22,39 @@
 /* exception */
 DEF_HELPER_FLAGS_2(exception, 0, void, env, i32)
 
+/* float */
+DEF_HELPER_FLAGS_2(itofd, 0, i64, env, i64)
+DEF_HELPER_FLAGS_2(itofs, 0, i32, env, i32)
+DEF_HELPER_FLAGS_2(ftoid, 0, i64, env, i64)
+DEF_HELPER_FLAGS_2(ftois, 0, i32, env, i32)
+
+#define FOP_MADD(op)                                             \
+DEF_HELPER_FLAGS_3(float_ ## op ## _s, 0, i32, env, i32, i32)    \
+DEF_HELPER_FLAGS_3(float_ ## op ## _d, 0, i64, env, i64, i64)
+FOP_MADD(muladd)
+#undef FOP_MADD
+
+#define FOP_CALC(op)                                            \
+DEF_HELPER_FLAGS_3(float_ ## op ## _s, 0, i32, env, i32, i32)    \
+DEF_HELPER_FLAGS_3(float_ ## op ## _d, 0, i64, env, i64, i64)
+FOP_CALC(add)
+FOP_CALC(sub)
+FOP_CALC(mul)
+FOP_CALC(div)
+FOP_CALC(rem)
+#undef FOP_CALC
+
+#define FOP_CMP(op)                                              \
+DEF_HELPER_FLAGS_3(float_ ## op ## _s, 0, i32, env, i32, i32)    \
+DEF_HELPER_FLAGS_3(float_ ## op ## _d, 0, i64, env, i64, i64)
+FOP_CMP(eq)
+FOP_CMP(lt)
+FOP_CMP(le)
+FOP_CMP(ne)
+FOP_CMP(gt)
+FOP_CMP(ge)
+#undef FOP_CMP
+
 /* int */
 DEF_HELPER_FLAGS_1(ff1, 0, tl, tl)
 DEF_HELPER_FLAGS_1(fl1, 0, tl, tl)
commit e54a5aff1305bd538ba320c4b637e0c89029337e
Author: Jia Liu <proljc at gmail.com>
Date:   Fri Jul 20 15:50:43 2012 +0800

    target-or32: Add int instruction helpers
    
    Add OpenRISC int instruction helpers.
    
    Signed-off-by: Jia Liu <proljc at gmail.com>
    Signed-off-by: Blue Swirl <blauwirbel at gmail.com>

diff --git a/target-openrisc/Makefile.objs b/target-openrisc/Makefile.objs
index 52d0158..e2a3715 100644
--- a/target-openrisc/Makefile.objs
+++ b/target-openrisc/Makefile.objs
@@ -1,3 +1,3 @@
 obj-$(CONFIG_SOFTMMU) += machine.o
 obj-y += cpu.o exception.o interrupt.o mmu.o translate.o
-obj-y += exception_helper.o interrupt_helper.o mmu_helper.o
+obj-y += exception_helper.o int_helper.o interrupt_helper.o mmu_helper.o
diff --git a/target-openrisc/helper.h b/target-openrisc/helper.h
index 43b23ca..b4128ac 100644
--- a/target-openrisc/helper.h
+++ b/target-openrisc/helper.h
@@ -22,6 +22,11 @@
 /* exception */
 DEF_HELPER_FLAGS_2(exception, 0, void, env, i32)
 
+/* int */
+DEF_HELPER_FLAGS_1(ff1, 0, tl, tl)
+DEF_HELPER_FLAGS_1(fl1, 0, tl, tl)
+DEF_HELPER_FLAGS_3(mul32, 0, i32, env, i32, i32)
+
 /* interrupt */
 DEF_HELPER_FLAGS_1(rfe, 0, void, env)
 
diff --git a/target-openrisc/int_helper.c b/target-openrisc/int_helper.c
new file mode 100644
index 0000000..2fdfd27
--- /dev/null
+++ b/target-openrisc/int_helper.c
@@ -0,0 +1,79 @@
+/*
+ * OpenRISC int helper routines
+ *
+ * Copyright (c) 2011-2012 Jia Liu <proljc at gmail.com>
+ *                         Feng Gao <gf91597 at gmail.com>
+ *
+ * This library is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Lesser General Public
+ * License as published by the Free Software Foundation; either
+ * version 2 of the License, or (at your option) any later version.
+ *
+ * This library is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
+ * Lesser General Public License for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public
+ * License along with this library; if not, see <http://www.gnu.org/licenses/>.
+ */
+
+#include "cpu.h"
+#include "helper.h"
+#include "exception.h"
+#include "host-utils.h"
+
+target_ulong HELPER(ff1)(target_ulong x)
+{
+/*#ifdef TARGET_OPENRISC64
+    return x ? ctz64(x) + 1 : 0;
+#else*/
+    return x ? ctz32(x) + 1 : 0;
+/*#endif*/
+}
+
+target_ulong HELPER(fl1)(target_ulong x)
+{
+/* not used yet, open it when we need or64.  */
+/*#ifdef TARGET_OPENRISC64
+    return 64 - clz64(x);
+#else*/
+    return 32 - clz32(x);
+/*#endif*/
+}
+
+uint32_t HELPER(mul32)(CPUOpenRISCState *env,
+                       uint32_t ra, uint32_t rb)
+{
+    uint64_t result;
+    uint32_t high, cy;
+
+    OpenRISCCPU *cpu = OPENRISC_CPU(ENV_GET_CPU(env));
+
+    result = (uint64_t)ra * rb;
+    /* regisiers in or32 is 32bit, so 32 is NOT a magic number.
+       or64 is not handled in this function, and not implement yet,
+       TARGET_LONG_BITS for or64 is 64, it will break this function,
+       so, we didn't use TARGET_LONG_BITS here.  */
+    high = result >> 32;
+    cy = result >> (32 - 1);
+
+    if ((cy & 0x1) == 0x0) {
+        if (high == 0x0) {
+            return result;
+        }
+    }
+
+    if ((cy & 0x1) == 0x1) {
+        if (high == 0xffffffff) {
+            return result;
+        }
+    }
+
+    cpu->env.sr |= (SR_OV | SR_CY);
+    if (cpu->env.sr & SR_OVE) {
+        raise_exception(cpu, EXCP_RANGE);
+    }
+
+    return result;
+}
commit 1d7d4034690a4dd292b214a788298a2cacd09fb2
Author: Jia Liu <proljc at gmail.com>
Date:   Fri Jul 20 15:50:42 2012 +0800

    target-or32: Add exception support
    
    Add OpenRISC exception support.
    
    Signed-off-by: Jia Liu <proljc at gmail.com>
    Signed-off-by: Blue Swirl <blauwirbel at gmail.com>

diff --git a/target-openrisc/Makefile.objs b/target-openrisc/Makefile.objs
index 74c4b8d..52d0158 100644
--- a/target-openrisc/Makefile.objs
+++ b/target-openrisc/Makefile.objs
@@ -1,3 +1,3 @@
 obj-$(CONFIG_SOFTMMU) += machine.o
-obj-y += cpu.o interrupt.o mmu.o translate.o
-obj-y += interrupt_helper.o mmu_helper.o
+obj-y += cpu.o exception.o interrupt.o mmu.o translate.o
+obj-y += exception_helper.o interrupt_helper.o mmu_helper.o
diff --git a/target-openrisc/exception.c b/target-openrisc/exception.c
new file mode 100644
index 0000000..58e53c6
--- /dev/null
+++ b/target-openrisc/exception.c
@@ -0,0 +1,27 @@
+/*
+ * OpenRISC exception.
+ *
+ * Copyright (c) 2011-2012 Jia Liu <proljc at gmail.com>
+ *
+ * This library is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Lesser General Public
+ * License as published by the Free Software Foundation; either
+ * version 2 of the License, or (at your option) any later version.
+ *
+ * This library is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
+ * Lesser General Public License for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public
+ * License along with this library; if not, see <http://www.gnu.org/licenses/>.
+ */
+
+#include "cpu.h"
+#include "exception.h"
+
+void QEMU_NORETURN raise_exception(OpenRISCCPU *cpu, uint32_t excp)
+{
+    cpu->env.exception_index = excp;
+    cpu_loop_exit(&cpu->env);
+}
diff --git a/target-openrisc/exception.h b/target-openrisc/exception.h
new file mode 100644
index 0000000..4b64430
--- /dev/null
+++ b/target-openrisc/exception.h
@@ -0,0 +1,28 @@
+/*
+ * OpenRISC exception header.
+ *
+ * Copyright (c) 2011-2012 Jia Liu <proljc at gmail.com>
+ *
+ * This library is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Lesser General Public
+ * License as published by the Free Software Foundation; either
+ * version 2 of the License, or (at your option) any later version.
+ *
+ * This library is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
+ * Lesser General Public License for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public
+ * License along with this library; if not, see <http://www.gnu.org/licenses/>.
+ */
+
+#ifndef QEMU_OPENRISC_EXCP_H
+#define QEMU_OPENRISC_EXCP_H
+
+#include "cpu.h"
+#include "qemu-common.h"
+
+void QEMU_NORETURN raise_exception(OpenRISCCPU *cpu, uint32_t excp);
+
+#endif /* QEMU_OPENRISC_EXCP_H */
diff --git a/target-openrisc/exception_helper.c b/target-openrisc/exception_helper.c
new file mode 100644
index 0000000..dab4148
--- /dev/null
+++ b/target-openrisc/exception_helper.c
@@ -0,0 +1,29 @@
+/*
+ * OpenRISC exception helper routines
+ *
+ * Copyright (c) 2011-2012 Jia Liu <proljc at gmail.com>
+ *
+ * This library is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Lesser General Public
+ * License as published by the Free Software Foundation; either
+ * version 2 of the License, or (at your option) any later version.
+ *
+ * This library is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
+ * Lesser General Public License for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public
+ * License along with this library; if not, see <http://www.gnu.org/licenses/>.
+ */
+
+#include "cpu.h"
+#include "helper.h"
+#include "exception.h"
+
+void HELPER(exception)(CPUOpenRISCState *env, uint32_t excp)
+{
+    OpenRISCCPU *cpu = OPENRISC_CPU(ENV_GET_CPU(env));
+
+    raise_exception(cpu, excp);
+}
diff --git a/target-openrisc/helper.h b/target-openrisc/helper.h
index 7ced5ea..43b23ca 100644
--- a/target-openrisc/helper.h
+++ b/target-openrisc/helper.h
@@ -19,6 +19,9 @@
 
 #include "def-helper.h"
 
+/* exception */
+DEF_HELPER_FLAGS_2(exception, 0, void, env, i32)
+
 /* interrupt */
 DEF_HELPER_FLAGS_1(rfe, 0, void, env)
 
commit b6a71ef7e01bcac7aeb47d8de4082704fbc6479c
Author: Jia Liu <proljc at gmail.com>
Date:   Fri Jul 20 15:50:41 2012 +0800

    target-or32: Add interrupt support
    
    Add OpenRISC interrupt support.
    
    Signed-off-by: Jia Liu <proljc at gmail.com>
    Signed-off-by: Blue Swirl <blauwirbel at gmail.com>

diff --git a/cpu-exec.c b/cpu-exec.c
index bc47114..543460c 100644
--- a/cpu-exec.c
+++ b/cpu-exec.c
@@ -388,6 +388,23 @@ int cpu_exec(CPUArchState *env)
                         do_interrupt(env);
                         next_tb = 0;
                     }
+#elif defined(TARGET_OPENRISC)
+                    {
+                        int idx = -1;
+                        if ((interrupt_request & CPU_INTERRUPT_HARD)
+                            && (env->sr & SR_IEE)) {
+                            idx = EXCP_INT;
+                        }
+                        if ((interrupt_request & CPU_INTERRUPT_TIMER)
+                            && (env->sr & SR_TEE)) {
+                            idx = EXCP_TICK;
+                        }
+                        if (idx >= 0) {
+                            env->exception_index = idx;
+                            do_interrupt(env);
+                            next_tb = 0;
+                        }
+                    }
 #elif defined(TARGET_SPARC)
                     if (interrupt_request & CPU_INTERRUPT_HARD) {
                         if (cpu_interrupts_enabled(env) &&
diff --git a/target-openrisc/Makefile.objs b/target-openrisc/Makefile.objs
index ef933ef..74c4b8d 100644
--- a/target-openrisc/Makefile.objs
+++ b/target-openrisc/Makefile.objs
@@ -1,3 +1,3 @@
 obj-$(CONFIG_SOFTMMU) += machine.o
 obj-y += cpu.o interrupt.o mmu.o translate.o
-obj-y += mmu_helper.o
+obj-y += interrupt_helper.o mmu_helper.o
diff --git a/target-openrisc/cpu.h b/target-openrisc/cpu.h
index 9423e77..51013f3 100644
--- a/target-openrisc/cpu.h
+++ b/target-openrisc/cpu.h
@@ -83,6 +83,9 @@ enum {
 /* Internal flags, delay slot flag */
 #define D_FLAG    1
 
+/* Interrupt */
+#define NR_IRQS  32
+
 /* Registers */
 enum {
     R0 = 0, R1, R2, R3, R4, R5, R6, R7, R8, R9, R10,
@@ -309,6 +312,7 @@ typedef struct CPUOpenRISCState {
     uint32_t picmr;         /* Interrupt mask register */
     uint32_t picsr;         /* Interrupt contrl register*/
 #endif
+    void *irq[32];          /* Interrupt irq input */
 } CPUOpenRISCState;
 
 /**
@@ -392,9 +396,11 @@ static inline int cpu_mmu_index(CPUOpenRISCState *env)
     return (env->sr & SR_SM) == 0 ? MMU_USER_IDX : MMU_SUPERVISOR_IDX;
 }
 
+#define CPU_INTERRUPT_TIMER   CPU_INTERRUPT_TGT_INT_0
 static inline bool cpu_has_work(CPUOpenRISCState *env)
 {
-    return true;
+    return env->interrupt_request & (CPU_INTERRUPT_HARD |
+                                     CPU_INTERRUPT_TIMER);
 }
 
 #include "exec-all.h"
diff --git a/target-openrisc/helper.h b/target-openrisc/helper.h
new file mode 100644
index 0000000..7ced5ea
--- /dev/null
+++ b/target-openrisc/helper.h
@@ -0,0 +1,25 @@
+/*
+ * OpenRISC helper defines
+ *
+ * Copyright (c) 2011-2012 Jia Liu <proljc at gmail.com>
+ *
+ * This library is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Lesser General Public
+ * License as published by the Free Software Foundation; either
+ * version 2 of the License, or (at your option) any later version.
+ *
+ * This library is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
+ * Lesser General Public License for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public
+ * License along with this library; if not, see <http://www.gnu.org/licenses/>.
+ */
+
+#include "def-helper.h"
+
+/* interrupt */
+DEF_HELPER_FLAGS_1(rfe, 0, void, env)
+
+#include "def-helper.h"
diff --git a/target-openrisc/interrupt.c b/target-openrisc/interrupt.c
index 7a9ee0b..642da7d 100644
--- a/target-openrisc/interrupt.c
+++ b/target-openrisc/interrupt.c
@@ -27,4 +27,48 @@
 
 void do_interrupt(CPUOpenRISCState *env)
 {
+#ifndef CONFIG_USER_ONLY
+    if (env->flags & D_FLAG) { /* Delay Slot insn */
+        env->flags &= ~D_FLAG;
+        env->sr |= SR_DSX;
+        if (env->exception_index == EXCP_TICK    ||
+            env->exception_index == EXCP_INT     ||
+            env->exception_index == EXCP_SYSCALL ||
+            env->exception_index == EXCP_FPE) {
+            env->epcr = env->jmp_pc;
+        } else {
+            env->epcr = env->pc - 4;
+        }
+    } else {
+        if (env->exception_index == EXCP_TICK    ||
+            env->exception_index == EXCP_INT     ||
+            env->exception_index == EXCP_SYSCALL ||
+            env->exception_index == EXCP_FPE) {
+            env->epcr = env->npc;
+        } else {
+            env->epcr = env->pc;
+        }
+    }
+
+    /* For machine-state changed between user-mode and supervisor mode,
+       we need flush TLB when we enter&exit EXCP.  */
+    tlb_flush(env, 1);
+
+    env->esr = env->sr;
+    env->sr &= ~SR_DME;
+    env->sr &= ~SR_IME;
+    env->sr |= SR_SM;
+    env->sr &= ~SR_IEE;
+    env->sr &= ~SR_TEE;
+    env->tlb->cpu_openrisc_map_address_data = &cpu_openrisc_get_phys_nommu;
+    env->tlb->cpu_openrisc_map_address_code = &cpu_openrisc_get_phys_nommu;
+
+    if (env->exception_index > 0 && env->exception_index < EXCP_NR) {
+        env->pc = (env->exception_index << 8);
+    } else {
+        cpu_abort(env, "Unhandled exception 0x%x\n", env->exception_index);
+    }
+#endif
+
+    env->exception_index = -1;
 }
diff --git a/target-openrisc/interrupt_helper.c b/target-openrisc/interrupt_helper.c
new file mode 100644
index 0000000..79f5afe
--- /dev/null
+++ b/target-openrisc/interrupt_helper.c
@@ -0,0 +1,57 @@
+/*
+ * OpenRISC interrupt helper routines
+ *
+ * Copyright (c) 2011-2012 Jia Liu <proljc at gmail.com>
+ *                         Feng Gao <gf91597 at gmail.com>
+ *
+ * This library is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Lesser General Public
+ * License as published by the Free Software Foundation; either
+ * version 2 of the License, or (at your option) any later version.
+ *
+ * This library is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
+ * Lesser General Public License for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public
+ * License along with this library; if not, see <http://www.gnu.org/licenses/>.
+ */
+
+#include "cpu.h"
+#include "helper.h"
+
+void HELPER(rfe)(CPUOpenRISCState *env)
+{
+    OpenRISCCPU *cpu = OPENRISC_CPU(ENV_GET_CPU(env));
+#ifndef CONFIG_USER_ONLY
+    int need_flush_tlb = (cpu->env.sr & (SR_SM | SR_IME | SR_DME)) ^
+                         (cpu->env.esr & (SR_SM | SR_IME | SR_DME));
+#endif
+    cpu->env.pc = cpu->env.epcr;
+    cpu->env.npc = cpu->env.epcr;
+    cpu->env.sr = cpu->env.esr;
+
+#ifndef CONFIG_USER_ONLY
+    if (cpu->env.sr & SR_DME) {
+        cpu->env.tlb->cpu_openrisc_map_address_data =
+            &cpu_openrisc_get_phys_data;
+    } else {
+        cpu->env.tlb->cpu_openrisc_map_address_data =
+            &cpu_openrisc_get_phys_nommu;
+    }
+
+    if (cpu->env.sr & SR_IME) {
+        cpu->env.tlb->cpu_openrisc_map_address_code =
+            &cpu_openrisc_get_phys_code;
+    } else {
+        cpu->env.tlb->cpu_openrisc_map_address_code =
+            &cpu_openrisc_get_phys_nommu;
+    }
+
+    if (need_flush_tlb) {
+        tlb_flush(&cpu->env, 1);
+    }
+#endif
+    cpu->env.interrupt_request |= CPU_INTERRUPT_EXITTB;
+}
commit 726fe04572093504e7bf4ea56e0b2de559063787
Author: Jia Liu <proljc at gmail.com>
Date:   Fri Jul 20 15:50:40 2012 +0800

    target-or32: Add MMU support
    
    Add OpenRISC MMU support.
    
    Signed-off-by: Jia Liu <proljc at gmail.com>
    Signed-off-by: Blue Swirl <blauwirbel at gmail.com>

diff --git a/target-openrisc/cpu.h b/target-openrisc/cpu.h
index 58c63fa..9423e77 100644
--- a/target-openrisc/cpu.h
+++ b/target-openrisc/cpu.h
@@ -25,6 +25,9 @@
 
 #define CPUArchState struct CPUOpenRISCState
 
+/* cpu_openrisc_map_address_* in CPUOpenRISCTLBContext need this decl.  */
+struct OpenRISCCPU;
+
 #include "config.h"
 #include "qemu-common.h"
 #include "cpu-defs.h"
@@ -57,6 +60,12 @@ typedef struct OpenRISCCPUClass {
 
 #define NB_MMU_MODES    3
 
+enum {
+    MMU_NOMMU_IDX = 0,
+    MMU_SUPERVISOR_IDX = 1,
+    MMU_USER_IDX = 2,
+};
+
 #define TARGET_PAGE_BITS 13
 
 #define TARGET_PHYS_ADDR_SPACE_BITS 32
@@ -208,6 +217,56 @@ enum {
     OPENRISC_FEATURE_OV64S = (1 << 9),
 };
 
+/* TLB size */
+enum {
+    DTLB_WAYS = 1,
+    DTLB_SIZE = 64,
+    DTLB_MASK = (DTLB_SIZE-1),
+    ITLB_WAYS = 1,
+    ITLB_SIZE = 64,
+    ITLB_MASK = (ITLB_SIZE-1),
+};
+
+/* TLB prot */
+enum {
+    URE = (1 << 6),
+    UWE = (1 << 7),
+    SRE = (1 << 8),
+    SWE = (1 << 9),
+
+    SXE = (1 << 6),
+    UXE = (1 << 7),
+};
+
+/* check if tlb available */
+enum {
+    TLBRET_INVALID = -3,
+    TLBRET_NOMATCH = -2,
+    TLBRET_BADADDR = -1,
+    TLBRET_MATCH = 0
+};
+
+typedef struct OpenRISCTLBEntry {
+    uint32_t mr;
+    uint32_t tr;
+} OpenRISCTLBEntry;
+
+#ifndef CONFIG_USER_ONLY
+typedef struct CPUOpenRISCTLBContext {
+    OpenRISCTLBEntry itlb[ITLB_WAYS][ITLB_SIZE];
+    OpenRISCTLBEntry dtlb[DTLB_WAYS][DTLB_SIZE];
+
+    int (*cpu_openrisc_map_address_code)(struct OpenRISCCPU *cpu,
+                                         target_phys_addr_t *physical,
+                                         int *prot,
+                                         target_ulong address, int rw);
+    int (*cpu_openrisc_map_address_data)(struct OpenRISCCPU *cpu,
+                                         target_phys_addr_t *physical,
+                                         int *prot,
+                                         target_ulong address, int rw);
+} CPUOpenRISCTLBContext;
+#endif
+
 typedef struct CPUOpenRISCState {
     target_ulong gpr[32];     /* General registers */
     target_ulong pc;          /* Program counter */
@@ -241,6 +300,8 @@ typedef struct CPUOpenRISCState {
     CPU_COMMON
 
 #ifndef CONFIG_USER_ONLY
+    CPUOpenRISCTLBContext * tlb;
+
     struct QEMUTimer *timer;
     uint32_t ttmr;          /* Timer tick mode register */
     uint32_t ttcr;          /* Timer tick count register */
@@ -280,13 +341,26 @@ void cpu_openrisc_list(FILE *f, fprintf_function cpu_fprintf);
 int cpu_openrisc_exec(CPUOpenRISCState *s);
 void do_interrupt(CPUOpenRISCState *env);
 void openrisc_translate_init(void);
+int cpu_openrisc_handle_mmu_fault(CPUOpenRISCState *env,
+                                  target_ulong address,
+                                  int rw, int mmu_idx);
 
 #define cpu_list cpu_openrisc_list
 #define cpu_exec cpu_openrisc_exec
 #define cpu_gen_code cpu_openrisc_gen_code
+#define cpu_handle_mmu_fault cpu_openrisc_handle_mmu_fault
 
 #ifndef CONFIG_USER_ONLY
 void cpu_openrisc_mmu_init(OpenRISCCPU *cpu);
+int cpu_openrisc_get_phys_nommu(OpenRISCCPU *cpu,
+                                target_phys_addr_t *physical,
+                                int *prot, target_ulong address, int rw);
+int cpu_openrisc_get_phys_code(OpenRISCCPU *cpu,
+                               target_phys_addr_t *physical,
+                               int *prot, target_ulong address, int rw);
+int cpu_openrisc_get_phys_data(OpenRISCCPU *cpu,
+                               target_phys_addr_t *physical,
+                               int *prot, target_ulong address, int rw);
 #endif
 
 static inline CPUOpenRISCState *cpu_init(const char *cpu_model)
@@ -312,7 +386,10 @@ static inline void cpu_get_tb_cpu_state(CPUOpenRISCState *env,
 
 static inline int cpu_mmu_index(CPUOpenRISCState *env)
 {
-    return 0;
+    if (!(env->sr & SR_IME)) {
+        return MMU_NOMMU_IDX;
+    }
+    return (env->sr & SR_SM) == 0 ? MMU_USER_IDX : MMU_SUPERVISOR_IDX;
 }
 
 static inline bool cpu_has_work(CPUOpenRISCState *env)
diff --git a/target-openrisc/mmu.c b/target-openrisc/mmu.c
index 1a72aaa..0be1d41 100644
--- a/target-openrisc/mmu.c
+++ b/target-openrisc/mmu.c
@@ -27,13 +27,217 @@
 #endif
 
 #ifndef CONFIG_USER_ONLY
+int cpu_openrisc_get_phys_nommu(OpenRISCCPU *cpu,
+                                target_phys_addr_t *physical,
+                                int *prot, target_ulong address, int rw)
+{
+    *physical = address;
+    *prot = PAGE_READ | PAGE_WRITE;
+    return TLBRET_MATCH;
+}
+
+int cpu_openrisc_get_phys_code(OpenRISCCPU *cpu,
+                               target_phys_addr_t *physical,
+                               int *prot, target_ulong address, int rw)
+{
+    int vpn = address >> TARGET_PAGE_BITS;
+    int idx = vpn & ITLB_MASK;
+    int right = 0;
+
+    if ((cpu->env.tlb->itlb[0][idx].mr >> TARGET_PAGE_BITS) != vpn) {
+        return TLBRET_NOMATCH;
+    }
+    if (!(cpu->env.tlb->itlb[0][idx].mr & 1)) {
+        return TLBRET_INVALID;
+    }
+
+    if (cpu->env.sr & SR_SM) { /* supervisor mode */
+        if (cpu->env.tlb->itlb[0][idx].tr & SXE) {
+            right |= PAGE_EXEC;
+        }
+    } else {
+        if (cpu->env.tlb->itlb[0][idx].tr & UXE) {
+            right |= PAGE_EXEC;
+        }
+    }
+
+    if ((rw & 2) && ((right & PAGE_EXEC) == 0)) {
+        return TLBRET_BADADDR;
+    }
+
+    *physical = (cpu->env.tlb->itlb[0][idx].tr & TARGET_PAGE_MASK) |
+                (address & (TARGET_PAGE_SIZE-1));
+    *prot = right;
+    return TLBRET_MATCH;
+}
+
+int cpu_openrisc_get_phys_data(OpenRISCCPU *cpu,
+                               target_phys_addr_t *physical,
+                               int *prot, target_ulong address, int rw)
+{
+    int vpn = address >> TARGET_PAGE_BITS;
+    int idx = vpn & DTLB_MASK;
+    int right = 0;
+
+    if ((cpu->env.tlb->dtlb[0][idx].mr >> TARGET_PAGE_BITS) != vpn) {
+        return TLBRET_NOMATCH;
+    }
+    if (!(cpu->env.tlb->dtlb[0][idx].mr & 1)) {
+        return TLBRET_INVALID;
+    }
+
+    if (cpu->env.sr & SR_SM) { /* supervisor mode */
+        if (cpu->env.tlb->dtlb[0][idx].tr & SRE) {
+            right |= PAGE_READ;
+        }
+        if (cpu->env.tlb->dtlb[0][idx].tr & SWE) {
+            right |= PAGE_WRITE;
+        }
+    } else {
+        if (cpu->env.tlb->dtlb[0][idx].tr & URE) {
+            right |= PAGE_READ;
+        }
+        if (cpu->env.tlb->dtlb[0][idx].tr & UWE) {
+            right |= PAGE_WRITE;
+        }
+    }
+
+    if ((rw & 0) && ((right & PAGE_READ) == 0)) {
+        return TLBRET_BADADDR;
+    }
+    if ((rw & 1) && ((right & PAGE_WRITE) == 0)) {
+        return TLBRET_BADADDR;
+    }
+
+    *physical = (cpu->env.tlb->dtlb[0][idx].tr & TARGET_PAGE_MASK) |
+                (address & (TARGET_PAGE_SIZE-1));
+    *prot = right;
+    return TLBRET_MATCH;
+}
+
+static int cpu_openrisc_get_phys_addr(OpenRISCCPU *cpu,
+                                      target_phys_addr_t *physical,
+                                      int *prot, target_ulong address,
+                                      int rw)
+{
+    int ret = TLBRET_MATCH;
+
+    /* [0x0000--0x2000]: unmapped */
+    if (address < 0x2000 && (cpu->env.sr & SR_SM)) {
+        *physical = address;
+        *prot = PAGE_READ | PAGE_WRITE;
+        return ret;
+    }
+
+    if (rw == 2) {    /* ITLB */
+       *physical = 0;
+        ret = cpu->env.tlb->cpu_openrisc_map_address_code(cpu, physical,
+                                                          prot, address, rw);
+    } else {          /* DTLB */
+        ret = cpu->env.tlb->cpu_openrisc_map_address_data(cpu, physical,
+                                                          prot, address, rw);
+    }
+
+    return ret;
+}
+#endif
+
+static void cpu_openrisc_raise_mmu_exception(OpenRISCCPU *cpu,
+                                             target_ulong address,
+                                             int rw, int tlb_error)
+{
+    int exception = 0;
+
+    switch (tlb_error) {
+    default:
+        if (rw == 2) {
+            exception = EXCP_IPF;
+        } else {
+            exception = EXCP_DPF;
+        }
+        break;
+#ifndef CONFIG_USER_ONLY
+    case TLBRET_BADADDR:
+        if (rw == 2) {
+            exception = EXCP_IPF;
+        } else {
+            exception = EXCP_DPF;
+        }
+        break;
+    case TLBRET_INVALID:
+    case TLBRET_NOMATCH:
+        /* No TLB match for a mapped address */
+        if (rw == 2) {
+            exception = EXCP_ITLBMISS;
+        } else {
+            exception = EXCP_DTLBMISS;
+        }
+        break;
+#endif
+    }
+
+    cpu->env.exception_index = exception;
+    cpu->env.eear = address;
+}
+
+#ifndef CONFIG_USER_ONLY
+int cpu_openrisc_handle_mmu_fault(CPUOpenRISCState *env,
+                                  target_ulong address, int rw, int mmu_idx)
+{
+    int ret = 0;
+    target_phys_addr_t physical = 0;
+    int prot = 0;
+    OpenRISCCPU *cpu = OPENRISC_CPU(ENV_GET_CPU(env));
+
+    ret = cpu_openrisc_get_phys_addr(cpu, &physical, &prot,
+                                     address, rw);
+
+    if (ret == TLBRET_MATCH) {
+        tlb_set_page(env, address & TARGET_PAGE_MASK,
+                     physical & TARGET_PAGE_MASK, prot | PAGE_EXEC,
+                     mmu_idx, TARGET_PAGE_SIZE);
+        ret = 0;
+    } else if (ret < 0) {
+        cpu_openrisc_raise_mmu_exception(cpu, address, rw, ret);
+        ret = 1;
+    }
+
+    return ret;
+}
+#else
+int cpu_openrisc_handle_mmu_fault(CPUOpenRISCState *env,
+                                  target_ulong address, int rw, int mmu_idx)
+{
+    int ret = 0;
+    OpenRISCCPU *cpu = OPENRISC_CPU(ENV_GET_CPU(env));
+
+    cpu_openrisc_raise_mmu_exception(cpu, address, rw, ret);
+    ret = 1;
+
+    return ret;
+}
+#endif
+
+#ifndef CONFIG_USER_ONLY
 target_phys_addr_t cpu_get_phys_page_debug(CPUOpenRISCState *env,
                                            target_ulong addr)
 {
-    return addr;
+    target_phys_addr_t phys_addr;
+    int prot;
+    OpenRISCCPU *cpu = OPENRISC_CPU(ENV_GET_CPU(env));
+
+    if (cpu_openrisc_get_phys_addr(cpu, &phys_addr, &prot, addr, 0)) {
+        return -1;
+    }
+
+    return phys_addr;
 }
 
 void cpu_openrisc_mmu_init(OpenRISCCPU *cpu)
 {
+    cpu->env.tlb = g_malloc0(sizeof(CPUOpenRISCTLBContext));
+
+    cpu->env.tlb->cpu_openrisc_map_address_code = &cpu_openrisc_get_phys_nommu;
+    cpu->env.tlb->cpu_openrisc_map_address_data = &cpu_openrisc_get_phys_nommu;
 }
 #endif
diff --git a/target-openrisc/mmu_helper.c b/target-openrisc/mmu_helper.c
index 7c28079..59ed371 100644
--- a/target-openrisc/mmu_helper.c
+++ b/target-openrisc/mmu_helper.c
@@ -39,5 +39,25 @@
 void tlb_fill(CPUOpenRISCState *env, target_ulong addr, int is_write,
               int mmu_idx, uintptr_t retaddr)
 {
+    TranslationBlock *tb;
+    unsigned long pc;
+    int ret;
+
+    ret = cpu_openrisc_handle_mmu_fault(env, addr, is_write, mmu_idx);
+
+    if (ret) {
+        if (retaddr) {
+            /* now we have a real cpu fault.  */
+            pc = (unsigned long)retaddr;
+            tb = tb_find_pc(pc);
+            if (tb) {
+                /* the PC is inside the translated code. It means that we
+                   have a virtual CPU fault.  */
+                cpu_restore_state(tb, env, pc);
+            }
+        }
+        /* Raise Exception.  */
+        cpu_loop_exit(env);
+    }
 }
 #endif
commit e67db06e9f6d7e514ee2a9b9b769ecd42977f6fb
Author: Jia Liu <proljc at gmail.com>
Date:   Fri Jul 20 15:50:39 2012 +0800

    target-or32: Add target stubs and QOM cpu
    
    Add OpenRISC target stubs, QOM cpu and basic machine.
    
    Signed-off-by: Jia Liu <proljc at gmail.com>
    Signed-off-by: Blue Swirl <blauwirbel at gmail.com>

diff --git a/arch_init.c b/arch_init.c
index 5b0f562..ebdad3a 100644
--- a/arch_init.c
+++ b/arch_init.c
@@ -79,6 +79,8 @@ int graphic_depth = 15;
 #define QEMU_ARCH QEMU_ARCH_MICROBLAZE
 #elif defined(TARGET_MIPS)
 #define QEMU_ARCH QEMU_ARCH_MIPS
+#elif defined(TARGET_OPENRISC)
+#define QEMU_ARCH QEMU_ARCH_OPENRISC
 #elif defined(TARGET_PPC)
 #define QEMU_ARCH QEMU_ARCH_PPC
 #elif defined(TARGET_S390X)
diff --git a/arch_init.h b/arch_init.h
index c7cb94a..3dfea3b 100644
--- a/arch_init.h
+++ b/arch_init.h
@@ -16,6 +16,7 @@ enum {
     QEMU_ARCH_SH4 = 1024,
     QEMU_ARCH_SPARC = 2048,
     QEMU_ARCH_XTENSA = 4096,
+    QEMU_ARCH_OPENRISC = 8192,
 };
 
 extern const uint32_t arch_type;
diff --git a/configure b/configure
index cef0a71..ec8b049 100755
--- a/configure
+++ b/configure
@@ -924,6 +924,7 @@ mips-softmmu \
 mipsel-softmmu \
 mips64-softmmu \
 mips64el-softmmu \
+or32-softmmu \
 ppc-softmmu \
 ppcemb-softmmu \
 ppc64-softmmu \
@@ -3520,7 +3521,7 @@ target_arch2=`echo $target | cut -d '-' -f 1`
 target_bigendian="no"
 
 case "$target_arch2" in
-  armeb|lm32|m68k|microblaze|mips|mipsn32|mips64|ppc|ppcemb|ppc64|ppc64abi32|s390x|sh4eb|sparc|sparc64|sparc32plus|xtensaeb)
+  armeb|lm32|m68k|microblaze|mips|mipsn32|mips64|or32|ppc|ppcemb|ppc64|ppc64abi32|s390x|sh4eb|sparc|sparc64|sparc32plus|xtensaeb)
   target_bigendian=yes
   ;;
 esac
@@ -3636,6 +3637,11 @@ case "$target_arch2" in
     target_phys_bits=64
     target_long_alignment=8
   ;;
+  or32)
+    TARGET_ARCH=openrisc
+    TARGET_BASE_ARCH=openrisc
+    target_phys_bits=32
+  ;;
   ppc)
     gdb_xml_files="power-core.xml power-fpu.xml power-altivec.xml power-spe.xml"
     target_phys_bits=64
@@ -3714,7 +3720,7 @@ symlink "$source_path/Makefile.target" "$target_dir/Makefile"
 
 
 case "$target_arch2" in
-  alpha | sparc* | xtensa* | ppc*)
+  alpha | or32 | sparc* | xtensa* | ppc*)
     echo "CONFIG_TCG_PASS_AREG0=y" >> $config_target_mak
   ;;
 esac
@@ -3888,6 +3894,10 @@ for i in $ARCH $TARGET_BASE_ARCH ; do
     echo "CONFIG_MIPS_DIS=y"  >> $config_target_mak
     echo "CONFIG_MIPS_DIS=y"  >> $libdis_config_mak
   ;;
+  or32)
+    echo "CONFIG_OPENRISC_DIS=y"  >> $config_target_mak
+    echo "CONFIG_OPENRISC_DIS=y"  >> $libdis_config_mak
+  ;;
   ppc*)
     echo "CONFIG_PPC_DIS=y"  >> $config_target_mak
     echo "CONFIG_PPC_DIS=y"  >> $libdis_config_mak
diff --git a/cpu-exec.c b/cpu-exec.c
index fc185a4..bc47114 100644
--- a/cpu-exec.c
+++ b/cpu-exec.c
@@ -225,6 +225,7 @@ int cpu_exec(CPUArchState *env)
 #elif defined(TARGET_LM32)
 #elif defined(TARGET_MICROBLAZE)
 #elif defined(TARGET_MIPS)
+#elif defined(TARGET_OPENRISC)
 #elif defined(TARGET_SH4)
 #elif defined(TARGET_CRIS)
 #elif defined(TARGET_S390X)
@@ -640,6 +641,7 @@ int cpu_exec(CPUArchState *env)
               | env->cc_dest | (env->cc_x << 4);
 #elif defined(TARGET_MICROBLAZE)
 #elif defined(TARGET_MIPS)
+#elif defined(TARGET_OPENRISC)
 #elif defined(TARGET_SH4)
 #elif defined(TARGET_ALPHA)
 #elif defined(TARGET_CRIS)
diff --git a/default-configs/or32-softmmu.mak b/default-configs/or32-softmmu.mak
new file mode 100644
index 0000000..cce4746
--- /dev/null
+++ b/default-configs/or32-softmmu.mak
@@ -0,0 +1,4 @@
+# Default configuration for or32-softmmu
+
+CONFIG_SERIAL=y
+CONFIG_OPENCORES_ETH=y
diff --git a/elf.h b/elf.h
index 9c9acfa..a21ea53 100644
--- a/elf.h
+++ b/elf.h
@@ -106,6 +106,8 @@ typedef int64_t  Elf64_Sxword;
 #define EM_H8S          48      /* Hitachi H8S     */
 #define EM_LATTICEMICO32 138    /* LatticeMico32 */
 
+#define EM_OPENRISC     92        /* OpenCores OpenRISC */
+
 #define EM_UNICORE32    110     /* UniCore32 */
 
 /*
diff --git a/hw/openrisc/Makefile.objs b/hw/openrisc/Makefile.objs
new file mode 100644
index 0000000..bfead21
--- /dev/null
+++ b/hw/openrisc/Makefile.objs
@@ -0,0 +1 @@
+obj-y := $(addprefix ../,$(obj-y))
diff --git a/poison.h b/poison.h
index d396f20..7d7b23b 100644
--- a/poison.h
+++ b/poison.h
@@ -14,6 +14,7 @@
 #pragma GCC poison TARGET_M68K
 #pragma GCC poison TARGET_MIPS
 #pragma GCC poison TARGET_MIPS64
+#pragma GCC poison TARGET_OPENRISC
 #pragma GCC poison TARGET_PPC
 #pragma GCC poison TARGET_PPCEMB
 #pragma GCC poison TARGET_PPC64
diff --git a/target-openrisc/Makefile.objs b/target-openrisc/Makefile.objs
new file mode 100644
index 0000000..ef933ef
--- /dev/null
+++ b/target-openrisc/Makefile.objs
@@ -0,0 +1,3 @@
+obj-$(CONFIG_SOFTMMU) += machine.o
+obj-y += cpu.o interrupt.o mmu.o translate.o
+obj-y += mmu_helper.o
diff --git a/target-openrisc/cpu.c b/target-openrisc/cpu.c
new file mode 100644
index 0000000..ba35b17
--- /dev/null
+++ b/target-openrisc/cpu.c
@@ -0,0 +1,220 @@
+/*
+ * QEMU OpenRISC CPU
+ *
+ * Copyright (c) 2012 Jia Liu <proljc at gmail.com>
+ *
+ * This library is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Lesser General Public
+ * License as published by the Free Software Foundation; either
+ * version 2 of the License, or (at your option) any later version.
+ *
+ * This library is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
+ * Lesser General Public License for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public
+ * License along with this library; if not, see <http://www.gnu.org/licenses/>.
+ */
+
+#include "cpu.h"
+#include "qemu-common.h"
+
+/* CPUClass::reset() */
+static void openrisc_cpu_reset(CPUState *s)
+{
+    OpenRISCCPU *cpu = OPENRISC_CPU(s);
+    OpenRISCCPUClass *occ = OPENRISC_CPU_GET_CLASS(cpu);
+
+    if (qemu_loglevel_mask(CPU_LOG_RESET)) {
+        qemu_log("CPU Reset (CPU %d)\n", cpu->env.cpu_index);
+        log_cpu_state(&cpu->env, 0);
+    }
+
+    occ->parent_reset(s);
+
+    memset(&cpu->env, 0, offsetof(CPUOpenRISCState, breakpoints));
+
+    tlb_flush(&cpu->env, 1);
+    /*tb_flush(&cpu->env);    FIXME: Do we need it?  */
+
+    cpu->env.pc = 0x100;
+    cpu->env.sr = SR_FO | SR_SM;
+    cpu->env.exception_index = -1;
+
+    cpu->env.upr = UPR_UP | UPR_DMP | UPR_IMP | UPR_PICP | UPR_TTP;
+    cpu->env.cpucfgr = CPUCFGR_OB32S | CPUCFGR_OF32S;
+    cpu->env.dmmucfgr = (DMMUCFGR_NTW & (0 << 2)) | (DMMUCFGR_NTS & (6 << 2));
+    cpu->env.immucfgr = (IMMUCFGR_NTW & (0 << 2)) | (IMMUCFGR_NTS & (6 << 2));
+
+#ifndef CONFIG_USER_ONLY
+    cpu->env.picmr = 0x00000000;
+    cpu->env.picsr = 0x00000000;
+
+    cpu->env.ttmr = 0x00000000;
+    cpu->env.ttcr = 0x00000000;
+#endif
+}
+
+static inline void set_feature(OpenRISCCPU *cpu, int feature)
+{
+    cpu->feature |= feature;
+    cpu->env.cpucfgr = cpu->feature;
+}
+
+void openrisc_cpu_realize(Object *obj, Error **errp)
+{
+    OpenRISCCPU *cpu = OPENRISC_CPU(obj);
+
+    qemu_init_vcpu(&cpu->env);
+    cpu_reset(CPU(cpu));
+}
+
+static void openrisc_cpu_initfn(Object *obj)
+{
+    OpenRISCCPU *cpu = OPENRISC_CPU(obj);
+    static int inited;
+
+    cpu_exec_init(&cpu->env);
+
+#ifndef CONFIG_USER_ONLY
+    cpu_openrisc_mmu_init(cpu);
+#endif
+
+    if (tcg_enabled() && !inited) {
+        inited = 1;
+        openrisc_translate_init();
+    }
+}
+
+/* CPU models */
+static void or1200_initfn(Object *obj)
+{
+    OpenRISCCPU *cpu = OPENRISC_CPU(obj);
+
+    set_feature(cpu, OPENRISC_FEATURE_OB32S);
+    set_feature(cpu, OPENRISC_FEATURE_OF32S);
+}
+
+static void openrisc_any_initfn(Object *obj)
+{
+    OpenRISCCPU *cpu = OPENRISC_CPU(obj);
+
+    set_feature(cpu, OPENRISC_FEATURE_OB32S);
+}
+
+typedef struct OpenRISCCPUInfo {
+    const char *name;
+    void (*initfn)(Object *obj);
+} OpenRISCCPUInfo;
+
+static const OpenRISCCPUInfo openrisc_cpus[] = {
+    { .name = "or1200",      .initfn = or1200_initfn },
+    { .name = "any",         .initfn = openrisc_any_initfn },
+};
+
+static void openrisc_cpu_class_init(ObjectClass *oc, void *data)
+{
+    OpenRISCCPUClass *occ = OPENRISC_CPU_CLASS(oc);
+    CPUClass *cc = CPU_CLASS(occ);
+
+    occ->parent_reset = cc->reset;
+    cc->reset = openrisc_cpu_reset;
+}
+
+static void cpu_register(const OpenRISCCPUInfo *info)
+{
+    TypeInfo type_info = {
+        .name = info->name,
+        .parent = TYPE_OPENRISC_CPU,
+        .instance_size = sizeof(OpenRISCCPU),
+        .instance_init = info->initfn,
+        .class_size = sizeof(OpenRISCCPUClass),
+    };
+
+    type_register_static(&type_info);
+}
+
+static const TypeInfo openrisc_cpu_type_info = {
+    .name = TYPE_OPENRISC_CPU,
+    .parent = TYPE_CPU,
+    .instance_size = sizeof(OpenRISCCPU),
+    .instance_init = openrisc_cpu_initfn,
+    .abstract = false,
+    .class_size = sizeof(OpenRISCCPUClass),
+    .class_init = openrisc_cpu_class_init,
+};
+
+static void openrisc_cpu_register_types(void)
+{
+    int i;
+
+    type_register_static(&openrisc_cpu_type_info);
+    for (i = 0; i < ARRAY_SIZE(openrisc_cpus); i++) {
+        cpu_register(&openrisc_cpus[i]);
+    }
+}
+
+OpenRISCCPU *cpu_openrisc_init(const char *cpu_model)
+{
+    OpenRISCCPU *cpu;
+
+    if (!object_class_by_name(cpu_model)) {
+        return NULL;
+    }
+    cpu = OPENRISC_CPU(object_new(cpu_model));
+    cpu->env.cpu_model_str = cpu_model;
+
+    openrisc_cpu_realize(OBJECT(cpu), NULL);
+
+    return cpu;
+}
+
+typedef struct OpenRISCCPUList {
+    fprintf_function cpu_fprintf;
+    FILE *file;
+} OpenRISCCPUList;
+
+/* Sort alphabetically by type name, except for "any". */
+static gint openrisc_cpu_list_compare(gconstpointer a, gconstpointer b)
+{
+    ObjectClass *class_a = (ObjectClass *)a;
+    ObjectClass *class_b = (ObjectClass *)b;
+    const char *name_a, *name_b;
+
+    name_a = object_class_get_name(class_a);
+    name_b = object_class_get_name(class_b);
+    if (strcmp(name_a, "any") == 0) {
+        return 1;
+    } else if (strcmp(name_b, "any") == 0) {
+        return -1;
+    } else {
+        return strcmp(name_a, name_b);
+    }
+}
+
+static void openrisc_cpu_list_entry(gpointer data, gpointer user_data)
+{
+    ObjectClass *oc = data;
+    OpenRISCCPUList *s = user_data;
+
+    (*s->cpu_fprintf)(s->file, "  %s\n",
+                      object_class_get_name(oc));
+}
+
+void cpu_openrisc_list(FILE *f, fprintf_function cpu_fprintf)
+{
+    OpenRISCCPUList s = {
+        .file = f,
+        .cpu_fprintf = cpu_fprintf,
+    };
+    GSList *list;
+
+    list = object_class_get_list(TYPE_OPENRISC_CPU, false);
+    list = g_slist_sort(list, openrisc_cpu_list_compare);
+    (*cpu_fprintf)(f, "Available CPUs:\n");
+    g_slist_foreach(list, openrisc_cpu_list_entry, &s);
+    g_slist_free(list);
+}
+
+type_init(openrisc_cpu_register_types)
diff --git a/target-openrisc/cpu.h b/target-openrisc/cpu.h
new file mode 100644
index 0000000..58c63fa
--- /dev/null
+++ b/target-openrisc/cpu.h
@@ -0,0 +1,335 @@
+/*
+ * OpenRISC virtual CPU header.
+ *
+ * Copyright (c) 2011-2012 Jia Liu <proljc at gmail.com>
+ *
+ * This library is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Lesser General Public
+ * License as published by the Free Software Foundation; either
+ * version 2 of the License, or (at your option) any later version.
+ *
+ * This library is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
+ * Lesser General Public License for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public
+ * License along with this library; if not, see <http://www.gnu.org/licenses/>.
+ */
+
+#ifndef CPU_OPENRISC_H
+#define CPU_OPENRISC_H
+
+#define TARGET_LONG_BITS 32
+#define ELF_MACHINE    EM_OPENRISC
+
+#define CPUArchState struct CPUOpenRISCState
+
+#include "config.h"
+#include "qemu-common.h"
+#include "cpu-defs.h"
+#include "softfloat.h"
+#include "qemu/cpu.h"
+#include "error.h"
+
+#define TYPE_OPENRISC_CPU "or32-cpu"
+
+#define OPENRISC_CPU_CLASS(klass) \
+    OBJECT_CLASS_CHECK(OpenRISCCPUClass, (klass), TYPE_OPENRISC_CPU)
+#define OPENRISC_CPU(obj) \
+    OBJECT_CHECK(OpenRISCCPU, (obj), TYPE_OPENRISC_CPU)
+#define OPENRISC_CPU_GET_CLASS(obj) \
+    OBJECT_GET_CLASS(OpenRISCCPUClass, (obj), TYPE_OPENRISC_CPU)
+
+/**
+ * OpenRISCCPUClass:
+ * @parent_reset: The parent class' reset handler.
+ *
+ * A OpenRISC CPU model.
+ */
+typedef struct OpenRISCCPUClass {
+    /*< private >*/
+    CPUClass parent_class;
+    /*< public >*/
+
+    void (*parent_reset)(CPUState *cpu);
+} OpenRISCCPUClass;
+
+#define NB_MMU_MODES    3
+
+#define TARGET_PAGE_BITS 13
+
+#define TARGET_PHYS_ADDR_SPACE_BITS 32
+#define TARGET_VIRT_ADDR_SPACE_BITS 32
+
+#define SET_FP_CAUSE(reg, v)    do {\
+                                    (reg) = ((reg) & ~(0x3f << 12)) | \
+                                            ((v & 0x3f) << 12);\
+                                } while (0)
+#define GET_FP_ENABLE(reg)       (((reg) >>  7) & 0x1f)
+#define UPDATE_FP_FLAGS(reg, v)   do {\
+                                      (reg) |= ((v & 0x1f) << 2);\
+                                  } while (0)
+
+/* Internal flags, delay slot flag */
+#define D_FLAG    1
+
+/* Registers */
+enum {
+    R0 = 0, R1, R2, R3, R4, R5, R6, R7, R8, R9, R10,
+    R11, R12, R13, R14, R15, R16, R17, R18, R19, R20,
+    R21, R22, R23, R24, R25, R26, R27, R28, R29, R30,
+    R31
+};
+
+/* Register aliases */
+enum {
+    R_ZERO = R0,
+    R_SP = R1,
+    R_FP = R2,
+    R_LR = R9,
+    R_RV = R11,
+    R_RVH = R12
+};
+
+/* Unit presece register */
+enum {
+    UPR_UP = (1 << 0),
+    UPR_DCP = (1 << 1),
+    UPR_ICP = (1 << 2),
+    UPR_DMP = (1 << 3),
+    UPR_IMP = (1 << 4),
+    UPR_MP = (1 << 5),
+    UPR_DUP = (1 << 6),
+    UPR_PCUR = (1 << 7),
+    UPR_PMP = (1 << 8),
+    UPR_PICP = (1 << 9),
+    UPR_TTP = (1 << 10),
+    UPR_CUP = (255 << 24),
+};
+
+/* CPU configure register */
+enum {
+    CPUCFGR_NSGF = (15 << 0),
+    CPUCFGR_CGF = (1 << 4),
+    CPUCFGR_OB32S = (1 << 5),
+    CPUCFGR_OB64S = (1 << 6),
+    CPUCFGR_OF32S = (1 << 7),
+    CPUCFGR_OF64S = (1 << 8),
+    CPUCFGR_OV64S = (1 << 9),
+};
+
+/* DMMU configure register */
+enum {
+    DMMUCFGR_NTW = (3 << 0),
+    DMMUCFGR_NTS = (7 << 2),
+    DMMUCFGR_NAE = (7 << 5),
+    DMMUCFGR_CRI = (1 << 8),
+    DMMUCFGR_PRI = (1 << 9),
+    DMMUCFGR_TEIRI = (1 << 10),
+    DMMUCFGR_HTR = (1 << 11),
+};
+
+/* IMMU configure register */
+enum {
+    IMMUCFGR_NTW = (3 << 0),
+    IMMUCFGR_NTS = (7 << 2),
+    IMMUCFGR_NAE = (7 << 5),
+    IMMUCFGR_CRI = (1 << 8),
+    IMMUCFGR_PRI = (1 << 9),
+    IMMUCFGR_TEIRI = (1 << 10),
+    IMMUCFGR_HTR = (1 << 11),
+};
+
+/* Float point control status register */
+enum {
+    FPCSR_FPEE = 1,
+    FPCSR_RM = (3 << 1),
+    FPCSR_OVF = (1 << 3),
+    FPCSR_UNF = (1 << 4),
+    FPCSR_SNF = (1 << 5),
+    FPCSR_QNF = (1 << 6),
+    FPCSR_ZF = (1 << 7),
+    FPCSR_IXF = (1 << 8),
+    FPCSR_IVF = (1 << 9),
+    FPCSR_INF = (1 << 10),
+    FPCSR_DZF = (1 << 11),
+};
+
+/* Exceptions indices */
+enum {
+    EXCP_RESET    = 0x1,
+    EXCP_BUSERR   = 0x2,
+    EXCP_DPF      = 0x3,
+    EXCP_IPF      = 0x4,
+    EXCP_TICK     = 0x5,
+    EXCP_ALIGN    = 0x6,
+    EXCP_ILLEGAL  = 0x7,
+    EXCP_INT      = 0x8,
+    EXCP_DTLBMISS = 0x9,
+    EXCP_ITLBMISS = 0xa,
+    EXCP_RANGE    = 0xb,
+    EXCP_SYSCALL  = 0xc,
+    EXCP_FPE      = 0xd,
+    EXCP_TRAP     = 0xe,
+    EXCP_NR,
+};
+
+/* Supervisor register */
+enum {
+    SR_SM = (1 << 0),
+    SR_TEE = (1 << 1),
+    SR_IEE = (1 << 2),
+    SR_DCE = (1 << 3),
+    SR_ICE = (1 << 4),
+    SR_DME = (1 << 5),
+    SR_IME = (1 << 6),
+    SR_LEE = (1 << 7),
+    SR_CE  = (1 << 8),
+    SR_F   = (1 << 9),
+    SR_CY  = (1 << 10),
+    SR_OV  = (1 << 11),
+    SR_OVE = (1 << 12),
+    SR_DSX = (1 << 13),
+    SR_EPH = (1 << 14),
+    SR_FO  = (1 << 15),
+    SR_SUMRA = (1 << 16),
+    SR_SCE = (1 << 17),
+};
+
+/* OpenRISC Hardware Capabilities */
+enum {
+    OPENRISC_FEATURE_NSGF = (15 << 0),
+    OPENRISC_FEATURE_CGF = (1 << 4),
+    OPENRISC_FEATURE_OB32S = (1 << 5),
+    OPENRISC_FEATURE_OB64S = (1 << 6),
+    OPENRISC_FEATURE_OF32S = (1 << 7),
+    OPENRISC_FEATURE_OF64S = (1 << 8),
+    OPENRISC_FEATURE_OV64S = (1 << 9),
+};
+
+typedef struct CPUOpenRISCState {
+    target_ulong gpr[32];     /* General registers */
+    target_ulong pc;          /* Program counter */
+    target_ulong npc;         /* Next PC */
+    target_ulong ppc;         /* Prev PC */
+    target_ulong jmp_pc;      /* Jump PC */
+
+    target_ulong machi;       /* Multiply register MACHI */
+    target_ulong maclo;       /* Multiply register MACLO */
+
+    target_ulong fpmaddhi;    /* Multiply and add float register FPMADDHI */
+    target_ulong fpmaddlo;    /* Multiply and add float register FPMADDLO */
+
+    target_ulong epcr;        /* Exception PC register */
+    target_ulong eear;        /* Exception EA register */
+
+    uint32_t sr;              /* Supervisor register */
+    uint32_t vr;              /* Version register */
+    uint32_t upr;             /* Unit presence register */
+    uint32_t cpucfgr;         /* CPU configure register */
+    uint32_t dmmucfgr;        /* DMMU configure register */
+    uint32_t immucfgr;        /* IMMU configure register */
+    uint32_t esr;             /* Exception supervisor register */
+    uint32_t fpcsr;           /* Float register */
+    float_status fp_status;
+
+    uint32_t flags;           /* cpu_flags, we only use it for exception
+                                 in solt so far.  */
+    uint32_t btaken;          /* the SR_F bit */
+
+    CPU_COMMON
+
+#ifndef CONFIG_USER_ONLY
+    struct QEMUTimer *timer;
+    uint32_t ttmr;          /* Timer tick mode register */
+    uint32_t ttcr;          /* Timer tick count register */
+
+    uint32_t picmr;         /* Interrupt mask register */
+    uint32_t picsr;         /* Interrupt contrl register*/
+#endif
+} CPUOpenRISCState;
+
+/**
+ * OpenRISCCPU:
+ * @env: #CPUOpenRISCState
+ *
+ * A OpenRISC CPU.
+ */
+typedef struct OpenRISCCPU {
+    /*< private >*/
+    CPUState parent_obj;
+    /*< public >*/
+
+    CPUOpenRISCState env;
+
+    uint32_t feature;       /* CPU Capabilities */
+} OpenRISCCPU;
+
+static inline OpenRISCCPU *openrisc_env_get_cpu(CPUOpenRISCState *env)
+{
+    return OPENRISC_CPU(container_of(env, OpenRISCCPU, env));
+}
+
+#define ENV_GET_CPU(e) CPU(openrisc_env_get_cpu(e))
+
+OpenRISCCPU *cpu_openrisc_init(const char *cpu_model);
+void openrisc_cpu_realize(Object *obj, Error **errp);
+
+void cpu_openrisc_list(FILE *f, fprintf_function cpu_fprintf);
+int cpu_openrisc_exec(CPUOpenRISCState *s);
+void do_interrupt(CPUOpenRISCState *env);
+void openrisc_translate_init(void);
+
+#define cpu_list cpu_openrisc_list
+#define cpu_exec cpu_openrisc_exec
+#define cpu_gen_code cpu_openrisc_gen_code
+
+#ifndef CONFIG_USER_ONLY
+void cpu_openrisc_mmu_init(OpenRISCCPU *cpu);
+#endif
+
+static inline CPUOpenRISCState *cpu_init(const char *cpu_model)
+{
+    OpenRISCCPU *cpu = cpu_openrisc_init(cpu_model);
+    if (cpu) {
+        return &cpu->env;
+    }
+    return NULL;
+}
+
+#include "cpu-all.h"
+
+static inline void cpu_get_tb_cpu_state(CPUOpenRISCState *env,
+                                        target_ulong *pc,
+                                        target_ulong *cs_base, int *flags)
+{
+    *pc = env->pc;
+    *cs_base = 0;
+    /* D_FLAG -- branch instruction exception */
+    *flags = (env->flags & D_FLAG);
+}
+
+static inline int cpu_mmu_index(CPUOpenRISCState *env)
+{
+    return 0;
+}
+
+static inline bool cpu_has_work(CPUOpenRISCState *env)
+{
+    return true;
+}
+
+#include "exec-all.h"
+
+static inline target_ulong cpu_get_pc(CPUOpenRISCState *env)
+{
+    return env->pc;
+}
+
+static inline void cpu_pc_from_tb(CPUOpenRISCState *env, TranslationBlock *tb)
+{
+    env->pc = tb->pc;
+}
+
+#endif /* CPU_OPENRISC_H */
diff --git a/target-openrisc/interrupt.c b/target-openrisc/interrupt.c
new file mode 100644
index 0000000..7a9ee0b
--- /dev/null
+++ b/target-openrisc/interrupt.c
@@ -0,0 +1,30 @@
+/*
+ * OpenRISC interrupt.
+ *
+ * Copyright (c) 2011-2012 Jia Liu <proljc at gmail.com>
+ *
+ * This library is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Lesser General Public
+ * License as published by the Free Software Foundation; either
+ * version 2 of the License, or (at your option) any later version.
+ *
+ * This library is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
+ * Lesser General Public License for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public
+ * License along with this library; if not, see <http://www.gnu.org/licenses/>.
+ */
+
+#include "cpu.h"
+#include "qemu-common.h"
+#include "gdbstub.h"
+#include "host-utils.h"
+#ifndef CONFIG_USER_ONLY
+#include "hw/loader.h"
+#endif
+
+void do_interrupt(CPUOpenRISCState *env)
+{
+}
diff --git a/target-openrisc/machine.c b/target-openrisc/machine.c
new file mode 100644
index 0000000..cba9811
--- /dev/null
+++ b/target-openrisc/machine.c
@@ -0,0 +1,47 @@
+/*
+ * OpenRISC Machine
+ *
+ * Copyright (c) 2011-2012 Jia Liu <proljc at gmail.com>
+ *
+ * This library is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Lesser General Public
+ * License as published by the Free Software Foundation; either
+ * version 2 of the License, or (at your option) any later version.
+ *
+ * This library is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
+ * Lesser General Public License for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public
+ * License along with this library; if not, see <http://www.gnu.org/licenses/>.
+ */
+
+#include "hw/hw.h"
+#include "hw/boards.h"
+
+static const VMStateDescription vmstate_cpu = {
+    .name = "cpu",
+    .fields = (VMStateField[]) {
+        VMSTATE_UINT32_ARRAY(gpr, CPUOpenRISCState, 32),
+        VMSTATE_UINT32(sr, CPUOpenRISCState),
+        VMSTATE_UINT32(epcr, CPUOpenRISCState),
+        VMSTATE_UINT32(eear, CPUOpenRISCState),
+        VMSTATE_UINT32(esr, CPUOpenRISCState),
+        VMSTATE_UINT32(fpcsr, CPUOpenRISCState),
+        VMSTATE_UINT32(pc, CPUOpenRISCState),
+        VMSTATE_UINT32(npc, CPUOpenRISCState),
+        VMSTATE_UINT32(ppc, CPUOpenRISCState),
+        VMSTATE_END_OF_LIST()
+    }
+};
+
+void cpu_save(QEMUFile *f, void *opaque)
+{
+    vmstate_save_state(f, &vmstate_cpu, opaque);
+}
+
+int cpu_load(QEMUFile *f, void *opaque, int version_id)
+{
+    return vmstate_load_state(f, &vmstate_cpu, opaque, version_id);
+}
diff --git a/target-openrisc/mmu.c b/target-openrisc/mmu.c
new file mode 100644
index 0000000..1a72aaa
--- /dev/null
+++ b/target-openrisc/mmu.c
@@ -0,0 +1,39 @@
+/*
+ * OpenRISC MMU.
+ *
+ * Copyright (c) 2011-2012 Jia Liu <proljc at gmail.com>
+ *                         Zhizhou Zhang <etouzh at gmail.com>
+ *
+ * This library is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Lesser General Public
+ * License as published by the Free Software Foundation; either
+ * version 2 of the License, or (at your option) any later version.
+ *
+ * This library is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
+ * Lesser General Public License for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public
+ * License along with this library; if not, see <http://www.gnu.org/licenses/>.
+ */
+
+#include "cpu.h"
+#include "qemu-common.h"
+#include "gdbstub.h"
+#include "host-utils.h"
+#ifndef CONFIG_USER_ONLY
+#include "hw/loader.h"
+#endif
+
+#ifndef CONFIG_USER_ONLY
+target_phys_addr_t cpu_get_phys_page_debug(CPUOpenRISCState *env,
+                                           target_ulong addr)
+{
+    return addr;
+}
+
+void cpu_openrisc_mmu_init(OpenRISCCPU *cpu)
+{
+}
+#endif
diff --git a/target-openrisc/mmu_helper.c b/target-openrisc/mmu_helper.c
new file mode 100644
index 0000000..7c28079
--- /dev/null
+++ b/target-openrisc/mmu_helper.c
@@ -0,0 +1,43 @@
+/*
+ * OpenRISC MMU helper routines
+ *
+ * Copyright (c) 2011-2012 Jia Liu <proljc at gmail.com>
+ *                         Zhizhou Zhang <etouzh at gmail.com>
+ *
+ * This library is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Lesser General Public
+ * License as published by the Free Software Foundation; either
+ * version 2 of the License, or (at your option) any later version.
+ *
+ * This library is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
+ * Lesser General Public License for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public
+ * License along with this library; if not, see <http://www.gnu.org/licenses/>.
+ */
+
+#include "cpu.h"
+
+#ifndef CONFIG_USER_ONLY
+#include "softmmu_exec.h"
+#define MMUSUFFIX _mmu
+
+#define SHIFT 0
+#include "softmmu_template.h"
+
+#define SHIFT 1
+#include "softmmu_template.h"
+
+#define SHIFT 2
+#include "softmmu_template.h"
+
+#define SHIFT 3
+#include "softmmu_template.h"
+
+void tlb_fill(CPUOpenRISCState *env, target_ulong addr, int is_write,
+              int mmu_idx, uintptr_t retaddr)
+{
+}
+#endif
diff --git a/target-openrisc/translate.c b/target-openrisc/translate.c
new file mode 100644
index 0000000..a2b9b4f
--- /dev/null
+++ b/target-openrisc/translate.c
@@ -0,0 +1,75 @@
+/*
+ * OpenRISC translation
+ *
+ * Copyright (c) 2011-2012 Jia Liu <proljc at gmail.com>
+ *                         Feng Gao <gf91597 at gmail.com>
+ *
+ * This library is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Lesser General Public
+ * License as published by the Free Software Foundation; either
+ * version 2 of the License, or (at your option) any later version.
+ *
+ * This library is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
+ * Lesser General Public License for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public
+ * License along with this library; if not, see <http://www.gnu.org/licenses/>.
+ */
+
+#include "cpu.h"
+#include "exec-all.h"
+#include "disas.h"
+#include "tcg-op.h"
+#include "qemu-common.h"
+#include "qemu-log.h"
+#include "config.h"
+
+#define OPENRISC_DISAS
+
+#ifdef OPENRISC_DISAS
+#  define LOG_DIS(...) qemu_log_mask(CPU_LOG_TB_IN_ASM, ## __VA_ARGS__)
+#else
+#  define LOG_DIS(...) do { } while (0)
+#endif
+
+void openrisc_translate_init(void)
+{
+}
+
+static inline void gen_intermediate_code_internal(OpenRISCCPU *cpu,
+                                                  TranslationBlock *tb,
+                                                  int search_pc)
+{
+}
+
+void gen_intermediate_code(CPUOpenRISCState *env, struct TranslationBlock *tb)
+{
+    gen_intermediate_code_internal(openrisc_env_get_cpu(env), tb, 0);
+}
+
+void gen_intermediate_code_pc(CPUOpenRISCState *env,
+                              struct TranslationBlock *tb)
+{
+    gen_intermediate_code_internal(openrisc_env_get_cpu(env), tb, 1);
+}
+
+void cpu_dump_state(CPUOpenRISCState *env, FILE *f,
+                    fprintf_function cpu_fprintf,
+                    int flags)
+{
+    int i;
+    uint32_t *regs = env->gpr;
+    cpu_fprintf(f, "PC=%08x\n", env->pc);
+    for (i = 0; i < 32; ++i) {
+        cpu_fprintf(f, "R%02d=%08x%c", i, regs[i],
+                    (i % 4) == 3 ? '\n' : ' ');
+    }
+}
+
+void restore_state_to_opc(CPUOpenRISCState *env, TranslationBlock *tb,
+                          int pc_pos)
+{
+    env->pc = gen_opc_pc[pc_pos];
+}
commit 4c205d0cb1c8bde5a53f6acceda74dae1043a197
Author: Paolo Bonzini <pbonzini at redhat.com>
Date:   Fri Jul 27 14:38:03 2012 +0200

    virtio-scsi: enable MSI-X support
    
    While virtio-scsi does support multiqueue, the default number of
    interrupt vectors is not enough to actually enable usage of
    multiple queues in the driver; this is because with only 2
    vectors the driver will not be able to use a separate
    interrupt for each request queue.  Derive the desired number
    of vectors from the number of request queues.
    
    Signed-off-by: Paolo Bonzini <pbonzini at redhat.com>

diff --git a/hw/virtio-pci.c b/hw/virtio-pci.c
index 82859a5..1109467 100644
--- a/hw/virtio-pci.c
+++ b/hw/virtio-pci.c
@@ -1023,7 +1023,9 @@ static int virtio_scsi_init_pci(PCIDevice *pci_dev)
         return -EINVAL;
     }
 
-    vdev->nvectors = proxy->nvectors;
+    vdev->nvectors = proxy->nvectors == DEV_NVECTORS_UNSPECIFIED
+                                        ? proxy->scsi.num_queues + 3
+                                        : proxy->nvectors;
     virtio_init_pci(proxy, vdev);
 
     /* make the actual value visible */
@@ -1041,7 +1043,7 @@ static int virtio_scsi_exit_pci(PCIDevice *pci_dev)
 
 static Property virtio_scsi_properties[] = {
     DEFINE_PROP_BIT("ioeventfd", VirtIOPCIProxy, flags, VIRTIO_PCI_FLAG_USE_IOEVENTFD_BIT, true),
-    DEFINE_PROP_UINT32("vectors", VirtIOPCIProxy, nvectors, 2),
+    DEFINE_PROP_UINT32("vectors", VirtIOPCIProxy, nvectors, DEV_NVECTORS_UNSPECIFIED),
     DEFINE_VIRTIO_SCSI_PROPERTIES(VirtIOPCIProxy, host_features, scsi),
     DEFINE_PROP_END_OF_LIST(),
 };
commit 3f910904ecce48bcfd6ee269e8ac84a571fbc1e3
Author: Paolo Bonzini <pbonzini at redhat.com>
Date:   Fri Jul 27 14:36:07 2012 +0200

    virtio-scsi: add ioeventfd support
    
    Probably due to bad merge months ago, virtio-scsi-pci did not have
    ioeventfd support.  Fix this and enable it by default, as is the
    case for other virtio-pci devices.
    
    Signed-off-by: Paolo Bonzini <pbonzini at redhat.com>

diff --git a/hw/virtio-pci.c b/hw/virtio-pci.c
index 4e03f0b..82859a5 100644
--- a/hw/virtio-pci.c
+++ b/hw/virtio-pci.c
@@ -1040,6 +1040,7 @@ static int virtio_scsi_exit_pci(PCIDevice *pci_dev)
 }
 
 static Property virtio_scsi_properties[] = {
+    DEFINE_PROP_BIT("ioeventfd", VirtIOPCIProxy, flags, VIRTIO_PCI_FLAG_USE_IOEVENTFD_BIT, true),
     DEFINE_PROP_UINT32("vectors", VirtIOPCIProxy, nvectors, 2),
     DEFINE_VIRTIO_SCSI_PROPERTIES(VirtIOPCIProxy, host_features, scsi),
     DEFINE_PROP_END_OF_LIST(),
commit feda01e40f101956021077ad5c587519410d2073
Author: Paolo Bonzini <pbonzini at redhat.com>
Date:   Mon Jul 16 14:22:52 2012 +0200

    virtio-scsi: report parameter change events
    
    Signed-off-by: Paolo Bonzini <pbonzini at redhat.com>

diff --git a/hw/virtio-scsi.c b/hw/virtio-scsi.c
index bf18861..c4a5b22 100644
--- a/hw/virtio-scsi.c
+++ b/hw/virtio-scsi.c
@@ -27,6 +27,7 @@
 /* Feature Bits */
 #define VIRTIO_SCSI_F_INOUT                    0
 #define VIRTIO_SCSI_F_HOTPLUG                  1
+#define VIRTIO_SCSI_F_CHANGE                   2
 
 /* Response codes */
 #define VIRTIO_SCSI_S_OK                       0
@@ -63,6 +64,7 @@
 #define VIRTIO_SCSI_T_NO_EVENT                 0
 #define VIRTIO_SCSI_T_TRANSPORT_RESET          1
 #define VIRTIO_SCSI_T_ASYNC_NOTIFY             2
+#define VIRTIO_SCSI_T_PARAM_CHANGE             3
 
 /* Reasons for transport reset event */
 #define VIRTIO_SCSI_EVT_RESET_HARD             0
@@ -554,6 +556,7 @@ static uint32_t virtio_scsi_get_features(VirtIODevice *vdev,
                                          uint32_t requested_features)
 {
     requested_features |= (1UL << VIRTIO_SCSI_F_HOTPLUG);
+    requested_features |= (1UL << VIRTIO_SCSI_F_CHANGE);
     return requested_features;
 }
 
@@ -641,6 +644,18 @@ static void virtio_scsi_handle_event(VirtIODevice *vdev, VirtQueue *vq)
     }
 }
 
+static void virtio_scsi_change(SCSIBus *bus, SCSIDevice *dev, SCSISense sense)
+{
+    VirtIOSCSI *s = container_of(bus, VirtIOSCSI, bus);
+
+    if (((s->vdev.guest_features >> VIRTIO_SCSI_F_CHANGE) & 1) &&
+        (s->vdev.status & VIRTIO_CONFIG_S_DRIVER_OK) &&
+        dev->type != TYPE_ROM) {
+        virtio_scsi_push_event(s, dev, VIRTIO_SCSI_T_PARAM_CHANGE,
+                               sense.asc | (sense.ascq << 8));
+    }
+}
+
 static void virtio_scsi_hotplug(SCSIBus *bus, SCSIDevice *dev)
 {
     VirtIOSCSI *s = container_of(bus, VirtIOSCSI, bus);
@@ -670,6 +685,7 @@ static struct SCSIBusInfo virtio_scsi_scsi_info = {
 
     .complete = virtio_scsi_command_complete,
     .cancel = virtio_scsi_request_cancelled,
+    .change = virtio_scsi_change,
     .hotplug = virtio_scsi_hotplug,
     .hot_unplug = virtio_scsi_hot_unplug,
     .get_sg_list = virtio_scsi_get_sg_list,
commit 2baa1beb1e47ec207e0f9bcacdb5c68e4bf1d8f5
Author: Paolo Bonzini <pbonzini at redhat.com>
Date:   Mon Jul 16 14:50:27 2012 +0200

    virtio-scsi: do not report dropped events after reset
    
    Signed-off-by: Paolo Bonzini <pbonzini at redhat.com>

diff --git a/hw/virtio-scsi.c b/hw/virtio-scsi.c
index d5c5984..bf18861 100644
--- a/hw/virtio-scsi.c
+++ b/hw/virtio-scsi.c
@@ -563,6 +563,7 @@ static void virtio_scsi_reset(VirtIODevice *vdev)
 
     s->sense_size = VIRTIO_SCSI_SENSE_SIZE;
     s->cdb_size = VIRTIO_SCSI_CDB_SIZE;
+    s->events_dropped = false;
 }
 
 /* The device does not have anything to save beyond the virtio data.
commit 64f64855d0ec2c5979f6986d2f52e8861d58e208
Author: Paolo Bonzini <pbonzini at redhat.com>
Date:   Mon Jul 2 10:47:35 2012 +0200

    virtio-scsi: Report missed events
    
    When an event is reported but no buffers are present in the event vq,
    we can set a flag and report a dummy event as soon as one is added.
    
    Signed-off-by: Paolo Bonzini <pbonzini at redhat.com>

diff --git a/hw/virtio-scsi.c b/hw/virtio-scsi.c
index 4f02195..d5c5984 100644
--- a/hw/virtio-scsi.c
+++ b/hw/virtio-scsi.c
@@ -141,6 +141,7 @@ typedef struct {
     uint32_t sense_size;
     uint32_t cdb_size;
     int resetting;
+    bool events_dropped;
     VirtQueue *ctrl_vq;
     VirtQueue *event_vq;
     VirtQueue *cmd_vqs[0];
@@ -416,10 +417,6 @@ static void virtio_scsi_handle_ctrl(VirtIODevice *vdev, VirtQueue *vq)
     }
 }
 
-static void virtio_scsi_handle_event(VirtIODevice *vdev, VirtQueue *vq)
-{
-}
-
 static void virtio_scsi_command_complete(SCSIRequest *r, uint32_t status,
                                          size_t resid)
 {
@@ -594,22 +591,34 @@ static void virtio_scsi_push_event(VirtIOSCSI *s, SCSIDevice *dev,
 {
     VirtIOSCSIReq *req = virtio_scsi_pop_req(s, s->event_vq);
     VirtIOSCSIEvent *evt;
+    int in_size;
 
-    if (req) {
-        int in_size;
-        if (req->elem.out_num || req->elem.in_num != 1) {
-            virtio_scsi_bad_req();
-        }
+    if (!req) {
+        s->events_dropped = true;
+        return;
+    }
 
-        in_size = req->elem.in_sg[0].iov_len;
-        if (in_size < sizeof(VirtIOSCSIEvent)) {
-            virtio_scsi_bad_req();
-        }
+    if (req->elem.out_num || req->elem.in_num != 1) {
+        virtio_scsi_bad_req();
+    }
 
-        evt = req->resp.event;
-        memset(evt, 0, sizeof(VirtIOSCSIEvent));
-        evt->event = event;
-        evt->reason = reason;
+    if (s->events_dropped) {
+        event |= VIRTIO_SCSI_T_EVENTS_MISSED;
+        s->events_dropped = false;
+    }
+
+    in_size = req->elem.in_sg[0].iov_len;
+    if (in_size < sizeof(VirtIOSCSIEvent)) {
+        virtio_scsi_bad_req();
+    }
+
+    evt = req->resp.event;
+    memset(evt, 0, sizeof(VirtIOSCSIEvent));
+    evt->event = event;
+    evt->reason = reason;
+    if (!dev) {
+        assert(event == VIRTIO_SCSI_T_NO_EVENT);
+    } else {
         evt->lun[0] = 1;
         evt->lun[1] = dev->id;
 
@@ -618,7 +627,16 @@ static void virtio_scsi_push_event(VirtIOSCSI *s, SCSIDevice *dev,
             evt->lun[2] = (dev->lun >> 8) | 0x40;
         }
         evt->lun[3] = dev->lun & 0xFF;
-        virtio_scsi_complete_req(req);
+    }
+    virtio_scsi_complete_req(req);
+}
+
+static void virtio_scsi_handle_event(VirtIODevice *vdev, VirtQueue *vq)
+{
+    VirtIOSCSI *s = (VirtIOSCSI *)vdev;
+
+    if (s->events_dropped) {
+        virtio_scsi_push_event(s, NULL, VIRTIO_SCSI_T_NO_EVENT, 0);
     }
 }
 
commit b6866fee58bc25b01485dcfcf8be44a915c5f573
Author: Cong Meng <mc at linux.vnet.ibm.com>
Date:   Wed Jun 20 14:47:11 2012 +0800

    virtio-scsi: Implement hotplug support for virtio-scsi
    
    Implement the hotplug() and hot_unplug() interfaces in virtio-scsi, by signal
    the virtio_scsi.ko in guest kernel via event virtual queue.
    
    The counterpart patch of virtio_scsi.ko will be sent soon in another thread.
    
    Signed-off-by: Sen Wang <senwang at linux.vnet.ibm.com>
    Signed-off-by: Cong Meng <mc at linux.vnet.ibm.com>
    [ Add memset, fix LUN field, placate checkpatch - Paolo ]
    Signed-off-by: Paolo Bonzini <pbonzini at redhat.com>

diff --git a/hw/virtio-scsi.c b/hw/virtio-scsi.c
index 0a5ac40..4f02195 100644
--- a/hw/virtio-scsi.c
+++ b/hw/virtio-scsi.c
@@ -24,6 +24,10 @@
 #define VIRTIO_SCSI_MAX_TARGET  255
 #define VIRTIO_SCSI_MAX_LUN     16383
 
+/* Feature Bits */
+#define VIRTIO_SCSI_F_INOUT                    0
+#define VIRTIO_SCSI_F_HOTPLUG                  1
+
 /* Response codes */
 #define VIRTIO_SCSI_S_OK                       0
 #define VIRTIO_SCSI_S_OVERRUN                  1
@@ -60,6 +64,11 @@
 #define VIRTIO_SCSI_T_TRANSPORT_RESET          1
 #define VIRTIO_SCSI_T_ASYNC_NOTIFY             2
 
+/* Reasons for transport reset event */
+#define VIRTIO_SCSI_EVT_RESET_HARD             0
+#define VIRTIO_SCSI_EVT_RESET_RESCAN           1
+#define VIRTIO_SCSI_EVT_RESET_REMOVED          2
+
 /* SCSI command request, followed by data-out */
 typedef struct {
     uint8_t lun[8];              /* Logical Unit Number */
@@ -206,11 +215,13 @@ static void qemu_sgl_init_external(QEMUSGList *qsgl, struct iovec *sg,
 static void virtio_scsi_parse_req(VirtIOSCSI *s, VirtQueue *vq,
                                   VirtIOSCSIReq *req)
 {
-    assert(req->elem.out_num && req->elem.in_num);
+    assert(req->elem.in_num);
     req->vq = vq;
     req->dev = s;
     req->sreq = NULL;
-    req->req.buf = req->elem.out_sg[0].iov_base;
+    if (req->elem.out_num) {
+        req->req.buf = req->elem.out_sg[0].iov_base;
+    }
     req->resp.buf = req->elem.in_sg[0].iov_base;
 
     if (req->elem.out_num > 1) {
@@ -545,6 +556,7 @@ static void virtio_scsi_set_config(VirtIODevice *vdev,
 static uint32_t virtio_scsi_get_features(VirtIODevice *vdev,
                                          uint32_t requested_features)
 {
+    requested_features |= (1UL << VIRTIO_SCSI_F_HOTPLUG);
     return requested_features;
 }
 
@@ -577,6 +589,60 @@ static int virtio_scsi_load(QEMUFile *f, void *opaque, int version_id)
     return 0;
 }
 
+static void virtio_scsi_push_event(VirtIOSCSI *s, SCSIDevice *dev,
+                                   uint32_t event, uint32_t reason)
+{
+    VirtIOSCSIReq *req = virtio_scsi_pop_req(s, s->event_vq);
+    VirtIOSCSIEvent *evt;
+
+    if (req) {
+        int in_size;
+        if (req->elem.out_num || req->elem.in_num != 1) {
+            virtio_scsi_bad_req();
+        }
+
+        in_size = req->elem.in_sg[0].iov_len;
+        if (in_size < sizeof(VirtIOSCSIEvent)) {
+            virtio_scsi_bad_req();
+        }
+
+        evt = req->resp.event;
+        memset(evt, 0, sizeof(VirtIOSCSIEvent));
+        evt->event = event;
+        evt->reason = reason;
+        evt->lun[0] = 1;
+        evt->lun[1] = dev->id;
+
+        /* Linux wants us to keep the same encoding we use for REPORT LUNS.  */
+        if (dev->lun >= 256) {
+            evt->lun[2] = (dev->lun >> 8) | 0x40;
+        }
+        evt->lun[3] = dev->lun & 0xFF;
+        virtio_scsi_complete_req(req);
+    }
+}
+
+static void virtio_scsi_hotplug(SCSIBus *bus, SCSIDevice *dev)
+{
+    VirtIOSCSI *s = container_of(bus, VirtIOSCSI, bus);
+
+    if (((s->vdev.guest_features >> VIRTIO_SCSI_F_HOTPLUG) & 1) &&
+        (s->vdev.status & VIRTIO_CONFIG_S_DRIVER_OK)) {
+        virtio_scsi_push_event(s, dev, VIRTIO_SCSI_T_TRANSPORT_RESET,
+                               VIRTIO_SCSI_EVT_RESET_RESCAN);
+    }
+}
+
+static void virtio_scsi_hot_unplug(SCSIBus *bus, SCSIDevice *dev)
+{
+    VirtIOSCSI *s = container_of(bus, VirtIOSCSI, bus);
+
+    if ((s->vdev.guest_features >> VIRTIO_SCSI_F_HOTPLUG) & 1) {
+        virtio_scsi_push_event(s, dev, VIRTIO_SCSI_T_TRANSPORT_RESET,
+                               VIRTIO_SCSI_EVT_RESET_REMOVED);
+    }
+}
+
 static struct SCSIBusInfo virtio_scsi_scsi_info = {
     .tcq = true,
     .max_channel = VIRTIO_SCSI_MAX_CHANNEL,
@@ -585,6 +651,8 @@ static struct SCSIBusInfo virtio_scsi_scsi_info = {
 
     .complete = virtio_scsi_command_complete,
     .cancel = virtio_scsi_request_cancelled,
+    .hotplug = virtio_scsi_hotplug,
+    .hot_unplug = virtio_scsi_hot_unplug,
     .get_sg_list = virtio_scsi_get_sg_list,
     .save_request = virtio_scsi_save_request,
     .load_request = virtio_scsi_load_request,
commit 53200fad0e61046909254ba07a3a1374cebd818f
Author: Paolo Bonzini <pbonzini at redhat.com>
Date:   Mon Jul 16 14:22:36 2012 +0200

    scsi: report parameter changes to HBA drivers
    
    Signed-off-by: Paolo Bonzini <pbonzini at redhat.com>

diff --git a/hw/scsi-bus.c b/hw/scsi-bus.c
index 04262de..e4ec19e 100644
--- a/hw/scsi-bus.c
+++ b/hw/scsi-bus.c
@@ -1072,6 +1072,16 @@ int scsi_req_parse(SCSICommand *cmd, SCSIDevice *dev, uint8_t *buf)
     return 0;
 }
 
+void scsi_device_report_change(SCSIDevice *dev, SCSISense sense)
+{
+    SCSIBus *bus = DO_UPCAST(SCSIBus, qbus, dev->qdev.parent_bus);
+
+    scsi_device_set_ua(dev, sense);
+    if (bus->info->change) {
+        bus->info->change(bus, dev, sense);
+    }
+}
+
 /*
  * Predefined sense codes
  */
diff --git a/hw/scsi-disk.c b/hw/scsi-disk.c
index 9ba405f..84b63ff 100644
--- a/hw/scsi-disk.c
+++ b/hw/scsi-disk.c
@@ -1869,6 +1869,7 @@ static void scsi_disk_resize_cb(void *opaque)
      */
     if (s->qdev.type == TYPE_DISK) {
         scsi_device_set_ua(&s->qdev, SENSE_CODE(CAPACITY_CHANGED));
+        scsi_device_report_change(&s->qdev, SENSE_CODE(CAPACITY_CHANGED));
     }
 }
 
diff --git a/hw/scsi.h b/hw/scsi.h
index 82a5fc8..1aeee46 100644
--- a/hw/scsi.h
+++ b/hw/scsi.h
@@ -133,6 +133,7 @@ struct SCSIBusInfo {
     void (*cancel)(SCSIRequest *req);
     void (*hotplug)(SCSIBus *bus, SCSIDevice *dev);
     void (*hot_unplug)(SCSIBus *bus, SCSIDevice *dev);
+    void (*change)(SCSIBus *bus, SCSIDevice *dev, SCSISense sense);
     QEMUSGList *(*get_sg_list)(SCSIRequest *req);
 
     void (*save_request)(QEMUFile *f, SCSIRequest *req);
@@ -242,6 +243,7 @@ void scsi_req_cancel(SCSIRequest *req);
 void scsi_req_retry(SCSIRequest *req);
 void scsi_device_purge_requests(SCSIDevice *sdev, SCSISense sense);
 void scsi_device_set_ua(SCSIDevice *sdev, SCSISense sense);
+void scsi_device_report_change(SCSIDevice *dev, SCSISense sense);
 int scsi_device_get_sense(SCSIDevice *dev, uint8_t *buf, int len, bool fixed);
 SCSIDevice *scsi_device_find(SCSIBus *bus, int channel, int target, int lun);
 
commit aaebacef0a55a7113335ae3f998031d3c538a477
Author: Paolo Bonzini <pbonzini at redhat.com>
Date:   Mon Jul 16 14:07:55 2012 +0200

    scsi-disk: report resized disk via sense codes
    
    Linux will not use these, but a very similar mechanism will be used to
    report the condition via virtio-scsi events.
    
    Signed-off-by: Paolo Bonzini <pbonzini at redhat.com>

diff --git a/hw/scsi-bus.c b/hw/scsi-bus.c
index c38c0ec..04262de 100644
--- a/hw/scsi-bus.c
+++ b/hw/scsi-bus.c
@@ -1161,6 +1161,11 @@ const struct SCSISense sense_code_LUN_FAILURE = {
     .key = ABORTED_COMMAND, .asc = 0x3e, .ascq = 0x01
 };
 
+/* Unit attention, Capacity data has changed */
+const struct SCSISense sense_code_CAPACITY_CHANGED = {
+    .key = UNIT_ATTENTION, .asc = 0x2a, .ascq = 0x09
+};
+
 /* Unit attention, Power on, reset or bus device reset occurred */
 const struct SCSISense sense_code_RESET = {
     .key = UNIT_ATTENTION, .asc = 0x29, .ascq = 0x00
diff --git a/hw/scsi-disk.c b/hw/scsi-disk.c
index 734fe13..9ba405f 100644
--- a/hw/scsi-disk.c
+++ b/hw/scsi-disk.c
@@ -1860,6 +1860,18 @@ static void scsi_destroy(SCSIDevice *dev)
     blockdev_mark_auto_del(s->qdev.conf.bs);
 }
 
+static void scsi_disk_resize_cb(void *opaque)
+{
+    SCSIDiskState *s = opaque;
+
+    /* SPC lists this sense code as available only for
+     * direct-access devices.
+     */
+    if (s->qdev.type == TYPE_DISK) {
+        scsi_device_set_ua(&s->qdev, SENSE_CODE(CAPACITY_CHANGED));
+    }
+}
+
 static void scsi_cd_change_media_cb(void *opaque, bool load)
 {
     SCSIDiskState *s = opaque;
@@ -1901,11 +1913,17 @@ static bool scsi_cd_is_medium_locked(void *opaque)
     return ((SCSIDiskState *)opaque)->tray_locked;
 }
 
-static const BlockDevOps scsi_cd_block_ops = {
+static const BlockDevOps scsi_disk_removable_block_ops = {
     .change_media_cb = scsi_cd_change_media_cb,
     .eject_request_cb = scsi_cd_eject_request_cb,
     .is_tray_open = scsi_cd_is_tray_open,
     .is_medium_locked = scsi_cd_is_medium_locked,
+
+    .resize_cb = scsi_disk_resize_cb,
+};
+
+static const BlockDevOps scsi_disk_block_ops = {
+    .resize_cb = scsi_disk_resize_cb,
 };
 
 static void scsi_disk_unit_attention_reported(SCSIDevice *dev)
@@ -1950,7 +1968,9 @@ static int scsi_initfn(SCSIDevice *dev)
     }
 
     if (s->features & (1 << SCSI_DISK_F_REMOVABLE)) {
-        bdrv_set_dev_ops(s->qdev.conf.bs, &scsi_cd_block_ops, s);
+        bdrv_set_dev_ops(s->qdev.conf.bs, &scsi_disk_removable_block_ops, s);
+    } else {
+        bdrv_set_dev_ops(s->qdev.conf.bs, &scsi_disk_block_ops, s);
     }
     bdrv_set_buffer_alignment(s->qdev.conf.bs, s->qdev.blocksize);
 
diff --git a/hw/scsi.h b/hw/scsi.h
index f920208..82a5fc8 100644
--- a/hw/scsi.h
+++ b/hw/scsi.h
@@ -200,6 +200,8 @@ extern const struct SCSISense sense_code_IO_ERROR;
 extern const struct SCSISense sense_code_I_T_NEXUS_LOSS;
 /* Command aborted, Logical Unit failure */
 extern const struct SCSISense sense_code_LUN_FAILURE;
+/* LUN not ready, Capacity data has changed */
+extern const struct SCSISense sense_code_CAPACITY_CHANGED;
 /* LUN not ready, Medium not present */
 extern const struct SCSISense sense_code_UNIT_ATTENTION_NO_MEDIUM;
 /* Unit attention, Power on, reset or bus device reset occurred */
commit e48e84ea80cb2e7fe6e48196ce187cfba6e3eb2c
Author: Paolo Bonzini <pbonzini at redhat.com>
Date:   Mon Jul 16 14:18:58 2012 +0200

    scsi: establish precedence levels for unit attention
    
    When a device is resized, we will report a unit attention condition
    for CAPACITY DATA HAS CHANGED.  However, we should ensure that this
    condition does not override a more important unit attention condition.
    
    Signed-off-by: Paolo Bonzini <pbonzini at redhat.com>

diff --git a/hw/scsi-bus.c b/hw/scsi-bus.c
index 6ee0c10..c38c0ec 100644
--- a/hw/scsi-bus.c
+++ b/hw/scsi-bus.c
@@ -1531,6 +1531,55 @@ void scsi_req_abort(SCSIRequest *req, int status)
     scsi_req_unref(req);
 }
 
+static int scsi_ua_precedence(SCSISense sense)
+{
+    if (sense.key != UNIT_ATTENTION) {
+        return INT_MAX;
+    }
+    if (sense.asc == 0x29 && sense.ascq == 0x04) {
+        /* DEVICE INTERNAL RESET goes with POWER ON OCCURRED */
+        return 1;
+    } else if (sense.asc == 0x3F && sense.ascq == 0x01) {
+        /* MICROCODE HAS BEEN CHANGED goes with SCSI BUS RESET OCCURRED */
+        return 2;
+    } else if (sense.asc == 0x29 && (sense.ascq == 0x05 || sense.ascq == 0x06)) {
+        /* These two go with "all others". */
+        ;
+    } else if (sense.asc == 0x29 && sense.ascq <= 0x07) {
+        /* POWER ON, RESET OR BUS DEVICE RESET OCCURRED = 0
+         * POWER ON OCCURRED = 1
+         * SCSI BUS RESET OCCURRED = 2
+         * BUS DEVICE RESET FUNCTION OCCURRED = 3
+         * I_T NEXUS LOSS OCCURRED = 7
+         */
+        return sense.ascq;
+    } else if (sense.asc == 0x2F && sense.ascq == 0x01) {
+        /* COMMANDS CLEARED BY POWER LOSS NOTIFICATION  */
+        return 8;
+    }
+    return (sense.asc << 8) | sense.ascq;
+}
+
+void scsi_device_set_ua(SCSIDevice *sdev, SCSISense sense)
+{
+    int prec1, prec2;
+    if (sense.key != UNIT_ATTENTION) {
+        return;
+    }
+    trace_scsi_device_set_ua(sdev->id, sdev->lun, sense.key,
+                             sense.asc, sense.ascq);
+
+    /*
+     * Override a pre-existing unit attention condition, except for a more
+     * important reset condition.
+    */
+    prec1 = scsi_ua_precedence(sdev->unit_attention);
+    prec2 = scsi_ua_precedence(sense);
+    if (prec2 < prec1) {
+        sdev->unit_attention = sense;
+    }
+}
+
 void scsi_device_purge_requests(SCSIDevice *sdev, SCSISense sense)
 {
     SCSIRequest *req;
@@ -1539,7 +1588,8 @@ void scsi_device_purge_requests(SCSIDevice *sdev, SCSISense sense)
         req = QTAILQ_FIRST(&sdev->requests);
         scsi_req_cancel(req);
     }
-    sdev->unit_attention = sense;
+
+    scsi_device_set_ua(sdev, sense);
 }
 
 static char *scsibus_get_dev_path(DeviceState *dev)
diff --git a/hw/scsi-disk.c b/hw/scsi-disk.c
index b52e304..734fe13 100644
--- a/hw/scsi-disk.c
+++ b/hw/scsi-disk.c
@@ -1876,7 +1876,7 @@ static void scsi_cd_change_media_cb(void *opaque, bool load)
      */
     s->media_changed = load;
     s->tray_open = !load;
-    s->qdev.unit_attention = SENSE_CODE(UNIT_ATTENTION_NO_MEDIUM);
+    scsi_device_set_ua(&s->qdev, SENSE_CODE(UNIT_ATTENTION_NO_MEDIUM));
     s->media_event = true;
     s->eject_request = false;
 }
@@ -1913,7 +1913,7 @@ static void scsi_disk_unit_attention_reported(SCSIDevice *dev)
     SCSIDiskState *s = DO_UPCAST(SCSIDiskState, qdev, dev);
     if (s->media_changed) {
         s->media_changed = false;
-        s->qdev.unit_attention = SENSE_CODE(MEDIUM_CHANGED);
+        scsi_device_set_ua(&s->qdev, SENSE_CODE(MEDIUM_CHANGED));
     }
 }
 
diff --git a/hw/scsi.h b/hw/scsi.h
index 088d519..f920208 100644
--- a/hw/scsi.h
+++ b/hw/scsi.h
@@ -239,6 +239,7 @@ void scsi_req_abort(SCSIRequest *req, int status);
 void scsi_req_cancel(SCSIRequest *req);
 void scsi_req_retry(SCSIRequest *req);
 void scsi_device_purge_requests(SCSIDevice *sdev, SCSISense sense);
+void scsi_device_set_ua(SCSIDevice *sdev, SCSISense sense);
 int scsi_device_get_sense(SCSIDevice *dev, uint8_t *buf, int len, bool fixed);
 SCSIDevice *scsi_device_find(SCSIBus *bus, int channel, int target, int lun);
 
diff --git a/trace-events b/trace-events
index 7aa28b1..6b12f83 100644
--- a/trace-events
+++ b/trace-events
@@ -412,6 +412,7 @@ scsi_req_parsed(int target, int lun, int tag, int cmd, int mode, int xfer) "targ
 scsi_req_parsed_lba(int target, int lun, int tag, int cmd, uint64_t lba) "target %d lun %d tag %d command %d lba %"PRIu64
 scsi_req_parse_bad(int target, int lun, int tag, int cmd) "target %d lun %d tag %d command %d"
 scsi_req_build_sense(int target, int lun, int tag, int key, int asc, int ascq) "target %d lun %d tag %d key %#02x asc %#02x ascq %#02x"
+scsi_device_set_ua(int target, int lun, int key, int asc, int ascq) "target %d lun %d key %#02x asc %#02x ascq %#02x"
 scsi_report_luns(int target, int lun, int tag) "target %d lun %d tag %d"
 scsi_inquiry(int target, int lun, int tag, int cdb1, int cdb2) "target %d lun %d tag %d page %#02x/%#02x"
 scsi_test_unit_ready(int target, int lun, int tag) "target %d lun %d tag %d"
commit 350e6e419902991b073b313aa65b240d1024d57e
Author: Cong Meng <mc at linux.vnet.ibm.com>
Date:   Wed Jun 20 14:47:10 2012 +0800

    scsi: introduce hotplug() and hot_unplug() interfaces for SCSI bus
    
    Add two interfaces hotplug() and hot_unplug() to scsi bus info.
    The scsi bus can implement these two interfaces to signal the HBA driver
    of guest kernel to add/remove the scsi device in question.
    
    Signed-off-by: Sen Wang <senwang at linux.vnet.ibm.com>
    Signed-off-by: Cong Meng <mc at linux.vnet.ibm.com>
    [ Fixed braces and indentation - Paolo ]
    Signed-off-by: Paolo Bonzini <pbonzini at redhat.com>

diff --git a/hw/scsi-bus.c b/hw/scsi-bus.c
index 543d9d2..6ee0c10 100644
--- a/hw/scsi-bus.c
+++ b/hw/scsi-bus.c
@@ -186,6 +186,10 @@ static int scsi_qdev_init(DeviceState *qdev)
                                                          dev);
     }
 
+    if (bus->info->hotplug) {
+        bus->info->hotplug(bus, dev);
+    }
+
 err:
     return rc;
 }
@@ -1650,6 +1654,17 @@ static int get_scsi_requests(QEMUFile *f, void *pv, size_t size)
     return 0;
 }
 
+static int scsi_qdev_unplug(DeviceState *qdev)
+{
+    SCSIDevice *dev = SCSI_DEVICE(qdev);
+    SCSIBus *bus = DO_UPCAST(SCSIBus, qbus, dev->qdev.parent_bus);
+
+    if (bus->info->hot_unplug) {
+        bus->info->hot_unplug(bus, dev);
+    }
+    return qdev_simple_unplug_cb(qdev);
+}
+
 static const VMStateInfo vmstate_info_scsi_requests = {
     .name = "scsi-requests",
     .get  = get_scsi_requests,
@@ -1686,7 +1701,7 @@ static void scsi_device_class_init(ObjectClass *klass, void *data)
     DeviceClass *k = DEVICE_CLASS(klass);
     k->bus_type = TYPE_SCSI_BUS;
     k->init     = scsi_qdev_init;
-    k->unplug   = qdev_simple_unplug_cb;
+    k->unplug   = scsi_qdev_unplug;
     k->exit     = scsi_qdev_exit;
     k->props    = scsi_props;
 }
diff --git a/hw/scsi.h b/hw/scsi.h
index fc9dc50..088d519 100644
--- a/hw/scsi.h
+++ b/hw/scsi.h
@@ -131,6 +131,8 @@ struct SCSIBusInfo {
     void (*transfer_data)(SCSIRequest *req, uint32_t arg);
     void (*complete)(SCSIRequest *req, uint32_t arg, size_t resid);
     void (*cancel)(SCSIRequest *req);
+    void (*hotplug)(SCSIBus *bus, SCSIDevice *dev);
+    void (*hot_unplug)(SCSIBus *bus, SCSIDevice *dev);
     QEMUSGList *(*get_sg_list)(SCSIRequest *req);
 
     void (*save_request)(QEMUFile *f, SCSIRequest *req);
commit 814589c450440da2fd7567aafaf6259bc8ea02f4
Author: Paolo Bonzini <pbonzini at redhat.com>
Date:   Fri Jul 27 08:23:07 2012 +0200

    scsi: add tracepoint for scsi_req_cancel
    
    Signed-off-by: Paolo Bonzini <pbonzini at redhat.com>

diff --git a/hw/scsi-bus.c b/hw/scsi-bus.c
index dd0cdd0..543d9d2 100644
--- a/hw/scsi-bus.c
+++ b/hw/scsi-bus.c
@@ -1496,6 +1496,7 @@ void scsi_req_complete(SCSIRequest *req, int status)
 
 void scsi_req_cancel(SCSIRequest *req)
 {
+    trace_scsi_req_cancel(req->dev->id, req->lun, req->tag);
     if (!req->enqueued) {
         return;
     }
diff --git a/trace-events b/trace-events
index 6fb5eb5..7aa28b1 100644
--- a/trace-events
+++ b/trace-events
@@ -403,6 +403,7 @@ usb_host_parse_error(int bus, int addr, const char *errmsg) "dev %d:%d, msg %s"
 
 # hw/scsi-bus.c
 scsi_req_alloc(int target, int lun, int tag) "target %d lun %d tag %d"
+scsi_req_cancel(int target, int lun, int tag) "target %d lun %d tag %d"
 scsi_req_data(int target, int lun, int tag, int len) "target %d lun %d tag %d len %d"
 scsi_req_data_canceled(int target, int lun, int tag, int len) "target %d lun %d tag %d len %d"
 scsi_req_dequeue(int target, int lun, int tag) "target %d lun %d tag %d"
commit b456a71c4a1eb5704d135fd08da9a0de8fd81231
Author: Paolo Bonzini <pbonzini at redhat.com>
Date:   Mon Jul 16 15:59:57 2012 +0200

    scsi-disk: removable hard disks support load/eject
    
    Support for the LOEJ bit of the START/STOP UNIT command right now is
    limited to CD-ROMs.  This is wrong, since removable hard disks (in the
    real world: SD card readers) also support it in pretty much the same way.
    
    Without the LOEJ bit, START/STOP UNIT does nothing for all devices.
    
    Signed-off-by: Paolo Bonzini <pbonzini at redhat.com>

diff --git a/hw/scsi-disk.c b/hw/scsi-disk.c
index fb0540a..b52e304 100644
--- a/hw/scsi-disk.c
+++ b/hw/scsi-disk.c
@@ -1248,7 +1248,7 @@ static int scsi_disk_emulate_start_stop(SCSIDiskReq *r)
     bool start = req->cmd.buf[4] & 1;
     bool loej = req->cmd.buf[4] & 2; /* load on start, eject on !start */
 
-    if (s->qdev.type == TYPE_ROM && loej) {
+    if ((s->features & (1 << SCSI_DISK_F_REMOVABLE)) && loej) {
         if (!start && !s->tray_open && s->tray_locked) {
             scsi_check_condition(r,
                                  bdrv_is_inserted(s->qdev.conf.bs)
commit 6a8a685c4d022d4edee57b0fb78c0ae1b4876478
Author: Ronnie Sahlberg <ronniesahlberg at gmail.com>
Date:   Mon Jul 16 08:53:28 2012 +0200

    scsi-disk: Fail medium writes with proper sense for readonly LUNs
    
    Add sense code for DATA_PROTECT/WRITE_PROTECTED and return this error
    for any WRITE*/WRITE_VERIFY* calls if the device is readonly=on,
    i.e. write-protected
    
    Signed-off-by: Ronnie Sahlberg <ronniesahlberg at gmail.com>
    Signed-off-by: Paolo Bonzini <pbonzini at redhat.com>

diff --git a/hw/scsi-bus.c b/hw/scsi-bus.c
index efbda6f..dd0cdd0 100644
--- a/hw/scsi-bus.c
+++ b/hw/scsi-bus.c
@@ -1182,6 +1182,11 @@ const struct SCSISense sense_code_DEVICE_INTERNAL_RESET = {
     .key = UNIT_ATTENTION, .asc = 0x29, .ascq = 0x04
 };
 
+/* Data Protection, Write Protected */
+const struct SCSISense sense_code_WRITE_PROTECTED = {
+    .key = DATA_PROTECT, .asc = 0x27, .ascq = 0x00
+};
+
 /*
  * scsi_build_sense
  *
diff --git a/hw/scsi-disk.c b/hw/scsi-disk.c
index 3c03159..fb0540a 100644
--- a/hw/scsi-disk.c
+++ b/hw/scsi-disk.c
@@ -1702,6 +1702,10 @@ static int32_t scsi_disk_emulate_command(SCSIRequest *req, uint8_t *buf)
     case WRITE_SAME_16:
         nb_sectors = ldl_be_p(&req->cmd.buf[10]) & 0xffffffffULL;
     write_same:
+        if (bdrv_is_read_only(s->qdev.conf.bs)) {
+            scsi_check_condition(r, SENSE_CODE(WRITE_PROTECTED));
+            return 0;
+        }
         if (r->req.cmd.lba > s->qdev.max_lba) {
             goto illegal_lba;
         }
@@ -1784,9 +1788,6 @@ static int32_t scsi_disk_dma_command(SCSIRequest *req, uint8_t *buf)
         r->sector = r->req.cmd.lba * (s->qdev.blocksize / 512);
         r->sector_count = len * (s->qdev.blocksize / 512);
         break;
-    case VERIFY_10:
-    case VERIFY_12:
-    case VERIFY_16:
     case WRITE_6:
     case WRITE_10:
     case WRITE_12:
@@ -1794,6 +1795,14 @@ static int32_t scsi_disk_dma_command(SCSIRequest *req, uint8_t *buf)
     case WRITE_VERIFY_10:
     case WRITE_VERIFY_12:
     case WRITE_VERIFY_16:
+        if (bdrv_is_read_only(s->qdev.conf.bs)) {
+            scsi_check_condition(r, SENSE_CODE(WRITE_PROTECTED));
+            return 0;
+        }
+        /* fallthrough */
+    case VERIFY_10:
+    case VERIFY_12:
+    case VERIFY_16:
         len = r->req.cmd.xfer / s->qdev.blocksize;
         DPRINTF("Write %s(sector %" PRId64 ", count %d)\n",
                 (command & 0xe) == 0xe ? "And Verify " : "",
diff --git a/hw/scsi.h b/hw/scsi.h
index e2fb8a4..fc9dc50 100644
--- a/hw/scsi.h
+++ b/hw/scsi.h
@@ -208,6 +208,8 @@ extern const struct SCSISense sense_code_MEDIUM_CHANGED;
 extern const struct SCSISense sense_code_REPORTED_LUNS_CHANGED;
 /* Unit attention, Device internal reset */
 extern const struct SCSISense sense_code_DEVICE_INTERNAL_RESET;
+/* Data Protection, Write Protected */
+extern const struct SCSISense sense_code_WRITE_PROTECTED;
 
 #define SENSE_CODE(x) sense_code_ ## x
 
commit ba6095cd6b497783e3621606b6b2320781aa3f52
Author: Ronnie Sahlberg <ronniesahlberg at gmail.com>
Date:   Thu Jul 12 16:52:47 2012 +1000

    scsi-disk: improve the lba-out-of-range tests for read/write/verify
    
    Improve the tests for the LBA to cover more cases.
    
    For the 16 byte opcodes, the lba is a uint64, so we need to check is to
    make sure that we do not wrap.  For example if an opcode would specify
    the LBA:0xffffffffffffffff and LEN:2 then lba+len would wrap to 1.
    
    Also verify that ALL requested blocks are available, not just the first one.
    
    Signed-off-by: Ronnie Sahlberg <ronniesahlberg at gmail.com>
    Signed-off-by: Paolo Bonzini <pbonzini at redhat.com>

diff --git a/hw/scsi-disk.c b/hw/scsi-disk.c
index 526da4b..3c03159 100644
--- a/hw/scsi-disk.c
+++ b/hw/scsi-disk.c
@@ -1777,7 +1777,8 @@ static int32_t scsi_disk_dma_command(SCSIRequest *req, uint8_t *buf)
         if (r->req.cmd.buf[1] & 0xe0) {
             goto illegal_request;
         }
-        if (r->req.cmd.lba > s->qdev.max_lba) {
+        if (r->req.cmd.lba > r->req.cmd.lba + len ||
+            r->req.cmd.lba + len - 1 > s->qdev.max_lba) {
             goto illegal_lba;
         }
         r->sector = r->req.cmd.lba * (s->qdev.blocksize / 512);
@@ -1800,7 +1801,8 @@ static int32_t scsi_disk_dma_command(SCSIRequest *req, uint8_t *buf)
         if (r->req.cmd.buf[1] & 0xe0) {
             goto illegal_request;
         }
-        if (r->req.cmd.lba > s->qdev.max_lba) {
+        if (r->req.cmd.lba > r->req.cmd.lba + len ||
+            r->req.cmd.lba + len - 1 > s->qdev.max_lba) {
             goto illegal_lba;
         }
         r->sector = r->req.cmd.lba * (s->qdev.blocksize / 512);
commit 96bdbbab55976b106f9db2b61042ebf5f0493e5a
Author: Ronnie Sahlberg <ronniesahlberg at gmail.com>
Date:   Thu Jul 12 10:19:38 2012 +1000

    scsi-disk: rd/wr/vr-protect !=0 is an error
    
    The QEMU SCSI emulation does not support protection information,
    so any READ/WRITE/VERIFY commands that has the protect bits set to
    non-zero should fail with ILLEGAL_REQUEST/INVALID_FIELD_IN_CDB
    
    From SCSI SBC :
    If the logical unit does not support protection information,
    then the device server should terminate the command with CHECK CONDITION
    status with the sense key set to ILLEGAL REQUEST and the additional sense
    code set to INVALID FIELD IN CDB.
    
    Signed-off-by: Ronnie Sahlberg <ronniesahlberg at gmail.com>
    [ Rebase after scsi_dma_reqops introduction - Paolo ]
    Signed-off-by: Paolo Bonzini <pbonzini at redhat.com>

diff --git a/hw/scsi-disk.c b/hw/scsi-disk.c
index fd5cd70..526da4b 100644
--- a/hw/scsi-disk.c
+++ b/hw/scsi-disk.c
@@ -1774,6 +1774,9 @@ static int32_t scsi_disk_dma_command(SCSIRequest *req, uint8_t *buf)
     case READ_16:
         len = r->req.cmd.xfer / s->qdev.blocksize;
         DPRINTF("Read (sector %" PRId64 ", count %d)\n", r->req.cmd.lba, len);
+        if (r->req.cmd.buf[1] & 0xe0) {
+            goto illegal_request;
+        }
         if (r->req.cmd.lba > s->qdev.max_lba) {
             goto illegal_lba;
         }
@@ -1794,6 +1797,9 @@ static int32_t scsi_disk_dma_command(SCSIRequest *req, uint8_t *buf)
         DPRINTF("Write %s(sector %" PRId64 ", count %d)\n",
                 (command & 0xe) == 0xe ? "And Verify " : "",
                 r->req.cmd.lba, len);
+        if (r->req.cmd.buf[1] & 0xe0) {
+            goto illegal_request;
+        }
         if (r->req.cmd.lba > s->qdev.max_lba) {
             goto illegal_lba;
         }
@@ -1802,6 +1808,9 @@ static int32_t scsi_disk_dma_command(SCSIRequest *req, uint8_t *buf)
         break;
     default:
         abort();
+    illegal_request:
+        scsi_check_condition(r, SENSE_CODE(INVALID_FIELD));
+        return 0;
     illegal_lba:
         scsi_check_condition(r, SENSE_CODE(LBA_OUT_OF_RANGE));
         return 0;
commit 96c91bbf6090b3098db22ed19ab5ae2f9c6e4f16
Author: Paolo Bonzini <pbonzini at redhat.com>
Date:   Tue Jul 10 15:03:17 2012 +0200

    scsi-disk: support toggling the write cache
    
    Finally, this uses the "plumbing" in the previous patch to
    add support for toggling the WCE bit of the caching mode page.
    
    Signed-off-by: Paolo Bonzini <pbonzini at redhat.com>

diff --git a/hw/scsi-disk.c b/hw/scsi-disk.c
index ad6c00d..fd5cd70 100644
--- a/hw/scsi-disk.c
+++ b/hw/scsi-disk.c
@@ -1050,10 +1050,8 @@ static int mode_sense_page(SCSIDiskState *s, int page, uint8_t **p_outbuf,
 
     case MODE_PAGE_CACHING:
         length = 0x12;
-        if (page_control == 1) { /* Changeable Values */
-            break;
-        }
-        if (bdrv_enable_write_cache(s->qdev.conf.bs)) {
+        if (page_control == 1 || /* Changeable Values */
+            bdrv_enable_write_cache(s->qdev.conf.bs)) {
             p[0] = 4; /* WCE */
         }
         break;
@@ -1325,6 +1323,14 @@ static int scsi_disk_check_mode_select(SCSIDiskState *s, int page,
 
 static void scsi_disk_apply_mode_select(SCSIDiskState *s, int page, uint8_t *p)
 {
+    switch (page) {
+    case MODE_PAGE_CACHING:
+        bdrv_set_enable_write_cache(s->qdev.conf.bs, (p[0] & 4) != 0);
+        break;
+
+    default:
+        break;
+    }
 }
 
 static int mode_select_pages(SCSIDiskReq *r, uint8_t *p, int len, bool change)
commit 380feaffb0fcc8e5f615ed8e86d2e93717a6f2c6
Author: Paolo Bonzini <pbonzini at redhat.com>
Date:   Tue Jul 10 15:02:55 2012 +0200

    scsi-disk: parse MODE SELECT commands and parameters
    
    This adds the bulk of the parsing code for MODE SELECT, including
    breaking out changes to different mode pages, and checking that only
    changeable values are modified.
    
    In order to report errors correctly two passes are made through the
    parameters; the first only looks for errors, the second actually
    applies the changes to the mode page.
    
    Signed-off-by: Paolo Bonzini <pbonzini at redhat.com>

diff --git a/hw/scsi-bus.c b/hw/scsi-bus.c
index dc74063..efbda6f 100644
--- a/hw/scsi-bus.c
+++ b/hw/scsi-bus.c
@@ -1112,6 +1112,16 @@ const struct SCSISense sense_code_INVALID_FIELD = {
     .key = ILLEGAL_REQUEST, .asc = 0x24, .ascq = 0x00
 };
 
+/* Illegal request, Invalid field in parameter list */
+const struct SCSISense sense_code_INVALID_PARAM = {
+    .key = ILLEGAL_REQUEST, .asc = 0x26, .ascq = 0x00
+};
+
+/* Illegal request, Parameter list length error */
+const struct SCSISense sense_code_INVALID_PARAM_LEN = {
+    .key = ILLEGAL_REQUEST, .asc = 0x1a, .ascq = 0x00
+};
+
 /* Illegal request, LUN not supported */
 const struct SCSISense sense_code_LUN_NOT_SUPPORTED = {
     .key = ILLEGAL_REQUEST, .asc = 0x25, .ascq = 0x00
diff --git a/hw/scsi-disk.c b/hw/scsi-disk.c
index 7015420..ad6c00d 100644
--- a/hw/scsi-disk.c
+++ b/hw/scsi-disk.c
@@ -43,6 +43,7 @@ do { printf("scsi-disk: " fmt , ## __VA_ARGS__); } while (0)
 
 #define SCSI_DMA_BUF_SIZE    131072
 #define SCSI_MAX_INQUIRY_LEN 256
+#define SCSI_MAX_MODE_LEN    256
 
 typedef struct SCSIDiskState SCSIDiskState;
 
@@ -1283,6 +1284,159 @@ static void scsi_disk_emulate_read_data(SCSIRequest *req)
     scsi_req_complete(&r->req, GOOD);
 }
 
+static int scsi_disk_check_mode_select(SCSIDiskState *s, int page,
+                                       uint8_t *inbuf, int inlen)
+{
+    uint8_t mode_current[SCSI_MAX_MODE_LEN];
+    uint8_t mode_changeable[SCSI_MAX_MODE_LEN];
+    uint8_t *p;
+    int len, expected_len, changeable_len, i;
+
+    /* The input buffer does not include the page header, so it is
+     * off by 2 bytes.
+     */
+    expected_len = inlen + 2;
+    if (expected_len > SCSI_MAX_MODE_LEN) {
+        return -1;
+    }
+
+    p = mode_current;
+    memset(mode_current, 0, inlen + 2);
+    len = mode_sense_page(s, page, &p, 0);
+    if (len < 0 || len != expected_len) {
+        return -1;
+    }
+
+    p = mode_changeable;
+    memset(mode_changeable, 0, inlen + 2);
+    changeable_len = mode_sense_page(s, page, &p, 1);
+    assert(changeable_len == len);
+
+    /* Check that unchangeable bits are the same as what MODE SENSE
+     * would return.
+     */
+    for (i = 2; i < len; i++) {
+        if (((mode_current[i] ^ inbuf[i - 2]) & ~mode_changeable[i]) != 0) {
+            return -1;
+        }
+    }
+    return 0;
+}
+
+static void scsi_disk_apply_mode_select(SCSIDiskState *s, int page, uint8_t *p)
+{
+}
+
+static int mode_select_pages(SCSIDiskReq *r, uint8_t *p, int len, bool change)
+{
+    SCSIDiskState *s = DO_UPCAST(SCSIDiskState, qdev, r->req.dev);
+
+    while (len > 0) {
+        int page, subpage, page_len;
+
+        /* Parse both possible formats for the mode page headers.  */
+        page = p[0] & 0x3f;
+        if (p[0] & 0x40) {
+            if (len < 4) {
+                goto invalid_param_len;
+            }
+            subpage = p[1];
+            page_len = lduw_be_p(&p[2]);
+            p += 4;
+            len -= 4;
+        } else {
+            if (len < 2) {
+                goto invalid_param_len;
+            }
+            subpage = 0;
+            page_len = p[1];
+            p += 2;
+            len -= 2;
+        }
+
+        if (subpage) {
+            goto invalid_param;
+        }
+        if (page_len > len) {
+            goto invalid_param_len;
+        }
+
+        if (!change) {
+            if (scsi_disk_check_mode_select(s, page, p, page_len) < 0) {
+                goto invalid_param;
+            }
+        } else {
+            scsi_disk_apply_mode_select(s, page, p);
+        }
+
+        p += page_len;
+        len -= page_len;
+    }
+    return 0;
+
+invalid_param:
+    scsi_check_condition(r, SENSE_CODE(INVALID_PARAM));
+    return -1;
+
+invalid_param_len:
+    scsi_check_condition(r, SENSE_CODE(INVALID_PARAM_LEN));
+    return -1;
+}
+
+static void scsi_disk_emulate_mode_select(SCSIDiskReq *r, uint8_t *inbuf)
+{
+    uint8_t *p = inbuf;
+    int cmd = r->req.cmd.buf[0];
+    int len = r->req.cmd.xfer;
+    int hdr_len = (cmd == MODE_SELECT ? 4 : 8);
+    int bd_len;
+    int pass;
+
+    /* We only support PF=1, SP=0.  */
+    if ((r->req.cmd.buf[1] & 0x11) != 0x10) {
+        goto invalid_field;
+    }
+
+    if (len < hdr_len) {
+        goto invalid_param_len;
+    }
+
+    bd_len = (cmd == MODE_SELECT ? p[3] : lduw_be_p(&p[6]));
+    len -= hdr_len;
+    p += hdr_len;
+    if (len < bd_len) {
+        goto invalid_param_len;
+    }
+    if (bd_len != 0 && bd_len != 8) {
+        goto invalid_param;
+    }
+
+    len -= bd_len;
+    p += bd_len;
+
+    /* Ensure no change is made if there is an error!  */
+    for (pass = 0; pass < 2; pass++) {
+        if (mode_select_pages(r, p, len, pass == 1) < 0) {
+            assert(pass == 0);
+            return;
+        }
+    }
+    scsi_req_complete(&r->req, GOOD);
+    return;
+
+invalid_param:
+    scsi_check_condition(r, SENSE_CODE(INVALID_PARAM));
+    return;
+
+invalid_param_len:
+    scsi_check_condition(r, SENSE_CODE(INVALID_PARAM_LEN));
+    return;
+
+invalid_field:
+    scsi_check_condition(r, SENSE_CODE(INVALID_FIELD));
+    return;
+}
+
 static void scsi_disk_emulate_write_data(SCSIRequest *req)
 {
     SCSIDiskReq *r = DO_UPCAST(SCSIDiskReq, req, req);
@@ -1299,7 +1453,7 @@ static void scsi_disk_emulate_write_data(SCSIRequest *req)
     case MODE_SELECT:
     case MODE_SELECT_10:
         /* This also clears the sense buffer for REQUEST SENSE.  */
-        scsi_req_complete(&r->req, GOOD);
+        scsi_disk_emulate_mode_select(r, r->iov.iov_base);
         break;
 
     default:
@@ -1532,19 +1686,9 @@ static int32_t scsi_disk_emulate_command(SCSIRequest *req, uint8_t *buf)
         break;
     case MODE_SELECT:
         DPRINTF("Mode Select(6) (len %lu)\n", (long)r->req.cmd.xfer);
-        /* We don't support mode parameter changes.
-           Allow the mode parameter header + block descriptors only. */
-        if (r->req.cmd.xfer > 12) {
-            goto illegal_request;
-        }
         break;
     case MODE_SELECT_10:
         DPRINTF("Mode Select(10) (len %lu)\n", (long)r->req.cmd.xfer);
-        /* We don't support mode parameter changes.
-           Allow the mode parameter header + block descriptors only. */
-        if (r->req.cmd.xfer > 16) {
-            goto illegal_request;
-        }
         break;
     case WRITE_SAME_10:
         nb_sectors = lduw_be_p(&req->cmd.buf[7]);
diff --git a/hw/scsi.h b/hw/scsi.h
index ea8a155..e2fb8a4 100644
--- a/hw/scsi.h
+++ b/hw/scsi.h
@@ -180,6 +180,10 @@ extern const struct SCSISense sense_code_INVALID_OPCODE;
 extern const struct SCSISense sense_code_LBA_OUT_OF_RANGE;
 /* Illegal request, Invalid field in CDB */
 extern const struct SCSISense sense_code_INVALID_FIELD;
+/* Illegal request, Invalid field in parameter list */
+extern const struct SCSISense sense_code_INVALID_PARAM;
+/* Illegal request, Parameter list length error */
+extern const struct SCSISense sense_code_INVALID_PARAM_LEN;
 /* Illegal request, LUN not supported */
 extern const struct SCSISense sense_code_LUN_NOT_SUPPORTED;
 /* Illegal request, Saving parameters not supported */
commit 4f588b151127a2556ad0c52158f98cfe1a9c0cfa
Author: Paolo Bonzini <pbonzini at redhat.com>
Date:   Tue Jul 10 14:04:51 2012 +0200

    scsi-disk: fix changeable values for MODE_PAGE_R_W_ERROR
    
    The changeable values were not all-zeros for this mode page, fix it.
    
    Signed-off-by: Paolo Bonzini <pbonzini at redhat.com>

diff --git a/hw/scsi-disk.c b/hw/scsi-disk.c
index dca9866..7015420 100644
--- a/hw/scsi-disk.c
+++ b/hw/scsi-disk.c
@@ -1059,6 +1059,9 @@ static int mode_sense_page(SCSIDiskState *s, int page, uint8_t **p_outbuf,
 
     case MODE_PAGE_R_W_ERROR:
         length = 10;
+        if (page_control == 1) { /* Changeable Values */
+            break;
+        }
         p[0] = 0x80; /* Automatic Write Reallocation Enabled */
         if (s->qdev.type == TYPE_ROM) {
             p[1] = 0x20; /* Read Retry Count */
commit ef405611168015cfd28669e04506bb99d7c39288
Author: Paolo Bonzini <pbonzini at redhat.com>
Date:   Thu Jul 12 16:08:24 2012 +0200

    scsi-disk: adjust offsets in MODE SENSE by 2
    
    This will make offsets the same when implementing MODE SELECT.  This is
    because MODE SELECT has to deal with both 2-byte and 4-byte headers.
    Unfortunately, this means that the offsets are now off by two compared
    to the descriptions in the SCSI specs, which include the header.
    
    Signed-off-by: Paolo Bonzini <pbonzini at redhat.com>

diff --git a/hw/scsi-disk.c b/hw/scsi-disk.c
index b8d6086..dca9866 100644
--- a/hw/scsi-disk.c
+++ b/hw/scsi-disk.c
@@ -959,148 +959,156 @@ static int mode_sense_page(SCSIDiskState *s, int page, uint8_t **p_outbuf,
         [MODE_PAGE_AUDIO_CTL]              = (1 << TYPE_ROM),
         [MODE_PAGE_CAPABILITIES]           = (1 << TYPE_ROM),
     };
-    uint8_t *p = *p_outbuf;
+
+    uint8_t *p = *p_outbuf + 2;
+    int length;
 
     if ((mode_sense_valid[page] & (1 << s->qdev.type)) == 0) {
         return -1;
     }
 
-    p[0] = page;
-
     /*
      * If Changeable Values are requested, a mask denoting those mode parameters
      * that are changeable shall be returned. As we currently don't support
      * parameter changes via MODE_SELECT all bits are returned set to zero.
      * The buffer was already menset to zero by the caller of this function.
+     *
+     * The offsets here are off by two compared to the descriptions in the
+     * SCSI specs, because those include a 2-byte header.  This is unfortunate,
+     * but it is done so that offsets are consistent within our implementation
+     * of MODE SENSE and MODE SELECT.  MODE SELECT has to deal with both
+     * 2-byte and 4-byte headers.
      */
     switch (page) {
     case MODE_PAGE_HD_GEOMETRY:
-        p[1] = 0x16;
+        length = 0x16;
         if (page_control == 1) { /* Changeable Values */
             break;
         }
         /* if a geometry hint is available, use it */
-        p[2] = (s->qdev.conf.cyls >> 16) & 0xff;
-        p[3] = (s->qdev.conf.cyls >> 8) & 0xff;
-        p[4] = s->qdev.conf.cyls & 0xff;
-        p[5] = s->qdev.conf.heads & 0xff;
+        p[0] = (s->qdev.conf.cyls >> 16) & 0xff;
+        p[1] = (s->qdev.conf.cyls >> 8) & 0xff;
+        p[2] = s->qdev.conf.cyls & 0xff;
+        p[3] = s->qdev.conf.heads & 0xff;
         /* Write precomp start cylinder, disabled */
-        p[6] = (s->qdev.conf.cyls >> 16) & 0xff;
-        p[7] = (s->qdev.conf.cyls >> 8) & 0xff;
-        p[8] = s->qdev.conf.cyls & 0xff;
+        p[4] = (s->qdev.conf.cyls >> 16) & 0xff;
+        p[5] = (s->qdev.conf.cyls >> 8) & 0xff;
+        p[6] = s->qdev.conf.cyls & 0xff;
         /* Reduced current start cylinder, disabled */
-        p[9] = (s->qdev.conf.cyls >> 16) & 0xff;
-        p[10] = (s->qdev.conf.cyls >> 8) & 0xff;
-        p[11] = s->qdev.conf.cyls & 0xff;
+        p[7] = (s->qdev.conf.cyls >> 16) & 0xff;
+        p[8] = (s->qdev.conf.cyls >> 8) & 0xff;
+        p[9] = s->qdev.conf.cyls & 0xff;
         /* Device step rate [ns], 200ns */
-        p[12] = 0;
-        p[13] = 200;
+        p[10] = 0;
+        p[11] = 200;
         /* Landing zone cylinder */
+        p[12] = 0xff;
+        p[13] =  0xff;
         p[14] = 0xff;
-        p[15] =  0xff;
-        p[16] = 0xff;
         /* Medium rotation rate [rpm], 5400 rpm */
-        p[20] = (5400 >> 8) & 0xff;
-        p[21] = 5400 & 0xff;
+        p[18] = (5400 >> 8) & 0xff;
+        p[19] = 5400 & 0xff;
         break;
 
     case MODE_PAGE_FLEXIBLE_DISK_GEOMETRY:
-        p[1] = 0x1e;
+        length = 0x1e;
         if (page_control == 1) { /* Changeable Values */
             break;
         }
         /* Transfer rate [kbit/s], 5Mbit/s */
-        p[2] = 5000 >> 8;
-        p[3] = 5000 & 0xff;
+        p[0] = 5000 >> 8;
+        p[1] = 5000 & 0xff;
         /* if a geometry hint is available, use it */
-        p[4] = s->qdev.conf.heads & 0xff;
-        p[5] = s->qdev.conf.secs & 0xff;
-        p[6] = s->qdev.blocksize >> 8;
+        p[2] = s->qdev.conf.heads & 0xff;
+        p[3] = s->qdev.conf.secs & 0xff;
+        p[4] = s->qdev.blocksize >> 8;
+        p[6] = (s->qdev.conf.cyls >> 8) & 0xff;
+        p[7] = s->qdev.conf.cyls & 0xff;
+        /* Write precomp start cylinder, disabled */
         p[8] = (s->qdev.conf.cyls >> 8) & 0xff;
         p[9] = s->qdev.conf.cyls & 0xff;
-        /* Write precomp start cylinder, disabled */
+        /* Reduced current start cylinder, disabled */
         p[10] = (s->qdev.conf.cyls >> 8) & 0xff;
         p[11] = s->qdev.conf.cyls & 0xff;
-        /* Reduced current start cylinder, disabled */
-        p[12] = (s->qdev.conf.cyls >> 8) & 0xff;
-        p[13] = s->qdev.conf.cyls & 0xff;
         /* Device step rate [100us], 100us */
-        p[14] = 0;
-        p[15] = 1;
+        p[12] = 0;
+        p[13] = 1;
         /* Device step pulse width [us], 1us */
-        p[16] = 1;
+        p[14] = 1;
         /* Device head settle delay [100us], 100us */
-        p[17] = 0;
-        p[18] = 1;
+        p[15] = 0;
+        p[16] = 1;
         /* Motor on delay [0.1s], 0.1s */
-        p[19] = 1;
+        p[17] = 1;
         /* Motor off delay [0.1s], 0.1s */
-        p[20] = 1;
+        p[18] = 1;
         /* Medium rotation rate [rpm], 5400 rpm */
-        p[28] = (5400 >> 8) & 0xff;
-        p[29] = 5400 & 0xff;
+        p[26] = (5400 >> 8) & 0xff;
+        p[27] = 5400 & 0xff;
         break;
 
     case MODE_PAGE_CACHING:
-        p[0] = 8;
-        p[1] = 0x12;
+        length = 0x12;
         if (page_control == 1) { /* Changeable Values */
             break;
         }
         if (bdrv_enable_write_cache(s->qdev.conf.bs)) {
-            p[2] = 4; /* WCE */
+            p[0] = 4; /* WCE */
         }
         break;
 
     case MODE_PAGE_R_W_ERROR:
-        p[1] = 10;
-        p[2] = 0x80; /* Automatic Write Reallocation Enabled */
+        length = 10;
+        p[0] = 0x80; /* Automatic Write Reallocation Enabled */
         if (s->qdev.type == TYPE_ROM) {
-            p[3] = 0x20; /* Read Retry Count */
+            p[1] = 0x20; /* Read Retry Count */
         }
         break;
 
     case MODE_PAGE_AUDIO_CTL:
-        p[1] = 14;
+        length = 14;
         break;
 
     case MODE_PAGE_CAPABILITIES:
-        p[1] = 0x14;
+        length = 0x14;
         if (page_control == 1) { /* Changeable Values */
             break;
         }
 
-        p[2] = 0x3b; /* CD-R & CD-RW read */
-        p[3] = 0; /* Writing not supported */
-        p[4] = 0x7f; /* Audio, composite, digital out,
+        p[0] = 0x3b; /* CD-R & CD-RW read */
+        p[1] = 0; /* Writing not supported */
+        p[2] = 0x7f; /* Audio, composite, digital out,
                         mode 2 form 1&2, multi session */
-        p[5] = 0xff; /* CD DA, DA accurate, RW supported,
+        p[3] = 0xff; /* CD DA, DA accurate, RW supported,
                         RW corrected, C2 errors, ISRC,
                         UPC, Bar code */
-        p[6] = 0x2d | (s->tray_locked ? 2 : 0);
+        p[4] = 0x2d | (s->tray_locked ? 2 : 0);
         /* Locking supported, jumper present, eject, tray */
-        p[7] = 0; /* no volume & mute control, no
+        p[5] = 0; /* no volume & mute control, no
                      changer */
-        p[8] = (50 * 176) >> 8; /* 50x read speed */
-        p[9] = (50 * 176) & 0xff;
-        p[10] = 2 >> 8; /* Two volume levels */
-        p[11] = 2 & 0xff;
-        p[12] = 2048 >> 8; /* 2M buffer */
-        p[13] = 2048 & 0xff;
-        p[14] = (16 * 176) >> 8; /* 16x read speed current */
-        p[15] = (16 * 176) & 0xff;
-        p[18] = (16 * 176) >> 8; /* 16x write speed */
+        p[6] = (50 * 176) >> 8; /* 50x read speed */
+        p[7] = (50 * 176) & 0xff;
+        p[8] = 2 >> 8; /* Two volume levels */
+        p[9] = 2 & 0xff;
+        p[10] = 2048 >> 8; /* 2M buffer */
+        p[11] = 2048 & 0xff;
+        p[12] = (16 * 176) >> 8; /* 16x read speed current */
+        p[13] = (16 * 176) & 0xff;
+        p[16] = (16 * 176) >> 8; /* 16x write speed */
+        p[17] = (16 * 176) & 0xff;
+        p[18] = (16 * 176) >> 8; /* 16x write speed current */
         p[19] = (16 * 176) & 0xff;
-        p[20] = (16 * 176) >> 8; /* 16x write speed current */
-        p[21] = (16 * 176) & 0xff;
         break;
 
     default:
         return -1;
     }
 
-    *p_outbuf += p[1] + 2;
-    return p[1] + 2;
+    assert(length < 256);
+    (*p_outbuf)[0] = page;
+    (*p_outbuf)[1] = length;
+    *p_outbuf += length + 2;
+    return length + 2;
 }
 
 static int scsi_disk_emulate_mode_sense(SCSIDiskReq *r, uint8_t *outbuf)
commit af6d510ddbef5e0be9ce40464c2bf46da58eacf2
Author: Paolo Bonzini <pbonzini at redhat.com>
Date:   Wed Feb 8 10:32:55 2012 +0100

    scsi-disk: support emulated TO_DEV requests
    
    This adds the implementation of write_data for the emulated
    command case.  The first time through it asks for more data,
    the second time it finishes the processing of the command.
    
    MODE SELECT and MODE SELECT(10) can now be re-enabled, but they
    will not do much.
    
    Signed-off-by: Paolo Bonzini <pbonzini at redhat.com>

diff --git a/hw/scsi-disk.c b/hw/scsi-disk.c
index 1633177..b8d6086 100644
--- a/hw/scsi-disk.c
+++ b/hw/scsi-disk.c
@@ -1274,7 +1274,26 @@ static void scsi_disk_emulate_read_data(SCSIRequest *req)
 
 static void scsi_disk_emulate_write_data(SCSIRequest *req)
 {
-    abort();
+    SCSIDiskReq *r = DO_UPCAST(SCSIDiskReq, req, req);
+
+    if (r->iov.iov_len) {
+        int buflen = r->iov.iov_len;
+        DPRINTF("Write buf_len=%zd\n", buflen);
+        r->iov.iov_len = 0;
+        scsi_req_data(&r->req, buflen);
+        return;
+    }
+
+    switch (req->cmd.buf[0]) {
+    case MODE_SELECT:
+    case MODE_SELECT_10:
+        /* This also clears the sense buffer for REQUEST SENSE.  */
+        scsi_req_complete(&r->req, GOOD);
+        break;
+
+    default:
+        abort();
+    }
 }
 
 static int32_t scsi_disk_emulate_command(SCSIRequest *req, uint8_t *buf)
@@ -1283,7 +1302,7 @@ static int32_t scsi_disk_emulate_command(SCSIRequest *req, uint8_t *buf)
     SCSIDiskState *s = DO_UPCAST(SCSIDiskState, qdev, req->dev);
     uint64_t nb_sectors;
     uint8_t *outbuf;
-    int buflen = 0;
+    int buflen;
 
     switch (req->cmd.buf[0]) {
     case INQUIRY:
@@ -1309,7 +1328,6 @@ static int32_t scsi_disk_emulate_command(SCSIRequest *req, uint8_t *buf)
         break;
     }
 
-    assert(req->cmd.mode != SCSI_XFER_TO_DEV);
     if (!r->iov.iov_base) {
         /*
          * FIXME: we shouldn't return anything bigger than 4k, but the code
@@ -1326,6 +1344,7 @@ static int32_t scsi_disk_emulate_command(SCSIRequest *req, uint8_t *buf)
         r->iov.iov_base = qemu_blockalign(s->qdev.conf.bs, r->buflen);
     }
 
+    buflen = req->cmd.xfer;
     outbuf = r->iov.iov_base;
     switch (req->cmd.buf[0]) {
     case TEST_UNIT_READY:
@@ -1500,7 +1519,6 @@ static int32_t scsi_disk_emulate_command(SCSIRequest *req, uint8_t *buf)
             goto illegal_lba;
         }
         break;
-#if 0
     case MODE_SELECT:
         DPRINTF("Mode Select(6) (len %lu)\n", (long)r->req.cmd.xfer);
         /* We don't support mode parameter changes.
@@ -1517,7 +1535,6 @@ static int32_t scsi_disk_emulate_command(SCSIRequest *req, uint8_t *buf)
             goto illegal_request;
         }
         break;
-#endif
     case WRITE_SAME_10:
         nb_sectors = lduw_be_p(&req->cmd.buf[7]);
         goto write_same;
@@ -1552,7 +1569,12 @@ static int32_t scsi_disk_emulate_command(SCSIRequest *req, uint8_t *buf)
     if (r->iov.iov_len == 0) {
         scsi_req_complete(&r->req, GOOD);
     }
-    return r->iov.iov_len;
+    if (r->req.cmd.mode == SCSI_XFER_TO_DEV) {
+        assert(r->iov.iov_len == req->cmd.xfer);
+        return -r->iov.iov_len;
+    } else {
+        return r->iov.iov_len;
+    }
 
 illegal_request:
     if (r->req.status == -1) {
@@ -1834,10 +1856,8 @@ static const SCSIReqOps *const scsi_disk_reqops_dispatch[256] = {
     [REQUEST_SENSE]                   = &scsi_disk_emulate_reqops,
     [SYNCHRONIZE_CACHE]               = &scsi_disk_emulate_reqops,
     [SEEK_10]                         = &scsi_disk_emulate_reqops,
-#if 0
     [MODE_SELECT]                     = &scsi_disk_emulate_reqops,
     [MODE_SELECT_10]                  = &scsi_disk_emulate_reqops,
-#endif
     [WRITE_SAME_10]                   = &scsi_disk_emulate_reqops,
     [WRITE_SAME_16]                   = &scsi_disk_emulate_reqops,
 
commit 314a329906d5238ab5993da95516fc5c40f58f54
Author: Paolo Bonzini <pbonzini at redhat.com>
Date:   Wed Feb 8 10:26:21 2012 +0100

    scsi-disk: separate read_data/write_data implementation for emulate_reqops
    
    The previous patch only separated the send_command callback.
    Use different implementations also for read_data and write_data.
    The latter is still unreachable, so it aborts for now.
    
    read_data passes the data buffer that was prepared and completes
    the command.
    
    Signed-off-by: Paolo Bonzini <pbonzini at redhat.com>

diff --git a/hw/scsi-disk.c b/hw/scsi-disk.c
index ea0b05e..1633177 100644
--- a/hw/scsi-disk.c
+++ b/hw/scsi-disk.c
@@ -343,13 +343,6 @@ static void scsi_read_data(SCSIRequest *req)
     SCSIDiskState *s = DO_UPCAST(SCSIDiskState, qdev, r->req.dev);
     bool first;
 
-    if (r->sector_count == (uint32_t)-1) {
-        DPRINTF("Read buf_len=%zd\n", r->iov.iov_len);
-        r->sector_count = 0;
-        r->started = true;
-        scsi_req_data(&r->req, r->iov.iov_len);
-        return;
-    }
     DPRINTF("Read sector_count=%d\n", r->sector_count);
     if (r->sector_count == 0) {
         /* This also clears the sense buffer for REQUEST SENSE.  */
@@ -1262,6 +1255,28 @@ static int scsi_disk_emulate_start_stop(SCSIDiskReq *r)
     return 0;
 }
 
+static void scsi_disk_emulate_read_data(SCSIRequest *req)
+{
+    SCSIDiskReq *r = DO_UPCAST(SCSIDiskReq, req, req);
+    int buflen = r->iov.iov_len;
+
+    if (buflen) {
+        DPRINTF("Read buf_len=%zd\n", buflen);
+        r->iov.iov_len = 0;
+        r->started = true;
+        scsi_req_data(&r->req, buflen);
+        return;
+    }
+
+    /* This also clears the sense buffer for REQUEST SENSE.  */
+    scsi_req_complete(&r->req, GOOD);
+}
+
+static void scsi_disk_emulate_write_data(SCSIRequest *req)
+{
+    abort();
+}
+
 static int32_t scsi_disk_emulate_command(SCSIRequest *req, uint8_t *buf)
 {
     SCSIDiskReq *r = DO_UPCAST(SCSIDiskReq, req, req);
@@ -1532,9 +1547,8 @@ static int32_t scsi_disk_emulate_command(SCSIRequest *req, uint8_t *buf)
         scsi_check_condition(r, SENSE_CODE(INVALID_OPCODE));
         return 0;
     }
-    assert(!r->req.aiocb && r->sector_count == 0);
+    assert(!r->req.aiocb);
     r->iov.iov_len = MIN(buflen, req->cmd.xfer);
-    r->sector_count = -1;
     if (r->iov.iov_len == 0) {
         scsi_req_complete(&r->req, GOOD);
     }
@@ -1785,8 +1799,8 @@ static const SCSIReqOps scsi_disk_emulate_reqops = {
     .size         = sizeof(SCSIDiskReq),
     .free_req     = scsi_free_request,
     .send_command = scsi_disk_emulate_command,
-    .read_data    = scsi_read_data,
-    .write_data   = scsi_write_data,
+    .read_data    = scsi_disk_emulate_read_data,
+    .write_data   = scsi_disk_emulate_write_data,
     .get_buf      = scsi_get_buf,
 };
 
commit b08d0ea0446aa91f373c9df4254ba3bc4ee84098
Author: Paolo Bonzini <pbonzini at redhat.com>
Date:   Wed Feb 8 09:53:42 2012 +0100

    scsi-disk: split scsi-disk reqops
    
    Only checks for present medium were still done in scsi_send_command
    for emulated commands.  So move those to scsi_disk_emulate_command
    and return different SCSIReqOps depending on the kind of command.
    
    Checks for present medium can be done unconditionally for the
    scsi_disk_dma_reqops case.
    
    Signed-off-by: Paolo Bonzini <pbonzini at redhat.com>

diff --git a/hw/scsi-disk.c b/hw/scsi-disk.c
index 9f7258d..ea0b05e 100644
--- a/hw/scsi-disk.c
+++ b/hw/scsi-disk.c
@@ -1262,14 +1262,39 @@ static int scsi_disk_emulate_start_stop(SCSIDiskReq *r)
     return 0;
 }
 
-static int scsi_disk_emulate_command(SCSIDiskReq *r)
+static int32_t scsi_disk_emulate_command(SCSIRequest *req, uint8_t *buf)
 {
-    SCSIRequest *req = &r->req;
+    SCSIDiskReq *r = DO_UPCAST(SCSIDiskReq, req, req);
     SCSIDiskState *s = DO_UPCAST(SCSIDiskState, qdev, req->dev);
     uint64_t nb_sectors;
     uint8_t *outbuf;
     int buflen = 0;
 
+    switch (req->cmd.buf[0]) {
+    case INQUIRY:
+    case MODE_SENSE:
+    case MODE_SENSE_10:
+    case RESERVE:
+    case RESERVE_10:
+    case RELEASE:
+    case RELEASE_10:
+    case START_STOP:
+    case ALLOW_MEDIUM_REMOVAL:
+    case GET_CONFIGURATION:
+    case GET_EVENT_STATUS_NOTIFICATION:
+    case MECHANISM_STATUS:
+    case REQUEST_SENSE:
+        break;
+
+    default:
+        if (s->tray_open || !bdrv_is_inserted(s->qdev.conf.bs)) {
+            scsi_check_condition(r, SENSE_CODE(NO_MEDIUM));
+            return 0;
+        }
+        break;
+    }
+
+    assert(req->cmd.mode != SCSI_XFER_TO_DEV);
     if (!r->iov.iov_base) {
         /*
          * FIXME: we shouldn't return anything bigger than 4k, but the code
@@ -1332,7 +1357,7 @@ static int scsi_disk_emulate_command(SCSIDiskReq *r)
         break;
     case START_STOP:
         if (scsi_disk_emulate_start_stop(r) < 0) {
-            return -1;
+            return 0;
         }
         break;
     case ALLOW_MEDIUM_REMOVAL:
@@ -1503,18 +1528,23 @@ static int scsi_disk_emulate_command(SCSIDiskReq *r)
                                         scsi_aio_complete, r);
         return 0;
     default:
+        DPRINTF("Unknown SCSI command (%2.2x)\n", buf[0]);
         scsi_check_condition(r, SENSE_CODE(INVALID_OPCODE));
-        return -1;
+        return 0;
     }
-    assert(r->sector_count == 0);
-    buflen = MIN(buflen, req->cmd.xfer);
-    return buflen;
+    assert(!r->req.aiocb && r->sector_count == 0);
+    r->iov.iov_len = MIN(buflen, req->cmd.xfer);
+    r->sector_count = -1;
+    if (r->iov.iov_len == 0) {
+        scsi_req_complete(&r->req, GOOD);
+    }
+    return r->iov.iov_len;
 
 illegal_request:
     if (r->req.status == -1) {
         scsi_check_condition(r, SENSE_CODE(INVALID_FIELD));
     }
-    return -1;
+    return 0;
 
 illegal_lba:
     scsi_check_condition(r, SENSE_CODE(LBA_OUT_OF_RANGE));
@@ -1526,49 +1556,18 @@ illegal_lba:
    (eg. disk reads), negative for transfers to the device (eg. disk writes),
    and zero if the command does not transfer any data.  */
 
-static int32_t scsi_send_command(SCSIRequest *req, uint8_t *buf)
+static int32_t scsi_disk_dma_command(SCSIRequest *req, uint8_t *buf)
 {
     SCSIDiskReq *r = DO_UPCAST(SCSIDiskReq, req, req);
     SCSIDiskState *s = DO_UPCAST(SCSIDiskState, qdev, req->dev);
     int32_t len;
     uint8_t command;
-    int rc;
 
     command = buf[0];
-    DPRINTF("Command: lun=%d tag=0x%x data=0x%02x", req->lun, req->tag, buf[0]);
-
-#ifdef DEBUG_SCSI
-    {
-        int i;
-        for (i = 1; i < r->req.cmd.len; i++) {
-            printf(" 0x%02x", buf[i]);
-        }
-        printf("\n");
-    }
-#endif
 
-    switch (command) {
-    case INQUIRY:
-    case MODE_SENSE:
-    case MODE_SENSE_10:
-    case RESERVE:
-    case RESERVE_10:
-    case RELEASE:
-    case RELEASE_10:
-    case START_STOP:
-    case ALLOW_MEDIUM_REMOVAL:
-    case GET_CONFIGURATION:
-    case GET_EVENT_STATUS_NOTIFICATION:
-    case MECHANISM_STATUS:
-    case REQUEST_SENSE:
-        break;
-
-    default:
-        if (s->tray_open || !bdrv_is_inserted(s->qdev.conf.bs)) {
-            scsi_check_condition(r, SENSE_CODE(NO_MEDIUM));
-            return 0;
-        }
-        break;
+    if (s->tray_open || !bdrv_is_inserted(s->qdev.conf.bs)) {
+        scsi_check_condition(r, SENSE_CODE(NO_MEDIUM));
+        return 0;
     }
 
     switch (command) {
@@ -1605,30 +1604,19 @@ static int32_t scsi_send_command(SCSIRequest *req, uint8_t *buf)
         r->sector_count = len * (s->qdev.blocksize / 512);
         break;
     default:
-        rc = scsi_disk_emulate_command(r);
-        if (rc < 0) {
-            return 0;
-        }
-        if (r->req.aiocb) {
-            return 0;
-        }
-        r->iov.iov_len = rc;
-        break;
+        abort();
     illegal_lba:
         scsi_check_condition(r, SENSE_CODE(LBA_OUT_OF_RANGE));
         return 0;
     }
-    if (r->sector_count == 0 && r->iov.iov_len == 0) {
+    if (r->sector_count == 0) {
         scsi_req_complete(&r->req, GOOD);
     }
-    len = r->sector_count * 512 + r->iov.iov_len;
+    assert(r->iov.iov_len == 0);
     if (r->req.cmd.mode == SCSI_XFER_TO_DEV) {
-        return -len;
+        return -r->sector_count * 512;
     } else {
-        if (!r->sector_count) {
-            r->sector_count = -1;
-        }
-        return len;
+        return r->sector_count * 512;
     }
 }
 
@@ -1793,10 +1781,19 @@ static int scsi_disk_initfn(SCSIDevice *dev)
     }
 }
 
-static const SCSIReqOps scsi_disk_reqops = {
+static const SCSIReqOps scsi_disk_emulate_reqops = {
     .size         = sizeof(SCSIDiskReq),
     .free_req     = scsi_free_request,
-    .send_command = scsi_send_command,
+    .send_command = scsi_disk_emulate_command,
+    .read_data    = scsi_read_data,
+    .write_data   = scsi_write_data,
+    .get_buf      = scsi_get_buf,
+};
+
+static const SCSIReqOps scsi_disk_dma_reqops = {
+    .size         = sizeof(SCSIDiskReq),
+    .free_req     = scsi_free_request,
+    .send_command = scsi_disk_dma_command,
     .read_data    = scsi_read_data,
     .write_data   = scsi_write_data,
     .cancel_io    = scsi_cancel_io,
@@ -1805,13 +1802,72 @@ static const SCSIReqOps scsi_disk_reqops = {
     .save_request = scsi_disk_save_request,
 };
 
+static const SCSIReqOps *const scsi_disk_reqops_dispatch[256] = {
+    [TEST_UNIT_READY]                 = &scsi_disk_emulate_reqops,
+    [INQUIRY]                         = &scsi_disk_emulate_reqops,
+    [MODE_SENSE]                      = &scsi_disk_emulate_reqops,
+    [MODE_SENSE_10]                   = &scsi_disk_emulate_reqops,
+    [START_STOP]                      = &scsi_disk_emulate_reqops,
+    [ALLOW_MEDIUM_REMOVAL]            = &scsi_disk_emulate_reqops,
+    [READ_CAPACITY_10]                = &scsi_disk_emulate_reqops,
+    [READ_TOC]                        = &scsi_disk_emulate_reqops,
+    [READ_DVD_STRUCTURE]              = &scsi_disk_emulate_reqops,
+    [READ_DISC_INFORMATION]           = &scsi_disk_emulate_reqops,
+    [GET_CONFIGURATION]               = &scsi_disk_emulate_reqops,
+    [GET_EVENT_STATUS_NOTIFICATION]   = &scsi_disk_emulate_reqops,
+    [MECHANISM_STATUS]                = &scsi_disk_emulate_reqops,
+    [SERVICE_ACTION_IN_16]            = &scsi_disk_emulate_reqops,
+    [REQUEST_SENSE]                   = &scsi_disk_emulate_reqops,
+    [SYNCHRONIZE_CACHE]               = &scsi_disk_emulate_reqops,
+    [SEEK_10]                         = &scsi_disk_emulate_reqops,
+#if 0
+    [MODE_SELECT]                     = &scsi_disk_emulate_reqops,
+    [MODE_SELECT_10]                  = &scsi_disk_emulate_reqops,
+#endif
+    [WRITE_SAME_10]                   = &scsi_disk_emulate_reqops,
+    [WRITE_SAME_16]                   = &scsi_disk_emulate_reqops,
+
+    [READ_6]                          = &scsi_disk_dma_reqops,
+    [READ_10]                         = &scsi_disk_dma_reqops,
+    [READ_12]                         = &scsi_disk_dma_reqops,
+    [READ_16]                         = &scsi_disk_dma_reqops,
+    [VERIFY_10]                       = &scsi_disk_dma_reqops,
+    [VERIFY_12]                       = &scsi_disk_dma_reqops,
+    [VERIFY_16]                       = &scsi_disk_dma_reqops,
+    [WRITE_6]                         = &scsi_disk_dma_reqops,
+    [WRITE_10]                        = &scsi_disk_dma_reqops,
+    [WRITE_12]                        = &scsi_disk_dma_reqops,
+    [WRITE_16]                        = &scsi_disk_dma_reqops,
+    [WRITE_VERIFY_10]                 = &scsi_disk_dma_reqops,
+    [WRITE_VERIFY_12]                 = &scsi_disk_dma_reqops,
+    [WRITE_VERIFY_16]                 = &scsi_disk_dma_reqops,
+};
+
 static SCSIRequest *scsi_new_request(SCSIDevice *d, uint32_t tag, uint32_t lun,
                                      uint8_t *buf, void *hba_private)
 {
     SCSIDiskState *s = DO_UPCAST(SCSIDiskState, qdev, d);
     SCSIRequest *req;
+    const SCSIReqOps *ops;
+    uint8_t command;
 
-    req = scsi_req_alloc(&scsi_disk_reqops, &s->qdev, tag, lun, hba_private);
+#ifdef DEBUG_SCSI
+    DPRINTF("Command: lun=%d tag=0x%x data=0x%02x", lun, buf[0]);
+    {
+        int i;
+        for (i = 1; i < r->req.cmd.len; i++) {
+            printf(" 0x%02x", buf[i]);
+        }
+        printf("\n");
+    }
+#endif
+
+    command = buf[0];
+    ops = scsi_disk_reqops_dispatch[command];
+    if (!ops) {
+        ops = &scsi_disk_emulate_reqops;
+    }
+    req = scsi_req_alloc(ops, &s->qdev, tag, lun, hba_private);
     return req;
 }
 
@@ -1925,15 +1981,14 @@ static SCSIRequest *scsi_block_new_request(SCSIDevice *d, uint32_t tag,
          * unreliable, too.  It is even possible that reads deliver random data
          * from the host page cache (this is probably a Linux bug).
          *
-         * We might use scsi_disk_reqops as long as no writing commands are
+         * We might use scsi_disk_dma_reqops as long as no writing commands are
          * seen, but performance usually isn't paramount on optical media.  So,
          * just make scsi-block operate the same as scsi-generic for them.
          */
-        if (s->qdev.type == TYPE_ROM) {
-            break;
-	}
-        return scsi_req_alloc(&scsi_disk_reqops, &s->qdev, tag, lun,
-                              hba_private);
+        if (s->qdev.type != TYPE_ROM) {
+            return scsi_req_alloc(&scsi_disk_dma_reqops, &s->qdev, tag, lun,
+                                  hba_private);
+        }
     }
 
     return scsi_req_alloc(&scsi_generic_req_ops, &s->qdev, tag, lun,
commit 101aa85f9862f23e17dec570221f53c46c5e86e1
Author: Paolo Bonzini <pbonzini at redhat.com>
Date:   Wed Feb 8 09:43:52 2012 +0100

    scsi-disk: move all non-DMA commands to scsi_disk_emulate_command
    
    We want to use separate SCSIReqOps for emulated commands needing an
    allocated buffer vs. those that are zerocopy when the HBA supports
    S/G lists.  Ensure that all of the former are in scsi_disk_emulate_command.
    
    Commands that do not have any parameters are more similar to emulated
    commands, so also move them, even if they do I/O.
    
    Finally, MODE SELECT and MODE SELECT(10) are broken because we do not
    yet support passing parameter data _to_ emulated commands, so disable
    them.
    
    Signed-off-by: Paolo Bonzini <pbonzini at redhat.com>

diff --git a/hw/scsi-disk.c b/hw/scsi-disk.c
index f8e9dc1..9f7258d 100644
--- a/hw/scsi-disk.c
+++ b/hw/scsi-disk.c
@@ -1448,10 +1448,65 @@ static int scsi_disk_emulate_command(SCSIDiskReq *r)
         }
         DPRINTF("Unsupported Service Action In\n");
         goto illegal_request;
+    case SYNCHRONIZE_CACHE:
+        /* The request is used as the AIO opaque value, so add a ref.  */
+        scsi_req_ref(&r->req);
+        bdrv_acct_start(s->qdev.conf.bs, &r->acct, 0, BDRV_ACCT_FLUSH);
+        r->req.aiocb = bdrv_aio_flush(s->qdev.conf.bs, scsi_aio_complete, r);
+        return 0;
+    case SEEK_10:
+        DPRINTF("Seek(10) (sector %" PRId64 ")\n", r->req.cmd.lba);
+        if (r->req.cmd.lba > s->qdev.max_lba) {
+            goto illegal_lba;
+        }
+        break;
+#if 0
+    case MODE_SELECT:
+        DPRINTF("Mode Select(6) (len %lu)\n", (long)r->req.cmd.xfer);
+        /* We don't support mode parameter changes.
+           Allow the mode parameter header + block descriptors only. */
+        if (r->req.cmd.xfer > 12) {
+            goto illegal_request;
+        }
+        break;
+    case MODE_SELECT_10:
+        DPRINTF("Mode Select(10) (len %lu)\n", (long)r->req.cmd.xfer);
+        /* We don't support mode parameter changes.
+           Allow the mode parameter header + block descriptors only. */
+        if (r->req.cmd.xfer > 16) {
+            goto illegal_request;
+        }
+        break;
+#endif
+    case WRITE_SAME_10:
+        nb_sectors = lduw_be_p(&req->cmd.buf[7]);
+        goto write_same;
+    case WRITE_SAME_16:
+        nb_sectors = ldl_be_p(&req->cmd.buf[10]) & 0xffffffffULL;
+    write_same:
+        if (r->req.cmd.lba > s->qdev.max_lba) {
+            goto illegal_lba;
+        }
+
+        /*
+         * We only support WRITE SAME with the unmap bit set for now.
+         */
+        if (!(req->cmd.buf[1] & 0x8)) {
+            goto illegal_request;
+        }
+
+        /* The request is used as the AIO opaque value, so add a ref.  */
+        scsi_req_ref(&r->req);
+        r->req.aiocb = bdrv_aio_discard(s->qdev.conf.bs,
+                                        r->req.cmd.lba * (s->qdev.blocksize / 512),
+                                        nb_sectors * (s->qdev.blocksize / 512),
+                                        scsi_aio_complete, r);
+        return 0;
     default:
         scsi_check_condition(r, SENSE_CODE(INVALID_OPCODE));
         return -1;
     }
+    assert(r->sector_count == 0);
     buflen = MIN(buflen, req->cmd.xfer);
     return buflen;
 
@@ -1460,6 +1515,10 @@ illegal_request:
         scsi_check_condition(r, SENSE_CODE(INVALID_FIELD));
     }
     return -1;
+
+illegal_lba:
+    scsi_check_condition(r, SENSE_CODE(LBA_OUT_OF_RANGE));
+    return 0;
 }
 
 /* Execute a scsi command.  Returns the length of the data expected by the
@@ -1513,38 +1572,6 @@ static int32_t scsi_send_command(SCSIRequest *req, uint8_t *buf)
     }
 
     switch (command) {
-    case TEST_UNIT_READY:
-    case INQUIRY:
-    case MODE_SENSE:
-    case MODE_SENSE_10:
-    case RESERVE:
-    case RESERVE_10:
-    case RELEASE:
-    case RELEASE_10:
-    case START_STOP:
-    case ALLOW_MEDIUM_REMOVAL:
-    case READ_CAPACITY_10:
-    case READ_TOC:
-    case READ_DISC_INFORMATION:
-    case READ_DVD_STRUCTURE:
-    case GET_CONFIGURATION:
-    case GET_EVENT_STATUS_NOTIFICATION:
-    case MECHANISM_STATUS:
-    case SERVICE_ACTION_IN_16:
-    case REQUEST_SENSE:
-        rc = scsi_disk_emulate_command(r);
-        if (rc < 0) {
-            return 0;
-        }
-
-        r->iov.iov_len = rc;
-        break;
-    case SYNCHRONIZE_CACHE:
-        /* The request is used as the AIO opaque value, so add a ref.  */
-        scsi_req_ref(&r->req);
-        bdrv_acct_start(s->qdev.conf.bs, &r->acct, 0, BDRV_ACCT_FLUSH);
-        r->req.aiocb = bdrv_aio_flush(s->qdev.conf.bs, scsi_aio_complete, r);
-        return 0;
     case READ_6:
     case READ_10:
     case READ_12:
@@ -1577,63 +1604,16 @@ static int32_t scsi_send_command(SCSIRequest *req, uint8_t *buf)
         r->sector = r->req.cmd.lba * (s->qdev.blocksize / 512);
         r->sector_count = len * (s->qdev.blocksize / 512);
         break;
-    case MODE_SELECT:
-        DPRINTF("Mode Select(6) (len %lu)\n", (long)r->req.cmd.xfer);
-        /* We don't support mode parameter changes.
-           Allow the mode parameter header + block descriptors only. */
-        if (r->req.cmd.xfer > 12) {
-            goto fail;
-        }
-        break;
-    case MODE_SELECT_10:
-        DPRINTF("Mode Select(10) (len %lu)\n", (long)r->req.cmd.xfer);
-        /* We don't support mode parameter changes.
-           Allow the mode parameter header + block descriptors only. */
-        if (r->req.cmd.xfer > 16) {
-            goto fail;
+    default:
+        rc = scsi_disk_emulate_command(r);
+        if (rc < 0) {
+            return 0;
         }
-        break;
-    case SEEK_10:
-        DPRINTF("Seek(10) (sector %" PRId64 ")\n", r->req.cmd.lba);
-        if (r->req.cmd.lba > s->qdev.max_lba) {
-            goto illegal_lba;
+        if (r->req.aiocb) {
+            return 0;
         }
+        r->iov.iov_len = rc;
         break;
-    case WRITE_SAME_10:
-        len = lduw_be_p(&buf[7]);
-        goto write_same;
-    case WRITE_SAME_16:
-        len = ldl_be_p(&buf[10]) & 0xffffffffULL;
-    write_same:
-
-        DPRINTF("WRITE SAME() (sector %" PRId64 ", count %d)\n",
-                r->req.cmd.lba, len);
-
-        if (r->req.cmd.lba > s->qdev.max_lba) {
-            goto illegal_lba;
-        }
-
-        /*
-         * We only support WRITE SAME with the unmap bit set for now.
-         */
-        if (!(buf[1] & 0x8)) {
-            goto fail;
-        }
-
-        /* The request is used as the AIO opaque value, so add a ref.  */
-        scsi_req_ref(&r->req);
-        r->req.aiocb = bdrv_aio_discard(s->qdev.conf.bs,
-                                        r->req.cmd.lba * (s->qdev.blocksize / 512),
-                                        len * (s->qdev.blocksize / 512),
-                                        scsi_aio_complete, r);
-        return 0;
-    default:
-        DPRINTF("Unknown SCSI command (%2.2x)\n", buf[0]);
-        scsi_check_condition(r, SENSE_CODE(INVALID_OPCODE));
-        return 0;
-    fail:
-        scsi_check_condition(r, SENSE_CODE(INVALID_FIELD));
-        return 0;
     illegal_lba:
         scsi_check_condition(r, SENSE_CODE(LBA_OUT_OF_RANGE));
         return 0;
commit c1b3524788c156c49bff5f0415c39f9f0b7cc0e2
Author: Paolo Bonzini <pbonzini at redhat.com>
Date:   Wed Feb 8 10:37:48 2012 +0100

    scsi-disk: make discard asynchronous
    
    By making discard asynchronous, we can reuse all the error handling
    code that is used for other commands.
    
    Signed-off-by: Paolo Bonzini <pbonzini at redhat.com>

diff --git a/hw/scsi-disk.c b/hw/scsi-disk.c
index 788fe86..f8e9dc1 100644
--- a/hw/scsi-disk.c
+++ b/hw/scsi-disk.c
@@ -169,7 +169,7 @@ static void scsi_disk_load_request(QEMUFile *f, SCSIRequest *req)
     qemu_iovec_init_external(&r->qiov, &r->iov, 1);
 }
 
-static void scsi_flush_complete(void * opaque, int ret)
+static void scsi_aio_complete(void *opaque, int ret)
 {
     SCSIDiskReq *r = (SCSIDiskReq *)opaque;
     SCSIDiskState *s = DO_UPCAST(SCSIDiskState, qdev, r->req.dev);
@@ -222,7 +222,7 @@ static void scsi_write_do_fua(SCSIDiskReq *r)
 
     if (scsi_is_cmd_fua(&r->req.cmd)) {
         bdrv_acct_start(s->qdev.conf.bs, &r->acct, 0, BDRV_ACCT_FLUSH);
-        r->req.aiocb = bdrv_aio_flush(s->qdev.conf.bs, scsi_flush_complete, r);
+        r->req.aiocb = bdrv_aio_flush(s->qdev.conf.bs, scsi_aio_complete, r);
         return;
     }
 
@@ -1543,7 +1543,7 @@ static int32_t scsi_send_command(SCSIRequest *req, uint8_t *buf)
         /* The request is used as the AIO opaque value, so add a ref.  */
         scsi_req_ref(&r->req);
         bdrv_acct_start(s->qdev.conf.bs, &r->acct, 0, BDRV_ACCT_FLUSH);
-        r->req.aiocb = bdrv_aio_flush(s->qdev.conf.bs, scsi_flush_complete, r);
+        r->req.aiocb = bdrv_aio_flush(s->qdev.conf.bs, scsi_aio_complete, r);
         return 0;
     case READ_6:
     case READ_10:
@@ -1620,15 +1620,13 @@ static int32_t scsi_send_command(SCSIRequest *req, uint8_t *buf)
             goto fail;
         }
 
-        rc = bdrv_discard(s->qdev.conf.bs,
-                          r->req.cmd.lba * (s->qdev.blocksize / 512),
-                          len * (s->qdev.blocksize / 512));
-        if (rc < 0) {
-            /* XXX: better error code ?*/
-            goto fail;
-        }
-
-        break;
+        /* The request is used as the AIO opaque value, so add a ref.  */
+        scsi_req_ref(&r->req);
+        r->req.aiocb = bdrv_aio_discard(s->qdev.conf.bs,
+                                        r->req.cmd.lba * (s->qdev.blocksize / 512),
+                                        len * (s->qdev.blocksize / 512),
+                                        scsi_aio_complete, r);
+        return 0;
     default:
         DPRINTF("Unknown SCSI command (%2.2x)\n", buf[0]);
         scsi_check_condition(r, SENSE_CODE(INVALID_OPCODE));
commit 353815aa6d706b1960fbeb75c4fd2bef7b23ed3e
Author: Dmitry Fleytman <dmitry.fleytman at ravellosystems.com>
Date:   Fri Jul 6 22:03:35 2012 -0700

    scsi-disk: let the user customize vendor and product name
    
    This patch adds two new properties vendor and product to SCSI disks.
    These options let the user customize the inquiry data returned by the
    disk.
    
    Signed-off-by: Yan Vugenfirer <yan at ravellosystems.com>
    Signed-off-by: Dmitry Fleytman <dmitry.fleytman at ravellosystems.com>
    [ Use vendor and product property names, avoid "if" statements. - PB ]
    Signed-off-by: Paolo Bonzini <pbonzini at redhat.com>

diff --git a/hw/scsi-disk.c b/hw/scsi-disk.c
index 8907197..788fe86 100644
--- a/hw/scsi-disk.c
+++ b/hw/scsi-disk.c
@@ -72,6 +72,8 @@ struct SCSIDiskState
     QEMUBH *bh;
     char *version;
     char *serial;
+    char *vendor;
+    char *product;
     bool tray_open;
     bool tray_locked;
 };
@@ -669,12 +671,10 @@ static int scsi_disk_emulate_inquiry(SCSIRequest *req, uint8_t *outbuf)
 
     outbuf[0] = s->qdev.type & 0x1f;
     outbuf[1] = (s->features & (1 << SCSI_DISK_F_REMOVABLE)) ? 0x80 : 0;
-    if (s->qdev.type == TYPE_ROM) {
-        memcpy(&outbuf[16], "QEMU CD-ROM     ", 16);
-    } else {
-        memcpy(&outbuf[16], "QEMU HARDDISK   ", 16);
-    }
-    memcpy(&outbuf[8], "QEMU    ", 8);
+
+    strpadcpy((char *) &outbuf[16], 16, s->product, ' ');
+    strpadcpy((char *) &outbuf[8], 8, s->vendor, ' ');
+
     memset(&outbuf[32], 0, 4);
     memcpy(&outbuf[32], s->version, MIN(4, strlen(s->version)));
     /*
@@ -1757,6 +1757,9 @@ static int scsi_initfn(SCSIDevice *dev)
     if (!s->version) {
         s->version = g_strdup(qemu_get_version());
     }
+    if (!s->vendor) {
+        s->vendor = g_strdup("QEMU");
+    }
 
     if (bdrv_is_sg(s->qdev.conf.bs)) {
         error_report("unwanted /dev/sg*");
@@ -1778,6 +1781,9 @@ static int scsi_hd_initfn(SCSIDevice *dev)
     SCSIDiskState *s = DO_UPCAST(SCSIDiskState, qdev, dev);
     s->qdev.blocksize = s->qdev.conf.logical_block_size;
     s->qdev.type = TYPE_DISK;
+    if (!s->product) {
+        s->product = g_strdup("QEMU HARDDISK");
+    }
     return scsi_initfn(&s->qdev);
 }
 
@@ -1787,6 +1793,9 @@ static int scsi_cd_initfn(SCSIDevice *dev)
     s->qdev.blocksize = 2048;
     s->qdev.type = TYPE_ROM;
     s->features |= 1 << SCSI_DISK_F_REMOVABLE;
+    if (!s->product) {
+        s->product = g_strdup("QEMU CD-ROM");
+    }
     return scsi_initfn(&s->qdev);
 }
 
@@ -1954,10 +1963,12 @@ static SCSIRequest *scsi_block_new_request(SCSIDevice *d, uint32_t tag,
 }
 #endif
 
-#define DEFINE_SCSI_DISK_PROPERTIES()                           \
-    DEFINE_BLOCK_PROPERTIES(SCSIDiskState, qdev.conf),          \
-    DEFINE_PROP_STRING("ver",  SCSIDiskState, version),         \
-    DEFINE_PROP_STRING("serial",  SCSIDiskState, serial)
+#define DEFINE_SCSI_DISK_PROPERTIES()                                \
+    DEFINE_BLOCK_PROPERTIES(SCSIDiskState, qdev.conf),               \
+    DEFINE_PROP_STRING("ver", SCSIDiskState, version),               \
+    DEFINE_PROP_STRING("serial", SCSIDiskState, serial),             \
+    DEFINE_PROP_STRING("vendor", SCSIDiskState, vendor),             \
+    DEFINE_PROP_STRING("product", SCSIDiskState, product)
 
 static Property scsi_hd_properties[] = {
     DEFINE_SCSI_DISK_PROPERTIES(),
commit 2a025ae454c361fb03aadf88e8a2f678b80b38e6
Author: Dmitry Fleytman <dmitry.fleytman at ravellosystems.com>
Date:   Mon Jul 9 08:50:43 2012 +0200

    cutils: add strpadcpy()
    
    Signed-off-by: Yan Vugenfirer <yan at ravellosystems.com>
    Signed-off-by: Dmitry Fleytman <dmitry.fleytman at ravellosystems.com>
    Signed-off-by: Paolo Bonzini <pbonzini at redhat.com>

diff --git a/cutils.c b/cutils.c
index e2bc1b8..9d4c570 100644
--- a/cutils.c
+++ b/cutils.c
@@ -28,6 +28,13 @@
 #include "qemu_socket.h"
 #include "iov.h"
 
+void strpadcpy(char *buf, int buf_size, const char *str, char pad)
+{
+    int len = qemu_strnlen(str, buf_size);
+    memcpy(buf, str, len);
+    memset(buf + len, pad, buf_size - len);
+}
+
 void pstrcpy(char *buf, int buf_size, const char *str)
 {
     int c;
diff --git a/qemu-common.h b/qemu-common.h
index 7c8dac8..d26ff39 100644
--- a/qemu-common.h
+++ b/qemu-common.h
@@ -138,6 +138,7 @@ int qemu_timedate_diff(struct tm *tm);
 
 /* cutils.c */
 void pstrcpy(char *buf, int buf_size, const char *str);
+void strpadcpy(char *buf, int buf_size, const char *str, char pad);
 char *pstrcat(char *buf, int buf_size, const char *s);
 int strstart(const char *str, const char *val, const char **ptr);
 int stristart(const char *str, const char *val, const char **ptr);
commit 038478370d5c7ed8f66fc9523bf3f60b8800fe86
Author: Paolo Bonzini <pbonzini at redhat.com>
Date:   Mon Jul 9 12:11:04 2012 +0200

    scsi-block: remove properties that are not relevant for passthrough
    
    scsi-block is a passthrough device and does not allow customization
    of vendor, product, removable, DPOFUA, block size or any other piece of
    information.  Thus, drop DEFINE_SCSI_DISK_PROPERTIES() from the
    list of qdev properties.
    
    Signed-off-by: Paolo Bonzini <pbonzini at redhat.com>

diff --git a/hw/scsi-disk.c b/hw/scsi-disk.c
index 525816c..8907197 100644
--- a/hw/scsi-disk.c
+++ b/hw/scsi-disk.c
@@ -2040,7 +2040,7 @@ static TypeInfo scsi_cd_info = {
 
 #ifdef __linux__
 static Property scsi_block_properties[] = {
-    DEFINE_SCSI_DISK_PROPERTIES(),
+    DEFINE_PROP_DRIVE("drive", SCSIDiskState, qdev.conf.bs),
     DEFINE_PROP_END_OF_LIST(),
 };
 
commit 8f6e699ddbcad32480fa64796ccf44cbaf5b4b91
Author: Paolo Bonzini <pbonzini at redhat.com>
Date:   Mon Jul 2 17:07:40 2012 +0200

    lsi: avoid redundant tests of s->current != NULL
    
    Simplify the code by checking against req->hba_private directly,
    and asserting that it is non-NULL before a command is completed
    or canceled.
    
    Signed-off-by: Paolo Bonzini <pbonzini at redhat.com>

diff --git a/hw/lsi53c895a.c b/hw/lsi53c895a.c
index 078ab6d..5f6cb17 100644
--- a/hw/lsi53c895a.c
+++ b/hw/lsi53c895a.c
@@ -706,7 +706,7 @@ static void lsi_command_complete(SCSIRequest *req, uint32_t status, size_t resid
         lsi_set_phase(s, PHASE_ST);
     }
 
-    if (s->current && req == s->current->req) {
+    if (req->hba_private == s->current) {
         req->hba_private = NULL;
         lsi_request_free(s, s->current);
         scsi_req_unref(req);
@@ -720,7 +720,8 @@ static void lsi_transfer_data(SCSIRequest *req, uint32_t len)
     LSIState *s = DO_UPCAST(LSIState, dev.qdev, req->bus->qbus.parent);
     int out;
 
-    if (s->waiting == 1 || !s->current || req->hba_private != s->current ||
+    assert(req->hba_private);
+    if (s->waiting == 1 || req->hba_private != s->current ||
         (lsi_irq_on_rsl(s) && !(s->scntl1 & LSI_SCNTL1_CON))) {
         if (lsi_queue_req(s, req, len)) {
             return;
commit d2a9998f8864e6f816262d9416d8b538186a8cad
Author: Paolo Bonzini <pbonzini at redhat.com>
Date:   Mon Jul 2 17:04:40 2012 +0200

    lsi: introduce lsi_request_free
    
    Split the common bits of lsi_request_cancelled and lsi_command_complete
    out to a new function.
    
    Signed-off-by: Paolo Bonzini <pbonzini at redhat.com>

diff --git a/hw/lsi53c895a.c b/hw/lsi53c895a.c
index f04cc68..078ab6d 100644
--- a/hw/lsi53c895a.c
+++ b/hw/lsi53c895a.c
@@ -641,23 +641,24 @@ static lsi_request *lsi_find_by_tag(LSIState *s, uint32_t tag)
     return NULL;
 }
 
+static void lsi_request_free(LSIState *s, lsi_request *p)
+{
+    if (p == s->current) {
+        s->current = NULL;
+    } else {
+        QTAILQ_REMOVE(&s->queue, p, next);
+    }
+    g_free(p);
+}
+
 static void lsi_request_cancelled(SCSIRequest *req)
 {
     LSIState *s = DO_UPCAST(LSIState, dev.qdev, req->bus->qbus.parent);
     lsi_request *p = req->hba_private;
 
-    if (s->current && req == s->current->req) {
-        scsi_req_unref(req);
-        g_free(s->current);
-        s->current = NULL;
-        return;
-    }
-
-    if (p) {
-        QTAILQ_REMOVE(&s->queue, p, next);
-        scsi_req_unref(req);
-        g_free(p);
-    }
+    req->hba_private = NULL;
+    lsi_request_free(s, p);
+    scsi_req_unref(req);
 }
 
 /* Record that data is available for a queued command.  Returns zero if
@@ -706,9 +707,9 @@ static void lsi_command_complete(SCSIRequest *req, uint32_t status, size_t resid
     }
 
     if (s->current && req == s->current->req) {
-        scsi_req_unref(s->current->req);
-        g_free(s->current);
-        s->current = NULL;
+        req->hba_private = NULL;
+        lsi_request_free(s, s->current);
+        scsi_req_unref(req);
     }
     lsi_resume_script(s);
 }
commit 2f0772c5b4818d4b2078be9dace0036d1030faee
Author: Paolo Bonzini <pbonzini at redhat.com>
Date:   Mon Jul 2 17:03:55 2012 +0200

    lsi: use qdev_reset_all
    
    By first resetting the devices, lsi_soft_reset will find the queue
    already cleared so there is no need to do that forcibly (which may also
    leak SCSIRequests, and/or worse due to dangling references to the
    lsi_request in the hba_private field).
    
    Signed-off-by: Paolo Bonzini <pbonzini at redhat.com>

diff --git a/hw/lsi53c895a.c b/hw/lsi53c895a.c
index 2fe141d..f04cc68 100644
--- a/hw/lsi53c895a.c
+++ b/hw/lsi53c895a.c
@@ -282,8 +282,6 @@ static inline int lsi_irq_on_rsl(LSIState *s)
 
 static void lsi_soft_reset(LSIState *s)
 {
-    lsi_request *p;
-
     DPRINTF("Reset\n");
     s->carry = 0;
 
@@ -350,15 +348,8 @@ static void lsi_soft_reset(LSIState *s)
     s->sbc = 0;
     s->csbc = 0;
     s->sbr = 0;
-    while (!QTAILQ_EMPTY(&s->queue)) {
-        p = QTAILQ_FIRST(&s->queue);
-        QTAILQ_REMOVE(&s->queue, p, next);
-        g_free(p);
-    }
-    if (s->current) {
-        g_free(s->current);
-        s->current = NULL;
-    }
+    assert(QTAILQ_EMPTY(&s->queue));
+    assert(!s->current);
 }
 
 static int lsi_dma_40bit(LSIState *s)
@@ -1738,7 +1729,7 @@ static void lsi_reg_writeb(LSIState *s, int offset, uint8_t val)
             lsi_execute_script(s);
         }
         if (val & LSI_ISTAT0_SRST) {
-            lsi_soft_reset(s);
+            qdev_reset_all(&s->dev.qdev);
         }
         break;
     case 0x16: /* MBOX0 */
commit e2b06058f7a0812729b95bcd4600238165323220
Author: Paolo Bonzini <pbonzini at redhat.com>
Date:   Thu Jul 12 15:02:29 2012 +0200

    megasas: fix misuse of scsi_req_abort
    
    scsi_req_abort is for terminating a command with a non-zero status.
    The ABORT task management function is invoked by scsi_req_cancel.
    In fact, ABORTED_COMMAND is a sense key, not a SAM status code.
    
    Signed-off-by: Paolo Bonzini <pbonzini at redhat.com>

diff --git a/hw/megasas.c b/hw/megasas.c
index c389ddf..9a0eab1 100644
--- a/hw/megasas.c
+++ b/hw/megasas.c
@@ -544,7 +544,7 @@ static void megasas_reset_frames(MegasasState *s)
 static void megasas_abort_command(MegasasCmd *cmd)
 {
     if (cmd->req) {
-        scsi_req_abort(cmd->req, ABORTED_COMMAND);
+        scsi_req_cancel(cmd->req);
         cmd->req = NULL;
     }
 }
commit 10d6530c64b4b4935fea3a4317e9c46d92a5e6db
Author: Hannes Reinecke <hare at suse.de>
Date:   Wed Jul 11 13:35:16 2012 +0200

    megasas: Replace trace_megasas_dcmd_dump_frame()
    
    trace_megasas_dcmd_dump_frame() takes 9 arguments, which is
    rather much. Plus the trace infrastructure doesn't support
    it.  As we can get the information via other means it's pointless
    to have it in the driver, so rather use some proper trace
    point here and remove the old one.
    
    Signed-off-by: Hannes Reinecke <hare at suse.de>
    Cc: Stefan Weil <sw at weilnetz.de>
    Signed-off-by: Paolo Bonzini <pbonzini at redhat.com>

diff --git a/hw/megasas.c b/hw/megasas.c
index b99fa97..c389ddf 100644
--- a/hw/megasas.c
+++ b/hw/megasas.c
@@ -1290,35 +1290,16 @@ static int megasas_cluster_reset_ld(MegasasState *s, MegasasCmd *cmd)
 
 static int megasas_dcmd_set_properties(MegasasState *s, MegasasCmd *cmd)
 {
-    uint8_t *dummy = g_malloc(cmd->iov_size);
-
-    dma_buf_write(dummy, cmd->iov_size, &cmd->qsg);
-
-    trace_megasas_dcmd_dump_frame(0,
-            dummy[0x00], dummy[0x01], dummy[0x02], dummy[0x03],
-            dummy[0x04], dummy[0x05], dummy[0x06], dummy[0x07]);
-    trace_megasas_dcmd_dump_frame(1,
-            dummy[0x08], dummy[0x09], dummy[0x0a], dummy[0x0b],
-            dummy[0x0c], dummy[0x0d], dummy[0x0e], dummy[0x0f]);
-    trace_megasas_dcmd_dump_frame(2,
-            dummy[0x10], dummy[0x11], dummy[0x12], dummy[0x13],
-            dummy[0x14], dummy[0x15], dummy[0x16], dummy[0x17]);
-    trace_megasas_dcmd_dump_frame(3,
-            dummy[0x18], dummy[0x19], dummy[0x1a], dummy[0x1b],
-            dummy[0x1c], dummy[0x1d], dummy[0x1e], dummy[0x1f]);
-    trace_megasas_dcmd_dump_frame(4,
-            dummy[0x20], dummy[0x21], dummy[0x22], dummy[0x23],
-            dummy[0x24], dummy[0x25], dummy[0x26], dummy[0x27]);
-    trace_megasas_dcmd_dump_frame(5,
-            dummy[0x28], dummy[0x29], dummy[0x2a], dummy[0x2b],
-            dummy[0x2c], dummy[0x2d], dummy[0x2e], dummy[0x2f]);
-    trace_megasas_dcmd_dump_frame(6,
-            dummy[0x30], dummy[0x31], dummy[0x32], dummy[0x33],
-            dummy[0x34], dummy[0x35], dummy[0x36], dummy[0x37]);
-    trace_megasas_dcmd_dump_frame(7,
-            dummy[0x38], dummy[0x39], dummy[0x3a], dummy[0x3b],
-            dummy[0x3c], dummy[0x3d], dummy[0x3e], dummy[0x3f]);
-    g_free(dummy);
+    struct mfi_ctrl_props info;
+    size_t dcmd_size = sizeof(info);
+
+    if (cmd->iov_size < dcmd_size) {
+        trace_megasas_dcmd_invalid_xfer_len(cmd->index, cmd->iov_size,
+                                            dcmd_size);
+        return MFI_STAT_INVALID_PARAMETER;
+    }
+    dma_buf_write((uint8_t *)&info, cmd->iov_size, &cmd->qsg);
+    trace_megasas_dcmd_unsupported(cmd->index, cmd->iov_size);
     return MFI_STAT_OK;
 }
 
diff --git a/trace-events b/trace-events
index 2a5f074..6fb5eb5 100644
--- a/trace-events
+++ b/trace-events
@@ -595,7 +595,7 @@ megasas_dcmd_ld_get_list(int cmd, int num, int max) "scmd %d: DCMD LD get list:
 megasas_dcmd_ld_get_info(int cmd, int ld_id) "scmd %d: DCMD LD get info for dev %d"
 megasas_dcmd_pd_get_info(int cmd, int pd_id) "scmd %d: DCMD PD get info for dev %d"
 megasas_dcmd_pd_list_query(int cmd, int flags) "scmd %d: DCMD PD list query flags %x"
-megasas_dcmd_dump_frame(int offset, char f0, char f1, char f2, char f3, char f4, char f5, char f6, char f7) "0x%x: %02x %02x %02x %02x %02x %02x %02x %02x"
+megasas_dcmd_unsupported(int cmd, unsigned long size) "scmd %d: set properties len %ld"
 megasas_abort_frame(int cmd, int abort_cmd) "scmd %d: aborting frame %x"
 megasas_abort_no_cmd(int cmd, uint64_t context) "scmd %d: no active command for frame context %" PRIx64 ""
 megasas_abort_invalid_context(int cmd, uint64_t context, int abort_cmd) "scmd %d: invalid frame context %" PRIx64 " for abort frame %x"
commit 39a5235cd7f367cce7be7b3f4d258452452e38e3
Author: Paolo Bonzini <pbonzini at redhat.com>
Date:   Wed Jul 18 14:57:15 2012 +0200

    qemu-nbd: add --cache and --aio options
    
    Add two options to tune the I/O implementation of qemu-nbd, matching
    the possibilities given by the QEMU -drive option.
    
    Signed-off-by: Paolo Bonzini <pbonzini at redhat.com>

diff --git a/qemu-nbd.c b/qemu-nbd.c
index 1c32290..1c1cf6a 100644
--- a/qemu-nbd.c
+++ b/qemu-nbd.c
@@ -33,7 +33,9 @@
 #include <libgen.h>
 #include <pthread.h>
 
-#define SOCKET_PATH    "/var/lock/qemu-nbd-%s"
+#define SOCKET_PATH         "/var/lock/qemu-nbd-%s"
+#define QEMU_NBD_OPT_CACHE  1
+#define QEMU_NBD_OPT_AIO    2
 
 static NBDExport *exp;
 static int verbose;
@@ -77,6 +79,10 @@ static void usage(const char *name)
 "  -r, --read-only      export read-only\n"
 "  -s, --snapshot       use snapshot file\n"
 "  -n, --nocache        disable host cache\n"
+"      --cache=MODE     set cache mode (none, writeback, ...)\n"
+#ifdef CONFIG_LINUX_AIO
+"      --aio=MODE       set AIO mode (native or threads)\n"
+#endif
 "\n"
 "Report bugs to <qemu-devel at nongnu.org>\n"
     , name, NBD_DEFAULT_PORT, "DEVICE");
@@ -306,6 +312,10 @@ int main(int argc, char **argv)
         { "disconnect", 0, NULL, 'd' },
         { "snapshot", 0, NULL, 's' },
         { "nocache", 0, NULL, 'n' },
+        { "cache", 1, NULL, QEMU_NBD_OPT_CACHE },
+#ifdef CONFIG_LINUX_AIO
+        { "aio", 1, NULL, QEMU_NBD_OPT_AIO },
+#endif
         { "shared", 1, NULL, 'e' },
         { "persistent", 0, NULL, 't' },
         { "verbose", 0, NULL, 'v' },
@@ -320,6 +330,10 @@ int main(int argc, char **argv)
     int ret;
     int fd;
     int persistent = 0;
+    bool seen_cache = false;
+#ifdef CONFIG_LINUX_AIO
+    bool seen_aio = false;
+#endif
     pthread_t client_thread;
 
     /* The client thread uses SIGTERM to interrupt the server.  A signal
@@ -336,8 +350,32 @@ int main(int argc, char **argv)
             flags |= BDRV_O_SNAPSHOT;
             break;
         case 'n':
-            flags |= BDRV_O_NOCACHE | BDRV_O_CACHE_WB;
+            optarg = (char *) "none";
+            /* fallthrough */
+        case QEMU_NBD_OPT_CACHE:
+            if (seen_cache) {
+                errx(EXIT_FAILURE, "-n and --cache can only be specified once");
+            }
+            seen_cache = true;
+            if (bdrv_parse_cache_flags(optarg, &flags) == -1) {
+                errx(EXIT_FAILURE, "Invalid cache mode `%s'", optarg);
+            }
             break;
+#ifdef CONFIG_LINUX_AIO
+        case QEMU_NBD_OPT_AIO:
+            if (seen_aio) {
+                errx(EXIT_FAILURE, "--aio can only be specified once");
+            }
+            seen_aio = true;
+            if (!strcmp(optarg, "native")) {
+                flags |= BDRV_O_NATIVE_AIO;
+            } else if (!strcmp(optarg, "threads")) {
+                /* this is the default */
+            } else {
+               errx(EXIT_FAILURE, "invalid aio mode `%s'", optarg);
+            }
+            break;
+#endif
         case 'b':
             bindto = optarg;
             break;
commit b033cd864042646dd3e17a23c7850c413bc360f4
Author: Paolo Bonzini <pbonzini at redhat.com>
Date:   Wed Jul 18 14:50:52 2012 +0200

    qemu-nbd: reorganize help message
    
    This patch separates qemu-nbd's options in logical groups, thus making
    the help message easier to read.
    
    Signed-off-by: Paolo Bonzini <pbonzini at redhat.com>

diff --git a/qemu-nbd.c b/qemu-nbd.c
index 5a0300e..1c32290 100644
--- a/qemu-nbd.c
+++ b/qemu-nbd.c
@@ -46,28 +46,39 @@ static int nb_fds;
 
 static void usage(const char *name)
 {
-    printf(
+    (printf) (
 "Usage: %s [OPTIONS] FILE\n"
 "QEMU Disk Network Block Device Server\n"
 "\n"
+"  -h, --help           display this help and exit\n"
+"  -V, --version        output version information and exit\n"
+"\n"
+"Connection properties:\n"
 "  -p, --port=PORT      port to listen on (default `%d')\n"
-"  -o, --offset=OFFSET  offset into the image\n"
 "  -b, --bind=IFACE     interface to bind to (default `0.0.0.0')\n"
 "  -k, --socket=PATH    path to the unix socket\n"
 "                       (default '"SOCKET_PATH"')\n"
-"  -r, --read-only      export read-only\n"
-"  -P, --partition=NUM  only expose partition NUM\n"
-"  -s, --snapshot       use snapshot file\n"
-"  -n, --nocache        disable host cache\n"
-"  -c, --connect=DEV    connect FILE to the local NBD device DEV\n"
-"  -d, --disconnect     disconnect the specified device\n"
 "  -e, --shared=NUM     device can be shared by NUM clients (default '1')\n"
 "  -t, --persistent     don't exit on the last connection\n"
 "  -v, --verbose        display extra debugging information\n"
-"  -h, --help           display this help and exit\n"
-"  -V, --version        output version information and exit\n"
 "\n"
-"Report bugs to <anthony at codemonkey.ws>\n"
+"Exposing part of the image:\n"
+"  -o, --offset=OFFSET  offset into the image\n"
+"  -P, --partition=NUM  only expose partition NUM\n"
+"\n"
+#ifdef __linux__
+"Kernel NBD client support:\n"
+"  -c, --connect=DEV    connect FILE to the local NBD device DEV\n"
+"  -d, --disconnect     disconnect the specified device\n"
+"\n"
+#endif
+"\n"
+"Block device options:\n"
+"  -r, --read-only      export read-only\n"
+"  -s, --snapshot       use snapshot file\n"
+"  -n, --nocache        disable host cache\n"
+"\n"
+"Report bugs to <qemu-devel at nongnu.org>\n"
     , name, NBD_DEFAULT_PORT, "DEVICE");
 }
 
commit a21143486b9c6d7a50b7b62877c02b3c686943cb
Merge: ef6bbdf... 1a0c095...
Author: Anthony Liguori <aliguori at us.ibm.com>
Date:   Mon Jul 23 13:15:34 2012 -0500

    Merge remote-tracking branch 'stefanha/net' into staging
    
    * stefanha/net:
      remove unused QemuOpts parameter from net init functions
      convert net_init_bridge() to NetClientOptions
      convert net_init_tap() to NetClientOptions
      convert net_init_vde() to NetClientOptions
      convert net_init_socket() to NetClientOptions
      convert net_init_slirp() to NetClientOptions
      convert net_init_dump() to NetClientOptions
      convert net_init_nic() to NetClientOptions
      convert net_client_init() to OptsVisitor
      hw, net: "net_client_type" -> "NetClientOptionsKind" (qapi-generated)
      qapi schema: add Netdev types
      qapi schema: remove trailing whitespace
      qapi: introduce OptsVisitor
      expose QemuOpt and QemuOpts struct definitions to interested parties
      qapi: introduce "size" type
      qapi: generate C types for fixed-width integers
      qapi: add test case for deallocating traversal of incomplete structure
      qapi: fix error propagation
      MAINTAINERS: Replace net maintainer Mark McLoughlin with Stefan Hajnoczi

commit ef6bbdf9e5eb6da5cbdea1bf55e08709c6e181d5
Merge: 400006c... 43ffe61...
Author: Anthony Liguori <aliguori at us.ibm.com>
Date:   Mon Jul 23 13:15:34 2012 -0500

    Merge remote-tracking branch 'stefanha/trivial-patches' into staging
    
    * stefanha/trivial-patches:
      Fix some more Qemus in documentation and help text
      qdev: Fix Open Firmware comment
      cpus.c: Make all_cpu_threads_idle() static
      Use macro QEMU_PACKED for new packed structures
      Recognize PCID feature
      powerpc pci: fixed packing of ranges[]

commit 400006c27622d54ef588e1a9bd5a005d5fc9be5b
Merge: 903f650... ffbbe7d...
Author: Anthony Liguori <aliguori at us.ibm.com>
Date:   Mon Jul 23 13:15:34 2012 -0500

    Merge remote-tracking branch 'pmaydell/arm-devs.for-upstream' into staging
    
    * pmaydell/arm-devs.for-upstream:
      exynos4210: add Exynos4210 i2c implementation
      hw/exynos4210_rtc.c: remove unnecessary code
      hw/exynos4210_rtc.c: Fix calculating for value of year
      hw/vexpress.c: Allow >4GB of RAM for Cortex-A15 daughterboard
      hw/arm_boot.c: Support DTBs which use 64 bit addresses
      device_tree: Add support for reading device tree properties
      hw/arm_boot.c: Check for RAM sizes exceeding ATAGS capacity
      hw/arm_boot.c: Consistently use ram_size from arm_boot_info struct
      hw/arm_boot.c: Make ram_size a uint64_t
      hw/pl011.c: Avoid crash on read when no chr backend present

commit 903f650b0c77827f8d92b35f61419401d648df1e
Merge: 61dc008... 90a147a...
Author: Anthony Liguori <aliguori at us.ibm.com>
Date:   Mon Jul 23 13:15:34 2012 -0500

    Merge remote-tracking branch 'stefanha/tracing' into staging
    
    * stefanha/tracing:
      Update simpletrace.py for new log format
      Simpletrace v2: Support multiple arguments, strings.
      monitor: remove unused do_info_trace
      trace: added ability to comment out events in the list

commit 6c779f22a93cc6e4565b940ef616e3efc5b50ba5
Author: Orit Wasserman <owasserm at redhat.com>
Date:   Tue Jul 10 12:37:13 2012 +0300

    Change ram_save_block to return -1 if there are no more changes
    
    It will return 0 if the page is unmodifed.
    
    Signed-off-by: Orit Wasserman <owasserm at redhat.com>

diff --git a/arch_init.c b/arch_init.c
index 8cbf8f4..78cdf50 100644
--- a/arch_init.c
+++ b/arch_init.c
@@ -184,11 +184,19 @@ static void save_block_hdr(QEMUFile *f, RAMBlock *block, ram_addr_t offset,
 static RAMBlock *last_block;
 static ram_addr_t last_offset;
 
+/*
+ * ram_save_block: Writes a page of memory to the stream f
+ *
+ * Returns:  0: if the page hasn't changed
+ *          -1: if there are no more dirty pages
+ *           n: the amount of bytes written in other case
+ */
+
 static int ram_save_block(QEMUFile *f)
 {
     RAMBlock *block = last_block;
     ram_addr_t offset = last_offset;
-    int bytes_sent = 0;
+    int bytes_sent = -1;
     MemoryRegion *mr;
 
     if (!block)
@@ -354,10 +362,11 @@ static int ram_save_iterate(QEMUFile *f, void *opaque)
         int bytes_sent;
 
         bytes_sent = ram_save_block(f);
-        bytes_transferred += bytes_sent;
-        if (bytes_sent == 0) { /* no more blocks */
+        /* no more blocks to sent */
+        if (bytes_sent < 0) {
             break;
         }
+        bytes_transferred += bytes_sent;
         /* we want to check in the 1st loop, just in case it was the 1st time
            and we had to sync the dirty bitmap.
            qemu_get_clock_ns() is a bit expensive, so we only check each some
@@ -405,14 +414,19 @@ static int ram_save_iterate(QEMUFile *f, void *opaque)
 
 static int ram_save_complete(QEMUFile *f, void *opaque)
 {
-    int bytes_sent;
-
     memory_global_sync_dirty_bitmap(get_system_memory());
 
     /* try transferring iterative blocks of memory */
 
     /* flush all remaining blocks regardless of rate limiting */
-    while ((bytes_sent = ram_save_block(f)) != 0) {
+    while (true) {
+        int bytes_sent;
+
+        bytes_sent = ram_save_block(f);
+        /* no more blocks to sent */
+        if (bytes_sent < 0) {
+            break;
+        }
         bytes_transferred += bytes_sent;
     }
     memory_global_dirty_log_stop();
commit 1a0c09583df097d62b0580f9073ba45c9d18351a
Author: Laszlo Ersek <lersek at redhat.com>
Date:   Tue Jul 17 16:17:21 2012 +0200

    remove unused QemuOpts parameter from net init functions
    
    v1->v2:
    - unchanged
    
    v2->v3:
    - keep "qemu-option.h" included in "net/slirp.h"
    
    Signed-off-by: Laszlo Ersek <lersek at redhat.com>
    Signed-off-by: Stefan Hajnoczi <stefanha at linux.vnet.ibm.com>

diff --git a/net.c b/net.c
index a62e902..dbca77b 100644
--- a/net.c
+++ b/net.c
@@ -748,8 +748,8 @@ int net_handle_fd_param(Monitor *mon, const char *param)
     return fd;
 }
 
-static int net_init_nic(QemuOpts *old_opts, const NetClientOptions *opts,
-                        const char *name, VLANState *vlan)
+static int net_init_nic(const NetClientOptions *opts, const char *name,
+                        VLANState *vlan)
 {
     int idx;
     NICInfo *nd;
@@ -813,8 +813,7 @@ static int net_init_nic(QemuOpts *old_opts, const NetClientOptions *opts,
 
 
 static int (* const net_client_init_fun[NET_CLIENT_OPTIONS_KIND_MAX])(
-    QemuOpts *old_opts,
-    const NetClientOptions *new_opts,
+    const NetClientOptions *opts,
     const char *name,
     VLANState *vlan) = {
         [NET_CLIENT_OPTIONS_KIND_NIC]    = net_init_nic,
@@ -833,8 +832,7 @@ static int (* const net_client_init_fun[NET_CLIENT_OPTIONS_KIND_MAX])(
 };
 
 
-static int net_client_init1(const void *object, int is_netdev,
-                            QemuOpts *old_opts, Error **errp)
+static int net_client_init1(const void *object, int is_netdev, Error **errp)
 {
     union {
         const Netdev    *netdev;
@@ -885,7 +883,7 @@ static int net_client_init1(const void *object, int is_netdev,
             vlan = qemu_find_vlan(u.net->has_vlan ? u.net->vlan : 0, true);
         }
 
-        if (net_client_init_fun[opts->kind](old_opts, opts, name, vlan) < 0) {
+        if (net_client_init_fun[opts->kind](opts, name, vlan) < 0) {
             /* TODO push error reporting into init() methods */
             error_set(errp, QERR_DEVICE_INIT_FAILED,
                       NetClientOptionsKind_lookup[opts->kind]);
@@ -920,7 +918,7 @@ int net_client_init(QemuOpts *opts, int is_netdev, Error **errp)
     }
 
     if (!err) {
-        ret = net_client_init1(object, is_netdev, opts, &err);
+        ret = net_client_init1(object, is_netdev, &err);
     }
 
     if (object) {
diff --git a/net/dump.c b/net/dump.c
index f3d2fa9..b575430 100644
--- a/net/dump.c
+++ b/net/dump.c
@@ -144,8 +144,8 @@ static int net_dump_init(VLANState *vlan, const char *device,
     return 0;
 }
 
-int net_init_dump(QemuOpts *old_opts, const NetClientOptions *opts,
-                  const char *name, VLANState *vlan)
+int net_init_dump(const NetClientOptions *opts, const char *name,
+                  VLANState *vlan)
 {
     int len;
     const char *file;
diff --git a/net/dump.h b/net/dump.h
index 85ac00b..0fa2dd7 100644
--- a/net/dump.h
+++ b/net/dump.h
@@ -25,10 +25,9 @@
 #define QEMU_NET_DUMP_H
 
 #include "net.h"
-#include "qemu-common.h"
 #include "qapi-types.h"
 
-int net_init_dump(QemuOpts *opts, const NetClientOptions *new_opts,
-                  const char *name, VLANState *vlan);
+int net_init_dump(const NetClientOptions *opts, const char *name,
+                  VLANState *vlan);
 
 #endif /* QEMU_NET_DUMP_H */
diff --git a/net/slirp.c b/net/slirp.c
index 44b059f..5c2e6b2 100644
--- a/net/slirp.c
+++ b/net/slirp.c
@@ -702,8 +702,8 @@ net_init_slirp_configs(const StringList *fwd, int flags)
     }
 }
 
-int net_init_slirp(QemuOpts *old_opts, const NetClientOptions *opts,
-                   const char *name, VLANState *vlan)
+int net_init_slirp(const NetClientOptions *opts, const char *name,
+                   VLANState *vlan)
 {
     struct slirp_config_str *config;
     char *vnet;
diff --git a/net/slirp.h b/net/slirp.h
index ef13a65..e2c71ee 100644
--- a/net/slirp.h
+++ b/net/slirp.h
@@ -31,8 +31,8 @@
 
 #ifdef CONFIG_SLIRP
 
-int net_init_slirp(QemuOpts *opts, const NetClientOptions *new_opts,
-                   const char *name, VLANState *vlan);
+int net_init_slirp(const NetClientOptions *opts, const char *name,
+                   VLANState *vlan);
 
 void net_slirp_hostfwd_add(Monitor *mon, const QDict *qdict);
 void net_slirp_hostfwd_remove(Monitor *mon, const QDict *qdict);
diff --git a/net/socket.c b/net/socket.c
index e3cba20..600c287 100644
--- a/net/socket.c
+++ b/net/socket.c
@@ -586,8 +586,8 @@ static int net_socket_udp_init(VLANState *vlan,
     return 0;
 }
 
-int net_init_socket(QemuOpts *old_opts, const NetClientOptions *opts,
-                    const char *name, VLANState *vlan)
+int net_init_socket(const NetClientOptions *opts, const char *name,
+                    VLANState *vlan)
 {
     const NetdevSocketOptions *sock;
 
diff --git a/net/socket.h b/net/socket.h
index e44d26e..c4809ad 100644
--- a/net/socket.h
+++ b/net/socket.h
@@ -25,10 +25,9 @@
 #define QEMU_NET_SOCKET_H
 
 #include "net.h"
-#include "qemu-common.h"
 #include "qapi-types.h"
 
-int net_init_socket(QemuOpts *opts, const NetClientOptions *new_opts,
-                    const char *name, VLANState *vlan);
+int net_init_socket(const NetClientOptions *opts, const char *name,
+                    VLANState *vlan);
 
 #endif /* QEMU_NET_SOCKET_H */
diff --git a/net/tap-win32.c b/net/tap-win32.c
index b6099cd..2328072 100644
--- a/net/tap-win32.c
+++ b/net/tap-win32.c
@@ -699,8 +699,8 @@ static int tap_win32_init(VLANState *vlan, const char *model,
     return 0;
 }
 
-int net_init_tap(QemuOpts *old_opts, const NetClientOptions *opts,
-                 const char *name, VLANState *vlan)
+int net_init_tap(const NetClientOptions *opts, const char *name,
+                 VLANState *vlan)
 {
     const NetdevTapOptions *tap;
 
diff --git a/net/tap.c b/net/tap.c
index d2736ea..7206227 100644
--- a/net/tap.c
+++ b/net/tap.c
@@ -513,8 +513,8 @@ static int net_bridge_run_helper(const char *helper, const char *bridge)
     return -1;
 }
 
-int net_init_bridge(QemuOpts *old_opts, const NetClientOptions *opts,
-                    const char *name, VLANState *vlan)
+int net_init_bridge(const NetClientOptions *opts, const char *name,
+                    VLANState *vlan)
 {
     const NetdevBridgeOptions *bridge;
     const char *helper, *br;
@@ -586,8 +586,8 @@ static int net_tap_init(const NetdevTapOptions *tap, int *vnet_hdr,
     return fd;
 }
 
-int net_init_tap(QemuOpts *old_opts, const NetClientOptions *opts,
-                 const char *name, VLANState *vlan)
+int net_init_tap(const NetClientOptions *opts, const char *name,
+                 VLANState *vlan)
 {
     const NetdevTapOptions *tap;
 
diff --git a/net/tap.h b/net/tap.h
index f092129..19dea58 100644
--- a/net/tap.h
+++ b/net/tap.h
@@ -27,14 +27,13 @@
 #define QEMU_NET_TAP_H
 
 #include "qemu-common.h"
-#include "qemu-option.h"
 #include "qapi-types.h"
 
 #define DEFAULT_NETWORK_SCRIPT "/etc/qemu-ifup"
 #define DEFAULT_NETWORK_DOWN_SCRIPT "/etc/qemu-ifdown"
 
-int net_init_tap(QemuOpts *opts, const NetClientOptions *new_opts,
-                 const char *name, VLANState *vlan);
+int net_init_tap(const NetClientOptions *opts, const char *name,
+                 VLANState *vlan);
 
 int tap_open(char *ifname, int ifname_size, int *vnet_hdr, int vnet_hdr_required);
 
@@ -59,7 +58,7 @@ int tap_get_fd(VLANClientState *vc);
 struct vhost_net;
 struct vhost_net *tap_get_vhost_net(VLANClientState *vc);
 
-int net_init_bridge(QemuOpts *opts, const NetClientOptions *new_opts,
-                    const char *name, VLANState *vlan);
+int net_init_bridge(const NetClientOptions *opts, const char *name,
+                    VLANState *vlan);
 
 #endif /* QEMU_NET_TAP_H */
diff --git a/net/vde.c b/net/vde.c
index 703888c..ee19f5c 100644
--- a/net/vde.c
+++ b/net/vde.c
@@ -110,8 +110,8 @@ static int net_vde_init(VLANState *vlan, const char *model,
     return 0;
 }
 
-int net_init_vde(QemuOpts *old_opts, const NetClientOptions *opts,
-                 const char *name, VLANState *vlan)
+int net_init_vde(const NetClientOptions *opts, const char *name,
+                 VLANState *vlan)
 {
     const NetdevVdeOptions *vde;
 
diff --git a/net/vde.h b/net/vde.h
index 5fc17f9..ad502ef 100644
--- a/net/vde.h
+++ b/net/vde.h
@@ -25,13 +25,12 @@
 #define QEMU_NET_VDE_H
 
 #include "qemu-common.h"
-#include "qemu-option.h"
 #include "qapi-types.h"
 
 #ifdef CONFIG_VDE
 
-int net_init_vde(QemuOpts *opts, const NetClientOptions *new_opts,
-                 const char *name, VLANState *vlan);
+int net_init_vde(const NetClientOptions *opts, const char *name,
+                 VLANState *vlan);
 
 #endif /* CONFIG_VDE */
 
commit f79b51b081e48fb307a9438eb0e7326806bc19d3
Author: Laszlo Ersek <lersek at redhat.com>
Date:   Tue Jul 17 16:17:20 2012 +0200

    convert net_init_bridge() to NetClientOptions
    
    Signed-off-by: Laszlo Ersek <lersek at redhat.com>
    Signed-off-by: Stefan Hajnoczi <stefanha at linux.vnet.ibm.com>

diff --git a/net/tap.c b/net/tap.c
index c5563c0..d2736ea 100644
--- a/net/tap.c
+++ b/net/tap.c
@@ -513,21 +513,22 @@ static int net_bridge_run_helper(const char *helper, const char *bridge)
     return -1;
 }
 
-int net_init_bridge(QemuOpts *opts, const NetClientOptions *new_opts,
+int net_init_bridge(QemuOpts *old_opts, const NetClientOptions *opts,
                     const char *name, VLANState *vlan)
 {
+    const NetdevBridgeOptions *bridge;
+    const char *helper, *br;
+
     TAPState *s;
     int fd, vnet_hdr;
 
-    if (!qemu_opt_get(opts, "br")) {
-        qemu_opt_set(opts, "br", DEFAULT_BRIDGE_INTERFACE);
-    }
-    if (!qemu_opt_get(opts, "helper")) {
-        qemu_opt_set(opts, "helper", DEFAULT_BRIDGE_HELPER);
-    }
+    assert(opts->kind == NET_CLIENT_OPTIONS_KIND_BRIDGE);
+    bridge = opts->bridge;
+
+    helper = bridge->has_helper ? bridge->helper : DEFAULT_BRIDGE_HELPER;
+    br     = bridge->has_br     ? bridge->br     : DEFAULT_BRIDGE_INTERFACE;
 
-    fd = net_bridge_run_helper(qemu_opt_get(opts, "helper"),
-                               qemu_opt_get(opts, "br"));
+    fd = net_bridge_run_helper(helper, br);
     if (fd == -1) {
         return -1;
     }
@@ -542,8 +543,8 @@ int net_init_bridge(QemuOpts *opts, const NetClientOptions *new_opts,
         return -1;
     }
 
-    snprintf(s->nc.info_str, sizeof(s->nc.info_str), "helper=%s,br=%s",
-             qemu_opt_get(opts, "helper"), qemu_opt_get(opts, "br"));
+    snprintf(s->nc.info_str, sizeof(s->nc.info_str), "helper=%s,br=%s", helper,
+             br);
 
     return 0;
 }
commit 08c573a8d14893518df412c68541aae5b7091982
Author: Laszlo Ersek <lersek at redhat.com>
Date:   Tue Jul 17 16:17:19 2012 +0200

    convert net_init_tap() to NetClientOptions
    
    Signed-off-by: Laszlo Ersek <lersek at redhat.com>
    Signed-off-by: Stefan Hajnoczi <stefanha at linux.vnet.ibm.com>

diff --git a/net/tap-aix.c b/net/tap-aix.c
index e19aaba..f27c177 100644
--- a/net/tap-aix.c
+++ b/net/tap-aix.c
@@ -31,7 +31,7 @@ int tap_open(char *ifname, int ifname_size, int *vnet_hdr, int vnet_hdr_required
     return -1;
 }
 
-int tap_set_sndbuf(int fd, QemuOpts *opts)
+int tap_set_sndbuf(int fd, const NetdevTapOptions *tap)
 {
     return 0;
 }
diff --git a/net/tap-bsd.c b/net/tap-bsd.c
index 937a94b..a3b717d 100644
--- a/net/tap-bsd.c
+++ b/net/tap-bsd.c
@@ -117,7 +117,7 @@ int tap_open(char *ifname, int ifname_size, int *vnet_hdr, int vnet_hdr_required
     return fd;
 }
 
-int tap_set_sndbuf(int fd, QemuOpts *opts)
+int tap_set_sndbuf(int fd, const NetdevTapOptions *tap)
 {
     return 0;
 }
diff --git a/net/tap-haiku.c b/net/tap-haiku.c
index 91dda8e..34739d1 100644
--- a/net/tap-haiku.c
+++ b/net/tap-haiku.c
@@ -31,7 +31,7 @@ int tap_open(char *ifname, int ifname_size, int *vnet_hdr, int vnet_hdr_required
     return -1;
 }
 
-int tap_set_sndbuf(int fd, QemuOpts *opts)
+int tap_set_sndbuf(int fd, const NetdevTapOptions *tap)
 {
     return 0;
 }
diff --git a/net/tap-linux.c b/net/tap-linux.c
index 41d581b..c6521be 100644
--- a/net/tap-linux.c
+++ b/net/tap-linux.c
@@ -98,16 +98,19 @@ int tap_open(char *ifname, int ifname_size, int *vnet_hdr, int vnet_hdr_required
  */
 #define TAP_DEFAULT_SNDBUF 0
 
-int tap_set_sndbuf(int fd, QemuOpts *opts)
+int tap_set_sndbuf(int fd, const NetdevTapOptions *tap)
 {
     int sndbuf;
 
-    sndbuf = qemu_opt_get_size(opts, "sndbuf", TAP_DEFAULT_SNDBUF);
+    sndbuf = !tap->has_sndbuf       ? TAP_DEFAULT_SNDBUF :
+             tap->sndbuf > INT_MAX  ? INT_MAX :
+             tap->sndbuf;
+
     if (!sndbuf) {
         sndbuf = INT_MAX;
     }
 
-    if (ioctl(fd, TUNSETSNDBUF, &sndbuf) == -1 && qemu_opt_get(opts, "sndbuf")) {
+    if (ioctl(fd, TUNSETSNDBUF, &sndbuf) == -1 && tap->has_sndbuf) {
         error_report("TUNSETSNDBUF ioctl failed: %s", strerror(errno));
         return -1;
     }
diff --git a/net/tap-solaris.c b/net/tap-solaris.c
index cf76463..5d6ac42 100644
--- a/net/tap-solaris.c
+++ b/net/tap-solaris.c
@@ -197,7 +197,7 @@ int tap_open(char *ifname, int ifname_size, int *vnet_hdr, int vnet_hdr_required
     return fd;
 }
 
-int tap_set_sndbuf(int fd, QemuOpts *opts)
+int tap_set_sndbuf(int fd, const NetdevTapOptions *tap)
 {
     return 0;
 }
diff --git a/net/tap-win32.c b/net/tap-win32.c
index b738f45..b6099cd 100644
--- a/net/tap-win32.c
+++ b/net/tap-win32.c
@@ -699,19 +699,20 @@ static int tap_win32_init(VLANState *vlan, const char *model,
     return 0;
 }
 
-int net_init_tap(QemuOpts *opts, const NetClientOptions *new_opts,
+int net_init_tap(QemuOpts *old_opts, const NetClientOptions *opts,
                  const char *name, VLANState *vlan)
 {
-    const char *ifname;
+    const NetdevTapOptions *tap;
 
-    ifname = qemu_opt_get(opts, "ifname");
+    assert(opts->kind == NET_CLIENT_OPTIONS_KIND_TAP);
+    tap = opts->tap;
 
-    if (!ifname) {
+    if (!tap->has_ifname) {
         error_report("tap: no interface name");
         return -1;
     }
 
-    if (tap_win32_init(vlan, "tap", name, ifname) == -1) {
+    if (tap_win32_init(vlan, "tap", name, tap->ifname) == -1) {
         return -1;
     }
 
diff --git a/net/tap.c b/net/tap.c
index 0fc856c..c5563c0 100644
--- a/net/tap.c
+++ b/net/tap.c
@@ -548,29 +548,32 @@ int net_init_bridge(QemuOpts *opts, const NetClientOptions *new_opts,
     return 0;
 }
 
-static int net_tap_init(QemuOpts *opts, int *vnet_hdr)
+static int net_tap_init(const NetdevTapOptions *tap, int *vnet_hdr,
+                        const char *setup_script, char *ifname,
+                        size_t ifname_sz)
 {
     int fd, vnet_hdr_required;
-    char ifname[128] = {0,};
-    const char *setup_script;
 
-    if (qemu_opt_get(opts, "ifname")) {
-        pstrcpy(ifname, sizeof(ifname), qemu_opt_get(opts, "ifname"));
+    if (tap->has_ifname) {
+        pstrcpy(ifname, ifname_sz, tap->ifname);
+    } else {
+        assert(ifname_sz > 0);
+        ifname[0] = '\0';
     }
 
-    *vnet_hdr = qemu_opt_get_bool(opts, "vnet_hdr", 1);
-    if (qemu_opt_get(opts, "vnet_hdr")) {
+    if (tap->has_vnet_hdr) {
+        *vnet_hdr = tap->vnet_hdr;
         vnet_hdr_required = *vnet_hdr;
     } else {
+        *vnet_hdr = 1;
         vnet_hdr_required = 0;
     }
 
-    TFR(fd = tap_open(ifname, sizeof(ifname), vnet_hdr, vnet_hdr_required));
+    TFR(fd = tap_open(ifname, ifname_sz, vnet_hdr, vnet_hdr_required));
     if (fd < 0) {
         return -1;
     }
 
-    setup_script = qemu_opt_get(opts, "script");
     if (setup_script &&
         setup_script[0] != '\0' &&
         strcmp(setup_script, "no") != 0 &&
@@ -579,30 +582,34 @@ static int net_tap_init(QemuOpts *opts, int *vnet_hdr)
         return -1;
     }
 
-    qemu_opt_set(opts, "ifname", ifname);
-
     return fd;
 }
 
-int net_init_tap(QemuOpts *opts, const NetClientOptions *new_opts,
+int net_init_tap(QemuOpts *old_opts, const NetClientOptions *opts,
                  const char *name, VLANState *vlan)
 {
-    TAPState *s;
+    const NetdevTapOptions *tap;
+
     int fd, vnet_hdr = 0;
     const char *model;
+    TAPState *s;
+
+    /* for the no-fd, no-helper case */
+    const char *script = NULL; /* suppress wrong "uninit'd use" gcc warning */
+    char ifname[128];
+
+    assert(opts->kind == NET_CLIENT_OPTIONS_KIND_TAP);
+    tap = opts->tap;
 
-    if (qemu_opt_get(opts, "fd")) {
-        if (qemu_opt_get(opts, "ifname") ||
-            qemu_opt_get(opts, "script") ||
-            qemu_opt_get(opts, "downscript") ||
-            qemu_opt_get(opts, "vnet_hdr") ||
-            qemu_opt_get(opts, "helper")) {
+    if (tap->has_fd) {
+        if (tap->has_ifname || tap->has_script || tap->has_downscript ||
+            tap->has_vnet_hdr || tap->has_helper) {
             error_report("ifname=, script=, downscript=, vnet_hdr=, "
                          "and helper= are invalid with fd=");
             return -1;
         }
 
-        fd = net_handle_fd_param(cur_mon, qemu_opt_get(opts, "fd"));
+        fd = net_handle_fd_param(cur_mon, tap->fd);
         if (fd == -1) {
             return -1;
         }
@@ -613,18 +620,15 @@ int net_init_tap(QemuOpts *opts, const NetClientOptions *new_opts,
 
         model = "tap";
 
-    } else if (qemu_opt_get(opts, "helper")) {
-        if (qemu_opt_get(opts, "ifname") ||
-            qemu_opt_get(opts, "script") ||
-            qemu_opt_get(opts, "downscript") ||
-            qemu_opt_get(opts, "vnet_hdr")) {
+    } else if (tap->has_helper) {
+        if (tap->has_ifname || tap->has_script || tap->has_downscript ||
+            tap->has_vnet_hdr) {
             error_report("ifname=, script=, downscript=, and vnet_hdr= "
                          "are invalid with helper=");
             return -1;
         }
 
-        fd = net_bridge_run_helper(qemu_opt_get(opts, "helper"),
-                                   DEFAULT_BRIDGE_INTERFACE);
+        fd = net_bridge_run_helper(tap->helper, DEFAULT_BRIDGE_INTERFACE);
         if (fd == -1) {
             return -1;
         }
@@ -636,15 +640,8 @@ int net_init_tap(QemuOpts *opts, const NetClientOptions *new_opts,
         model = "bridge";
 
     } else {
-        if (!qemu_opt_get(opts, "script")) {
-            qemu_opt_set(opts, "script", DEFAULT_NETWORK_SCRIPT);
-        }
-
-        if (!qemu_opt_get(opts, "downscript")) {
-            qemu_opt_set(opts, "downscript", DEFAULT_NETWORK_DOWN_SCRIPT);
-        }
-
-        fd = net_tap_init(opts, &vnet_hdr);
+        script = tap->has_script ? tap->script : DEFAULT_NETWORK_SCRIPT;
+        fd = net_tap_init(tap, &vnet_hdr, script, ifname, sizeof ifname);
         if (fd == -1) {
             return -1;
         }
@@ -658,25 +655,24 @@ int net_init_tap(QemuOpts *opts, const NetClientOptions *new_opts,
         return -1;
     }
 
-    if (tap_set_sndbuf(s->fd, opts) < 0) {
+    if (tap_set_sndbuf(s->fd, tap) < 0) {
         return -1;
     }
 
-    if (qemu_opt_get(opts, "fd")) {
+    if (tap->has_fd) {
         snprintf(s->nc.info_str, sizeof(s->nc.info_str), "fd=%d", fd);
-    } else if (qemu_opt_get(opts, "helper")) {
-        snprintf(s->nc.info_str, sizeof(s->nc.info_str),
-                 "helper=%s", qemu_opt_get(opts, "helper"));
+    } else if (tap->has_helper) {
+        snprintf(s->nc.info_str, sizeof(s->nc.info_str), "helper=%s",
+                 tap->helper);
     } else {
-        const char *ifname, *script, *downscript;
+        const char *downscript;
 
-        ifname     = qemu_opt_get(opts, "ifname");
-        script     = qemu_opt_get(opts, "script");
-        downscript = qemu_opt_get(opts, "downscript");
+        downscript = tap->has_downscript ? tap->downscript :
+                                           DEFAULT_NETWORK_DOWN_SCRIPT;
 
         snprintf(s->nc.info_str, sizeof(s->nc.info_str),
-                 "ifname=%s,script=%s,downscript=%s",
-                 ifname, script, downscript);
+                 "ifname=%s,script=%s,downscript=%s", ifname, script,
+                 downscript);
 
         if (strcmp(downscript, "no") != 0) {
             snprintf(s->down_script, sizeof(s->down_script), "%s", downscript);
@@ -684,25 +680,26 @@ int net_init_tap(QemuOpts *opts, const NetClientOptions *new_opts,
         }
     }
 
-    if (qemu_opt_get_bool(opts, "vhost", !!qemu_opt_get(opts, "vhostfd") ||
-                          qemu_opt_get_bool(opts, "vhostforce", false))) {
-        int vhostfd, r;
-        bool force = qemu_opt_get_bool(opts, "vhostforce", false);
-        if (qemu_opt_get(opts, "vhostfd")) {
-            r = net_handle_fd_param(cur_mon, qemu_opt_get(opts, "vhostfd"));
-            if (r == -1) {
+    if (tap->has_vhost ? tap->vhost :
+        tap->has_vhostfd || (tap->has_vhostforce && tap->vhostforce)) {
+        int vhostfd;
+
+        if (tap->has_vhostfd) {
+            vhostfd = net_handle_fd_param(cur_mon, tap->vhostfd);
+            if (vhostfd == -1) {
                 return -1;
             }
-            vhostfd = r;
         } else {
             vhostfd = -1;
         }
-        s->vhost_net = vhost_net_init(&s->nc, vhostfd, force);
+
+        s->vhost_net = vhost_net_init(&s->nc, vhostfd,
+                                      tap->has_vhostforce && tap->vhostforce);
         if (!s->vhost_net) {
             error_report("vhost-net requested but could not be initialized");
             return -1;
         }
-    } else if (qemu_opt_get(opts, "vhostfd")) {
+    } else if (tap->has_vhostfd) {
         error_report("vhostfd= is not valid without vhost");
         return -1;
     }
diff --git a/net/tap.h b/net/tap.h
index 44e31ce..f092129 100644
--- a/net/tap.h
+++ b/net/tap.h
@@ -47,7 +47,7 @@ void tap_using_vnet_hdr(VLANClientState *vc, int using_vnet_hdr);
 void tap_set_offload(VLANClientState *vc, int csum, int tso4, int tso6, int ecn, int ufo);
 void tap_set_vnet_hdr_len(VLANClientState *vc, int len);
 
-int tap_set_sndbuf(int fd, QemuOpts *opts);
+int tap_set_sndbuf(int fd, const NetdevTapOptions *tap);
 int tap_probe_vnet_hdr(int fd);
 int tap_probe_vnet_hdr_len(int fd, int len);
 int tap_probe_has_ufo(int fd);
commit 4a917c39aed9ad7f648c435204a6586c4ca3f2f2
Author: Laszlo Ersek <lersek at redhat.com>
Date:   Tue Jul 17 16:17:18 2012 +0200

    convert net_init_vde() to NetClientOptions
    
    v1->v2:
    - NetdevVdeOptions::port and ::mode are of type uint16. Remove superfluous
      range checks.
    
    Signed-off-by: Laszlo Ersek <lersek at redhat.com>
    Signed-off-by: Stefan Hajnoczi <stefanha at linux.vnet.ibm.com>

diff --git a/net/vde.c b/net/vde.c
index 8e60f68..703888c 100644
--- a/net/vde.c
+++ b/net/vde.c
@@ -110,20 +110,17 @@ static int net_vde_init(VLANState *vlan, const char *model,
     return 0;
 }
 
-int net_init_vde(QemuOpts *opts, const NetClientOptions *new_opts,
+int net_init_vde(QemuOpts *old_opts, const NetClientOptions *opts,
                  const char *name, VLANState *vlan)
 {
-    const char *sock;
-    const char *group;
-    int port, mode;
+    const NetdevVdeOptions *vde;
 
-    sock  = qemu_opt_get(opts, "sock");
-    group = qemu_opt_get(opts, "group");
+    assert(opts->kind == NET_CLIENT_OPTIONS_KIND_VDE);
+    vde = opts->vde;
 
-    port = qemu_opt_get_number(opts, "port", 0);
-    mode = qemu_opt_get_number(opts, "mode", 0700);
-
-    if (net_vde_init(vlan, "vde", name, sock, port, group, mode) == -1) {
+    /* missing optional values have been initialized to "all bits zero" */
+    if (net_vde_init(vlan, "vde", name, vde->sock, vde->port, vde->group,
+                     vde->has_mode ? vde->mode : 0700) == -1) {
         return -1;
     }
 
commit bef8e8fe07e80821992f61d3775c6ac3766eee48
Author: Laszlo Ersek <lersek at redhat.com>
Date:   Tue Jul 17 16:17:17 2012 +0200

    convert net_init_socket() to NetClientOptions
    
    I "reverse engineered" the following permissions between the -socket
    sub-options:
    
                 fd  listen  connect  mcast  udp | localaddr
      fd         x   .       .        .      .   | .
      listen     .   x       .        .      .   | .
      connect    .   .       x        .      .   | .
      mcast      .   .       .        x      .   | x
      udp        .   .       .        .      x   | x
      -------------------------------------------+
      localaddr  .   .       .        x      x     x
    
    I transformed the code accordingly. The real fix would be to embed "fd",
    "listen", "connect", "mcast" and "udp" in a separate union. However
    OptsVisitor's enum parser only supports the type=XXX QemuOpt instance as
    union discriminator.
    
    Signed-off-by: Laszlo Ersek <lersek at redhat.com>
    Signed-off-by: Stefan Hajnoczi <stefanha at linux.vnet.ibm.com>

diff --git a/net/socket.c b/net/socket.c
index 563447d..e3cba20 100644
--- a/net/socket.c
+++ b/net/socket.c
@@ -586,101 +586,68 @@ static int net_socket_udp_init(VLANState *vlan,
     return 0;
 }
 
-int net_init_socket(QemuOpts *opts, const NetClientOptions *new_opts,
+int net_init_socket(QemuOpts *old_opts, const NetClientOptions *opts,
                     const char *name, VLANState *vlan)
 {
-    if (qemu_opt_get(opts, "fd")) {
-        int fd;
+    const NetdevSocketOptions *sock;
 
-        if (qemu_opt_get(opts, "listen") ||
-            qemu_opt_get(opts, "connect") ||
-            qemu_opt_get(opts, "mcast") ||
-            qemu_opt_get(opts, "localaddr")) {
-            error_report("listen=, connect=, mcast= and localaddr= is invalid with fd=");
-            return -1;
-        }
+    assert(opts->kind == NET_CLIENT_OPTIONS_KIND_SOCKET);
+    sock = opts->socket;
 
-        fd = net_handle_fd_param(cur_mon, qemu_opt_get(opts, "fd"));
-        if (fd == -1) {
-            return -1;
-        }
+    if (sock->has_fd + sock->has_listen + sock->has_connect + sock->has_mcast +
+        sock->has_udp != 1) {
+        error_report("exactly one of fd=, listen=, connect=, mcast= or udp="
+                     " is required");
+        return -1;
+    }
 
-        if (!net_socket_fd_init(vlan, "socket", name, fd, 1)) {
-            return -1;
-        }
-    } else if (qemu_opt_get(opts, "listen")) {
-        const char *listen;
-
-        if (qemu_opt_get(opts, "fd") ||
-            qemu_opt_get(opts, "connect") ||
-            qemu_opt_get(opts, "mcast") ||
-            qemu_opt_get(opts, "localaddr")) {
-            error_report("fd=, connect=, mcast= and localaddr= is invalid with listen=");
-            return -1;
-        }
+    if (sock->has_localaddr && !sock->has_mcast && !sock->has_udp) {
+        error_report("localaddr= is only valid with mcast= or udp=");
+        return -1;
+    }
 
-        listen = qemu_opt_get(opts, "listen");
+    if (sock->has_fd) {
+        int fd;
 
-        if (net_socket_listen_init(vlan, "socket", name, listen) == -1) {
-            return -1;
-        }
-    } else if (qemu_opt_get(opts, "connect")) {
-        const char *connect;
-
-        if (qemu_opt_get(opts, "fd") ||
-            qemu_opt_get(opts, "listen") ||
-            qemu_opt_get(opts, "mcast") ||
-            qemu_opt_get(opts, "localaddr")) {
-            error_report("fd=, listen=, mcast= and localaddr= is invalid with connect=");
+        fd = net_handle_fd_param(cur_mon, sock->fd);
+        if (fd == -1 || !net_socket_fd_init(vlan, "socket", name, fd, 1)) {
             return -1;
         }
+        return 0;
+    }
 
-        connect = qemu_opt_get(opts, "connect");
-
-        if (net_socket_connect_init(vlan, "socket", name, connect) == -1) {
+    if (sock->has_listen) {
+        if (net_socket_listen_init(vlan, "socket", name, sock->listen) == -1) {
             return -1;
         }
-    } else if (qemu_opt_get(opts, "mcast")) {
-        const char *mcast, *localaddr;
+        return 0;
+    }
 
-        if (qemu_opt_get(opts, "fd") ||
-            qemu_opt_get(opts, "connect") ||
-            qemu_opt_get(opts, "listen")) {
-            error_report("fd=, connect= and listen= is invalid with mcast=");
+    if (sock->has_connect) {
+        if (net_socket_connect_init(vlan, "socket", name, sock->connect) ==
+            -1) {
             return -1;
         }
+        return 0;
+    }
 
-        mcast = qemu_opt_get(opts, "mcast");
-        localaddr = qemu_opt_get(opts, "localaddr");
-
-        if (net_socket_mcast_init(vlan, "socket", name, mcast, localaddr) == -1) {
-            return -1;
-        }
-    } else if (qemu_opt_get(opts, "udp")) {
-        const char *udp, *localaddr;
-
-        if (qemu_opt_get(opts, "fd") ||
-            qemu_opt_get(opts, "connect") ||
-            qemu_opt_get(opts, "listen") ||
-            qemu_opt_get(opts, "mcast")) {
-            error_report("fd=, connect=, listen="
-                         " and mcast= is invalid with udp=");
+    if (sock->has_mcast) {
+        /* if sock->localaddr is missing, it has been initialized to "all bits
+         * zero" */
+        if (net_socket_mcast_init(vlan, "socket", name, sock->mcast,
+            sock->localaddr) == -1) {
             return -1;
         }
+        return 0;
+    }
 
-        udp = qemu_opt_get(opts, "udp");
-        localaddr = qemu_opt_get(opts, "localaddr");
-        if (localaddr == NULL) {
-                error_report("localaddr= is mandatory with udp=");
-                return -1;
-        }
-
-        if (net_socket_udp_init(vlan, "udp", name, udp, localaddr) == -1) {
-            return -1;
-        }
-    } else {
-        error_report("-socket requires fd=, listen=,"
-                     " connect=, mcast= or udp=");
+    assert(sock->has_udp);
+    if (!sock->has_localaddr) {
+        error_report("localaddr= is mandatory with udp=");
+        return -1;
+    }
+    if (net_socket_udp_init(vlan, "udp", name, sock->udp, sock->localaddr) ==
+        -1) {
         return -1;
     }
     return 0;
commit 094f15c5c80a835dbe69afa8534909c681d35856
Author: Laszlo Ersek <lersek at redhat.com>
Date:   Tue Jul 17 16:17:16 2012 +0200

    convert net_init_slirp() to NetClientOptions
    
    Signed-off-by: Laszlo Ersek <lersek at redhat.com>
    Signed-off-by: Stefan Hajnoczi <stefanha at linux.vnet.ibm.com>

diff --git a/net/slirp.c b/net/slirp.c
index 1243d43..44b059f 100644
--- a/net/slirp.c
+++ b/net/slirp.c
@@ -686,89 +686,46 @@ void do_info_usernet(Monitor *mon)
     }
 }
 
-static int net_init_slirp_configs(const char *name, const char *value, void *opaque)
+static void
+net_init_slirp_configs(const StringList *fwd, int flags)
 {
-    struct slirp_config_str *config;
-
-    if (strcmp(name, "hostfwd") != 0 && strcmp(name, "guestfwd") != 0) {
-        return 0;
-    }
-
-    config = g_malloc0(sizeof(*config));
+    while (fwd) {
+        struct slirp_config_str *config;
 
-    pstrcpy(config->str, sizeof(config->str), value);
+        config = g_malloc0(sizeof(*config));
+        pstrcpy(config->str, sizeof(config->str), fwd->value->str);
+        config->flags = flags;
+        config->next = slirp_configs;
+        slirp_configs = config;
 
-    if (!strcmp(name, "hostfwd")) {
-        config->flags = SLIRP_CFG_HOSTFWD;
+        fwd = fwd->next;
     }
-
-    config->next = slirp_configs;
-    slirp_configs = config;
-
-    return 0;
 }
 
-int net_init_slirp(QemuOpts *opts, const NetClientOptions *new_opts,
+int net_init_slirp(QemuOpts *old_opts, const NetClientOptions *opts,
                    const char *name, VLANState *vlan)
 {
     struct slirp_config_str *config;
-    const char *vhost;
-    const char *vhostname;
-    const char *vdhcp_start;
-    const char *vnamesrv;
-    const char *tftp_export;
-    const char *bootfile;
-    const char *smb_export;
-    const char *vsmbsrv;
-    const char *restrict_opt;
-    char *vnet = NULL;
-    int restricted = 0;
+    char *vnet;
     int ret;
+    const NetdevUserOptions *user;
 
-    vhost       = qemu_opt_get(opts, "host");
-    vhostname   = qemu_opt_get(opts, "hostname");
-    vdhcp_start = qemu_opt_get(opts, "dhcpstart");
-    vnamesrv    = qemu_opt_get(opts, "dns");
-    tftp_export = qemu_opt_get(opts, "tftp");
-    bootfile    = qemu_opt_get(opts, "bootfile");
-    smb_export  = qemu_opt_get(opts, "smb");
-    vsmbsrv     = qemu_opt_get(opts, "smbserver");
-
-    restrict_opt = qemu_opt_get(opts, "restrict");
-    if (restrict_opt) {
-        if (!strcmp(restrict_opt, "on") ||
-            !strcmp(restrict_opt, "yes") || !strcmp(restrict_opt, "y")) {
-            restricted = 1;
-        } else if (strcmp(restrict_opt, "off") &&
-            strcmp(restrict_opt, "no") && strcmp(restrict_opt, "n")) {
-            error_report("invalid option: 'restrict=%s'", restrict_opt);
-            return -1;
-        }
-    }
-
-    if (qemu_opt_get(opts, "ip")) {
-        const char *ip = qemu_opt_get(opts, "ip");
-        int l = strlen(ip) + strlen("/24") + 1;
+    assert(opts->kind == NET_CLIENT_OPTIONS_KIND_USER);
+    user = opts->user;
 
-        vnet = g_malloc(l);
+    vnet = user->has_net ? g_strdup(user->net) :
+           user->has_ip  ? g_strdup_printf("%s/24", user->ip) :
+           NULL;
 
-        /* emulate legacy ip= parameter */
-        pstrcpy(vnet, l, ip);
-        pstrcat(vnet, l, "/24");
-    }
-
-    if (qemu_opt_get(opts, "net")) {
-        if (vnet) {
-            g_free(vnet);
-        }
-        vnet = g_strdup(qemu_opt_get(opts, "net"));
-    }
+    /* all optional fields are initialized to "all bits zero" */
 
-    qemu_opt_foreach(opts, net_init_slirp_configs, NULL, 0);
+    net_init_slirp_configs(user->hostfwd, SLIRP_CFG_HOSTFWD);
+    net_init_slirp_configs(user->guestfwd, 0);
 
-    ret = net_slirp_init(vlan, "user", name, restricted, vnet, vhost,
-                         vhostname, tftp_export, bootfile, vdhcp_start,
-                         vnamesrv, smb_export, vsmbsrv);
+    ret = net_slirp_init(vlan, "user", name, user->restrict, vnet, user->host,
+                         user->hostname, user->tftp, user->bootfile,
+                         user->dhcpstart, user->dns, user->smb,
+                         user->smbserver);
 
     while (slirp_configs) {
         config = slirp_configs;
commit 848040d1748e6d3871c319960ecfafce29f410a3
Author: Laszlo Ersek <lersek at redhat.com>
Date:   Tue Jul 17 16:17:15 2012 +0200

    convert net_init_dump() to NetClientOptions
    
    v1->v2:
    - NetdevDumpOptions::len is of type 'size', whose C type was changed to
      uint64_t. Adapt the printf() format specifier macro.
    
    Signed-off-by: Laszlo Ersek <lersek at redhat.com>
    Signed-off-by: Stefan Hajnoczi <stefanha at linux.vnet.ibm.com>

diff --git a/net/dump.c b/net/dump.c
index 27e9528..f3d2fa9 100644
--- a/net/dump.c
+++ b/net/dump.c
@@ -144,22 +144,35 @@ static int net_dump_init(VLANState *vlan, const char *device,
     return 0;
 }
 
-int net_init_dump(QemuOpts *opts, const NetClientOptions *new_opts,
+int net_init_dump(QemuOpts *old_opts, const NetClientOptions *opts,
                   const char *name, VLANState *vlan)
 {
     int len;
     const char *file;
     char def_file[128];
+    const NetdevDumpOptions *dump;
+
+    assert(opts->kind == NET_CLIENT_OPTIONS_KIND_DUMP);
+    dump = opts->dump;
 
     assert(vlan);
 
-    file = qemu_opt_get(opts, "file");
-    if (!file) {
+    if (dump->has_file) {
+        file = dump->file;
+    } else {
         snprintf(def_file, sizeof(def_file), "qemu-vlan%d.pcap", vlan->id);
         file = def_file;
     }
 
-    len = qemu_opt_get_size(opts, "len", 65536);
+    if (dump->has_len) {
+        if (dump->len > INT_MAX) {
+            error_report("invalid length: %"PRIu64, dump->len);
+            return -1;
+        }
+        len = dump->len;
+    } else {
+        len = 65536;
+    }
 
     return net_dump_init(vlan, "dump", name, file, len);
 }
commit 2456f36f18c29ccc343fc676ef1af32e26cd7c88
Author: Laszlo Ersek <lersek at redhat.com>
Date:   Tue Jul 17 16:17:14 2012 +0200

    convert net_init_nic() to NetClientOptions
    
    v1->v2:
    - NetLegacyNicOptions::vectors is of type uint32
    
    Signed-off-by: Laszlo Ersek <lersek at redhat.com>
    Signed-off-by: Stefan Hajnoczi <stefanha at linux.vnet.ibm.com>

diff --git a/net.c b/net.c
index af544b2..a62e902 100644
--- a/net.c
+++ b/net.c
@@ -748,12 +748,15 @@ int net_handle_fd_param(Monitor *mon, const char *param)
     return fd;
 }
 
-static int net_init_nic(QemuOpts *opts, const NetClientOptions *new_opts,
+static int net_init_nic(QemuOpts *old_opts, const NetClientOptions *opts,
                         const char *name, VLANState *vlan)
 {
     int idx;
     NICInfo *nd;
-    const char *netdev;
+    const NetLegacyNicOptions *nic;
+
+    assert(opts->kind == NET_CLIENT_OPTIONS_KIND_NIC);
+    nic = opts->nic;
 
     idx = nic_get_free_idx();
     if (idx == -1 || nb_nics >= MAX_NICS) {
@@ -765,10 +768,10 @@ static int net_init_nic(QemuOpts *opts, const NetClientOptions *new_opts,
 
     memset(nd, 0, sizeof(*nd));
 
-    if ((netdev = qemu_opt_get(opts, "netdev"))) {
-        nd->netdev = qemu_find_netdev(netdev);
+    if (nic->has_netdev) {
+        nd->netdev = qemu_find_netdev(nic->netdev);
         if (!nd->netdev) {
-            error_report("netdev '%s' not found", netdev);
+            error_report("netdev '%s' not found", nic->netdev);
             return -1;
         }
     } else {
@@ -778,26 +781,28 @@ static int net_init_nic(QemuOpts *opts, const NetClientOptions *new_opts,
     if (name) {
         nd->name = g_strdup(name);
     }
-    if (qemu_opt_get(opts, "model")) {
-        nd->model = g_strdup(qemu_opt_get(opts, "model"));
+    if (nic->has_model) {
+        nd->model = g_strdup(nic->model);
     }
-    if (qemu_opt_get(opts, "addr")) {
-        nd->devaddr = g_strdup(qemu_opt_get(opts, "addr"));
+    if (nic->has_addr) {
+        nd->devaddr = g_strdup(nic->addr);
     }
 
-    if (qemu_opt_get(opts, "macaddr") &&
-        net_parse_macaddr(nd->macaddr.a, qemu_opt_get(opts, "macaddr")) < 0) {
+    if (nic->has_macaddr &&
+        net_parse_macaddr(nd->macaddr.a, nic->macaddr) < 0) {
         error_report("invalid syntax for ethernet address");
         return -1;
     }
     qemu_macaddr_default_if_unset(&nd->macaddr);
 
-    nd->nvectors = qemu_opt_get_number(opts, "vectors",
-                                       DEV_NVECTORS_UNSPECIFIED);
-    if (nd->nvectors != DEV_NVECTORS_UNSPECIFIED &&
-        (nd->nvectors < 0 || nd->nvectors > 0x7ffffff)) {
-        error_report("invalid # of vectors: %d", nd->nvectors);
-        return -1;
+    if (nic->has_vectors) {
+        if (nic->vectors > 0x7ffffff) {
+            error_report("invalid # of vectors: %"PRIu32, nic->vectors);
+            return -1;
+        }
+        nd->nvectors = nic->vectors;
+    } else {
+        nd->nvectors = DEV_NVECTORS_UNSPECIFIED;
     }
 
     nd->used = 1;
commit 6687b79d636cd60ed9adb1177d0d946b58fa7717
Author: Laszlo Ersek <lersek at redhat.com>
Date:   Tue Jul 17 16:17:13 2012 +0200

    convert net_client_init() to OptsVisitor
    
    The net_client_init() prototype is kept intact.
    
    Based on "is_netdev", the QemuOpts-rooted QemuOpt-list is parsed as a
    Netdev or a NetLegacy. The original meat of net_client_init() is moved to
    and simplified in net_client_init1():
    
    Fields not common between -net and -netdev are clearly separated. Getting
    the name for the init functions is cleaner: Netdev::id is mandatory, and
    all init functions handle a NULL NetLegacy::name. NetLegacy::vlan
    explicitly depends on -net (see below).
    
    Verifying the "type=" option for -netdev can be turned into a switch.
    
    Format validation with qemu_opts_validate() can be removed because the
    visitor covers it. Relatedly, the "net_client_types" array is reduced to
    an array of init functions that can be directly indexed by opts->kind.
    (Help text is available in the schema JSON.)
    
    The outermost negation in the condition around qemu_find_vlan() was
    flattened, because it expresses the dependent code's requirements more
    clearly.
    
    VLAN lookup is avoided if there's no init function to pass the VLAN to.
    
    Whenever the value of type=... is needed, we substitute
    NetClientOptionsKind_lookup[kind].
    
    The individual init functions are not converted yet, thus the original
    QemuOpts instance is passed transparently.
    
    v1->v2:
    - NetLegacy::name is optional. Tracked it through all init functions: they
      all handle a NULL name. Updated commit message accordingly.
    
    v2->v3:
    - NetLegacy::id is allowed and takes precedence over NetLegacy::name.
    
    Signed-off-by: Laszlo Ersek <lersek at redhat.com>
    Signed-off-by: Stefan Hajnoczi <stefanha at linux.vnet.ibm.com>

diff --git a/net.c b/net.c
index c46695f..af544b2 100644
--- a/net.c
+++ b/net.c
@@ -37,6 +37,9 @@
 #include "qmp-commands.h"
 #include "hw/qdev.h"
 #include "iov.h"
+#include "qapi-visit.h"
+#include "qapi/opts-visitor.h"
+#include "qapi/qapi-dealloc-visitor.h"
 
 /* Net bridge is currently not supported for W32. */
 #if !defined(_WIN32)
@@ -745,7 +748,8 @@ int net_handle_fd_param(Monitor *mon, const char *param)
     return fd;
 }
 
-static int net_init_nic(QemuOpts *opts, const char *name, VLANState *vlan)
+static int net_init_nic(QemuOpts *opts, const NetClientOptions *new_opts,
+                        const char *name, VLANState *vlan)
 {
     int idx;
     NICInfo *nd;
@@ -802,371 +806,130 @@ static int net_init_nic(QemuOpts *opts, const char *name, VLANState *vlan)
     return idx;
 }
 
-#define NET_COMMON_PARAMS_DESC                     \
-    {                                              \
-        .name = "type",                            \
-        .type = QEMU_OPT_STRING,                   \
-        .help = "net client type (nic, tap etc.)", \
-     }, {                                          \
-        .name = "vlan",                            \
-        .type = QEMU_OPT_NUMBER,                   \
-        .help = "vlan number",                     \
-     }, {                                          \
-        .name = "name",                            \
-        .type = QEMU_OPT_STRING,                   \
-        .help = "identifier for monitor commands", \
-     }
-
-typedef int (*net_client_init_func)(QemuOpts *opts,
-                                    const char *name,
-                                    VLANState *vlan);
-
-/* magic number, but compiler will warn if too small */
-#define NET_MAX_DESC 20
-
-static const struct {
-    const char *type;
-    net_client_init_func init;
-    QemuOptDesc desc[NET_MAX_DESC];
-} net_client_types[NET_CLIENT_OPTIONS_KIND_MAX] = {
-    [NET_CLIENT_OPTIONS_KIND_NONE] = {
-        .type = "none",
-        .desc = {
-            NET_COMMON_PARAMS_DESC,
-            { /* end of list */ }
-        },
-    },
-    [NET_CLIENT_OPTIONS_KIND_NIC] = {
-        .type = "nic",
-        .init = net_init_nic,
-        .desc = {
-            NET_COMMON_PARAMS_DESC,
-            {
-                .name = "netdev",
-                .type = QEMU_OPT_STRING,
-                .help = "id of -netdev to connect to",
-            },
-            {
-                .name = "macaddr",
-                .type = QEMU_OPT_STRING,
-                .help = "MAC address",
-            }, {
-                .name = "model",
-                .type = QEMU_OPT_STRING,
-                .help = "device model (e1000, rtl8139, virtio etc.)",
-            }, {
-                .name = "addr",
-                .type = QEMU_OPT_STRING,
-                .help = "PCI device address",
-            }, {
-                .name = "vectors",
-                .type = QEMU_OPT_NUMBER,
-                .help = "number of MSI-x vectors, 0 to disable MSI-X",
-            },
-            { /* end of list */ }
-        },
-    },
+
+static int (* const net_client_init_fun[NET_CLIENT_OPTIONS_KIND_MAX])(
+    QemuOpts *old_opts,
+    const NetClientOptions *new_opts,
+    const char *name,
+    VLANState *vlan) = {
+        [NET_CLIENT_OPTIONS_KIND_NIC]    = net_init_nic,
 #ifdef CONFIG_SLIRP
-    [NET_CLIENT_OPTIONS_KIND_USER] = {
-        .type = "user",
-        .init = net_init_slirp,
-        .desc = {
-            NET_COMMON_PARAMS_DESC,
-            {
-                .name = "hostname",
-                .type = QEMU_OPT_STRING,
-                .help = "client hostname reported by the builtin DHCP server",
-            }, {
-                .name = "restrict",
-                .type = QEMU_OPT_STRING,
-                .help = "isolate the guest from the host (y|yes|n|no)",
-            }, {
-                .name = "ip",
-                .type = QEMU_OPT_STRING,
-                .help = "legacy parameter, use net= instead",
-            }, {
-                .name = "net",
-                .type = QEMU_OPT_STRING,
-                .help = "IP address and optional netmask",
-            }, {
-                .name = "host",
-                .type = QEMU_OPT_STRING,
-                .help = "guest-visible address of the host",
-            }, {
-                .name = "tftp",
-                .type = QEMU_OPT_STRING,
-                .help = "root directory of the built-in TFTP server",
-            }, {
-                .name = "bootfile",
-                .type = QEMU_OPT_STRING,
-                .help = "BOOTP filename, for use with tftp=",
-            }, {
-                .name = "dhcpstart",
-                .type = QEMU_OPT_STRING,
-                .help = "the first of the 16 IPs the built-in DHCP server can assign",
-            }, {
-                .name = "dns",
-                .type = QEMU_OPT_STRING,
-                .help = "guest-visible address of the virtual nameserver",
-            }, {
-                .name = "smb",
-                .type = QEMU_OPT_STRING,
-                .help = "root directory of the built-in SMB server",
-            }, {
-                .name = "smbserver",
-                .type = QEMU_OPT_STRING,
-                .help = "IP address of the built-in SMB server",
-            }, {
-                .name = "hostfwd",
-                .type = QEMU_OPT_STRING,
-                .help = "guest port number to forward incoming TCP or UDP connections",
-            }, {
-                .name = "guestfwd",
-                .type = QEMU_OPT_STRING,
-                .help = "IP address and port to forward guest TCP connections",
-            },
-            { /* end of list */ }
-        },
-    },
-#endif
-    [NET_CLIENT_OPTIONS_KIND_TAP] = {
-        .type = "tap",
-        .init = net_init_tap,
-        .desc = {
-            NET_COMMON_PARAMS_DESC,
-            {
-                .name = "ifname",
-                .type = QEMU_OPT_STRING,
-                .help = "interface name",
-            },
-#ifndef _WIN32
-            {
-                .name = "fd",
-                .type = QEMU_OPT_STRING,
-                .help = "file descriptor of an already opened tap",
-            }, {
-                .name = "script",
-                .type = QEMU_OPT_STRING,
-                .help = "script to initialize the interface",
-            }, {
-                .name = "downscript",
-                .type = QEMU_OPT_STRING,
-                .help = "script to shut down the interface",
-            }, {
-#ifdef CONFIG_NET_BRIDGE
-                .name = "helper",
-                .type = QEMU_OPT_STRING,
-                .help = "command to execute to configure bridge",
-            }, {
+        [NET_CLIENT_OPTIONS_KIND_USER]   = net_init_slirp,
 #endif
-                .name = "sndbuf",
-                .type = QEMU_OPT_SIZE,
-                .help = "send buffer limit"
-            }, {
-                .name = "vnet_hdr",
-                .type = QEMU_OPT_BOOL,
-                .help = "enable the IFF_VNET_HDR flag on the tap interface"
-            }, {
-                .name = "vhost",
-                .type = QEMU_OPT_BOOL,
-                .help = "enable vhost-net network accelerator",
-            }, {
-                .name = "vhostfd",
-                .type = QEMU_OPT_STRING,
-                .help = "file descriptor of an already opened vhost net device",
-            }, {
-                .name = "vhostforce",
-                .type = QEMU_OPT_BOOL,
-                .help = "force vhost on for non-MSIX virtio guests",
-        },
-#endif /* _WIN32 */
-            { /* end of list */ }
-        },
-    },
-    [NET_CLIENT_OPTIONS_KIND_SOCKET] = {
-        .type = "socket",
-        .init = net_init_socket,
-        .desc = {
-            NET_COMMON_PARAMS_DESC,
-            {
-                .name = "fd",
-                .type = QEMU_OPT_STRING,
-                .help = "file descriptor of an already opened socket",
-            }, {
-                .name = "listen",
-                .type = QEMU_OPT_STRING,
-                .help = "port number, and optional hostname, to listen on",
-            }, {
-                .name = "connect",
-                .type = QEMU_OPT_STRING,
-                .help = "port number, and optional hostname, to connect to",
-            }, {
-                .name = "mcast",
-                .type = QEMU_OPT_STRING,
-                .help = "UDP multicast address and port number",
-            }, {
-                .name = "localaddr",
-                .type = QEMU_OPT_STRING,
-                .help = "source address and port for multicast and udp packets",
-            }, {
-                .name = "udp",
-                .type = QEMU_OPT_STRING,
-                .help = "UDP unicast address and port number",
-            },
-            { /* end of list */ }
-        },
-    },
+        [NET_CLIENT_OPTIONS_KIND_TAP]    = net_init_tap,
+        [NET_CLIENT_OPTIONS_KIND_SOCKET] = net_init_socket,
 #ifdef CONFIG_VDE
-    [NET_CLIENT_OPTIONS_KIND_VDE] = {
-        .type = "vde",
-        .init = net_init_vde,
-        .desc = {
-            NET_COMMON_PARAMS_DESC,
-            {
-                .name = "sock",
-                .type = QEMU_OPT_STRING,
-                .help = "socket path",
-            }, {
-                .name = "port",
-                .type = QEMU_OPT_NUMBER,
-                .help = "port number",
-            }, {
-                .name = "group",
-                .type = QEMU_OPT_STRING,
-                .help = "group owner of socket",
-            }, {
-                .name = "mode",
-                .type = QEMU_OPT_NUMBER,
-                .help = "permissions for socket",
-            },
-            { /* end of list */ }
-        },
-    },
+        [NET_CLIENT_OPTIONS_KIND_VDE]    = net_init_vde,
 #endif
-    [NET_CLIENT_OPTIONS_KIND_DUMP] = {
-        .type = "dump",
-        .init = net_init_dump,
-        .desc = {
-            NET_COMMON_PARAMS_DESC,
-            {
-                .name = "len",
-                .type = QEMU_OPT_SIZE,
-                .help = "per-packet size limit (64k default)",
-            }, {
-                .name = "file",
-                .type = QEMU_OPT_STRING,
-                .help = "dump file path (default is qemu-vlan0.pcap)",
-            },
-            { /* end of list */ }
-        },
-    },
+        [NET_CLIENT_OPTIONS_KIND_DUMP]   = net_init_dump,
 #ifdef CONFIG_NET_BRIDGE
-    [NET_CLIENT_OPTIONS_KIND_BRIDGE] = {
-        .type = "bridge",
-        .init = net_init_bridge,
-        .desc = {
-            NET_COMMON_PARAMS_DESC,
-            {
-                .name = "br",
-                .type = QEMU_OPT_STRING,
-                .help = "bridge name",
-            }, {
-                .name = "helper",
-                .type = QEMU_OPT_STRING,
-                .help = "command to execute to configure bridge",
-            },
-            { /* end of list */ }
-        },
-    },
-#endif /* CONFIG_NET_BRIDGE */
+        [NET_CLIENT_OPTIONS_KIND_BRIDGE] = net_init_bridge,
+#endif
 };
 
-int net_client_init(QemuOpts *opts, int is_netdev, Error **errp)
+
+static int net_client_init1(const void *object, int is_netdev,
+                            QemuOpts *old_opts, Error **errp)
 {
+    union {
+        const Netdev    *netdev;
+        const NetLegacy *net;
+    } u;
+    const NetClientOptions *opts;
     const char *name;
-    const char *type;
-    int i;
-
-    type = qemu_opt_get(opts, "type");
-    if (!type) {
-        error_set(errp, QERR_MISSING_PARAMETER, "type");
-        return -1;
-    }
 
     if (is_netdev) {
-        if (strcmp(type, "tap") != 0 &&
-#ifdef CONFIG_NET_BRIDGE
-            strcmp(type, "bridge") != 0 &&
-#endif
+        u.netdev = object;
+        opts = u.netdev->opts;
+        name = u.netdev->id;
+
+        switch (opts->kind) {
 #ifdef CONFIG_SLIRP
-            strcmp(type, "user") != 0 &&
+        case NET_CLIENT_OPTIONS_KIND_USER:
 #endif
+        case NET_CLIENT_OPTIONS_KIND_TAP:
+        case NET_CLIENT_OPTIONS_KIND_SOCKET:
 #ifdef CONFIG_VDE
-            strcmp(type, "vde") != 0 &&
+        case NET_CLIENT_OPTIONS_KIND_VDE:
+#endif
+#ifdef CONFIG_NET_BRIDGE
+        case NET_CLIENT_OPTIONS_KIND_BRIDGE:
 #endif
-            strcmp(type, "socket") != 0) {
+            break;
+
+        default:
             error_set(errp, QERR_INVALID_PARAMETER_VALUE, "type",
                       "a netdev backend type");
             return -1;
         }
+    } else {
+        u.net = object;
+        opts = u.net->opts;
+        /* missing optional values have been initialized to "all bits zero" */
+        name = u.net->has_id ? u.net->id : u.net->name;
+    }
 
-        if (qemu_opt_get(opts, "vlan")) {
-            error_set(errp, QERR_INVALID_PARAMETER, "vlan");
-            return -1;
-        }
-        if (qemu_opt_get(opts, "name")) {
-            error_set(errp, QERR_INVALID_PARAMETER, "name");
-            return -1;
+    if (net_client_init_fun[opts->kind]) {
+        VLANState *vlan = NULL;
+
+        /* Do not add to a vlan if it's a -netdev or a nic with a netdev=
+         * parameter. */
+        if (!is_netdev &&
+            (opts->kind != NET_CLIENT_OPTIONS_KIND_NIC ||
+             !opts->nic->has_netdev)) {
+            vlan = qemu_find_vlan(u.net->has_vlan ? u.net->vlan : 0, true);
         }
-        if (!qemu_opts_id(opts)) {
-            error_set(errp, QERR_MISSING_PARAMETER, "id");
+
+        if (net_client_init_fun[opts->kind](old_opts, opts, name, vlan) < 0) {
+            /* TODO push error reporting into init() methods */
+            error_set(errp, QERR_DEVICE_INIT_FAILED,
+                      NetClientOptionsKind_lookup[opts->kind]);
             return -1;
         }
     }
+    return 0;
+}
+
 
-    name = qemu_opts_id(opts);
-    if (!name) {
-        name = qemu_opt_get(opts, "name");
+static void net_visit(Visitor *v, int is_netdev, void **object, Error **errp)
+{
+    if (is_netdev) {
+        visit_type_Netdev(v, (Netdev **)object, NULL, errp);
+    } else {
+        visit_type_NetLegacy(v, (NetLegacy **)object, NULL, errp);
     }
+}
 
-    for (i = 0; i < NET_CLIENT_OPTIONS_KIND_MAX; i++) {
-        if (net_client_types[i].type != NULL &&
-            !strcmp(net_client_types[i].type, type)) {
-            Error *local_err = NULL;
-            VLANState *vlan = NULL;
-            int ret;
 
-            qemu_opts_validate(opts, &net_client_types[i].desc[0], &local_err);
-            if (error_is_set(&local_err)) {
-                error_propagate(errp, local_err);
-                return -1;
-            }
+int net_client_init(QemuOpts *opts, int is_netdev, Error **errp)
+{
+    void *object = NULL;
+    Error *err = NULL;
+    int ret = -1;
 
-            /* Do not add to a vlan if it's a -netdev or a nic with a
-             * netdev= parameter. */
-            if (!(is_netdev ||
-                  (strcmp(type, "nic") == 0 && qemu_opt_get(opts, "netdev")))) {
-                vlan = qemu_find_vlan(qemu_opt_get_number(opts, "vlan", 0), 1);
-            }
+    {
+        OptsVisitor *ov = opts_visitor_new(opts);
 
-            ret = 0;
-            if (net_client_types[i].init) {
-                ret = net_client_types[i].init(opts, name, vlan);
-                if (ret < 0) {
-                    /* TODO push error reporting into init() methods */
-                    error_set(errp, QERR_DEVICE_INIT_FAILED, type);
-                    return -1;
-                }
-            }
-            return ret;
-        }
+        net_visit(opts_get_visitor(ov), is_netdev, &object, &err);
+        opts_visitor_cleanup(ov);
     }
 
-    error_set(errp, QERR_INVALID_PARAMETER_VALUE, "type",
-              "a network client type");
-    return -1;
+    if (!err) {
+        ret = net_client_init1(object, is_netdev, opts, &err);
+    }
+
+    if (object) {
+        QapiDeallocVisitor *dv = qapi_dealloc_visitor_new();
+
+        net_visit(qapi_dealloc_get_visitor(dv), is_netdev, &object, NULL);
+        qapi_dealloc_visitor_cleanup(dv);
+    }
+
+    error_propagate(errp, err);
+    return ret;
 }
 
+
 static int net_host_check_device(const char *device)
 {
     int i;
@@ -1286,7 +1049,7 @@ void qmp_netdev_del(const char *id, Error **errp)
 static void print_net_client(Monitor *mon, VLANClientState *vc)
 {
     monitor_printf(mon, "%s: type=%s,%s\n", vc->name,
-                   net_client_types[vc->info->type].type, vc->info_str);
+                   NetClientOptionsKind_lookup[vc->info->type], vc->info_str);
 }
 
 void do_info_network(Monitor *mon)
diff --git a/net/dump.c b/net/dump.c
index 2124b9a..27e9528 100644
--- a/net/dump.c
+++ b/net/dump.c
@@ -144,7 +144,8 @@ static int net_dump_init(VLANState *vlan, const char *device,
     return 0;
 }
 
-int net_init_dump(QemuOpts *opts, const char *name, VLANState *vlan)
+int net_init_dump(QemuOpts *opts, const NetClientOptions *new_opts,
+                  const char *name, VLANState *vlan)
 {
     int len;
     const char *file;
diff --git a/net/dump.h b/net/dump.h
index 2b5d9ba..85ac00b 100644
--- a/net/dump.h
+++ b/net/dump.h
@@ -26,7 +26,9 @@
 
 #include "net.h"
 #include "qemu-common.h"
+#include "qapi-types.h"
 
-int net_init_dump(QemuOpts *opts, const char *name, VLANState *vlan);
+int net_init_dump(QemuOpts *opts, const NetClientOptions *new_opts,
+                  const char *name, VLANState *vlan);
 
 #endif /* QEMU_NET_DUMP_H */
diff --git a/net/slirp.c b/net/slirp.c
index 1f63d50..1243d43 100644
--- a/net/slirp.c
+++ b/net/slirp.c
@@ -708,7 +708,8 @@ static int net_init_slirp_configs(const char *name, const char *value, void *opa
     return 0;
 }
 
-int net_init_slirp(QemuOpts *opts, const char *name, VLANState *vlan)
+int net_init_slirp(QemuOpts *opts, const NetClientOptions *new_opts,
+                   const char *name, VLANState *vlan)
 {
     struct slirp_config_str *config;
     const char *vhost;
diff --git a/net/slirp.h b/net/slirp.h
index 53fe95d..ef13a65 100644
--- a/net/slirp.h
+++ b/net/slirp.h
@@ -27,10 +27,12 @@
 #include "qemu-common.h"
 #include "qdict.h"
 #include "qemu-option.h"
+#include "qapi-types.h"
 
 #ifdef CONFIG_SLIRP
 
-int net_init_slirp(QemuOpts *opts, const char *name, VLANState *vlan);
+int net_init_slirp(QemuOpts *opts, const NetClientOptions *new_opts,
+                   const char *name, VLANState *vlan);
 
 void net_slirp_hostfwd_add(Monitor *mon, const QDict *qdict);
 void net_slirp_hostfwd_remove(Monitor *mon, const QDict *qdict);
diff --git a/net/socket.c b/net/socket.c
index 30536ef..563447d 100644
--- a/net/socket.c
+++ b/net/socket.c
@@ -586,7 +586,8 @@ static int net_socket_udp_init(VLANState *vlan,
     return 0;
 }
 
-int net_init_socket(QemuOpts *opts, const char *name, VLANState *vlan)
+int net_init_socket(QemuOpts *opts, const NetClientOptions *new_opts,
+                    const char *name, VLANState *vlan)
 {
     if (qemu_opt_get(opts, "fd")) {
         int fd;
diff --git a/net/socket.h b/net/socket.h
index e1fe959..e44d26e 100644
--- a/net/socket.h
+++ b/net/socket.h
@@ -26,7 +26,9 @@
 
 #include "net.h"
 #include "qemu-common.h"
+#include "qapi-types.h"
 
-int net_init_socket(QemuOpts *opts, const char *name, VLANState *vlan);
+int net_init_socket(QemuOpts *opts, const NetClientOptions *new_opts,
+                    const char *name, VLANState *vlan);
 
 #endif /* QEMU_NET_SOCKET_H */
diff --git a/net/tap-win32.c b/net/tap-win32.c
index f7b6129..b738f45 100644
--- a/net/tap-win32.c
+++ b/net/tap-win32.c
@@ -699,7 +699,8 @@ static int tap_win32_init(VLANState *vlan, const char *model,
     return 0;
 }
 
-int net_init_tap(QemuOpts *opts, const char *name, VLANState *vlan)
+int net_init_tap(QemuOpts *opts, const NetClientOptions *new_opts,
+                 const char *name, VLANState *vlan)
 {
     const char *ifname;
 
diff --git a/net/tap.c b/net/tap.c
index 9131ef5..0fc856c 100644
--- a/net/tap.c
+++ b/net/tap.c
@@ -513,7 +513,8 @@ static int net_bridge_run_helper(const char *helper, const char *bridge)
     return -1;
 }
 
-int net_init_bridge(QemuOpts *opts, const char *name, VLANState *vlan)
+int net_init_bridge(QemuOpts *opts, const NetClientOptions *new_opts,
+                    const char *name, VLANState *vlan)
 {
     TAPState *s;
     int fd, vnet_hdr;
@@ -583,7 +584,8 @@ static int net_tap_init(QemuOpts *opts, int *vnet_hdr)
     return fd;
 }
 
-int net_init_tap(QemuOpts *opts, const char *name, VLANState *vlan)
+int net_init_tap(QemuOpts *opts, const NetClientOptions *new_opts,
+                 const char *name, VLANState *vlan)
 {
     TAPState *s;
     int fd, vnet_hdr = 0;
diff --git a/net/tap.h b/net/tap.h
index b2a9450..44e31ce 100644
--- a/net/tap.h
+++ b/net/tap.h
@@ -28,11 +28,13 @@
 
 #include "qemu-common.h"
 #include "qemu-option.h"
+#include "qapi-types.h"
 
 #define DEFAULT_NETWORK_SCRIPT "/etc/qemu-ifup"
 #define DEFAULT_NETWORK_DOWN_SCRIPT "/etc/qemu-ifdown"
 
-int net_init_tap(QemuOpts *opts, const char *name, VLANState *vlan);
+int net_init_tap(QemuOpts *opts, const NetClientOptions *new_opts,
+                 const char *name, VLANState *vlan);
 
 int tap_open(char *ifname, int ifname_size, int *vnet_hdr, int vnet_hdr_required);
 
@@ -57,6 +59,7 @@ int tap_get_fd(VLANClientState *vc);
 struct vhost_net;
 struct vhost_net *tap_get_vhost_net(VLANClientState *vc);
 
-int net_init_bridge(QemuOpts *opts, const char *name, VLANState *vlan);
+int net_init_bridge(QemuOpts *opts, const NetClientOptions *new_opts,
+                    const char *name, VLANState *vlan);
 
 #endif /* QEMU_NET_TAP_H */
diff --git a/net/vde.c b/net/vde.c
index 0e8bf23..8e60f68 100644
--- a/net/vde.c
+++ b/net/vde.c
@@ -110,7 +110,8 @@ static int net_vde_init(VLANState *vlan, const char *model,
     return 0;
 }
 
-int net_init_vde(QemuOpts *opts, const char *name, VLANState *vlan)
+int net_init_vde(QemuOpts *opts, const NetClientOptions *new_opts,
+                 const char *name, VLANState *vlan)
 {
     const char *sock;
     const char *group;
diff --git a/net/vde.h b/net/vde.h
index 732e575..5fc17f9 100644
--- a/net/vde.h
+++ b/net/vde.h
@@ -26,10 +26,12 @@
 
 #include "qemu-common.h"
 #include "qemu-option.h"
+#include "qapi-types.h"
 
 #ifdef CONFIG_VDE
 
-int net_init_vde(QemuOpts *opts, const char *name, VLANState *vlan);
+int net_init_vde(QemuOpts *opts, const NetClientOptions *new_opts,
+                 const char *name, VLANState *vlan);
 
 #endif /* CONFIG_VDE */
 
commit 2be64a68ed05c65fc510dc450a1eb1823edf9330
Author: Laszlo Ersek <lersek at redhat.com>
Date:   Tue Jul 17 16:17:12 2012 +0200

    hw, net: "net_client_type" -> "NetClientOptionsKind" (qapi-generated)
    
    NET_CLIENT_TYPE_ -> NET_CLIENT_OPTIONS_KIND_
    
    Signed-off-by: Laszlo Ersek <lersek at redhat.com>
    Signed-off-by: Stefan Hajnoczi <stefanha at linux.vnet.ibm.com>

diff --git a/hw/cadence_gem.c b/hw/cadence_gem.c
index 87143ca..a0f51de 100644
--- a/hw/cadence_gem.c
+++ b/hw/cadence_gem.c
@@ -1161,7 +1161,7 @@ static void gem_set_link(VLANClientState *nc)
 }
 
 static NetClientInfo net_gem_info = {
-    .type = NET_CLIENT_TYPE_NIC,
+    .type = NET_CLIENT_OPTIONS_KIND_NIC,
     .size = sizeof(NICState),
     .can_receive = gem_can_receive,
     .receive = gem_receive,
diff --git a/hw/dp8393x.c b/hw/dp8393x.c
index 017d074..756d630 100644
--- a/hw/dp8393x.c
+++ b/hw/dp8393x.c
@@ -872,7 +872,7 @@ static void nic_cleanup(VLANClientState *nc)
 }
 
 static NetClientInfo net_dp83932_info = {
-    .type = NET_CLIENT_TYPE_NIC,
+    .type = NET_CLIENT_OPTIONS_KIND_NIC,
     .size = sizeof(NICState),
     .can_receive = nic_can_receive,
     .receive = nic_receive,
diff --git a/hw/e1000.c b/hw/e1000.c
index 4573f13..ad24298 100644
--- a/hw/e1000.c
+++ b/hw/e1000.c
@@ -1206,7 +1206,7 @@ pci_e1000_uninit(PCIDevice *dev)
 }
 
 static NetClientInfo net_e1000_info = {
-    .type = NET_CLIENT_TYPE_NIC,
+    .type = NET_CLIENT_OPTIONS_KIND_NIC,
     .size = sizeof(NICState),
     .can_receive = e1000_can_receive,
     .receive = e1000_receive,
diff --git a/hw/eepro100.c b/hw/eepro100.c
index 6279ae3..f343685 100644
--- a/hw/eepro100.c
+++ b/hw/eepro100.c
@@ -1845,7 +1845,7 @@ static int pci_nic_uninit(PCIDevice *pci_dev)
 }
 
 static NetClientInfo net_eepro100_info = {
-    .type = NET_CLIENT_TYPE_NIC,
+    .type = NET_CLIENT_OPTIONS_KIND_NIC,
     .size = sizeof(NICState),
     .can_receive = nic_can_receive,
     .receive = nic_receive,
diff --git a/hw/etraxfs_eth.c b/hw/etraxfs_eth.c
index 16a0637..45fb40c 100644
--- a/hw/etraxfs_eth.c
+++ b/hw/etraxfs_eth.c
@@ -579,7 +579,7 @@ static void eth_cleanup(VLANClientState *nc)
 }
 
 static NetClientInfo net_etraxfs_info = {
-	.type = NET_CLIENT_TYPE_NIC,
+	.type = NET_CLIENT_OPTIONS_KIND_NIC,
 	.size = sizeof(NICState),
 	.can_receive = eth_can_receive,
 	.receive = eth_receive,
diff --git a/hw/lan9118.c b/hw/lan9118.c
index 7b4fe87..40fb765 100644
--- a/hw/lan9118.c
+++ b/hw/lan9118.c
@@ -1310,7 +1310,7 @@ static void lan9118_cleanup(VLANClientState *nc)
 }
 
 static NetClientInfo net_lan9118_info = {
-    .type = NET_CLIENT_TYPE_NIC,
+    .type = NET_CLIENT_OPTIONS_KIND_NIC,
     .size = sizeof(NICState),
     .can_receive = lan9118_can_receive,
     .receive = lan9118_receive,
diff --git a/hw/lance.c b/hw/lance.c
index ce3d46c..91c0e16 100644
--- a/hw/lance.c
+++ b/hw/lance.c
@@ -93,7 +93,7 @@ static void lance_cleanup(VLANClientState *nc)
 }
 
 static NetClientInfo net_lance_info = {
-    .type = NET_CLIENT_TYPE_NIC,
+    .type = NET_CLIENT_OPTIONS_KIND_NIC,
     .size = sizeof(NICState),
     .can_receive = pcnet_can_receive,
     .receive = pcnet_receive,
diff --git a/hw/mcf_fec.c b/hw/mcf_fec.c
index ae37bef..4ab4ff5 100644
--- a/hw/mcf_fec.c
+++ b/hw/mcf_fec.c
@@ -450,7 +450,7 @@ static void mcf_fec_cleanup(VLANClientState *nc)
 }
 
 static NetClientInfo net_mcf_fec_info = {
-    .type = NET_CLIENT_TYPE_NIC,
+    .type = NET_CLIENT_OPTIONS_KIND_NIC,
     .size = sizeof(NICState),
     .can_receive = mcf_fec_can_receive,
     .receive = mcf_fec_receive,
diff --git a/hw/milkymist-minimac2.c b/hw/milkymist-minimac2.c
index 70bf336..3924b83 100644
--- a/hw/milkymist-minimac2.c
+++ b/hw/milkymist-minimac2.c
@@ -448,7 +448,7 @@ static void milkymist_minimac2_reset(DeviceState *d)
 }
 
 static NetClientInfo net_milkymist_minimac2_info = {
-    .type = NET_CLIENT_TYPE_NIC,
+    .type = NET_CLIENT_OPTIONS_KIND_NIC,
     .size = sizeof(NICState),
     .can_receive = minimac2_can_rx,
     .receive = minimac2_rx,
diff --git a/hw/mipsnet.c b/hw/mipsnet.c
index 3107246..3385be7 100644
--- a/hw/mipsnet.c
+++ b/hw/mipsnet.c
@@ -217,7 +217,7 @@ static void mipsnet_cleanup(VLANClientState *nc)
 }
 
 static NetClientInfo net_mipsnet_info = {
-    .type = NET_CLIENT_TYPE_NIC,
+    .type = NET_CLIENT_OPTIONS_KIND_NIC,
     .size = sizeof(NICState),
     .can_receive = mipsnet_can_receive,
     .receive = mipsnet_receive,
diff --git a/hw/musicpal.c b/hw/musicpal.c
index f14f20d..448897f 100644
--- a/hw/musicpal.c
+++ b/hw/musicpal.c
@@ -374,7 +374,7 @@ static void eth_cleanup(VLANClientState *nc)
 }
 
 static NetClientInfo net_mv88w8618_info = {
-    .type = NET_CLIENT_TYPE_NIC,
+    .type = NET_CLIENT_OPTIONS_KIND_NIC,
     .size = sizeof(NICState),
     .can_receive = eth_can_receive,
     .receive = eth_receive,
diff --git a/hw/ne2000-isa.c b/hw/ne2000-isa.c
index a4a783a..99ed965 100644
--- a/hw/ne2000-isa.c
+++ b/hw/ne2000-isa.c
@@ -44,7 +44,7 @@ static void isa_ne2000_cleanup(VLANClientState *nc)
 }
 
 static NetClientInfo net_ne2000_isa_info = {
-    .type = NET_CLIENT_TYPE_NIC,
+    .type = NET_CLIENT_OPTIONS_KIND_NIC,
     .size = sizeof(NICState),
     .can_receive = ne2000_can_receive,
     .receive = ne2000_receive,
diff --git a/hw/ne2000.c b/hw/ne2000.c
index d02e60c..760ed29 100644
--- a/hw/ne2000.c
+++ b/hw/ne2000.c
@@ -711,7 +711,7 @@ static void ne2000_cleanup(VLANClientState *nc)
 }
 
 static NetClientInfo net_ne2000_info = {
-    .type = NET_CLIENT_TYPE_NIC,
+    .type = NET_CLIENT_OPTIONS_KIND_NIC,
     .size = sizeof(NICState),
     .can_receive = ne2000_can_receive,
     .receive = ne2000_receive,
diff --git a/hw/opencores_eth.c b/hw/opencores_eth.c
index 350f731..f4498d4 100644
--- a/hw/opencores_eth.c
+++ b/hw/opencores_eth.c
@@ -467,7 +467,7 @@ static void open_eth_cleanup(VLANClientState *nc)
 }
 
 static NetClientInfo net_open_eth_info = {
-    .type = NET_CLIENT_TYPE_NIC,
+    .type = NET_CLIENT_OPTIONS_KIND_NIC,
     .size = sizeof(NICState),
     .can_receive = open_eth_can_receive,
     .receive = open_eth_receive,
diff --git a/hw/pcnet-pci.c b/hw/pcnet-pci.c
index 34d73aa..931fedd 100644
--- a/hw/pcnet-pci.c
+++ b/hw/pcnet-pci.c
@@ -284,7 +284,7 @@ static int pci_pcnet_uninit(PCIDevice *dev)
 }
 
 static NetClientInfo net_pci_pcnet_info = {
-    .type = NET_CLIENT_TYPE_NIC,
+    .type = NET_CLIENT_OPTIONS_KIND_NIC,
     .size = sizeof(NICState),
     .can_receive = pcnet_can_receive,
     .receive = pcnet_receive,
diff --git a/hw/rtl8139.c b/hw/rtl8139.c
index 436b015..82fe235 100644
--- a/hw/rtl8139.c
+++ b/hw/rtl8139.c
@@ -3455,7 +3455,7 @@ static int pci_rtl8139_uninit(PCIDevice *dev)
 }
 
 static NetClientInfo net_rtl8139_info = {
-    .type = NET_CLIENT_TYPE_NIC,
+    .type = NET_CLIENT_OPTIONS_KIND_NIC,
     .size = sizeof(NICState),
     .can_receive = rtl8139_can_receive,
     .receive = rtl8139_receive,
diff --git a/hw/smc91c111.c b/hw/smc91c111.c
index 1a5213f..451ede0 100644
--- a/hw/smc91c111.c
+++ b/hw/smc91c111.c
@@ -736,7 +736,7 @@ static void smc91c111_cleanup(VLANClientState *nc)
 }
 
 static NetClientInfo net_smc91c111_info = {
-    .type = NET_CLIENT_TYPE_NIC,
+    .type = NET_CLIENT_OPTIONS_KIND_NIC,
     .size = sizeof(NICState),
     .can_receive = smc91c111_can_receive,
     .receive = smc91c111_receive,
diff --git a/hw/spapr_llan.c b/hw/spapr_llan.c
index d26fe9f..d54f933 100644
--- a/hw/spapr_llan.c
+++ b/hw/spapr_llan.c
@@ -176,7 +176,7 @@ static ssize_t spapr_vlan_receive(VLANClientState *nc, const uint8_t *buf,
 }
 
 static NetClientInfo net_spapr_vlan_info = {
-    .type = NET_CLIENT_TYPE_NIC,
+    .type = NET_CLIENT_OPTIONS_KIND_NIC,
     .size = sizeof(NICState),
     .can_receive = spapr_vlan_can_receive,
     .receive = spapr_vlan_receive,
diff --git a/hw/stellaris_enet.c b/hw/stellaris_enet.c
index fbe99cb..b593cd0 100644
--- a/hw/stellaris_enet.c
+++ b/hw/stellaris_enet.c
@@ -393,7 +393,7 @@ static void stellaris_enet_cleanup(VLANClientState *nc)
 }
 
 static NetClientInfo net_stellaris_enet_info = {
-    .type = NET_CLIENT_TYPE_NIC,
+    .type = NET_CLIENT_OPTIONS_KIND_NIC,
     .size = sizeof(NICState),
     .can_receive = stellaris_enet_can_receive,
     .receive = stellaris_enet_receive,
diff --git a/hw/usb/dev-network.c b/hw/usb/dev-network.c
index 5d2f098..f40c349 100644
--- a/hw/usb/dev-network.c
+++ b/hw/usb/dev-network.c
@@ -1313,7 +1313,7 @@ static void usb_net_handle_destroy(USBDevice *dev)
 }
 
 static NetClientInfo net_usbnet_info = {
-    .type = NET_CLIENT_TYPE_NIC,
+    .type = NET_CLIENT_OPTIONS_KIND_NIC,
     .size = sizeof(NICState),
     .can_receive = usbnet_can_receive,
     .receive = usbnet_receive,
diff --git a/hw/vhost_net.c b/hw/vhost_net.c
index f672e9d..75f8211 100644
--- a/hw/vhost_net.c
+++ b/hw/vhost_net.c
@@ -83,7 +83,7 @@ void vhost_net_ack_features(struct vhost_net *net, unsigned features)
 static int vhost_net_get_fd(VLANClientState *backend)
 {
     switch (backend->info->type) {
-    case NET_CLIENT_TYPE_TAP:
+    case NET_CLIENT_OPTIONS_KIND_TAP:
         return tap_get_fd(backend);
     default:
         fprintf(stderr, "vhost-net requires tap backend\n");
diff --git a/hw/virtio-net.c b/hw/virtio-net.c
index 533aa3d..df20499 100644
--- a/hw/virtio-net.c
+++ b/hw/virtio-net.c
@@ -108,7 +108,7 @@ static void virtio_net_vhost_status(VirtIONet *n, uint8_t status)
     if (!n->nic->nc.peer) {
         return;
     }
-    if (n->nic->nc.peer->info->type != NET_CLIENT_TYPE_TAP) {
+    if (n->nic->nc.peer->info->type != NET_CLIENT_OPTIONS_KIND_TAP) {
         return;
     }
 
@@ -205,7 +205,7 @@ static int peer_has_vnet_hdr(VirtIONet *n)
     if (!n->nic->nc.peer)
         return 0;
 
-    if (n->nic->nc.peer->info->type != NET_CLIENT_TYPE_TAP)
+    if (n->nic->nc.peer->info->type != NET_CLIENT_OPTIONS_KIND_TAP)
         return 0;
 
     n->has_vnet_hdr = tap_has_vnet_hdr(n->nic->nc.peer);
@@ -249,7 +249,7 @@ static uint32_t virtio_net_get_features(VirtIODevice *vdev, uint32_t features)
     }
 
     if (!n->nic->nc.peer ||
-        n->nic->nc.peer->info->type != NET_CLIENT_TYPE_TAP) {
+        n->nic->nc.peer->info->type != NET_CLIENT_OPTIONS_KIND_TAP) {
         return features;
     }
     if (!tap_get_vhost_net(n->nic->nc.peer)) {
@@ -288,7 +288,7 @@ static void virtio_net_set_features(VirtIODevice *vdev, uint32_t features)
                         (features >> VIRTIO_NET_F_GUEST_UFO)  & 1);
     }
     if (!n->nic->nc.peer ||
-        n->nic->nc.peer->info->type != NET_CLIENT_TYPE_TAP) {
+        n->nic->nc.peer->info->type != NET_CLIENT_OPTIONS_KIND_TAP) {
         return;
     }
     if (!tap_get_vhost_net(n->nic->nc.peer)) {
@@ -988,7 +988,7 @@ static void virtio_net_cleanup(VLANClientState *nc)
 }
 
 static NetClientInfo net_virtio_info = {
-    .type = NET_CLIENT_TYPE_NIC,
+    .type = NET_CLIENT_OPTIONS_KIND_NIC,
     .size = sizeof(NICState),
     .can_receive = virtio_net_can_receive,
     .receive = virtio_net_receive,
diff --git a/hw/xen_nic.c b/hw/xen_nic.c
index 98db9bb..593a572 100644
--- a/hw/xen_nic.c
+++ b/hw/xen_nic.c
@@ -301,7 +301,7 @@ static ssize_t net_rx_packet(VLANClientState *nc, const uint8_t *buf, size_t siz
 /* ------------------------------------------------------------- */
 
 static NetClientInfo net_xen_info = {
-    .type = NET_CLIENT_TYPE_NIC,
+    .type = NET_CLIENT_OPTIONS_KIND_NIC,
     .size = sizeof(NICState),
     .can_receive = net_rx_ok,
     .receive = net_rx_packet,
diff --git a/hw/xgmac.c b/hw/xgmac.c
index dd4bdc4..e539681 100644
--- a/hw/xgmac.c
+++ b/hw/xgmac.c
@@ -371,7 +371,7 @@ static void eth_cleanup(VLANClientState *nc)
 }
 
 static NetClientInfo net_xgmac_enet_info = {
-    .type = NET_CLIENT_TYPE_NIC,
+    .type = NET_CLIENT_OPTIONS_KIND_NIC,
     .size = sizeof(NICState),
     .can_receive = eth_can_rx,
     .receive = eth_rx,
diff --git a/hw/xilinx_axienet.c b/hw/xilinx_axienet.c
index 2e8d8a5..e948505 100644
--- a/hw/xilinx_axienet.c
+++ b/hw/xilinx_axienet.c
@@ -832,7 +832,7 @@ axienet_stream_push(void *opaque, uint8_t *buf, size_t size, uint32_t *hdr)
 }
 
 static NetClientInfo net_xilinx_enet_info = {
-    .type = NET_CLIENT_TYPE_NIC,
+    .type = NET_CLIENT_OPTIONS_KIND_NIC,
     .size = sizeof(NICState),
     .can_receive = eth_can_rx,
     .receive = eth_rx,
diff --git a/hw/xilinx_ethlite.c b/hw/xilinx_ethlite.c
index affbb8b..9006322 100644
--- a/hw/xilinx_ethlite.c
+++ b/hw/xilinx_ethlite.c
@@ -202,7 +202,7 @@ static void eth_cleanup(VLANClientState *nc)
 }
 
 static NetClientInfo net_xilinx_ethlite_info = {
-    .type = NET_CLIENT_TYPE_NIC,
+    .type = NET_CLIENT_OPTIONS_KIND_NIC,
     .size = sizeof(NICState),
     .can_receive = eth_can_rx,
     .receive = eth_rx,
diff --git a/net.c b/net.c
index abf0fd0..c46695f 100644
--- a/net.c
+++ b/net.c
@@ -239,7 +239,7 @@ NICState *qemu_new_nic(NetClientInfo *info,
     VLANClientState *nc;
     NICState *nic;
 
-    assert(info->type == NET_CLIENT_TYPE_NIC);
+    assert(info->type == NET_CLIENT_OPTIONS_KIND_NIC);
     assert(info->size >= sizeof(NICState));
 
     nc = qemu_new_net_client(info, conf->vlan, conf->peer, model, name);
@@ -282,7 +282,7 @@ static void qemu_free_vlan_client(VLANClientState *vc)
 void qemu_del_vlan_client(VLANClientState *vc)
 {
     /* If there is a peer NIC, delete and cleanup client, but do not free. */
-    if (!vc->vlan && vc->peer && vc->peer->info->type == NET_CLIENT_TYPE_NIC) {
+    if (!vc->vlan && vc->peer && vc->peer->info->type == NET_CLIENT_OPTIONS_KIND_NIC) {
         NICState *nic = DO_UPCAST(NICState, nc, vc->peer);
         if (nic->peer_deleted) {
             return;
@@ -298,7 +298,7 @@ void qemu_del_vlan_client(VLANClientState *vc)
     }
 
     /* If this is a peer NIC and peer has already been deleted, free it now. */
-    if (!vc->vlan && vc->peer && vc->info->type == NET_CLIENT_TYPE_NIC) {
+    if (!vc->vlan && vc->peer && vc->info->type == NET_CLIENT_OPTIONS_KIND_NIC) {
         NICState *nic = DO_UPCAST(NICState, nc, vc);
         if (nic->peer_deleted) {
             qemu_free_vlan_client(vc->peer);
@@ -341,14 +341,14 @@ void qemu_foreach_nic(qemu_nic_foreach func, void *opaque)
     VLANState *vlan;
 
     QTAILQ_FOREACH(nc, &non_vlan_clients, next) {
-        if (nc->info->type == NET_CLIENT_TYPE_NIC) {
+        if (nc->info->type == NET_CLIENT_OPTIONS_KIND_NIC) {
             func(DO_UPCAST(NICState, nc, nc), opaque);
         }
     }
 
     QTAILQ_FOREACH(vlan, &vlans, next) {
         QTAILQ_FOREACH(nc, &vlan->clients, next) {
-            if (nc->info->type == NET_CLIENT_TYPE_NIC) {
+            if (nc->info->type == NET_CLIENT_OPTIONS_KIND_NIC) {
                 func(DO_UPCAST(NICState, nc, nc), opaque);
             }
         }
@@ -664,7 +664,7 @@ VLANClientState *qemu_find_netdev(const char *id)
     VLANClientState *vc;
 
     QTAILQ_FOREACH(vc, &non_vlan_clients, next) {
-        if (vc->info->type == NET_CLIENT_TYPE_NIC)
+        if (vc->info->type == NET_CLIENT_OPTIONS_KIND_NIC)
             continue;
         if (!strcmp(vc->name, id)) {
             return vc;
@@ -828,15 +828,15 @@ static const struct {
     const char *type;
     net_client_init_func init;
     QemuOptDesc desc[NET_MAX_DESC];
-} net_client_types[NET_CLIENT_TYPE_MAX] = {
-    [NET_CLIENT_TYPE_NONE] = {
+} net_client_types[NET_CLIENT_OPTIONS_KIND_MAX] = {
+    [NET_CLIENT_OPTIONS_KIND_NONE] = {
         .type = "none",
         .desc = {
             NET_COMMON_PARAMS_DESC,
             { /* end of list */ }
         },
     },
-    [NET_CLIENT_TYPE_NIC] = {
+    [NET_CLIENT_OPTIONS_KIND_NIC] = {
         .type = "nic",
         .init = net_init_nic,
         .desc = {
@@ -867,7 +867,7 @@ static const struct {
         },
     },
 #ifdef CONFIG_SLIRP
-    [NET_CLIENT_TYPE_USER] = {
+    [NET_CLIENT_OPTIONS_KIND_USER] = {
         .type = "user",
         .init = net_init_slirp,
         .desc = {
@@ -929,7 +929,7 @@ static const struct {
         },
     },
 #endif
-    [NET_CLIENT_TYPE_TAP] = {
+    [NET_CLIENT_OPTIONS_KIND_TAP] = {
         .type = "tap",
         .init = net_init_tap,
         .desc = {
@@ -983,7 +983,7 @@ static const struct {
             { /* end of list */ }
         },
     },
-    [NET_CLIENT_TYPE_SOCKET] = {
+    [NET_CLIENT_OPTIONS_KIND_SOCKET] = {
         .type = "socket",
         .init = net_init_socket,
         .desc = {
@@ -1017,7 +1017,7 @@ static const struct {
         },
     },
 #ifdef CONFIG_VDE
-    [NET_CLIENT_TYPE_VDE] = {
+    [NET_CLIENT_OPTIONS_KIND_VDE] = {
         .type = "vde",
         .init = net_init_vde,
         .desc = {
@@ -1043,7 +1043,7 @@ static const struct {
         },
     },
 #endif
-    [NET_CLIENT_TYPE_DUMP] = {
+    [NET_CLIENT_OPTIONS_KIND_DUMP] = {
         .type = "dump",
         .init = net_init_dump,
         .desc = {
@@ -1061,7 +1061,7 @@ static const struct {
         },
     },
 #ifdef CONFIG_NET_BRIDGE
-    [NET_CLIENT_TYPE_BRIDGE] = {
+    [NET_CLIENT_OPTIONS_KIND_BRIDGE] = {
         .type = "bridge",
         .init = net_init_bridge,
         .desc = {
@@ -1129,7 +1129,7 @@ int net_client_init(QemuOpts *opts, int is_netdev, Error **errp)
         name = qemu_opt_get(opts, "name");
     }
 
-    for (i = 0; i < NET_CLIENT_TYPE_MAX; i++) {
+    for (i = 0; i < NET_CLIENT_OPTIONS_KIND_MAX; i++) {
         if (net_client_types[i].type != NULL &&
             !strcmp(net_client_types[i].type, type)) {
             Error *local_err = NULL;
@@ -1293,7 +1293,7 @@ void do_info_network(Monitor *mon)
 {
     VLANState *vlan;
     VLANClientState *vc, *peer;
-    net_client_type type;
+    NetClientOptionsKind type;
 
     QTAILQ_FOREACH(vlan, &vlans, next) {
         monitor_printf(mon, "VLAN %d devices:\n", vlan->id);
@@ -1307,11 +1307,11 @@ void do_info_network(Monitor *mon)
     QTAILQ_FOREACH(vc, &non_vlan_clients, next) {
         peer = vc->peer;
         type = vc->info->type;
-        if (!peer || type == NET_CLIENT_TYPE_NIC) {
+        if (!peer || type == NET_CLIENT_OPTIONS_KIND_NIC) {
             monitor_printf(mon, "  ");
             print_net_client(mon, vc);
         } /* else it's a netdev connected to a NIC, printed with the NIC */
-        if (peer && type == NET_CLIENT_TYPE_NIC) {
+        if (peer && type == NET_CLIENT_OPTIONS_KIND_NIC) {
             monitor_printf(mon, "   \\ ");
             print_net_client(mon, peer);
         }
@@ -1399,13 +1399,13 @@ void net_check_clients(void)
 
         QTAILQ_FOREACH(vc, &vlan->clients, next) {
             switch (vc->info->type) {
-            case NET_CLIENT_TYPE_NIC:
+            case NET_CLIENT_OPTIONS_KIND_NIC:
                 has_nic = 1;
                 break;
-            case NET_CLIENT_TYPE_USER:
-            case NET_CLIENT_TYPE_TAP:
-            case NET_CLIENT_TYPE_SOCKET:
-            case NET_CLIENT_TYPE_VDE:
+            case NET_CLIENT_OPTIONS_KIND_USER:
+            case NET_CLIENT_OPTIONS_KIND_TAP:
+            case NET_CLIENT_OPTIONS_KIND_SOCKET:
+            case NET_CLIENT_OPTIONS_KIND_VDE:
                 has_host_dev = 1;
                 break;
             default: ;
@@ -1421,7 +1421,7 @@ void net_check_clients(void)
     QTAILQ_FOREACH(vc, &non_vlan_clients, next) {
         if (!vc->peer) {
             fprintf(stderr, "Warning: %s %s has no peer\n",
-                    vc->info->type == NET_CLIENT_TYPE_NIC ? "nic" : "netdev",
+                    vc->info->type == NET_CLIENT_OPTIONS_KIND_NIC ? "nic" : "netdev",
                     vc->name);
         }
     }
diff --git a/net.h b/net.h
index bdc2a06..b0b8c7a 100644
--- a/net.h
+++ b/net.h
@@ -7,6 +7,7 @@
 #include "qemu-option.h"
 #include "net/queue.h"
 #include "vmstate.h"
+#include "qapi-types.h"
 
 struct MACAddr {
     uint8_t a[6];
@@ -29,19 +30,6 @@ typedef struct NICConf {
 
 /* VLANs support */
 
-typedef enum {
-    NET_CLIENT_TYPE_NONE,
-    NET_CLIENT_TYPE_NIC,
-    NET_CLIENT_TYPE_USER,
-    NET_CLIENT_TYPE_TAP,
-    NET_CLIENT_TYPE_SOCKET,
-    NET_CLIENT_TYPE_VDE,
-    NET_CLIENT_TYPE_DUMP,
-    NET_CLIENT_TYPE_BRIDGE,
-
-    NET_CLIENT_TYPE_MAX
-} net_client_type;
-
 typedef void (NetPoll)(VLANClientState *, bool enable);
 typedef int (NetCanReceive)(VLANClientState *);
 typedef ssize_t (NetReceive)(VLANClientState *, const uint8_t *, size_t);
@@ -50,7 +38,7 @@ typedef void (NetCleanup) (VLANClientState *);
 typedef void (LinkStatusChanged)(VLANClientState *);
 
 typedef struct NetClientInfo {
-    net_client_type type;
+    NetClientOptionsKind type;
     size_t size;
     NetReceive *receive;
     NetReceive *receive_raw;
diff --git a/net/dump.c b/net/dump.c
index f835c51..2124b9a 100644
--- a/net/dump.c
+++ b/net/dump.c
@@ -93,7 +93,7 @@ static void dump_cleanup(VLANClientState *nc)
 }
 
 static NetClientInfo net_dump_info = {
-    .type = NET_CLIENT_TYPE_DUMP,
+    .type = NET_CLIENT_OPTIONS_KIND_DUMP,
     .size = sizeof(DumpState),
     .receive = dump_receive,
     .cleanup = dump_cleanup,
diff --git a/net/slirp.c b/net/slirp.c
index b82eab0..1f63d50 100644
--- a/net/slirp.c
+++ b/net/slirp.c
@@ -129,7 +129,7 @@ static void net_slirp_cleanup(VLANClientState *nc)
 }
 
 static NetClientInfo net_slirp_info = {
-    .type = NET_CLIENT_TYPE_USER,
+    .type = NET_CLIENT_OPTIONS_KIND_USER,
     .size = sizeof(SlirpState),
     .receive = net_slirp_receive,
     .cleanup = net_slirp_cleanup,
diff --git a/net/socket.c b/net/socket.c
index fcd0a3c..30536ef 100644
--- a/net/socket.c
+++ b/net/socket.c
@@ -239,7 +239,7 @@ static void net_socket_cleanup(VLANClientState *nc)
 }
 
 static NetClientInfo net_dgram_socket_info = {
-    .type = NET_CLIENT_TYPE_SOCKET,
+    .type = NET_CLIENT_OPTIONS_KIND_SOCKET,
     .size = sizeof(NetSocketState),
     .receive = net_socket_receive_dgram,
     .cleanup = net_socket_cleanup,
@@ -317,7 +317,7 @@ static void net_socket_connect(void *opaque)
 }
 
 static NetClientInfo net_socket_info = {
-    .type = NET_CLIENT_TYPE_SOCKET,
+    .type = NET_CLIENT_OPTIONS_KIND_SOCKET,
     .size = sizeof(NetSocketState),
     .receive = net_socket_receive,
     .cleanup = net_socket_cleanup,
diff --git a/net/tap-win32.c b/net/tap-win32.c
index a801a55..f7b6129 100644
--- a/net/tap-win32.c
+++ b/net/tap-win32.c
@@ -667,7 +667,7 @@ static void tap_win32_send(void *opaque)
 }
 
 static NetClientInfo net_tap_win32_info = {
-    .type = NET_CLIENT_TYPE_TAP,
+    .type = NET_CLIENT_OPTIONS_KIND_TAP,
     .size = sizeof(TAPState),
     .receive = tap_receive,
     .cleanup = tap_cleanup,
diff --git a/net/tap.c b/net/tap.c
index 17e9135..9131ef5 100644
--- a/net/tap.c
+++ b/net/tap.c
@@ -218,7 +218,7 @@ int tap_has_ufo(VLANClientState *nc)
 {
     TAPState *s = DO_UPCAST(TAPState, nc, nc);
 
-    assert(nc->info->type == NET_CLIENT_TYPE_TAP);
+    assert(nc->info->type == NET_CLIENT_OPTIONS_KIND_TAP);
 
     return s->has_ufo;
 }
@@ -227,7 +227,7 @@ int tap_has_vnet_hdr(VLANClientState *nc)
 {
     TAPState *s = DO_UPCAST(TAPState, nc, nc);
 
-    assert(nc->info->type == NET_CLIENT_TYPE_TAP);
+    assert(nc->info->type == NET_CLIENT_OPTIONS_KIND_TAP);
 
     return !!s->host_vnet_hdr_len;
 }
@@ -236,7 +236,7 @@ int tap_has_vnet_hdr_len(VLANClientState *nc, int len)
 {
     TAPState *s = DO_UPCAST(TAPState, nc, nc);
 
-    assert(nc->info->type == NET_CLIENT_TYPE_TAP);
+    assert(nc->info->type == NET_CLIENT_OPTIONS_KIND_TAP);
 
     return tap_probe_vnet_hdr_len(s->fd, len);
 }
@@ -245,7 +245,7 @@ void tap_set_vnet_hdr_len(VLANClientState *nc, int len)
 {
     TAPState *s = DO_UPCAST(TAPState, nc, nc);
 
-    assert(nc->info->type == NET_CLIENT_TYPE_TAP);
+    assert(nc->info->type == NET_CLIENT_OPTIONS_KIND_TAP);
     assert(len == sizeof(struct virtio_net_hdr_mrg_rxbuf) ||
            len == sizeof(struct virtio_net_hdr));
 
@@ -259,7 +259,7 @@ void tap_using_vnet_hdr(VLANClientState *nc, int using_vnet_hdr)
 
     using_vnet_hdr = using_vnet_hdr != 0;
 
-    assert(nc->info->type == NET_CLIENT_TYPE_TAP);
+    assert(nc->info->type == NET_CLIENT_OPTIONS_KIND_TAP);
     assert(!!s->host_vnet_hdr_len == using_vnet_hdr);
 
     s->using_vnet_hdr = using_vnet_hdr;
@@ -306,14 +306,14 @@ static void tap_poll(VLANClientState *nc, bool enable)
 int tap_get_fd(VLANClientState *nc)
 {
     TAPState *s = DO_UPCAST(TAPState, nc, nc);
-    assert(nc->info->type == NET_CLIENT_TYPE_TAP);
+    assert(nc->info->type == NET_CLIENT_OPTIONS_KIND_TAP);
     return s->fd;
 }
 
 /* fd support */
 
 static NetClientInfo net_tap_info = {
-    .type = NET_CLIENT_TYPE_TAP,
+    .type = NET_CLIENT_OPTIONS_KIND_TAP,
     .size = sizeof(TAPState),
     .receive = tap_receive,
     .receive_raw = tap_receive_raw,
@@ -711,6 +711,6 @@ int net_init_tap(QemuOpts *opts, const char *name, VLANState *vlan)
 VHostNetState *tap_get_vhost_net(VLANClientState *nc)
 {
     TAPState *s = DO_UPCAST(TAPState, nc, nc);
-    assert(nc->info->type == NET_CLIENT_TYPE_TAP);
+    assert(nc->info->type == NET_CLIENT_OPTIONS_KIND_TAP);
     return s->vhost_net;
 }
diff --git a/net/vde.c b/net/vde.c
index 6b9d452..0e8bf23 100644
--- a/net/vde.c
+++ b/net/vde.c
@@ -69,7 +69,7 @@ static void vde_cleanup(VLANClientState *nc)
 }
 
 static NetClientInfo net_vde_info = {
-    .type = NET_CLIENT_TYPE_VDE,
+    .type = NET_CLIENT_OPTIONS_KIND_VDE,
     .size = sizeof(VDEState),
     .receive = vde_receive,
     .cleanup = vde_cleanup,
commit 14aa0c2de045a6c2fcfadf38c04434fd15909455
Author: Laszlo Ersek <lersek at redhat.com>
Date:   Tue Jul 17 16:17:11 2012 +0200

    qapi schema: add Netdev types
    
    NetdevTapOptions::sndbuf and NetdevDumpOptions::len use the new "size"
    type.
    
    v1->v2:
    - NetLegacy::name is optional
    - NetLegacyNicOptions::vectors is of type uint32
    - NetdevVdeOptions::port and ::mode are of type uint16
    - NetLegacy::vlan has type int32
    
    v2->v3:
    - NetLegacy::id is allowed and takes precedence over NetLegacy::name
    - replace "@traits" with "@opts" in NetLegacy & Netdev descriptions
    
    Signed-off-by: Laszlo Ersek <lersek at redhat.com>
    Signed-off-by: Stefan Hajnoczi <stefanha at linux.vnet.ibm.com>

diff --git a/qapi-schema.json b/qapi-schema.json
index d2f8e02..bc55ed2 100644
--- a/qapi-schema.json
+++ b/qapi-schema.json
@@ -1872,6 +1872,284 @@
 { 'command': 'netdev_del', 'data': {'id': 'str'} }
 
 ##
+# @NetdevNoneOptions
+#
+# Use it alone to have zero network devices.
+#
+# Since 1.2
+##
+{ 'type': 'NetdevNoneOptions',
+  'data': { } }
+
+##
+# @NetLegacyNicOptions
+#
+# Create a new Network Interface Card.
+#
+# @netdev: #optional id of -netdev to connect to
+#
+# @macaddr: #optional MAC address
+#
+# @model: #optional device model (e1000, rtl8139, virtio etc.)
+#
+# @addr: #optional PCI device address
+#
+# @vectors: #optional number of MSI-x vectors, 0 to disable MSI-X
+#
+# Since 1.2
+##
+{ 'type': 'NetLegacyNicOptions',
+  'data': {
+    '*netdev':  'str',
+    '*macaddr': 'str',
+    '*model':   'str',
+    '*addr':    'str',
+    '*vectors': 'uint32' } }
+
+##
+# @String
+#
+# A fat type wrapping 'str', to be embedded in lists.
+#
+# Since 1.2
+##
+{ 'type': 'String',
+  'data': {
+    'str': 'str' } }
+
+##
+# @NetdevUserOptions
+#
+# Use the user mode network stack which requires no administrator privilege to
+# run.
+#
+# @hostname: #optional client hostname reported by the builtin DHCP server
+#
+# @restrict: #optional isolate the guest from the host
+#
+# @ip: #optional legacy parameter, use net= instead
+#
+# @net: #optional IP address and optional netmask
+#
+# @host: #optional guest-visible address of the host
+#
+# @tftp: #optional root directory of the built-in TFTP server
+#
+# @bootfile: #optional BOOTP filename, for use with tftp=
+#
+# @dhcpstart: #optional the first of the 16 IPs the built-in DHCP server can
+#             assign
+#
+# @dns: #optional guest-visible address of the virtual nameserver
+#
+# @smb: #optional root directory of the built-in SMB server
+#
+# @smbserver: #optional IP address of the built-in SMB server
+#
+# @hostfwd: #optional redirect incoming TCP or UDP host connections to guest
+#           endpoints
+#
+# @guestfwd: #optional forward guest TCP connections
+#
+# Since 1.2
+##
+{ 'type': 'NetdevUserOptions',
+  'data': {
+    '*hostname':  'str',
+    '*restrict':  'bool',
+    '*ip':        'str',
+    '*net':       'str',
+    '*host':      'str',
+    '*tftp':      'str',
+    '*bootfile':  'str',
+    '*dhcpstart': 'str',
+    '*dns':       'str',
+    '*smb':       'str',
+    '*smbserver': 'str',
+    '*hostfwd':   ['String'],
+    '*guestfwd':  ['String'] } }
+
+##
+# @NetdevTapOptions
+#
+# Connect the host TAP network interface name to the VLAN.
+#
+# @ifname: #optional interface name
+#
+# @fd: #optional file descriptor of an already opened tap
+#
+# @script: #optional script to initialize the interface
+#
+# @downscript: #optional script to shut down the interface
+#
+# @helper: #optional command to execute to configure bridge
+#
+# @sndbuf: #optional send buffer limit. Understands [TGMKkb] suffixes.
+#
+# @vnet_hdr: #optional enable the IFF_VNET_HDR flag on the tap interface
+#
+# @vhost: #optional enable vhost-net network accelerator
+#
+# @vhostfd: #optional file descriptor of an already opened vhost net device
+#
+# @vhostforce: #optional vhost on for non-MSIX virtio guests
+#
+# Since 1.2
+##
+{ 'type': 'NetdevTapOptions',
+  'data': {
+    '*ifname':     'str',
+    '*fd':         'str',
+    '*script':     'str',
+    '*downscript': 'str',
+    '*helper':     'str',
+    '*sndbuf':     'size',
+    '*vnet_hdr':   'bool',
+    '*vhost':      'bool',
+    '*vhostfd':    'str',
+    '*vhostforce': 'bool' } }
+
+##
+# @NetdevSocketOptions
+#
+# Connect the VLAN to a remote VLAN in another QEMU virtual machine using a TCP
+# socket connection.
+#
+# @fd: #optional file descriptor of an already opened socket
+#
+# @listen: #optional port number, and optional hostname, to listen on
+#
+# @connect: #optional port number, and optional hostname, to connect to
+#
+# @mcast: #optional UDP multicast address and port number
+#
+# @localaddr: #optional source address and port for multicast and udp packets
+#
+# @udp: #optional UDP unicast address and port number
+#
+# Since 1.2
+##
+{ 'type': 'NetdevSocketOptions',
+  'data': {
+    '*fd':        'str',
+    '*listen':    'str',
+    '*connect':   'str',
+    '*mcast':     'str',
+    '*localaddr': 'str',
+    '*udp':       'str' } }
+
+##
+# @NetdevVdeOptions
+#
+# Connect the VLAN to a vde switch running on the host.
+#
+# @sock: #optional socket path
+#
+# @port: #optional port number
+#
+# @group: #optional group owner of socket
+#
+# @mode: #optional permissions for socket
+#
+# Since 1.2
+##
+{ 'type': 'NetdevVdeOptions',
+  'data': {
+    '*sock':  'str',
+    '*port':  'uint16',
+    '*group': 'str',
+    '*mode':  'uint16' } }
+
+##
+# @NetdevDumpOptions
+#
+# Dump VLAN network traffic to a file.
+#
+# @len: #optional per-packet size limit (64k default). Understands [TGMKkb]
+# suffixes.
+#
+# @file: #optional dump file path (default is qemu-vlan0.pcap)
+#
+# Since 1.2
+##
+{ 'type': 'NetdevDumpOptions',
+  'data': {
+    '*len':  'size',
+    '*file': 'str' } }
+
+##
+# @NetdevBridgeOptions
+#
+# Connect a host TAP network interface to a host bridge device.
+#
+# @br: #optional bridge name
+#
+# @helper: #optional command to execute to configure bridge
+#
+# Since 1.2
+##
+{ 'type': 'NetdevBridgeOptions',
+  'data': {
+    '*br':     'str',
+    '*helper': 'str' } }
+
+##
+# @NetClientOptions
+#
+# A discriminated record of network device traits.
+#
+# Since 1.2
+##
+{ 'union': 'NetClientOptions',
+  'data': {
+    'none':   'NetdevNoneOptions',
+    'nic':    'NetLegacyNicOptions',
+    'user':   'NetdevUserOptions',
+    'tap':    'NetdevTapOptions',
+    'socket': 'NetdevSocketOptions',
+    'vde':    'NetdevVdeOptions',
+    'dump':   'NetdevDumpOptions',
+    'bridge': 'NetdevBridgeOptions' } }
+
+##
+# @NetLegacy
+#
+# Captures the configuration of a network device; legacy.
+#
+# @vlan: #optional vlan number
+#
+# @id: #optional identifier for monitor commands
+#
+# @name: #optional identifier for monitor commands, ignored if @id is present
+#
+# @opts: device type specific properties (legacy)
+#
+# Since 1.2
+##
+{ 'type': 'NetLegacy',
+  'data': {
+    '*vlan': 'int32',
+    '*id':   'str',
+    '*name': 'str',
+    'opts':  'NetClientOptions' } }
+
+##
+# @Netdev
+#
+# Captures the configuration of a network device.
+#
+# @id: identifier for monitor commands.
+#
+# @opts: device type specific properties
+#
+# Since 1.2
+##
+{ 'type': 'Netdev',
+  'data': {
+    'id':   'str',
+    'opts': 'NetClientOptions' } }
+
+##
 # @getfd:
 #
 # Receive a file descriptor via SCM rights and assign it a name
commit b80e560bd1c1a69839730130572504c91087bc6c
Author: Laszlo Ersek <lersek at redhat.com>
Date:   Tue Jul 17 16:17:10 2012 +0200

    qapi schema: remove trailing whitespace
    
    Signed-off-by: Laszlo Ersek <lersek at redhat.com>
    Signed-off-by: Stefan Hajnoczi <stefanha at linux.vnet.ibm.com>

diff --git a/qapi-schema.json b/qapi-schema.json
index a92adb1..d2f8e02 100644
--- a/qapi-schema.json
+++ b/qapi-schema.json
@@ -343,7 +343,7 @@
 # @CPU: the index of the virtual CPU
 #
 # @current: this only exists for backwards compatible and should be ignored
-# 
+#
 # @halted: true if the virtual CPU is in the halt state.  Halt usually refers
 #          to a processor specific low power mode.
 #
@@ -686,7 +686,7 @@
 # @SpiceInfo
 #
 # Information about the SPICE session.
-# 
+#
 # @enabled: true if the SPICE server is enabled, false otherwise
 #
 # @host: #optional The hostname the SPICE server is bound to.  This depends on
@@ -1297,7 +1297,7 @@
 ##
 { 'command': 'human-monitor-command',
   'data': {'command-line': 'str', '*cpu-index': 'int'},
-  'returns': 'str' } 
+  'returns': 'str' }
 
 ##
 # @migrate_cancel
@@ -1458,7 +1458,7 @@
 # @password: the new password
 #
 # @connected: #optional how to handle existing clients when changing the
-#                       password.  If nothing is specified, defaults to `keep' 
+#                       password.  If nothing is specified, defaults to `keep'
 #                       `fail' to fail the command if clients are connected
 #                       `disconnect' to disconnect existing clients
 #                       `keep' to maintain existing clients
@@ -1598,7 +1598,7 @@
 #          If the argument combination is invalid, InvalidParameterCombination
 #
 # Since: 1.1
-## 
+##
 { 'command': 'block_set_io_throttle',
   'data': { 'device': 'str', 'bps': 'int', 'bps_rd': 'int', 'bps_wr': 'int',
             'iops': 'int', 'iops_rd': 'int', 'iops_wr': 'int' } }
commit eb7ee2cbebe4ac9e687d5fb3c104f0220d26cdfc
Author: Laszlo Ersek <lersek at redhat.com>
Date:   Tue Jul 17 16:17:09 2012 +0200

    qapi: introduce OptsVisitor
    
    This visitor supports parsing
    
      -option [type=]discriminator[,optarg1=val1][,optarg2=val2][,...]
    
    style QemuOpts objects into "native" C structures. After defining the type
    tree in the qapi schema (see below), a root type traversal with this
    visitor linked to the underlying QemuOpts object will build the "native" C
    representation of the option.
    
    The type tree in the schema, corresponding to an option with a
    discriminator, must have the following structure:
    
      struct
        scalar member for non-discriminated optarg 1 [*]
        list for repeating non-discriminated optarg 2 [*]
          wrapper struct
            single scalar member
        union
          struct for discriminator case 1
            scalar member for optarg 3 [*]
            list for repeating optarg 4 [*]
              wrapper struct
                single scalar member
            scalar member for optarg 5 [*]
          struct for discriminator case 2
            ...
    
    The "type" optarg name is fixed for the discriminator role. Its schema
    representation is "union of structures", and each discriminator value must
    correspond to a member name in the union.
    
    If the option takes no "type" descriminator, then the type subtree rooted
    at the union must be absent from the schema (including the union itself).
    
    Optarg values can be of scalar types str / bool / integers / size.
    
    Members marked with [*] may be defined as optional in the schema,
    describing an optional optarg.
    
    Repeating an optarg is supported; its schema representation must be "list
    of structure with single mandatory scalar member". If an optarg is not
    described as repeating in the schema (ie. it is defined as a scalar field
    instead of a list), its last occurrence will take effect. Ordering between
    differently named optargs is not preserved.
    
    A mandatory list (or an optional one which is reported to be available),
    corresponding to a repeating optarg, has at least one element after
    successful parsing.
    
    v1->v2:
    - Update opts_type_size() prototype to uint64_t.
    - Add opts_type_uint64() for options needing the full uint64_t range.
      (Internals could be extracted to "cutils.c".)
    - Allow negative values in opts_type_int().
    - Rebase to nested Makefiles.
    
    v2->v3:
    - Factor opts_visitor_insert() out of opts_start_struct() and call it
      separately for opts_root->id if there's any.
    - Don't require non-negative values in opts_type_int()'s error message.
    - g_malloc0() may return NULL for zero-sized requests. Support empty
      structures by requesting 1 byte for them instead.
    
    Signed-off-by: Laszlo Ersek <lersek at redhat.com>
    Signed-off-by: Stefan Hajnoczi <stefanha at linux.vnet.ibm.com>

diff --git a/qapi/Makefile.objs b/qapi/Makefile.objs
index d0b0c16..5f5846e 100644
--- a/qapi/Makefile.objs
+++ b/qapi/Makefile.objs
@@ -1,3 +1,3 @@
 qapi-obj-y = qapi-visit-core.o qapi-dealloc-visitor.o qmp-input-visitor.o
 qapi-obj-y += qmp-output-visitor.o qmp-registry.o qmp-dispatch.o
-qapi-obj-y += string-input-visitor.o string-output-visitor.o
+qapi-obj-y += string-input-visitor.o string-output-visitor.o opts-visitor.o
diff --git a/qapi/opts-visitor.c b/qapi/opts-visitor.c
new file mode 100644
index 0000000..a59d306
--- /dev/null
+++ b/qapi/opts-visitor.c
@@ -0,0 +1,427 @@
+/*
+ * Options Visitor
+ *
+ * Copyright Red Hat, Inc. 2012
+ *
+ * Author: Laszlo Ersek <lersek at redhat.com>
+ *
+ * This work is licensed under the terms of the GNU LGPL, version 2.1 or later.
+ * See the COPYING.LIB file in the top-level directory.
+ *
+ */
+
+#include "opts-visitor.h"
+#include "qemu-queue.h"
+#include "qemu-option-internal.h"
+#include "qapi-visit-impl.h"
+
+
+struct OptsVisitor
+{
+    Visitor visitor;
+
+    /* Ownership remains with opts_visitor_new()'s caller. */
+    const QemuOpts *opts_root;
+
+    unsigned depth;
+
+    /* Non-null iff depth is positive. Each key is a QemuOpt name. Each value
+     * is a non-empty GQueue, enumerating all QemuOpt occurrences with that
+     * name. */
+    GHashTable *unprocessed_opts;
+
+    /* The list currently being traversed with opts_start_list() /
+     * opts_next_list(). The list must have a struct element type in the
+     * schema, with a single mandatory scalar member. */
+    GQueue *repeated_opts;
+    bool repeated_opts_first;
+
+    /* If "opts_root->id" is set, reinstantiate it as a fake QemuOpt for
+     * uniformity. Only its "name" and "str" fields are set. "fake_id_opt" does
+     * not survive or escape the OptsVisitor object.
+     */
+    QemuOpt *fake_id_opt;
+};
+
+
+static void
+destroy_list(gpointer list)
+{
+  g_queue_free(list);
+}
+
+
+static void
+opts_visitor_insert(GHashTable *unprocessed_opts, const QemuOpt *opt)
+{
+    GQueue *list;
+
+    list = g_hash_table_lookup(unprocessed_opts, opt->name);
+    if (list == NULL) {
+        list = g_queue_new();
+
+        /* GHashTable will never try to free the keys -- we supply NULL as
+         * "key_destroy_func" in opts_start_struct(). Thus cast away key
+         * const-ness in order to suppress gcc's warning.
+         */
+        g_hash_table_insert(unprocessed_opts, (gpointer)opt->name, list);
+    }
+
+    /* Similarly, destroy_list() doesn't call g_queue_free_full(). */
+    g_queue_push_tail(list, (gpointer)opt);
+}
+
+
+static void
+opts_start_struct(Visitor *v, void **obj, const char *kind,
+                  const char *name, size_t size, Error **errp)
+{
+    OptsVisitor *ov = DO_UPCAST(OptsVisitor, visitor, v);
+    const QemuOpt *opt;
+
+    *obj = g_malloc0(size > 0 ? size : 1);
+    if (ov->depth++ > 0) {
+        return;
+    }
+
+    ov->unprocessed_opts = g_hash_table_new_full(&g_str_hash, &g_str_equal,
+                                                 NULL, &destroy_list);
+    QTAILQ_FOREACH(opt, &ov->opts_root->head, next) {
+        /* ensured by qemu-option.c::opts_do_parse() */
+        assert(strcmp(opt->name, "id") != 0);
+
+        opts_visitor_insert(ov->unprocessed_opts, opt);
+    }
+
+    if (ov->opts_root->id != NULL) {
+        ov->fake_id_opt = g_malloc0(sizeof *ov->fake_id_opt);
+
+        ov->fake_id_opt->name = "id";
+        ov->fake_id_opt->str = ov->opts_root->id;
+        opts_visitor_insert(ov->unprocessed_opts, ov->fake_id_opt);
+    }
+}
+
+
+static gboolean
+ghr_true(gpointer ign_key, gpointer ign_value, gpointer ign_user_data)
+{
+    return TRUE;
+}
+
+
+static void
+opts_end_struct(Visitor *v, Error **errp)
+{
+    OptsVisitor *ov = DO_UPCAST(OptsVisitor, visitor, v);
+    GQueue *any;
+
+    if (--ov->depth > 0) {
+        return;
+    }
+
+    /* we should have processed all (distinct) QemuOpt instances */
+    any = g_hash_table_find(ov->unprocessed_opts, &ghr_true, NULL);
+    if (any) {
+        const QemuOpt *first;
+
+        first = g_queue_peek_head(any);
+        error_set(errp, QERR_INVALID_PARAMETER, first->name);
+    }
+    g_hash_table_destroy(ov->unprocessed_opts);
+    ov->unprocessed_opts = NULL;
+    g_free(ov->fake_id_opt);
+    ov->fake_id_opt = NULL;
+}
+
+
+static GQueue *
+lookup_distinct(const OptsVisitor *ov, const char *name, Error **errp)
+{
+    GQueue *list;
+
+    list = g_hash_table_lookup(ov->unprocessed_opts, name);
+    if (!list) {
+        error_set(errp, QERR_MISSING_PARAMETER, name);
+    }
+    return list;
+}
+
+
+static void
+opts_start_list(Visitor *v, const char *name, Error **errp)
+{
+    OptsVisitor *ov = DO_UPCAST(OptsVisitor, visitor, v);
+
+    /* we can't traverse a list in a list */
+    assert(ov->repeated_opts == NULL);
+    ov->repeated_opts = lookup_distinct(ov, name, errp);
+    ov->repeated_opts_first = (ov->repeated_opts != NULL);
+}
+
+
+static GenericList *
+opts_next_list(Visitor *v, GenericList **list, Error **errp)
+{
+    OptsVisitor *ov = DO_UPCAST(OptsVisitor, visitor, v);
+    GenericList **link;
+
+    if (ov->repeated_opts_first) {
+        ov->repeated_opts_first = false;
+        link = list;
+    } else {
+        const QemuOpt *opt;
+
+        opt = g_queue_pop_head(ov->repeated_opts);
+        if (g_queue_is_empty(ov->repeated_opts)) {
+            g_hash_table_remove(ov->unprocessed_opts, opt->name);
+            return NULL;
+        }
+        link = &(*list)->next;
+    }
+
+    *link = g_malloc0(sizeof **link);
+    return *link;
+}
+
+
+static void
+opts_end_list(Visitor *v, Error **errp)
+{
+    OptsVisitor *ov = DO_UPCAST(OptsVisitor, visitor, v);
+
+    ov->repeated_opts = NULL;
+}
+
+
+static const QemuOpt *
+lookup_scalar(const OptsVisitor *ov, const char *name, Error **errp)
+{
+    if (ov->repeated_opts == NULL) {
+        GQueue *list;
+
+        /* the last occurrence of any QemuOpt takes effect when queried by name
+         */
+        list = lookup_distinct(ov, name, errp);
+        return list ? g_queue_peek_tail(list) : NULL;
+    }
+    return g_queue_peek_head(ov->repeated_opts);
+}
+
+
+static void
+processed(OptsVisitor *ov, const char *name)
+{
+    if (ov->repeated_opts == NULL) {
+        g_hash_table_remove(ov->unprocessed_opts, name);
+    }
+}
+
+
+static void
+opts_type_str(Visitor *v, char **obj, const char *name, Error **errp)
+{
+    OptsVisitor *ov = DO_UPCAST(OptsVisitor, visitor, v);
+    const QemuOpt *opt;
+
+    opt = lookup_scalar(ov, name, errp);
+    if (!opt) {
+        return;
+    }
+    *obj = g_strdup(opt->str ? opt->str : "");
+    processed(ov, name);
+}
+
+
+/* mimics qemu-option.c::parse_option_bool() */
+static void
+opts_type_bool(Visitor *v, bool *obj, const char *name, Error **errp)
+{
+    OptsVisitor *ov = DO_UPCAST(OptsVisitor, visitor, v);
+    const QemuOpt *opt;
+
+    opt = lookup_scalar(ov, name, errp);
+    if (!opt) {
+        return;
+    }
+
+    if (opt->str) {
+        if (strcmp(opt->str, "on") == 0 ||
+            strcmp(opt->str, "yes") == 0 ||
+            strcmp(opt->str, "y") == 0) {
+            *obj = true;
+        } else if (strcmp(opt->str, "off") == 0 ||
+            strcmp(opt->str, "no") == 0 ||
+            strcmp(opt->str, "n") == 0) {
+            *obj = false;
+        } else {
+            error_set(errp, QERR_INVALID_PARAMETER_VALUE, opt->name,
+                "on|yes|y|off|no|n");
+            return;
+        }
+    } else {
+        *obj = true;
+    }
+
+    processed(ov, name);
+}
+
+
+static void
+opts_type_int(Visitor *v, int64_t *obj, const char *name, Error **errp)
+{
+    OptsVisitor *ov = DO_UPCAST(OptsVisitor, visitor, v);
+    const QemuOpt *opt;
+    const char *str;
+    long long val;
+    char *endptr;
+
+    opt = lookup_scalar(ov, name, errp);
+    if (!opt) {
+        return;
+    }
+    str = opt->str ? opt->str : "";
+
+    errno = 0;
+    val = strtoll(str, &endptr, 0);
+    if (*str != '\0' && *endptr == '\0' && errno == 0 && INT64_MIN <= val &&
+        val <= INT64_MAX) {
+        *obj = val;
+        processed(ov, name);
+        return;
+    }
+    error_set(errp, QERR_INVALID_PARAMETER_VALUE, opt->name, "an int64 value");
+}
+
+
+static void
+opts_type_uint64(Visitor *v, uint64_t *obj, const char *name, Error **errp)
+{
+    OptsVisitor *ov = DO_UPCAST(OptsVisitor, visitor, v);
+    const QemuOpt *opt;
+    const char *str;
+
+    opt = lookup_scalar(ov, name, errp);
+    if (!opt) {
+        return;
+    }
+
+    str = opt->str;
+    if (str != NULL) {
+        while (isspace((unsigned char)*str)) {
+            ++str;
+        }
+
+        if (*str != '-' && *str != '\0') {
+            unsigned long long val;
+            char *endptr;
+
+            /* non-empty, non-negative subject sequence */
+            errno = 0;
+            val = strtoull(str, &endptr, 0);
+            if (*endptr == '\0' && errno == 0 && val <= UINT64_MAX) {
+                *obj = val;
+                processed(ov, name);
+                return;
+            }
+        }
+    }
+    error_set(errp, QERR_INVALID_PARAMETER_VALUE, opt->name,
+              "an uint64 value");
+}
+
+
+static void
+opts_type_size(Visitor *v, uint64_t *obj, const char *name, Error **errp)
+{
+    OptsVisitor *ov = DO_UPCAST(OptsVisitor, visitor, v);
+    const QemuOpt *opt;
+    int64_t val;
+    char *endptr;
+
+    opt = lookup_scalar(ov, name, errp);
+    if (!opt) {
+        return;
+    }
+
+    val = strtosz_suffix(opt->str ? opt->str : "", &endptr,
+                         STRTOSZ_DEFSUFFIX_B);
+    if (val != -1 && *endptr == '\0') {
+        *obj = val;
+        processed(ov, name);
+        return;
+    }
+    error_set(errp, QERR_INVALID_PARAMETER_VALUE, opt->name,
+              "a size value representible as a non-negative int64");
+}
+
+
+static void
+opts_start_optional(Visitor *v, bool *present, const char *name,
+                       Error **errp)
+{
+    OptsVisitor *ov = DO_UPCAST(OptsVisitor, visitor, v);
+
+    /* we only support a single mandatory scalar field in a list node */
+    assert(ov->repeated_opts == NULL);
+    *present = (lookup_distinct(ov, name, NULL) != NULL);
+}
+
+
+OptsVisitor *
+opts_visitor_new(const QemuOpts *opts)
+{
+    OptsVisitor *ov;
+
+    ov = g_malloc0(sizeof *ov);
+
+    ov->visitor.start_struct = &opts_start_struct;
+    ov->visitor.end_struct   = &opts_end_struct;
+
+    ov->visitor.start_list = &opts_start_list;
+    ov->visitor.next_list  = &opts_next_list;
+    ov->visitor.end_list   = &opts_end_list;
+
+    /* input_type_enum() covers both "normal" enums and union discriminators.
+     * The union discriminator field is always generated as "type"; it should
+     * match the "type" QemuOpt child of any QemuOpts.
+     *
+     * input_type_enum() will remove the looked-up key from the
+     * "unprocessed_opts" hash even if the lookup fails, because the removal is
+     * done earlier in opts_type_str(). This should be harmless.
+     */
+    ov->visitor.type_enum = &input_type_enum;
+
+    ov->visitor.type_int    = &opts_type_int;
+    ov->visitor.type_uint64 = &opts_type_uint64;
+    ov->visitor.type_size   = &opts_type_size;
+    ov->visitor.type_bool   = &opts_type_bool;
+    ov->visitor.type_str    = &opts_type_str;
+
+    /* type_number() is not filled in, but this is not the first visitor to
+     * skip some mandatory methods... */
+
+    ov->visitor.start_optional = &opts_start_optional;
+
+    ov->opts_root = opts;
+
+    return ov;
+}
+
+
+void
+opts_visitor_cleanup(OptsVisitor *ov)
+{
+    if (ov->unprocessed_opts != NULL) {
+        g_hash_table_destroy(ov->unprocessed_opts);
+    }
+    g_free(ov->fake_id_opt);
+    memset(ov, '\0', sizeof *ov);
+}
+
+
+Visitor *
+opts_get_visitor(OptsVisitor *ov)
+{
+    return &ov->visitor;
+}
diff --git a/qapi/opts-visitor.h b/qapi/opts-visitor.h
new file mode 100644
index 0000000..ea1a395
--- /dev/null
+++ b/qapi/opts-visitor.h
@@ -0,0 +1,31 @@
+/*
+ * Options Visitor
+ *
+ * Copyright Red Hat, Inc. 2012
+ *
+ * Author: Laszlo Ersek <lersek at redhat.com>
+ *
+ * This work is licensed under the terms of the GNU LGPL, version 2.1 or later.
+ * See the COPYING.LIB file in the top-level directory.
+ *
+ */
+
+#ifndef OPTS_VISITOR_H
+#define OPTS_VISITOR_H
+
+#include "qapi-visit-core.h"
+#include "qemu-option.h"
+
+typedef struct OptsVisitor OptsVisitor;
+
+/* Contrarily to qemu-option.c::parse_option_number(), OptsVisitor's "int"
+ * parser relies on strtoll() instead of strtoull(). Consequences:
+ * - string representations of negative numbers yield negative values,
+ * - values below INT64_MIN or LLONG_MIN are rejected,
+ * - values above INT64_MAX or LLONG_MAX are rejected.
+ */
+OptsVisitor *opts_visitor_new(const QemuOpts *opts);
+void opts_visitor_cleanup(OptsVisitor *nv);
+Visitor *opts_get_visitor(OptsVisitor *nv);
+
+#endif
commit fdb17976fc1b8cff02b52b1054562d220b9208c7
Author: Laszlo Ersek <lersek at redhat.com>
Date:   Tue Jul 17 16:17:08 2012 +0200

    expose QemuOpt and QemuOpts struct definitions to interested parties
    
    The only clients should be the existent "qemu-option.c", and the upcoming
    "qapi/opts-visitor.c".
    
    Signed-off-by: Laszlo Ersek <lersek at redhat.com>
    Signed-off-by: Stefan Hajnoczi <stefanha at linux.vnet.ibm.com>

diff --git a/qemu-option-internal.h b/qemu-option-internal.h
new file mode 100644
index 0000000..19fdc1c
--- /dev/null
+++ b/qemu-option-internal.h
@@ -0,0 +1,53 @@
+/*
+ * Commandline option parsing functions
+ *
+ * Copyright (c) 2003-2008 Fabrice Bellard
+ * Copyright (c) 2009 Kevin Wolf <kwolf at redhat.com>
+ *
+ * Permission is hereby granted, free of charge, to any person obtaining a copy
+ * of this software and associated documentation files (the "Software"), to deal
+ * in the Software without restriction, including without limitation the rights
+ * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+ * copies of the Software, and to permit persons to whom the Software is
+ * furnished to do so, subject to the following conditions:
+ *
+ * The above copyright notice and this permission notice shall be included in
+ * all copies or substantial portions of the Software.
+ *
+ * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+ * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+ * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
+ * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+ * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
+ * THE SOFTWARE.
+ */
+
+#ifndef QEMU_OPTIONS_INTERNAL_H
+#define QEMU_OPTIONS_INTERNAL_H
+
+#include "qemu-option.h"
+
+struct QemuOpt {
+    const char   *name;
+    const char   *str;
+
+    const QemuOptDesc *desc;
+    union {
+        bool boolean;
+        uint64_t uint;
+    } value;
+
+    QemuOpts     *opts;
+    QTAILQ_ENTRY(QemuOpt) next;
+};
+
+struct QemuOpts {
+    char *id;
+    QemuOptsList *list;
+    Location loc;
+    QTAILQ_HEAD(QemuOptHead, QemuOpt) head;
+    QTAILQ_ENTRY(QemuOpts) next;
+};
+
+#endif
diff --git a/qemu-option.c b/qemu-option.c
index bb3886c..8334190 100644
--- a/qemu-option.c
+++ b/qemu-option.c
@@ -29,9 +29,9 @@
 #include "qemu-common.h"
 #include "qemu-error.h"
 #include "qemu-objects.h"
-#include "qemu-option.h"
 #include "error.h"
 #include "qerror.h"
+#include "qemu-option-internal.h"
 
 /*
  * Extracts the name of an option from the parameter string (p points at the
@@ -511,28 +511,6 @@ void print_option_help(QEMUOptionParameter *list)
 
 /* ------------------------------------------------------------------ */
 
-struct QemuOpt {
-    const char   *name;
-    const char   *str;
-
-    const QemuOptDesc *desc;
-    union {
-        bool boolean;
-        uint64_t uint;
-    } value;
-
-    QemuOpts     *opts;
-    QTAILQ_ENTRY(QemuOpt) next;
-};
-
-struct QemuOpts {
-    char *id;
-    QemuOptsList *list;
-    Location loc;
-    QTAILQ_HEAD(QemuOptHead, QemuOpt) head;
-    QTAILQ_ENTRY(QemuOpts) next;
-};
-
 static QemuOpt *qemu_opt_find(QemuOpts *opts, const char *name)
 {
     QemuOpt *opt;
commit 092705d4eb6779060661c8d521d0314e9571773f
Author: Laszlo Ersek <lersek at redhat.com>
Date:   Tue Jul 17 16:17:07 2012 +0200

    qapi: introduce "size" type
    
    v1->v2:
    - fall back to uint64 rather than int
    
    Signed-off-by: Laszlo Ersek <lersek at redhat.com>
    Signed-off-by: Stefan Hajnoczi <stefanha at linux.vnet.ibm.com>

diff --git a/qapi/qapi-visit-core.c b/qapi/qapi-visit-core.c
index d41595e..7a82b63 100644
--- a/qapi/qapi-visit-core.c
+++ b/qapi/qapi-visit-core.c
@@ -234,6 +234,13 @@ void visit_type_int64(Visitor *v, int64_t *obj, const char *name, Error **errp)
     }
 }
 
+void visit_type_size(Visitor *v, uint64_t *obj, const char *name, Error **errp)
+{
+    if (!error_is_set(errp)) {
+        (v->type_size ? v->type_size : v->type_uint64)(v, obj, name, errp);
+    }
+}
+
 void visit_type_bool(Visitor *v, bool *obj, const char *name, Error **errp)
 {
     if (!error_is_set(errp)) {
diff --git a/qapi/qapi-visit-core.h b/qapi/qapi-visit-core.h
index a19d70c..60aceda 100644
--- a/qapi/qapi-visit-core.h
+++ b/qapi/qapi-visit-core.h
@@ -60,6 +60,8 @@ struct Visitor
     void (*type_int16)(Visitor *v, int16_t *obj, const char *name, Error **errp);
     void (*type_int32)(Visitor *v, int32_t *obj, const char *name, Error **errp);
     void (*type_int64)(Visitor *v, int64_t *obj, const char *name, Error **errp);
+    /* visit_type_size() falls back to (*type_uint64)() if type_size is unset */
+    void (*type_size)(Visitor *v, uint64_t *obj, const char *name, Error **errp);
 };
 
 void visit_start_handle(Visitor *v, void **obj, const char *kind,
@@ -85,6 +87,7 @@ void visit_type_int8(Visitor *v, int8_t *obj, const char *name, Error **errp);
 void visit_type_int16(Visitor *v, int16_t *obj, const char *name, Error **errp);
 void visit_type_int32(Visitor *v, int32_t *obj, const char *name, Error **errp);
 void visit_type_int64(Visitor *v, int64_t *obj, const char *name, Error **errp);
+void visit_type_size(Visitor *v, uint64_t *obj, const char *name, Error **errp);
 void visit_type_bool(Visitor *v, bool *obj, const char *name, Error **errp);
 void visit_type_str(Visitor *v, char **obj, const char *name, Error **errp);
 void visit_type_number(Visitor *v, double *obj, const char *name, Error **errp);
diff --git a/scripts/qapi.py b/scripts/qapi.py
index 1292476..8082af3 100644
--- a/scripts/qapi.py
+++ b/scripts/qapi.py
@@ -163,6 +163,8 @@ def c_type(name):
           name == 'int64' or name == 'uint8' or name == 'uint16' or
           name == 'uint32' or name == 'uint64'):
         return name + '_t'
+    elif name == 'size':
+        return 'uint64_t'
     elif name == 'bool':
         return 'bool'
     elif name == 'number':
commit c46f18ce2b6dae531d72f61cf8441110c7936e70
Author: Laszlo Ersek <lersek at redhat.com>
Date:   Tue Jul 17 16:17:06 2012 +0200

    qapi: generate C types for fixed-width integers
    
    (Long line folded using parens:
    <http://www.python.org/dev/peps/pep-0008/#maximum-line-length>.)
    
    Signed-off-by: Laszlo Ersek <lersek at redhat.com>
    Signed-off-by: Stefan Hajnoczi <stefanha at linux.vnet.ibm.com>

diff --git a/scripts/qapi.py b/scripts/qapi.py
index e062336..1292476 100644
--- a/scripts/qapi.py
+++ b/scripts/qapi.py
@@ -159,6 +159,10 @@ def c_type(name):
         return 'char *'
     elif name == 'int':
         return 'int64_t'
+    elif (name == 'int8' or name == 'int16' or name == 'int32' or
+          name == 'int64' or name == 'uint8' or name == 'uint16' or
+          name == 'uint32' or name == 'uint64'):
+        return name + '_t'
     elif name == 'bool':
         return 'bool'
     elif name == 'number':
commit d98150f0522890046b3cc699552a3c94d9645cb6
Author: Laszlo Ersek <lersek at redhat.com>
Date:   Tue Jul 17 16:17:05 2012 +0200

    qapi: add test case for deallocating traversal of incomplete structure
    
    v3:
    - new patch
    
    Signed-off-by: Laszlo Ersek <lersek at redhat.com>
    Signed-off-by: Stefan Hajnoczi <stefanha at linux.vnet.ibm.com>

diff --git a/tests/test-qmp-commands.c b/tests/test-qmp-commands.c
index 60cbf01..dc3c507 100644
--- a/tests/test-qmp-commands.c
+++ b/tests/test-qmp-commands.c
@@ -3,6 +3,9 @@
 #include "test-qmp-commands.h"
 #include "qapi/qmp-core.h"
 #include "module.h"
+#include "qapi/qmp-input-visitor.h"
+#include "tests/test-qapi-types.h"
+#include "tests/test-qapi-visit.h"
 
 void qmp_user_def_cmd(Error **errp)
 {
@@ -123,6 +126,44 @@ static void test_dealloc_types(void)
     qapi_free_UserDefOneList(ud1list);
 }
 
+/* test generated deallocation on an object whose construction was prematurely
+ * terminated due to an error */
+static void test_dealloc_partial(void)
+{
+    static const char text[] = "don't leak me";
+
+    UserDefTwo *ud2 = NULL;
+    Error *err = NULL;
+
+    /* create partial object */
+    {
+        QDict *ud2_dict;
+        QmpInputVisitor *qiv;
+
+        ud2_dict = qdict_new();
+        qdict_put_obj(ud2_dict, "string", QOBJECT(qstring_from_str(text)));
+
+        qiv = qmp_input_visitor_new(QOBJECT(ud2_dict));
+        visit_type_UserDefTwo(qmp_input_get_visitor(qiv), &ud2, NULL, &err);
+        qmp_input_visitor_cleanup(qiv);
+        QDECREF(ud2_dict);
+    }
+
+    /* verify partial success */
+    assert(ud2 != NULL);
+    assert(ud2->string != NULL);
+    assert(strcmp(ud2->string, text) == 0);
+    assert(ud2->dict.dict.userdef == NULL);
+
+    /* confirm & release construction error */
+    assert(err != NULL);
+    error_free(err);
+
+    /* tear down partial object */
+    qapi_free_UserDefTwo(ud2);
+}
+
+
 int main(int argc, char **argv)
 {
     g_test_init(&argc, &argv, NULL);
@@ -131,6 +172,7 @@ int main(int argc, char **argv)
     g_test_add_func("/0.15/dispatch_cmd_error", test_dispatch_cmd_error);
     g_test_add_func("/0.15/dispatch_cmd_io", test_dispatch_cmd_io);
     g_test_add_func("/0.15/dealloc_types", test_dealloc_types);
+    g_test_add_func("/0.15/dealloc_partial", test_dealloc_partial);
 
     module_call_init(MODULE_INIT_QAPI);
     g_test_run();
commit d195325b05199038b5907fa791729425b9720d21
Author: Paolo Bonzini <pbonzini at redhat.com>
Date:   Tue Jul 17 16:17:04 2012 +0200

    qapi: fix error propagation
    
    Don't overwrite / leak previously set errors.
    Make traversal cope with missing mandatory sub-structs.
    Don't try to end a container that could not be started.
    
    v1->v2:
    - unchanged
    
    v2->v3:
    - instead of examining, assert that we never overwrite errors with
      error_set()
    - allow visitors to set a NULL struct pointer successfully, so traversal
      of incomplete objects can continue
    - check for a NULL "obj" before accessing "(*obj)->has_XXX" (this is not a
      typo, "obj != NULL" implies "*obj != NULL" here)
    - fix start_struct / end_struct balance for unions as well
    
    Signed-off-by: Paolo Bonzini <pbonzini at redhat.com>
    Signed-off-by: Laszlo Ersek <lersek at redhat.com>
    Signed-off-by: Stefan Hajnoczi <stefanha at linux.vnet.ibm.com>

diff --git a/docs/qapi-code-gen.txt b/docs/qapi-code-gen.txt
index ad11767..cccb11e 100644
--- a/docs/qapi-code-gen.txt
+++ b/docs/qapi-code-gen.txt
@@ -220,6 +220,8 @@ Example:
     #endif
     mdroth at illuin:~/w/qemu2.git$
 
+(The actual structure of the visit_type_* functions is a bit more complex
+in order to propagate errors correctly and avoid leaking memory).
 
 === scripts/qapi-commands.py ===
 
diff --git a/error.c b/error.c
index a52b771..58f55a0 100644
--- a/error.c
+++ b/error.c
@@ -32,6 +32,7 @@ void error_set(Error **errp, const char *fmt, ...)
     if (errp == NULL) {
         return;
     }
+    assert(*errp == NULL);
 
     err = g_malloc0(sizeof(*err));
 
@@ -132,7 +133,7 @@ bool error_is_type(Error *err, const char *fmt)
 
 void error_propagate(Error **dst_err, Error *local_err)
 {
-    if (dst_err) {
+    if (dst_err && !*dst_err) {
         *dst_err = local_err;
     } else if (local_err) {
         error_free(local_err);
diff --git a/error.h b/error.h
index 45ff6c1..3d9d96d 100644
--- a/error.h
+++ b/error.h
@@ -57,7 +57,7 @@ void error_set_field(Error *err, const char *field, const char *value);
 /**
  * Propagate an error to an indirect pointer to an error.  This function will
  * always transfer ownership of the error reference and handles the case where
- * dst_err is NULL correctly.
+ * dst_err is NULL correctly.  Errors after the first are discarded.
  */
 void error_propagate(Error **dst_err, Error *local_err);
 
diff --git a/qapi/qapi-visit-core.c b/qapi/qapi-visit-core.c
index 705eca9..d41595e 100644
--- a/qapi/qapi-visit-core.c
+++ b/qapi/qapi-visit-core.c
@@ -39,9 +39,8 @@ void visit_start_struct(Visitor *v, void **obj, const char *kind,
 
 void visit_end_struct(Visitor *v, Error **errp)
 {
-    if (!error_is_set(errp)) {
-        v->end_struct(v, errp);
-    }
+    assert(!error_is_set(errp));
+    v->end_struct(v, errp);
 }
 
 void visit_start_list(Visitor *v, const char *name, Error **errp)
@@ -62,9 +61,8 @@ GenericList *visit_next_list(Visitor *v, GenericList **list, Error **errp)
 
 void visit_end_list(Visitor *v, Error **errp)
 {
-    if (!error_is_set(errp)) {
-        v->end_list(v, errp);
-    }
+    assert(!error_is_set(errp));
+    v->end_list(v, errp);
 }
 
 void visit_start_optional(Visitor *v, bool *present, const char *name,
diff --git a/scripts/qapi-visit.py b/scripts/qapi-visit.py
index 8d4e94a..04ef7c4 100644
--- a/scripts/qapi-visit.py
+++ b/scripts/qapi-visit.py
@@ -17,32 +17,49 @@ import os
 import getopt
 import errno
 
-def generate_visit_struct_body(field_prefix, members):
-    ret = ""
+def generate_visit_struct_body(field_prefix, name, members):
+    ret = mcgen('''
+if (!error_is_set(errp)) {
+''')
+    push_indent()
+
     if len(field_prefix):
         field_prefix = field_prefix + "."
+        ret += mcgen('''
+Error **errp = &err; /* from outer scope */
+Error *err = NULL;
+visit_start_struct(m, NULL, "", "%(name)s", 0, &err);
+''',
+                name=name)
+    else:
+        ret += mcgen('''
+Error *err = NULL;
+visit_start_struct(m, (void **)obj, "%(name)s", name, sizeof(%(name)s), &err);
+''',
+                name=name)
+
+    ret += mcgen('''
+if (!err) {
+    if (!obj || *obj) {
+''')
+
+    push_indent()
+    push_indent()
     for argname, argentry, optional, structured in parse_args(members):
         if optional:
             ret += mcgen('''
-visit_start_optional(m, (obj && *obj) ? &(*obj)->%(c_prefix)shas_%(c_name)s : NULL, "%(name)s", errp);
-if ((*obj)->%(prefix)shas_%(c_name)s) {
+visit_start_optional(m, obj ? &(*obj)->%(c_prefix)shas_%(c_name)s : NULL, "%(name)s", &err);
+if (obj && (*obj)->%(prefix)shas_%(c_name)s) {
 ''',
                          c_prefix=c_var(field_prefix), prefix=field_prefix,
                          c_name=c_var(argname), name=argname)
             push_indent()
 
         if structured:
-            ret += mcgen('''
-visit_start_struct(m, NULL, "", "%(name)s", 0, errp);
-''',
-                         name=argname)
-            ret += generate_visit_struct_body(field_prefix + argname, argentry)
-            ret += mcgen('''
-visit_end_struct(m, errp);
-''')
+            ret += generate_visit_struct_body(field_prefix + argname, argname, argentry)
         else:
             ret += mcgen('''
-visit_type_%(type)s(m, (obj && *obj) ? &(*obj)->%(c_prefix)s%(c_name)s : NULL, "%(name)s", errp);
+visit_type_%(type)s(m, obj ? &(*obj)->%(c_prefix)s%(c_name)s : NULL, "%(name)s", &err);
 ''',
                          c_prefix=c_var(field_prefix), prefix=field_prefix,
                          type=type_name(argentry), c_name=c_var(argname),
@@ -52,7 +69,25 @@ visit_type_%(type)s(m, (obj && *obj) ? &(*obj)->%(c_prefix)s%(c_name)s : NULL, "
             pop_indent()
             ret += mcgen('''
 }
-visit_end_optional(m, errp);
+visit_end_optional(m, &err);
+''')
+
+    pop_indent()
+    ret += mcgen('''
+
+    error_propagate(errp, err);
+    err = NULL;
+}
+''')
+
+    pop_indent()
+    pop_indent()
+    ret += mcgen('''
+        /* Always call end_struct if start_struct succeeded.  */
+        visit_end_struct(m, &err);
+    }
+    error_propagate(errp, err);
+}
 ''')
     return ret
 
@@ -61,22 +96,14 @@ def generate_visit_struct(name, members):
 
 void visit_type_%(name)s(Visitor *m, %(name)s ** obj, const char *name, Error **errp)
 {
-    if (error_is_set(errp)) {
-        return;
-    }
-    visit_start_struct(m, (void **)obj, "%(name)s", name, sizeof(%(name)s), errp);
-    if (obj && !*obj) {
-        goto end;
-    }
 ''',
                 name=name)
+
     push_indent()
-    ret += generate_visit_struct_body("", members)
+    ret += generate_visit_struct_body("", name, members)
     pop_indent()
 
     ret += mcgen('''
-end:
-    visit_end_struct(m, errp);
 }
 ''')
     return ret
@@ -87,18 +114,23 @@ def generate_visit_list(name, members):
 void visit_type_%(name)sList(Visitor *m, %(name)sList ** obj, const char *name, Error **errp)
 {
     GenericList *i, **prev = (GenericList **)obj;
+    Error *err = NULL;
 
-    if (error_is_set(errp)) {
-        return;
-    }
-    visit_start_list(m, name, errp);
-
-    for (; (i = visit_next_list(m, prev, errp)) != NULL; prev = &i) {
-        %(name)sList *native_i = (%(name)sList *)i;
-        visit_type_%(name)s(m, &native_i->value, NULL, errp);
+    if (!error_is_set(errp)) {
+        visit_start_list(m, name, &err);
+        if (!err) {
+            for (; (i = visit_next_list(m, prev, &err)) != NULL; prev = &i) {
+                %(name)sList *native_i = (%(name)sList *)i;
+                visit_type_%(name)s(m, &native_i->value, NULL, &err);
+            }
+            error_propagate(errp, err);
+            err = NULL;
+
+            /* Always call end_list if start_list succeeded.  */
+            visit_end_list(m, &err);
+        }
+        error_propagate(errp, err);
     }
-
-    visit_end_list(m, errp);
 }
 ''',
                 name=name)
@@ -122,27 +154,23 @@ void visit_type_%(name)s(Visitor *m, %(name)s ** obj, const char *name, Error **
 {
     Error *err = NULL;
 
-    if (error_is_set(errp)) {
-        return;
-    }
-    visit_start_struct(m, (void **)obj, "%(name)s", name, sizeof(%(name)s), &err);
-    if (obj && !*obj) {
-        goto end;
-    }
-    visit_type_%(name)sKind(m, &(*obj)->kind, "type", &err);
-    if (err) {
-        error_propagate(errp, err);
-        goto end;
-    }
-    switch ((*obj)->kind) {
+    if (!error_is_set(errp)) {
+        visit_start_struct(m, (void **)obj, "%(name)s", name, sizeof(%(name)s), &err);
+        if (!err) {
+            if (!obj || *obj) {
+                visit_type_%(name)sKind(m, &(*obj)->kind, "type", &err);
+                if (!err) {
+                    switch ((*obj)->kind) {
 ''',
                  name=name)
 
+    push_indent()
+    push_indent()
     for key in members:
         ret += mcgen('''
-    case %(abbrev)s_KIND_%(enum)s:
-        visit_type_%(c_type)s(m, &(*obj)->%(c_name)s, "data", errp);
-        break;
+            case %(abbrev)s_KIND_%(enum)s:
+                visit_type_%(c_type)s(m, &(*obj)->%(c_name)s, "data", &err);
+                break;
 ''',
                 abbrev = de_camel_case(name).upper(),
                 enum = c_fun(de_camel_case(key)).upper(),
@@ -150,11 +178,25 @@ void visit_type_%(name)s(Visitor *m, %(name)s ** obj, const char *name, Error **
                 c_name=c_fun(key))
 
     ret += mcgen('''
-    default:
-        abort();
+            default:
+                abort();
+            }
+        }
+        error_propagate(errp, err);
+        err = NULL;
+    }
+''')
+    pop_indent()
+    ret += mcgen('''
+        /* Always call end_struct if start_struct succeeded.  */
+        visit_end_struct(m, &err);
     }
-end:
-    visit_end_struct(m, errp);
+    error_propagate(errp, err);
+}
+''')
+
+    pop_indent();
+    ret += mcgen('''
 }
 ''')
 
diff --git a/tests/test-qmp-input-visitor.c b/tests/test-qmp-input-visitor.c
index c30fdc4..8f5a509 100644
--- a/tests/test-qmp-input-visitor.c
+++ b/tests/test-qmp-input-visitor.c
@@ -151,14 +151,22 @@ typedef struct TestStruct
 static void visit_type_TestStruct(Visitor *v, TestStruct **obj,
                                   const char *name, Error **errp)
 {
-    visit_start_struct(v, (void **)obj, "TestStruct", name, sizeof(TestStruct),
-                       errp);
-
-    visit_type_int(v, &(*obj)->integer, "integer", errp);
-    visit_type_bool(v, &(*obj)->boolean, "boolean", errp);
-    visit_type_str(v, &(*obj)->string, "string", errp);
-
-    visit_end_struct(v, errp);
+    Error *err = NULL;
+    if (!error_is_set(errp)) {
+        visit_start_struct(v, (void **)obj, "TestStruct", name, sizeof(TestStruct),
+                           &err);
+        if (!err) {
+            visit_type_int(v, &(*obj)->integer, "integer", &err);
+            visit_type_bool(v, &(*obj)->boolean, "boolean", &err);
+            visit_type_str(v, &(*obj)->string, "string", &err);
+
+            /* Always call end_struct if start_struct succeeded.  */
+            error_propagate(errp, err);
+            err = NULL;
+            visit_end_struct(v, &err);
+        }
+        error_propagate(errp, err);
+    }
 }
 
 static void test_visitor_in_struct(TestInputVisitorData *data,
commit 837c36e7871a74dda78d2ca89d9027b19553a871
Author: Stefan Hajnoczi <stefanha at linux.vnet.ibm.com>
Date:   Fri Jul 20 14:29:24 2012 +0100

    MAINTAINERS: Replace net maintainer Mark McLoughlin with Stefan Hajnoczi
    
    The net subsystem has lacked an active maintainer since 2009.  I have
    built and tested a net-next tree to get the ball rolling again.
    
    Signed-off-by: Stefan Hajnoczi <stefanha at linux.vnet.ibm.com>

diff --git a/MAINTAINERS b/MAINTAINERS
index 30ed56d..2d219d2 100644
--- a/MAINTAINERS
+++ b/MAINTAINERS
@@ -560,9 +560,10 @@ F: monitor.c
 
 Network device layer
 M: Anthony Liguori <aliguori at us.ibm.com>
-M: Mark McLoughlin <markmc at redhat.com>
+M: Stefan Hajnoczi <stefanha at linux.vnet.ibm.com>
 S: Maintained
 F: net/
+T: git git://github.com/stefanha/qemu.git net
 
 Network Block Device (NBD)
 M: Paolo Bonzini <pbonzini at redhat.com>
commit 43ffe61f9cc22f9ad4d05a18a304b1095fa1f2b3
Author: Stefan Weil <sw at weilnetz.de>
Date:   Fri Jul 20 23:26:02 2012 +0200

    Fix some more Qemus in documentation and help text
    
    Hopefully they will be eliminated one day.
    
    Signed-off-by: Stefan Weil <sw at weilnetz.de>
    Signed-off-by: Stefan Hajnoczi <stefanha at linux.vnet.ibm.com>

diff --git a/docs/usb-storage.txt b/docs/usb-storage.txt
index ff97559..e58e849 100644
--- a/docs/usb-storage.txt
+++ b/docs/usb-storage.txt
@@ -2,7 +2,7 @@
 qemu usb storage emulation
 --------------------------
 
-Qemu has two emulations for usb storage devices.
+QEMU has two emulations for usb storage devices.
 
 Number one emulates the classic bulk-only transport protocol which is
 used by 99% of the usb sticks on the marked today and is called
diff --git a/qemu-options.hx b/qemu-options.hx
index 97245a3..dc68e15 100644
--- a/qemu-options.hx
+++ b/qemu-options.hx
@@ -1439,7 +1439,7 @@ Forward guest TCP connections to the IP address @var{server} on port @var{port}
 to the character device @var{dev} or to a program executed by @var{cmd:command}
 which gets spawned for each connection. This option can be given multiple times.
 
-You can either use a chardev directly and have that one used throughout Qemu's
+You can either use a chardev directly and have that one used throughout QEMU's
 lifetime, like in the following example:
 
 @example
@@ -1449,7 +1449,7 @@ qemu -net user,guestfwd=tcp:10.0.2.100:1234-tcp:10.10.1.1:4321 [...]
 @end example
 
 Or you can execute a command on every TCP connection established by the guest,
-so that Qemu behaves similar to an inetd process for that virtual server:
+so that QEMU behaves similar to an inetd process for that virtual server:
 
 @example
 # call "netcat 10.10.1.1 4321" on every TCP connection to 10.0.2.100:1234
commit c5788614516c6a88ca0bb98d412ab390c0b77e1e
Author: Stefan Weil <sw at weilnetz.de>
Date:   Fri Jul 20 23:04:49 2012 +0200

    qdev: Fix Open Firmware comment
    
    Commit 0d936928ef87ca1bb7b41b5b89c400c699a7691c removed code,
    but left the related comment at a location where it no longer
    belongs to.
    
    The patch moves the comment to the correct callback and improves the text.
    
    Signed-off-by: Stefan Weil <sw at weilnetz.de>
    Signed-off-by: Stefan Hajnoczi <stefanha at linux.vnet.ibm.com>

diff --git a/hw/qdev.h b/hw/qdev.h
index 247dd1e..a2cbd9d 100644
--- a/hw/qdev.h
+++ b/hw/qdev.h
@@ -78,12 +78,6 @@ struct DeviceState {
     int alias_required_for_version;
 };
 
-/*
- * This callback is used to create Open Firmware device path in accordance with
- * OF spec http://forthworks.com/standards/of1275.pdf. Indicidual bus bindings
- * can be found here http://playground.sun.com/1275/bindings/.
- */
-
 #define TYPE_BUS "bus"
 #define BUS(obj) OBJECT_CHECK(BusState, (obj), TYPE_BUS)
 #define BUS_CLASS(klass) OBJECT_CLASS_CHECK(BusClass, (klass), TYPE_BUS)
@@ -95,6 +89,11 @@ struct BusClass {
     /* FIXME first arg should be BusState */
     void (*print_dev)(Monitor *mon, DeviceState *dev, int indent);
     char *(*get_dev_path)(DeviceState *dev);
+    /*
+     * This callback is used to create Open Firmware device path in accordance
+     * with OF spec http://forthworks.com/standards/of1275.pdf. Individual bus
+     * bindings can be found at http://playground.sun.com/1275/bindings/.
+     */
     char *(*get_fw_dev_path)(DeviceState *dev);
     int (*reset)(BusState *bus);
 };
commit ac873f1ed5060653719320d562bff7c8f6c4e6a9
Author: Peter Maydell <peter.maydell at linaro.org>
Date:   Thu Jul 19 16:52:27 2012 +0100

    cpus.c: Make all_cpu_threads_idle() static
    
    Commit 946fb27c1 moved all the uses of all_cpu_threads_idle()
    into cpus.c. This means we can mark the function 'static'
    (again), if we shuffle it a bit earlier in the source file.
    
    Signed-off-by: Peter Maydell <peter.maydell at linaro.org>
    Signed-off-by: Stefan Hajnoczi <stefanha at linux.vnet.ibm.com>

diff --git a/cpus.c b/cpus.c
index b182b3d..756e624 100644
--- a/cpus.c
+++ b/cpus.c
@@ -61,6 +61,32 @@
 
 static CPUArchState *next_cpu;
 
+static bool cpu_thread_is_idle(CPUArchState *env)
+{
+    if (env->stop || env->queued_work_first) {
+        return false;
+    }
+    if (env->stopped || !runstate_is_running()) {
+        return true;
+    }
+    if (!env->halted || qemu_cpu_has_work(env) || kvm_irqchip_in_kernel()) {
+        return false;
+    }
+    return true;
+}
+
+static bool all_cpu_threads_idle(void)
+{
+    CPUArchState *env;
+
+    for (env = first_cpu; env != NULL; env = env->next_cpu) {
+        if (!cpu_thread_is_idle(env)) {
+            return false;
+        }
+    }
+    return true;
+}
+
 /***********************************************************/
 /* guest cycle counter */
 
@@ -433,32 +459,6 @@ static int cpu_can_run(CPUArchState *env)
     return 1;
 }
 
-static bool cpu_thread_is_idle(CPUArchState *env)
-{
-    if (env->stop || env->queued_work_first) {
-        return false;
-    }
-    if (env->stopped || !runstate_is_running()) {
-        return true;
-    }
-    if (!env->halted || qemu_cpu_has_work(env) || kvm_irqchip_in_kernel()) {
-        return false;
-    }
-    return true;
-}
-
-bool all_cpu_threads_idle(void)
-{
-    CPUArchState *env;
-
-    for (env = first_cpu; env != NULL; env = env->next_cpu) {
-        if (!cpu_thread_is_idle(env)) {
-            return false;
-        }
-    }
-    return true;
-}
-
 static void cpu_handle_guest_debug(CPUArchState *env)
 {
     gdb_set_stop_cpu(env);
diff --git a/qemu-common.h b/qemu-common.h
index 09676f5..7c8dac8 100644
--- a/qemu-common.h
+++ b/qemu-common.h
@@ -293,7 +293,6 @@ int cpu_load(QEMUFile *f, void *opaque, int version_id);
 void qemu_cpu_kick(void *env);
 void qemu_cpu_kick_self(void);
 int qemu_cpu_is_self(void *env);
-bool all_cpu_threads_idle(void);
 
 /* work queue */
 struct qemu_work_item {
commit 7c7bb0223e667c656950427cd17bf95d92993f76
Author: Stefan Weil <sw at weilnetz.de>
Date:   Wed Jul 18 18:12:37 2012 +0200

    Use macro QEMU_PACKED for new packed structures
    
    Since commit 541dc0d47f10973c241e9955afc2aefc96adec51,
    some new packed structures were added without using QEMU_PACKED.
    
    QEMU_PACKED is needed for compilations with MinGW.
    For other platforms nothing changes.
    
    The code was fixed using this command:
    
        git grep -la '__attribute__ ((packed))'|xargs perl -pi -e 's/__attribute__ \(\(packed\)\)/QEMU_PACKED/'
    
    Signed-off-by: Stefan Weil <sw at weilnetz.de>
    Reviewed-by: Peter Maydell <peter.maydell at linaro.org>
    Signed-off-by: Stefan Hajnoczi <stefanha at linux.vnet.ibm.com>

diff --git a/hw/mfi.h b/hw/mfi.h
index 8a82162..3045d4e 100644
--- a/hw/mfi.h
+++ b/hw/mfi.h
@@ -435,24 +435,24 @@ typedef enum {
 struct mfi_sg32 {
     uint32_t addr;
     uint32_t len;
-} __attribute__ ((packed));
+} QEMU_PACKED;
 
 struct mfi_sg64 {
     uint64_t addr;
     uint32_t len;
-} __attribute__ ((packed));
+} QEMU_PACKED;
 
 struct mfi_sg_skinny {
     uint64_t addr;
     uint32_t len;
     uint32_t flag;
-} __attribute__ ((packed));
+} QEMU_PACKED;
 
 union mfi_sgl {
     struct mfi_sg32 sg32[1];
     struct mfi_sg64 sg64[1];
     struct mfi_sg_skinny sg_skinny[1];
-} __attribute__ ((packed));
+} QEMU_PACKED;
 
 /* Message frames.  All messages have a common header */
 struct mfi_frame_header {
@@ -468,7 +468,7 @@ struct mfi_frame_header {
     uint16_t flags;
     uint16_t timeout;
     uint32_t data_len;
-} __attribute__ ((packed));
+} QEMU_PACKED;
 
 struct mfi_init_frame {
     struct mfi_frame_header header;
@@ -487,7 +487,7 @@ struct mfi_io_frame {
     uint32_t lba_lo;
     uint32_t lba_hi;
     union mfi_sgl sgl;
-} __attribute__ ((packed));
+} QEMU_PACKED;
 
 #define MFI_PASS_FRAME_SIZE 48
 struct mfi_pass_frame {
@@ -496,7 +496,7 @@ struct mfi_pass_frame {
     uint32_t sense_addr_hi;
     uint8_t cdb[16];
     union mfi_sgl sgl;
-} __attribute__ ((packed));
+} QEMU_PACKED;
 
 #define MFI_DCMD_FRAME_SIZE 40
 struct mfi_dcmd_frame {
@@ -504,7 +504,7 @@ struct mfi_dcmd_frame {
     uint32_t opcode;
     uint8_t mbox[MFI_MBOX_SIZE];
     union mfi_sgl sgl;
-} __attribute__ ((packed));
+} QEMU_PACKED;
 
 struct mfi_abort_frame {
     struct mfi_frame_header header;
@@ -512,7 +512,7 @@ struct mfi_abort_frame {
     uint32_t abort_mfi_addr_lo;
     uint32_t abort_mfi_addr_hi;
     uint32_t reserved1[6];
-} __attribute__ ((packed));
+} QEMU_PACKED;
 
 struct mfi_smp_frame {
     struct mfi_frame_header header;
@@ -521,7 +521,7 @@ struct mfi_smp_frame {
         struct mfi_sg32 sg32[2];
         struct mfi_sg64 sg64[2];
     } sgl;
-} __attribute__ ((packed));
+} QEMU_PACKED;
 
 struct mfi_stp_frame {
     struct mfi_frame_header header;
@@ -531,7 +531,7 @@ struct mfi_stp_frame {
         struct mfi_sg32 sg32[2];
         struct mfi_sg64 sg64[2];
     } sgl;
-} __attribute__ ((packed));
+} QEMU_PACKED;
 
 union mfi_frame {
     struct mfi_frame_header header;
@@ -563,7 +563,7 @@ struct mfi_init_qinfo {
     uint32_t pi_addr_hi;
     uint32_t ci_addr_lo;
     uint32_t ci_addr_hi;
-} __attribute__ ((packed));
+} QEMU_PACKED;
 
 /* Controller properties */
 struct mfi_ctrl_props {
@@ -626,7 +626,7 @@ struct mfi_ctrl_props {
                                * is spun down (0=use FW defaults)
                                */
     uint8_t reserved[24];
-} __attribute__ ((packed));
+} QEMU_PACKED;
 
 /* PCI information about the card. */
 struct mfi_info_pci {
@@ -635,7 +635,7 @@ struct mfi_info_pci {
     uint16_t subvendor;
     uint16_t subdevice;
     uint8_t reserved[24];
-} __attribute__ ((packed));
+} QEMU_PACKED;
 
 /* Host (front end) interface information */
 struct mfi_info_host {
@@ -647,7 +647,7 @@ struct mfi_info_host {
     uint8_t reserved[6];
     uint8_t port_count;
     uint64_t port_addr[8];
-} __attribute__ ((packed));
+} QEMU_PACKED;
 
 /* Device (back end) interface information */
 struct mfi_info_device {
@@ -659,7 +659,7 @@ struct mfi_info_device {
     uint8_t reserved[6];
     uint8_t port_count;
     uint64_t port_addr[8];
-} __attribute__ ((packed));
+} QEMU_PACKED;
 
 /* Firmware component information */
 struct mfi_info_component {
@@ -667,7 +667,7 @@ struct mfi_info_component {
     char version[32];
     char build_date[16];
     char build_time[16];
-} __attribute__ ((packed));
+} QEMU_PACKED;
 
 /* Controller default settings */
 struct mfi_defaults {
@@ -710,7 +710,7 @@ struct mfi_defaults {
     uint8_t fde_only;
     uint8_t delay_during_post;
     uint8_t resv[19];
-} __attribute__ ((packed));
+} QEMU_PACKED;
 
 /* Controller default settings */
 struct mfi_bios_data {
@@ -722,7 +722,7 @@ struct mfi_bios_data {
     uint8_t expose_all_drives;
     uint8_t reserved[56];
     uint8_t check_sum;
-} __attribute__ ((packed));
+} QEMU_PACKED;
 
 /* SAS (?) controller info, returned from MFI_DCMD_CTRL_GETINFO. */
 struct mfi_ctrl_info {
@@ -807,7 +807,7 @@ struct mfi_ctrl_info {
         uint8_t min;
         uint8_t max;
         uint8_t reserved[2];
-    } __attribute__ ((packed)) stripe_sz_ops;
+    } QEMU_PACKED stripe_sz_ops;
 
     uint32_t pd_ops;
 #define MFI_INFO_PDOPS_FORCE_ONLINE     0x01
@@ -826,7 +826,7 @@ struct mfi_ctrl_info {
     struct mfi_ctrl_props properties;
     char package_version[0x60];
     uint8_t pad[0x800 - 0x6a0];
-} __attribute__ ((packed));
+} QEMU_PACKED;
 
 /* keep track of an event. */
 union mfi_evt {
@@ -836,7 +836,7 @@ union mfi_evt {
         int8_t class;
     } members;
     uint32_t word;
-} __attribute__ ((packed));
+} QEMU_PACKED;
 
 /* event log state. */
 struct mfi_evt_log_state {
@@ -845,24 +845,24 @@ struct mfi_evt_log_state {
     uint32_t clear_seq_num;
     uint32_t shutdown_seq_num;
     uint32_t boot_seq_num;
-} __attribute__ ((packed));
+} QEMU_PACKED;
 
 struct mfi_progress {
     uint16_t progress;
     uint16_t elapsed_seconds;
-} __attribute__ ((packed));
+} QEMU_PACKED;
 
 struct mfi_evt_ld {
     uint16_t target_id;
     uint8_t ld_index;
     uint8_t reserved;
-} __attribute__ ((packed));
+} QEMU_PACKED;
 
 struct mfi_evt_pd {
     uint16_t device_id;
     uint8_t enclosure_index;
     uint8_t slot_number;
-} __attribute__ ((packed));
+} QEMU_PACKED;
 
 /* event detail, returned from MFI_DCMD_CTRL_EVENT_WAIT. */
 struct mfi_evt_detail {
@@ -982,13 +982,13 @@ struct mfi_evt_detail {
     } args;
 
     char description[128];
-} __attribute__ ((packed));
+} QEMU_PACKED;
 
 struct mfi_evt_list {
     uint32_t count;
     uint32_t reserved;
     struct mfi_evt_detail event[1];
-} __attribute__ ((packed));
+} QEMU_PACKED;
 
 union mfi_pd_ref {
     struct {
@@ -996,7 +996,7 @@ union mfi_pd_ref {
         uint16_t seq_num;
     } v;
     uint32_t ref;
-} __attribute__ ((packed));
+} QEMU_PACKED;
 
 union mfi_pd_ddf_type {
     struct {
@@ -1016,7 +1016,7 @@ union mfi_pd_ddf_type {
         uint32_t reserved;
     } non_disk;
     uint32_t type;
-} __attribute__ ((packed));
+} QEMU_PACKED;
 
 struct mfi_pd_progress {
     uint32_t active;
@@ -1027,7 +1027,7 @@ struct mfi_pd_progress {
     struct mfi_progress patrol;
     struct mfi_progress clear;
     struct mfi_progress reserved[4];
-} __attribute__ ((packed));
+} QEMU_PACKED;
 
 struct mfi_pd_info {
     union mfi_pd_ref ref;
@@ -1062,7 +1062,7 @@ struct mfi_pd_info {
     uint8_t unusable_in_current_config;
     uint8_t vpd_page83_ext[64];
     uint8_t reserved[512-358];
-} __attribute__ ((packed));
+} QEMU_PACKED;
 
 struct mfi_pd_address {
     uint16_t device_id;
@@ -1072,14 +1072,14 @@ struct mfi_pd_address {
     uint8_t scsi_dev_type;
     uint8_t connect_port_bitmap;
     uint64_t sas_addr[2];
-} __attribute__ ((packed));
+} QEMU_PACKED;
 
 #define MFI_MAX_SYS_PDS 240
 struct mfi_pd_list {
     uint32_t size;
     uint32_t count;
     struct mfi_pd_address addr[MFI_MAX_SYS_PDS];
-} __attribute__ ((packed));
+} QEMU_PACKED;
 
 union mfi_ld_ref {
     struct {
@@ -1088,7 +1088,7 @@ union mfi_ld_ref {
         uint16_t seq;
     } v;
     uint32_t ref;
-} __attribute__ ((packed));
+} QEMU_PACKED;
 
 struct mfi_ld_list {
     uint32_t ld_count;
@@ -1099,7 +1099,7 @@ struct mfi_ld_list {
         uint8_t reserved2[3];
         uint64_t size;
     } ld_list[MFI_MAX_LD];
-} __attribute__ ((packed));
+} QEMU_PACKED;
 
 enum mfi_ld_access {
     MFI_LD_ACCESS_RW =          0,
@@ -1136,7 +1136,7 @@ struct mfi_ld_props {
     uint8_t current_cache_policy;
     uint8_t no_bgi;
     uint8_t reserved[7];
-} __attribute__ ((packed));
+} QEMU_PACKED;
 
 struct mfi_ld_params {
     uint8_t primary_raid_level;
@@ -1149,7 +1149,7 @@ struct mfi_ld_params {
     uint8_t init_state;
     uint8_t is_consistent;
     uint8_t reserved[23];
-} __attribute__ ((packed));
+} QEMU_PACKED;
 
 struct mfi_ld_progress {
     uint32_t            active;
@@ -1162,21 +1162,21 @@ struct mfi_ld_progress {
     struct mfi_progress fgi;
     struct mfi_progress recon;
     struct mfi_progress reserved[4];
-} __attribute__ ((packed));
+} QEMU_PACKED;
 
 struct mfi_span {
     uint64_t start_block;
     uint64_t num_blocks;
     uint16_t array_ref;
     uint8_t reserved[6];
-} __attribute__ ((packed));
+} QEMU_PACKED;
 
 #define MFI_MAX_SPAN_DEPTH      8
 struct mfi_ld_config {
     struct mfi_ld_props properties;
     struct mfi_ld_params params;
     struct mfi_span span[MFI_MAX_SPAN_DEPTH];
-} __attribute__ ((packed));
+} QEMU_PACKED;
 
 struct mfi_ld_info {
     struct mfi_ld_config ld_config;
@@ -1187,7 +1187,7 @@ struct mfi_ld_info {
     uint8_t reserved1[1];
     uint8_t vpd_page83[64];
     uint8_t reserved2[16];
-} __attribute__ ((packed));
+} QEMU_PACKED;
 
 union mfi_spare_type {
     uint8_t flags;
@@ -1195,7 +1195,7 @@ union mfi_spare_type {
 #define MFI_SPARE_IS_REVERTABLE (1 << 1)
 #define MFI_SPARE_IS_ENCL_AFFINITY (1 << 2)
     uint8_t type;
-} __attribute__ ((packed));
+} QEMU_PACKED;
 
 #define MFI_MAX_ARRAYS 16
 struct mfi_spare {
@@ -1204,7 +1204,7 @@ struct mfi_spare {
     uint8_t reserved[2];
     uint8_t array_count;
     uint16_t array_refd[MFI_MAX_ARRAYS];
-} __attribute__ ((packed));
+} QEMU_PACKED;
 
 #define MFI_MAX_ROW_SIZE 32
 struct mfi_array {
@@ -1221,7 +1221,7 @@ struct mfi_array {
             uint8_t slot;
         } encl;
     } pd[MFI_MAX_ROW_SIZE];
-} __attribute__ ((packed));
+} QEMU_PACKED;
 
 struct mfi_config_data {
     uint32_t size;
@@ -1237,7 +1237,7 @@ struct mfi_config_data {
       struct mfi_ld_config ld[];
       struct mfi_spare  spare[];
     */
-} __attribute__ ((packed));
+} QEMU_PACKED;
 
 #define MFI_SCSI_MAX_TARGETS  128
 #define MFI_SCSI_MAX_LUNS       8
diff --git a/hw/ppce500_spin.c b/hw/ppce500_spin.c
index fddf219..c5b8e05 100644
--- a/hw/ppce500_spin.c
+++ b/hw/ppce500_spin.c
@@ -40,7 +40,7 @@ typedef struct spin_info {
     uint32_t resv;
     uint32_t pir;
     uint64_t reserved;
-} __attribute__ ((packed)) SpinInfo;
+} QEMU_PACKED SpinInfo;
 
 typedef struct spin_state {
     SysBusDevice busdev;
commit 434acb817b8ae747f31e91ec152f9f47ac514433
Author: Mao, Junjie <junjie.mao at intel.com>
Date:   Fri Jul 20 07:08:21 2012 +0000

    Recognize PCID feature
    
    This patch makes Qemu recognize the PCID feature specified from configuration or command line options.
    
    Signed-off-by: Junjie Mao <junjie.mao at intel.com>
    Signed-off-by: Stefan Hajnoczi <stefanha at linux.vnet.ibm.com>

diff --git a/target-i386/cpu.c b/target-i386/cpu.c
index b3bcbac..6b9659f 100644
--- a/target-i386/cpu.c
+++ b/target-i386/cpu.c
@@ -50,7 +50,7 @@ static const char *ext_feature_name[] = {
     "ds_cpl", "vmx", "smx", "est",
     "tm2", "ssse3", "cid", NULL,
     "fma", "cx16", "xtpr", "pdcm",
-    NULL, NULL, "dca", "sse4.1|sse4_1",
+    NULL, "pcid", "dca", "sse4.1|sse4_1",
     "sse4.2|sse4_2", "x2apic", "movbe", "popcnt",
     "tsc-deadline", "aes", "xsave", "osxsave",
     "avx", NULL, NULL, "hypervisor",
commit c4889f54237aec5195d42de2c87292d6e41dd704
Author: Alexey Kardashevskiy <aik at ozlabs.ru>
Date:   Wed Jul 18 18:22:51 2012 +1000

    powerpc pci: fixed packing of ranges[]
    
    By default mingw-gcc is trying to pack structures the way to
    preserve binary compatibility with MS Visual C what leads to
    incorrect and unexpected padding in the PCI bus ranges property of
    the sPAPR PHB.
    
    The patch replaces __attribute__((packed)) with more strict QEMU_PACKED
    which actually is __attribute__((gcc_struct, packed)) on Windows.
    
    Signed-off-by: Alexey Kardashevskiy <aik at ozlabs.ru>
    Tested-by: Stefan Weil <sw at weilnetz.de>
    Reviewed-by: Stefan Weil <sw at weilnetz.de>
    Acked-by: Alexander Graf <agraf at suse.de>
    Signed-off-by: Stefan Hajnoczi <stefanha at linux.vnet.ibm.com>

diff --git a/hw/spapr_pci.c b/hw/spapr_pci.c
index 47ba5ff..b2e4f78 100644
--- a/hw/spapr_pci.c
+++ b/hw/spapr_pci.c
@@ -418,7 +418,7 @@ int spapr_populate_pci_devices(sPAPRPHBState *phb,
         uint64_t child;
         uint64_t parent;
         uint64_t size;
-    } __attribute__((packed)) ranges[] = {
+    } QEMU_PACKED ranges[] = {
         {
             cpu_to_be32(b_ss(1)), cpu_to_be64(0),
             cpu_to_be64(phb->io_win_addr),
commit ffbbe7d02fd02a6b563df443e4406de076ac7d93
Author: Mitsyanko Igor <i.mitsyanko at samsung.com>
Date:   Wed Jul 18 08:18:34 2012 +0000

    exynos4210: add Exynos4210 i2c implementation
    
    Create 9 exynos4210 i2c interfaces.
    
    Signed-off-by: Igor Mitsyanko <i.mitsyanko at samsung.com>
    Reviewed-by: Andreas Färber <afaerber at suse.de>
    Signed-off-by: Peter Maydell <peter.maydell at linaro.org>

diff --git a/hw/arm/Makefile.objs b/hw/arm/Makefile.objs
index 236786e..c413780 100644
--- a/hw/arm/Makefile.objs
+++ b/hw/arm/Makefile.objs
@@ -11,7 +11,7 @@ obj-y += realview_gic.o realview.o arm_sysctl.o arm11mpcore.o a9mpcore.o
 obj-y += exynos4210_gic.o exynos4210_combiner.o exynos4210.o
 obj-y += exynos4_boards.o exynos4210_uart.o exynos4210_pwm.o
 obj-y += exynos4210_pmu.o exynos4210_mct.o exynos4210_fimd.o
-obj-y += exynos4210_rtc.o
+obj-y += exynos4210_rtc.o exynos4210_i2c.o
 obj-y += arm_l2x0.o
 obj-y += arm_mptimer.o a15mpcore.o
 obj-y += armv7m.o armv7m_nvic.o stellaris.o pl022.o stellaris_enet.o
diff --git a/hw/exynos4210.c b/hw/exynos4210.c
index 7c58c90..00d4db8 100644
--- a/hw/exynos4210.c
+++ b/hw/exynos4210.c
@@ -39,6 +39,13 @@
 /* MCT */
 #define EXYNOS4210_MCT_BASE_ADDR       0x10050000
 
+/* I2C */
+#define EXYNOS4210_I2C_SHIFT           0x00010000
+#define EXYNOS4210_I2C_BASE_ADDR       0x13860000
+/* Interrupt Group of External Interrupt Combiner for I2C */
+#define EXYNOS4210_I2C_INTG            27
+#define EXYNOS4210_HDMI_INTG           16
+
 /* UART's definitions */
 #define EXYNOS4210_UART0_BASE_ADDR     0x13800000
 #define EXYNOS4210_UART1_BASE_ADDR     0x13810000
@@ -283,6 +290,26 @@ Exynos4210State *exynos4210_init(MemoryRegion *system_mem,
             s->irq_table[exynos4210_get_irq(35, 3)]);
     sysbus_mmio_map(busdev, 0, EXYNOS4210_MCT_BASE_ADDR);
 
+    /*** I2C ***/
+    for (n = 0; n < EXYNOS4210_I2C_NUMBER; n++) {
+        uint32_t addr = EXYNOS4210_I2C_BASE_ADDR + EXYNOS4210_I2C_SHIFT * n;
+        qemu_irq i2c_irq;
+
+        if (n < 8) {
+            i2c_irq = s->irq_table[exynos4210_get_irq(EXYNOS4210_I2C_INTG, n)];
+        } else {
+            i2c_irq = s->irq_table[exynos4210_get_irq(EXYNOS4210_HDMI_INTG, 1)];
+        }
+
+        dev = qdev_create(NULL, "exynos4210.i2c");
+        qdev_init_nofail(dev);
+        busdev = sysbus_from_qdev(dev);
+        sysbus_connect_irq(busdev, 0, i2c_irq);
+        sysbus_mmio_map(busdev, 0, addr);
+        s->i2c_if[n] = (i2c_bus *)qdev_get_child_bus(dev, "i2c");
+    }
+
+
     /*** UARTs ***/
     exynos4210_uart_create(EXYNOS4210_UART0_BASE_ADDR,
                            EXYNOS4210_UART0_FIFO_SIZE, 0, NULL,
diff --git a/hw/exynos4210.h b/hw/exynos4210.h
index 9b1ae4c..a43ba3a 100644
--- a/hw/exynos4210.h
+++ b/hw/exynos4210.h
@@ -74,6 +74,8 @@
 #define EXYNOS4210_EXT_GIC_NIRQ     (160-32)
 #define EXYNOS4210_INT_GIC_NIRQ     64
 
+#define EXYNOS4210_I2C_NUMBER               9
+
 typedef struct Exynos4210Irq {
     qemu_irq int_combiner_irq[EXYNOS4210_MAX_INT_COMBINER_IN_IRQ];
     qemu_irq ext_combiner_irq[EXYNOS4210_MAX_EXT_COMBINER_IN_IRQ];
@@ -95,6 +97,7 @@ typedef struct Exynos4210State {
     MemoryRegion dram1_mem;
     MemoryRegion boot_secondary;
     MemoryRegion bootreg_mem;
+    i2c_bus *i2c_if[EXYNOS4210_I2C_NUMBER];
 } Exynos4210State;
 
 void exynos4210_write_secondary(ARMCPU *cpu,
diff --git a/hw/exynos4210_i2c.c b/hw/exynos4210_i2c.c
new file mode 100644
index 0000000..3f72a5c
--- /dev/null
+++ b/hw/exynos4210_i2c.c
@@ -0,0 +1,334 @@
+/*
+ *  Exynos4210 I2C Bus Serial Interface Emulation
+ *
+ *  Copyright (C) 2012 Samsung Electronics Co Ltd.
+ *    Maksim Kozlov, <m.kozlov at samsung.com>
+ *    Igor Mitsyanko, <i.mitsyanko at samsung.com>
+ *
+ *  This program is free software; you can redistribute it and/or modify it
+ *  under the terms of the GNU General Public License as published by the
+ *  Free Software Foundation; either version 2 of the License, or
+ *  (at your option) any later version.
+ *
+ *  This program is distributed in the hope that it will be useful, but WITHOUT
+ *  ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ *  FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
+ *  for more details.
+ *
+ *  You should have received a copy of the GNU General Public License along
+ *  with this program; if not, see <http://www.gnu.org/licenses/>.
+ *
+ */
+
+#include "qemu-timer.h"
+#include "sysbus.h"
+#include "i2c.h"
+
+#ifndef EXYNOS4_I2C_DEBUG
+#define EXYNOS4_I2C_DEBUG                 0
+#endif
+
+#define TYPE_EXYNOS4_I2C                  "exynos4210.i2c"
+#define EXYNOS4_I2C(obj)                  \
+    OBJECT_CHECK(Exynos4210I2CState, (obj), TYPE_EXYNOS4_I2C)
+
+/* Exynos4210 I2C memory map */
+#define EXYNOS4_I2C_MEM_SIZE              0x14
+#define I2CCON_ADDR                       0x00  /* control register */
+#define I2CSTAT_ADDR                      0x04  /* control/status register */
+#define I2CADD_ADDR                       0x08  /* address register */
+#define I2CDS_ADDR                        0x0c  /* data shift register */
+#define I2CLC_ADDR                        0x10  /* line control register */
+
+#define I2CCON_ACK_GEN                    (1 << 7)
+#define I2CCON_INTRS_EN                   (1 << 5)
+#define I2CCON_INT_PEND                   (1 << 4)
+
+#define EXYNOS4_I2C_MODE(reg)             (((reg) >> 6) & 3)
+#define I2C_IN_MASTER_MODE(reg)           (((reg) >> 6) & 2)
+#define I2CMODE_MASTER_Rx                 0x2
+#define I2CMODE_MASTER_Tx                 0x3
+#define I2CSTAT_LAST_BIT                  (1 << 0)
+#define I2CSTAT_OUTPUT_EN                 (1 << 4)
+#define I2CSTAT_START_BUSY                (1 << 5)
+
+
+#if EXYNOS4_I2C_DEBUG
+#define DPRINT(fmt, args...)              \
+    do { fprintf(stderr, "QEMU I2C: "fmt, ## args); } while (0)
+
+static const char *exynos4_i2c_get_regname(unsigned offset)
+{
+    switch (offset) {
+    case I2CCON_ADDR:
+        return "I2CCON";
+    case I2CSTAT_ADDR:
+        return "I2CSTAT";
+    case I2CADD_ADDR:
+        return "I2CADD";
+    case I2CDS_ADDR:
+        return "I2CDS";
+    case I2CLC_ADDR:
+        return "I2CLC";
+    default:
+        return "[?]";
+    }
+}
+
+#else
+#define DPRINT(fmt, args...)              do { } while (0)
+#endif
+
+typedef struct Exynos4210I2CState {
+    SysBusDevice busdev;
+    MemoryRegion iomem;
+    i2c_bus *bus;
+    qemu_irq irq;
+
+    uint8_t i2ccon;
+    uint8_t i2cstat;
+    uint8_t i2cadd;
+    uint8_t i2cds;
+    uint8_t i2clc;
+    bool scl_free;
+} Exynos4210I2CState;
+
+static inline void exynos4210_i2c_raise_interrupt(Exynos4210I2CState *s)
+{
+    if (s->i2ccon & I2CCON_INTRS_EN) {
+        s->i2ccon |= I2CCON_INT_PEND;
+        qemu_irq_raise(s->irq);
+    }
+}
+
+static void exynos4210_i2c_data_receive(void *opaque)
+{
+    Exynos4210I2CState *s = (Exynos4210I2CState *)opaque;
+    int ret;
+
+    s->i2cstat &= ~I2CSTAT_LAST_BIT;
+    s->scl_free = false;
+    ret = i2c_recv(s->bus);
+    if (ret < 0 && (s->i2ccon & I2CCON_ACK_GEN)) {
+        s->i2cstat |= I2CSTAT_LAST_BIT;  /* Data is not acknowledged */
+    } else {
+        s->i2cds = ret;
+    }
+    exynos4210_i2c_raise_interrupt(s);
+}
+
+static void exynos4210_i2c_data_send(void *opaque)
+{
+    Exynos4210I2CState *s = (Exynos4210I2CState *)opaque;
+
+    s->i2cstat &= ~I2CSTAT_LAST_BIT;
+    s->scl_free = false;
+    if (i2c_send(s->bus, s->i2cds) < 0 && (s->i2ccon & I2CCON_ACK_GEN)) {
+        s->i2cstat |= I2CSTAT_LAST_BIT;
+    }
+    exynos4210_i2c_raise_interrupt(s);
+}
+
+static uint64_t exynos4210_i2c_read(void *opaque, target_phys_addr_t offset,
+                                 unsigned size)
+{
+    Exynos4210I2CState *s = (Exynos4210I2CState *)opaque;
+    uint8_t value;
+
+    switch (offset) {
+    case I2CCON_ADDR:
+        value = s->i2ccon;
+        break;
+    case I2CSTAT_ADDR:
+        value = s->i2cstat;
+        break;
+    case I2CADD_ADDR:
+        value = s->i2cadd;
+        break;
+    case I2CDS_ADDR:
+        value = s->i2cds;
+        s->scl_free = true;
+        if (EXYNOS4_I2C_MODE(s->i2cstat) == I2CMODE_MASTER_Rx &&
+               (s->i2cstat & I2CSTAT_START_BUSY) &&
+               !(s->i2ccon & I2CCON_INT_PEND)) {
+            exynos4210_i2c_data_receive(s);
+        }
+        break;
+    case I2CLC_ADDR:
+        value = s->i2clc;
+        break;
+    default:
+        value = 0;
+        DPRINT("ERROR: Bad read offset 0x%x\n", (unsigned int)offset);
+        break;
+    }
+
+    DPRINT("read %s [0x%02x] -> 0x%02x\n", exynos4_i2c_get_regname(offset),
+            (unsigned int)offset, value);
+    return value;
+}
+
+static void exynos4210_i2c_write(void *opaque, target_phys_addr_t offset,
+                              uint64_t value, unsigned size)
+{
+    Exynos4210I2CState *s = (Exynos4210I2CState *)opaque;
+    uint8_t v = value & 0xff;
+
+    DPRINT("write %s [0x%02x] <- 0x%02x\n", exynos4_i2c_get_regname(offset),
+            (unsigned int)offset, v);
+
+    switch (offset) {
+    case I2CCON_ADDR:
+        s->i2ccon = (v & ~I2CCON_INT_PEND) | (s->i2ccon & I2CCON_INT_PEND);
+        if ((s->i2ccon & I2CCON_INT_PEND) && !(v & I2CCON_INT_PEND)) {
+            s->i2ccon &= ~I2CCON_INT_PEND;
+            qemu_irq_lower(s->irq);
+            if (!(s->i2ccon & I2CCON_INTRS_EN)) {
+                s->i2cstat &= ~I2CSTAT_START_BUSY;
+            }
+
+            if (s->i2cstat & I2CSTAT_START_BUSY) {
+                if (s->scl_free) {
+                    if (EXYNOS4_I2C_MODE(s->i2cstat) == I2CMODE_MASTER_Tx) {
+                        exynos4210_i2c_data_send(s);
+                    } else if (EXYNOS4_I2C_MODE(s->i2cstat) ==
+                            I2CMODE_MASTER_Rx) {
+                        exynos4210_i2c_data_receive(s);
+                    }
+                } else {
+                    s->i2ccon |= I2CCON_INT_PEND;
+                    qemu_irq_raise(s->irq);
+                }
+            }
+        }
+        break;
+    case I2CSTAT_ADDR:
+        s->i2cstat =
+                (s->i2cstat & I2CSTAT_START_BUSY) | (v & ~I2CSTAT_START_BUSY);
+
+        if (!(s->i2cstat & I2CSTAT_OUTPUT_EN)) {
+            s->i2cstat &= ~I2CSTAT_START_BUSY;
+            s->scl_free = true;
+            qemu_irq_lower(s->irq);
+            break;
+        }
+
+        /* Nothing to do if in i2c slave mode */
+        if (!I2C_IN_MASTER_MODE(s->i2cstat)) {
+            break;
+        }
+
+        if (v & I2CSTAT_START_BUSY) {
+            s->i2cstat &= ~I2CSTAT_LAST_BIT;
+            s->i2cstat |= I2CSTAT_START_BUSY;    /* Line is busy */
+            s->scl_free = false;
+
+            /* Generate start bit and send slave address */
+            if (i2c_start_transfer(s->bus, s->i2cds >> 1, s->i2cds & 0x1) &&
+                    (s->i2ccon & I2CCON_ACK_GEN)) {
+                s->i2cstat |= I2CSTAT_LAST_BIT;
+            } else if (EXYNOS4_I2C_MODE(s->i2cstat) == I2CMODE_MASTER_Rx) {
+                exynos4210_i2c_data_receive(s);
+            }
+            exynos4210_i2c_raise_interrupt(s);
+        } else {
+            i2c_end_transfer(s->bus);
+            if (!(s->i2ccon & I2CCON_INT_PEND)) {
+                s->i2cstat &= ~I2CSTAT_START_BUSY;
+            }
+            s->scl_free = true;
+        }
+        break;
+    case I2CADD_ADDR:
+        if ((s->i2cstat & I2CSTAT_OUTPUT_EN) == 0) {
+            s->i2cadd = v;
+        }
+        break;
+    case I2CDS_ADDR:
+        if (s->i2cstat & I2CSTAT_OUTPUT_EN) {
+            s->i2cds = v;
+            s->scl_free = true;
+            if (EXYNOS4_I2C_MODE(s->i2cstat) == I2CMODE_MASTER_Tx &&
+                    (s->i2cstat & I2CSTAT_START_BUSY) &&
+                    !(s->i2ccon & I2CCON_INT_PEND)) {
+                exynos4210_i2c_data_send(s);
+            }
+        }
+        break;
+    case I2CLC_ADDR:
+        s->i2clc = v;
+        break;
+    default:
+        DPRINT("ERROR: Bad write offset 0x%x\n", (unsigned int)offset);
+        break;
+    }
+}
+
+static const MemoryRegionOps exynos4210_i2c_ops = {
+    .read = exynos4210_i2c_read,
+    .write = exynos4210_i2c_write,
+    .endianness = DEVICE_NATIVE_ENDIAN,
+};
+
+static const VMStateDescription exynos4210_i2c_vmstate = {
+    .name = TYPE_EXYNOS4_I2C,
+    .version_id = 1,
+    .minimum_version_id = 1,
+    .fields = (VMStateField[]) {
+        VMSTATE_UINT8(i2ccon, Exynos4210I2CState),
+        VMSTATE_UINT8(i2cstat, Exynos4210I2CState),
+        VMSTATE_UINT8(i2cds, Exynos4210I2CState),
+        VMSTATE_UINT8(i2cadd, Exynos4210I2CState),
+        VMSTATE_UINT8(i2clc, Exynos4210I2CState),
+        VMSTATE_BOOL(scl_free, Exynos4210I2CState),
+        VMSTATE_END_OF_LIST()
+    }
+};
+
+static void exynos4210_i2c_reset(DeviceState *d)
+{
+    Exynos4210I2CState *s = EXYNOS4_I2C(d);
+
+    s->i2ccon  = 0x00;
+    s->i2cstat = 0x00;
+    s->i2cds   = 0xFF;
+    s->i2clc   = 0x00;
+    s->i2cadd  = 0xFF;
+    s->scl_free = true;
+}
+
+static int exynos4210_i2c_realize(SysBusDevice *dev)
+{
+    Exynos4210I2CState *s = EXYNOS4_I2C(dev);
+
+    memory_region_init_io(&s->iomem, &exynos4210_i2c_ops, s, TYPE_EXYNOS4_I2C,
+                          EXYNOS4_I2C_MEM_SIZE);
+    sysbus_init_mmio(dev, &s->iomem);
+    sysbus_init_irq(dev, &s->irq);
+    s->bus = i2c_init_bus(&dev->qdev, "i2c");
+    return 0;
+}
+
+static void exynos4210_i2c_class_init(ObjectClass *klass, void *data)
+{
+    DeviceClass *dc = DEVICE_CLASS(klass);
+    SysBusDeviceClass *sbdc = SYS_BUS_DEVICE_CLASS(klass);
+
+    dc->vmsd = &exynos4210_i2c_vmstate;
+    dc->reset = exynos4210_i2c_reset;
+    sbdc->init = exynos4210_i2c_realize;
+}
+
+static const TypeInfo exynos4210_i2c_type_info = {
+    .name = TYPE_EXYNOS4_I2C,
+    .parent = TYPE_SYS_BUS_DEVICE,
+    .instance_size = sizeof(Exynos4210I2CState),
+    .class_init = exynos4210_i2c_class_init,
+};
+
+static void exynos4210_i2c_register_types(void)
+{
+    type_register_static(&exynos4210_i2c_type_info);
+}
+
+type_init(exynos4210_i2c_register_types)
commit 4688870d87883784bd151e0b7d024e5027c39f01
Author: Oleg Ogurtsov <o.ogurtsov at samsung.com>
Date:   Wed Jul 11 00:03:28 2012 +0000

    hw/exynos4210_rtc.c: remove unnecessary code
    
    Signed-off-by: Oleg Ogurtsov <o.ogurtsov at samsung.com>
    Signed-off-by: Peter Maydell <peter.maydell at linaro.org>

diff --git a/hw/exynos4210_rtc.c b/hw/exynos4210_rtc.c
index b42586e..42a4ddc 100644
--- a/hw/exynos4210_rtc.c
+++ b/hw/exynos4210_rtc.c
@@ -510,10 +510,7 @@ static void exynos4210_rtc_reset(DeviceState *d)
 {
     Exynos4210RTCState *s = (Exynos4210RTCState *)d;
 
-    struct tm tm;
-
-    qemu_get_timedate(&tm, 0);
-    s->current_tm = tm;
+    qemu_get_timedate(&s->current_tm, 0);
 
     DPRINTF("Get time from host: %d-%d-%d %2d:%02d:%02d\n",
             s->current_tm.tm_year, s->current_tm.tm_mon, s->current_tm.tm_mday,
commit 64de1ecfe7b3e88cb9f04c993e14ab85c2b5c532
Author: Oleg Ogurtsov <o.ogurtsov at samsung.com>
Date:   Wed Jul 11 00:03:27 2012 +0000

    hw/exynos4210_rtc.c: Fix calculating for value of year
    
    Signed-off-by: Oleg Ogurtsov <o.ogurtsov at samsung.com>
    Signed-off-by: Peter Maydell <peter.maydell at linaro.org>

diff --git a/hw/exynos4210_rtc.c b/hw/exynos4210_rtc.c
index f781020..b42586e 100644
--- a/hw/exynos4210_rtc.c
+++ b/hw/exynos4210_rtc.c
@@ -142,7 +142,7 @@ static const VMStateDescription vmstate_exynos4210_rtc_state = {
 };
 
 #define BCD3DIGITS(x) \
-    ((uint32_t)to_bcd((uint8_t)x) + \
+    ((uint32_t)to_bcd((uint8_t)(x % 100)) + \
     ((uint32_t)to_bcd((uint8_t)((x % 1000) / 100)) << 8))
 
 static void check_alarm_raise(Exynos4210RTCState *s)
commit 25d716998217e1fb37e16774060459c4dfff405e
Author: Peter Maydell <peter.maydell at linaro.org>
Date:   Fri Jul 20 13:34:50 2012 +0100

    hw/vexpress.c: Allow >4GB of RAM for Cortex-A15 daughterboard
    
    Now that we have LPAE support and can handle passing 64 bit
    RAM sizes to Linux via the device tree, we can lift the
    restriction in the Versatile Express A15 daughterboard model
    on not having more than 2GB of RAM. Allow up to 30GB, which
    is the maximum that can fit in the address map before running
    into the (unmodelled) aliases of the first 2GB.
    
    Signed-off-by: Peter Maydell <peter.maydell at linaro.org>

diff --git a/hw/vexpress.c b/hw/vexpress.c
index 8072c5a..b2dc8a5 100644
--- a/hw/vexpress.c
+++ b/hw/vexpress.c
@@ -284,9 +284,16 @@ static void a15_daughterboard_init(const VEDBoardInfo *daughterboard,
         cpu_irq[n] = irqp[ARM_PIC_CPU_IRQ];
     }
 
-    if (ram_size > 0x80000000) {
-        fprintf(stderr, "vexpress-a15: cannot model more than 2GB RAM\n");
-        exit(1);
+    {
+        /* We have to use a separate 64 bit variable here to avoid the gcc
+         * "comparison is always false due to limited range of data type"
+         * warning if we are on a host where ram_addr_t is 32 bits.
+         */
+        uint64_t rsz = ram_size;
+        if (rsz > (30ULL * 1024 * 1024 * 1024)) {
+            fprintf(stderr, "vexpress-a15: cannot model more than 30GB RAM\n");
+            exit(1);
+        }
     }
 
     memory_region_init_ram(ram, "vexpress.highmem", ram_size);
commit 9bfa659e6b33327e77d08018661fd1d707377e60
Author: Peter Maydell <peter.maydell at linaro.org>
Date:   Fri Jul 20 13:34:50 2012 +0100

    hw/arm_boot.c: Support DTBs which use 64 bit addresses
    
    Support the case where the device tree blob specifies that
    #address-cells and #size-cells are greater than 1. (This
    is needed for device trees which can handle 64 bit physical
    addresses and thus total RAM sizes over 4GB.)
    
    Signed-off-by: Peter Maydell <peter.maydell at linaro.org>
    Reviewed-by: Peter A. G. Crosthwaite <peter.crosthwaite at petalogix.com>

diff --git a/hw/arm_boot.c b/hw/arm_boot.c
index af71ed6..a6e9143 100644
--- a/hw/arm_boot.c
+++ b/hw/arm_boot.c
@@ -216,11 +216,12 @@ static void set_kernel_args_old(const struct arm_boot_info *info)
 static int load_dtb(target_phys_addr_t addr, const struct arm_boot_info *binfo)
 {
 #ifdef CONFIG_FDT
-    uint32_t mem_reg_property[] = { cpu_to_be32(binfo->loader_start),
-                                    cpu_to_be32(binfo->ram_size) };
+    uint32_t *mem_reg_property;
+    uint32_t mem_reg_propsize;
     void *fdt = NULL;
     char *filename;
     int size, rc;
+    uint32_t acells, scells, hival;
 
     filename = qemu_find_file(QEMU_FILE_TYPE_BIOS, binfo->dtb_filename);
     if (!filename) {
@@ -236,8 +237,36 @@ static int load_dtb(target_phys_addr_t addr, const struct arm_boot_info *binfo)
     }
     g_free(filename);
 
+    acells = qemu_devtree_getprop_cell(fdt, "/", "#address-cells");
+    scells = qemu_devtree_getprop_cell(fdt, "/", "#size-cells");
+    if (acells == 0 || scells == 0) {
+        fprintf(stderr, "dtb file invalid (#address-cells or #size-cells 0)\n");
+        return -1;
+    }
+
+    mem_reg_propsize = acells + scells;
+    mem_reg_property = g_new0(uint32_t, mem_reg_propsize);
+    mem_reg_property[acells - 1] = cpu_to_be32(binfo->loader_start);
+    hival = cpu_to_be32(binfo->loader_start >> 32);
+    if (acells > 1) {
+        mem_reg_property[acells - 2] = hival;
+    } else if (hival != 0) {
+        fprintf(stderr, "qemu: dtb file not compatible with "
+                "RAM start address > 4GB\n");
+        exit(1);
+    }
+    mem_reg_property[acells + scells - 1] = cpu_to_be32(binfo->ram_size);
+    hival = cpu_to_be32(binfo->ram_size >> 32);
+    if (scells > 1) {
+        mem_reg_property[acells + scells - 2] = hival;
+    } else if (hival != 0) {
+        fprintf(stderr, "qemu: dtb file not compatible with "
+                "RAM size > 4GB\n");
+        exit(1);
+    }
+
     rc = qemu_devtree_setprop(fdt, "/memory", "reg", mem_reg_property,
-                               sizeof(mem_reg_property));
+                              mem_reg_propsize * sizeof(uint32_t));
     if (rc < 0) {
         fprintf(stderr, "couldn't set /memory/reg\n");
     }
commit f0aa713f65e83ff39882b6c21d4b83500bf5ae80
Author: Peter Maydell <peter.maydell at linaro.org>
Date:   Fri Jul 20 13:34:50 2012 +0100

    device_tree: Add support for reading device tree properties
    
    Add support for reading device tree properties (both generic
    and single-cell ones) to QEMU's convenience wrapper layer.
    
    Signed-off-by: Peter Maydell <peter.maydell at linaro.org>
    Reviewed-by: Peter A. G. Crosthwaite <peter.crosthwaite at petalogix.com>

diff --git a/device_tree.c b/device_tree.c
index b366fdd..d7a9b6b 100644
--- a/device_tree.c
+++ b/device_tree.c
@@ -178,6 +178,36 @@ int qemu_devtree_setprop_string(void *fdt, const char *node_path,
     return r;
 }
 
+const void *qemu_devtree_getprop(void *fdt, const char *node_path,
+                                 const char *property, int *lenp)
+{
+    int len;
+    const void *r;
+    if (!lenp) {
+        lenp = &len;
+    }
+    r = fdt_getprop(fdt, findnode_nofail(fdt, node_path), property, lenp);
+    if (!r) {
+        fprintf(stderr, "%s: Couldn't get %s/%s: %s\n", __func__,
+                node_path, property, fdt_strerror(*lenp));
+        exit(1);
+    }
+    return r;
+}
+
+uint32_t qemu_devtree_getprop_cell(void *fdt, const char *node_path,
+                                   const char *property)
+{
+    int len;
+    const uint32_t *p = qemu_devtree_getprop(fdt, node_path, property, &len);
+    if (len != 4) {
+        fprintf(stderr, "%s: %s/%s not 4 bytes long (not a cell?)\n",
+                __func__, node_path, property);
+        exit(1);
+    }
+    return be32_to_cpu(*p);
+}
+
 uint32_t qemu_devtree_get_phandle(void *fdt, const char *path)
 {
     uint32_t r;
diff --git a/device_tree.h b/device_tree.h
index 2244270..f7a3e6c 100644
--- a/device_tree.h
+++ b/device_tree.h
@@ -28,6 +28,10 @@ int qemu_devtree_setprop_string(void *fdt, const char *node_path,
 int qemu_devtree_setprop_phandle(void *fdt, const char *node_path,
                                  const char *property,
                                  const char *target_node_path);
+const void *qemu_devtree_getprop(void *fdt, const char *node_path,
+                                 const char *property, int *lenp);
+uint32_t qemu_devtree_getprop_cell(void *fdt, const char *node_path,
+                                   const char *property);
 uint32_t qemu_devtree_get_phandle(void *fdt, const char *path);
 uint32_t qemu_devtree_alloc_phandle(void *fdt);
 int qemu_devtree_nop_node(void *fdt, const char *node_path);
commit 3871481c0a3f64f25563a5a246c188acdc01ee49
Author: Peter Maydell <peter.maydell at linaro.org>
Date:   Fri Jul 20 13:34:50 2012 +0100

    hw/arm_boot.c: Check for RAM sizes exceeding ATAGS capacity
    
    The legacy ATAGS format for passing information to the kernel only
    allows RAM sizes which fit in 32 bits; enforce this restriction
    rather than silently doing something weird.
    
    Signed-off-by: Peter Maydell <peter.maydell at linaro.org>
    Reviewed-by: Peter A. G. Crosthwaite <peter.crosthwaite at petalogix.com>

diff --git a/hw/arm_boot.c b/hw/arm_boot.c
index 29ae324..af71ed6 100644
--- a/hw/arm_boot.c
+++ b/hw/arm_boot.c
@@ -399,6 +399,12 @@ void arm_load_kernel(ARMCPU *cpu, struct arm_boot_info *info)
             bootloader[5] = dtb_start;
         } else {
             bootloader[5] = info->loader_start + KERNEL_ARGS_ADDR;
+            if (info->ram_size >= (1ULL << 32)) {
+                fprintf(stderr, "qemu: RAM size must be less than 4GB to boot"
+                        " Linux kernel using ATAGS (try passing a device tree"
+                        " using -dtb)\n");
+                exit(1);
+            }
         }
         bootloader[6] = entry;
         for (n = 0; n < sizeof(bootloader) / 4; n++) {
commit 0b94438480c8f52cc9e22b1038e6ba5096245c4e
Author: Peter Maydell <peter.maydell at linaro.org>
Date:   Fri Jul 20 13:34:50 2012 +0100

    hw/arm_boot.c: Consistently use ram_size from arm_boot_info struct
    
    Clean up the mix of getting the RAM size from the global ram_size
    and from the ram_size field in the arm_boot_info structure, so
    that we always use the structure field.
    
    Signed-off-by: Peter Maydell <peter.maydell at linaro.org>
    Reviewed-by: Peter A. G. Crosthwaite <peter.crosthwaite at petalogix.com>

diff --git a/hw/arm_boot.c b/hw/arm_boot.c
index a1e6ddb..29ae324 100644
--- a/hw/arm_boot.c
+++ b/hw/arm_boot.c
@@ -357,7 +357,7 @@ void arm_load_kernel(ARMCPU *cpu, struct arm_boot_info *info)
     if (kernel_size < 0) {
         entry = info->loader_start + KERNEL_LOAD_ADDR;
         kernel_size = load_image_targphys(info->kernel_filename, entry,
-                                          ram_size - KERNEL_LOAD_ADDR);
+                                          info->ram_size - KERNEL_LOAD_ADDR);
         is_linux = 1;
     }
     if (kernel_size < 0) {
@@ -371,7 +371,8 @@ void arm_load_kernel(ARMCPU *cpu, struct arm_boot_info *info)
             initrd_size = load_image_targphys(info->initrd_filename,
                                               info->loader_start
                                               + INITRD_LOAD_ADDR,
-                                              ram_size - INITRD_LOAD_ADDR);
+                                              info->ram_size
+                                              - INITRD_LOAD_ADDR);
             if (initrd_size < 0) {
                 fprintf(stderr, "qemu: could not load initrd '%s'\n",
                         info->initrd_filename);
commit de841dea59168e4abb8a2d09aaa30cc217fefda3
Author: Peter Maydell <peter.maydell at linaro.org>
Date:   Fri Jul 20 13:34:49 2012 +0100

    hw/arm_boot.c: Make ram_size a uint64_t
    
    Make the RAM size in arm_boot_info a uint64_t so it can express
    the larger RAM sizes that may be seen in LPAE systems.
    
    Signed-off-by: Peter Maydell <peter.maydell at linaro.org>
    Reviewed-by: Peter A. G. Crosthwaite <peter.crosthwaite at petalogix.com>

diff --git a/hw/arm-misc.h b/hw/arm-misc.h
index 1f96229..bdd8fec 100644
--- a/hw/arm-misc.h
+++ b/hw/arm-misc.h
@@ -25,7 +25,7 @@ qemu_irq *armv7m_init(MemoryRegion *address_space_mem,
 
 /* arm_boot.c */
 struct arm_boot_info {
-    int ram_size;
+    uint64_t ram_size;
     const char *kernel_filename;
     const char *kernel_cmdline;
     const char *initrd_filename;
commit 0d4abda8f7328c8911c1d020bb6961650eaf7801
Author: Peter Maydell <peter.maydell at linaro.org>
Date:   Fri Jul 20 13:34:49 2012 +0100

    hw/pl011.c: Avoid crash on read when no chr backend present
    
    Add a missing guard that meant we would segfault if the guest read
    UARTDR on a PL011 serial device which had no chr backend connected.
    (This didn't happen for Linux guests because Linux reads the flags
    register and doesn't try to read the UART if it's empty.)
    
    Reported-by: Christian Müller <christian.mueller at heig-vd.ch>
    Signed-off-by: Peter Maydell <peter.maydell at linaro.org>

diff --git a/hw/pl011.c b/hw/pl011.c
index 8a5a8f5..3245702 100644
--- a/hw/pl011.c
+++ b/hw/pl011.c
@@ -78,7 +78,9 @@ static uint64_t pl011_read(void *opaque, target_phys_addr_t offset,
         if (s->read_count == s->read_trigger - 1)
             s->int_level &= ~ PL011_INT_RX;
         pl011_update(s);
-        qemu_chr_accept_input(s->chr);
+        if (s->chr) {
+            qemu_chr_accept_input(s->chr);
+        }
         return c;
     case 1: /* UARTCR */
         return 0;
commit 6d2fe810ed995dc79090c2ba179f4f0c694243b1
Author: Juan Quintela <quintela at redhat.com>
Date:   Thu Jun 28 19:58:47 2012 +0200

    ram: save_live_setup() we don't need to synchronize the dirty bitmap.
    
    1st: we were synchonizing the dirty bitmap before calling
          memory_global_dirty_log_start().
    
    2nd: We are marking all pages as dirty anywhere, no reason to go
         through all the bitmap to "mark" dirty same pages twice.
    
    So, call removed.
    
    Signed-off-by: Juan Quintela <quintela at redhat.com>

diff --git a/arch_init.c b/arch_init.c
index b08c615..8cbf8f4 100644
--- a/arch_init.c
+++ b/arch_init.c
@@ -308,8 +308,6 @@ static int ram_save_setup(QEMUFile *f, void *opaque)
     ram_addr_t addr;
     RAMBlock *block;
 
-    memory_global_sync_dirty_bitmap(get_system_memory());
-
     bytes_transferred = 0;
     last_block = NULL;
     last_offset = 0;
commit 00d94f3f7648bc3d7126bc6b84d42e22194d9230
Author: Juan Quintela <quintela at redhat.com>
Date:   Thu Jun 28 19:51:17 2012 +0200

    ram: iterate phase
    
    We only need to synchronize the bitmap when the number of dirty pages is low.
    Not every time that we call the function.
    
    Signed-off-by: Juan Quintela <quintela at redhat.com>

diff --git a/arch_init.c b/arch_init.c
index 3c38a52..b08c615 100644
--- a/arch_init.c
+++ b/arch_init.c
@@ -348,8 +348,6 @@ static int ram_save_iterate(QEMUFile *f, void *opaque)
     int i;
     uint64_t expected_time;
 
-    memory_global_sync_dirty_bitmap(get_system_memory());
-
     bytes_transferred_last = bytes_transferred;
     bwidth = qemu_get_clock_ns(rt_clock);
 
@@ -398,7 +396,13 @@ static int ram_save_iterate(QEMUFile *f, void *opaque)
     DPRINTF("ram_save_live: expected(" PRIu64 ") <= max(" PRIu64 ")?\n",
             expected_time, migrate_max_downtime());
 
-    return expected_time <= migrate_max_downtime();
+    if (expected_time <= migrate_max_downtime()) {
+        memory_global_sync_dirty_bitmap(get_system_memory());
+        expected_time = ram_save_remaining() * TARGET_PAGE_SIZE / bwidth;
+
+        return expected_time <= migrate_max_downtime();
+    }
+    return 0;
 }
 
 static int ram_save_complete(QEMUFile *f, void *opaque)
commit b81e712d252cf41a0825f5abad0ce2f4746864f1
Author: Juan Quintela <quintela at redhat.com>
Date:   Thu Jun 28 19:48:09 2012 +0200

    ram: save_live_complete() only do one loop
    
    We were doing the same loop that stage2, and a new one for stage3.  We
    only need the one for stage3.
    
    Signed-off-by: Juan Quintela <quintela at redhat.com>

diff --git a/arch_init.c b/arch_init.c
index 2a6fc77..3c38a52 100644
--- a/arch_init.c
+++ b/arch_init.c
@@ -403,42 +403,10 @@ static int ram_save_iterate(QEMUFile *f, void *opaque)
 
 static int ram_save_complete(QEMUFile *f, void *opaque)
 {
-    double bwidth = 0;
-    int ret;
-    int i;
     int bytes_sent;
 
     memory_global_sync_dirty_bitmap(get_system_memory());
 
-    bwidth = qemu_get_clock_ns(rt_clock);
-
-    i = 0;
-    while ((ret = qemu_file_rate_limit(f)) == 0) {
-        bytes_sent = ram_save_block(f);
-        bytes_transferred += bytes_sent;
-        if (bytes_sent == 0) { /* no more blocks */
-            break;
-        }
-        /* we want to check in the 1st loop, just in case it was the 1st time
-           and we had to sync the dirty bitmap.
-           qemu_get_clock_ns() is a bit expensive, so we only check each some
-           iterations
-        */
-        if ((i & 63) == 0) {
-            uint64_t t1 = (qemu_get_clock_ns(rt_clock) - bwidth) / 1000000;
-            if (t1 > MAX_WAIT) {
-                DPRINTF("big wait: " PRIu64 " milliseconds, %d iterations\n",
-                        t1, i);
-                break;
-            }
-        }
-        i++;
-    }
-
-    if (ret < 0) {
-        return ret;
-    }
-
     /* try transferring iterative blocks of memory */
 
     /* flush all remaining blocks regardless of rate limiting */
commit 5910d1e6cbb190809d5dd0d75bb5e8398dd3ffb7
Author: Juan Quintela <quintela at redhat.com>
Date:   Thu Jun 28 19:41:52 2012 +0200

    ram: save_live_setup() don't need to sent pages
    
    We should send pages on interate phase, not in setup one.  This was a
    "bug".  Just removing the loop does what we want.  Tested that it
    works with current ram_load().
    
    Signed-off-by: Juan Quintela <quintela at redhat.com>

diff --git a/arch_init.c b/arch_init.c
index 7e04ea5..2a6fc77 100644
--- a/arch_init.c
+++ b/arch_init.c
@@ -307,9 +307,6 @@ static int ram_save_setup(QEMUFile *f, void *opaque)
 {
     ram_addr_t addr;
     RAMBlock *block;
-    double bwidth = 0;
-    int ret;
-    int i;
 
     memory_global_sync_dirty_bitmap(get_system_memory());
 
@@ -338,37 +335,6 @@ static int ram_save_setup(QEMUFile *f, void *opaque)
         qemu_put_be64(f, block->length);
     }
 
-    bwidth = qemu_get_clock_ns(rt_clock);
-
-    i = 0;
-    while ((ret = qemu_file_rate_limit(f)) == 0) {
-        int bytes_sent;
-
-        bytes_sent = ram_save_block(f);
-        bytes_transferred += bytes_sent;
-        if (bytes_sent == 0) { /* no more blocks */
-            break;
-        }
-        /* we want to check in the 1st loop, just in case it was the 1st time
-           and we had to sync the dirty bitmap.
-           qemu_get_clock_ns() is a bit expensive, so we only check each some
-           iterations
-        */
-        if ((i & 63) == 0) {
-            uint64_t t1 = (qemu_get_clock_ns(rt_clock) - bwidth) / 1000000;
-            if (t1 > MAX_WAIT) {
-                DPRINTF("big wait: " PRIu64 " milliseconds, %d iterations\n",
-                        t1, i);
-                break;
-            }
-        }
-        i++;
-    }
-
-    if (ret < 0) {
-        return ret;
-    }
-
     qemu_put_be64(f, RAM_SAVE_FLAG_EOS);
 
     return 0;
commit 16310a3cca7320edb9341c976f7819de0a8c27e0
Author: Juan Quintela <quintela at redhat.com>
Date:   Thu Jun 28 15:31:37 2012 +0200

    savevm: split save_live into stage2 and stage3
    
    We split it into 2 functions, foo_live_iterate, and foo_live_complete.
    At this point, we only remove the bits that are for the other stage,
    functionally this is equivalent to previous code.
    
    Signed-off-by: Juan Quintela <quintela at redhat.com>

diff --git a/arch_init.c b/arch_init.c
index 2a4903c..7e04ea5 100644
--- a/arch_init.c
+++ b/arch_init.c
@@ -374,12 +374,13 @@ static int ram_save_setup(QEMUFile *f, void *opaque)
     return 0;
 }
 
-static int ram_save_live(QEMUFile *f, int stage, void *opaque)
+static int ram_save_iterate(QEMUFile *f, void *opaque)
 {
     uint64_t bytes_transferred_last;
     double bwidth = 0;
     int ret;
     int i;
+    uint64_t expected_time;
 
     memory_global_sync_dirty_bitmap(get_system_memory());
 
@@ -424,28 +425,64 @@ static int ram_save_live(QEMUFile *f, int stage, void *opaque)
         bwidth = 0.000001;
     }
 
-    /* try transferring iterative blocks of memory */
-    if (stage == 3) {
-        int bytes_sent;
+    qemu_put_be64(f, RAM_SAVE_FLAG_EOS);
+
+    expected_time = ram_save_remaining() * TARGET_PAGE_SIZE / bwidth;
+
+    DPRINTF("ram_save_live: expected(" PRIu64 ") <= max(" PRIu64 ")?\n",
+            expected_time, migrate_max_downtime());
+
+    return expected_time <= migrate_max_downtime();
+}
+
+static int ram_save_complete(QEMUFile *f, void *opaque)
+{
+    double bwidth = 0;
+    int ret;
+    int i;
+    int bytes_sent;
 
-        /* flush all remaining blocks regardless of rate limiting */
-        while ((bytes_sent = ram_save_block(f)) != 0) {
-            bytes_transferred += bytes_sent;
+    memory_global_sync_dirty_bitmap(get_system_memory());
+
+    bwidth = qemu_get_clock_ns(rt_clock);
+
+    i = 0;
+    while ((ret = qemu_file_rate_limit(f)) == 0) {
+        bytes_sent = ram_save_block(f);
+        bytes_transferred += bytes_sent;
+        if (bytes_sent == 0) { /* no more blocks */
+            break;
         }
-        memory_global_dirty_log_stop();
+        /* we want to check in the 1st loop, just in case it was the 1st time
+           and we had to sync the dirty bitmap.
+           qemu_get_clock_ns() is a bit expensive, so we only check each some
+           iterations
+        */
+        if ((i & 63) == 0) {
+            uint64_t t1 = (qemu_get_clock_ns(rt_clock) - bwidth) / 1000000;
+            if (t1 > MAX_WAIT) {
+                DPRINTF("big wait: " PRIu64 " milliseconds, %d iterations\n",
+                        t1, i);
+                break;
+            }
+        }
+        i++;
     }
 
-    qemu_put_be64(f, RAM_SAVE_FLAG_EOS);
-
-    if (stage == 2) {
-        uint64_t expected_time;
-        expected_time = ram_save_remaining() * TARGET_PAGE_SIZE / bwidth;
+    if (ret < 0) {
+        return ret;
+    }
 
-        DPRINTF("ram_save_live: expected(" PRIu64 ") <= max(" PRIu64 ")?\n",
-                expected_time, migrate_max_downtime());
+    /* try transferring iterative blocks of memory */
 
-        return expected_time <= migrate_max_downtime();
+    /* flush all remaining blocks regardless of rate limiting */
+    while ((bytes_sent = ram_save_block(f)) != 0) {
+        bytes_transferred += bytes_sent;
     }
+    memory_global_dirty_log_stop();
+
+    qemu_put_be64(f, RAM_SAVE_FLAG_EOS);
+
     return 0;
 }
 
@@ -578,7 +615,8 @@ done:
 
 SaveVMHandlers savevm_ram_handlers = {
     .save_live_setup = ram_save_setup,
-    .save_live_state = ram_save_live,
+    .save_live_iterate = ram_save_iterate,
+    .save_live_complete = ram_save_complete,
     .load_state = ram_load,
     .cancel = ram_migration_cancel,
 };
diff --git a/block-migration.c b/block-migration.c
index fc3d1f4..7def8ab 100644
--- a/block-migration.c
+++ b/block-migration.c
@@ -568,12 +568,12 @@ static int block_save_setup(QEMUFile *f, void *opaque)
     return 0;
 }
 
-static int block_save_live(QEMUFile *f, int stage, void *opaque)
+static int block_save_iterate(QEMUFile *f, void *opaque)
 {
     int ret;
 
-    DPRINTF("Enter save live stage %d submitted %d transferred %d\n",
-            stage, block_mig_state.submitted, block_mig_state.transferred);
+    DPRINTF("Enter save live iterate submitted %d transferred %d\n",
+            block_mig_state.submitted, block_mig_state.transferred);
 
     flush_blks(f);
 
@@ -585,56 +585,76 @@ static int block_save_live(QEMUFile *f, int stage, void *opaque)
 
     blk_mig_reset_dirty_cursor();
 
-    if (stage == 2) {
-        /* control the rate of transfer */
-        while ((block_mig_state.submitted +
-                block_mig_state.read_done) * BLOCK_SIZE <
-               qemu_file_get_rate_limit(f)) {
-            if (block_mig_state.bulk_completed == 0) {
-                /* first finish the bulk phase */
-                if (blk_mig_save_bulked_block(f) == 0) {
-                    /* finished saving bulk on all devices */
-                    block_mig_state.bulk_completed = 1;
-                }
-            } else {
-                if (blk_mig_save_dirty_block(f, 1) == 0) {
-                    /* no more dirty blocks */
-                    break;
-                }
+    /* control the rate of transfer */
+    while ((block_mig_state.submitted +
+            block_mig_state.read_done) * BLOCK_SIZE <
+           qemu_file_get_rate_limit(f)) {
+        if (block_mig_state.bulk_completed == 0) {
+            /* first finish the bulk phase */
+            if (blk_mig_save_bulked_block(f) == 0) {
+                /* finished saving bulk on all devices */
+                block_mig_state.bulk_completed = 1;
+            }
+        } else {
+            if (blk_mig_save_dirty_block(f, 1) == 0) {
+                /* no more dirty blocks */
+                break;
             }
         }
+    }
 
-        flush_blks(f);
+    flush_blks(f);
 
-        ret = qemu_file_get_error(f);
-        if (ret) {
-            blk_mig_cleanup();
-            return ret;
-        }
+    ret = qemu_file_get_error(f);
+    if (ret) {
+        blk_mig_cleanup();
+        return ret;
     }
 
-    if (stage == 3) {
-        /* we know for sure that save bulk is completed and
-           all async read completed */
-        assert(block_mig_state.submitted == 0);
+    qemu_put_be64(f, BLK_MIG_FLAG_EOS);
+
+    return is_stage2_completed();
+}
+
+static int block_save_complete(QEMUFile *f, void *opaque)
+{
+    int ret;
+
+    DPRINTF("Enter save live complete submitted %d transferred %d\n",
+            block_mig_state.submitted, block_mig_state.transferred);
+
+    flush_blks(f);
 
-        while (blk_mig_save_dirty_block(f, 0) != 0);
+    ret = qemu_file_get_error(f);
+    if (ret) {
         blk_mig_cleanup();
+        return ret;
+    }
 
-        /* report completion */
-        qemu_put_be64(f, (100 << BDRV_SECTOR_BITS) | BLK_MIG_FLAG_PROGRESS);
+    blk_mig_reset_dirty_cursor();
 
-        ret = qemu_file_get_error(f);
-        if (ret) {
-            return ret;
-        }
+    /* we know for sure that save bulk is completed and
+       all async read completed */
+    assert(block_mig_state.submitted == 0);
+
+    while (blk_mig_save_dirty_block(f, 0) != 0) {
+        /* Do nothing */
+    }
+    blk_mig_cleanup();
+
+    /* report completion */
+    qemu_put_be64(f, (100 << BDRV_SECTOR_BITS) | BLK_MIG_FLAG_PROGRESS);
 
-        DPRINTF("Block migration completed\n");
+    ret = qemu_file_get_error(f);
+    if (ret) {
+        return ret;
     }
 
+    DPRINTF("Block migration completed\n");
+
     qemu_put_be64(f, BLK_MIG_FLAG_EOS);
 
-    return ((stage == 2) && is_stage2_completed());
+    return 0;
 }
 
 static int block_load(QEMUFile *f, void *opaque, int version_id)
@@ -731,7 +751,8 @@ static bool block_is_active(void *opaque)
 SaveVMHandlers savevm_block_handlers = {
     .set_params = block_set_params,
     .save_live_setup = block_save_setup,
-    .save_live_state = block_save_live,
+    .save_live_iterate = block_save_iterate,
+    .save_live_complete = block_save_complete,
     .load_state = block_load,
     .cancel = block_migration_cancel,
     .is_active = block_is_active,
diff --git a/savevm.c b/savevm.c
index 0b80a94..6e82b2d 100644
--- a/savevm.c
+++ b/savevm.c
@@ -1236,7 +1236,7 @@ int register_savevm_live(DeviceState *dev,
     se->vmsd = NULL;
     se->no_migrate = 0;
     /* if this is a live_savem then set is_ram */
-    if (ops->save_live_state != NULL) {
+    if (ops->save_live_setup != NULL) {
         se->is_ram = 1;
     }
 
@@ -1620,7 +1620,7 @@ int qemu_savevm_state_iterate(QEMUFile *f)
     int ret = 1;
 
     QTAILQ_FOREACH(se, &savevm_handlers, entry) {
-        if (!se->ops || !se->ops->save_live_state) {
+        if (!se->ops || !se->ops->save_live_iterate) {
             continue;
         }
         if (se->ops && se->ops->is_active) {
@@ -1636,7 +1636,7 @@ int qemu_savevm_state_iterate(QEMUFile *f)
         qemu_put_byte(f, QEMU_VM_SECTION_PART);
         qemu_put_be32(f, se->section_id);
 
-        ret = se->ops->save_live_state(f, QEMU_VM_SECTION_PART, se->opaque);
+        ret = se->ops->save_live_iterate(f, se->opaque);
         trace_savevm_section_end(se->section_id);
 
         if (ret <= 0) {
@@ -1665,7 +1665,7 @@ int qemu_savevm_state_complete(QEMUFile *f)
     cpu_synchronize_all_states();
 
     QTAILQ_FOREACH(se, &savevm_handlers, entry) {
-        if (!se->ops || !se->ops->save_live_state) {
+        if (!se->ops || !se->ops->save_live_complete) {
             continue;
         }
         if (se->ops && se->ops->is_active) {
@@ -1678,7 +1678,7 @@ int qemu_savevm_state_complete(QEMUFile *f)
         qemu_put_byte(f, QEMU_VM_SECTION_END);
         qemu_put_be32(f, se->section_id);
 
-        ret = se->ops->save_live_state(f, QEMU_VM_SECTION_END, se->opaque);
+        ret = se->ops->save_live_complete(f, se->opaque);
         trace_savevm_section_end(se->section_id);
         if (ret < 0) {
             return ret;
diff --git a/vmstate.h b/vmstate.h
index 049f2b7..5bd2b76 100644
--- a/vmstate.h
+++ b/vmstate.h
@@ -33,7 +33,8 @@ typedef struct SaveVMHandlers {
     void (*set_params)(const MigrationParams *params, void * opaque);
     SaveStateHandler *save_state;
     int (*save_live_setup)(QEMUFile *f, void *opaque);
-    int (*save_live_state)(QEMUFile *f, int stage, void *opaque);
+    int (*save_live_iterate)(QEMUFile *f, void *opaque);
+    int (*save_live_complete)(QEMUFile *f, void *opaque);
     void (*cancel)(void *opaque);
     LoadStateHandler *load_state;
     bool (*is_active)(void *opaque);
commit d1315aac6e4df1f472a6f87ef6e310b8c109f498
Author: Juan Quintela <quintela at redhat.com>
Date:   Thu Jun 28 15:11:57 2012 +0200

    savevm: split save_live_setup from save_live_state
    
    This patch splits stage 1 to its own function for both save_live
    users, ram and block.  It is just a copy of the function, removing the
    parts of the other stages.  Optimizations would came later.
    
    Signed-off-by: Juan Quintela <quintela at redhat.com>

diff --git a/arch_init.c b/arch_init.c
index f6bc3fe..2a4903c 100644
--- a/arch_init.c
+++ b/arch_init.c
@@ -303,44 +303,86 @@ static void ram_migration_cancel(void *opaque)
 
 #define MAX_WAIT 50 /* ms, half buffered_file limit */
 
-static int ram_save_live(QEMUFile *f, int stage, void *opaque)
+static int ram_save_setup(QEMUFile *f, void *opaque)
 {
     ram_addr_t addr;
-    uint64_t bytes_transferred_last;
+    RAMBlock *block;
     double bwidth = 0;
     int ret;
     int i;
 
     memory_global_sync_dirty_bitmap(get_system_memory());
 
-    if (stage == 1) {
-        RAMBlock *block;
-        bytes_transferred = 0;
-        last_block = NULL;
-        last_offset = 0;
-        sort_ram_list();
-
-        /* Make sure all dirty bits are set */
-        QLIST_FOREACH(block, &ram_list.blocks, next) {
-            for (addr = 0; addr < block->length; addr += TARGET_PAGE_SIZE) {
-                if (!memory_region_get_dirty(block->mr, addr, TARGET_PAGE_SIZE,
-                                             DIRTY_MEMORY_MIGRATION)) {
-                    memory_region_set_dirty(block->mr, addr, TARGET_PAGE_SIZE);
-                }
+    bytes_transferred = 0;
+    last_block = NULL;
+    last_offset = 0;
+    sort_ram_list();
+
+    /* Make sure all dirty bits are set */
+    QLIST_FOREACH(block, &ram_list.blocks, next) {
+        for (addr = 0; addr < block->length; addr += TARGET_PAGE_SIZE) {
+            if (!memory_region_get_dirty(block->mr, addr, TARGET_PAGE_SIZE,
+                                         DIRTY_MEMORY_MIGRATION)) {
+                memory_region_set_dirty(block->mr, addr, TARGET_PAGE_SIZE);
             }
         }
+    }
 
-        memory_global_dirty_log_start();
+    memory_global_dirty_log_start();
+
+    qemu_put_be64(f, ram_bytes_total() | RAM_SAVE_FLAG_MEM_SIZE);
+
+    QLIST_FOREACH(block, &ram_list.blocks, next) {
+        qemu_put_byte(f, strlen(block->idstr));
+        qemu_put_buffer(f, (uint8_t *)block->idstr, strlen(block->idstr));
+        qemu_put_be64(f, block->length);
+    }
+
+    bwidth = qemu_get_clock_ns(rt_clock);
 
-        qemu_put_be64(f, ram_bytes_total() | RAM_SAVE_FLAG_MEM_SIZE);
+    i = 0;
+    while ((ret = qemu_file_rate_limit(f)) == 0) {
+        int bytes_sent;
 
-        QLIST_FOREACH(block, &ram_list.blocks, next) {
-            qemu_put_byte(f, strlen(block->idstr));
-            qemu_put_buffer(f, (uint8_t *)block->idstr, strlen(block->idstr));
-            qemu_put_be64(f, block->length);
+        bytes_sent = ram_save_block(f);
+        bytes_transferred += bytes_sent;
+        if (bytes_sent == 0) { /* no more blocks */
+            break;
+        }
+        /* we want to check in the 1st loop, just in case it was the 1st time
+           and we had to sync the dirty bitmap.
+           qemu_get_clock_ns() is a bit expensive, so we only check each some
+           iterations
+        */
+        if ((i & 63) == 0) {
+            uint64_t t1 = (qemu_get_clock_ns(rt_clock) - bwidth) / 1000000;
+            if (t1 > MAX_WAIT) {
+                DPRINTF("big wait: " PRIu64 " milliseconds, %d iterations\n",
+                        t1, i);
+                break;
+            }
         }
+        i++;
+    }
+
+    if (ret < 0) {
+        return ret;
     }
 
+    qemu_put_be64(f, RAM_SAVE_FLAG_EOS);
+
+    return 0;
+}
+
+static int ram_save_live(QEMUFile *f, int stage, void *opaque)
+{
+    uint64_t bytes_transferred_last;
+    double bwidth = 0;
+    int ret;
+    int i;
+
+    memory_global_sync_dirty_bitmap(get_system_memory());
+
     bytes_transferred_last = bytes_transferred;
     bwidth = qemu_get_clock_ns(rt_clock);
 
@@ -535,6 +577,7 @@ done:
 }
 
 SaveVMHandlers savevm_ram_handlers = {
+    .save_live_setup = ram_save_setup,
     .save_live_state = ram_save_live,
     .load_state = ram_load,
     .cancel = ram_migration_cancel,
diff --git a/block-migration.c b/block-migration.c
index 6d37dc1..fc3d1f4 100644
--- a/block-migration.c
+++ b/block-migration.c
@@ -541,20 +541,40 @@ static void block_migration_cancel(void *opaque)
     blk_mig_cleanup();
 }
 
-static int block_save_live(QEMUFile *f, int stage, void *opaque)
+static int block_save_setup(QEMUFile *f, void *opaque)
 {
     int ret;
 
-    DPRINTF("Enter save live stage %d submitted %d transferred %d\n",
-            stage, block_mig_state.submitted, block_mig_state.transferred);
+    DPRINTF("Enter save live setup submitted %d transferred %d\n",
+            block_mig_state.submitted, block_mig_state.transferred);
 
-    if (stage == 1) {
-        init_blk_migration(f);
+    init_blk_migration(f);
+
+    /* start track dirty blocks */
+    set_dirty_tracking(1);
+
+    flush_blks(f);
 
-        /* start track dirty blocks */
-        set_dirty_tracking(1);
+    ret = qemu_file_get_error(f);
+    if (ret) {
+        blk_mig_cleanup();
+        return ret;
     }
 
+    blk_mig_reset_dirty_cursor();
+
+    qemu_put_be64(f, BLK_MIG_FLAG_EOS);
+
+    return 0;
+}
+
+static int block_save_live(QEMUFile *f, int stage, void *opaque)
+{
+    int ret;
+
+    DPRINTF("Enter save live stage %d submitted %d transferred %d\n",
+            stage, block_mig_state.submitted, block_mig_state.transferred);
+
     flush_blks(f);
 
     ret = qemu_file_get_error(f);
@@ -710,6 +730,7 @@ static bool block_is_active(void *opaque)
 
 SaveVMHandlers savevm_block_handlers = {
     .set_params = block_set_params,
+    .save_live_setup = block_save_setup,
     .save_live_state = block_save_live,
     .load_state = block_load,
     .cancel = block_migration_cancel,
diff --git a/savevm.c b/savevm.c
index afa0c9e..0b80a94 100644
--- a/savevm.c
+++ b/savevm.c
@@ -1573,7 +1573,7 @@ int qemu_savevm_state_begin(QEMUFile *f,
     QTAILQ_FOREACH(se, &savevm_handlers, entry) {
         int len;
 
-        if (!se->ops || !se->ops->save_live_state) {
+        if (!se->ops || !se->ops->save_live_setup) {
             continue;
         }
         if (se->ops && se->ops->is_active) {
@@ -1593,7 +1593,7 @@ int qemu_savevm_state_begin(QEMUFile *f,
         qemu_put_be32(f, se->instance_id);
         qemu_put_be32(f, se->version_id);
 
-        ret = se->ops->save_live_state(f, QEMU_VM_SECTION_START, se->opaque);
+        ret = se->ops->save_live_setup(f, se->opaque);
         if (ret < 0) {
             qemu_savevm_state_cancel(f);
             return ret;
diff --git a/vmstate.h b/vmstate.h
index 96651a5..049f2b7 100644
--- a/vmstate.h
+++ b/vmstate.h
@@ -32,6 +32,7 @@ typedef int LoadStateHandler(QEMUFile *f, void *opaque, int version_id);
 typedef struct SaveVMHandlers {
     void (*set_params)(const MigrationParams *params, void * opaque);
     SaveStateHandler *save_state;
+    int (*save_live_setup)(QEMUFile *f, void *opaque);
     int (*save_live_state)(QEMUFile *f, int stage, void *opaque);
     void (*cancel)(void *opaque);
     LoadStateHandler *load_state;
commit 6bd68781331590c4f2fbd1fdf98e80d7f6588b31
Author: Juan Quintela <quintela at redhat.com>
Date:   Wed Jun 27 10:59:15 2012 +0200

    savevm: introduce is_active method
    
    Enable the creation of a method to tell migration if that section is
    active and should be migrate.  We use it for blk-migration, that is
    normally not active.  We don't create the method for RAM, as setups
    without RAM are very strange O:-)
    
    Signed-off-by: Juan Quintela <quintela at redhat.com>

diff --git a/block-migration.c b/block-migration.c
index cd8a8dd..6d37dc1 100644
--- a/block-migration.c
+++ b/block-migration.c
@@ -548,13 +548,6 @@ static int block_save_live(QEMUFile *f, int stage, void *opaque)
     DPRINTF("Enter save live stage %d submitted %d transferred %d\n",
             stage, block_mig_state.submitted, block_mig_state.transferred);
 
-
-    if (block_mig_state.blk_enable != 1) {
-        /* no need to migrate storage */
-        qemu_put_be64(f, BLK_MIG_FLAG_EOS);
-        return 1;
-    }
-
     if (stage == 1) {
         init_blk_migration(f);
 
@@ -710,11 +703,17 @@ static void block_set_params(const MigrationParams *params, void *opaque)
     block_mig_state.blk_enable |= params->shared;
 }
 
+static bool block_is_active(void *opaque)
+{
+    return block_mig_state.blk_enable == 1;
+}
+
 SaveVMHandlers savevm_block_handlers = {
     .set_params = block_set_params,
     .save_live_state = block_save_live,
     .load_state = block_load,
     .cancel = block_migration_cancel,
+    .is_active = block_is_active,
 };
 
 void blk_mig_init(void)
diff --git a/savevm.c b/savevm.c
index 888c5a2..afa0c9e 100644
--- a/savevm.c
+++ b/savevm.c
@@ -1576,6 +1576,11 @@ int qemu_savevm_state_begin(QEMUFile *f,
         if (!se->ops || !se->ops->save_live_state) {
             continue;
         }
+        if (se->ops && se->ops->is_active) {
+            if (!se->ops->is_active(se->opaque)) {
+                continue;
+            }
+        }
         /* Section type */
         qemu_put_byte(f, QEMU_VM_SECTION_START);
         qemu_put_be32(f, se->section_id);
@@ -1618,6 +1623,11 @@ int qemu_savevm_state_iterate(QEMUFile *f)
         if (!se->ops || !se->ops->save_live_state) {
             continue;
         }
+        if (se->ops && se->ops->is_active) {
+            if (!se->ops->is_active(se->opaque)) {
+                continue;
+            }
+        }
         if (qemu_file_rate_limit(f)) {
             return 0;
         }
@@ -1658,6 +1668,11 @@ int qemu_savevm_state_complete(QEMUFile *f)
         if (!se->ops || !se->ops->save_live_state) {
             continue;
         }
+        if (se->ops && se->ops->is_active) {
+            if (!se->ops->is_active(se->opaque)) {
+                continue;
+            }
+        }
         trace_savevm_section_start();
         /* Section type */
         qemu_put_byte(f, QEMU_VM_SECTION_END);
diff --git a/vmstate.h b/vmstate.h
index 1dd42f5..96651a5 100644
--- a/vmstate.h
+++ b/vmstate.h
@@ -35,6 +35,7 @@ typedef struct SaveVMHandlers {
     int (*save_live_state)(QEMUFile *f, int stage, void *opaque);
     void (*cancel)(void *opaque);
     LoadStateHandler *load_state;
+    bool (*is_active)(void *opaque);
 } SaveVMHandlers;
 
 int register_savevm(DeviceState *dev,
commit 9b5bfab05f7c2a56d5908117e8cc62015e6b2c63
Author: Juan Quintela <quintela at redhat.com>
Date:   Tue Jun 26 19:26:41 2012 +0200

    savevm: Refactor cancel operation in its own operation
    
    Intead of abusing stage with value -1.
    
    Signed-off-by: Juan Quintela <quintela at redhat.com>

diff --git a/arch_init.c b/arch_init.c
index 606b848..f6bc3fe 100644
--- a/arch_init.c
+++ b/arch_init.c
@@ -296,6 +296,11 @@ static void migration_end(void)
     memory_global_dirty_log_stop();
 }
 
+static void ram_migration_cancel(void *opaque)
+{
+    migration_end();
+}
+
 #define MAX_WAIT 50 /* ms, half buffered_file limit */
 
 static int ram_save_live(QEMUFile *f, int stage, void *opaque)
@@ -306,11 +311,6 @@ static int ram_save_live(QEMUFile *f, int stage, void *opaque)
     int ret;
     int i;
 
-    if (stage < 0) {
-        migration_end();
-        return 0;
-    }
-
     memory_global_sync_dirty_bitmap(get_system_memory());
 
     if (stage == 1) {
@@ -537,6 +537,7 @@ done:
 SaveVMHandlers savevm_ram_handlers = {
     .save_live_state = ram_save_live,
     .load_state = ram_load,
+    .cancel = ram_migration_cancel,
 };
 
 #ifdef HAS_AUDIO
diff --git a/block-migration.c b/block-migration.c
index 00151a0..cd8a8dd 100644
--- a/block-migration.c
+++ b/block-migration.c
@@ -536,6 +536,11 @@ static void blk_mig_cleanup(void)
     }
 }
 
+static void block_migration_cancel(void *opaque)
+{
+    blk_mig_cleanup();
+}
+
 static int block_save_live(QEMUFile *f, int stage, void *opaque)
 {
     int ret;
@@ -543,10 +548,6 @@ static int block_save_live(QEMUFile *f, int stage, void *opaque)
     DPRINTF("Enter save live stage %d submitted %d transferred %d\n",
             stage, block_mig_state.submitted, block_mig_state.transferred);
 
-    if (stage < 0) {
-        blk_mig_cleanup();
-        return 0;
-    }
 
     if (block_mig_state.blk_enable != 1) {
         /* no need to migrate storage */
@@ -713,6 +714,7 @@ SaveVMHandlers savevm_block_handlers = {
     .set_params = block_set_params,
     .save_live_state = block_save_live,
     .load_state = block_load,
+    .cancel = block_migration_cancel,
 };
 
 void blk_mig_init(void)
diff --git a/savevm.c b/savevm.c
index a451be2..888c5a2 100644
--- a/savevm.c
+++ b/savevm.c
@@ -1703,8 +1703,8 @@ void qemu_savevm_state_cancel(QEMUFile *f)
     SaveStateEntry *se;
 
     QTAILQ_FOREACH(se, &savevm_handlers, entry) {
-        if (se->ops && se->ops->save_live_state) {
-            se->ops->save_live_state(f, -1, se->opaque);
+        if (se->ops && se->ops->cancel) {
+            se->ops->cancel(se->opaque);
         }
     }
 }
diff --git a/vmstate.h b/vmstate.h
index 0e24834..1dd42f5 100644
--- a/vmstate.h
+++ b/vmstate.h
@@ -33,6 +33,7 @@ typedef struct SaveVMHandlers {
     void (*set_params)(const MigrationParams *params, void * opaque);
     SaveStateHandler *save_state;
     int (*save_live_state)(QEMUFile *f, int stage, void *opaque);
+    void (*cancel)(void *opaque);
     LoadStateHandler *load_state;
 } SaveVMHandlers;
 
commit 226aa6a9b19e5465418fa62c5188acac280f1c13
Author: Juan Quintela <quintela at redhat.com>
Date:   Tue Jun 26 18:53:29 2012 +0200

    savevm: remove SaveLiveStateHandler
    
    It was used only once, just unfold.
    
    Signed-off-by: Juan Quintela <quintela at redhat.com>

diff --git a/vmstate.h b/vmstate.h
index 5e1a7cc..0e24834 100644
--- a/vmstate.h
+++ b/vmstate.h
@@ -27,13 +27,12 @@
 #define QEMU_VMSTATE_H 1
 
 typedef void SaveStateHandler(QEMUFile *f, void *opaque);
-typedef int SaveLiveStateHandler(QEMUFile *f, int stage, void *opaque);
 typedef int LoadStateHandler(QEMUFile *f, void *opaque, int version_id);
 
 typedef struct SaveVMHandlers {
     void (*set_params)(const MigrationParams *params, void * opaque);
     SaveStateHandler *save_state;
-    SaveLiveStateHandler *save_live_state;
+    int (*save_live_state)(QEMUFile *f, int stage, void *opaque);
     LoadStateHandler *load_state;
 } SaveVMHandlers;
 
commit 8625368515411ce941ac268287ba9e962ad26460
Author: Juan Quintela <quintela at redhat.com>
Date:   Tue Jun 26 18:51:00 2012 +0200

    savevm: remove SaveSetParamsHandler
    
    It was used only once, just unfold.
    
    Signed-off-by: Juan Quintela <quintela at redhat.com>

diff --git a/vmstate.h b/vmstate.h
index 4bce53b..5e1a7cc 100644
--- a/vmstate.h
+++ b/vmstate.h
@@ -26,13 +26,12 @@
 #ifndef QEMU_VMSTATE_H
 #define QEMU_VMSTATE_H 1
 
-typedef void SaveSetParamsHandler(const MigrationParams *params, void * opaque);
 typedef void SaveStateHandler(QEMUFile *f, void *opaque);
 typedef int SaveLiveStateHandler(QEMUFile *f, int stage, void *opaque);
 typedef int LoadStateHandler(QEMUFile *f, void *opaque, int version_id);
 
 typedef struct SaveVMHandlers {
-    SaveSetParamsHandler *set_params;
+    void (*set_params)(const MigrationParams *params, void * opaque);
     SaveStateHandler *save_state;
     SaveLiveStateHandler *save_live_state;
     LoadStateHandler *load_state;
commit 7908c78d3e1a117ae6b9545e601409eee3d33863
Author: Juan Quintela <quintela at redhat.com>
Date:   Tue Jun 26 18:46:10 2012 +0200

    savevm: Live migration handlers register the struct directly
    
    Notice that the live migration users never unregister, so no problem
    about freeing the ops structure.
    
    Signed-off-by: Juan Quintela <quintela at redhat.com>

diff --git a/arch_init.c b/arch_init.c
index 5b0f562..606b848 100644
--- a/arch_init.c
+++ b/arch_init.c
@@ -298,7 +298,7 @@ static void migration_end(void)
 
 #define MAX_WAIT 50 /* ms, half buffered_file limit */
 
-int ram_save_live(QEMUFile *f, int stage, void *opaque)
+static int ram_save_live(QEMUFile *f, int stage, void *opaque)
 {
     ram_addr_t addr;
     uint64_t bytes_transferred_last;
@@ -437,7 +437,7 @@ static inline void *host_from_stream_offset(QEMUFile *f,
     return NULL;
 }
 
-int ram_load(QEMUFile *f, void *opaque, int version_id)
+static int ram_load(QEMUFile *f, void *opaque, int version_id)
 {
     ram_addr_t addr;
     int flags, ret = 0;
@@ -534,6 +534,11 @@ done:
     return ret;
 }
 
+SaveVMHandlers savevm_ram_handlers = {
+    .save_live_state = ram_save_live,
+    .load_state = ram_load,
+};
+
 #ifdef HAS_AUDIO
 struct soundhw {
     const char *name;
diff --git a/block-migration.c b/block-migration.c
index b95b4e1..00151a0 100644
--- a/block-migration.c
+++ b/block-migration.c
@@ -709,11 +709,17 @@ static void block_set_params(const MigrationParams *params, void *opaque)
     block_mig_state.blk_enable |= params->shared;
 }
 
+SaveVMHandlers savevm_block_handlers = {
+    .set_params = block_set_params,
+    .save_live_state = block_save_live,
+    .load_state = block_load,
+};
+
 void blk_mig_init(void)
 {
     QSIMPLEQ_INIT(&block_mig_state.bmds_list);
     QSIMPLEQ_INIT(&block_mig_state.blk_list);
 
-    register_savevm_live(NULL, "block", 0, 1, block_set_params,
-                         block_save_live, NULL, block_load, &block_mig_state);
+    register_savevm_live(NULL, "block", 0, 1, &savevm_block_handlers,
+                         &block_mig_state);
 }
diff --git a/migration.h b/migration.h
index de13004..57572a6 100644
--- a/migration.h
+++ b/migration.h
@@ -18,6 +18,7 @@
 #include "qemu-common.h"
 #include "notify.h"
 #include "error.h"
+#include "vmstate.h"
 
 struct MigrationParams {
     bool blk;
@@ -81,8 +82,7 @@ uint64_t ram_bytes_remaining(void);
 uint64_t ram_bytes_transferred(void);
 uint64_t ram_bytes_total(void);
 
-int ram_save_live(QEMUFile *f, int stage, void *opaque);
-int ram_load(QEMUFile *f, void *opaque, int version_id);
+extern SaveVMHandlers savevm_ram_handlers;
 
 /**
  * @migrate_add_blocker - prevent migration from proceeding
diff --git a/savevm.c b/savevm.c
index 73626d4..a451be2 100644
--- a/savevm.c
+++ b/savevm.c
@@ -1223,10 +1223,7 @@ int register_savevm_live(DeviceState *dev,
                          const char *idstr,
                          int instance_id,
                          int version_id,
-                         SaveSetParamsHandler *set_params,
-                         SaveLiveStateHandler *save_live_state,
-                         SaveStateHandler *save_state,
-                         LoadStateHandler *load_state,
+                         SaveVMHandlers *ops,
                          void *opaque)
 {
     SaveStateEntry *se;
@@ -1234,16 +1231,12 @@ int register_savevm_live(DeviceState *dev,
     se = g_malloc0(sizeof(SaveStateEntry));
     se->version_id = version_id;
     se->section_id = global_section_id++;
-    se->ops = g_malloc0(sizeof(SaveVMHandlers));
-    se->ops->set_params = set_params;
-    se->ops->save_live_state = save_live_state;
-    se->ops->save_state = save_state;
-    se->ops->load_state = load_state;
+    se->ops = ops;
     se->opaque = opaque;
     se->vmsd = NULL;
     se->no_migrate = 0;
     /* if this is a live_savem then set is_ram */
-    if (save_live_state != NULL) {
+    if (ops->save_live_state != NULL) {
         se->is_ram = 1;
     }
 
@@ -1282,8 +1275,11 @@ int register_savevm(DeviceState *dev,
                     LoadStateHandler *load_state,
                     void *opaque)
 {
+    SaveVMHandlers *ops = g_malloc0(sizeof(SaveVMHandlers));
+    ops->save_state = save_state;
+    ops->load_state = load_state;
     return register_savevm_live(dev, idstr, instance_id, version_id,
-                                NULL, NULL, save_state, load_state, opaque);
+                                ops, opaque);
 }
 
 void unregister_savevm(DeviceState *dev, const char *idstr, void *opaque)
diff --git a/vl.c b/vl.c
index 8904db1..54e36ed 100644
--- a/vl.c
+++ b/vl.c
@@ -3437,8 +3437,7 @@ int main(int argc, char **argv, char **envp)
     default_drive(default_sdcard, snapshot, machine->use_scsi,
                   IF_SD, 0, SD_OPTS);
 
-    register_savevm_live(NULL, "ram", 0, 4, NULL, ram_save_live, NULL,
-                         ram_load, NULL);
+    register_savevm_live(NULL, "ram", 0, 4, &savevm_ram_handlers, NULL);
 
     if (nb_numa_nodes > 0) {
         int i;
diff --git a/vmstate.h b/vmstate.h
index 909af69..4bce53b 100644
--- a/vmstate.h
+++ b/vmstate.h
@@ -50,10 +50,7 @@ int register_savevm_live(DeviceState *dev,
                          const char *idstr,
                          int instance_id,
                          int version_id,
-                         SaveSetParamsHandler *set_params,
-                         SaveLiveStateHandler *save_live_state,
-                         SaveStateHandler *save_state,
-                         LoadStateHandler *load_state,
+                         SaveVMHandlers *ops,
                          void *opaque);
 
 void unregister_savevm(DeviceState *dev, const char *idstr, void *opaque);
commit 22ea40f4ff072a113fdf96bff10bc81ee063da32
Author: Juan Quintela <quintela at redhat.com>
Date:   Tue Jun 26 17:19:10 2012 +0200

    savevm: Use a struct to pass all handlers
    
    This would make easier to add more operations in the next patches.
    
    Signed-off-by: Juan Quintela <quintela at redhat.com>

diff --git a/savevm.c b/savevm.c
index a15c163..73626d4 100644
--- a/savevm.c
+++ b/savevm.c
@@ -1171,10 +1171,7 @@ typedef struct SaveStateEntry {
     int alias_id;
     int version_id;
     int section_id;
-    SaveSetParamsHandler *set_params;
-    SaveLiveStateHandler *save_live_state;
-    SaveStateHandler *save_state;
-    LoadStateHandler *load_state;
+    SaveVMHandlers *ops;
     const VMStateDescription *vmsd;
     void *opaque;
     CompatEntry *compat;
@@ -1237,10 +1234,11 @@ int register_savevm_live(DeviceState *dev,
     se = g_malloc0(sizeof(SaveStateEntry));
     se->version_id = version_id;
     se->section_id = global_section_id++;
-    se->set_params = set_params;
-    se->save_live_state = save_live_state;
-    se->save_state = save_state;
-    se->load_state = load_state;
+    se->ops = g_malloc0(sizeof(SaveVMHandlers));
+    se->ops->set_params = set_params;
+    se->ops->save_live_state = save_live_state;
+    se->ops->save_state = save_state;
+    se->ops->load_state = load_state;
     se->opaque = opaque;
     se->vmsd = NULL;
     se->no_migrate = 0;
@@ -1309,6 +1307,7 @@ void unregister_savevm(DeviceState *dev, const char *idstr, void *opaque)
             if (se->compat) {
                 g_free(se->compat);
             }
+            g_free(se->ops);
             g_free(se);
         }
     }
@@ -1327,9 +1326,6 @@ int vmstate_register_with_alias_id(DeviceState *dev, int instance_id,
     se = g_malloc0(sizeof(SaveStateEntry));
     se->version_id = vmsd->version_id;
     se->section_id = global_section_id++;
-    se->save_live_state = NULL;
-    se->save_state = NULL;
-    se->load_state = NULL;
     se->opaque = opaque;
     se->vmsd = vmsd;
     se->alias_id = alias_id;
@@ -1524,7 +1520,7 @@ void vmstate_save_state(QEMUFile *f, const VMStateDescription *vmsd,
 static int vmstate_load(QEMUFile *f, SaveStateEntry *se, int version_id)
 {
     if (!se->vmsd) {         /* Old style */
-        return se->load_state(f, se->opaque, version_id);
+        return se->ops->load_state(f, se->opaque, version_id);
     }
     return vmstate_load_state(f, se->vmsd, se->opaque, version_id);
 }
@@ -1532,7 +1528,7 @@ static int vmstate_load(QEMUFile *f, SaveStateEntry *se, int version_id)
 static void vmstate_save(QEMUFile *f, SaveStateEntry *se)
 {
     if (!se->vmsd) {         /* Old style */
-        se->save_state(f, se->opaque);
+        se->ops->save_state(f, se->opaque);
         return;
     }
     vmstate_save_state(f,se->vmsd, se->opaque);
@@ -1569,10 +1565,10 @@ int qemu_savevm_state_begin(QEMUFile *f,
     int ret;
 
     QTAILQ_FOREACH(se, &savevm_handlers, entry) {
-        if(se->set_params == NULL) {
+        if (!se->ops || !se->ops->set_params) {
             continue;
         }
-        se->set_params(params, se->opaque);
+        se->ops->set_params(params, se->opaque);
     }
     
     qemu_put_be32(f, QEMU_VM_FILE_MAGIC);
@@ -1581,9 +1577,9 @@ int qemu_savevm_state_begin(QEMUFile *f,
     QTAILQ_FOREACH(se, &savevm_handlers, entry) {
         int len;
 
-        if (se->save_live_state == NULL)
+        if (!se->ops || !se->ops->save_live_state) {
             continue;
-
+        }
         /* Section type */
         qemu_put_byte(f, QEMU_VM_SECTION_START);
         qemu_put_be32(f, se->section_id);
@@ -1596,7 +1592,7 @@ int qemu_savevm_state_begin(QEMUFile *f,
         qemu_put_be32(f, se->instance_id);
         qemu_put_be32(f, se->version_id);
 
-        ret = se->save_live_state(f, QEMU_VM_SECTION_START, se->opaque);
+        ret = se->ops->save_live_state(f, QEMU_VM_SECTION_START, se->opaque);
         if (ret < 0) {
             qemu_savevm_state_cancel(f);
             return ret;
@@ -1623,9 +1619,9 @@ int qemu_savevm_state_iterate(QEMUFile *f)
     int ret = 1;
 
     QTAILQ_FOREACH(se, &savevm_handlers, entry) {
-        if (se->save_live_state == NULL)
+        if (!se->ops || !se->ops->save_live_state) {
             continue;
-
+        }
         if (qemu_file_rate_limit(f)) {
             return 0;
         }
@@ -1634,7 +1630,7 @@ int qemu_savevm_state_iterate(QEMUFile *f)
         qemu_put_byte(f, QEMU_VM_SECTION_PART);
         qemu_put_be32(f, se->section_id);
 
-        ret = se->save_live_state(f, QEMU_VM_SECTION_PART, se->opaque);
+        ret = se->ops->save_live_state(f, QEMU_VM_SECTION_PART, se->opaque);
         trace_savevm_section_end(se->section_id);
 
         if (ret <= 0) {
@@ -1663,15 +1659,15 @@ int qemu_savevm_state_complete(QEMUFile *f)
     cpu_synchronize_all_states();
 
     QTAILQ_FOREACH(se, &savevm_handlers, entry) {
-        if (se->save_live_state == NULL)
+        if (!se->ops || !se->ops->save_live_state) {
             continue;
-
+        }
         trace_savevm_section_start();
         /* Section type */
         qemu_put_byte(f, QEMU_VM_SECTION_END);
         qemu_put_be32(f, se->section_id);
 
-        ret = se->save_live_state(f, QEMU_VM_SECTION_END, se->opaque);
+        ret = se->ops->save_live_state(f, QEMU_VM_SECTION_END, se->opaque);
         trace_savevm_section_end(se->section_id);
         if (ret < 0) {
             return ret;
@@ -1681,9 +1677,9 @@ int qemu_savevm_state_complete(QEMUFile *f)
     QTAILQ_FOREACH(se, &savevm_handlers, entry) {
         int len;
 
-	if (se->save_state == NULL && se->vmsd == NULL)
+        if ((!se->ops || !se->ops->save_state) && !se->vmsd) {
 	    continue;
-
+        }
         trace_savevm_section_start();
         /* Section type */
         qemu_put_byte(f, QEMU_VM_SECTION_FULL);
@@ -1711,8 +1707,8 @@ void qemu_savevm_state_cancel(QEMUFile *f)
     SaveStateEntry *se;
 
     QTAILQ_FOREACH(se, &savevm_handlers, entry) {
-        if (se->save_live_state) {
-            se->save_live_state(f, -1, se->opaque);
+        if (se->ops && se->ops->save_live_state) {
+            se->ops->save_live_state(f, -1, se->opaque);
         }
     }
 }
@@ -1765,7 +1761,7 @@ static int qemu_save_device_state(QEMUFile *f)
         if (se->is_ram) {
             continue;
         }
-        if (se->save_state == NULL && se->vmsd == NULL) {
+        if ((!se->ops || !se->ops->save_state) && !se->vmsd) {
             continue;
         }
 
diff --git a/vmstate.h b/vmstate.h
index 5af45e0..909af69 100644
--- a/vmstate.h
+++ b/vmstate.h
@@ -31,6 +31,13 @@ typedef void SaveStateHandler(QEMUFile *f, void *opaque);
 typedef int SaveLiveStateHandler(QEMUFile *f, int stage, void *opaque);
 typedef int LoadStateHandler(QEMUFile *f, void *opaque, int version_id);
 
+typedef struct SaveVMHandlers {
+    SaveSetParamsHandler *set_params;
+    SaveStateHandler *save_state;
+    SaveLiveStateHandler *save_live_state;
+    LoadStateHandler *load_state;
+} SaveVMHandlers;
+
 int register_savevm(DeviceState *dev,
                     const char *idstr,
                     int instance_id,
commit 61dc008f3529fa74a63aad1907438dad857e255a
Author: Anthony Liguori <aliguori at us.ibm.com>
Date:   Thu Jul 19 18:25:52 2012 -0500

    Revert "audio: Make PC speaker audio card available by default"
    
    This reverts commit 504972922da9b562f15e13544d3efca84b46b8fd which broke the
    build for ARM.
    
    I don't think this change is necessary.  If I'm wrong, please recommit this
    changeset with an appropriate fix for ARM.
    
    Signed-off-by: Anthony Liguori <aliguori at us.ibm.com>

diff --git a/configure b/configure
index e1f1cd8..cef0a71 100755
--- a/configure
+++ b/configure
@@ -90,8 +90,8 @@ static="no"
 sparc_cpu=""
 cross_prefix=""
 audio_drv_list=""
-audio_card_list="ac97 es1370 sb16 hda pcspk"
-audio_possible_cards="ac97 es1370 sb16 cs4231a adlib gus hda pcspk"
+audio_card_list="ac97 es1370 sb16 hda"
+audio_possible_cards="ac97 es1370 sb16 cs4231a adlib gus hda"
 block_drv_whitelist=""
 host_cc="gcc"
 helper_cflags=""
commit 504972922da9b562f15e13544d3efca84b46b8fd
Author: Jan Kiszka <jan.kiszka at siemens.com>
Date:   Thu Jul 19 17:57:51 2012 +0200

    audio: Make PC speaker audio card available by default
    
        [ The following text is in the "ISO-8859-1" character set. ]
        [ Your display is set for the "KOI8-R" character set.  ]
        [ Some special characters may be displayed incorrectly. ]
    
    Signed-off-by: Jan Kiszka <jan.kiszka at siemens.com>
    Signed-off-by: malc <av1474 at comtv.ru>

diff --git a/configure b/configure
index cef0a71..e1f1cd8 100755
--- a/configure
+++ b/configure
@@ -90,8 +90,8 @@ static="no"
 sparc_cpu=""
 cross_prefix=""
 audio_drv_list=""
-audio_card_list="ac97 es1370 sb16 hda"
-audio_possible_cards="ac97 es1370 sb16 cs4231a adlib gus hda"
+audio_card_list="ac97 es1370 sb16 hda pcspk"
+audio_possible_cards="ac97 es1370 sb16 cs4231a adlib gus hda pcspk"
 block_drv_whitelist=""
 host_cc="gcc"
 helper_cflags=""
commit 932d4a42afa28829fadf3cbfbb0507cc09aafd8b
Author: Alexey Kardashevskiy <aik at ozlabs.ru>
Date:   Thu Jul 19 10:35:07 2012 +1000

    msi/msix: added API to set MSI message address and data
    
    Added (msi|msix)_set_message() function for whoever might
    want to use them.
    
    Currently msi_notify()/msix_notify() write to these vectors to
    signal the guest about an interrupt so the correct values have to
    written there by the guest or QEMU.
    
    For example, POWER guest never initializes MSI/MSIX vectors, instead
    it uses RTAS hypercalls. So in order to support MSIX for virtio-pci on
    POWER we have to initialize MSI/MSIX message from QEMU.
    
    Signed-off-by: Alexey Kardashevskiy <aik at ozlabs.ru>
    Signed-off-by: Michael S. Tsirkin <mst at redhat.com>

diff --git a/hw/msi.c b/hw/msi.c
index 5233204..e2273a0 100644
--- a/hw/msi.c
+++ b/hw/msi.c
@@ -105,6 +105,23 @@ static inline uint8_t msi_pending_off(const PCIDevice* dev, bool msi64bit)
     return dev->msi_cap + (msi64bit ? PCI_MSI_PENDING_64 : PCI_MSI_PENDING_32);
 }
 
+/*
+ * Special API for POWER to configure the vectors through
+ * a side channel. Should never be used by devices.
+ */
+void msi_set_message(PCIDevice *dev, MSIMessage msg)
+{
+    uint16_t flags = pci_get_word(dev->config + msi_flags_off(dev));
+    bool msi64bit = flags & PCI_MSI_FLAGS_64BIT;
+
+    if (msi64bit) {
+        pci_set_quad(dev->config + msi_address_lo_off(dev), msg.address);
+    } else {
+        pci_set_long(dev->config + msi_address_lo_off(dev), msg.address);
+    }
+    pci_set_word(dev->config + msi_data_off(dev, msi64bit), msg.data);
+}
+
 bool msi_enabled(const PCIDevice *dev)
 {
     return msi_present(dev) &&
diff --git a/hw/msi.h b/hw/msi.h
index 75747ab..6ec1f99 100644
--- a/hw/msi.h
+++ b/hw/msi.h
@@ -31,6 +31,7 @@ struct MSIMessage {
 
 extern bool msi_supported;
 
+void msi_set_message(PCIDevice *dev, MSIMessage msg);
 bool msi_enabled(const PCIDevice *dev);
 int msi_init(struct PCIDevice *dev, uint8_t offset,
              unsigned int nr_vectors, bool msi64bit, bool msi_per_vector_mask);
diff --git a/hw/msix.c b/hw/msix.c
index fd9ea95..800fc32 100644
--- a/hw/msix.c
+++ b/hw/msix.c
@@ -37,6 +37,19 @@ static MSIMessage msix_get_message(PCIDevice *dev, unsigned vector)
     return msg;
 }
 
+/*
+ * Special API for POWER to configure the vectors through
+ * a side channel. Should never be used by devices.
+ */
+void msix_set_message(PCIDevice *dev, int vector, struct MSIMessage msg)
+{
+    uint8_t *table_entry = dev->msix_table + vector * PCI_MSIX_ENTRY_SIZE;
+
+    pci_set_quad(table_entry + PCI_MSIX_ENTRY_LOWER_ADDR, msg.address);
+    pci_set_long(table_entry + PCI_MSIX_ENTRY_DATA, msg.data);
+    table_entry[PCI_MSIX_ENTRY_VECTOR_CTRL] &= ~PCI_MSIX_ENTRY_CTRL_MASKBIT;
+}
+
 static uint8_t msix_pending_mask(int vector)
 {
     return 1 << (vector % 8);
diff --git a/hw/msix.h b/hw/msix.h
index 1786e27..15211cb 100644
--- a/hw/msix.h
+++ b/hw/msix.h
@@ -4,6 +4,7 @@
 #include "qemu-common.h"
 #include "pci.h"
 
+void msix_set_message(PCIDevice *dev, int vector, MSIMessage msg);
 int msix_init(PCIDevice *dev, unsigned short nentries,
               MemoryRegion *table_bar, uint8_t table_bar_nr,
               unsigned table_offset, MemoryRegion *pba_bar,
commit 0ae1625177aba9ac70beb1556615530ddb18086d
Author: Jan Kiszka <jan.kiszka at siemens.com>
Date:   Mon Jul 2 14:38:47 2012 +0200

    pci: Add INTx routing notifier
    
    This per-device notifier shall be triggered by any interrupt router
    along the path of a device's legacy interrupt signal on routing changes.
    For simplicity reasons and as this is a slow path anyway, no further
    details on the routing changes are provided. Instead, the callback is
    expected to use pci_device_route_intx_to_irq to check the effect of the
    change.
    
    Will be used by KVM PCI device assignment and VFIO.
    
    Signed-off-by: Jan Kiszka <jan.kiszka at siemens.com>
    Signed-off-by: Michael S. Tsirkin <mst at redhat.com>

diff --git a/hw/pci.c b/hw/pci.c
index e80599f..94601f2 100644
--- a/hw/pci.c
+++ b/hw/pci.c
@@ -1086,6 +1086,29 @@ PCIINTxRoute pci_device_route_intx_to_irq(PCIDevice *dev, int pin)
     return bus->route_intx_to_irq(bus->irq_opaque, pin);
 }
 
+void pci_bus_fire_intx_routing_notifier(PCIBus *bus)
+{
+    PCIDevice *dev;
+    PCIBus *sec;
+    int i;
+
+    for (i = 0; i < ARRAY_SIZE(bus->devices); ++i) {
+        dev = bus->devices[i];
+        if (dev && dev->intx_routing_notifier) {
+            dev->intx_routing_notifier(dev);
+        }
+        QLIST_FOREACH(sec, &bus->child, sibling) {
+            pci_bus_fire_intx_routing_notifier(sec);
+        }
+    }
+}
+
+void pci_device_set_intx_routing_notifier(PCIDevice *dev,
+                                          PCIINTxRoutingNotifier notifier)
+{
+    dev->intx_routing_notifier = notifier;
+}
+
 /***********************************************************/
 /* monitor info on PCI */
 
diff --git a/hw/pci.h b/hw/pci.h
index 7f7f88c..e96e8a7 100644
--- a/hw/pci.h
+++ b/hw/pci.h
@@ -182,6 +182,7 @@ typedef struct PCIDeviceClass {
     const char *romfile;
 } PCIDeviceClass;
 
+typedef void (*PCIINTxRoutingNotifier)(PCIDevice *dev);
 typedef int (*MSIVectorUseNotifier)(PCIDevice *dev, unsigned int vector,
                                       MSIMessage msg);
 typedef void (*MSIVectorReleaseNotifier)(PCIDevice *dev, unsigned int vector);
@@ -259,6 +260,9 @@ struct PCIDevice {
     MemoryRegion rom;
     uint32_t rom_bar;
 
+    /* INTx routing notifier */
+    PCIINTxRoutingNotifier intx_routing_notifier;
+
     /* MSI-X notifiers */
     MSIVectorUseNotifier msix_vector_use_notifier;
     MSIVectorReleaseNotifier msix_vector_release_notifier;
@@ -318,6 +322,9 @@ PCIBus *pci_register_bus(DeviceState *parent, const char *name,
                          uint8_t devfn_min, int nirq);
 void pci_bus_set_route_irq_fn(PCIBus *, pci_route_irq_fn);
 PCIINTxRoute pci_device_route_intx_to_irq(PCIDevice *dev, int pin);
+void pci_bus_fire_intx_routing_notifier(PCIBus *bus);
+void pci_device_set_intx_routing_notifier(PCIDevice *dev,
+                                          PCIINTxRoutingNotifier notifier);
 void pci_device_reset(PCIDevice *dev);
 void pci_bus_reset(PCIBus *bus);
 
diff --git a/hw/piix_pci.c b/hw/piix_pci.c
index 8ece07c..c497a01 100644
--- a/hw/piix_pci.c
+++ b/hw/piix_pci.c
@@ -423,6 +423,8 @@ static void piix3_write_config(PCIDevice *dev,
     if (ranges_overlap(address, len, PIIX_PIRQC, 4)) {
         PIIX3State *piix3 = DO_UPCAST(PIIX3State, dev, dev);
         int pic_irq;
+
+        pci_bus_fire_intx_routing_notifier(piix3->dev.bus);
         piix3_update_irq_levels(piix3);
         for (pic_irq = 0; pic_irq < PIIX_NUM_PIC_IRQS; pic_irq++) {
             piix3_set_irq_pic(piix3, pic_irq);
commit 3afa9bb488ea981d39255a25aaeb85eeafda41cb
Author: Michael S. Tsirkin <mst at redhat.com>
Date:   Thu Jul 19 17:11:47 2012 +0300

    pci: Add pci_device_route_intx_to_irq
    
    Device assigned on KVM needs to know the mode
    (enabled/inverted/disabled) and the IRQ number that a given device
    triggers in the attached interrupt controller.
    
    Add a PCI IRQ path discovery function that walks from a given device to
    the host bridge, and gets this information.  For
    this purpose, a host bridge callback function is introduced:
    route_intx_to_irq. It is so far only implemented by the PIIX3, other
    host bridges can be added later on as required.
    
    Will be used for KVM PCI device assignment and VFIO.
    
    Based on patch by Jan Kiszka, with minor tweaks.
    
    Signed-off-by: Jan Kiszka <jan.kiszka at siemens.com>
    Signed-off-by: Michael S. Tsirkin <mst at redhat.com>

diff --git a/hw/pci.c b/hw/pci.c
index ef7607e..e80599f 100644
--- a/hw/pci.c
+++ b/hw/pci.c
@@ -1066,6 +1066,26 @@ static void pci_set_irq(void *opaque, int irq_num, int level)
     pci_change_irq_level(pci_dev, irq_num, change);
 }
 
+/* Special hooks used by device assignment */
+void pci_bus_set_route_irq_fn(PCIBus *bus, pci_route_irq_fn route_intx_to_irq)
+{
+    assert(!bus->parent_dev);
+    bus->route_intx_to_irq = route_intx_to_irq;
+}
+
+PCIINTxRoute pci_device_route_intx_to_irq(PCIDevice *dev, int pin)
+{
+    PCIBus *bus;
+
+    do {
+         bus = dev->bus;
+         pin = bus->map_irq(dev, pin);
+         dev = bus->parent_dev;
+    } while (dev);
+    assert(bus->route_intx_to_irq);
+    return bus->route_intx_to_irq(bus->irq_opaque, pin);
+}
+
 /***********************************************************/
 /* monitor info on PCI */
 
diff --git a/hw/pci.h b/hw/pci.h
index 6983b2f..7f7f88c 100644
--- a/hw/pci.h
+++ b/hw/pci.h
@@ -141,6 +141,15 @@ enum {
 #define PCI_DEVICE_GET_CLASS(obj) \
      OBJECT_GET_CLASS(PCIDeviceClass, (obj), TYPE_PCI_DEVICE)
 
+typedef struct PCIINTxRoute {
+    enum {
+        PCI_INTX_ENABLED,
+        PCI_INTX_INVERTED,
+        PCI_INTX_DISABLED,
+    } mode;
+    int irq;
+} PCIINTxRoute;
+
 typedef struct PCIDeviceClass {
     DeviceClass parent_class;
 
@@ -278,6 +287,7 @@ MemoryRegion *pci_address_space_io(PCIDevice *dev);
 
 typedef void (*pci_set_irq_fn)(void *opaque, int irq_num, int level);
 typedef int (*pci_map_irq_fn)(PCIDevice *pci_dev, int irq_num);
+typedef PCIINTxRoute (*pci_route_irq_fn)(void *opaque, int pin);
 
 typedef enum {
     PCI_HOTPLUG_DISABLED,
@@ -306,6 +316,8 @@ PCIBus *pci_register_bus(DeviceState *parent, const char *name,
                          MemoryRegion *address_space_mem,
                          MemoryRegion *address_space_io,
                          uint8_t devfn_min, int nirq);
+void pci_bus_set_route_irq_fn(PCIBus *, pci_route_irq_fn);
+PCIINTxRoute pci_device_route_intx_to_irq(PCIDevice *dev, int pin);
 void pci_device_reset(PCIDevice *dev);
 void pci_bus_reset(PCIBus *bus);
 
diff --git a/hw/pci_internals.h b/hw/pci_internals.h
index 96690b7..d704704 100644
--- a/hw/pci_internals.h
+++ b/hw/pci_internals.h
@@ -19,6 +19,7 @@ struct PCIBus {
     uint8_t devfn_min;
     pci_set_irq_fn set_irq;
     pci_map_irq_fn map_irq;
+    pci_route_irq_fn route_intx_to_irq;
     pci_hotplug_fn hotplug;
     DeviceState *hotplug_qdev;
     void *irq_opaque;
diff --git a/hw/piix_pci.c b/hw/piix_pci.c
index 09e84f5..8ece07c 100644
--- a/hw/piix_pci.c
+++ b/hw/piix_pci.c
@@ -89,6 +89,7 @@ struct PCII440FXState {
 #define I440FX_SMRAM    0x72
 
 static void piix3_set_irq(void *opaque, int pirq, int level);
+static PCIINTxRoute piix3_route_intx_pin_to_irq(void *opaque, int pci_intx);
 static void piix3_write_config_xen(PCIDevice *dev,
                                uint32_t address, uint32_t val, int len);
 
@@ -315,6 +316,7 @@ static PCIBus *i440fx_common_init(const char *device_name,
                 pci_create_simple_multifunction(b, -1, true, "PIIX3"));
         pci_bus_irqs(b, piix3_set_irq, pci_slot_get_pirq, piix3,
                 PIIX_NUM_PIRQS);
+        pci_bus_set_route_irq_fn(b, piix3_route_intx_pin_to_irq);
     }
     piix3->pic = pic;
     *isa_bus = DO_UPCAST(ISABus, qbus,
@@ -386,6 +388,22 @@ static void piix3_set_irq(void *opaque, int pirq, int level)
     piix3_set_irq_level(piix3, pirq, level);
 }
 
+static PCIINTxRoute piix3_route_intx_pin_to_irq(void *opaque, int pin)
+{
+    PIIX3State *piix3 = opaque;
+    int irq = piix3->dev.config[PIIX_PIRQC + pin];
+    PCIINTxRoute route;
+
+    if (irq < PIIX_NUM_PIC_IRQS) {
+        route.mode = PCI_INTX_ENABLED;
+        route.irq = irq;
+    } else {
+        route.mode = PCI_INTX_DISABLED;
+        route.irq = -1;
+    }
+    return route;
+}
+
 /* irq routing is changed. so rebuild bitmap */
 static void piix3_update_irq_levels(PIIX3State *piix3)
 {
commit 90a147a275da3a432bdf00238ebf438eff1d2c1b
Author: Harsh Prateek Bora <harsh at linux.vnet.ibm.com>
Date:   Wed Jul 18 15:16:00 2012 +0530

    Update simpletrace.py for new log format
    
    Support new tracelog format for multiple arguments and strings.
    
    Signed-off-by: Harsh Prateek Bora <harsh at linux.vnet.ibm.com>
    Signed-off-by: Stefan Hajnoczi <stefanha at linux.vnet.ibm.com>

diff --git a/scripts/simpletrace.py b/scripts/simpletrace.py
index f55e5e6..9b4419f 100755
--- a/scripts/simpletrace.py
+++ b/scripts/simpletrace.py
@@ -12,53 +12,69 @@
 import struct
 import re
 import inspect
+from tracetool import _read_events, Event
+from tracetool.backend.simple import is_string
 
 header_event_id = 0xffffffffffffffff
 header_magic    = 0xf2b177cb0aa429b4
-header_version  = 0
 dropped_event_id = 0xfffffffffffffffe
 
-trace_fmt = '=QQQQQQQQ'
-trace_len = struct.calcsize(trace_fmt)
-event_re  = re.compile(r'(disable\s+)?([a-zA-Z0-9_]+)\(([^)]*)\).*')
+log_header_fmt = '=QQQ'
+rec_header_fmt = '=QQII'
 
-def parse_events(fobj):
-    """Parse a trace-events file into {event_num: (name, arg1, ...)}."""
-
-    def get_argnames(args):
-        """Extract argument names from a parameter list."""
-        return tuple(arg.split()[-1].lstrip('*') for arg in args.split(','))
-
-    events = {dropped_event_id: ('dropped', 'count')}
-    event_num = 0
-    for line in fobj:
-        m = event_re.match(line.strip())
-        if m is None:
-            continue
-
-        disable, name, args = m.groups()
-        events[event_num] = (name,) + get_argnames(args)
-        event_num += 1
-    return events
+def read_header(fobj, hfmt):
+    '''Read a trace record header'''
+    hlen = struct.calcsize(hfmt)
+    hdr = fobj.read(hlen)
+    if len(hdr) != hlen:
+        return None
+    return struct.unpack(hfmt, hdr)
 
-def read_record(fobj):
+def get_record(edict, rechdr, fobj):
     """Deserialize a trace record from a file into a tuple (event_num, timestamp, arg1, ..., arg6)."""
-    s = fobj.read(trace_len)
-    if len(s) != trace_len:
+    if rechdr is None:
         return None
-    return struct.unpack(trace_fmt, s)
+    rec = (rechdr[0], rechdr[1])
+    if rechdr[0] != dropped_event_id:
+        event_id = rechdr[0]
+        event = edict[event_id]
+        for type, name in event.args:
+            if is_string(type):
+                l = fobj.read(4)
+                (len,) = struct.unpack('=L', l)
+                s = fobj.read(len)
+                rec = rec + (s,)
+            else:
+                (value,) = struct.unpack('=Q', fobj.read(8))
+                rec = rec + (value,)
+    else:
+        (value,) = struct.unpack('=Q', fobj.read(8))
+        rec = rec + (value,)
+    return rec
+
+
+def read_record(edict, fobj):
+    """Deserialize a trace record from a file into a tuple (event_num, timestamp, arg1, ..., arg6)."""
+    rechdr = read_header(fobj, rec_header_fmt)
+    return get_record(edict, rechdr, fobj) # return tuple of record elements
 
-def read_trace_file(fobj):
+def read_trace_file(edict, fobj):
     """Deserialize trace records from a file, yielding record tuples (event_num, timestamp, arg1, ..., arg6)."""
-    header = read_record(fobj)
+    header = read_header(fobj, log_header_fmt)
     if header is None or \
        header[0] != header_event_id or \
-       header[1] != header_magic or \
-       header[2] != header_version:
-        raise ValueError('not a trace file or incompatible version')
+       header[1] != header_magic:
+        raise ValueError('Not a valid trace file!')
+    if header[2] != 0 and \
+       header[2] != 2:
+        raise ValueError('Unknown version of tracelog format!')
+
+    log_version = header[2]
+    if log_version == 0:
+        raise ValueError('Older log format, not supported with this Qemu release!')
 
     while True:
-        rec = read_record(fobj)
+        rec = read_record(edict, fobj)
         if rec is None:
             break
 
@@ -89,16 +105,29 @@ class Analyzer(object):
 def process(events, log, analyzer):
     """Invoke an analyzer on each event in a log."""
     if isinstance(events, str):
-        events = parse_events(open(events, 'r'))
+        events = _read_events(open(events, 'r'))
     if isinstance(log, str):
         log = open(log, 'rb')
 
+    enabled_events = []
+    dropped_event = Event.build("Dropped_Event(uint64_t num_events_dropped)")
+    edict = {dropped_event_id: dropped_event}
+
+    for e in events:
+        if 'disable' not in e.properties:
+            enabled_events.append(e)
+    for num, event in enumerate(enabled_events):
+        edict[num] = event
+
     def build_fn(analyzer, event):
-        fn = getattr(analyzer, event[0], None)
+        if isinstance(event, str):
+            return analyzer.catchall
+
+        fn = getattr(analyzer, event.name, None)
         if fn is None:
             return analyzer.catchall
 
-        event_argcount = len(event) - 1
+        event_argcount = len(event.args)
         fn_argcount = len(inspect.getargspec(fn)[0]) - 1
         if fn_argcount == event_argcount + 1:
             # Include timestamp as first argument
@@ -109,9 +138,9 @@ def process(events, log, analyzer):
 
     analyzer.begin()
     fn_cache = {}
-    for rec in read_trace_file(log):
+    for rec in read_trace_file(edict, log):
         event_num = rec[0]
-        event = events[event_num]
+        event = edict[event_num]
         if event_num not in fn_cache:
             fn_cache[event_num] = build_fn(analyzer, event)
         fn_cache[event_num](event, rec)
@@ -128,7 +157,7 @@ def run(analyzer):
         sys.stderr.write('usage: %s <trace-events> <trace-file>\n' % sys.argv[0])
         sys.exit(1)
 
-    events = parse_events(open(sys.argv[1], 'r'))
+    events = _read_events(open(sys.argv[1], 'r'))
     process(events, sys.argv[2], analyzer)
 
 if __name__ == '__main__':
@@ -137,15 +166,20 @@ if __name__ == '__main__':
             self.last_timestamp = None
 
         def catchall(self, event, rec):
+            i = 1
             timestamp = rec[1]
             if self.last_timestamp is None:
                 self.last_timestamp = timestamp
             delta_ns = timestamp - self.last_timestamp
             self.last_timestamp = timestamp
 
-            fields = [event[0], '%0.3f' % (delta_ns / 1000.0)]
-            for i in xrange(1, len(event)):
-                fields.append('%s=0x%x' % (event[i], rec[i + 1]))
+            fields = [event.name, '%0.3f' % (delta_ns / 1000.0)]
+            for type, name in event.args:
+                if is_string(type):
+                    fields.append('%s=%s' % (name, rec[i + 1]))
+                else:
+                    fields.append('%s=0x%x' % (name, rec[i + 1]))
+                i += 1
             print ' '.join(fields)
 
     run(Formatter())
commit 62bab73213ba885426a781eb2741670b9f3cae36
Author: Harsh Prateek Bora <harsh at linux.vnet.ibm.com>
Date:   Wed Jul 18 15:15:59 2012 +0530

    Simpletrace v2: Support multiple arguments, strings.
    
    Existing simpletrace backend allows to trace at max 6 args and does not
    support strings. This newer tracelog format gets rid of fixed size records
    and therefore allows to trace variable number of args including strings.
    
    Sample trace with strings:
    v9fs_version 0.000 tag=0xffff id=0x64 msize=0x2000 version=9P2000.L
    v9fs_version_return 6.705 tag=0xffff id=0x64 msize=0x2000 version=9P2000.L
    
    Signed-off-by: Harsh Prateek Bora <harsh at linux.vnet.ibm.com>
    Signed-off-by: Stefan Hajnoczi <stefanha at linux.vnet.ibm.com>

diff --git a/scripts/tracetool/backend/simple.py b/scripts/tracetool/backend/simple.py
index fbb5717..c7e47d6 100644
--- a/scripts/tracetool/backend/simple.py
+++ b/scripts/tracetool/backend/simple.py
@@ -15,9 +15,16 @@ __email__      = "stefanha at linux.vnet.ibm.com"
 
 from tracetool import out
 
+def is_string(arg):
+    strtype = ('const char*', 'char*', 'const char *', 'char *')
+    if arg.lstrip().startswith(strtype):
+        return True
+    else:
+        return False
 
 def c(events):
     out('#include "trace.h"',
+        '#include "trace/simple.h"',
         '',
         'TraceEvent trace_list[] = {')
 
@@ -26,30 +33,75 @@ def c(events):
             name = e.name,
             )
 
-    out('};')
+    out('};',
+        '')
+
+    for num, event in enumerate(events):
+        out('void trace_%(name)s(%(args)s)',
+            '{',
+            '    TraceBufferRecord rec;',
+            name = event.name,
+            args = event.args,
+            )
+        sizes = []
+        for type_, name in event.args:
+            if is_string(type_):
+                out('    size_t arg%(name)s_len = %(name)s ? MIN(strlen(%(name)s), MAX_TRACE_STRLEN) : 0;',
+                    name = name,
+                   )
+                strsizeinfo = "4 + arg%s_len" % name
+                sizes.append(strsizeinfo)
+            else:
+                sizes.append("8")
+        sizestr = " + ".join(sizes)
+        if len(event.args) == 0:
+            sizestr = '0'
+
+
+        out('',
+            '    if (!trace_list[%(event_id)s].state) {',
+            '        return;',
+            '    }',
+            '',
+            '    if (trace_record_start(&rec, %(event_id)s, %(size_str)s)) {',
+            '        return; /* Trace Buffer Full, Event Dropped ! */',
+            '    }',
+            event_id = num,
+            size_str = sizestr,
+            )
+
+        if len(event.args) > 0:
+            for type_, name in event.args:
+                # string
+                if is_string(type_):
+                    out('    trace_record_write_str(&rec, %(name)s, arg%(name)s_len);',
+                        name = name,
+                       )
+                # pointer var (not string)
+                elif type_.endswith('*'):
+                    out('    trace_record_write_u64(&rec, (uint64_t)(uint64_t *)%(name)s);',
+                        name = name,
+                       )
+                # primitive data type
+                else:
+                    out('    trace_record_write_u64(&rec, (uint64_t)%(name)s);',
+                       name = name,
+                       )
+
+        out('    trace_record_finish(&rec);',
+            '}',
+            '')
+
 
 def h(events):
     out('#include "trace/simple.h"',
         '')
 
-    for num, e in enumerate(events):
-        if len(e.args):
-            argstr = e.args.names()
-            arg_prefix = ', (uint64_t)(uintptr_t)'
-            cast_args = arg_prefix + arg_prefix.join(argstr)
-            simple_args = (str(num) + cast_args)
-        else:
-            simple_args = str(num)
-
-        out('static inline void trace_%(name)s(%(args)s)',
-            '{',
-            '    trace%(argc)d(%(trace_args)s);',
-            '}',
-            name = e.name,
-            args = e.args,
-            argc = len(e.args),
-            trace_args = simple_args,
+    for event in events:
+        out('void trace_%(name)s(%(args)s);',
+            name = event.name,
+            args = event.args,
             )
-
+    out('')
     out('#define NR_TRACE_EVENTS %d' % len(events))
     out('extern TraceEvent trace_list[NR_TRACE_EVENTS];')
diff --git a/trace/simple.c b/trace/simple.c
index b64bcf4..b700ea3 100644
--- a/trace/simple.c
+++ b/trace/simple.c
@@ -27,7 +27,7 @@
 #define HEADER_MAGIC 0xf2b177cb0aa429b4ULL
 
 /** Trace file version number, bump if format changes */
-#define HEADER_VERSION 0
+#define HEADER_VERSION 2
 
 /** Records were dropped event ID */
 #define DROPPED_EVENT_ID (~(uint64_t)0 - 1)
@@ -35,23 +35,6 @@
 /** Trace record is valid */
 #define TRACE_RECORD_VALID ((uint64_t)1 << 63)
 
-/** Trace buffer entry */
-typedef struct {
-    uint64_t event;
-    uint64_t timestamp_ns;
-    uint64_t x1;
-    uint64_t x2;
-    uint64_t x3;
-    uint64_t x4;
-    uint64_t x5;
-    uint64_t x6;
-} TraceRecord;
-
-enum {
-    TRACE_BUF_LEN = 4096,
-    TRACE_BUF_FLUSH_THRESHOLD = TRACE_BUF_LEN / 4,
-};
-
 /*
  * Trace records are written out by a dedicated thread.  The thread waits for
  * records to become available, writes them out, and then waits again.
@@ -62,11 +45,48 @@ static GCond *trace_empty_cond;
 static bool trace_available;
 static bool trace_writeout_enabled;
 
-static TraceRecord trace_buf[TRACE_BUF_LEN];
+enum {
+    TRACE_BUF_LEN = 4096 * 64,
+    TRACE_BUF_FLUSH_THRESHOLD = TRACE_BUF_LEN / 4,
+};
+
+uint8_t trace_buf[TRACE_BUF_LEN];
 static unsigned int trace_idx;
+static unsigned int writeout_idx;
+static uint64_t dropped_events;
 static FILE *trace_fp;
 static char *trace_file_name = NULL;
 
+/* * Trace buffer entry */
+typedef struct {
+    uint64_t event; /*   TraceEventID */
+    uint64_t timestamp_ns;
+    uint32_t length;   /*    in bytes */
+    uint32_t reserved; /*    unused */
+    uint8_t arguments[];
+} TraceRecord;
+
+typedef struct {
+    uint64_t header_event_id; /* HEADER_EVENT_ID */
+    uint64_t header_magic;    /* HEADER_MAGIC    */
+    uint64_t header_version;  /* HEADER_VERSION  */
+} TraceRecordHeader;
+
+
+static void read_from_buffer(unsigned int idx, void *dataptr, size_t size);
+static unsigned int write_to_buffer(unsigned int idx, void *dataptr, size_t size);
+
+static void clear_buffer_range(unsigned int idx, size_t len)
+{
+    uint32_t num = 0;
+    while (num < len) {
+        if (idx >= TRACE_BUF_LEN) {
+            idx = idx % TRACE_BUF_LEN;
+        }
+        trace_buf[idx++] = 0;
+        num++;
+    }
+}
 /**
  * Read a trace record from the trace buffer
  *
@@ -75,16 +95,30 @@ static char *trace_file_name = NULL;
  *
  * Returns false if the record is not valid.
  */
-static bool get_trace_record(unsigned int idx, TraceRecord *record)
+static bool get_trace_record(unsigned int idx, TraceRecord **recordptr)
 {
-    if (!(trace_buf[idx].event & TRACE_RECORD_VALID)) {
+    uint64_t event_flag = 0;
+    TraceRecord record;
+    /* read the event flag to see if its a valid record */
+    read_from_buffer(idx, &record, sizeof(event_flag));
+
+    if (!(record.event & TRACE_RECORD_VALID)) {
         return false;
     }
 
-    __sync_synchronize(); /* read memory barrier before accessing record */
-
-    *record = trace_buf[idx];
-    record->event &= ~TRACE_RECORD_VALID;
+    smp_rmb(); /* read memory barrier before accessing record */
+    /* read the record header to know record length */
+    read_from_buffer(idx, &record, sizeof(TraceRecord));
+    *recordptr = malloc(record.length); /* dont use g_malloc, can deadlock when traced */
+    /* make a copy of record to avoid being overwritten */
+    read_from_buffer(idx, *recordptr, record.length);
+    smp_rmb(); /* memory barrier before clearing valid flag */
+    (*recordptr)->event &= ~TRACE_RECORD_VALID;
+    /* clear the trace buffer range for consumed record otherwise any byte
+     * with its MSB set may be considered as a valid event id when the writer
+     * thread crosses this range of buffer again.
+     */
+    clear_buffer_range(idx, record.length);
     return true;
 }
 
@@ -120,29 +154,39 @@ static void wait_for_trace_records_available(void)
 
 static gpointer writeout_thread(gpointer opaque)
 {
-    TraceRecord record;
-    unsigned int writeout_idx = 0;
-    unsigned int num_available, idx;
+    TraceRecord *recordptr;
+    union {
+        TraceRecord rec;
+        uint8_t bytes[sizeof(TraceRecord) + sizeof(uint64_t)];
+    } dropped;
+    unsigned int idx = 0;
+    uint64_t dropped_count;
     size_t unused __attribute__ ((unused));
 
     for (;;) {
         wait_for_trace_records_available();
 
-        num_available = trace_idx - writeout_idx;
-        if (num_available > TRACE_BUF_LEN) {
-            record = (TraceRecord){
-                .event = DROPPED_EVENT_ID,
-                .x1 = num_available,
-            };
-            unused = fwrite(&record, sizeof(record), 1, trace_fp);
-            writeout_idx += num_available;
+        if (dropped_events) {
+            dropped.rec.event = DROPPED_EVENT_ID,
+            dropped.rec.timestamp_ns = get_clock();
+            dropped.rec.length = sizeof(TraceRecord) + sizeof(dropped_events),
+            dropped.rec.reserved = 0;
+            while (1) {
+                dropped_count = dropped_events;
+                if (g_atomic_int_compare_and_exchange((gint *)&dropped_events,
+                                                      dropped_count, 0)) {
+                    break;
+                }
+            }
+            memcpy(dropped.rec.arguments, &dropped_count, sizeof(uint64_t));
+            unused = fwrite(&dropped.rec, dropped.rec.length, 1, trace_fp);
         }
 
-        idx = writeout_idx % TRACE_BUF_LEN;
-        while (get_trace_record(idx, &record)) {
-            trace_buf[idx].event = 0; /* clear valid bit */
-            unused = fwrite(&record, sizeof(record), 1, trace_fp);
-            idx = ++writeout_idx % TRACE_BUF_LEN;
+        while (get_trace_record(idx, &recordptr)) {
+            unused = fwrite(recordptr, recordptr->length, 1, trace_fp);
+            writeout_idx += recordptr->length;
+            free(recordptr); /* dont use g_free, can deadlock when traced */
+            idx = writeout_idx % TRACE_BUF_LEN;
         }
 
         fflush(trace_fp);
@@ -150,73 +194,93 @@ static gpointer writeout_thread(gpointer opaque)
     return NULL;
 }
 
-static void trace(TraceEventID event, uint64_t x1, uint64_t x2, uint64_t x3,
-                  uint64_t x4, uint64_t x5, uint64_t x6)
+void trace_record_write_u64(TraceBufferRecord *rec, uint64_t val)
 {
-    unsigned int idx;
-    uint64_t timestamp;
-
-    if (!trace_list[event].state) {
-        return;
-    }
-
-    timestamp = get_clock();
-#if GLIB_CHECK_VERSION(2, 30, 0)
-    idx = g_atomic_int_add((gint *)&trace_idx, 1) % TRACE_BUF_LEN;
-#else
-    idx = g_atomic_int_exchange_and_add((gint *)&trace_idx, 1) % TRACE_BUF_LEN;
-#endif
-    trace_buf[idx] = (TraceRecord){
-        .event = event,
-        .timestamp_ns = timestamp,
-        .x1 = x1,
-        .x2 = x2,
-        .x3 = x3,
-        .x4 = x4,
-        .x5 = x5,
-        .x6 = x6,
-    };
-    __sync_synchronize(); /* write barrier before marking as valid */
-    trace_buf[idx].event |= TRACE_RECORD_VALID;
-
-    if ((idx + 1) % TRACE_BUF_FLUSH_THRESHOLD == 0) {
-        flush_trace_file(false);
-    }
+    rec->rec_off = write_to_buffer(rec->rec_off, &val, sizeof(uint64_t));
 }
 
-void trace0(TraceEventID event)
+void trace_record_write_str(TraceBufferRecord *rec, const char *s, uint32_t slen)
 {
-    trace(event, 0, 0, 0, 0, 0, 0);
+    /* Write string length first */
+    rec->rec_off = write_to_buffer(rec->rec_off, &slen, sizeof(slen));
+    /* Write actual string now */
+    rec->rec_off = write_to_buffer(rec->rec_off, (void*)s, slen);
 }
 
-void trace1(TraceEventID event, uint64_t x1)
+int trace_record_start(TraceBufferRecord *rec, TraceEventID event, size_t datasize)
 {
-    trace(event, x1, 0, 0, 0, 0, 0);
-}
+    unsigned int idx, rec_off, old_idx, new_idx;
+    uint32_t rec_len = sizeof(TraceRecord) + datasize;
+    uint64_t timestamp_ns = get_clock();
+
+    while (1) {
+        old_idx = trace_idx;
+        smp_rmb();
+        new_idx = old_idx + rec_len;
+
+        if (new_idx - writeout_idx > TRACE_BUF_LEN) {
+            /* Trace Buffer Full, Event dropped ! */
+            g_atomic_int_inc((gint *)&dropped_events);
+            return -ENOSPC;
+        }
 
-void trace2(TraceEventID event, uint64_t x1, uint64_t x2)
-{
-    trace(event, x1, x2, 0, 0, 0, 0);
-}
+        if (g_atomic_int_compare_and_exchange((gint *)&trace_idx,
+                                              old_idx, new_idx)) {
+            break;
+        }
+    }
 
-void trace3(TraceEventID event, uint64_t x1, uint64_t x2, uint64_t x3)
-{
-    trace(event, x1, x2, x3, 0, 0, 0);
+    idx = old_idx % TRACE_BUF_LEN;
+    /*  To check later if threshold crossed */
+    rec->next_tbuf_idx = new_idx % TRACE_BUF_LEN;
+
+    rec_off = idx;
+    rec_off = write_to_buffer(rec_off, (uint8_t*)&event, sizeof(event));
+    rec_off = write_to_buffer(rec_off, (uint8_t*)&timestamp_ns, sizeof(timestamp_ns));
+    rec_off = write_to_buffer(rec_off, (uint8_t*)&rec_len, sizeof(rec_len));
+
+    rec->tbuf_idx = idx;
+    rec->rec_off  = (idx + sizeof(TraceRecord)) % TRACE_BUF_LEN;
+    return 0;
 }
 
-void trace4(TraceEventID event, uint64_t x1, uint64_t x2, uint64_t x3, uint64_t x4)
+static void read_from_buffer(unsigned int idx, void *dataptr, size_t size)
 {
-    trace(event, x1, x2, x3, x4, 0, 0);
+    uint8_t *data_ptr = dataptr;
+    uint32_t x = 0;
+    while (x < size) {
+        if (idx >= TRACE_BUF_LEN) {
+            idx = idx % TRACE_BUF_LEN;
+        }
+        data_ptr[x++] = trace_buf[idx++];
+    }
 }
 
-void trace5(TraceEventID event, uint64_t x1, uint64_t x2, uint64_t x3, uint64_t x4, uint64_t x5)
+static unsigned int write_to_buffer(unsigned int idx, void *dataptr, size_t size)
 {
-    trace(event, x1, x2, x3, x4, x5, 0);
+    uint8_t *data_ptr = dataptr;
+    uint32_t x = 0;
+    while (x < size) {
+        if (idx >= TRACE_BUF_LEN) {
+            idx = idx % TRACE_BUF_LEN;
+        }
+        trace_buf[idx++] = data_ptr[x++];
+    }
+    return idx; /* most callers wants to know where to write next */
 }
 
-void trace6(TraceEventID event, uint64_t x1, uint64_t x2, uint64_t x3, uint64_t x4, uint64_t x5, uint64_t x6)
+void trace_record_finish(TraceBufferRecord *rec)
 {
-    trace(event, x1, x2, x3, x4, x5, x6);
+    uint8_t temp_rec[sizeof(TraceRecord)];
+    TraceRecord *record = (TraceRecord *) temp_rec;
+    read_from_buffer(rec->tbuf_idx, temp_rec, sizeof(TraceRecord));
+    smp_wmb(); /* write barrier before marking as valid */
+    record->event |= TRACE_RECORD_VALID;
+    write_to_buffer(rec->tbuf_idx, temp_rec, sizeof(TraceRecord));
+
+    if ((trace_idx - writeout_idx) > TRACE_BUF_FLUSH_THRESHOLD) {
+        flush_trace_file(false);
+    }
 }
 
 void st_set_trace_file_enabled(bool enable)
@@ -231,10 +295,11 @@ void st_set_trace_file_enabled(bool enable)
     flush_trace_file(true);
 
     if (enable) {
-        static const TraceRecord header = {
-            .event = HEADER_EVENT_ID,
-            .timestamp_ns = HEADER_MAGIC,
-            .x1 = HEADER_VERSION,
+        static const TraceRecordHeader header = {
+            .header_event_id = HEADER_EVENT_ID,
+            .header_magic = HEADER_MAGIC,
+            /* Older log readers will check for version at next location */
+            .header_version = HEADER_VERSION,
         };
 
         trace_fp = fopen(trace_file_name, "wb");
diff --git a/trace/simple.h b/trace/simple.h
index 6b5358c..7e521c1 100644
--- a/trace/simple.h
+++ b/trace/simple.h
@@ -22,16 +22,41 @@ typedef struct {
     bool state;
 } TraceEvent;
 
-void trace0(TraceEventID event);
-void trace1(TraceEventID event, uint64_t x1);
-void trace2(TraceEventID event, uint64_t x1, uint64_t x2);
-void trace3(TraceEventID event, uint64_t x1, uint64_t x2, uint64_t x3);
-void trace4(TraceEventID event, uint64_t x1, uint64_t x2, uint64_t x3, uint64_t x4);
-void trace5(TraceEventID event, uint64_t x1, uint64_t x2, uint64_t x3, uint64_t x4, uint64_t x5);
-void trace6(TraceEventID event, uint64_t x1, uint64_t x2, uint64_t x3, uint64_t x4, uint64_t x5, uint64_t x6);
 void st_print_trace_file_status(FILE *stream, fprintf_function stream_printf);
 void st_set_trace_file_enabled(bool enable);
 bool st_set_trace_file(const char *file);
 void st_flush_trace_buffer(void);
 
+typedef struct {
+    unsigned int tbuf_idx;
+    unsigned int next_tbuf_idx;
+    unsigned int rec_off;
+} TraceBufferRecord;
+
+/* Note for hackers: Make sure MAX_TRACE_LEN < sizeof(uint32_t) */
+#define MAX_TRACE_STRLEN 512
+/**
+ * Initialize a trace record and claim space for it in the buffer
+ *
+ * @arglen  number of bytes required for arguments
+ */
+int trace_record_start(TraceBufferRecord *rec, TraceEventID id, size_t arglen);
+
+/**
+ * Append a 64-bit argument to a trace record
+ */
+void trace_record_write_u64(TraceBufferRecord *rec, uint64_t val);
+
+/**
+ * Append a string argument to a trace record
+ */
+void trace_record_write_str(TraceBufferRecord *rec, const char *s, uint32_t slen);
+
+/**
+ * Mark a trace record completed
+ *
+ * Don't append any more arguments to the trace record after calling this.
+ */
+void trace_record_finish(TraceBufferRecord *rec);
+
 #endif /* TRACE_SIMPLE_H */
commit 88affa1c77c9019f3450f851495997897bd14e40
Author: Harsh Prateek Bora <harsh at linux.vnet.ibm.com>
Date:   Wed Jul 18 15:15:58 2012 +0530

    monitor: remove unused do_info_trace
    
    Going forward with simpletrace v2 variable size trace records, we cannot
    have a generic function to print trace event info and therefore this
    interface becomes invalid.
    
    As per Stefan Hajnoczi:
    
    "This command is only available from the human monitor.  It's not very
    useful because it historically hasn't been able to pretty-print events
    or show them in the right order (we use a ringbuffer but it prints
    them out from index 0).
    
    Therefore, I don't think we're under any obligation to keep this
    command around.  No one has complained about it's limitations - I
    think this is a sign that no one has used it.  I'd be okay with a
    patch that removes it."
    
    Ref: http://lists.gnu.org/archive/html/qemu-devel/2012-01/msg01268.html
    
    Signed-off-by: Harsh Prateek Bora <harsh at linux.vnet.ibm.com>
    Signed-off-by: Stefan Hajnoczi <stefanha at linux.vnet.ibm.com>

diff --git a/monitor.c b/monitor.c
index 09aa3cd..49dccfe 100644
--- a/monitor.c
+++ b/monitor.c
@@ -941,13 +941,6 @@ static void do_info_cpu_stats(Monitor *mon)
 }
 #endif
 
-#if defined(CONFIG_TRACE_SIMPLE)
-static void do_info_trace(Monitor *mon)
-{
-    st_print_trace((FILE *)mon, &monitor_fprintf);
-}
-#endif
-
 static void do_trace_print_events(Monitor *mon)
 {
     trace_print_events((FILE *)mon, &monitor_fprintf);
@@ -2689,15 +2682,6 @@ static mon_cmd_t info_cmds[] = {
         .help       = "show roms",
         .mhandler.info = do_info_roms,
     },
-#if defined(CONFIG_TRACE_SIMPLE)
-    {
-        .name       = "trace",
-        .args_type  = "",
-        .params     = "",
-        .help       = "show current contents of trace buffer",
-        .mhandler.info = do_info_trace,
-    },
-#endif
     {
         .name       = "trace-events",
         .args_type  = "",
diff --git a/trace/simple.c b/trace/simple.c
index b4a3c6e..b64bcf4 100644
--- a/trace/simple.c
+++ b/trace/simple.c
@@ -291,24 +291,6 @@ void st_print_trace_file_status(FILE *stream, int (*stream_printf)(FILE *stream,
                   trace_file_name, trace_fp ? "on" : "off");
 }
 
-void st_print_trace(FILE *stream, int (*stream_printf)(FILE *stream, const char *fmt, ...))
-{
-    unsigned int i;
-
-    for (i = 0; i < TRACE_BUF_LEN; i++) {
-        TraceRecord record;
-
-        if (!get_trace_record(i, &record)) {
-            continue;
-        }
-        stream_printf(stream, "Event %" PRIu64 " : %" PRIx64 " %" PRIx64
-                      " %" PRIx64 " %" PRIx64 " %" PRIx64 " %" PRIx64 "\n",
-                      record.event, record.x1, record.x2,
-                      record.x3, record.x4, record.x5,
-                      record.x6);
-    }
-}
-
 void st_flush_trace_buffer(void)
 {
     flush_trace_file(true);
diff --git a/trace/simple.h b/trace/simple.h
index 466e75b..6b5358c 100644
--- a/trace/simple.h
+++ b/trace/simple.h
@@ -29,7 +29,6 @@ void trace3(TraceEventID event, uint64_t x1, uint64_t x2, uint64_t x3);
 void trace4(TraceEventID event, uint64_t x1, uint64_t x2, uint64_t x3, uint64_t x4);
 void trace5(TraceEventID event, uint64_t x1, uint64_t x2, uint64_t x3, uint64_t x4, uint64_t x5);
 void trace6(TraceEventID event, uint64_t x1, uint64_t x2, uint64_t x3, uint64_t x4, uint64_t x5, uint64_t x6);
-void st_print_trace(FILE *stream, fprintf_function stream_printf);
 void st_print_trace_file_status(FILE *stream, fprintf_function stream_printf);
 void st_set_trace_file_enabled(bool enable);
 bool st_set_trace_file(const char *file);
commit 794b1f962eb3b1ceb6bbb98dd7a57f62fc0fbc11
Author: Alexey Kardashevskiy <aik at ozlabs.ru>
Date:   Thu Jun 14 14:41:40 2012 +1000

    trace: added ability to comment out events in the list
    
    It is convenient for debug to be able to switch on/off some events easily.
    The only possibility now is to remove event name from the file completely
    and type it again when we want it back.
    
    The patch adds '#' symbol handling as a comment specifier.
    
    Signed-off-by: Alexey Kardashevskiy <aik at ozlabs.ru>
    Signed-off-by: Stefan Hajnoczi <stefanha at linux.vnet.ibm.com>

diff --git a/trace/control.c b/trace/control.c
index 4c5527d..22d5863 100644
--- a/trace/control.c
+++ b/trace/control.c
@@ -27,6 +27,9 @@ void trace_backend_init_events(const char *fname)
         size_t len = strlen(line_buf);
         if (len > 1) {              /* skip empty lines */
             line_buf[len - 1] = '\0';
+            if ('#' == line_buf[0]) { /* skip commented lines */
+                continue;
+            }
             if (!trace_event_set_state(line_buf, true)) {
                 fprintf(stderr,
                         "error: trace event '%s' does not exist\n", line_buf);
commit dfe1ce5d80cba603bafaac91b239d683abe19cf7
Merge: 09f06a6... c3cdc1b...
Author: Anthony Liguori <aliguori at us.ibm.com>
Date:   Wed Jul 18 14:44:50 2012 -0500

    Merge remote-tracking branch 'kwolf/for-anthony' into staging
    
    * kwolf/for-anthony: (41 commits)
      fdc-test: Clean up a bit
      fdc-test: introduce test_relative_seek
      fdc: fix relative seek
      qemu-iotests: Valgrind support
      coroutine-ucontext: Help valgrind understand coroutines
      qemu-io: Fix memory leaks
      hw/block-common: Factor out fall back to legacy -drive cyls=...
      blockdev: Don't limit DriveInfo serial to 20 characters
      hw/block-common: Factor out fall back to legacy -drive serial=...
      hw/block-common: Move BlockConf & friends from block.h
      Relax IDE CHS limits from 16383,16,63 to 65535,16,255
      blockdev: Drop redundant CHS validation for if=ide
      hd-geometry: Compute BIOS CHS translation in one place
      qtest: Test we don't put hard disk info into CMOS for a CD-ROM
      ide pc: Put hard disk info into CMOS only for hard disks
      block: Geometry and translation hints are now useless, purge them
      qtest: Cover qdev property for BIOS CHS translation
      ide: qdev property for BIOS CHS translation
      qdev: New property type chs-translation
      qdev: Collect private helpers in one place
      ...

commit 09f06a6c603ce64284287d32f6ffadaaa5064850
Merge: 513e6bd... 15b2bd1...
Author: Anthony Liguori <aliguori at us.ibm.com>
Date:   Wed Jul 18 14:44:43 2012 -0500

    Merge remote-tracking branch 'qemu-kvm/uq/master' into staging
    
    * qemu-kvm/uq/master:
      virtio: move common irqfd handling out of virtio-pci
      virtio: move common ioeventfd handling out of virtio-pci
      event_notifier: add event_notifier_set_handler
      memory: pass EventNotifier, not eventfd
      ivshmem: wrap ivshmem_del_eventfd loops with transaction
      ivshmem: use EventNotifier and memory API
      event_notifier: add event_notifier_init_fd
      event_notifier: remove event_notifier_test
      event_notifier: add event_notifier_set
      apic: Defer interrupt updates to VCPU thread
      apic: Reevaluate pending interrupts on LVT_LINT0 changes
      apic: Resolve potential endless loop around apic_update_irq
      kvm: expose tsc deadline timer feature to guest
      kvm_pv_eoi: add flag support
      kvm: Don't abort on kvm_irqchip_add_msi_route()

commit 513e6bde4fa551c293e7d346e27b618b57a4087a
Merge: 052bb77... 208c9d1...
Author: Anthony Liguori <aliguori at us.ibm.com>
Date:   Wed Jul 18 14:44:37 2012 -0500

    Merge remote-tracking branch 'qmp/queue/qmp' into staging
    
    * qmp/queue/qmp:
      qapi: Convert getfd and closefd
      qapi: input_type_enum(): fix error message
      qmp: dump-guest-memory: improve schema doc

commit 052bb77a47ce2508538d0e4c9a2fb4b9787a2267
Merge: 83199ca... b456677...
Author: Anthony Liguori <aliguori at us.ibm.com>
Date:   Wed Jul 18 14:44:32 2012 -0500

    Merge remote-tracking branch 'kraxel/bios.2' into staging
    
    * kraxel/bios.2:
      Add vgabios build rules to roms/Makefile

commit 83199ca43c81e6931e62e133d9e53024108831ed
Merge: cb5fc67... afb7a0b...
Author: Anthony Liguori <aliguori at us.ibm.com>
Date:   Wed Jul 18 14:44:27 2012 -0500

    Merge remote-tracking branch 'kraxel/usb.57' into staging
    
    * kraxel/usb.57:
      ehci: improve expire time calculation
      ehci: implement Interrupt Threshold Control support
      ehci: raise irq in the frame timer
      uhci: initialize expire_time when loading v1 vmstate
      usb: add usb attached scsi emulation
      scsi: add free_request callback

commit cb5fc67db90d80c5dddbd7be1044cc10ef471974
Author: Anthony Liguori <aliguori at us.ibm.com>
Date:   Tue Jul 17 18:58:20 2012 -0500

    build: fix build breakage due to bad merge
    
    34bb443ee74df3780d86044dbf6492eb798c5807 broke the build but in a subtle way.
    The patch on the ML was actually based on the 1.1.1 stable branch
    (accidentally).  When I merged it from the ML, the fuzzing got resolved in a
    such a way that the newly introduced Makefile dependency on GENERATED_HEADERS
    got lost (that was not in 1.1.1).
    
    The dist bits also got duplicated (but this is just cosmetic).
    
    Signed-off-by: Anthony Liguori <aliguori at us.ibm.com>

diff --git a/Makefile b/Makefile
index 720c108..ab82ef3 100644
--- a/Makefile
+++ b/Makefile
@@ -240,13 +240,6 @@ dist: qemu-$(VERSION).tar.bz2
 qemu-%.tar.bz2:
 	$(SRC_PATH)/scripts/make-release "$(SRC_PATH)" "$(patsubst qemu-%.tar.bz2,%,$@)"
 
-VERSION ?= $(shell cat VERSION)
-
-dist: qemu-$(VERSION).tar.bz2
-
-qemu-%.tar.bz2:
-	$(SRC_PATH)/scripts/make-release "$(SRC_PATH)" "$(patsubst qemu-%.tar.bz2,%,$@)"
-
 distclean: clean
 	rm -f config-host.mak config-host.h* config-host.ld $(DOCS) qemu-options.texi qemu-img-cmds.texi qemu-monitor.texi
 	rm -f config-all-devices.mak
@@ -405,6 +398,10 @@ qemu-doc.dvi qemu-doc.html qemu-doc.info qemu-doc.pdf: \
 	qemu-img.texi qemu-nbd.texi qemu-options.texi \
 	qemu-monitor.texi qemu-img-cmds.texi
 
+# Add a dependency on the generated files, so that they are always
+# rebuilt before other object files
+Makefile: $(GENERATED_HEADERS)
+
 # Include automatically generated dependency files
 # All subdir dependencies come automatically from our recursive subdir rules
 -include $(wildcard *.d)
commit 34bb443ee74df3780d86044dbf6492eb798c5807
Author: Anthony Liguori <aliguori at us.ibm.com>
Date:   Tue Jul 17 13:33:32 2012 -0500

    build: add make dist target (v2)
    
    Let's stop screwing up releases by having a script do the work that Anthony's
    fat fingers can't seem to get right.
    
    Cc: Michael Roth <mdroth at linux.vnet.ibm.com>
    Reviewed-by: Eric Blake <eblake at redhat.com>
    Tested-by: Michael Roth <mdroth at linux.vnet.ibm.com>
    Signed-off-by: Anthony Liguori <aliguori at us.ibm.com>

diff --git a/Makefile b/Makefile
index 6eeabd0..720c108 100644
--- a/Makefile
+++ b/Makefile
@@ -31,7 +31,7 @@ Makefile: ;
 configure: ;
 
 .PHONY: all clean cscope distclean dvi html info install install-doc \
-	pdf recurse-all speed tar tarbin test
+	pdf recurse-all speed test dist
 
 $(call set-vpath, $(SRC_PATH))
 
@@ -233,6 +233,20 @@ clean:
 	rm -f $$d/qemu-options.def; \
         done
 
+VERSION ?= $(shell cat VERSION)
+
+dist: qemu-$(VERSION).tar.bz2
+
+qemu-%.tar.bz2:
+	$(SRC_PATH)/scripts/make-release "$(SRC_PATH)" "$(patsubst qemu-%.tar.bz2,%,$@)"
+
+VERSION ?= $(shell cat VERSION)
+
+dist: qemu-$(VERSION).tar.bz2
+
+qemu-%.tar.bz2:
+	$(SRC_PATH)/scripts/make-release "$(SRC_PATH)" "$(patsubst qemu-%.tar.bz2,%,$@)"
+
 distclean: clean
 	rm -f config-host.mak config-host.h* config-host.ld $(DOCS) qemu-options.texi qemu-img-cmds.texi qemu-monitor.texi
 	rm -f config-all-devices.mak
@@ -391,20 +405,6 @@ qemu-doc.dvi qemu-doc.html qemu-doc.info qemu-doc.pdf: \
 	qemu-img.texi qemu-nbd.texi qemu-options.texi \
 	qemu-monitor.texi qemu-img-cmds.texi
 
-VERSION ?= $(shell cat VERSION)
-FILE = qemu-$(VERSION)
-
-# tar release (use 'make -k tar' on a checkouted tree)
-tar:
-	rm -rf /tmp/$(FILE)
-	cp -r . /tmp/$(FILE)
-	cd /tmp && tar zcvf ~/$(FILE).tar.gz $(FILE) --exclude CVS --exclude .git --exclude .svn
-	rm -rf /tmp/$(FILE)
-
-# Add a dependency on the generated files, so that they are always
-# rebuilt before other object files
-Makefile: $(GENERATED_HEADERS)
-
 # Include automatically generated dependency files
 # All subdir dependencies come automatically from our recursive subdir rules
 -include $(wildcard *.d)
diff --git a/scripts/make-release b/scripts/make-release
new file mode 100755
index 0000000..196c755
--- /dev/null
+++ b/scripts/make-release
@@ -0,0 +1,24 @@
+#!/bin/bash -e
+#
+# QEMU Release Script
+#
+# Copyright IBM, Corp. 2012
+#
+# Authors:
+#  Anthony Liguori <aliguori at us.ibm.com>
+#
+# This work is licensed under the terms of the GNU GPLv2 or later.
+# See the COPYING file in the top-level directory.
+
+src="$1"
+version="$2"
+destination=qemu-${version}
+
+git clone "${src}" ${destination}
+pushd ${destination}
+git checkout "v${version}"
+git submodule update --init
+rm -rf .git roms/*/.git
+popd
+tar cfj ${destination}.tar.bz2 ${destination}
+rm -rf ${destination}
commit 86ee5bc304249da960e7e8b9b567583960745993
Author: Michal Novotny <minovotn at redhat.com>
Date:   Mon Jul 16 15:54:38 2012 +0200

    qemu-options.hx: Fix set_password and expire_password description
    
    The description for set_password and expire_password commands is
    incomplete. This patch fixes the man page that is being generated
    to match the real behaviour of these functions.
    
    Signed-off-by: Michal Novotny <minovotn at redhat.com>
    Signed-off-by: Michal Novotny <minovotn at redhat.com>
    Signed-off-by: Anthony Liguori <aliguori at us.ibm.com>

diff --git a/qemu-options.hx b/qemu-options.hx
index 92cb0b1..97245a3 100644
--- a/qemu-options.hx
+++ b/qemu-options.hx
@@ -1030,8 +1030,21 @@ is a TCP port number, not a display number.
 @item password
 
 Require that password based authentication is used for client connections.
-The password must be set separately using the @code{change} command in the
- at ref{pcsys_monitor}
+
+The password must be set separately using the @code{set_password} command in
+the @ref{pcsys_monitor}. The syntax to change your password is:
+ at code{set_password <protocol> <password>} where <protocol> could be either
+"vnc" or "spice".
+
+If you would like to change <protocol> password expiration, you should use
+ at code{expire_password <protocol> <expiration-time>} where expiration time could
+be one of the following options: now, never, +seconds or UNIX time of
+expiration, e.g. +60 to make password expire in 60 seconds, or 1335196800
+to make password expire on "Mon Apr 23 12:00:00 EDT 2012" (UNIX time for this
+date and time).
+
+You can also use keywords "now" or "never" for the expiration time to
+allow <protocol> password to expire immediately or never expire.
 
 @item tls
 
commit 66c19bf1204f2cb283918c24d4eb74d02c5e882c
Author: Michal Novotny <minovotn at redhat.com>
Date:   Mon Jul 16 14:35:10 2012 +0200

    qemu-options.hx: Improve -nodefaults description
    
    This patch improves the description of -nodefaults QEMU command line
    option by adding more information what is being disabled using this
    command.
    
    Signed-off-by: Michal Novotny <minovotn at redhat.com>
    Signed-off-by: Anthony Liguori <aliguori at us.ibm.com>

diff --git a/qemu-options.hx b/qemu-options.hx
index 7130bc3..92cb0b1 100644
--- a/qemu-options.hx
+++ b/qemu-options.hx
@@ -2641,7 +2641,10 @@ DEF("nodefaults", 0, QEMU_OPTION_nodefaults, \
 STEXI
 @item -nodefaults
 @findex -nodefaults
-Don't create default devices.
+Don't create default devices. Normally, QEMU sets the default devices like serial
+port, parallel port, virtual console, monitor device, VGA adapter, floppy and
+CD-ROM drive and others. The @code{-nodefaults} option will disable all those
+default devices.
 ETEXI
 
 #ifndef _WIN32
commit ed24cfac07289d458ff284898bbd0389743a18b7
Author: Michal Novotny <minovotn at redhat.com>
Date:   Mon Jul 16 14:28:32 2012 +0200

    qemu-options.hx: Improve -{read|write}config options description
    
    This is the patch to improve description for -{read|write}config
    functions.
    
    Signed-off-by: Michal Novotny <minovotn at redhat.com>
    Signed-off-by: Anthony Liguori <aliguori at us.ibm.com>

diff --git a/qemu-options.hx b/qemu-options.hx
index ecf7ca1..7130bc3 100644
--- a/qemu-options.hx
+++ b/qemu-options.hx
@@ -2697,7 +2697,9 @@ DEF("readconfig", HAS_ARG, QEMU_OPTION_readconfig,
 STEXI
 @item -readconfig @var{file}
 @findex -readconfig
-Read device configuration from @var{file}.
+Read device configuration from @var{file}. This approach is useful when you want to spawn
+QEMU process with many command line options but you don't want to exceed the command line
+character limit.
 ETEXI
 DEF("writeconfig", HAS_ARG, QEMU_OPTION_writeconfig,
     "-writeconfig <file>\n"
@@ -2705,7 +2707,9 @@ DEF("writeconfig", HAS_ARG, QEMU_OPTION_writeconfig,
 STEXI
 @item -writeconfig @var{file}
 @findex -writeconfig
-Write device configuration to @var{file}.
+Write device configuration to @var{file}. The @var{file} can be either filename to save
+command line and device configuration into file or dash @code{-}) character to print the
+output to stdout. This can be later used as input file for @code{-readconfig} option.
 ETEXI
 DEF("nodefconfig", 0, QEMU_OPTION_nodefconfig,
     "-nodefconfig\n"
commit 3b25597bcf7fa8c92ba2107fbdb260ce0eccd64b
Author: Christian Borntraeger <borntraeger at de.ibm.com>
Date:   Tue Jul 17 15:26:17 2012 +0200

    constify value pointer for qdev_prop_set_string
    
    qdev_prop_set_string uses object_property_set_str, which takes
    a const char * for the value. Lets propagate the constness
    into qdev_prop_set_string.
    
    Signed-off-by: Christian Borntraeger <borntraeger at de.ibm.com>
    Signed-off-by: Anthony Liguori <aliguori at us.ibm.com>

diff --git a/hw/qdev-properties.c b/hw/qdev-properties.c
index 0b89462..3571cf3 100644
--- a/hw/qdev-properties.c
+++ b/hw/qdev-properties.c
@@ -1123,7 +1123,7 @@ void qdev_prop_set_uint64(DeviceState *dev, const char *name, uint64_t value)
     assert_no_error(errp);
 }
 
-void qdev_prop_set_string(DeviceState *dev, const char *name, char *value)
+void qdev_prop_set_string(DeviceState *dev, const char *name, const char *value)
 {
     Error *errp = NULL;
     object_property_set_str(OBJECT(dev), value, name, &errp);
diff --git a/hw/qdev.h b/hw/qdev.h
index f4683dc..a0770b0 100644
--- a/hw/qdev.h
+++ b/hw/qdev.h
@@ -316,7 +316,7 @@ void qdev_prop_set_uint16(DeviceState *dev, const char *name, uint16_t value);
 void qdev_prop_set_uint32(DeviceState *dev, const char *name, uint32_t value);
 void qdev_prop_set_int32(DeviceState *dev, const char *name, int32_t value);
 void qdev_prop_set_uint64(DeviceState *dev, const char *name, uint64_t value);
-void qdev_prop_set_string(DeviceState *dev, const char *name, char *value);
+void qdev_prop_set_string(DeviceState *dev, const char *name, const char *value);
 void qdev_prop_set_chr(DeviceState *dev, const char *name, CharDriverState *value);
 void qdev_prop_set_netdev(DeviceState *dev, const char *name, VLANClientState *value);
 void qdev_prop_set_vlan(DeviceState *dev, const char *name, VLANState *value);
commit e1b4382cbf74f99992a0cf67a891bd82ab8cd68e
Author: Stefan Weil <sw at weilnetz.de>
Date:   Mon Jul 16 23:37:07 2012 +0200

    doc: Fix indefinite article an -> a before nouns that begin with 'h'
    
    Although the rule also allows 'an' for historical reasons,
    'a' is more common because 'h' is pronounced.
    
    Reviewed-by: Peter Maydell <peter.maydell at linaro.org>
    Signed-off-by: Stefan Weil <sw at weilnetz.de>
    Signed-off-by: Anthony Liguori <aliguori at us.ibm.com>

diff --git a/qemu-doc.texi b/qemu-doc.texi
index 0af0ff4..84dad19 100644
--- a/qemu-doc.texi
+++ b/qemu-doc.texi
@@ -78,7 +78,7 @@ to ease cross-compilation and cross-debugging.
 
 @end itemize
 
-QEMU can run without an host kernel driver and yet gives acceptable
+QEMU can run without a host kernel driver and yet gives acceptable
 performance.
 
 For system emulation, the following hardware targets are supported:
diff --git a/qemu-tech.texi b/qemu-tech.texi
index b51a58a..d73dda8 100644
--- a/qemu-tech.texi
+++ b/qemu-tech.texi
@@ -536,7 +536,7 @@ timers, especially together with the use of bottom halves (BHs).
 @node Hardware interrupts
 @section Hardware interrupts
 
-In order to be faster, QEMU does not check at every basic block if an
+In order to be faster, QEMU does not check at every basic block if a
 hardware interrupt is pending. Instead, the user must asynchronously
 call a specific function to tell that an interrupt is pending. This
 function resets the chaining of the currently executing basic
commit c3cdc1b0ff84d1cfed0c8052d2c83f8ecbf24166
Author: Kevin Wolf <kwolf at redhat.com>
Date:   Mon Jul 16 16:06:56 2012 +0200

    fdc-test: Clean up a bit
    
    Readability of the test code has suffered as the test case evolved. This
    should improve it a bit again.
    
    Signed-off-by: Kevin Wolf <kwolf at redhat.com>

diff --git a/tests/fdc-test.c b/tests/fdc-test.c
index 10d11a4..fa74411 100644
--- a/tests/fdc-test.c
+++ b/tests/fdc-test.c
@@ -93,17 +93,21 @@ static uint8_t floppy_recv(void)
     return inb(FLOPPY_BASE + reg_fifo);
 }
 
-static uint8_t ack_irq(void)
+/* pcn: Present Cylinder Number */
+static void ack_irq(uint8_t *pcn)
 {
     uint8_t ret;
 
     g_assert(get_irq(FLOPPY_IRQ));
     floppy_send(CMD_SENSE_INT);
     floppy_recv();
+
     ret = floppy_recv();
-    g_assert(!get_irq(FLOPPY_IRQ));
+    if (pcn != NULL) {
+        *pcn = ret;
+    }
 
-    return ret;
+    g_assert(!get_irq(FLOPPY_IRQ));
 }
 
 static uint8_t send_read_command(void)
@@ -162,7 +166,7 @@ static uint8_t send_read_command(void)
     return ret;
 }
 
-static void send_step_pulse(int cyl)
+static void send_seek(int cyl)
 {
     int drive = 0;
     int head = 0;
@@ -171,7 +175,7 @@ static void send_step_pulse(int cyl)
     floppy_send(head << 2 | drive);
     g_assert(!get_irq(FLOPPY_IRQ));
     floppy_send(cyl);
-    ack_irq();
+    ack_irq(NULL);
 }
 
 static uint8_t cmos_read(uint8_t reg)
@@ -198,7 +202,7 @@ static void test_no_media_on_start(void)
     assert_bit_set(dir, DSKCHG);
     dir = inb(FLOPPY_BASE + reg_dir);
     assert_bit_set(dir, DSKCHG);
-    send_step_pulse(1);
+    send_seek(1);
     dir = inb(FLOPPY_BASE + reg_dir);
     assert_bit_set(dir, DSKCHG);
     dir = inb(FLOPPY_BASE + reg_dir);
@@ -229,14 +233,14 @@ static void test_media_change(void)
     dir = inb(FLOPPY_BASE + reg_dir);
     assert_bit_set(dir, DSKCHG);
 
-    send_step_pulse(0);
+    send_seek(0);
     dir = inb(FLOPPY_BASE + reg_dir);
     assert_bit_set(dir, DSKCHG);
     dir = inb(FLOPPY_BASE + reg_dir);
     assert_bit_set(dir, DSKCHG);
 
     /* Step to next track should clear DSKCHG bit. */
-    send_step_pulse(1);
+    send_seek(1);
     dir = inb(FLOPPY_BASE + reg_dir);
     assert_bit_clear(dir, DSKCHG);
     dir = inb(FLOPPY_BASE + reg_dir);
@@ -252,13 +256,13 @@ static void test_media_change(void)
     dir = inb(FLOPPY_BASE + reg_dir);
     assert_bit_set(dir, DSKCHG);
 
-    send_step_pulse(0);
+    send_seek(0);
     dir = inb(FLOPPY_BASE + reg_dir);
     assert_bit_set(dir, DSKCHG);
     dir = inb(FLOPPY_BASE + reg_dir);
     assert_bit_set(dir, DSKCHG);
 
-    send_step_pulse(1);
+    send_seek(1);
     dir = inb(FLOPPY_BASE + reg_dir);
     assert_bit_set(dir, DSKCHG);
     dir = inb(FLOPPY_BASE + reg_dir);
@@ -292,10 +296,10 @@ static void test_relative_seek(void)
     uint8_t drive = 0;
     uint8_t head = 0;
     uint8_t cyl = 1;
-    uint8_t ret;
+    uint8_t pcn;
 
     /* Send seek to track 0 */
-    send_step_pulse(0);
+    send_seek(0);
 
     /* Send relative seek to increase track by 1 */
     floppy_send(CMD_RELATIVE_SEEK_IN);
@@ -303,8 +307,8 @@ static void test_relative_seek(void)
     g_assert(!get_irq(FLOPPY_IRQ));
     floppy_send(cyl);
 
-    ret = ack_irq();
-    g_assert(ret == 1);
+    ack_irq(&pcn);
+    g_assert(pcn == 1);
 
     /* Send relative seek to decrease track by 1 */
     floppy_send(CMD_RELATIVE_SEEK_OUT);
@@ -312,8 +316,8 @@ static void test_relative_seek(void)
     g_assert(!get_irq(FLOPPY_IRQ));
     floppy_send(cyl);
 
-    ret = ack_irq();
-    g_assert(ret == 0);
+    ack_irq(&pcn);
+    g_assert(pcn == 0);
 }
 
 /* success if no crash or abort */
commit 98272dbb5c0679018718814b5cc3fc26f3f76c5f
Author: Pavel Hrdina <phrdina at redhat.com>
Date:   Mon Jul 16 15:48:27 2012 +0200

    fdc-test: introduce test_relative_seek
    
    Signed-off-by: Pavel Hrdina <phrdina at redhat.com>
    Signed-off-by: Kevin Wolf <kwolf at redhat.com>

diff --git a/tests/fdc-test.c b/tests/fdc-test.c
index 585fb0e..10d11a4 100644
--- a/tests/fdc-test.c
+++ b/tests/fdc-test.c
@@ -47,9 +47,11 @@ enum {
 };
 
 enum {
-    CMD_SENSE_INT   = 0x08,
-    CMD_SEEK        = 0x0f,
-    CMD_READ        = 0xe6,
+    CMD_SENSE_INT           = 0x08,
+    CMD_SEEK                = 0x0f,
+    CMD_READ                = 0xe6,
+    CMD_RELATIVE_SEEK_OUT   = 0x8f,
+    CMD_RELATIVE_SEEK_IN    = 0xcf,
 };
 
 enum {
@@ -91,13 +93,17 @@ static uint8_t floppy_recv(void)
     return inb(FLOPPY_BASE + reg_fifo);
 }
 
-static void ack_irq(void)
+static uint8_t ack_irq(void)
 {
+    uint8_t ret;
+
     g_assert(get_irq(FLOPPY_IRQ));
     floppy_send(CMD_SENSE_INT);
     floppy_recv();
-    floppy_recv();
+    ret = floppy_recv();
     g_assert(!get_irq(FLOPPY_IRQ));
+
+    return ret;
 }
 
 static uint8_t send_read_command(void)
@@ -281,6 +287,35 @@ static void test_sense_interrupt(void)
     floppy_recv();
 }
 
+static void test_relative_seek(void)
+{
+    uint8_t drive = 0;
+    uint8_t head = 0;
+    uint8_t cyl = 1;
+    uint8_t ret;
+
+    /* Send seek to track 0 */
+    send_step_pulse(0);
+
+    /* Send relative seek to increase track by 1 */
+    floppy_send(CMD_RELATIVE_SEEK_IN);
+    floppy_send(head << 2 | drive);
+    g_assert(!get_irq(FLOPPY_IRQ));
+    floppy_send(cyl);
+
+    ret = ack_irq();
+    g_assert(ret == 1);
+
+    /* Send relative seek to decrease track by 1 */
+    floppy_send(CMD_RELATIVE_SEEK_OUT);
+    floppy_send(head << 2 | drive);
+    g_assert(!get_irq(FLOPPY_IRQ));
+    floppy_send(cyl);
+
+    ret = ack_irq();
+    g_assert(ret == 0);
+}
+
 /* success if no crash or abort */
 static void fuzz_registers(void)
 {
@@ -329,6 +364,7 @@ int main(int argc, char **argv)
     qtest_add_func("/fdc/read_without_media", test_read_without_media);
     qtest_add_func("/fdc/media_change", test_media_change);
     qtest_add_func("/fdc/sense_interrupt", test_sense_interrupt);
+    qtest_add_func("/fdc/relative_seek", test_relative_seek);
     qtest_add_func("/fdc/fuzz-registers", fuzz_registers);
 
     ret = g_test_run();
commit 6d013772c03e916adc3d57868542854311489b51
Author: Pavel Hrdina <phrdina at redhat.com>
Date:   Mon Jul 16 15:48:26 2012 +0200

    fdc: fix relative seek
    
    Signed-off-by: Pavel Hrdina <phrdina at redhat.com>
    Signed-off-by: Kevin Wolf <kwolf at redhat.com>

diff --git a/hw/fdc.c b/hw/fdc.c
index 41191c7..08830c1 100644
--- a/hw/fdc.c
+++ b/hw/fdc.c
@@ -1802,7 +1802,7 @@ static void fdctrl_handle_drive_specification_command(FDCtrl *fdctrl, int direct
     }
 }
 
-static void fdctrl_handle_relative_seek_out(FDCtrl *fdctrl, int direction)
+static void fdctrl_handle_relative_seek_in(FDCtrl *fdctrl, int direction)
 {
     FDrive *cur_drv;
 
@@ -1812,14 +1812,15 @@ static void fdctrl_handle_relative_seek_out(FDCtrl *fdctrl, int direction)
         fd_seek(cur_drv, cur_drv->head, cur_drv->max_track - 1,
                 cur_drv->sect, 1);
     } else {
-        fd_seek(cur_drv, cur_drv->head, fdctrl->fifo[2], cur_drv->sect, 1);
+        fd_seek(cur_drv, cur_drv->head,
+                cur_drv->track + fdctrl->fifo[2], cur_drv->sect, 1);
     }
     fdctrl_reset_fifo(fdctrl);
     /* Raise Interrupt */
     fdctrl_raise_irq(fdctrl, FD_SR0_SEEK);
 }
 
-static void fdctrl_handle_relative_seek_in(FDCtrl *fdctrl, int direction)
+static void fdctrl_handle_relative_seek_out(FDCtrl *fdctrl, int direction)
 {
     FDrive *cur_drv;
 
@@ -1828,7 +1829,8 @@ static void fdctrl_handle_relative_seek_in(FDCtrl *fdctrl, int direction)
     if (fdctrl->fifo[2] > cur_drv->track) {
         fd_seek(cur_drv, cur_drv->head, 0, cur_drv->sect, 1);
     } else {
-        fd_seek(cur_drv, cur_drv->head, fdctrl->fifo[2], cur_drv->sect, 1);
+        fd_seek(cur_drv, cur_drv->head,
+                cur_drv->track - fdctrl->fifo[2], cur_drv->sect, 1);
     }
     fdctrl_reset_fifo(fdctrl);
     /* Raise Interrupt */
commit 2f24e8fb8d684f576f3dcced820860d70652a7f9
Author: Kevin Wolf <kwolf at redhat.com>
Date:   Thu Jun 28 16:55:54 2012 +0200

    qemu-iotests: Valgrind support
    
    check -valgrind wraps all qemu-io calls with valgrind. This makes it a
    bit easier to debug problems that occur somewhere deep in a test case.
    
    Signed-off-by: Kevin Wolf <kwolf at redhat.com>
    Reviewed-by: Paolo Bonzini <pbonzini at redhat.com>

diff --git a/tests/qemu-iotests/common b/tests/qemu-iotests/common
index eeb70cb..1f6fdf5 100644
--- a/tests/qemu-iotests/common
+++ b/tests/qemu-iotests/common
@@ -41,6 +41,7 @@ sortme=false
 expunge=true
 have_test_arg=false
 randomize=false
+valgrind=false
 rm -f $tmp.list $tmp.tmp $tmp.sed
 
 export IMGFMT=raw
@@ -212,6 +213,11 @@ testlist options
 	    xpand=false
 	    ;;
 
+    -valgrind)
+        valgrind=true
+	    xpand=false
+        ;;
+
 	-g)	# -g group ... pick from group file
 	    group=true
 	    xpand=false
@@ -345,3 +351,8 @@ fi
 [ "$QEMU" = "" ] && _fatal "qemu not found"
 [ "$QEMU_IMG" = "" ] && _fatal "qemu-img not found"
 [ "$QEMU_IO" = "" ] && _fatal "qemu-img not found"
+
+if $valgrind; then
+    export REAL_QEMU_IO="$QEMU_IO_PROG"
+    export QEMU_IO_PROG=valgrind_qemu_io
+fi
diff --git a/tests/qemu-iotests/common.rc b/tests/qemu-iotests/common.rc
index e535874..5e3a524 100644
--- a/tests/qemu-iotests/common.rc
+++ b/tests/qemu-iotests/common.rc
@@ -53,6 +53,16 @@ else
     TEST_IMG=$IMGPROTO:$TEST_DIR/t.$IMGFMT
 fi
 
+function valgrind_qemu_io()
+{
+    valgrind --log-file=/tmp/$$.valgrind --error-exitcode=99 $REAL_QEMU_IO "$@"
+    if [ $? != 0 ]; then
+        cat /tmp/$$.valgrind
+    fi
+    rm -f /tmp/$$.valgrind
+}
+
+
 _optstr_add()
 {
     if [ -n "$1" ]; then
commit 3f4349dc8b9494315f8331b2ea4e8d1f83fb801d
Author: Kevin Wolf <kwolf at redhat.com>
Date:   Fri Jun 29 13:40:27 2012 +0200

    coroutine-ucontext: Help valgrind understand coroutines
    
    valgrind tends to get confused and report false positives when you
    switch stacks and don't tell it about it.
    
    Signed-off-by: Kevin Wolf <kwolf at redhat.com>
    Reviewed-by: Paolo Bonzini <pbonzini at redhat.com>

diff --git a/configure b/configure
index 0a3896e..cef0a71 100755
--- a/configure
+++ b/configure
@@ -2871,6 +2871,22 @@ if compile_prog "" "" ; then
 fi
 
 ########################################
+# check if we have valgrind/valgrind.h
+
+valgrind_h=no
+cat > $TMPC << EOF
+#include <valgrind/valgrind.h>
+#pragma GCC diagnostic ignored "-Wunused-but-set-variable"
+int main(void) {
+  VALGRIND_STACK_DEREGISTER(0);
+  return 0;
+}
+EOF
+if compile_prog "" "" ; then
+    valgrind_h=yes
+fi
+
+########################################
 # check if environ is declared
 
 has_environ=no
@@ -3379,6 +3395,10 @@ if test "$linux_magic_h" = "yes" ; then
   echo "CONFIG_LINUX_MAGIC_H=y" >> $config_host_mak
 fi
 
+if test "$valgrind_h" = "yes" ; then
+  echo "CONFIG_VALGRIND_H=y" >> $config_host_mak
+fi
+
 if test "$has_environ" = "yes" ; then
   echo "CONFIG_HAS_ENVIRON=y" >> $config_host_mak
 fi
diff --git a/coroutine-ucontext.c b/coroutine-ucontext.c
index 5f43083..e3c450b 100644
--- a/coroutine-ucontext.c
+++ b/coroutine-ucontext.c
@@ -30,6 +30,10 @@
 #include "qemu-common.h"
 #include "qemu-coroutine-int.h"
 
+#ifdef CONFIG_VALGRIND_H
+#include <valgrind/valgrind.h>
+#endif
+
 enum {
     /* Maximum free pool size prevents holding too many freed coroutines */
     POOL_MAX_SIZE = 64,
@@ -43,6 +47,11 @@ typedef struct {
     Coroutine base;
     void *stack;
     jmp_buf env;
+
+#ifdef CONFIG_VALGRIND_H
+    unsigned int valgrind_stack_id;
+#endif
+
 } CoroutineUContext;
 
 /**
@@ -159,6 +168,11 @@ static Coroutine *coroutine_new(void)
     uc.uc_stack.ss_size = stack_size;
     uc.uc_stack.ss_flags = 0;
 
+#ifdef CONFIG_VALGRIND_H
+    co->valgrind_stack_id =
+        VALGRIND_STACK_REGISTER(co->stack, co->stack + stack_size);
+#endif
+
     arg.p = co;
 
     makecontext(&uc, (void (*)(void))coroutine_trampoline,
@@ -185,6 +199,16 @@ Coroutine *qemu_coroutine_new(void)
     return co;
 }
 
+#ifdef CONFIG_VALGRIND_H
+/* Work around an unused variable in the valgrind.h macro... */
+#pragma GCC diagnostic ignored "-Wunused-but-set-variable"
+static inline void valgrind_stack_deregister(CoroutineUContext *co)
+{
+    VALGRIND_STACK_DEREGISTER(co->valgrind_stack_id);
+}
+#pragma GCC diagnostic error "-Wunused-but-set-variable"
+#endif
+
 void qemu_coroutine_delete(Coroutine *co_)
 {
     CoroutineUContext *co = DO_UPCAST(CoroutineUContext, base, co_);
@@ -196,6 +220,10 @@ void qemu_coroutine_delete(Coroutine *co_)
         return;
     }
 
+#ifdef CONFIG_VALGRIND_H
+    valgrind_stack_deregister(co);
+#endif
+
     g_free(co->stack);
     g_free(co);
 }
commit 9e559533bd825a3e371497875576137a8586c831
Author: Kevin Wolf <kwolf at redhat.com>
Date:   Mon Jul 2 15:13:53 2012 +0200

    qemu-io: Fix memory leaks
    
    Almost all callers of create_iovec() forgot to destroy the qiov when the
    request has completed.
    
    Signed-off-by: Kevin Wolf <kwolf at redhat.com>
    Reviewed-by: Stefan Hajnoczi <stefanha at linux.vnet.ibm.com>

diff --git a/qemu-io.c b/qemu-io.c
index 5882067..8f3b94b 100644
--- a/qemu-io.c
+++ b/qemu-io.c
@@ -670,6 +670,7 @@ static int readv_f(int argc, char **argv)
     print_report("read", &t2, offset, qiov.size, total, cnt, Cflag);
 
 out:
+    qemu_iovec_destroy(&qiov);
     qemu_io_free(buf);
     return 0;
 }
@@ -928,6 +929,7 @@ static int writev_f(int argc, char **argv)
     t2 = tsub(t2, t1);
     print_report("wrote", &t2, offset, qiov.size, total, cnt, Cflag);
 out:
+    qemu_iovec_destroy(&qiov);
     qemu_io_free(buf);
     return 0;
 }
@@ -1126,6 +1128,7 @@ static void aio_write_done(void *opaque, int ret)
                  ctx->qiov.size, 1, ctx->Cflag);
 out:
     qemu_io_free(ctx->buf);
+    qemu_iovec_destroy(&ctx->qiov);
     g_free(ctx);
 }
 
@@ -1166,6 +1169,7 @@ static void aio_read_done(void *opaque, int ret)
                  ctx->qiov.size, 1, ctx->Cflag);
 out:
     qemu_io_free(ctx->buf);
+    qemu_iovec_destroy(&ctx->qiov);
     g_free(ctx);
 }
 
commit b7eb0c9f95e50239ce5b5266373dc52c85e75299
Author: Markus Armbruster <armbru at redhat.com>
Date:   Wed Jul 11 15:08:39 2012 +0200

    hw/block-common: Factor out fall back to legacy -drive cyls=...
    
    Signed-off-by: Markus Armbruster <armbru at redhat.com>
    Signed-off-by: Kevin Wolf <kwolf at redhat.com>

diff --git a/hw/block-common.c b/hw/block-common.c
index 0a0542a..f0196d7 100644
--- a/hw/block-common.c
+++ b/hw/block-common.c
@@ -9,6 +9,7 @@
 
 #include "blockdev.h"
 #include "hw/block-common.h"
+#include "qemu-error.h"
 
 void blkconf_serial(BlockConf *conf, char **serial)
 {
@@ -22,3 +23,42 @@ void blkconf_serial(BlockConf *conf, char **serial)
         }
     }
 }
+
+int blkconf_geometry(BlockConf *conf, int *ptrans,
+                     unsigned cyls_max, unsigned heads_max, unsigned secs_max)
+{
+    DriveInfo *dinfo;
+
+    if (!conf->cyls && !conf->heads && !conf->secs) {
+        /* try to fall back to value set with legacy -drive cyls=... */
+        dinfo = drive_get_by_blockdev(conf->bs);
+        conf->cyls  = dinfo->cyls;
+        conf->heads = dinfo->heads;
+        conf->secs  = dinfo->secs;
+        if (ptrans) {
+            *ptrans = dinfo->trans;
+        }
+    }
+    if (!conf->cyls && !conf->heads && !conf->secs) {
+        hd_geometry_guess(conf->bs,
+                          &conf->cyls, &conf->heads, &conf->secs,
+                          ptrans);
+    } else if (ptrans && *ptrans == BIOS_ATA_TRANSLATION_AUTO) {
+        *ptrans = hd_bios_chs_auto_trans(conf->cyls, conf->heads, conf->secs);
+    }
+    if (conf->cyls || conf->heads || conf->secs) {
+        if (conf->cyls < 1 || conf->cyls > cyls_max) {
+            error_report("cyls must be between 1 and %u", cyls_max);
+            return -1;
+        }
+        if (conf->heads < 1 || conf->heads > heads_max) {
+            error_report("heads must be between 1 and %u", heads_max);
+            return -1;
+        }
+        if (conf->secs < 1 || conf->secs > secs_max) {
+            error_report("secs must be between 1 and %u", secs_max);
+            return -1;
+        }
+    }
+    return 0;
+}
diff --git a/hw/block-common.h b/hw/block-common.h
index 52bddda..bb808f7 100644
--- a/hw/block-common.h
+++ b/hw/block-common.h
@@ -60,6 +60,8 @@ static inline unsigned int get_physical_block_exp(BlockConf *conf)
 /* Configuration helpers */
 
 void blkconf_serial(BlockConf *conf, char **serial);
+int blkconf_geometry(BlockConf *conf, int *trans,
+                     unsigned cyls_max, unsigned heads_max, unsigned secs_max);
 
 /* Hard disk geometry */
 
diff --git a/hw/ide/core.c b/hw/ide/core.c
index 5378fc3..d65ef3d 100644
--- a/hw/ide/core.c
+++ b/hw/ide/core.c
@@ -1935,18 +1935,6 @@ int ide_init_drive(IDEState *s, BlockDriverState *bs, IDEDriveKind kind,
     s->drive_kind = kind;
 
     bdrv_get_geometry(bs, &nb_sectors);
-    if (cylinders < 1 || cylinders > 65535) {
-        error_report("cyls must be between 1 and 65535");
-        return -1;
-    }
-    if (heads < 1 || heads > 16) {
-        error_report("heads must be between 1 and 16");
-        return -1;
-    }
-    if (secs < 1 || secs > 255) {
-        error_report("secs must be between 1 and 255");
-        return -1;
-    }
     s->cylinders = cylinders;
     s->heads = heads;
     s->sectors = secs;
@@ -2094,6 +2082,18 @@ void ide_init2_with_non_qdev_drives(IDEBus *bus, DriveInfo *hd0,
             } else if (trans == BIOS_ATA_TRANSLATION_AUTO) {
                 trans = hd_bios_chs_auto_trans(cyls, heads, secs);
             }
+            if (cyls < 1 || cyls > 65535) {
+                error_report("cyls must be between 1 and 65535");
+                exit(1);
+            }
+            if (heads < 1 || heads > 16) {
+                error_report("heads must be between 1 and 16");
+                exit(1);
+            }
+            if (secs < 1 || secs > 255) {
+                error_report("secs must be between 1 and 255");
+                exit(1);
+            }
             if (ide_init_drive(&bus->ifs[i], dinfo->bdrv,
                                dinfo->media_cd ? IDE_CD : IDE_HD,
                                NULL, dinfo->serial, NULL, 0,
diff --git a/hw/ide/qdev.c b/hw/ide/qdev.c
index 7fe803c..22e58df 100644
--- a/hw/ide/qdev.c
+++ b/hw/ide/qdev.c
@@ -142,7 +142,6 @@ static int ide_dev_initfn(IDEDevice *dev, IDEDriveKind kind)
 {
     IDEBus *bus = DO_UPCAST(IDEBus, qbus, dev->qdev.parent_bus);
     IDEState *s = bus->ifs + dev->unit;
-    DriveInfo *dinfo;
 
     if (dev->conf.discard_granularity && dev->conf.discard_granularity != 512) {
         error_report("discard_granularity must be 512 for ide");
@@ -150,22 +149,8 @@ static int ide_dev_initfn(IDEDevice *dev, IDEDriveKind kind)
     }
 
     blkconf_serial(&dev->conf, &dev->serial);
-
-    if (!dev->conf.cyls && !dev->conf.heads && !dev->conf.secs) {
-        /* try to fall back to value set with legacy -drive cyls=... */
-        dinfo = drive_get_by_blockdev(dev->conf.bs);
-        dev->conf.cyls  = dinfo->cyls;
-        dev->conf.heads = dinfo->heads;
-        dev->conf.secs  = dinfo->secs;
-        dev->chs_trans  = dinfo->trans;
-    }
-    if (!dev->conf.cyls && !dev->conf.heads && !dev->conf.secs) {
-        hd_geometry_guess(dev->conf.bs,
-                          &dev->conf.cyls, &dev->conf.heads, &dev->conf.secs,
-                          &dev->chs_trans);
-    } else if (dev->chs_trans == BIOS_ATA_TRANSLATION_AUTO) {
-        dev->chs_trans = hd_bios_chs_auto_trans(dev->conf.cyls,
-                                        dev->conf.heads, dev->conf.secs);
+    if (blkconf_geometry(&dev->conf, &dev->chs_trans, 65536, 16, 255) < 0) {
+        return -1;
     }
 
     if (ide_init_drive(s, dev->conf.bs, kind,
diff --git a/hw/scsi-disk.c b/hw/scsi-disk.c
index 39a07d7..525816c 100644
--- a/hw/scsi-disk.c
+++ b/hw/scsi-disk.c
@@ -1737,7 +1737,6 @@ static void scsi_disk_unit_attention_reported(SCSIDevice *dev)
 static int scsi_initfn(SCSIDevice *dev)
 {
     SCSIDiskState *s = DO_UPCAST(SCSIDiskState, qdev, dev);
-    DriveInfo *dinfo;
 
     if (!s->qdev.conf.bs) {
         error_report("drive property not set");
@@ -1750,34 +1749,10 @@ static int scsi_initfn(SCSIDevice *dev)
         return -1;
     }
 
-    if (!dev->conf.cyls && !dev->conf.heads && !dev->conf.secs) {
-        /* try to fall back to value set with legacy -drive cyls=... */
-        dinfo = drive_get_by_blockdev(s->qdev.conf.bs);
-        dev->conf.cyls = dinfo->cyls;
-        dev->conf.heads = dinfo->heads;
-        dev->conf.secs = dinfo->secs;
-    }
-    if (!dev->conf.cyls && !dev->conf.heads && !dev->conf.secs) {
-        hd_geometry_guess(s->qdev.conf.bs,
-                          &dev->conf.cyls, &dev->conf.heads, &dev->conf.secs,
-                          NULL);
-    }
-    if (dev->conf.cyls || dev->conf.heads || dev->conf.secs) {
-        if (dev->conf.cyls < 1 || dev->conf.cyls > 65535) {
-            error_report("cyls must be between 1 and 65535");
-            return -1;
-        }
-        if (dev->conf.heads < 1 || dev->conf.heads > 255) {
-            error_report("heads must be between 1 and 255");
-            return -1;
-        }
-        if (dev->conf.secs < 1 || dev->conf.secs > 255) {
-            error_report("secs must be between 1 and 255");
-            return -1;
-        }
-    }
-
     blkconf_serial(&s->qdev.conf, &s->serial);
+    if (blkconf_geometry(&dev->conf, NULL, 65535, 255, 255) < 0) {
+        return -1;
+    }
 
     if (!s->version) {
         s->version = g_strdup(qemu_get_version());
diff --git a/hw/virtio-blk.c b/hw/virtio-blk.c
index ba087bc..f21757e 100644
--- a/hw/virtio-blk.c
+++ b/hw/virtio-blk.c
@@ -589,7 +589,6 @@ VirtIODevice *virtio_blk_init(DeviceState *dev, VirtIOBlkConf *blk)
 {
     VirtIOBlock *s;
     static int virtio_blk_id;
-    DriveInfo *dinfo;
 
     if (!blk->conf.bs) {
         error_report("drive property not set");
@@ -601,6 +600,9 @@ VirtIODevice *virtio_blk_init(DeviceState *dev, VirtIOBlkConf *blk)
     }
 
     blkconf_serial(&blk->conf, &blk->serial);
+    if (blkconf_geometry(&blk->conf, NULL, 65535, 255, 255) < 0) {
+        return NULL;
+    }
 
     s = (VirtIOBlock *)virtio_common_init("virtio-blk", VIRTIO_ID_BLOCK,
                                           sizeof(struct virtio_blk_config),
@@ -615,33 +617,6 @@ VirtIODevice *virtio_blk_init(DeviceState *dev, VirtIOBlkConf *blk)
     s->rq = NULL;
     s->sector_mask = (s->conf->logical_block_size / BDRV_SECTOR_SIZE) - 1;
 
-    if (!blk->conf.cyls && !blk->conf.heads && !blk->conf.secs) {
-        /* try to fall back to value set with legacy -drive cyls=... */
-        dinfo = drive_get_by_blockdev(blk->conf.bs);
-        blk->conf.cyls = dinfo->cyls;
-        blk->conf.heads = dinfo->heads;
-        blk->conf.secs = dinfo->secs;
-    }
-    if (!blk->conf.cyls && !blk->conf.heads && !blk->conf.secs) {
-        hd_geometry_guess(s->bs,
-                          &blk->conf.cyls, &blk->conf.heads, &blk->conf.secs,
-                          NULL);
-    }
-    if (blk->conf.cyls || blk->conf.heads || blk->conf.secs) {
-        if (blk->conf.cyls < 1 || blk->conf.cyls > 65535) {
-            error_report("cyls must be between 1 and 65535");
-            return NULL;
-        }
-        if (blk->conf.heads < 1 || blk->conf.heads > 255) {
-            error_report("heads must be between 1 and 255");
-            return NULL;
-        }
-        if (blk->conf.secs < 1 || blk->conf.secs > 255) {
-            error_report("secs must be between 1 and 255");
-            return NULL;
-        }
-    }
-
     s->vq = virtio_add_queue(&s->vdev, 128, virtio_blk_handle_output);
 
     qemu_add_vm_change_state_handler(virtio_blk_dma_restart_cb, s);
commit 577d0a38070d1d6c4c7fab5c2054380770b1ec6b
Author: Markus Armbruster <armbru at redhat.com>
Date:   Wed Jul 11 15:08:38 2012 +0200

    blockdev: Don't limit DriveInfo serial to 20 characters
    
    All current users (IDE, SCSI and virtio-blk) happen to share this 20
    characters limit.  Still, it should be left to device models.  They
    already enforce their limits.  They have to, as the DriveInfo limit
    only affects legacy -drive serial=..., not the qdev properties.
    
    usb-storage, which doesn't limit serial number length, also uses
    DriveInfo for -usbdevice.  But that doesn't provide access to
    DriveInfo serial.
    
    Signed-off-by: Markus Armbruster <armbru at redhat.com>
    Signed-off-by: Kevin Wolf <kwolf at redhat.com>

diff --git a/blockdev.c b/blockdev.c
index 5f8677e..3d75015 100644
--- a/blockdev.c
+++ b/blockdev.c
@@ -536,9 +536,7 @@ DriveInfo *drive_init(QemuOpts *opts, int default_to_scsi)
     dinfo->trans = translation;
     dinfo->opts = opts;
     dinfo->refcount = 1;
-    if (serial) {
-        pstrcpy(dinfo->serial, sizeof(dinfo->serial), serial);
-    }
+    dinfo->serial = serial;
     QTAILQ_INSERT_TAIL(&drives, dinfo, next);
 
     bdrv_set_on_error(dinfo->bdrv, on_read_error, on_write_error);
diff --git a/blockdev.h b/blockdev.h
index 9c29948..5f27b64 100644
--- a/blockdev.h
+++ b/blockdev.h
@@ -17,8 +17,6 @@
 void blockdev_mark_auto_del(BlockDriverState *bs);
 void blockdev_auto_del(BlockDriverState *bs);
 
-#define BLOCK_SERIAL_STRLEN 20
-
 typedef enum {
     IF_DEFAULT = -1,            /* for use with drive_add() only */
     IF_NONE,
@@ -37,7 +35,7 @@ struct DriveInfo {
     int media_cd;
     int cyls, heads, secs, trans;
     QemuOpts *opts;
-    char serial[BLOCK_SERIAL_STRLEN + 1];
+    const char *serial;
     QTAILQ_ENTRY(DriveInfo) next;
     int refcount;
 };
diff --git a/hw/block-common.c b/hw/block-common.c
index 036334b..0a0542a 100644
--- a/hw/block-common.c
+++ b/hw/block-common.c
@@ -17,7 +17,7 @@ void blkconf_serial(BlockConf *conf, char **serial)
     if (!*serial) {
         /* try to fall back to value set with legacy -drive serial=... */
         dinfo = drive_get_by_blockdev(conf->bs);
-        if (*dinfo->serial) {
+        if (dinfo->serial) {
             *serial = g_strdup(dinfo->serial);
         }
     }
diff --git a/hw/ide/core.c b/hw/ide/core.c
index 58a454f..5378fc3 100644
--- a/hw/ide/core.c
+++ b/hw/ide/core.c
@@ -2095,9 +2095,9 @@ void ide_init2_with_non_qdev_drives(IDEBus *bus, DriveInfo *hd0,
                 trans = hd_bios_chs_auto_trans(cyls, heads, secs);
             }
             if (ide_init_drive(&bus->ifs[i], dinfo->bdrv,
-                               dinfo->media_cd ? IDE_CD : IDE_HD, NULL,
-                               *dinfo->serial ? dinfo->serial : NULL,
-                               NULL, 0, cyls, heads, secs, trans) < 0) {
+                               dinfo->media_cd ? IDE_CD : IDE_HD,
+                               NULL, dinfo->serial, NULL, 0,
+                               cyls, heads, secs, trans) < 0) {
                 error_report("Can't set up IDE drive %s", dinfo->id);
                 exit(1);
             }
commit 911525dba9ecc21f97b05c0f09bf9319a9de3a7d
Author: Markus Armbruster <armbru at redhat.com>
Date:   Wed Jul 11 15:08:37 2012 +0200

    hw/block-common: Factor out fall back to legacy -drive serial=...
    
    Signed-off-by: Markus Armbruster <armbru at redhat.com>
    Signed-off-by: Kevin Wolf <kwolf at redhat.com>

diff --git a/hw/Makefile.objs b/hw/Makefile.objs
index c3bdedc..8327e55 100644
--- a/hw/Makefile.objs
+++ b/hw/Makefile.objs
@@ -138,7 +138,7 @@ common-obj-$(CONFIG_MAX111X) += max111x.o
 common-obj-$(CONFIG_DS1338) += ds1338.o
 common-obj-y += i2c.o smbus.o smbus_eeprom.o
 common-obj-y += eeprom93xx.o
-common-obj-y += scsi-disk.o cdrom.o hd-geometry.o
+common-obj-y += scsi-disk.o cdrom.o hd-geometry.o block-common.o
 common-obj-y += scsi-generic.o scsi-bus.o
 common-obj-y += hid.o
 common-obj-$(CONFIG_SSI) += ssi.o
diff --git a/hw/block-common.c b/hw/block-common.c
new file mode 100644
index 0000000..036334b
--- /dev/null
+++ b/hw/block-common.c
@@ -0,0 +1,24 @@
+/*
+ * Common code for block device models
+ *
+ * Copyright (C) 2012 Red Hat, Inc.
+ *
+ * This work is licensed under the terms of the GNU GPL, version 2 or
+ * later.  See the COPYING file in the top-level directory.
+ */
+
+#include "blockdev.h"
+#include "hw/block-common.h"
+
+void blkconf_serial(BlockConf *conf, char **serial)
+{
+    DriveInfo *dinfo;
+
+    if (!*serial) {
+        /* try to fall back to value set with legacy -drive serial=... */
+        dinfo = drive_get_by_blockdev(conf->bs);
+        if (*dinfo->serial) {
+            *serial = g_strdup(dinfo->serial);
+        }
+    }
+}
diff --git a/hw/block-common.h b/hw/block-common.h
index f0d509b..52bddda 100644
--- a/hw/block-common.h
+++ b/hw/block-common.h
@@ -57,6 +57,9 @@ static inline unsigned int get_physical_block_exp(BlockConf *conf)
     DEFINE_PROP_UINT32("heads", _state, _conf.heads, 0), \
     DEFINE_PROP_UINT32("secs", _state, _conf.secs, 0)
 
+/* Configuration helpers */
+
+void blkconf_serial(BlockConf *conf, char **serial);
 
 /* Hard disk geometry */
 
diff --git a/hw/ide/qdev.c b/hw/ide/qdev.c
index de9db3b..7fe803c 100644
--- a/hw/ide/qdev.c
+++ b/hw/ide/qdev.c
@@ -142,7 +142,6 @@ static int ide_dev_initfn(IDEDevice *dev, IDEDriveKind kind)
 {
     IDEBus *bus = DO_UPCAST(IDEBus, qbus, dev->qdev.parent_bus);
     IDEState *s = bus->ifs + dev->unit;
-    const char *serial;
     DriveInfo *dinfo;
 
     if (dev->conf.discard_granularity && dev->conf.discard_granularity != 512) {
@@ -150,14 +149,7 @@ static int ide_dev_initfn(IDEDevice *dev, IDEDriveKind kind)
         return -1;
     }
 
-    serial = dev->serial;
-    if (!serial) {
-        /* try to fall back to value set with legacy -drive serial=... */
-        dinfo = drive_get_by_blockdev(dev->conf.bs);
-        if (*dinfo->serial) {
-            serial = dinfo->serial;
-        }
-    }
+    blkconf_serial(&dev->conf, &dev->serial);
 
     if (!dev->conf.cyls && !dev->conf.heads && !dev->conf.secs) {
         /* try to fall back to value set with legacy -drive cyls=... */
@@ -177,7 +169,7 @@ static int ide_dev_initfn(IDEDevice *dev, IDEDriveKind kind)
     }
 
     if (ide_init_drive(s, dev->conf.bs, kind,
-                       dev->version, serial, dev->model, dev->wwn,
+                       dev->version, dev->serial, dev->model, dev->wwn,
                        dev->conf.cyls, dev->conf.heads, dev->conf.secs,
                        dev->chs_trans) < 0) {
         return -1;
diff --git a/hw/scsi-disk.c b/hw/scsi-disk.c
index 0a182f9..39a07d7 100644
--- a/hw/scsi-disk.c
+++ b/hw/scsi-disk.c
@@ -1777,13 +1777,7 @@ static int scsi_initfn(SCSIDevice *dev)
         }
     }
 
-    if (!s->serial) {
-        /* try to fall back to value set with legacy -drive serial=... */
-        dinfo = drive_get_by_blockdev(s->qdev.conf.bs);
-        if (*dinfo->serial) {
-            s->serial = g_strdup(dinfo->serial);
-        }
-    }
+    blkconf_serial(&s->qdev.conf, &s->serial);
 
     if (!s->version) {
         s->version = g_strdup(qemu_get_version());
diff --git a/hw/usb/dev-storage.c b/hw/usb/dev-storage.c
index 251e7de..7fa8b83 100644
--- a/hw/usb/dev-storage.c
+++ b/hw/usb/dev-storage.c
@@ -532,13 +532,14 @@ static int usb_msd_initfn(USBDevice *dev)
 {
     MSDState *s = DO_UPCAST(MSDState, dev, dev);
     BlockDriverState *bs = s->conf.bs;
-    DriveInfo *dinfo;
 
     if (!bs) {
         error_report("drive property not set");
         return -1;
     }
 
+    blkconf_serial(&s->conf, &s->serial);
+
     /*
      * Hack alert: this pretends to be a block device, but it's really
      * a SCSI bus that can serve only a single device, which it
@@ -551,13 +552,6 @@ static int usb_msd_initfn(USBDevice *dev)
     bdrv_detach_dev(bs, &s->dev.qdev);
     s->conf.bs = NULL;
 
-    if (!s->serial) {
-        /* try to fall back to value set with legacy -drive serial=... */
-        dinfo = drive_get_by_blockdev(bs);
-        if (*dinfo->serial) {
-            s->serial = strdup(dinfo->serial);
-        }
-    }
     if (s->serial) {
         usb_desc_set_string(dev, STR_SERIALNUMBER, s->serial);
     } else {
diff --git a/hw/virtio-blk.c b/hw/virtio-blk.c
index 3885904..ba087bc 100644
--- a/hw/virtio-blk.c
+++ b/hw/virtio-blk.c
@@ -600,13 +600,7 @@ VirtIODevice *virtio_blk_init(DeviceState *dev, VirtIOBlkConf *blk)
         return NULL;
     }
 
-    if (!blk->serial) {
-        /* try to fall back to value set with legacy -drive serial=... */
-        dinfo = drive_get_by_blockdev(blk->conf.bs);
-        if (*dinfo->serial) {
-            blk->serial = strdup(dinfo->serial);
-        }
-    }
+    blkconf_serial(&blk->conf, &blk->serial);
 
     s = (VirtIOBlock *)virtio_common_init("virtio-blk", VIRTIO_ID_BLOCK,
                                           sizeof(struct virtio_blk_config),
commit 31e404f4ffb6adadea0b35de08e0a6b640e81a02
Author: Markus Armbruster <armbru at redhat.com>
Date:   Wed Jul 11 15:08:36 2012 +0200

    hw/block-common: Move BlockConf & friends from block.h
    
    This stuff doesn't belong to block layer, and was put there only
    because a better home didn't exist then.  Now it does.
    
    Signed-off-by: Markus Armbruster <armbru at redhat.com>
    Signed-off-by: Kevin Wolf <kwolf at redhat.com>

diff --git a/block.h b/block.h
index 29c5eab..c89590d 100644
--- a/block.h
+++ b/block.h
@@ -403,49 +403,4 @@ typedef enum {
 #define BLKDBG_EVENT(bs, evt) bdrv_debug_event(bs, evt)
 void bdrv_debug_event(BlockDriverState *bs, BlkDebugEvent event);
 
-
-/* Convenience for block device models */
-
-typedef struct BlockConf {
-    BlockDriverState *bs;
-    uint16_t physical_block_size;
-    uint16_t logical_block_size;
-    uint16_t min_io_size;
-    uint32_t opt_io_size;
-    int32_t bootindex;
-    uint32_t discard_granularity;
-    /* geometry, not all devices use this */
-    uint32_t cyls, heads, secs;
-} BlockConf;
-
-static inline unsigned int get_physical_block_exp(BlockConf *conf)
-{
-    unsigned int exp = 0, size;
-
-    for (size = conf->physical_block_size;
-        size > conf->logical_block_size;
-        size >>= 1) {
-        exp++;
-    }
-
-    return exp;
-}
-
-#define DEFINE_BLOCK_PROPERTIES(_state, _conf)                          \
-    DEFINE_PROP_DRIVE("drive", _state, _conf.bs),                       \
-    DEFINE_PROP_BLOCKSIZE("logical_block_size", _state,                 \
-                          _conf.logical_block_size, 512),               \
-    DEFINE_PROP_BLOCKSIZE("physical_block_size", _state,                \
-                          _conf.physical_block_size, 512),              \
-    DEFINE_PROP_UINT16("min_io_size", _state, _conf.min_io_size, 0),  \
-    DEFINE_PROP_UINT32("opt_io_size", _state, _conf.opt_io_size, 0),    \
-    DEFINE_PROP_INT32("bootindex", _state, _conf.bootindex, -1),        \
-    DEFINE_PROP_UINT32("discard_granularity", _state, \
-                       _conf.discard_granularity, 0)
-
-#define DEFINE_BLOCK_CHS_PROPERTIES(_state, _conf)      \
-    DEFINE_PROP_UINT32("cyls", _state, _conf.cyls, 0),  \
-    DEFINE_PROP_UINT32("heads", _state, _conf.heads, 0), \
-    DEFINE_PROP_UINT32("secs", _state, _conf.secs, 0)
-
 #endif
diff --git a/hw/block-common.h b/hw/block-common.h
index 31e12ba..f0d509b 100644
--- a/hw/block-common.h
+++ b/hw/block-common.h
@@ -13,6 +13,51 @@
 
 #include "qemu-common.h"
 
+/* Configuration */
+
+typedef struct BlockConf {
+    BlockDriverState *bs;
+    uint16_t physical_block_size;
+    uint16_t logical_block_size;
+    uint16_t min_io_size;
+    uint32_t opt_io_size;
+    int32_t bootindex;
+    uint32_t discard_granularity;
+    /* geometry, not all devices use this */
+    uint32_t cyls, heads, secs;
+} BlockConf;
+
+static inline unsigned int get_physical_block_exp(BlockConf *conf)
+{
+    unsigned int exp = 0, size;
+
+    for (size = conf->physical_block_size;
+        size > conf->logical_block_size;
+        size >>= 1) {
+        exp++;
+    }
+
+    return exp;
+}
+
+#define DEFINE_BLOCK_PROPERTIES(_state, _conf)                          \
+    DEFINE_PROP_DRIVE("drive", _state, _conf.bs),                       \
+    DEFINE_PROP_BLOCKSIZE("logical_block_size", _state,                 \
+                          _conf.logical_block_size, 512),               \
+    DEFINE_PROP_BLOCKSIZE("physical_block_size", _state,                \
+                          _conf.physical_block_size, 512),              \
+    DEFINE_PROP_UINT16("min_io_size", _state, _conf.min_io_size, 0),  \
+    DEFINE_PROP_UINT32("opt_io_size", _state, _conf.opt_io_size, 0),    \
+    DEFINE_PROP_INT32("bootindex", _state, _conf.bootindex, -1),        \
+    DEFINE_PROP_UINT32("discard_granularity", _state, \
+                       _conf.discard_granularity, 0)
+
+#define DEFINE_BLOCK_CHS_PROPERTIES(_state, _conf)      \
+    DEFINE_PROP_UINT32("cyls", _state, _conf.cyls, 0),  \
+    DEFINE_PROP_UINT32("heads", _state, _conf.heads, 0), \
+    DEFINE_PROP_UINT32("secs", _state, _conf.secs, 0)
+
+
 /* Hard disk geometry */
 
 #define BIOS_ATA_TRANSLATION_AUTO   0
diff --git a/hw/ide/internal.h b/hw/ide/internal.h
index c3ecafc..7170bd9 100644
--- a/hw/ide/internal.h
+++ b/hw/ide/internal.h
@@ -11,6 +11,7 @@
 #include "iorange.h"
 #include "dma.h"
 #include "sysemu.h"
+#include "hw/block-common.h"
 #include "hw/scsi-defs.h"
 
 /* debug IDE devices */
diff --git a/hw/scsi.h b/hw/scsi.h
index 76f06d4..d90e970 100644
--- a/hw/scsi.h
+++ b/hw/scsi.h
@@ -3,6 +3,7 @@
 
 #include "qdev.h"
 #include "block.h"
+#include "hw/block-common.h"
 #include "sysemu.h"
 
 #define MAX_SCSI_DEVS	255
diff --git a/hw/usb.h b/hw/usb.h
index 7ed8fb8..432ccae 100644
--- a/hw/usb.h
+++ b/hw/usb.h
@@ -25,7 +25,6 @@
  * THE SOFTWARE.
  */
 
-#include "block.h"
 #include "qdev.h"
 #include "qemu-queue.h"
 
diff --git a/hw/virtio-blk.h b/hw/virtio-blk.h
index d785001..79ebccc 100644
--- a/hw/virtio-blk.h
+++ b/hw/virtio-blk.h
@@ -15,7 +15,7 @@
 #define _QEMU_VIRTIO_BLK_H
 
 #include "virtio.h"
-#include "block.h"
+#include "hw/block-common.h"
 
 /* from Linux's linux/virtio_blk.h */
 
diff --git a/hw/virtio.h b/hw/virtio.h
index 85aabe5..42a7762 100644
--- a/hw/virtio.h
+++ b/hw/virtio.h
@@ -18,7 +18,6 @@
 #include "net.h"
 #include "qdev.h"
 #include "sysemu.h"
-#include "block.h"
 #include "event_notifier.h"
 #ifdef CONFIG_LINUX
 #include "9p.h"
commit b51daf003aa42c5c23876739ebd0b64dd2075931
Author: Markus Armbruster <armbru at redhat.com>
Date:   Tue Jul 10 11:12:55 2012 +0200

    Relax IDE CHS limits from 16383,16,63 to 65535,16,255
    
    New limits straight from ATA4 6.2 Register delivered data transfer
    command sector addressing.
    
    I figure the old sector limit 63 was blindly copied from the BIOS
    int 13 limit.  Doesn't apply to the hardware.  No idea where the old
    cylinder limit comes from.
    
    Signed-off-by: Markus Armbruster <armbru at redhat.com>
    Signed-off-by: Kevin Wolf <kwolf at redhat.com>

diff --git a/hw/ide/core.c b/hw/ide/core.c
index 1ca7cdf..58a454f 100644
--- a/hw/ide/core.c
+++ b/hw/ide/core.c
@@ -1935,16 +1935,16 @@ int ide_init_drive(IDEState *s, BlockDriverState *bs, IDEDriveKind kind,
     s->drive_kind = kind;
 
     bdrv_get_geometry(bs, &nb_sectors);
-    if (cylinders < 1 || cylinders > 16383) {
-        error_report("cyls must be between 1 and 16383");
+    if (cylinders < 1 || cylinders > 65535) {
+        error_report("cyls must be between 1 and 65535");
         return -1;
     }
     if (heads < 1 || heads > 16) {
         error_report("heads must be between 1 and 16");
         return -1;
     }
-    if (secs < 1 || secs > 63) {
-        error_report("secs must be between 1 and 63");
+    if (secs < 1 || secs > 255) {
+        error_report("secs must be between 1 and 255");
         return -1;
     }
     s->cylinders = cylinders;
commit aaea3f366eeb8c5c23d821cdd1ce078086fe3764
Author: Markus Armbruster <armbru at redhat.com>
Date:   Tue Jul 10 11:12:54 2012 +0200

    blockdev: Drop redundant CHS validation for if=ide
    
    Leave it to ide_init_drive().
    
    Signed-off-by: Markus Armbruster <armbru at redhat.com>
    Signed-off-by: Kevin Wolf <kwolf at redhat.com>

diff --git a/blockdev.c b/blockdev.c
index 06c997e..5f8677e 100644
--- a/blockdev.c
+++ b/blockdev.c
@@ -330,15 +330,15 @@ DriveInfo *drive_init(QemuOpts *opts, int default_to_scsi)
     max_devs = if_max_devs[type];
 
     if (cyls || heads || secs) {
-        if (cyls < 1 || (type == IF_IDE && cyls > 16383)) {
+        if (cyls < 1) {
             error_report("invalid physical cyls number");
 	    return NULL;
 	}
-        if (heads < 1 || (type == IF_IDE && heads > 16)) {
+        if (heads < 1) {
             error_report("invalid physical heads number");
 	    return NULL;
 	}
-        if (secs < 1 || (type == IF_IDE && secs > 63)) {
+        if (secs < 1) {
             error_report("invalid physical secs number");
 	    return NULL;
 	}
commit 2adc99b277ab05877ef847bddde45346378f561a
Author: Markus Armbruster <armbru at redhat.com>
Date:   Tue Jul 10 11:12:53 2012 +0200

    hd-geometry: Compute BIOS CHS translation in one place
    
    Currently, it is split between hd_geometry_guess() and
    pc_cmos_init_late().  Confusing.  info qtree shows the result of the
    former.  Also confusing.
    
    Fold the part done in pc_cmos_init_late() into hd_geometry_guess().
    
    Signed-off-by: Markus Armbruster <armbru at redhat.com>
    Signed-off-by: Kevin Wolf <kwolf at redhat.com>

diff --git a/hw/block-common.h b/hw/block-common.h
index ec7810d..31e12ba 100644
--- a/hw/block-common.h
+++ b/hw/block-common.h
@@ -24,5 +24,6 @@
 void hd_geometry_guess(BlockDriverState *bs,
                        uint32_t *pcyls, uint32_t *pheads, uint32_t *psecs,
                        int *ptrans);
+int hd_bios_chs_auto_trans(uint32_t cyls, uint32_t heads, uint32_t secs);
 
 #endif
diff --git a/hw/hd-geometry.c b/hw/hd-geometry.c
index 74678a6..1cdb9fb 100644
--- a/hw/hd-geometry.c
+++ b/hw/hd-geometry.c
@@ -125,7 +125,7 @@ void hd_geometry_guess(BlockDriverState *bs,
     if (guess_disk_lchs(bs, &cylinders, &heads, &secs) < 0) {
         /* no LCHS guess: use a standard physical disk geometry  */
         guess_chs_for_size(bs, pcyls, pheads, psecs);
-        translation = BIOS_ATA_TRANSLATION_AUTO;
+        translation = hd_bios_chs_auto_trans(*pcyls, *pheads, *psecs);
     } else if (heads > 16) {
         /* LCHS guess with heads > 16 means that a BIOS LBA
            translation was active, so a standard physical disk
@@ -148,3 +148,10 @@ void hd_geometry_guess(BlockDriverState *bs,
     }
     trace_hd_geometry_guess(bs, *pcyls, *pheads, *psecs, translation);
 }
+
+int hd_bios_chs_auto_trans(uint32_t cyls, uint32_t heads, uint32_t secs)
+{
+    return cyls <= 1024 && heads <= 16 && secs <= 63
+        ? BIOS_ATA_TRANSLATION_NONE
+        : BIOS_ATA_TRANSLATION_LBA;
+}
diff --git a/hw/ide/core.c b/hw/ide/core.c
index bf1ce89..1ca7cdf 100644
--- a/hw/ide/core.c
+++ b/hw/ide/core.c
@@ -2091,6 +2091,8 @@ void ide_init2_with_non_qdev_drives(IDEBus *bus, DriveInfo *hd0,
             trans = dinfo->trans;
             if (!cyls && !heads && !secs) {
                 hd_geometry_guess(dinfo->bdrv, &cyls, &heads, &secs, &trans);
+            } else if (trans == BIOS_ATA_TRANSLATION_AUTO) {
+                trans = hd_bios_chs_auto_trans(cyls, heads, secs);
             }
             if (ide_init_drive(&bus->ifs[i], dinfo->bdrv,
                                dinfo->media_cd ? IDE_CD : IDE_HD, NULL,
diff --git a/hw/ide/qdev.c b/hw/ide/qdev.c
index 84097fd..de9db3b 100644
--- a/hw/ide/qdev.c
+++ b/hw/ide/qdev.c
@@ -171,6 +171,9 @@ static int ide_dev_initfn(IDEDevice *dev, IDEDriveKind kind)
         hd_geometry_guess(dev->conf.bs,
                           &dev->conf.cyls, &dev->conf.heads, &dev->conf.secs,
                           &dev->chs_trans);
+    } else if (dev->chs_trans == BIOS_ATA_TRANSLATION_AUTO) {
+        dev->chs_trans = hd_bios_chs_auto_trans(dev->conf.cyls,
+                                        dev->conf.heads, dev->conf.secs);
     }
 
     if (ide_init_drive(s, dev->conf.bs, kind,
diff --git a/hw/pc.c b/hw/pc.c
index 77b12b4..598267a 100644
--- a/hw/pc.c
+++ b/hw/pc.c
@@ -290,7 +290,7 @@ static void pc_cmos_init_late(void *opaque)
     int16_t cylinders;
     int8_t heads, sectors;
     int val;
-    int i;
+    int i, trans;
 
     val = 0;
     if (ide_get_geometry(arg->idebus[0], 0,
@@ -313,20 +313,9 @@ static void pc_cmos_init_late(void *opaque)
            geometry can be different if a translation is done. */
         if (ide_get_geometry(arg->idebus[i / 2], i % 2,
                              &cylinders, &heads, &sectors) >= 0) {
-            int translation = ide_get_bios_chs_trans(arg->idebus[i / 2],
-                                                     i % 2);
-            if (translation == BIOS_ATA_TRANSLATION_AUTO) {
-                if (cylinders <= 1024 && heads <= 16 && sectors <= 63) {
-                    /* No translation. */
-                    translation = 0;
-                } else {
-                    /* LBA translation. */
-                    translation = 1;
-                }
-            } else {
-                translation--;
-            }
-            val |= translation << (i * 2);
+            trans = ide_get_bios_chs_trans(arg->idebus[i / 2], i % 2) - 1;
+            assert((trans & ~3) == 0);
+            val |= trans << (i * 2);
         }
     }
     rtc_set_memory(s, 0x39, val);
commit 4e4e6e319b5508289da0f2966f63c841c832b847
Author: Markus Armbruster <armbru at redhat.com>
Date:   Tue Jul 10 11:12:52 2012 +0200

    qtest: Test we don't put hard disk info into CMOS for a CD-ROM
    
    Signed-off-by: Markus Armbruster <armbru at redhat.com>
    Signed-off-by: Kevin Wolf <kwolf at redhat.com>

diff --git a/tests/hd-geo-test.c b/tests/hd-geo-test.c
index 5d9d2e4..9a31e85 100644
--- a/tests/hd-geo-test.c
+++ b/tests/hd-geo-test.c
@@ -369,6 +369,27 @@ static void test_ide_device_user_chst(void)
     test_ide_drive_user("ide-hd", true);
 }
 
+/*
+ * Test case: IDE devices (if=ide), but use index=0 for CD-ROM
+ */
+static void test_ide_drive_cd_0(void)
+{
+    char *argv[256];
+    int argc, ide_idx;
+    Backend i;
+
+    argc = setup_common(argv, ARRAY_SIZE(argv));
+    for (i = 0; i <= backend_empty; i++) {
+        ide_idx = backend_empty - i;
+        cur_ide[ide_idx] = &hd_chst[i][mbr_blank];
+        argc = setup_ide(argc, argv, ARRAY_SIZE(argv),
+                         ide_idx, NULL, i, mbr_blank, "");
+    }
+    qtest_start(g_strjoinv(" ", argv));
+    test_cmos();
+    qtest_quit(global_qtest);
+}
+
 int main(int argc, char **argv)
 {
     Backend i;
@@ -390,6 +411,7 @@ int main(int argc, char **argv)
     qtest_add_func("hd-geo/ide/drive/mbr/chs", test_ide_drive_mbr_chs);
     qtest_add_func("hd-geo/ide/drive/user/chs", test_ide_drive_user_chs);
     qtest_add_func("hd-geo/ide/drive/user/chst", test_ide_drive_user_chst);
+    qtest_add_func("hd-geo/ide/drive/cd_0", test_ide_drive_cd_0);
     qtest_add_func("hd-geo/ide/device/mbr/blank", test_ide_device_mbr_blank);
     qtest_add_func("hd-geo/ide/device/mbr/lba", test_ide_device_mbr_lba);
     qtest_add_func("hd-geo/ide/device/mbr/chs", test_ide_device_mbr_chs);
commit 9dc13e381385787b65ad2095ed343bbc8b4e5220
Author: Markus Armbruster <armbru at redhat.com>
Date:   Tue Jul 10 11:12:51 2012 +0200

    ide pc: Put hard disk info into CMOS only for hard disks
    
    In particular, don't set disk type and geometry when a CD-ROM on bus
    ide.0 has media during CMOS initialization.
    
    Signed-off-by: Markus Armbruster <armbru at redhat.com>
    Signed-off-by: Kevin Wolf <kwolf at redhat.com>

diff --git a/hw/ide/qdev.c b/hw/ide/qdev.c
index f191dd3..84097fd 100644
--- a/hw/ide/qdev.c
+++ b/hw/ide/qdev.c
@@ -117,7 +117,7 @@ int ide_get_geometry(BusState *bus, int unit,
 {
     IDEState *s = &DO_UPCAST(IDEBus, qbus, bus)->ifs[unit];
 
-    if (!s->bs) {
+    if (s->drive_kind != IDE_HD || !s->bs) {
         return -1;
     }
 
commit 2b584959ed300ddff4acba0d7554becad5f274fd
Author: Markus Armbruster <armbru at redhat.com>
Date:   Tue Jul 10 11:12:50 2012 +0200

    block: Geometry and translation hints are now useless, purge them
    
    There are two producers of these hints: drive_init() on behalf of
    -drive, and hd_geometry_guess().
    
    The only consumer of the hint is hd_geometry_guess().
    
    The callers of hd_geometry_guess() call it only when drive_init()
    didn't set the hints.  Therefore, drive_init()'s hints are never used.
    
    Thus, hd_geometry_guess() only ever sees hints it produced itself in a
    prior call.  Only the first call computes something, subsequent calls
    just repeat the first call's results.  However, hd_geometry_guess() is
    never called more than once: the device models don't, and the block
    device is destroyed on unplug.  Thus, dropping the repeat feature
    doesn't break anything now.
    
    If a block device wasn't destroyed on unplug and could be reused with
    a new device, then repeating old results would be wrong.  Thus,
    dropping the repeat feature prevents future breakage.
    
    This renders the hints unused.  Purge them from the block layer.
    
    Signed-off-by: Markus Armbruster <armbru at redhat.com>
    Signed-off-by: Kevin Wolf <kwolf at redhat.com>

diff --git a/block.c b/block.c
index 06323cf..ce7eb8f 100644
--- a/block.c
+++ b/block.c
@@ -996,12 +996,6 @@ static void bdrv_move_feature_fields(BlockDriverState *bs_dest,
     bs_dest->block_timer        = bs_src->block_timer;
     bs_dest->io_limits_enabled  = bs_src->io_limits_enabled;
 
-    /* geometry */
-    bs_dest->cyls               = bs_src->cyls;
-    bs_dest->heads              = bs_src->heads;
-    bs_dest->secs               = bs_src->secs;
-    bs_dest->translation        = bs_src->translation;
-
     /* r/w error */
     bs_dest->on_read_error      = bs_src->on_read_error;
     bs_dest->on_write_error     = bs_src->on_write_error;
@@ -2132,27 +2126,6 @@ void bdrv_get_geometry(BlockDriverState *bs, uint64_t *nb_sectors_ptr)
     *nb_sectors_ptr = length;
 }
 
-void bdrv_set_geometry_hint(BlockDriverState *bs,
-                            int cyls, int heads, int secs)
-{
-    bs->cyls = cyls;
-    bs->heads = heads;
-    bs->secs = secs;
-}
-
-void bdrv_set_translation_hint(BlockDriverState *bs, int translation)
-{
-    bs->translation = translation;
-}
-
-void bdrv_get_geometry_hint(BlockDriverState *bs,
-                            int *pcyls, int *pheads, int *psecs)
-{
-    *pcyls = bs->cyls;
-    *pheads = bs->heads;
-    *psecs = bs->secs;
-}
-
 /* throttling disk io limits */
 void bdrv_set_io_limits(BlockDriverState *bs,
                         BlockIOLimit *io_limits)
@@ -2161,11 +2134,6 @@ void bdrv_set_io_limits(BlockDriverState *bs,
     bs->io_limits_enabled = bdrv_io_limits_enabled(bs);
 }
 
-int bdrv_get_translation_hint(BlockDriverState *bs)
-{
-    return bs->translation;
-}
-
 void bdrv_set_on_error(BlockDriverState *bs, BlockErrorAction on_read_error,
                        BlockErrorAction on_write_error)
 {
diff --git a/block.h b/block.h
index 1cd8a01..29c5eab 100644
--- a/block.h
+++ b/block.h
@@ -257,18 +257,6 @@ int bdrv_has_zero_init(BlockDriverState *bs);
 int bdrv_is_allocated(BlockDriverState *bs, int64_t sector_num, int nb_sectors,
                       int *pnum);
 
-#define BIOS_ATA_TRANSLATION_AUTO   0
-#define BIOS_ATA_TRANSLATION_NONE   1
-#define BIOS_ATA_TRANSLATION_LBA    2
-#define BIOS_ATA_TRANSLATION_LARGE  3
-#define BIOS_ATA_TRANSLATION_RECHS  4
-
-void bdrv_set_geometry_hint(BlockDriverState *bs,
-                            int cyls, int heads, int secs);
-void bdrv_set_translation_hint(BlockDriverState *bs, int translation);
-void bdrv_get_geometry_hint(BlockDriverState *bs,
-                            int *pcyls, int *pheads, int *psecs);
-int bdrv_get_translation_hint(BlockDriverState *bs);
 void bdrv_set_on_error(BlockDriverState *bs, BlockErrorAction on_read_error,
                        BlockErrorAction on_write_error);
 BlockErrorAction bdrv_get_on_error(BlockDriverState *bs, int is_read);
diff --git a/block_int.h b/block_int.h
index 1fb5352..d72317f 100644
--- a/block_int.h
+++ b/block_int.h
@@ -320,7 +320,6 @@ struct BlockDriverState {
 
     /* NOTE: the following infos are only hints for real hardware
        drivers. They are not used by the block driver */
-    int cyls, heads, secs, translation;
     BlockErrorAction on_read_error, on_write_error;
     bool iostatus_enabled;
     BlockDeviceIoStatus iostatus;
diff --git a/blockdev.c b/blockdev.c
index 161985b..06c997e 100644
--- a/blockdev.c
+++ b/blockdev.c
@@ -7,8 +7,8 @@
  * later.  See the COPYING file in the top-level directory.
  */
 
-#include "block.h"
 #include "blockdev.h"
+#include "hw/block-common.h"
 #include "monitor.h"
 #include "qerror.h"
 #include "qemu-option.h"
@@ -551,17 +551,7 @@ DriveInfo *drive_init(QemuOpts *opts, int default_to_scsi)
     case IF_SCSI:
     case IF_XEN:
     case IF_NONE:
-        switch(media) {
-	case MEDIA_DISK:
-            if (cyls != 0) {
-                bdrv_set_geometry_hint(dinfo->bdrv, cyls, heads, secs);
-                bdrv_set_translation_hint(dinfo->bdrv, translation);
-            }
-	    break;
-	case MEDIA_CDROM:
-            dinfo->media_cd = 1;
-	    break;
-	}
+        dinfo->media_cd = media == MEDIA_CDROM;
         break;
     case IF_SD:
     case IF_FLOPPY:
diff --git a/hw/block-common.h b/hw/block-common.h
index 2f65186..ec7810d 100644
--- a/hw/block-common.h
+++ b/hw/block-common.h
@@ -15,6 +15,12 @@
 
 /* Hard disk geometry */
 
+#define BIOS_ATA_TRANSLATION_AUTO   0
+#define BIOS_ATA_TRANSLATION_NONE   1
+#define BIOS_ATA_TRANSLATION_LBA    2
+#define BIOS_ATA_TRANSLATION_LARGE  3
+#define BIOS_ATA_TRANSLATION_RECHS  4
+
 void hd_geometry_guess(BlockDriverState *bs,
                        uint32_t *pcyls, uint32_t *pheads, uint32_t *psecs,
                        int *ptrans);
diff --git a/hw/hd-geometry.c b/hw/hd-geometry.c
index 7626cbb..74678a6 100644
--- a/hw/hd-geometry.c
+++ b/hw/hd-geometry.c
@@ -122,25 +122,10 @@ void hd_geometry_guess(BlockDriverState *bs,
 {
     int cylinders, heads, secs, translation;
 
-    bdrv_get_geometry_hint(bs, &cylinders, &heads, &secs);
-    translation = bdrv_get_translation_hint(bs);
-
-    if (cylinders != 0) {
-        /* already got a geometry hint: use it */
-        *pcyls = cylinders;
-        *pheads = heads;
-        *psecs = secs;
-        if (ptrans) {
-            *ptrans = translation;
-        }
-        return;
-    }
-
-    assert(translation == BIOS_ATA_TRANSLATION_AUTO);
-
     if (guess_disk_lchs(bs, &cylinders, &heads, &secs) < 0) {
         /* no LCHS guess: use a standard physical disk geometry  */
         guess_chs_for_size(bs, pcyls, pheads, psecs);
+        translation = BIOS_ATA_TRANSLATION_AUTO;
     } else if (heads > 16) {
         /* LCHS guess with heads > 16 means that a BIOS LBA
            translation was active, so a standard physical disk
@@ -149,7 +134,6 @@ void hd_geometry_guess(BlockDriverState *bs,
         translation = *pcyls * *pheads <= 131072
             ? BIOS_ATA_TRANSLATION_LARGE
             : BIOS_ATA_TRANSLATION_LBA;
-        bdrv_set_translation_hint(bs, translation);
     } else {
         /* LCHS guess with heads <= 16: use as physical geometry */
         *pcyls = cylinders;
@@ -158,11 +142,9 @@ void hd_geometry_guess(BlockDriverState *bs,
         /* disable any translation to be in sync with
            the logical geometry */
         translation = BIOS_ATA_TRANSLATION_NONE;
-        bdrv_set_translation_hint(bs, translation);
     }
     if (ptrans) {
         *ptrans = translation;
     }
-    bdrv_set_geometry_hint(bs, *pcyls, *pheads, *psecs);
     trace_hd_geometry_guess(bs, *pcyls, *pheads, *psecs, translation);
 }
diff --git a/hw/pc.c b/hw/pc.c
index 89a0c66..77b12b4 100644
--- a/hw/pc.c
+++ b/hw/pc.c
@@ -44,6 +44,7 @@
 #include "kvm.h"
 #include "xen.h"
 #include "blockdev.h"
+#include "hw/block-common.h"
 #include "ui/qemu-spice.h"
 #include "memory.h"
 #include "exec-memory.h"
diff --git a/hw/qdev-properties.c b/hw/qdev-properties.c
index 0b18f8c..01c378f 100644
--- a/hw/qdev-properties.c
+++ b/hw/qdev-properties.c
@@ -2,6 +2,7 @@
 #include "qdev.h"
 #include "qerror.h"
 #include "blockdev.h"
+#include "hw/block-common.h"
 
 void *qdev_get_prop_ptr(DeviceState *dev, Property *prop)
 {
diff --git a/vl.c b/vl.c
index 46248b9..8904db1 100644
--- a/vl.c
+++ b/vl.c
@@ -130,8 +130,8 @@ int main(int argc, char **argv)
 #include "qemu-timer.h"
 #include "qemu-char.h"
 #include "cache-utils.h"
-#include "block.h"
 #include "blockdev.h"
+#include "hw/block-common.h"
 #include "block-migration.h"
 #include "dma.h"
 #include "audio/audio.h"
commit 856dcba23ad2aeea4d98d5d3c97cd46aac0cd073
Author: Markus Armbruster <armbru at redhat.com>
Date:   Tue Jul 10 11:12:49 2012 +0200

    qtest: Cover qdev property for BIOS CHS translation
    
    Signed-off-by: Markus Armbruster <armbru at redhat.com>
    Signed-off-by: Kevin Wolf <kwolf at redhat.com>

diff --git a/tests/hd-geo-test.c b/tests/hd-geo-test.c
index a47b945..5d9d2e4 100644
--- a/tests/hd-geo-test.c
+++ b/tests/hd-geo-test.c
@@ -321,15 +321,16 @@ static void test_ide_drive_user(const char *dev, bool trans)
     const CHST expected_chst = { secs / (4 * 32) , 4, 32, trans };
 
     argc = setup_common(argv, ARRAY_SIZE(argv));
-    opts = g_strdup_printf("%s,cyls=%d,heads=%d,secs=%d%s",
-                           dev && !trans ? dev : "",
+    opts = g_strdup_printf("%s,%s%scyls=%d,heads=%d,secs=%d",
+                           dev ?: "",
+                           trans && dev ? "bios-chs-" : "",
+                           trans ? "trans=lba," : "",
                            expected_chst.cyls, expected_chst.heads,
-                           expected_chst.secs,
-                           trans ? ",trans=lba" : "");
+                           expected_chst.secs);
     cur_ide[0] = &expected_chst;
     argc = setup_ide(argc, argv, ARRAY_SIZE(argv),
-                     0, dev && !trans ? opts : NULL, backend_small, mbr_chs,
-                     dev && !trans ? "" : opts);
+                     0, dev ? opts : NULL, backend_small, mbr_chs,
+                     dev ? "" : opts);
     g_free(opts);
     qtest_start(g_strjoinv(" ", argv));
     test_cmos();
commit 6e6f61a66aa45a15c9f411ad000a8d3d57272f8a
Author: Markus Armbruster <armbru at redhat.com>
Date:   Tue Jul 10 11:12:48 2012 +0200

    ide: qdev property for BIOS CHS translation
    
    This isn't quite orthodox.  CHS translation is firmware configuration,
    communicated via the RTC's CMOS RAM, not a property of the disk.  But
    it's best to treat it just like geometry anyway.
    
    Maintain backward compatibility exactly like for geometry: fall back
    to DriveInfo's translation, set with -drive trans=...
    
    Bonus: info qtree now shows the translation.  Except when it shows
    "auto": that's resolved by pc_cmos_init_late().  To be addressed
    shortly.
    
    Signed-off-by: Markus Armbruster <armbru at redhat.com>
    Signed-off-by: Kevin Wolf <kwolf at redhat.com>

diff --git a/hw/ide/internal.h b/hw/ide/internal.h
index 685e976..c3ecafc 100644
--- a/hw/ide/internal.h
+++ b/hw/ide/internal.h
@@ -474,6 +474,7 @@ struct IDEDevice {
     DeviceState qdev;
     uint32_t unit;
     BlockConf conf;
+    int chs_trans;
     char *version;
     char *serial;
     char *model;
diff --git a/hw/ide/qdev.c b/hw/ide/qdev.c
index 3e297dc..f191dd3 100644
--- a/hw/ide/qdev.c
+++ b/hw/ide/qdev.c
@@ -144,7 +144,6 @@ static int ide_dev_initfn(IDEDevice *dev, IDEDriveKind kind)
     IDEState *s = bus->ifs + dev->unit;
     const char *serial;
     DriveInfo *dinfo;
-    int trans;
 
     if (dev->conf.discard_granularity && dev->conf.discard_granularity != 512) {
         error_report("discard_granularity must be 512 for ide");
@@ -160,25 +159,24 @@ static int ide_dev_initfn(IDEDevice *dev, IDEDriveKind kind)
         }
     }
 
-    trans = BIOS_ATA_TRANSLATION_AUTO;
     if (!dev->conf.cyls && !dev->conf.heads && !dev->conf.secs) {
         /* try to fall back to value set with legacy -drive cyls=... */
         dinfo = drive_get_by_blockdev(dev->conf.bs);
         dev->conf.cyls  = dinfo->cyls;
         dev->conf.heads = dinfo->heads;
         dev->conf.secs  = dinfo->secs;
-        trans           = dinfo->trans;
+        dev->chs_trans  = dinfo->trans;
     }
     if (!dev->conf.cyls && !dev->conf.heads && !dev->conf.secs) {
         hd_geometry_guess(dev->conf.bs,
                           &dev->conf.cyls, &dev->conf.heads, &dev->conf.secs,
-                          &trans);
+                          &dev->chs_trans);
     }
 
     if (ide_init_drive(s, dev->conf.bs, kind,
                        dev->version, serial, dev->model, dev->wwn,
                        dev->conf.cyls, dev->conf.heads, dev->conf.secs,
-                       trans) < 0) {
+                       dev->chs_trans) < 0) {
         return -1;
     }
 
@@ -222,6 +220,8 @@ static int ide_drive_initfn(IDEDevice *dev)
 static Property ide_hd_properties[] = {
     DEFINE_IDE_DEV_PROPERTIES(),
     DEFINE_BLOCK_CHS_PROPERTIES(IDEDrive, dev.conf),
+    DEFINE_PROP_BIOS_CHS_TRANS("bios-chs-trans",
+                IDEDrive, dev.chs_trans, BIOS_ATA_TRANSLATION_AUTO),
     DEFINE_PROP_END_OF_LIST(),
 };
 
commit 8cd41745fbe4ebbc7adff247cf2955765f7eb5e2
Author: Markus Armbruster <armbru at redhat.com>
Date:   Tue Jul 10 11:12:47 2012 +0200

    qdev: New property type chs-translation
    
    Signed-off-by: Markus Armbruster <armbru at redhat.com>
    Signed-off-by: Kevin Wolf <kwolf at redhat.com>

diff --git a/hw/qdev-properties.c b/hw/qdev-properties.c
index 002c7f9..0b18f8c 100644
--- a/hw/qdev-properties.c
+++ b/hw/qdev-properties.c
@@ -782,6 +782,21 @@ PropertyInfo qdev_prop_losttickpolicy = {
     .set   = set_enum,
 };
 
+/* --- BIOS CHS translation */
+
+static const char *bios_chs_trans_table[] = {
+    [BIOS_ATA_TRANSLATION_AUTO] = "auto",
+    [BIOS_ATA_TRANSLATION_NONE] = "none",
+    [BIOS_ATA_TRANSLATION_LBA]  = "lba",
+};
+
+PropertyInfo qdev_prop_bios_chs_trans = {
+    .name = "bios-chs-trans",
+    .enum_table = bios_chs_trans_table,
+    .get = get_enum,
+    .set = set_enum,
+};
+
 /* --- pci address --- */
 
 /*
diff --git a/hw/qdev.h b/hw/qdev.h
index f4683dc..9be35d4 100644
--- a/hw/qdev.h
+++ b/hw/qdev.h
@@ -232,6 +232,7 @@ extern PropertyInfo qdev_prop_chr;
 extern PropertyInfo qdev_prop_ptr;
 extern PropertyInfo qdev_prop_macaddr;
 extern PropertyInfo qdev_prop_losttickpolicy;
+extern PropertyInfo qdev_prop_bios_chs_trans;
 extern PropertyInfo qdev_prop_drive;
 extern PropertyInfo qdev_prop_netdev;
 extern PropertyInfo qdev_prop_vlan;
@@ -299,6 +300,8 @@ extern PropertyInfo qdev_prop_pci_host_devaddr;
 #define DEFINE_PROP_LOSTTICKPOLICY(_n, _s, _f, _d) \
     DEFINE_PROP_DEFAULT(_n, _s, _f, _d, qdev_prop_losttickpolicy, \
                         LostTickPolicy)
+#define DEFINE_PROP_BIOS_CHS_TRANS(_n, _s, _f, _d) \
+    DEFINE_PROP_DEFAULT(_n, _s, _f, _d, qdev_prop_bios_chs_trans, int)
 #define DEFINE_PROP_BLOCKSIZE(_n, _s, _f, _d) \
     DEFINE_PROP_DEFAULT(_n, _s, _f, _d, qdev_prop_blocksize, uint16_t)
 #define DEFINE_PROP_PCI_HOST_DEVADDR(_n, _s, _f) \
commit d4d34b0d3f5af5c8e09980da0de2eebe9a27dc71
Author: Markus Armbruster <armbru at redhat.com>
Date:   Tue Jul 10 11:12:46 2012 +0200

    qdev: Collect private helpers in one place
    
    Just code motion, with one long line wrapped to keep checkpatch.pl
    happy.
    
    Signed-off-by: Markus Armbruster <armbru at redhat.com>
    Signed-off-by: Kevin Wolf <kwolf at redhat.com>

diff --git a/hw/qdev-properties.c b/hw/qdev-properties.c
index 0b89462..002c7f9 100644
--- a/hw/qdev-properties.c
+++ b/hw/qdev-properties.c
@@ -10,6 +10,78 @@ void *qdev_get_prop_ptr(DeviceState *dev, Property *prop)
     return ptr;
 }
 
+static void get_pointer(Object *obj, Visitor *v, Property *prop,
+                        const char *(*print)(void *ptr),
+                        const char *name, Error **errp)
+{
+    DeviceState *dev = DEVICE(obj);
+    void **ptr = qdev_get_prop_ptr(dev, prop);
+    char *p;
+
+    p = (char *) (*ptr ? print(*ptr) : "");
+    visit_type_str(v, &p, name, errp);
+}
+
+static void set_pointer(Object *obj, Visitor *v, Property *prop,
+                        int (*parse)(DeviceState *dev, const char *str,
+                                     void **ptr),
+                        const char *name, Error **errp)
+{
+    DeviceState *dev = DEVICE(obj);
+    Error *local_err = NULL;
+    void **ptr = qdev_get_prop_ptr(dev, prop);
+    char *str;
+    int ret;
+
+    if (dev->state != DEV_STATE_CREATED) {
+        error_set(errp, QERR_PERMISSION_DENIED);
+        return;
+    }
+
+    visit_type_str(v, &str, name, &local_err);
+    if (local_err) {
+        error_propagate(errp, local_err);
+        return;
+    }
+    if (!*str) {
+        g_free(str);
+        *ptr = NULL;
+        return;
+    }
+    ret = parse(dev, str, ptr);
+    error_set_from_qdev_prop_error(errp, ret, dev, prop, str);
+    g_free(str);
+}
+
+static void get_enum(Object *obj, Visitor *v, void *opaque,
+                     const char *name, Error **errp)
+{
+    DeviceState *dev = DEVICE(obj);
+    Property *prop = opaque;
+    int *ptr = qdev_get_prop_ptr(dev, prop);
+
+    visit_type_enum(v, ptr, prop->info->enum_table,
+                    prop->info->name, prop->name, errp);
+}
+
+static void set_enum(Object *obj, Visitor *v, void *opaque,
+                     const char *name, Error **errp)
+{
+    DeviceState *dev = DEVICE(obj);
+    Property *prop = opaque;
+    int *ptr = qdev_get_prop_ptr(dev, prop);
+
+    if (dev->state != DEV_STATE_CREATED) {
+        error_set(errp, QERR_PERMISSION_DENIED);
+        return;
+    }
+
+    visit_type_enum(v, ptr, prop->info->enum_table,
+                    prop->info->name, prop->name, errp);
+}
+
+/* Bit */
+
 static uint32_t qdev_get_prop_mask(Property *prop)
 {
     assert(prop->info == &qdev_prop_bit);
@@ -26,8 +98,6 @@ static void bit_prop_set(DeviceState *dev, Property *props, bool val)
         *p &= ~mask;
 }
 
-/* Bit */
-
 static int print_bit(DeviceState *dev, Property *prop, char *dest, size_t len)
 {
     uint32_t *p = qdev_get_prop_ptr(dev, prop);
@@ -435,48 +505,6 @@ static const char *print_drive(void *ptr)
     return bdrv_get_device_name(ptr);
 }
 
-static void get_pointer(Object *obj, Visitor *v, Property *prop,
-                        const char *(*print)(void *ptr),
-                        const char *name, Error **errp)
-{
-    DeviceState *dev = DEVICE(obj);
-    void **ptr = qdev_get_prop_ptr(dev, prop);
-    char *p;
-
-    p = (char *) (*ptr ? print(*ptr) : "");
-    visit_type_str(v, &p, name, errp);
-}
-
-static void set_pointer(Object *obj, Visitor *v, Property *prop,
-                        int (*parse)(DeviceState *dev, const char *str, void **ptr),
-                        const char *name, Error **errp)
-{
-    DeviceState *dev = DEVICE(obj);
-    Error *local_err = NULL;
-    void **ptr = qdev_get_prop_ptr(dev, prop);
-    char *str;
-    int ret;
-
-    if (dev->state != DEV_STATE_CREATED) {
-        error_set(errp, QERR_PERMISSION_DENIED);
-        return;
-    }
-
-    visit_type_str(v, &str, name, &local_err);
-    if (local_err) {
-        error_propagate(errp, local_err);
-        return;
-    }
-    if (!*str) {
-        g_free(str);
-        *ptr = NULL;
-        return;
-    }
-    ret = parse(dev, str, ptr);
-    error_set_from_qdev_prop_error(errp, ret, dev, prop, str);
-    g_free(str);
-}
-
 static void get_drive(Object *obj, Visitor *v, void *opaque,
                       const char *name, Error **errp)
 {
@@ -735,7 +763,6 @@ PropertyInfo qdev_prop_macaddr = {
     .set   = set_mac,
 };
 
-
 /* --- lost tick policy --- */
 
 static const char *lost_tick_policy_table[LOST_TICK_MAX+1] = {
@@ -748,33 +775,6 @@ static const char *lost_tick_policy_table[LOST_TICK_MAX+1] = {
 
 QEMU_BUILD_BUG_ON(sizeof(LostTickPolicy) != sizeof(int));
 
-static void get_enum(Object *obj, Visitor *v, void *opaque,
-                     const char *name, Error **errp)
-{
-    DeviceState *dev = DEVICE(obj);
-    Property *prop = opaque;
-    int *ptr = qdev_get_prop_ptr(dev, prop);
-
-    visit_type_enum(v, ptr, prop->info->enum_table,
-                    prop->info->name, prop->name, errp);
-}
-
-static void set_enum(Object *obj, Visitor *v, void *opaque,
-                     const char *name, Error **errp)
-{
-    DeviceState *dev = DEVICE(obj);
-    Property *prop = opaque;
-    int *ptr = qdev_get_prop_ptr(dev, prop);
-
-    if (dev->state != DEV_STATE_CREATED) {
-        error_set(errp, QERR_PERMISSION_DENIED);
-        return;
-    }
-
-    visit_type_enum(v, ptr, prop->info->enum_table,
-                    prop->info->name, prop->name, errp);
-}
-
 PropertyInfo qdev_prop_losttickpolicy = {
     .name  = "LostTickPolicy",
     .enum_table  = lost_tick_policy_table,
commit eb0e4b9804ce634386c4de4b2708af0ad01edaa1
Author: Markus Armbruster <armbru at redhat.com>
Date:   Tue Jul 10 11:12:45 2012 +0200

    qtest: Cover qdev properties for disk geometry
    
    Signed-off-by: Markus Armbruster <armbru at redhat.com>
    Signed-off-by: Kevin Wolf <kwolf at redhat.com>

diff --git a/tests/hd-geo-test.c b/tests/hd-geo-test.c
index cc447a2..a47b945 100644
--- a/tests/hd-geo-test.c
+++ b/tests/hd-geo-test.c
@@ -321,13 +321,15 @@ static void test_ide_drive_user(const char *dev, bool trans)
     const CHST expected_chst = { secs / (4 * 32) , 4, 32, trans };
 
     argc = setup_common(argv, ARRAY_SIZE(argv));
-    opts = g_strdup_printf(",cyls=%d,heads=%d,secs=%d%s",
+    opts = g_strdup_printf("%s,cyls=%d,heads=%d,secs=%d%s",
+                           dev && !trans ? dev : "",
                            expected_chst.cyls, expected_chst.heads,
                            expected_chst.secs,
                            trans ? ",trans=lba" : "");
     cur_ide[0] = &expected_chst;
     argc = setup_ide(argc, argv, ARRAY_SIZE(argv),
-                     0, dev, backend_small, mbr_chs, opts);
+                     0, dev && !trans ? opts : NULL, backend_small, mbr_chs,
+                     dev && !trans ? "" : opts);
     g_free(opts);
     qtest_start(g_strjoinv(" ", argv));
     test_cmos();
commit ba801960db1c08035f7e1772bd482aa80d909a35
Author: Markus Armbruster <armbru at redhat.com>
Date:   Tue Jul 10 11:12:44 2012 +0200

    ide: qdev properties for disk geometry
    
    Geometry needs to be qdev properties, because it belongs to the
    disk's guest part.
    
    Maintain backward compatibility exactly like for serial: fall back to
    DriveInfo's geometry, set with -drive cyls=...
    
    Do this only for ide-hd.  ide-drive is legacy.  ide-cd doesn't have a
    geometry.
    
    Bonus: info qtree now shows the geometry.
    
    Signed-off-by: Markus Armbruster <armbru at redhat.com>
    Signed-off-by: Kevin Wolf <kwolf at redhat.com>

diff --git a/hw/ide/core.c b/hw/ide/core.c
index f1966e3..bf1ce89 100644
--- a/hw/ide/core.c
+++ b/hw/ide/core.c
@@ -1925,16 +1925,16 @@ static const BlockDevOps ide_cd_block_ops = {
 
 int ide_init_drive(IDEState *s, BlockDriverState *bs, IDEDriveKind kind,
                    const char *version, const char *serial, const char *model,
-                   uint64_t wwn)
+                   uint64_t wwn,
+                   uint32_t cylinders, uint32_t heads, uint32_t secs,
+                   int chs_trans)
 {
-    uint32_t cylinders, heads, secs;
     uint64_t nb_sectors;
 
     s->bs = bs;
     s->drive_kind = kind;
 
     bdrv_get_geometry(bs, &nb_sectors);
-    hd_geometry_guess(bs, &cylinders, &heads, &secs, &s->chs_trans);
     if (cylinders < 1 || cylinders > 16383) {
         error_report("cyls must be between 1 and 16383");
         return -1;
@@ -1950,6 +1950,7 @@ int ide_init_drive(IDEState *s, BlockDriverState *bs, IDEDriveKind kind,
     s->cylinders = cylinders;
     s->heads = heads;
     s->sectors = secs;
+    s->chs_trans = chs_trans;
     s->nb_sectors = nb_sectors;
     s->wwn = wwn;
     /* The SMART values should be preserved across power cycles
@@ -2076,17 +2077,25 @@ void ide_init2(IDEBus *bus, qemu_irq irq)
 void ide_init2_with_non_qdev_drives(IDEBus *bus, DriveInfo *hd0,
                                     DriveInfo *hd1, qemu_irq irq)
 {
-    int i;
+    int i, trans;
     DriveInfo *dinfo;
+    uint32_t cyls, heads, secs;
 
     for(i = 0; i < 2; i++) {
         dinfo = i == 0 ? hd0 : hd1;
         ide_init1(bus, i);
         if (dinfo) {
+            cyls  = dinfo->cyls;
+            heads = dinfo->heads;
+            secs  = dinfo->secs;
+            trans = dinfo->trans;
+            if (!cyls && !heads && !secs) {
+                hd_geometry_guess(dinfo->bdrv, &cyls, &heads, &secs, &trans);
+            }
             if (ide_init_drive(&bus->ifs[i], dinfo->bdrv,
                                dinfo->media_cd ? IDE_CD : IDE_HD, NULL,
                                *dinfo->serial ? dinfo->serial : NULL,
-                               NULL, 0) < 0) {
+                               NULL, 0, cyls, heads, secs, trans) < 0) {
                 error_report("Can't set up IDE drive %s", dinfo->id);
                 exit(1);
             }
diff --git a/hw/ide/internal.h b/hw/ide/internal.h
index 56c718e..685e976 100644
--- a/hw/ide/internal.h
+++ b/hw/ide/internal.h
@@ -545,7 +545,9 @@ uint32_t ide_data_readl(void *opaque, uint32_t addr);
 
 int ide_init_drive(IDEState *s, BlockDriverState *bs, IDEDriveKind kind,
                    const char *version, const char *serial, const char *model,
-                   uint64_t wwn);
+                   uint64_t wwn,
+                   uint32_t cylinders, uint32_t heads, uint32_t secs,
+                   int chs_trans);
 void ide_init2(IDEBus *bus, qemu_irq irq);
 void ide_init2_with_non_qdev_drives(IDEBus *bus, DriveInfo *hd0,
                                     DriveInfo *hd1, qemu_irq irq);
diff --git a/hw/ide/qdev.c b/hw/ide/qdev.c
index 87e0b75..3e297dc 100644
--- a/hw/ide/qdev.c
+++ b/hw/ide/qdev.c
@@ -21,6 +21,7 @@
 #include "qemu-error.h"
 #include <hw/ide/internal.h>
 #include "blockdev.h"
+#include "hw/block-common.h"
 #include "sysemu.h"
 
 /* --------------------------------- */
@@ -143,6 +144,7 @@ static int ide_dev_initfn(IDEDevice *dev, IDEDriveKind kind)
     IDEState *s = bus->ifs + dev->unit;
     const char *serial;
     DriveInfo *dinfo;
+    int trans;
 
     if (dev->conf.discard_granularity && dev->conf.discard_granularity != 512) {
         error_report("discard_granularity must be 512 for ide");
@@ -158,8 +160,25 @@ static int ide_dev_initfn(IDEDevice *dev, IDEDriveKind kind)
         }
     }
 
+    trans = BIOS_ATA_TRANSLATION_AUTO;
+    if (!dev->conf.cyls && !dev->conf.heads && !dev->conf.secs) {
+        /* try to fall back to value set with legacy -drive cyls=... */
+        dinfo = drive_get_by_blockdev(dev->conf.bs);
+        dev->conf.cyls  = dinfo->cyls;
+        dev->conf.heads = dinfo->heads;
+        dev->conf.secs  = dinfo->secs;
+        trans           = dinfo->trans;
+    }
+    if (!dev->conf.cyls && !dev->conf.heads && !dev->conf.secs) {
+        hd_geometry_guess(dev->conf.bs,
+                          &dev->conf.cyls, &dev->conf.heads, &dev->conf.secs,
+                          &trans);
+    }
+
     if (ide_init_drive(s, dev->conf.bs, kind,
-                       dev->version, serial, dev->model, dev->wwn) < 0) {
+                       dev->version, serial, dev->model, dev->wwn,
+                       dev->conf.cyls, dev->conf.heads, dev->conf.secs,
+                       trans) < 0) {
         return -1;
     }
 
@@ -202,6 +221,7 @@ static int ide_drive_initfn(IDEDevice *dev)
 
 static Property ide_hd_properties[] = {
     DEFINE_IDE_DEV_PROPERTIES(),
+    DEFINE_BLOCK_CHS_PROPERTIES(IDEDrive, dev.conf),
     DEFINE_PROP_END_OF_LIST(),
 };
 
commit e63e7fde24a3e88f1a4992d8f47b7a44ddcf14ff
Author: Markus Armbruster <armbru at redhat.com>
Date:   Tue Jul 10 11:12:43 2012 +0200

    virtio-blk: qdev properties for disk geometry
    
    Geometry needs to be qdev properties, because it belongs to the
    disk's guest part.
    
    Maintain backward compatibility exactly like for serial: fall back to
    DriveInfo's geometry, set with -drive cyls=...
    
    Bonus: info qtree now shows the geometry.
    
    Signed-off-by: Markus Armbruster <armbru at redhat.com>
    Signed-off-by: Kevin Wolf <kwolf at redhat.com>

diff --git a/hw/s390-virtio-bus.c b/hw/s390-virtio-bus.c
index 4d49b96..a245684 100644
--- a/hw/s390-virtio-bus.c
+++ b/hw/s390-virtio-bus.c
@@ -402,6 +402,7 @@ static TypeInfo s390_virtio_net = {
 
 static Property s390_virtio_blk_properties[] = {
     DEFINE_BLOCK_PROPERTIES(VirtIOS390Device, blk.conf),
+    DEFINE_BLOCK_CHS_PROPERTIES(VirtIOS390Device, blk.conf),
     DEFINE_PROP_STRING("serial", VirtIOS390Device, blk.serial),
 #ifdef __linux__
     DEFINE_PROP_BIT("scsi", VirtIOS390Device, blk.scsi, 0, true),
diff --git a/hw/virtio-blk.c b/hw/virtio-blk.c
index 4344e28..3885904 100644
--- a/hw/virtio-blk.c
+++ b/hw/virtio-blk.c
@@ -479,19 +479,17 @@ static void virtio_blk_update_config(VirtIODevice *vdev, uint8_t *config)
     VirtIOBlock *s = to_virtio_blk(vdev);
     struct virtio_blk_config blkcfg;
     uint64_t capacity;
-    int cylinders, heads, secs;
     int blk_size = s->conf->logical_block_size;
 
     bdrv_get_geometry(s->bs, &capacity);
-    bdrv_get_geometry_hint(s->bs, &cylinders, &heads, &secs);
     memset(&blkcfg, 0, sizeof(blkcfg));
     stq_raw(&blkcfg.capacity, capacity);
     stl_raw(&blkcfg.seg_max, 128 - 2);
-    stw_raw(&blkcfg.cylinders, cylinders);
+    stw_raw(&blkcfg.cylinders, s->conf->cyls);
     stl_raw(&blkcfg.blk_size, blk_size);
     stw_raw(&blkcfg.min_io_size, s->conf->min_io_size / blk_size);
     stw_raw(&blkcfg.opt_io_size, s->conf->opt_io_size / blk_size);
-    blkcfg.heads = heads;
+    blkcfg.heads = s->conf->heads;
     /*
      * We must ensure that the block device capacity is a multiple of
      * the logical block size. If that is not the case, lets use
@@ -503,10 +501,10 @@ static void virtio_blk_update_config(VirtIODevice *vdev, uint8_t *config)
      * divided by 512 - instead it is the amount of blk_size blocks
      * per track (cylinder).
      */
-    if (bdrv_getlength(s->bs) /  heads / secs % blk_size) {
-        blkcfg.sectors = secs & ~s->sector_mask;
+    if (bdrv_getlength(s->bs) /  s->conf->heads / s->conf->secs % blk_size) {
+        blkcfg.sectors = s->conf->secs & ~s->sector_mask;
     } else {
-        blkcfg.sectors = secs;
+        blkcfg.sectors = s->conf->secs;
     }
     blkcfg.size_max = 0;
     blkcfg.physical_block_exp = get_physical_block_exp(s->conf);
@@ -590,7 +588,6 @@ static const BlockDevOps virtio_block_ops = {
 VirtIODevice *virtio_blk_init(DeviceState *dev, VirtIOBlkConf *blk)
 {
     VirtIOBlock *s;
-    uint32_t cylinders, heads, secs;
     static int virtio_blk_id;
     DriveInfo *dinfo;
 
@@ -623,7 +620,33 @@ VirtIODevice *virtio_blk_init(DeviceState *dev, VirtIOBlkConf *blk)
     s->blk = blk;
     s->rq = NULL;
     s->sector_mask = (s->conf->logical_block_size / BDRV_SECTOR_SIZE) - 1;
-    hd_geometry_guess(s->bs, &cylinders, &heads, &secs, NULL);
+
+    if (!blk->conf.cyls && !blk->conf.heads && !blk->conf.secs) {
+        /* try to fall back to value set with legacy -drive cyls=... */
+        dinfo = drive_get_by_blockdev(blk->conf.bs);
+        blk->conf.cyls = dinfo->cyls;
+        blk->conf.heads = dinfo->heads;
+        blk->conf.secs = dinfo->secs;
+    }
+    if (!blk->conf.cyls && !blk->conf.heads && !blk->conf.secs) {
+        hd_geometry_guess(s->bs,
+                          &blk->conf.cyls, &blk->conf.heads, &blk->conf.secs,
+                          NULL);
+    }
+    if (blk->conf.cyls || blk->conf.heads || blk->conf.secs) {
+        if (blk->conf.cyls < 1 || blk->conf.cyls > 65535) {
+            error_report("cyls must be between 1 and 65535");
+            return NULL;
+        }
+        if (blk->conf.heads < 1 || blk->conf.heads > 255) {
+            error_report("heads must be between 1 and 255");
+            return NULL;
+        }
+        if (blk->conf.secs < 1 || blk->conf.secs > 255) {
+            error_report("secs must be between 1 and 255");
+            return NULL;
+        }
+    }
 
     s->vq = virtio_add_queue(&s->vdev, 128, virtio_blk_handle_output);
 
diff --git a/hw/virtio-pci.c b/hw/virtio-pci.c
index 9342eed..557d1d3 100644
--- a/hw/virtio-pci.c
+++ b/hw/virtio-pci.c
@@ -936,6 +936,7 @@ static int virtio_balloon_exit_pci(PCIDevice *pci_dev)
 static Property virtio_blk_properties[] = {
     DEFINE_PROP_HEX32("class", VirtIOPCIProxy, class_code, 0),
     DEFINE_BLOCK_PROPERTIES(VirtIOPCIProxy, blk.conf),
+    DEFINE_BLOCK_CHS_PROPERTIES(VirtIOPCIProxy, blk.conf),
     DEFINE_PROP_STRING("serial", VirtIOPCIProxy, blk.serial),
 #ifdef __linux__
     DEFINE_PROP_BIT("scsi", VirtIOPCIProxy, blk.scsi, 0, true),
commit d252df489879ca3b128e080409b89305491d04cf
Author: Markus Armbruster <armbru at redhat.com>
Date:   Tue Jul 10 11:12:42 2012 +0200

    scsi-hd: qdev properties for disk geometry
    
    Geometry needs to be qdev properties, because it belongs to the
    disk's guest part.
    
    Maintain backward compatibility exactly like for serial: fall back to
    DriveInfo's geometry, set with -drive cyls=...
    
    Do this only for scsi-hd.  scsi-disk is legacy.  scsi-cd doesn't have
    a geometry.  scsi-block should get geometry from the host disk.
    
    Bonus: info qtree now shows the geometry.
    
    Signed-off-by: Markus Armbruster <armbru at redhat.com>
    Signed-off-by: Kevin Wolf <kwolf at redhat.com>

diff --git a/hw/scsi-disk.c b/hw/scsi-disk.c
index c881acf..0a182f9 100644
--- a/hw/scsi-disk.c
+++ b/hw/scsi-disk.c
@@ -966,9 +966,6 @@ static int mode_sense_page(SCSIDiskState *s, int page, uint8_t **p_outbuf,
         [MODE_PAGE_AUDIO_CTL]              = (1 << TYPE_ROM),
         [MODE_PAGE_CAPABILITIES]           = (1 << TYPE_ROM),
     };
-
-    BlockDriverState *bdrv = s->qdev.conf.bs;
-    uint32_t cylinders, heads, secs;
     uint8_t *p = *p_outbuf;
 
     if ((mode_sense_valid[page] & (1 << s->qdev.type)) == 0) {
@@ -990,19 +987,18 @@ static int mode_sense_page(SCSIDiskState *s, int page, uint8_t **p_outbuf,
             break;
         }
         /* if a geometry hint is available, use it */
-        hd_geometry_guess(bdrv, &cylinders, &heads, &secs, NULL);
-        p[2] = (cylinders >> 16) & 0xff;
-        p[3] = (cylinders >> 8) & 0xff;
-        p[4] = cylinders & 0xff;
-        p[5] = heads & 0xff;
+        p[2] = (s->qdev.conf.cyls >> 16) & 0xff;
+        p[3] = (s->qdev.conf.cyls >> 8) & 0xff;
+        p[4] = s->qdev.conf.cyls & 0xff;
+        p[5] = s->qdev.conf.heads & 0xff;
         /* Write precomp start cylinder, disabled */
-        p[6] = (cylinders >> 16) & 0xff;
-        p[7] = (cylinders >> 8) & 0xff;
-        p[8] = cylinders & 0xff;
+        p[6] = (s->qdev.conf.cyls >> 16) & 0xff;
+        p[7] = (s->qdev.conf.cyls >> 8) & 0xff;
+        p[8] = s->qdev.conf.cyls & 0xff;
         /* Reduced current start cylinder, disabled */
-        p[9] = (cylinders >> 16) & 0xff;
-        p[10] = (cylinders >> 8) & 0xff;
-        p[11] = cylinders & 0xff;
+        p[9] = (s->qdev.conf.cyls >> 16) & 0xff;
+        p[10] = (s->qdev.conf.cyls >> 8) & 0xff;
+        p[11] = s->qdev.conf.cyls & 0xff;
         /* Device step rate [ns], 200ns */
         p[12] = 0;
         p[13] = 200;
@@ -1024,18 +1020,17 @@ static int mode_sense_page(SCSIDiskState *s, int page, uint8_t **p_outbuf,
         p[2] = 5000 >> 8;
         p[3] = 5000 & 0xff;
         /* if a geometry hint is available, use it */
-        hd_geometry_guess(bdrv, &cylinders, &heads, &secs, NULL);
-        p[4] = heads & 0xff;
-        p[5] = secs & 0xff;
+        p[4] = s->qdev.conf.heads & 0xff;
+        p[5] = s->qdev.conf.secs & 0xff;
         p[6] = s->qdev.blocksize >> 8;
-        p[8] = (cylinders >> 8) & 0xff;
-        p[9] = cylinders & 0xff;
+        p[8] = (s->qdev.conf.cyls >> 8) & 0xff;
+        p[9] = s->qdev.conf.cyls & 0xff;
         /* Write precomp start cylinder, disabled */
-        p[10] = (cylinders >> 8) & 0xff;
-        p[11] = cylinders & 0xff;
+        p[10] = (s->qdev.conf.cyls >> 8) & 0xff;
+        p[11] = s->qdev.conf.cyls & 0xff;
         /* Reduced current start cylinder, disabled */
-        p[12] = (cylinders >> 8) & 0xff;
-        p[13] = cylinders & 0xff;
+        p[12] = (s->qdev.conf.cyls >> 8) & 0xff;
+        p[13] = s->qdev.conf.cyls & 0xff;
         /* Device step rate [100us], 100us */
         p[14] = 0;
         p[15] = 1;
@@ -1755,6 +1750,33 @@ static int scsi_initfn(SCSIDevice *dev)
         return -1;
     }
 
+    if (!dev->conf.cyls && !dev->conf.heads && !dev->conf.secs) {
+        /* try to fall back to value set with legacy -drive cyls=... */
+        dinfo = drive_get_by_blockdev(s->qdev.conf.bs);
+        dev->conf.cyls = dinfo->cyls;
+        dev->conf.heads = dinfo->heads;
+        dev->conf.secs = dinfo->secs;
+    }
+    if (!dev->conf.cyls && !dev->conf.heads && !dev->conf.secs) {
+        hd_geometry_guess(s->qdev.conf.bs,
+                          &dev->conf.cyls, &dev->conf.heads, &dev->conf.secs,
+                          NULL);
+    }
+    if (dev->conf.cyls || dev->conf.heads || dev->conf.secs) {
+        if (dev->conf.cyls < 1 || dev->conf.cyls > 65535) {
+            error_report("cyls must be between 1 and 65535");
+            return -1;
+        }
+        if (dev->conf.heads < 1 || dev->conf.heads > 255) {
+            error_report("heads must be between 1 and 255");
+            return -1;
+        }
+        if (dev->conf.secs < 1 || dev->conf.secs > 255) {
+            error_report("secs must be between 1 and 255");
+            return -1;
+        }
+    }
+
     if (!s->serial) {
         /* try to fall back to value set with legacy -drive serial=... */
         dinfo = drive_get_by_blockdev(s->qdev.conf.bs);
@@ -1975,6 +1997,7 @@ static Property scsi_hd_properties[] = {
     DEFINE_PROP_BIT("dpofua", SCSIDiskState, features,
                     SCSI_DISK_F_DPOFUA, false),
     DEFINE_PROP_HEX64("wwn", SCSIDiskState, wwn, 0),
+    DEFINE_BLOCK_CHS_PROPERTIES(SCSIDiskState, qdev.conf),
     DEFINE_PROP_END_OF_LIST(),
 };
 
commit 1f24d7b47e1f18b5e7f0f050f915a42e9aa645db
Author: Markus Armbruster <armbru at redhat.com>
Date:   Tue Jul 10 11:12:41 2012 +0200

    hd-geometry: Switch to uint32_t to match BlockConf
    
    Best to use the same type, to avoid unwanted truncation or sign
    extension.
    
    BlockConf can't use plain int for cyls, heads and secs, because
    integer properties require an exact width.
    
    Signed-off-by: Markus Armbruster <armbru at redhat.com>
    Signed-off-by: Kevin Wolf <kwolf at redhat.com>

diff --git a/hw/block-common.h b/hw/block-common.h
index bba817a..2f65186 100644
--- a/hw/block-common.h
+++ b/hw/block-common.h
@@ -16,7 +16,7 @@
 /* Hard disk geometry */
 
 void hd_geometry_guess(BlockDriverState *bs,
-                       int *pcyls, int *pheads, int *psecs,
+                       uint32_t *pcyls, uint32_t *pheads, uint32_t *psecs,
                        int *ptrans);
 
 #endif
diff --git a/hw/hd-geometry.c b/hw/hd-geometry.c
index 4d746b7..7626cbb 100644
--- a/hw/hd-geometry.c
+++ b/hw/hd-geometry.c
@@ -98,7 +98,7 @@ static int guess_disk_lchs(BlockDriverState *bs,
 }
 
 static void guess_chs_for_size(BlockDriverState *bs,
-                               int *pcyls, int *pheads, int *psecs)
+                uint32_t *pcyls, uint32_t *pheads, uint32_t *psecs)
 {
     uint64_t nb_sectors;
     int cylinders;
@@ -117,7 +117,7 @@ static void guess_chs_for_size(BlockDriverState *bs,
 }
 
 void hd_geometry_guess(BlockDriverState *bs,
-                       int *pcyls, int *pheads, int *psecs,
+                       uint32_t *pcyls, uint32_t *pheads, uint32_t *psecs,
                        int *ptrans)
 {
     int cylinders, heads, secs, translation;
diff --git a/hw/ide/core.c b/hw/ide/core.c
index 7f5ad07..f1966e3 100644
--- a/hw/ide/core.c
+++ b/hw/ide/core.c
@@ -1927,7 +1927,7 @@ int ide_init_drive(IDEState *s, BlockDriverState *bs, IDEDriveKind kind,
                    const char *version, const char *serial, const char *model,
                    uint64_t wwn)
 {
-    int cylinders, heads, secs;
+    uint32_t cylinders, heads, secs;
     uint64_t nb_sectors;
 
     s->bs = bs;
diff --git a/hw/scsi-disk.c b/hw/scsi-disk.c
index fc077f5..c881acf 100644
--- a/hw/scsi-disk.c
+++ b/hw/scsi-disk.c
@@ -968,7 +968,7 @@ static int mode_sense_page(SCSIDiskState *s, int page, uint8_t **p_outbuf,
     };
 
     BlockDriverState *bdrv = s->qdev.conf.bs;
-    int cylinders, heads, secs;
+    uint32_t cylinders, heads, secs;
     uint8_t *p = *p_outbuf;
 
     if ((mode_sense_valid[page] & (1 << s->qdev.type)) == 0) {
diff --git a/hw/virtio-blk.c b/hw/virtio-blk.c
index d2709a7..4344e28 100644
--- a/hw/virtio-blk.c
+++ b/hw/virtio-blk.c
@@ -590,7 +590,7 @@ static const BlockDevOps virtio_block_ops = {
 VirtIODevice *virtio_blk_init(DeviceState *dev, VirtIOBlkConf *blk)
 {
     VirtIOBlock *s;
-    int cylinders, heads, secs;
+    uint32_t cylinders, heads, secs;
     static int virtio_blk_id;
     DriveInfo *dinfo;
 
diff --git a/trace-events b/trace-events
index 5f27f1a..8b1fb24 100644
--- a/trace-events
+++ b/trace-events
@@ -143,7 +143,7 @@ ecc_diag_mem_readb(uint64_t addr, uint32_t ret) "Read diagnostic %"PRId64"= %02x
 
 # hw/hd-geometry.c
 hd_geometry_lchs_guess(void *bs, int cyls, int heads, int secs) "bs %p LCHS %d %d %d"
-hd_geometry_guess(void *bs, int cyls, int heads, int secs, int trans) "bs %p CHS %d %d %d trans %d"
+hd_geometry_guess(void *bs, uint32_t cyls, uint32_t heads, uint32_t secs, int trans) "bs %p CHS %u %u %u trans %d"
 
 # hw/jazz-led.c
 jazz_led_read(uint64_t addr, uint8_t val) "read addr=0x%"PRIx64": 0x%x"
commit 8a4bc5aafa7286e03bbced8abdb43aa6abdf95ea
Author: Markus Armbruster <armbru at redhat.com>
Date:   Tue Jul 10 11:12:40 2012 +0200

    qdev: Introduce block geometry properties
    
    Signed-off-by: Markus Armbruster <armbru at redhat.com>
    Signed-off-by: Kevin Wolf <kwolf at redhat.com>

diff --git a/block.h b/block.h
index 993894e..1cd8a01 100644
--- a/block.h
+++ b/block.h
@@ -426,6 +426,8 @@ typedef struct BlockConf {
     uint32_t opt_io_size;
     int32_t bootindex;
     uint32_t discard_granularity;
+    /* geometry, not all devices use this */
+    uint32_t cyls, heads, secs;
 } BlockConf;
 
 static inline unsigned int get_physical_block_exp(BlockConf *conf)
@@ -453,5 +455,9 @@ static inline unsigned int get_physical_block_exp(BlockConf *conf)
     DEFINE_PROP_UINT32("discard_granularity", _state, \
                        _conf.discard_granularity, 0)
 
-#endif
+#define DEFINE_BLOCK_CHS_PROPERTIES(_state, _conf)      \
+    DEFINE_PROP_UINT32("cyls", _state, _conf.cyls, 0),  \
+    DEFINE_PROP_UINT32("heads", _state, _conf.heads, 0), \
+    DEFINE_PROP_UINT32("secs", _state, _conf.secs, 0)
 
+#endif
commit 317bb412293672ff930884d67235e970dad88566
Author: Markus Armbruster <armbru at redhat.com>
Date:   Tue Jul 10 11:12:39 2012 +0200

    blockdev: Save geometry in DriveInfo
    
    In preparation of purging it from the block layer, which will happen
    later in this series.
    
    Signed-off-by: Markus Armbruster <armbru at redhat.com>
    Signed-off-by: Kevin Wolf <kwolf at redhat.com>

diff --git a/blockdev.c b/blockdev.c
index a85a429..161985b 100644
--- a/blockdev.c
+++ b/blockdev.c
@@ -530,6 +530,10 @@ DriveInfo *drive_init(QemuOpts *opts, int default_to_scsi)
     dinfo->type = type;
     dinfo->bus = bus_id;
     dinfo->unit = unit_id;
+    dinfo->cyls = cyls;
+    dinfo->heads = heads;
+    dinfo->secs = secs;
+    dinfo->trans = translation;
     dinfo->opts = opts;
     dinfo->refcount = 1;
     if (serial) {
diff --git a/blockdev.h b/blockdev.h
index 260e16b..9c29948 100644
--- a/blockdev.h
+++ b/blockdev.h
@@ -35,6 +35,7 @@ struct DriveInfo {
     int unit;
     int auto_del;               /* see blockdev_mark_auto_del() */
     int media_cd;
+    int cyls, heads, secs, trans;
     QemuOpts *opts;
     char serial[BLOCK_SERIAL_STRLEN + 1];
     QTAILQ_ENTRY(DriveInfo) next;
commit 9139046c16688615023f35668660f6d3947a05d6
Author: Markus Armbruster <armbru at redhat.com>
Date:   Tue Jul 10 11:12:38 2012 +0200

    ide pc: Cut out the block layer geometry middleman
    
    PC BIOS setup needs IDE geometry information.  Get it directly from
    the device model rather than through the block layer.  In preparation
    of purging geometry from the block layer, which will happen later in
    this series.
    
    Signed-off-by: Markus Armbruster <armbru at redhat.com>
    Signed-off-by: Kevin Wolf <kwolf at redhat.com>

diff --git a/hw/ide.h b/hw/ide.h
index 0b18c90..2db4079 100644
--- a/hw/ide.h
+++ b/hw/ide.h
@@ -29,7 +29,9 @@ void mmio_ide_init (target_phys_addr_t membase, target_phys_addr_t membase2,
                     qemu_irq irq, int shift,
                     DriveInfo *hd0, DriveInfo *hd1);
 
-void ide_get_bs(BlockDriverState *bs[], BusState *qbus);
+int ide_get_geometry(BusState *bus, int unit,
+                     int16_t *cyls, int8_t *heads, int8_t *secs);
+int ide_get_bios_chs_trans(BusState *bus, int unit);
 
 /* ide/core.c */
 void ide_drive_get(DriveInfo **hd, int max_bus);
diff --git a/hw/ide/core.c b/hw/ide/core.c
index 28f04ad..7f5ad07 100644
--- a/hw/ide/core.c
+++ b/hw/ide/core.c
@@ -1934,7 +1934,7 @@ int ide_init_drive(IDEState *s, BlockDriverState *bs, IDEDriveKind kind,
     s->drive_kind = kind;
 
     bdrv_get_geometry(bs, &nb_sectors);
-    hd_geometry_guess(bs, &cylinders, &heads, &secs, NULL);
+    hd_geometry_guess(bs, &cylinders, &heads, &secs, &s->chs_trans);
     if (cylinders < 1 || cylinders > 16383) {
         error_report("cyls must be between 1 and 16383");
         return -1;
diff --git a/hw/ide/internal.h b/hw/ide/internal.h
index 1a02f57..56c718e 100644
--- a/hw/ide/internal.h
+++ b/hw/ide/internal.h
@@ -344,7 +344,7 @@ struct IDEState {
     uint8_t unit;
     /* ide config */
     IDEDriveKind drive_kind;
-    int cylinders, heads, sectors;
+    int cylinders, heads, sectors, chs_trans;
     int64_t nb_sectors;
     int mult_sectors;
     int identify_set;
diff --git a/hw/ide/qdev.c b/hw/ide/qdev.c
index c122395..87e0b75 100644
--- a/hw/ide/qdev.c
+++ b/hw/ide/qdev.c
@@ -111,11 +111,24 @@ IDEDevice *ide_create_drive(IDEBus *bus, int unit, DriveInfo *drive)
     return DO_UPCAST(IDEDevice, qdev, dev);
 }
 
-void ide_get_bs(BlockDriverState *bs[], BusState *qbus)
+int ide_get_geometry(BusState *bus, int unit,
+                     int16_t *cyls, int8_t *heads, int8_t *secs)
 {
-    IDEBus *bus = DO_UPCAST(IDEBus, qbus, qbus);
-    bs[0] = bus->master ? bus->master->conf.bs : NULL;
-    bs[1] = bus->slave  ? bus->slave->conf.bs  : NULL;
+    IDEState *s = &DO_UPCAST(IDEBus, qbus, bus)->ifs[unit];
+
+    if (!s->bs) {
+        return -1;
+    }
+
+    *cyls = s->cylinders;
+    *heads = s->heads;
+    *secs = s->sectors;
+    return 0;
+}
+
+int ide_get_bios_chs_trans(BusState *bus, int unit)
+{
+    return DO_UPCAST(IDEBus, qbus, bus)->ifs[unit].chs_trans;
 }
 
 /* --------------------------------- */
diff --git a/hw/pc.c b/hw/pc.c
index 91cf77d..89a0c66 100644
--- a/hw/pc.c
+++ b/hw/pc.c
@@ -216,11 +216,9 @@ static int cmos_get_fd_drive_type(FDriveType fd0)
     return val;
 }
 
-static void cmos_init_hd(int type_ofs, int info_ofs, BlockDriverState *hd,
-                         ISADevice *s)
+static void cmos_init_hd(ISADevice *s, int type_ofs, int info_ofs,
+                         int16_t cylinders, int8_t heads, int8_t sectors)
 {
-    int cylinders, heads, sectors;
-    bdrv_get_geometry_hint(hd, &cylinders, &heads, &sectors);
     rtc_set_memory(s, type_ofs, 47);
     rtc_set_memory(s, info_ofs, cylinders);
     rtc_set_memory(s, info_ofs + 1, cylinders >> 8);
@@ -281,37 +279,42 @@ static int pc_boot_set(void *opaque, const char *boot_device)
 
 typedef struct pc_cmos_init_late_arg {
     ISADevice *rtc_state;
-    BusState *idebus0, *idebus1;
+    BusState *idebus[2];
 } pc_cmos_init_late_arg;
 
 static void pc_cmos_init_late(void *opaque)
 {
     pc_cmos_init_late_arg *arg = opaque;
     ISADevice *s = arg->rtc_state;
+    int16_t cylinders;
+    int8_t heads, sectors;
     int val;
-    BlockDriverState *hd_table[4];
     int i;
 
-    ide_get_bs(hd_table, arg->idebus0);
-    ide_get_bs(hd_table + 2, arg->idebus1);
-
-    rtc_set_memory(s, 0x12, (hd_table[0] ? 0xf0 : 0) | (hd_table[1] ? 0x0f : 0));
-    if (hd_table[0])
-        cmos_init_hd(0x19, 0x1b, hd_table[0], s);
-    if (hd_table[1])
-        cmos_init_hd(0x1a, 0x24, hd_table[1], s);
+    val = 0;
+    if (ide_get_geometry(arg->idebus[0], 0,
+                         &cylinders, &heads, &sectors) >= 0) {
+        cmos_init_hd(s, 0x19, 0x1b, cylinders, heads, sectors);
+        val |= 0xf0;
+    }
+    if (ide_get_geometry(arg->idebus[0], 1,
+                         &cylinders, &heads, &sectors) >= 0) {
+        cmos_init_hd(s, 0x1a, 0x24, cylinders, heads, sectors);
+        val |= 0x0f;
+    }
+    rtc_set_memory(s, 0x12, val);
 
     val = 0;
     for (i = 0; i < 4; i++) {
-        if (hd_table[i]) {
-            int cylinders, heads, sectors, translation;
-            /* NOTE: bdrv_get_geometry_hint() returns the physical
-                geometry.  It is always such that: 1 <= sects <= 63, 1
-                <= heads <= 16, 1 <= cylinders <= 16383. The BIOS
-                geometry can be different if a translation is done. */
-            translation = bdrv_get_translation_hint(hd_table[i]);
+        /* NOTE: ide_get_geometry() returns the physical
+           geometry.  It is always such that: 1 <= sects <= 63, 1
+           <= heads <= 16, 1 <= cylinders <= 16383. The BIOS
+           geometry can be different if a translation is done. */
+        if (ide_get_geometry(arg->idebus[i / 2], i % 2,
+                             &cylinders, &heads, &sectors) >= 0) {
+            int translation = ide_get_bios_chs_trans(arg->idebus[i / 2],
+                                                     i % 2);
             if (translation == BIOS_ATA_TRANSLATION_AUTO) {
-                bdrv_get_geometry_hint(hd_table[i], &cylinders, &heads, &sectors);
                 if (cylinders <= 1024 && heads <= 16 && sectors <= 63) {
                     /* No translation. */
                     translation = 0;
@@ -411,8 +414,8 @@ void pc_cmos_init(ram_addr_t ram_size, ram_addr_t above_4g_mem_size,
 
     /* hard drives */
     arg.rtc_state = s;
-    arg.idebus0 = idebus0;
-    arg.idebus1 = idebus1;
+    arg.idebus[0] = idebus0;
+    arg.idebus[1] = idebus1;
     qemu_register_reset(pc_cmos_init_late, &arg);
 }
 
commit e2f3dc2b6a205cf969ba5d1307293db17fd9621f
Author: Markus Armbruster <armbru at redhat.com>
Date:   Tue Jul 10 11:12:37 2012 +0200

    hd-geometry: Cut out block layer translation middleman
    
    hd_geometry_guess() picks geometry and translation.  Callers can get
    the geometry directly, via parameters, but for translation they need
    to go through the block layer.
    
    Add a parameter for translation, so it can optionally be gotten just
    like geometry.  In preparation of purging translation from the block
    layer, which will happen later in this series.
    
    Signed-off-by: Markus Armbruster <armbru at redhat.com>
    Signed-off-by: Kevin Wolf <kwolf at redhat.com>

diff --git a/hw/block-common.h b/hw/block-common.h
index 3a4d4c6..bba817a 100644
--- a/hw/block-common.h
+++ b/hw/block-common.h
@@ -16,6 +16,7 @@
 /* Hard disk geometry */
 
 void hd_geometry_guess(BlockDriverState *bs,
-                       int *pcyls, int *pheads, int *psecs);
+                       int *pcyls, int *pheads, int *psecs,
+                       int *ptrans);
 
 #endif
diff --git a/hw/hd-geometry.c b/hw/hd-geometry.c
index 241aed9..4d746b7 100644
--- a/hw/hd-geometry.c
+++ b/hw/hd-geometry.c
@@ -117,7 +117,8 @@ static void guess_chs_for_size(BlockDriverState *bs,
 }
 
 void hd_geometry_guess(BlockDriverState *bs,
-                       int *pcyls, int *pheads, int *psecs)
+                       int *pcyls, int *pheads, int *psecs,
+                       int *ptrans)
 {
     int cylinders, heads, secs, translation;
 
@@ -129,6 +130,9 @@ void hd_geometry_guess(BlockDriverState *bs,
         *pcyls = cylinders;
         *pheads = heads;
         *psecs = secs;
+        if (ptrans) {
+            *ptrans = translation;
+        }
         return;
     }
 
@@ -142,10 +146,10 @@ void hd_geometry_guess(BlockDriverState *bs,
            translation was active, so a standard physical disk
            geometry is OK */
         guess_chs_for_size(bs, pcyls, pheads, psecs);
-        bdrv_set_translation_hint(bs,
-                                  *pcyls * *pheads <= 131072
-                                  ? BIOS_ATA_TRANSLATION_LARGE
-                                  : BIOS_ATA_TRANSLATION_LBA);
+        translation = *pcyls * *pheads <= 131072
+            ? BIOS_ATA_TRANSLATION_LARGE
+            : BIOS_ATA_TRANSLATION_LBA;
+        bdrv_set_translation_hint(bs, translation);
     } else {
         /* LCHS guess with heads <= 16: use as physical geometry */
         *pcyls = cylinders;
@@ -153,7 +157,11 @@ void hd_geometry_guess(BlockDriverState *bs,
         *psecs = secs;
         /* disable any translation to be in sync with
            the logical geometry */
-        bdrv_set_translation_hint(bs, BIOS_ATA_TRANSLATION_NONE);
+        translation = BIOS_ATA_TRANSLATION_NONE;
+        bdrv_set_translation_hint(bs, translation);
+    }
+    if (ptrans) {
+        *ptrans = translation;
     }
     bdrv_set_geometry_hint(bs, *pcyls, *pheads, *psecs);
     trace_hd_geometry_guess(bs, *pcyls, *pheads, *psecs, translation);
diff --git a/hw/ide/core.c b/hw/ide/core.c
index 0d1bf10..28f04ad 100644
--- a/hw/ide/core.c
+++ b/hw/ide/core.c
@@ -1934,7 +1934,7 @@ int ide_init_drive(IDEState *s, BlockDriverState *bs, IDEDriveKind kind,
     s->drive_kind = kind;
 
     bdrv_get_geometry(bs, &nb_sectors);
-    hd_geometry_guess(bs, &cylinders, &heads, &secs);
+    hd_geometry_guess(bs, &cylinders, &heads, &secs, NULL);
     if (cylinders < 1 || cylinders > 16383) {
         error_report("cyls must be between 1 and 16383");
         return -1;
diff --git a/hw/scsi-disk.c b/hw/scsi-disk.c
index 5339c2e..fc077f5 100644
--- a/hw/scsi-disk.c
+++ b/hw/scsi-disk.c
@@ -990,7 +990,7 @@ static int mode_sense_page(SCSIDiskState *s, int page, uint8_t **p_outbuf,
             break;
         }
         /* if a geometry hint is available, use it */
-        hd_geometry_guess(bdrv, &cylinders, &heads, &secs);
+        hd_geometry_guess(bdrv, &cylinders, &heads, &secs, NULL);
         p[2] = (cylinders >> 16) & 0xff;
         p[3] = (cylinders >> 8) & 0xff;
         p[4] = cylinders & 0xff;
@@ -1024,7 +1024,7 @@ static int mode_sense_page(SCSIDiskState *s, int page, uint8_t **p_outbuf,
         p[2] = 5000 >> 8;
         p[3] = 5000 & 0xff;
         /* if a geometry hint is available, use it */
-        hd_geometry_guess(bdrv, &cylinders, &heads, &secs);
+        hd_geometry_guess(bdrv, &cylinders, &heads, &secs, NULL);
         p[4] = heads & 0xff;
         p[5] = secs & 0xff;
         p[6] = s->qdev.blocksize >> 8;
diff --git a/hw/virtio-blk.c b/hw/virtio-blk.c
index f16c5ce..d2709a7 100644
--- a/hw/virtio-blk.c
+++ b/hw/virtio-blk.c
@@ -623,7 +623,7 @@ VirtIODevice *virtio_blk_init(DeviceState *dev, VirtIOBlkConf *blk)
     s->blk = blk;
     s->rq = NULL;
     s->sector_mask = (s->conf->logical_block_size / BDRV_SECTOR_SIZE) - 1;
-    hd_geometry_guess(s->bs, &cylinders, &heads, &secs);
+    hd_geometry_guess(s->bs, &cylinders, &heads, &secs, NULL);
 
     s->vq = virtio_add_queue(&s->vdev, 128, virtio_blk_handle_output);
 
commit dc28c0cd30d7b122500b17eedc7e070624fd7c86
Author: Markus Armbruster <armbru at redhat.com>
Date:   Tue Jul 10 11:12:36 2012 +0200

    hd-geometry: Clean up confusing use of prior translation hint
    
    When hd_geometry_guess() picks a geometry, it also picks the
    appropriate translation, but only when the prior translation hint is
    BIOS_ATA_TRANSLATION_AUTO.  Looks wrong, because such a prior
    translation would be passed to the BIOS whether it's suitable for the
    geometry or not.
    
    Fortunately, that can't happen.  There are just two ways for the
    translation hint to get set to something other than
    BIOS_ATA_TRANSLATION_AUTO: drive_init() on behalf of -drive trans=...,
    and hd_geometry_guess().  Both set it only when they also set a valid
    geometry hint, i.e. one with a non-zero number of cylinders.
    
    Since hd_geometry_guess() returns right away when it finds a valid
    geometry hint, translation can only be BIOS_ATA_TRANSLATION_AUTO in
    the remainder of the function.
    
    Assert this, and simplify accordingly.
    
    Signed-off-by: Markus Armbruster <armbru at redhat.com>
    Signed-off-by: Kevin Wolf <kwolf at redhat.com>

diff --git a/hw/hd-geometry.c b/hw/hd-geometry.c
index fb849a3..241aed9 100644
--- a/hw/hd-geometry.c
+++ b/hw/hd-geometry.c
@@ -132,6 +132,8 @@ void hd_geometry_guess(BlockDriverState *bs,
         return;
     }
 
+    assert(translation == BIOS_ATA_TRANSLATION_AUTO);
+
     if (guess_disk_lchs(bs, &cylinders, &heads, &secs) < 0) {
         /* no LCHS guess: use a standard physical disk geometry  */
         guess_chs_for_size(bs, pcyls, pheads, psecs);
@@ -140,12 +142,10 @@ void hd_geometry_guess(BlockDriverState *bs,
            translation was active, so a standard physical disk
            geometry is OK */
         guess_chs_for_size(bs, pcyls, pheads, psecs);
-        if (translation == BIOS_ATA_TRANSLATION_AUTO) {
-            bdrv_set_translation_hint(bs,
-                                      *pcyls * *pheads <= 131072
-                                      ? BIOS_ATA_TRANSLATION_LARGE
-                                      : BIOS_ATA_TRANSLATION_LBA);
-        }
+        bdrv_set_translation_hint(bs,
+                                  *pcyls * *pheads <= 131072
+                                  ? BIOS_ATA_TRANSLATION_LARGE
+                                  : BIOS_ATA_TRANSLATION_LBA);
     } else {
         /* LCHS guess with heads <= 16: use as physical geometry */
         *pcyls = cylinders;
@@ -153,10 +153,7 @@ void hd_geometry_guess(BlockDriverState *bs,
         *psecs = secs;
         /* disable any translation to be in sync with
            the logical geometry */
-        if (translation == BIOS_ATA_TRANSLATION_AUTO) {
-            bdrv_set_translation_hint(bs,
-                                      BIOS_ATA_TRANSLATION_NONE);
-        }
+        bdrv_set_translation_hint(bs, BIOS_ATA_TRANSLATION_NONE);
     }
     bdrv_set_geometry_hint(bs, *pcyls, *pheads, *psecs);
     trace_hd_geometry_guess(bs, *pcyls, *pheads, *psecs, translation);
commit 82b11662be5b6e462ae843363b316779a9c88a61
Author: Markus Armbruster <armbru at redhat.com>
Date:   Tue Jul 10 11:12:35 2012 +0200

    hd-geometry: Clean up gratuitous goto in hd_geometry_guess()
    
    Signed-off-by: Markus Armbruster <armbru at redhat.com>
    Signed-off-by: Kevin Wolf <kwolf at redhat.com>

diff --git a/hw/hd-geometry.c b/hw/hd-geometry.c
index 1a58894..fb849a3 100644
--- a/hw/hd-geometry.c
+++ b/hw/hd-geometry.c
@@ -119,8 +119,7 @@ static void guess_chs_for_size(BlockDriverState *bs,
 void hd_geometry_guess(BlockDriverState *bs,
                        int *pcyls, int *pheads, int *psecs)
 {
-    int translation, lba_detected = 0;
-    int cylinders, heads, secs;
+    int cylinders, heads, secs, translation;
 
     bdrv_get_geometry_hint(bs, &cylinders, &heads, &secs);
     translation = bdrv_get_translation_hint(bs);
@@ -135,23 +134,18 @@ void hd_geometry_guess(BlockDriverState *bs,
 
     if (guess_disk_lchs(bs, &cylinders, &heads, &secs) < 0) {
         /* no LCHS guess: use a standard physical disk geometry  */
-    default_geometry:
         guess_chs_for_size(bs, pcyls, pheads, psecs);
-        if ((lba_detected == 1) && (translation == BIOS_ATA_TRANSLATION_AUTO)) {
-            if ((*pcyls * *pheads) <= 131072) {
-                bdrv_set_translation_hint(bs,
-                                          BIOS_ATA_TRANSLATION_LARGE);
-            } else {
-                bdrv_set_translation_hint(bs,
-                                          BIOS_ATA_TRANSLATION_LBA);
-            }
-        }
     } else if (heads > 16) {
         /* LCHS guess with heads > 16 means that a BIOS LBA
            translation was active, so a standard physical disk
            geometry is OK */
-        lba_detected = 1;
-        goto default_geometry;
+        guess_chs_for_size(bs, pcyls, pheads, psecs);
+        if (translation == BIOS_ATA_TRANSLATION_AUTO) {
+            bdrv_set_translation_hint(bs,
+                                      *pcyls * *pheads <= 131072
+                                      ? BIOS_ATA_TRANSLATION_LARGE
+                                      : BIOS_ATA_TRANSLATION_LBA);
+        }
     } else {
         /* LCHS guess with heads <= 16: use as physical geometry */
         *pcyls = cylinders;
commit 2fa5008ffd49e51540756adccf966a2fcde6e6c1
Author: Markus Armbruster <armbru at redhat.com>
Date:   Tue Jul 10 11:12:34 2012 +0200

    hd-geometry: Factor out guess_chs_for_size()
    
    Signed-off-by: Markus Armbruster <armbru at redhat.com>
    Signed-off-by: Kevin Wolf <kwolf at redhat.com>

diff --git a/hw/hd-geometry.c b/hw/hd-geometry.c
index db47846..1a58894 100644
--- a/hw/hd-geometry.c
+++ b/hw/hd-geometry.c
@@ -97,14 +97,31 @@ static int guess_disk_lchs(BlockDriverState *bs,
     return -1;
 }
 
+static void guess_chs_for_size(BlockDriverState *bs,
+                               int *pcyls, int *pheads, int *psecs)
+{
+    uint64_t nb_sectors;
+    int cylinders;
+
+    bdrv_get_geometry(bs, &nb_sectors);
+
+    cylinders = nb_sectors / (16 * 63);
+    if (cylinders > 16383) {
+        cylinders = 16383;
+    } else if (cylinders < 2) {
+        cylinders = 2;
+    }
+    *pcyls = cylinders;
+    *pheads = 16;
+    *psecs = 63;
+}
+
 void hd_geometry_guess(BlockDriverState *bs,
                        int *pcyls, int *pheads, int *psecs)
 {
     int translation, lba_detected = 0;
     int cylinders, heads, secs;
-    uint64_t nb_sectors;
 
-    bdrv_get_geometry(bs, &nb_sectors);
     bdrv_get_geometry_hint(bs, &cylinders, &heads, &secs);
     translation = bdrv_get_translation_hint(bs);
 
@@ -119,16 +136,7 @@ void hd_geometry_guess(BlockDriverState *bs,
     if (guess_disk_lchs(bs, &cylinders, &heads, &secs) < 0) {
         /* no LCHS guess: use a standard physical disk geometry  */
     default_geometry:
-        cylinders = nb_sectors / (16 * 63);
-
-        if (cylinders > 16383) {
-            cylinders = 16383;
-        } else if (cylinders < 2) {
-            cylinders = 2;
-        }
-        *pcyls = cylinders;
-        *pheads = 16;
-        *psecs = 63;
+        guess_chs_for_size(bs, pcyls, pheads, psecs);
         if ((lba_detected == 1) && (translation == BIOS_ATA_TRANSLATION_AUTO)) {
             if ((*pcyls * *pheads) <= 131072) {
                 bdrv_set_translation_hint(bs,
commit c06aaf018b1a39b62c1f6867794807dd5705b355
Author: Markus Armbruster <armbru at redhat.com>
Date:   Tue Jul 10 11:12:33 2012 +0200

    hd-geometry: Unnest conditional in hd_geometry_guess()
    
    Signed-off-by: Markus Armbruster <armbru at redhat.com>
    Signed-off-by: Kevin Wolf <kwolf at redhat.com>

diff --git a/hw/hd-geometry.c b/hw/hd-geometry.c
index f0dd021..db47846 100644
--- a/hw/hd-geometry.c
+++ b/hw/hd-geometry.c
@@ -104,58 +104,58 @@ void hd_geometry_guess(BlockDriverState *bs,
     int cylinders, heads, secs;
     uint64_t nb_sectors;
 
-    /* if a geometry hint is available, use it */
     bdrv_get_geometry(bs, &nb_sectors);
     bdrv_get_geometry_hint(bs, &cylinders, &heads, &secs);
     translation = bdrv_get_translation_hint(bs);
+
     if (cylinders != 0) {
+        /* already got a geometry hint: use it */
         *pcyls = cylinders;
         *pheads = heads;
         *psecs = secs;
-    } else {
-        if (guess_disk_lchs(bs, &cylinders, &heads, &secs) == 0) {
-            if (heads > 16) {
-                /* if heads > 16, it means that a BIOS LBA
-                   translation was active, so the default
-                   hardware geometry is OK */
-                lba_detected = 1;
-                goto default_geometry;
-            } else {
-                *pcyls = cylinders;
-                *pheads = heads;
-                *psecs = secs;
-                /* disable any translation to be in sync with
-                   the logical geometry */
-                if (translation == BIOS_ATA_TRANSLATION_AUTO) {
-                    bdrv_set_translation_hint(bs,
-                                              BIOS_ATA_TRANSLATION_NONE);
-                }
-            }
-        } else {
-        default_geometry:
-            /* if no geometry, use a standard physical disk geometry */
-            cylinders = nb_sectors / (16 * 63);
+        return;
+    }
 
-            if (cylinders > 16383) {
-                cylinders = 16383;
-            } else if (cylinders < 2) {
-                cylinders = 2;
-            }
-            *pcyls = cylinders;
-            *pheads = 16;
-            *psecs = 63;
-            if ((lba_detected == 1)
-                && (translation == BIOS_ATA_TRANSLATION_AUTO)) {
-                if ((*pcyls * *pheads) <= 131072) {
-                    bdrv_set_translation_hint(bs,
-                                              BIOS_ATA_TRANSLATION_LARGE);
-                } else {
-                    bdrv_set_translation_hint(bs,
-                                              BIOS_ATA_TRANSLATION_LBA);
-                }
+    if (guess_disk_lchs(bs, &cylinders, &heads, &secs) < 0) {
+        /* no LCHS guess: use a standard physical disk geometry  */
+    default_geometry:
+        cylinders = nb_sectors / (16 * 63);
+
+        if (cylinders > 16383) {
+            cylinders = 16383;
+        } else if (cylinders < 2) {
+            cylinders = 2;
+        }
+        *pcyls = cylinders;
+        *pheads = 16;
+        *psecs = 63;
+        if ((lba_detected == 1) && (translation == BIOS_ATA_TRANSLATION_AUTO)) {
+            if ((*pcyls * *pheads) <= 131072) {
+                bdrv_set_translation_hint(bs,
+                                          BIOS_ATA_TRANSLATION_LARGE);
+            } else {
+                bdrv_set_translation_hint(bs,
+                                          BIOS_ATA_TRANSLATION_LBA);
             }
         }
-        bdrv_set_geometry_hint(bs, *pcyls, *pheads, *psecs);
+    } else if (heads > 16) {
+        /* LCHS guess with heads > 16 means that a BIOS LBA
+           translation was active, so a standard physical disk
+           geometry is OK */
+        lba_detected = 1;
+        goto default_geometry;
+    } else {
+        /* LCHS guess with heads <= 16: use as physical geometry */
+        *pcyls = cylinders;
+        *pheads = heads;
+        *psecs = secs;
+        /* disable any translation to be in sync with
+           the logical geometry */
+        if (translation == BIOS_ATA_TRANSLATION_AUTO) {
+            bdrv_set_translation_hint(bs,
+                                      BIOS_ATA_TRANSLATION_NONE);
+        }
     }
+    bdrv_set_geometry_hint(bs, *pcyls, *pheads, *psecs);
     trace_hd_geometry_guess(bs, *pcyls, *pheads, *psecs, translation);
 }
commit 31f7eedfa6e7e8f4c4760930cbe82bf969e73fa7
Author: Markus Armbruster <armbru at redhat.com>
Date:   Tue Jul 10 11:12:32 2012 +0200

    hd-geometry: Add tracepoints
    
    Signed-off-by: Markus Armbruster <armbru at redhat.com>
    Signed-off-by: Kevin Wolf <kwolf at redhat.com>

diff --git a/hw/hd-geometry.c b/hw/hd-geometry.c
index c45eafd..f0dd021 100644
--- a/hw/hd-geometry.c
+++ b/hw/hd-geometry.c
@@ -32,6 +32,7 @@
 
 #include "block.h"
 #include "hw/block-common.h"
+#include "trace.h"
 
 struct partition {
         uint8_t boot_ind;           /* 0x80 - active */
@@ -89,10 +90,7 @@ static int guess_disk_lchs(BlockDriverState *bs,
             *pheads = heads;
             *psectors = sectors;
             *pcylinders = cylinders;
-#if 0
-            printf("guessed geometry: LCHS=%d %d %d\n",
-                   cylinders, heads, sectors);
-#endif
+            trace_hd_geometry_lchs_guess(bs, cylinders, heads, sectors);
             return 0;
         }
     }
@@ -159,4 +157,5 @@ void hd_geometry_guess(BlockDriverState *bs,
         }
         bdrv_set_geometry_hint(bs, *pcyls, *pheads, *psecs);
     }
+    trace_hd_geometry_guess(bs, *pcyls, *pheads, *psecs, translation);
 }
diff --git a/trace-events b/trace-events
index fc32bc6..5f27f1a 100644
--- a/trace-events
+++ b/trace-events
@@ -141,6 +141,10 @@ ecc_mem_readl_ecr1(uint32_t ret) "Read event count 2 %08x"
 ecc_diag_mem_writeb(uint64_t addr, uint32_t val) "Write diagnostic %"PRId64" = %02x"
 ecc_diag_mem_readb(uint64_t addr, uint32_t ret) "Read diagnostic %"PRId64"= %02x"
 
+# hw/hd-geometry.c
+hd_geometry_lchs_guess(void *bs, int cyls, int heads, int secs) "bs %p LCHS %d %d %d"
+hd_geometry_guess(void *bs, int cyls, int heads, int secs, int trans) "bs %p CHS %d %d %d trans %d"
+
 # hw/jazz-led.c
 jazz_led_read(uint64_t addr, uint8_t val) "read addr=0x%"PRIx64": 0x%x"
 jazz_led_write(uint64_t addr, uint8_t new) "write addr=0x%"PRIx64": 0x%x"
commit 9db1c0f7a94c6382e2b3e1365566a9a8b8ae74c1
Author: Markus Armbruster <armbru at redhat.com>
Date:   Tue Jul 10 11:12:31 2012 +0200

    hd-geometry: Move disk geometry guessing back from block.c
    
    Commit f3d54fc4 factored it out of hw/ide.c for reuse.  Sensible,
    except it was put into block.c.  Device-specific functionality should
    be kept in device code, not the block layer.  Move it to
    hw/hd-geometry.c, and make stylistic changes required to keep
    checkpatch.pl happy.
    
    Signed-off-by: Markus Armbruster <armbru at redhat.com>
    Signed-off-by: Kevin Wolf <kwolf at redhat.com>

diff --git a/block.c b/block.c
index ffda1c2..06323cf 100644
--- a/block.c
+++ b/block.c
@@ -2132,127 +2132,6 @@ void bdrv_get_geometry(BlockDriverState *bs, uint64_t *nb_sectors_ptr)
     *nb_sectors_ptr = length;
 }
 
-struct partition {
-        uint8_t boot_ind;           /* 0x80 - active */
-        uint8_t head;               /* starting head */
-        uint8_t sector;             /* starting sector */
-        uint8_t cyl;                /* starting cylinder */
-        uint8_t sys_ind;            /* What partition type */
-        uint8_t end_head;           /* end head */
-        uint8_t end_sector;         /* end sector */
-        uint8_t end_cyl;            /* end cylinder */
-        uint32_t start_sect;        /* starting sector counting from 0 */
-        uint32_t nr_sects;          /* nr of sectors in partition */
-} QEMU_PACKED;
-
-/* try to guess the disk logical geometry from the MSDOS partition table. Return 0 if OK, -1 if could not guess */
-static int guess_disk_lchs(BlockDriverState *bs,
-                           int *pcylinders, int *pheads, int *psectors)
-{
-    uint8_t buf[BDRV_SECTOR_SIZE];
-    int i, heads, sectors, cylinders;
-    struct partition *p;
-    uint32_t nr_sects;
-    uint64_t nb_sectors;
-
-    bdrv_get_geometry(bs, &nb_sectors);
-
-    /**
-     * The function will be invoked during startup not only in sync I/O mode,
-     * but also in async I/O mode. So the I/O throttling function has to
-     * be disabled temporarily here, not permanently.
-     */
-    if (bdrv_read_unthrottled(bs, 0, buf, 1) < 0) {
-        return -1;
-    }
-    /* test msdos magic */
-    if (buf[510] != 0x55 || buf[511] != 0xaa)
-        return -1;
-    for(i = 0; i < 4; i++) {
-        p = ((struct partition *)(buf + 0x1be)) + i;
-        nr_sects = le32_to_cpu(p->nr_sects);
-        if (nr_sects && p->end_head) {
-            /* We make the assumption that the partition terminates on
-               a cylinder boundary */
-            heads = p->end_head + 1;
-            sectors = p->end_sector & 63;
-            if (sectors == 0)
-                continue;
-            cylinders = nb_sectors / (heads * sectors);
-            if (cylinders < 1 || cylinders > 16383)
-                continue;
-            *pheads = heads;
-            *psectors = sectors;
-            *pcylinders = cylinders;
-#if 0
-            printf("guessed geometry: LCHS=%d %d %d\n",
-                   cylinders, heads, sectors);
-#endif
-            return 0;
-        }
-    }
-    return -1;
-}
-
-void bdrv_guess_geometry(BlockDriverState *bs, int *pcyls, int *pheads, int *psecs)
-{
-    int translation, lba_detected = 0;
-    int cylinders, heads, secs;
-    uint64_t nb_sectors;
-
-    /* if a geometry hint is available, use it */
-    bdrv_get_geometry(bs, &nb_sectors);
-    bdrv_get_geometry_hint(bs, &cylinders, &heads, &secs);
-    translation = bdrv_get_translation_hint(bs);
-    if (cylinders != 0) {
-        *pcyls = cylinders;
-        *pheads = heads;
-        *psecs = secs;
-    } else {
-        if (guess_disk_lchs(bs, &cylinders, &heads, &secs) == 0) {
-            if (heads > 16) {
-                /* if heads > 16, it means that a BIOS LBA
-                   translation was active, so the default
-                   hardware geometry is OK */
-                lba_detected = 1;
-                goto default_geometry;
-            } else {
-                *pcyls = cylinders;
-                *pheads = heads;
-                *psecs = secs;
-                /* disable any translation to be in sync with
-                   the logical geometry */
-                if (translation == BIOS_ATA_TRANSLATION_AUTO) {
-                    bdrv_set_translation_hint(bs,
-                                              BIOS_ATA_TRANSLATION_NONE);
-                }
-            }
-        } else {
-        default_geometry:
-            /* if no geometry, use a standard physical disk geometry */
-            cylinders = nb_sectors / (16 * 63);
-
-            if (cylinders > 16383)
-                cylinders = 16383;
-            else if (cylinders < 2)
-                cylinders = 2;
-            *pcyls = cylinders;
-            *pheads = 16;
-            *psecs = 63;
-            if ((lba_detected == 1) && (translation == BIOS_ATA_TRANSLATION_AUTO)) {
-                if ((*pcyls * *pheads) <= 131072) {
-                    bdrv_set_translation_hint(bs,
-                                              BIOS_ATA_TRANSLATION_LARGE);
-                } else {
-                    bdrv_set_translation_hint(bs,
-                                              BIOS_ATA_TRANSLATION_LBA);
-                }
-            }
-        }
-        bdrv_set_geometry_hint(bs, *pcyls, *pheads, *psecs);
-    }
-}
-
 void bdrv_set_geometry_hint(BlockDriverState *bs,
                             int cyls, int heads, int secs)
 {
diff --git a/block.h b/block.h
index b24f664..993894e 100644
--- a/block.h
+++ b/block.h
@@ -178,7 +178,6 @@ int bdrv_truncate(BlockDriverState *bs, int64_t offset);
 int64_t bdrv_getlength(BlockDriverState *bs);
 int64_t bdrv_get_allocated_file_size(BlockDriverState *bs);
 void bdrv_get_geometry(BlockDriverState *bs, uint64_t *nb_sectors_ptr);
-void bdrv_guess_geometry(BlockDriverState *bs, int *pcyls, int *pheads, int *psecs);
 int bdrv_commit(BlockDriverState *bs);
 int bdrv_commit_all(void);
 int bdrv_change_backing_file(BlockDriverState *bs,
diff --git a/hw/Makefile.objs b/hw/Makefile.objs
index 9a350de..c3bdedc 100644
--- a/hw/Makefile.objs
+++ b/hw/Makefile.objs
@@ -138,7 +138,7 @@ common-obj-$(CONFIG_MAX111X) += max111x.o
 common-obj-$(CONFIG_DS1338) += ds1338.o
 common-obj-y += i2c.o smbus.o smbus_eeprom.o
 common-obj-y += eeprom93xx.o
-common-obj-y += scsi-disk.o cdrom.o
+common-obj-y += scsi-disk.o cdrom.o hd-geometry.o
 common-obj-y += scsi-generic.o scsi-bus.o
 common-obj-y += hid.o
 common-obj-$(CONFIG_SSI) += ssi.o
diff --git a/hw/block-common.h b/hw/block-common.h
new file mode 100644
index 0000000..3a4d4c6
--- /dev/null
+++ b/hw/block-common.h
@@ -0,0 +1,21 @@
+/*
+ * Common code for block device models
+ *
+ * Copyright (C) 2012 Red Hat, Inc.
+ * Copyright (c) 2003-2008 Fabrice Bellard
+ *
+ * This work is licensed under the terms of the GNU GPL, version 2 or
+ * later.  See the COPYING file in the top-level directory.
+ */
+
+#ifndef HW_BLOCK_COMMON_H
+#define HW_BLOCK_COMMON_H
+
+#include "qemu-common.h"
+
+/* Hard disk geometry */
+
+void hd_geometry_guess(BlockDriverState *bs,
+                       int *pcyls, int *pheads, int *psecs);
+
+#endif
diff --git a/hw/hd-geometry.c b/hw/hd-geometry.c
new file mode 100644
index 0000000..c45eafd
--- /dev/null
+++ b/hw/hd-geometry.c
@@ -0,0 +1,162 @@
+/*
+ * Hard disk geometry utilities
+ *
+ * Copyright (C) 2012 Red Hat, Inc.
+ *
+ * This work is licensed under the terms of the GNU GPL, version 2 or later.
+ * See the COPYING file in the top-level directory.
+ *
+ * This file incorporates work covered by the following copyright and
+ * permission notice:
+ *
+ * Copyright (c) 2003 Fabrice Bellard
+ *
+ * Permission is hereby granted, free of charge, to any person obtaining a copy
+ * of this software and associated documentation files (the "Software"), to deal
+ * in the Software without restriction, including without limitation the rights
+ * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+ * copies of the Software, and to permit persons to whom the Software is
+ * furnished to do so, subject to the following conditions:
+ *
+ * The above copyright notice and this permission notice shall be included in
+ * all copies or substantial portions of the Software.
+ *
+ * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+ * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+ * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
+ * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+ * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
+ * THE SOFTWARE.
+ */
+
+#include "block.h"
+#include "hw/block-common.h"
+
+struct partition {
+        uint8_t boot_ind;           /* 0x80 - active */
+        uint8_t head;               /* starting head */
+        uint8_t sector;             /* starting sector */
+        uint8_t cyl;                /* starting cylinder */
+        uint8_t sys_ind;            /* What partition type */
+        uint8_t end_head;           /* end head */
+        uint8_t end_sector;         /* end sector */
+        uint8_t end_cyl;            /* end cylinder */
+        uint32_t start_sect;        /* starting sector counting from 0 */
+        uint32_t nr_sects;          /* nr of sectors in partition */
+} QEMU_PACKED;
+
+/* try to guess the disk logical geometry from the MSDOS partition table.
+   Return 0 if OK, -1 if could not guess */
+static int guess_disk_lchs(BlockDriverState *bs,
+                           int *pcylinders, int *pheads, int *psectors)
+{
+    uint8_t buf[BDRV_SECTOR_SIZE];
+    int i, heads, sectors, cylinders;
+    struct partition *p;
+    uint32_t nr_sects;
+    uint64_t nb_sectors;
+
+    bdrv_get_geometry(bs, &nb_sectors);
+
+    /**
+     * The function will be invoked during startup not only in sync I/O mode,
+     * but also in async I/O mode. So the I/O throttling function has to
+     * be disabled temporarily here, not permanently.
+     */
+    if (bdrv_read_unthrottled(bs, 0, buf, 1) < 0) {
+        return -1;
+    }
+    /* test msdos magic */
+    if (buf[510] != 0x55 || buf[511] != 0xaa) {
+        return -1;
+    }
+    for (i = 0; i < 4; i++) {
+        p = ((struct partition *)(buf + 0x1be)) + i;
+        nr_sects = le32_to_cpu(p->nr_sects);
+        if (nr_sects && p->end_head) {
+            /* We make the assumption that the partition terminates on
+               a cylinder boundary */
+            heads = p->end_head + 1;
+            sectors = p->end_sector & 63;
+            if (sectors == 0) {
+                continue;
+            }
+            cylinders = nb_sectors / (heads * sectors);
+            if (cylinders < 1 || cylinders > 16383) {
+                continue;
+            }
+            *pheads = heads;
+            *psectors = sectors;
+            *pcylinders = cylinders;
+#if 0
+            printf("guessed geometry: LCHS=%d %d %d\n",
+                   cylinders, heads, sectors);
+#endif
+            return 0;
+        }
+    }
+    return -1;
+}
+
+void hd_geometry_guess(BlockDriverState *bs,
+                       int *pcyls, int *pheads, int *psecs)
+{
+    int translation, lba_detected = 0;
+    int cylinders, heads, secs;
+    uint64_t nb_sectors;
+
+    /* if a geometry hint is available, use it */
+    bdrv_get_geometry(bs, &nb_sectors);
+    bdrv_get_geometry_hint(bs, &cylinders, &heads, &secs);
+    translation = bdrv_get_translation_hint(bs);
+    if (cylinders != 0) {
+        *pcyls = cylinders;
+        *pheads = heads;
+        *psecs = secs;
+    } else {
+        if (guess_disk_lchs(bs, &cylinders, &heads, &secs) == 0) {
+            if (heads > 16) {
+                /* if heads > 16, it means that a BIOS LBA
+                   translation was active, so the default
+                   hardware geometry is OK */
+                lba_detected = 1;
+                goto default_geometry;
+            } else {
+                *pcyls = cylinders;
+                *pheads = heads;
+                *psecs = secs;
+                /* disable any translation to be in sync with
+                   the logical geometry */
+                if (translation == BIOS_ATA_TRANSLATION_AUTO) {
+                    bdrv_set_translation_hint(bs,
+                                              BIOS_ATA_TRANSLATION_NONE);
+                }
+            }
+        } else {
+        default_geometry:
+            /* if no geometry, use a standard physical disk geometry */
+            cylinders = nb_sectors / (16 * 63);
+
+            if (cylinders > 16383) {
+                cylinders = 16383;
+            } else if (cylinders < 2) {
+                cylinders = 2;
+            }
+            *pcyls = cylinders;
+            *pheads = 16;
+            *psecs = 63;
+            if ((lba_detected == 1)
+                && (translation == BIOS_ATA_TRANSLATION_AUTO)) {
+                if ((*pcyls * *pheads) <= 131072) {
+                    bdrv_set_translation_hint(bs,
+                                              BIOS_ATA_TRANSLATION_LARGE);
+                } else {
+                    bdrv_set_translation_hint(bs,
+                                              BIOS_ATA_TRANSLATION_LBA);
+                }
+            }
+        }
+        bdrv_set_geometry_hint(bs, *pcyls, *pheads, *psecs);
+    }
+}
diff --git a/hw/ide/core.c b/hw/ide/core.c
index 71d4d77..0d1bf10 100644
--- a/hw/ide/core.c
+++ b/hw/ide/core.c
@@ -30,6 +30,7 @@
 #include "qemu-timer.h"
 #include "sysemu.h"
 #include "dma.h"
+#include "hw/block-common.h"
 #include "blockdev.h"
 
 #include <hw/ide/internal.h>
@@ -1933,7 +1934,7 @@ int ide_init_drive(IDEState *s, BlockDriverState *bs, IDEDriveKind kind,
     s->drive_kind = kind;
 
     bdrv_get_geometry(bs, &nb_sectors);
-    bdrv_guess_geometry(bs, &cylinders, &heads, &secs);
+    hd_geometry_guess(bs, &cylinders, &heads, &secs);
     if (cylinders < 1 || cylinders > 16383) {
         error_report("cyls must be between 1 and 16383");
         return -1;
diff --git a/hw/scsi-disk.c b/hw/scsi-disk.c
index 34336b1..5339c2e 100644
--- a/hw/scsi-disk.c
+++ b/hw/scsi-disk.c
@@ -34,6 +34,7 @@ do { printf("scsi-disk: " fmt , ## __VA_ARGS__); } while (0)
 #include "scsi-defs.h"
 #include "sysemu.h"
 #include "blockdev.h"
+#include "hw/block-common.h"
 #include "dma.h"
 
 #ifdef __linux
@@ -989,7 +990,7 @@ static int mode_sense_page(SCSIDiskState *s, int page, uint8_t **p_outbuf,
             break;
         }
         /* if a geometry hint is available, use it */
-        bdrv_guess_geometry(bdrv, &cylinders, &heads, &secs);
+        hd_geometry_guess(bdrv, &cylinders, &heads, &secs);
         p[2] = (cylinders >> 16) & 0xff;
         p[3] = (cylinders >> 8) & 0xff;
         p[4] = cylinders & 0xff;
@@ -1023,7 +1024,7 @@ static int mode_sense_page(SCSIDiskState *s, int page, uint8_t **p_outbuf,
         p[2] = 5000 >> 8;
         p[3] = 5000 & 0xff;
         /* if a geometry hint is available, use it */
-        bdrv_guess_geometry(bdrv, &cylinders, &heads, &secs);
+        hd_geometry_guess(bdrv, &cylinders, &heads, &secs);
         p[4] = heads & 0xff;
         p[5] = secs & 0xff;
         p[6] = s->qdev.blocksize >> 8;
diff --git a/hw/virtio-blk.c b/hw/virtio-blk.c
index fe07746..f16c5ce 100644
--- a/hw/virtio-blk.c
+++ b/hw/virtio-blk.c
@@ -14,6 +14,7 @@
 #include "qemu-common.h"
 #include "qemu-error.h"
 #include "trace.h"
+#include "hw/block-common.h"
 #include "blockdev.h"
 #include "virtio-blk.h"
 #include "scsi-defs.h"
@@ -622,7 +623,7 @@ VirtIODevice *virtio_blk_init(DeviceState *dev, VirtIOBlkConf *blk)
     s->blk = blk;
     s->rq = NULL;
     s->sector_mask = (s->conf->logical_block_size / BDRV_SECTOR_SIZE) - 1;
-    bdrv_guess_geometry(s->bs, &cylinders, &heads, &secs);
+    hd_geometry_guess(s->bs, &cylinders, &heads, &secs);
 
     s->vq = virtio_add_queue(&s->vdev, 128, virtio_blk_handle_output);
 
commit 0e8a8c8f6d988f3907d7cdba877a711a4d47ec5c
Author: Markus Armbruster <armbru at redhat.com>
Date:   Tue Jul 10 11:12:30 2012 +0200

    qtest: Add hard disk geometry test
    
    So far covers only IDE and tests only CMOS contents.
    
    Signed-off-by: Markus Armbruster <armbru at redhat.com>
    Signed-off-by: Kevin Wolf <kwolf at redhat.com>

diff --git a/tests/Makefile b/tests/Makefile
index d687ecc..9675ba7 100644
--- a/tests/Makefile
+++ b/tests/Makefile
@@ -21,6 +21,7 @@ check-block-$(CONFIG_POSIX) += tests/qemu-iotests-quick.sh
 # All QTests for now are POSIX-only, but the dependencies are
 # really in libqtest, not in the testcases themselves.
 check-qtest-i386-y = tests/fdc-test$(EXESUF)
+check-qtest-i386-y += tests/hd-geo-test$(EXESUF)
 check-qtest-i386-y += tests/rtc-test$(EXESUF)
 check-qtest-x86_64-y = $(check-qtest-i386-y)
 check-qtest-sparc-y = tests/m48t59-test$(EXESUF)
@@ -72,6 +73,7 @@ tests/test-visitor-serialization$(EXESUF): tests/test-visitor-serialization.o $(
 tests/rtc-test$(EXESUF): tests/rtc-test.o $(trace-obj-y)
 tests/m48t59-test$(EXESUF): tests/m48t59-test.o $(trace-obj-y)
 tests/fdc-test$(EXESUF): tests/fdc-test.o tests/libqtest.o $(trace-obj-y)
+tests/hd-geo-test$(EXESUF): tests/hd-geo-test.o tests/libqtest.o $(trace-obj-y)
 
 # QTest rules
 
diff --git a/tests/hd-geo-test.c b/tests/hd-geo-test.c
new file mode 100644
index 0000000..cc447a2
--- /dev/null
+++ b/tests/hd-geo-test.c
@@ -0,0 +1,403 @@
+/*
+ * Hard disk geometry test cases.
+ *
+ * Copyright (c) 2012 Red Hat Inc.
+ *
+ * Authors:
+ *  Markus Armbruster <armbru at redhat.com>,
+ *
+ * This work is licensed under the terms of the GNU GPL, version 2 or later.
+ * See the COPYING file in the top-level directory.
+ */
+
+/*
+ * Covers only IDE and tests only CMOS contents.  Better than nothing.
+ * Improvements welcome.
+ */
+
+#include <glib.h>
+#include <stdlib.h>
+#include <string.h>
+#include <unistd.h>
+#include "qemu-common.h"
+#include "libqtest.h"
+
+static const char test_image[] = "/tmp/qtest.XXXXXX";
+
+static char *create_test_img(int secs)
+{
+    char *template = strdup("/tmp/qtest.XXXXXX");
+    int fd, ret;
+
+    fd = mkstemp(template);
+    g_assert(fd >= 0);
+    ret = ftruncate(fd, (off_t)secs * 512);
+    g_assert(ret == 0);
+    close(fd);
+    return template;
+}
+
+typedef struct {
+    int cyls, heads, secs, trans;
+} CHST;
+
+typedef enum {
+    mbr_blank, mbr_lba, mbr_chs,
+    mbr_last
+} MBRcontents;
+
+typedef enum {
+    /* order is relevant */
+    backend_small, backend_large, backend_empty,
+    backend_last
+} Backend;
+
+static const int img_secs[backend_last] = {
+    [backend_small] = 61440,
+    [backend_large] = 8388608,
+    [backend_empty] = -1,
+};
+
+static const CHST hd_chst[backend_last][mbr_last] = {
+    [backend_small] = {
+        [mbr_blank] = { 60, 16, 63, 0 },
+        [mbr_lba]   = { 60, 16, 63, 2 },
+        [mbr_chs]   = { 60, 16, 63, 0 }
+    },
+    [backend_large] = {
+        [mbr_blank] = { 8322, 16, 63, 1 },
+        [mbr_lba]   = { 8322, 16, 63, 1 },
+        [mbr_chs]   = { 8322, 16, 63, 0 }
+    },
+};
+
+static const char *img_file_name[backend_last];
+
+static const CHST *cur_ide[4];
+
+static bool is_hd(const CHST *expected_chst)
+{
+    return expected_chst && expected_chst->cyls;
+}
+
+static void test_cmos_byte(int reg, int expected)
+{
+    enum { cmos_base = 0x70 };
+    int actual;
+
+    outb(cmos_base + 0, reg);
+    actual = inb(cmos_base + 1);
+    g_assert(actual == expected);
+}
+
+static void test_cmos_bytes(int reg0, int n, uint8_t expected[])
+{
+    int i;
+
+    for (i = 0; i < 9; i++) {
+        test_cmos_byte(reg0 + i, expected[i]);
+    }
+}
+
+static void test_cmos_disk_data(void)
+{
+    test_cmos_byte(0x12,
+                   (is_hd(cur_ide[0]) ? 0xf0 : 0) |
+                   (is_hd(cur_ide[1]) ? 0x0f : 0));
+}
+
+static void test_cmos_drive_cyl(int reg0, const CHST *expected_chst)
+{
+    if (is_hd(expected_chst)) {
+        int c = expected_chst->cyls;
+        int h = expected_chst->heads;
+        int s = expected_chst->secs;
+        uint8_t expected_bytes[9] = {
+            c & 0xff, c >> 8, h, 0xff, 0xff, 0xc0 | ((h > 8) << 3),
+            c & 0xff, c >> 8, s
+        };
+        test_cmos_bytes(reg0, 9, expected_bytes);
+    } else {
+        int i;
+
+        for (i = 0; i < 9; i++) {
+            test_cmos_byte(reg0 + i, 0);
+        }
+    }
+}
+
+static void test_cmos_drive1(void)
+{
+    test_cmos_byte(0x19, is_hd(cur_ide[0]) ? 47 : 0);
+    test_cmos_drive_cyl(0x1b, cur_ide[0]);
+}
+
+static void test_cmos_drive2(void)
+{
+    test_cmos_byte(0x1a, is_hd(cur_ide[1]) ? 47 : 0);
+    test_cmos_drive_cyl(0x24, cur_ide[1]);
+}
+
+static void test_cmos_disktransflag(void)
+{
+    int val, i;
+
+    val = 0;
+    for (i = 0; i < ARRAY_SIZE(cur_ide); i++) {
+        if (is_hd(cur_ide[i])) {
+            val |= cur_ide[i]->trans << (2 * i);
+        }
+    }
+    test_cmos_byte(0x39, val);
+}
+
+static void test_cmos(void)
+{
+    test_cmos_disk_data();
+    test_cmos_drive1();
+    test_cmos_drive2();
+    test_cmos_disktransflag();
+}
+
+static int append_arg(int argc, char *argv[], int argv_sz, char *arg)
+{
+    g_assert(argc + 1 < argv_sz);
+    argv[argc++] = arg;
+    argv[argc] = NULL;
+    return argc;
+}
+
+static int setup_common(char *argv[], int argv_sz)
+{
+    memset(cur_ide, 0, sizeof(cur_ide));
+    return append_arg(0, argv, argv_sz,
+                      g_strdup("-nodefaults -display none"));
+}
+
+static void setup_mbr(int img_idx, MBRcontents mbr)
+{
+    static const uint8_t part_lba[16] = {
+        /* chs 0,1,1 (lba 63) to chs 0,127,63 (8001 sectors) */
+        0x80, 1, 1, 0, 6, 127, 63, 0, 63, 0, 0, 0, 0x41, 0x1F, 0, 0,
+    };
+    static const uint8_t part_chs[16] = {
+        /* chs 0,1,1 (lba 63) to chs 7,15,63 (8001 sectors) */
+        0x80, 1, 1, 0, 6,  15, 63, 7, 63, 0, 0, 0, 0x41, 0x1F, 0, 0,
+    };
+    uint8_t buf[512];
+    int fd, ret;
+
+    memset(buf, 0, sizeof(buf));
+
+    if (mbr != mbr_blank) {
+        buf[0x1fe] = 0x55;
+        buf[0x1ff] = 0xAA;
+        memcpy(buf + 0x1BE, mbr == mbr_lba ? part_lba : part_chs, 16);
+    }
+
+    fd = open(img_file_name[img_idx], O_WRONLY);
+    g_assert(fd >= 0);
+    ret = write(fd, buf, sizeof(buf));
+    g_assert(ret == sizeof(buf));
+    close(fd);
+}
+
+static int setup_ide(int argc, char *argv[], int argv_sz,
+                     int ide_idx, const char *dev, int img_idx,
+                     MBRcontents mbr, const char *opts)
+{
+    char *s1, *s2, *s3;
+
+    s1 = g_strdup_printf("-drive id=drive%d,if=%s",
+                         ide_idx, dev ? "none" : "ide");
+    s2 = dev ? g_strdup("") : g_strdup_printf(",index=%d", ide_idx);
+
+    if (img_secs[img_idx] >= 0) {
+        setup_mbr(img_idx, mbr);
+        s3 = g_strdup_printf(",file=%s", img_file_name[img_idx]);
+    } else {
+        s3 = g_strdup(",media=cdrom");
+    }
+    argc = append_arg(argc, argv, argv_sz,
+                      g_strdup_printf("%s%s%s%s", s1, s2, s3, opts));
+    g_free(s1);
+    g_free(s2);
+    g_free(s3);
+
+    if (dev) {
+        argc = append_arg(argc, argv, argv_sz,
+                          g_strdup_printf("-device %s,drive=drive%d,"
+                                          "bus=ide.%d,unit=%d",
+                                          dev, ide_idx,
+                                          ide_idx / 2, ide_idx % 2));
+    }
+    return argc;
+}
+
+/*
+ * Test case: no IDE devices
+ */
+static void test_ide_none(void)
+{
+    char *argv[256];
+
+    setup_common(argv, ARRAY_SIZE(argv));
+    qtest_start(g_strjoinv(" ", argv));
+    test_cmos();
+    qtest_quit(global_qtest);
+}
+
+static void test_ide_mbr(bool use_device, MBRcontents mbr)
+{
+    char *argv[256];
+    int argc;
+    Backend i;
+    const char *dev;
+
+    argc = setup_common(argv, ARRAY_SIZE(argv));
+    for (i = 0; i < backend_last; i++) {
+        cur_ide[i] = &hd_chst[i][mbr];
+        dev = use_device ? (is_hd(cur_ide[i]) ? "ide-hd" : "ide-cd") : NULL;
+        argc = setup_ide(argc, argv, ARRAY_SIZE(argv), i, dev, i, mbr, "");
+    }
+    qtest_start(g_strjoinv(" ", argv));
+    test_cmos();
+    qtest_quit(global_qtest);
+}
+
+/*
+ * Test case: IDE devices (if=ide) with blank MBRs
+ */
+static void test_ide_drive_mbr_blank(void)
+{
+    test_ide_mbr(false, mbr_blank);
+}
+
+/*
+ * Test case: IDE devices (if=ide) with MBRs indicating LBA is in use
+ */
+static void test_ide_drive_mbr_lba(void)
+{
+    test_ide_mbr(false, mbr_lba);
+}
+
+/*
+ * Test case: IDE devices (if=ide) with MBRs indicating CHS is in use
+ */
+static void test_ide_drive_mbr_chs(void)
+{
+    test_ide_mbr(false, mbr_chs);
+}
+
+/*
+ * Test case: IDE devices (if=none) with blank MBRs
+ */
+static void test_ide_device_mbr_blank(void)
+{
+    test_ide_mbr(true, mbr_blank);
+}
+
+/*
+ * Test case: IDE devices (if=none) with MBRs indicating LBA is in use
+ */
+static void test_ide_device_mbr_lba(void)
+{
+    test_ide_mbr(true, mbr_lba);
+}
+
+/*
+ * Test case: IDE devices (if=none) with MBRs indicating CHS is in use
+ */
+static void test_ide_device_mbr_chs(void)
+{
+    test_ide_mbr(true, mbr_chs);
+}
+
+static void test_ide_drive_user(const char *dev, bool trans)
+{
+    char *argv[256], *opts;
+    int argc;
+    int secs = img_secs[backend_small];
+    const CHST expected_chst = { secs / (4 * 32) , 4, 32, trans };
+
+    argc = setup_common(argv, ARRAY_SIZE(argv));
+    opts = g_strdup_printf(",cyls=%d,heads=%d,secs=%d%s",
+                           expected_chst.cyls, expected_chst.heads,
+                           expected_chst.secs,
+                           trans ? ",trans=lba" : "");
+    cur_ide[0] = &expected_chst;
+    argc = setup_ide(argc, argv, ARRAY_SIZE(argv),
+                     0, dev, backend_small, mbr_chs, opts);
+    g_free(opts);
+    qtest_start(g_strjoinv(" ", argv));
+    test_cmos();
+    qtest_quit(global_qtest);
+}
+
+/*
+ * Test case: IDE device (if=ide) with explicit CHS
+ */
+static void test_ide_drive_user_chs(void)
+{
+    test_ide_drive_user(NULL, false);
+}
+
+/*
+ * Test case: IDE device (if=ide) with explicit CHS and translation
+ */
+static void test_ide_drive_user_chst(void)
+{
+    test_ide_drive_user(NULL, true);
+}
+
+/*
+ * Test case: IDE device (if=none) with explicit CHS
+ */
+static void test_ide_device_user_chs(void)
+{
+    test_ide_drive_user("ide-hd", false);
+}
+
+/*
+ * Test case: IDE device (if=none) with explicit CHS and translation
+ */
+static void test_ide_device_user_chst(void)
+{
+    test_ide_drive_user("ide-hd", true);
+}
+
+int main(int argc, char **argv)
+{
+    Backend i;
+    int ret;
+
+    g_test_init(&argc, &argv, NULL);
+
+    for (i = 0; i < backend_last; i++) {
+        if (img_secs[i] >= 0) {
+            img_file_name[i] = create_test_img(img_secs[i]);
+        } else {
+            img_file_name[i] = NULL;
+        }
+    }
+
+    qtest_add_func("hd-geo/ide/none", test_ide_none);
+    qtest_add_func("hd-geo/ide/drive/mbr/blank", test_ide_drive_mbr_blank);
+    qtest_add_func("hd-geo/ide/drive/mbr/lba", test_ide_drive_mbr_lba);
+    qtest_add_func("hd-geo/ide/drive/mbr/chs", test_ide_drive_mbr_chs);
+    qtest_add_func("hd-geo/ide/drive/user/chs", test_ide_drive_user_chs);
+    qtest_add_func("hd-geo/ide/drive/user/chst", test_ide_drive_user_chst);
+    qtest_add_func("hd-geo/ide/device/mbr/blank", test_ide_device_mbr_blank);
+    qtest_add_func("hd-geo/ide/device/mbr/lba", test_ide_device_mbr_lba);
+    qtest_add_func("hd-geo/ide/device/mbr/chs", test_ide_device_mbr_chs);
+    qtest_add_func("hd-geo/ide/device/user/chs", test_ide_device_user_chs);
+    qtest_add_func("hd-geo/ide/device/user/chst", test_ide_device_user_chst);
+
+    ret = g_test_run();
+
+    for (i = 0; i < backend_last; i++) {
+        unlink(img_file_name[i]);
+    }
+
+    return ret;
+}
commit 4480e0f924a42e1db8b8cfcac4d0634dd1bb27a0
Author: Markus Armbruster <armbru at redhat.com>
Date:   Tue Jul 10 11:12:29 2012 +0200

    vvfat: Do not clobber the user's geometry
    
    vvfat creates a virtual VFAT filesystem with a certain logical
    geometry that depends on its options.  It sets the "geometry hint" to
    this geometry.  It is the only block driver to do this.
    
    The geometry hint is about about *physical* geometry, and used only by
    certain hard disk device models.
    
    vvfat's hint is normally invisible for device models, because
    bdrv_open() puts a raw format on top of vvfat's fat protocol.  That
    raw format is where drive_init() puts the user's geometry (if any),
    and where the device model gets it from.
    
    Nobody complained, because the default physical geometry is the same
    as vvfat's logical geometry:
    
        opts        LCHS        def. PCHS
                    1024,16,63  same
        :32:        1024,16,63  same
        :16:        1024,16,63  same
        :12:          64,16,63  same
    
    Except when you specify :floppy:
    
        opts        LCHS        def. PCHS
           :floppy:   80, 2,36  5,16,63
        :32:floppy:   80, 2,36  5,16,63
        :16:floppy:   80, 2,36  5,16,63
        :12:floppy:   80, 2,18  2,16,63
    
    Silly thing to do for use with a hard disk.
    
    However, the "raw" format can be suppressed by adding an
    redundant-looking "format=vvfat" to "file=fat:FOO".  Then, vvfat's
    hint clobbers the user's geometry, i.e. -drive options cyls, heads,
    secs get silently ignored.  Don't do that.
    
    No change without format=vvfat.  With it, the user's hard disk
    geometry (-drive options cyls, heads, secs) is now obeyed, and the
    default hard disk geometry with :floppy: now matches the one without
    format=vvfat.
    
    Signed-off-by: Markus Armbruster <armbru at redhat.com>
    Signed-off-by: Kevin Wolf <kwolf at redhat.com>

diff --git a/block/vvfat.c b/block/vvfat.c
index e2b83a2..7b1dcee 100644
--- a/block/vvfat.c
+++ b/block/vvfat.c
@@ -359,11 +359,12 @@ typedef struct BDRVVVFATState {
  * if the position is outside the specified geometry, fill maximum value for CHS
  * and return 1 to signal overflow.
  */
-static int sector2CHS(BlockDriverState* bs, mbr_chs_t * chs, int spos){
+static int sector2CHS(mbr_chs_t *chs, int spos, int cyls, int heads, int secs)
+{
     int head,sector;
-    sector   = spos % (bs->secs);  spos/= bs->secs;
-    head     = spos % (bs->heads); spos/= bs->heads;
-    if(spos >= bs->cyls){
+    sector   = spos % secs;  spos /= secs;
+    head     = spos % heads; spos /= heads;
+    if (spos >= cyls) {
         /* Overflow,
         it happens if 32bit sector positions are used, while CHS is only 24bit.
         Windows/Dos is said to take 1023/255/63 as nonrepresentable CHS */
@@ -378,7 +379,7 @@ static int sector2CHS(BlockDriverState* bs, mbr_chs_t * chs, int spos){
     return 0;
 }
 
-static void init_mbr(BDRVVVFATState* s)
+static void init_mbr(BDRVVVFATState *s, int cyls, int heads, int secs)
 {
     /* TODO: if the files mbr.img and bootsect.img exist, use them */
     mbr_t* real_mbr=(mbr_t*)s->first_sectors;
@@ -393,8 +394,10 @@ static void init_mbr(BDRVVVFATState* s)
     partition->attributes=0x80; /* bootable */
 
     /* LBA is used when partition is outside the CHS geometry */
-    lba = sector2CHS(s->bs, &partition->start_CHS, s->first_sectors_number-1);
-    lba |= sector2CHS(s->bs, &partition->end_CHS, s->bs->total_sectors - 1);
+    lba  = sector2CHS(&partition->start_CHS, s->first_sectors_number - 1,
+                     cyls, heads, secs);
+    lba |= sector2CHS(&partition->end_CHS,   s->bs->total_sectors - 1,
+                     cyls, heads, secs);
 
     /*LBA partitions are identified only by start/length_sector_long not by CHS*/
     partition->start_sector_long  = cpu_to_le32(s->first_sectors_number - 1);
@@ -831,7 +834,7 @@ static inline off_t cluster2sector(BDRVVVFATState* s, uint32_t cluster_num)
 }
 
 static int init_directories(BDRVVVFATState* s,
-	const char* dirname)
+                            const char *dirname, int heads, int secs)
 {
     bootsector_t* bootsector;
     mapping_t* mapping;
@@ -958,8 +961,8 @@ static int init_directories(BDRVVVFATState* s,
     bootsector->media_type=(s->first_sectors_number>1?0xf8:0xf0); /* media descriptor (f8=hd, f0=3.5 fd)*/
     s->fat.pointer[0] = bootsector->media_type;
     bootsector->sectors_per_fat=cpu_to_le16(s->sectors_per_fat);
-    bootsector->sectors_per_track=cpu_to_le16(s->bs->secs);
-    bootsector->number_of_heads=cpu_to_le16(s->bs->heads);
+    bootsector->sectors_per_track = cpu_to_le16(secs);
+    bootsector->number_of_heads = cpu_to_le16(heads);
     bootsector->hidden_sectors=cpu_to_le32(s->first_sectors_number==1?0:0x3f);
     bootsector->total_sectors=cpu_to_le32(s->sector_count>0xffff?s->sector_count:0);
 
@@ -992,7 +995,7 @@ static void vvfat_rebind(BlockDriverState *bs)
 static int vvfat_open(BlockDriverState *bs, const char* dirname, int flags)
 {
     BDRVVVFATState *s = bs->opaque;
-    int i;
+    int i, cyls, heads, secs;
 
 #ifdef DEBUG
     vvv = s;
@@ -1034,24 +1037,28 @@ DLOG(if (stderr == NULL) {
 	/* 1.44MB or 2.88MB floppy.  2.88MB can be FAT12 (default) or FAT16. */
 	if (!s->fat_type) {
 	    s->fat_type = 12;
-	    bs->secs = 36;
+            secs = 36;
 	    s->sectors_per_cluster=2;
 	} else {
-	    bs->secs=(s->fat_type == 12 ? 18 : 36);
+            secs = s->fat_type == 12 ? 18 : 36;
 	    s->sectors_per_cluster=1;
 	}
 	s->first_sectors_number = 1;
-	bs->cyls=80; bs->heads=2;
+        cyls = 80;
+        heads = 2;
     } else {
 	/* 32MB or 504MB disk*/
 	if (!s->fat_type) {
 	    s->fat_type = 16;
 	}
-	bs->cyls=(s->fat_type == 12 ? 64 : 1024);
-	bs->heads=16; bs->secs=63;
+        cyls = s->fat_type == 12 ? 64 : 1024;
+        heads = 16;
+        secs = 63;
     }
+    fprintf(stderr, "vvfat %s chs %d,%d,%d\n",
+            dirname, cyls, heads, secs);
 
-    s->sector_count=bs->cyls*bs->heads*bs->secs-(s->first_sectors_number-1);
+    s->sector_count = cyls * heads * secs - (s->first_sectors_number - 1);
 
     if (strstr(dirname, ":rw:")) {
 	if (enable_write_target(s))
@@ -1067,18 +1074,16 @@ DLOG(if (stderr == NULL) {
     else
 	dirname += i+1;
 
-    bs->total_sectors=bs->cyls*bs->heads*bs->secs;
+    bs->total_sectors = cyls * heads * secs;
 
-    if(init_directories(s, dirname))
+    if (init_directories(s, dirname, heads, secs)) {
 	return -1;
+    }
 
     s->sector_count = s->faked_sectors + s->sectors_per_cluster*s->cluster_count;
 
-    if(s->first_sectors_number==0x40)
-	init_mbr(s);
-    else {
-        /* MS-DOS does not like to know about CHS (?). */
-	bs->heads = bs->cyls = bs->secs = 0;
+    if (s->first_sectors_number == 0x40) {
+        init_mbr(s, cyls, heads, secs);
     }
 
     //    assert(is_consistent(s));
commit f91cbefe2d0eb3f7b5071bcb1fd3a02970f1a776
Author: Markus Armbruster <armbru at redhat.com>
Date:   Tue Jul 10 11:12:28 2012 +0200

    vvfat: Fix partition table
    
    Unless parameter ":floppy:" is given, vvfat creates a virtual image
    with DOS MBR defining a single partition which holds the FAT file
    system.  The size of the virtual image depends on the width of the
    FAT: 32 MiB (CHS 64, 16, 63) for 12 bit FAT, 504 MiB (CHS 1024, 16,
    63) for 16 and 32 bit FAT, leaving (64*16-1)*63 = 64449 and
    (1024*16-1)*64 = 1032129 sectors for the partition.
    
    However, it screws up the end of the partition in the MBR:
    
        FAT width param.  start CHS  end CHS     start LBA  size
            :32:          0,1,1      1023,14,63       63    1032065
            :16:          0,1,1      1023,14,55       63    1032057
            :12:          0,1,1        63,14,55       63      64377
    
    The actual FAT file system nevertheless assumes the partition has
    1032129 or 64449 sectors.  Oops.
    
    Signed-off-by: Markus Armbruster <armbru at redhat.com>
    Signed-off-by: Kevin Wolf <kwolf at redhat.com>

diff --git a/block/vvfat.c b/block/vvfat.c
index 0fd3367..e2b83a2 100644
--- a/block/vvfat.c
+++ b/block/vvfat.c
@@ -394,11 +394,12 @@ static void init_mbr(BDRVVVFATState* s)
 
     /* LBA is used when partition is outside the CHS geometry */
     lba = sector2CHS(s->bs, &partition->start_CHS, s->first_sectors_number-1);
-    lba|= sector2CHS(s->bs, &partition->end_CHS,   s->sector_count);
+    lba |= sector2CHS(s->bs, &partition->end_CHS, s->bs->total_sectors - 1);
 
     /*LBA partitions are identified only by start/length_sector_long not by CHS*/
-    partition->start_sector_long =cpu_to_le32(s->first_sectors_number-1);
-    partition->length_sector_long=cpu_to_le32(s->sector_count - s->first_sectors_number+1);
+    partition->start_sector_long  = cpu_to_le32(s->first_sectors_number - 1);
+    partition->length_sector_long = cpu_to_le32(s->bs->total_sectors
+                                                - s->first_sectors_number + 1);
 
     /* FAT12/FAT16/FAT32 */
     /* DOS uses different types when partition is LBA,
commit 61a8d649ff1e125966b51d688ff43dc6ef6ca63b
Author: Markus Armbruster <armbru at redhat.com>
Date:   Tue Jul 10 11:12:27 2012 +0200

    fdc: Move floppy geometry guessing back from block.c
    
    Commit 5bbdbb46 moved it to block.c because "other geometry guessing
    functions already reside in block.c".  Device-specific functionality
    should be kept in device code, not the block layer.  Move it back.
    
    Disk geometry guessing is still in block.c.  To be moved out in a
    later patch series.
    
    Bonus: the floppy type used in pc_cmos_init() now obviously matches
    the one in the FDrive.  Before, we relied on
    bdrv_get_floppy_geometry_hint() picking the same type both in
    fd_revalidate() and in pc_cmos_init().
    
    Signed-off-by: Markus Armbruster <armbru at redhat.com>
    Signed-off-by: Kevin Wolf <kwolf at redhat.com>

diff --git a/block.c b/block.c
index 0c923f2..ffda1c2 100644
--- a/block.c
+++ b/block.c
@@ -2282,107 +2282,6 @@ void bdrv_set_io_limits(BlockDriverState *bs,
     bs->io_limits_enabled = bdrv_io_limits_enabled(bs);
 }
 
-/* Recognize floppy formats */
-typedef struct FDFormat {
-    FDriveType drive;
-    uint8_t last_sect;
-    uint8_t max_track;
-    uint8_t max_head;
-    FDriveRate rate;
-} FDFormat;
-
-static const FDFormat fd_formats[] = {
-    /* First entry is default format */
-    /* 1.44 MB 3"1/2 floppy disks */
-    { FDRIVE_DRV_144, 18, 80, 1, FDRIVE_RATE_500K, },
-    { FDRIVE_DRV_144, 20, 80, 1, FDRIVE_RATE_500K, },
-    { FDRIVE_DRV_144, 21, 80, 1, FDRIVE_RATE_500K, },
-    { FDRIVE_DRV_144, 21, 82, 1, FDRIVE_RATE_500K, },
-    { FDRIVE_DRV_144, 21, 83, 1, FDRIVE_RATE_500K, },
-    { FDRIVE_DRV_144, 22, 80, 1, FDRIVE_RATE_500K, },
-    { FDRIVE_DRV_144, 23, 80, 1, FDRIVE_RATE_500K, },
-    { FDRIVE_DRV_144, 24, 80, 1, FDRIVE_RATE_500K, },
-    /* 2.88 MB 3"1/2 floppy disks */
-    { FDRIVE_DRV_288, 36, 80, 1, FDRIVE_RATE_1M, },
-    { FDRIVE_DRV_288, 39, 80, 1, FDRIVE_RATE_1M, },
-    { FDRIVE_DRV_288, 40, 80, 1, FDRIVE_RATE_1M, },
-    { FDRIVE_DRV_288, 44, 80, 1, FDRIVE_RATE_1M, },
-    { FDRIVE_DRV_288, 48, 80, 1, FDRIVE_RATE_1M, },
-    /* 720 kB 3"1/2 floppy disks */
-    { FDRIVE_DRV_144,  9, 80, 1, FDRIVE_RATE_250K, },
-    { FDRIVE_DRV_144, 10, 80, 1, FDRIVE_RATE_250K, },
-    { FDRIVE_DRV_144, 10, 82, 1, FDRIVE_RATE_250K, },
-    { FDRIVE_DRV_144, 10, 83, 1, FDRIVE_RATE_250K, },
-    { FDRIVE_DRV_144, 13, 80, 1, FDRIVE_RATE_250K, },
-    { FDRIVE_DRV_144, 14, 80, 1, FDRIVE_RATE_250K, },
-    /* 1.2 MB 5"1/4 floppy disks */
-    { FDRIVE_DRV_120, 15, 80, 1, FDRIVE_RATE_500K, },
-    { FDRIVE_DRV_120, 18, 80, 1, FDRIVE_RATE_500K, },
-    { FDRIVE_DRV_120, 18, 82, 1, FDRIVE_RATE_500K, },
-    { FDRIVE_DRV_120, 18, 83, 1, FDRIVE_RATE_500K, },
-    { FDRIVE_DRV_120, 20, 80, 1, FDRIVE_RATE_500K, },
-    /* 720 kB 5"1/4 floppy disks */
-    { FDRIVE_DRV_120,  9, 80, 1, FDRIVE_RATE_250K, },
-    { FDRIVE_DRV_120, 11, 80, 1, FDRIVE_RATE_250K, },
-    /* 360 kB 5"1/4 floppy disks */
-    { FDRIVE_DRV_120,  9, 40, 1, FDRIVE_RATE_300K, },
-    { FDRIVE_DRV_120,  9, 40, 0, FDRIVE_RATE_300K, },
-    { FDRIVE_DRV_120, 10, 41, 1, FDRIVE_RATE_300K, },
-    { FDRIVE_DRV_120, 10, 42, 1, FDRIVE_RATE_300K, },
-    /* 320 kB 5"1/4 floppy disks */
-    { FDRIVE_DRV_120,  8, 40, 1, FDRIVE_RATE_250K, },
-    { FDRIVE_DRV_120,  8, 40, 0, FDRIVE_RATE_250K, },
-    /* 360 kB must match 5"1/4 better than 3"1/2... */
-    { FDRIVE_DRV_144,  9, 80, 0, FDRIVE_RATE_250K, },
-    /* end */
-    { FDRIVE_DRV_NONE, -1, -1, 0, 0, },
-};
-
-void bdrv_get_floppy_geometry_hint(BlockDriverState *bs, int *nb_heads,
-                                   int *max_track, int *last_sect,
-                                   FDriveType drive_in, FDriveType *drive,
-                                   FDriveRate *rate)
-{
-    const FDFormat *parse;
-    uint64_t nb_sectors, size;
-    int i, first_match, match;
-
-    bdrv_get_geometry(bs, &nb_sectors);
-    match = -1;
-    first_match = -1;
-    for (i = 0; ; i++) {
-        parse = &fd_formats[i];
-        if (parse->drive == FDRIVE_DRV_NONE) {
-            break;
-        }
-        if (drive_in == parse->drive ||
-            drive_in == FDRIVE_DRV_NONE) {
-            size = (parse->max_head + 1) * parse->max_track *
-                parse->last_sect;
-            if (nb_sectors == size) {
-                match = i;
-                break;
-            }
-            if (first_match == -1) {
-                first_match = i;
-            }
-        }
-    }
-    if (match == -1) {
-        if (first_match == -1) {
-            match = 1;
-        } else {
-            match = first_match;
-        }
-        parse = &fd_formats[match];
-    }
-    *nb_heads = parse->max_head + 1;
-    *max_track = parse->max_track;
-    *last_sect = parse->last_sect;
-    *drive = parse->drive;
-    *rate = parse->rate;
-}
-
 int bdrv_get_translation_hint(BlockDriverState *bs)
 {
     return bs->translation;
diff --git a/block.h b/block.h
index e34d942..b24f664 100644
--- a/block.h
+++ b/block.h
@@ -269,24 +269,6 @@ void bdrv_set_geometry_hint(BlockDriverState *bs,
 void bdrv_set_translation_hint(BlockDriverState *bs, int translation);
 void bdrv_get_geometry_hint(BlockDriverState *bs,
                             int *pcyls, int *pheads, int *psecs);
-typedef enum FDriveType {
-    FDRIVE_DRV_144  = 0x00,   /* 1.44 MB 3"5 drive      */
-    FDRIVE_DRV_288  = 0x01,   /* 2.88 MB 3"5 drive      */
-    FDRIVE_DRV_120  = 0x02,   /* 1.2  MB 5"25 drive     */
-    FDRIVE_DRV_NONE = 0x03,   /* No drive connected     */
-} FDriveType;
-
-typedef enum FDriveRate {
-    FDRIVE_RATE_500K = 0x00,  /* 500 Kbps */
-    FDRIVE_RATE_300K = 0x01,  /* 300 Kbps */
-    FDRIVE_RATE_250K = 0x02,  /* 250 Kbps */
-    FDRIVE_RATE_1M   = 0x03,  /*   1 Mbps */
-} FDriveRate;
-
-void bdrv_get_floppy_geometry_hint(BlockDriverState *bs, int *nb_heads,
-                                   int *max_track, int *last_sect,
-                                   FDriveType drive_in, FDriveType *drive,
-                                   FDriveRate *rate);
 int bdrv_get_translation_hint(BlockDriverState *bs);
 void bdrv_set_on_error(BlockDriverState *bs, BlockErrorAction on_read_error,
                        BlockErrorAction on_write_error);
diff --git a/hw/fdc.c b/hw/fdc.c
index edf0706..41191c7 100644
--- a/hw/fdc.c
+++ b/hw/fdc.c
@@ -52,6 +52,113 @@
 /********************************************************/
 /* Floppy drive emulation                               */
 
+typedef enum FDriveRate {
+    FDRIVE_RATE_500K = 0x00,  /* 500 Kbps */
+    FDRIVE_RATE_300K = 0x01,  /* 300 Kbps */
+    FDRIVE_RATE_250K = 0x02,  /* 250 Kbps */
+    FDRIVE_RATE_1M   = 0x03,  /*   1 Mbps */
+} FDriveRate;
+
+typedef struct FDFormat {
+    FDriveType drive;
+    uint8_t last_sect;
+    uint8_t max_track;
+    uint8_t max_head;
+    FDriveRate rate;
+} FDFormat;
+
+static const FDFormat fd_formats[] = {
+    /* First entry is default format */
+    /* 1.44 MB 3"1/2 floppy disks */
+    { FDRIVE_DRV_144, 18, 80, 1, FDRIVE_RATE_500K, },
+    { FDRIVE_DRV_144, 20, 80, 1, FDRIVE_RATE_500K, },
+    { FDRIVE_DRV_144, 21, 80, 1, FDRIVE_RATE_500K, },
+    { FDRIVE_DRV_144, 21, 82, 1, FDRIVE_RATE_500K, },
+    { FDRIVE_DRV_144, 21, 83, 1, FDRIVE_RATE_500K, },
+    { FDRIVE_DRV_144, 22, 80, 1, FDRIVE_RATE_500K, },
+    { FDRIVE_DRV_144, 23, 80, 1, FDRIVE_RATE_500K, },
+    { FDRIVE_DRV_144, 24, 80, 1, FDRIVE_RATE_500K, },
+    /* 2.88 MB 3"1/2 floppy disks */
+    { FDRIVE_DRV_288, 36, 80, 1, FDRIVE_RATE_1M, },
+    { FDRIVE_DRV_288, 39, 80, 1, FDRIVE_RATE_1M, },
+    { FDRIVE_DRV_288, 40, 80, 1, FDRIVE_RATE_1M, },
+    { FDRIVE_DRV_288, 44, 80, 1, FDRIVE_RATE_1M, },
+    { FDRIVE_DRV_288, 48, 80, 1, FDRIVE_RATE_1M, },
+    /* 720 kB 3"1/2 floppy disks */
+    { FDRIVE_DRV_144,  9, 80, 1, FDRIVE_RATE_250K, },
+    { FDRIVE_DRV_144, 10, 80, 1, FDRIVE_RATE_250K, },
+    { FDRIVE_DRV_144, 10, 82, 1, FDRIVE_RATE_250K, },
+    { FDRIVE_DRV_144, 10, 83, 1, FDRIVE_RATE_250K, },
+    { FDRIVE_DRV_144, 13, 80, 1, FDRIVE_RATE_250K, },
+    { FDRIVE_DRV_144, 14, 80, 1, FDRIVE_RATE_250K, },
+    /* 1.2 MB 5"1/4 floppy disks */
+    { FDRIVE_DRV_120, 15, 80, 1, FDRIVE_RATE_500K, },
+    { FDRIVE_DRV_120, 18, 80, 1, FDRIVE_RATE_500K, },
+    { FDRIVE_DRV_120, 18, 82, 1, FDRIVE_RATE_500K, },
+    { FDRIVE_DRV_120, 18, 83, 1, FDRIVE_RATE_500K, },
+    { FDRIVE_DRV_120, 20, 80, 1, FDRIVE_RATE_500K, },
+    /* 720 kB 5"1/4 floppy disks */
+    { FDRIVE_DRV_120,  9, 80, 1, FDRIVE_RATE_250K, },
+    { FDRIVE_DRV_120, 11, 80, 1, FDRIVE_RATE_250K, },
+    /* 360 kB 5"1/4 floppy disks */
+    { FDRIVE_DRV_120,  9, 40, 1, FDRIVE_RATE_300K, },
+    { FDRIVE_DRV_120,  9, 40, 0, FDRIVE_RATE_300K, },
+    { FDRIVE_DRV_120, 10, 41, 1, FDRIVE_RATE_300K, },
+    { FDRIVE_DRV_120, 10, 42, 1, FDRIVE_RATE_300K, },
+    /* 320 kB 5"1/4 floppy disks */
+    { FDRIVE_DRV_120,  8, 40, 1, FDRIVE_RATE_250K, },
+    { FDRIVE_DRV_120,  8, 40, 0, FDRIVE_RATE_250K, },
+    /* 360 kB must match 5"1/4 better than 3"1/2... */
+    { FDRIVE_DRV_144,  9, 80, 0, FDRIVE_RATE_250K, },
+    /* end */
+    { FDRIVE_DRV_NONE, -1, -1, 0, 0, },
+};
+
+static void pick_geometry(BlockDriverState *bs, int *nb_heads,
+                          int *max_track, int *last_sect,
+                          FDriveType drive_in, FDriveType *drive,
+                          FDriveRate *rate)
+{
+    const FDFormat *parse;
+    uint64_t nb_sectors, size;
+    int i, first_match, match;
+
+    bdrv_get_geometry(bs, &nb_sectors);
+    match = -1;
+    first_match = -1;
+    for (i = 0; ; i++) {
+        parse = &fd_formats[i];
+        if (parse->drive == FDRIVE_DRV_NONE) {
+            break;
+        }
+        if (drive_in == parse->drive ||
+            drive_in == FDRIVE_DRV_NONE) {
+            size = (parse->max_head + 1) * parse->max_track *
+                parse->last_sect;
+            if (nb_sectors == size) {
+                match = i;
+                break;
+            }
+            if (first_match == -1) {
+                first_match = i;
+            }
+        }
+    }
+    if (match == -1) {
+        if (first_match == -1) {
+            match = 1;
+        } else {
+            match = first_match;
+        }
+        parse = &fd_formats[match];
+    }
+    *nb_heads = parse->max_head + 1;
+    *max_track = parse->max_track;
+    *last_sect = parse->last_sect;
+    *drive = parse->drive;
+    *rate = parse->rate;
+}
+
 #define GET_CUR_DRV(fdctrl) ((fdctrl)->cur_drv)
 #define SET_CUR_DRV(fdctrl, drive) ((fdctrl)->cur_drv = (drive))
 
@@ -187,8 +294,8 @@ static void fd_revalidate(FDrive *drv)
     FLOPPY_DPRINTF("revalidate\n");
     if (drv->bs != NULL) {
         ro = bdrv_is_read_only(drv->bs);
-        bdrv_get_floppy_geometry_hint(drv->bs, &nb_heads, &max_track,
-                                      &last_sect, drv->drive, &drive, &rate);
+        pick_geometry(drv->bs, &nb_heads, &max_track,
+                      &last_sect, drv->drive, &drive, &rate);
         if (!bdrv_is_inserted(drv->bs)) {
             FLOPPY_DPRINTF("No disk in drive\n");
         } else {
@@ -2054,18 +2161,13 @@ static int sun4m_fdc_init1(SysBusDevice *dev)
     return fdctrl_init_common(fdctrl);
 }
 
-void fdc_get_bs(BlockDriverState *bs[], ISADevice *dev)
+FDriveType isa_fdc_get_drive_type(ISADevice *fdc, int i)
 {
-    FDCtrlISABus *isa = DO_UPCAST(FDCtrlISABus, busdev, dev);
-    FDCtrl *fdctrl = &isa->state;
-    int i;
+    FDCtrlISABus *isa = DO_UPCAST(FDCtrlISABus, busdev, fdc);
 
-    for (i = 0; i < MAX_FD; i++) {
-        bs[i] = fdctrl->drives[i].bs;
-    }
+    return isa->state.drives[i].drive;
 }
 
-
 static const VMStateDescription vmstate_isa_fdc ={
     .name = "fdc",
     .version_id = 2,
diff --git a/hw/fdc.h b/hw/fdc.h
index 1b32b17..b5c9f31 100644
--- a/hw/fdc.h
+++ b/hw/fdc.h
@@ -6,11 +6,19 @@
 /* fdc.c */
 #define MAX_FD 2
 
+typedef enum FDriveType {
+    FDRIVE_DRV_144  = 0x00,   /* 1.44 MB 3"5 drive      */
+    FDRIVE_DRV_288  = 0x01,   /* 2.88 MB 3"5 drive      */
+    FDRIVE_DRV_120  = 0x02,   /* 1.2  MB 5"25 drive     */
+    FDRIVE_DRV_NONE = 0x03,   /* No drive connected     */
+} FDriveType;
+
 ISADevice *fdctrl_init_isa(ISABus *bus, DriveInfo **fds);
 void fdctrl_init_sysbus(qemu_irq irq, int dma_chann,
                         target_phys_addr_t mmio_base, DriveInfo **fds);
 void sun4m_fdctrl_init(qemu_irq irq, target_phys_addr_t io_base,
                        DriveInfo **fds, qemu_irq *fdc_tc);
-void fdc_get_bs(BlockDriverState *bs[], ISADevice *dev);
+
+FDriveType isa_fdc_get_drive_type(ISADevice *fdc, int i);
 
 #endif
diff --git a/hw/pc.c b/hw/pc.c
index c7e9ab3..91cf77d 100644
--- a/hw/pc.c
+++ b/hw/pc.c
@@ -335,10 +335,8 @@ void pc_cmos_init(ram_addr_t ram_size, ram_addr_t above_4g_mem_size,
                   ISADevice *floppy, BusState *idebus0, BusState *idebus1,
                   ISADevice *s)
 {
-    int val, nb, nb_heads, max_track, last_sect, i;
+    int val, nb, i;
     FDriveType fd_type[2] = { FDRIVE_DRV_NONE, FDRIVE_DRV_NONE };
-    FDriveRate rate;
-    BlockDriverState *fd[MAX_FD];
     static pc_cmos_init_late_arg arg;
 
     /* various important CMOS locations needed by PC/Bochs bios */
@@ -381,13 +379,8 @@ void pc_cmos_init(ram_addr_t ram_size, ram_addr_t above_4g_mem_size,
 
     /* floppy type */
     if (floppy) {
-        fdc_get_bs(fd, floppy);
         for (i = 0; i < 2; i++) {
-            if (fd[i]) {
-                bdrv_get_floppy_geometry_hint(fd[i], &nb_heads, &max_track,
-                                              &last_sect, FDRIVE_DRV_NONE,
-                                              &fd_type[i], &rate);
-            }
+            fd_type[i] = isa_fdc_get_drive_type(floppy, i);
         }
     }
     val = (cmos_get_fd_drive_type(fd_type[0]) << 4) |
commit 19db9b9042657ef80ddd4c94b1748dc2368aab70
Author: Christoph Hellwig <hch at lst.de>
Date:   Tue Jul 10 16:12:27 2012 +0200

    sheepdog: do not blindly memset all read buffers
    
    Only buffers that map to unallocated blocks need to be zeroed.
    
    Signed-off-by: Christoph Hellwig <hch at lst.de>
    Acked-by: MORITA Kazutaka <morita.kazutaka at lab.ntt.co.jp>
    Signed-off-by: Kevin Wolf <kwolf at redhat.com>

diff --git a/block/sheepdog.c b/block/sheepdog.c
index 465dc97..a04ad99 100644
--- a/block/sheepdog.c
+++ b/block/sheepdog.c
@@ -1571,18 +1571,25 @@ static int coroutine_fn sd_co_rw_vector(void *p)
 
         len = MIN(total - done, SD_DATA_OBJ_SIZE - offset);
 
-        if (!inode->data_vdi_id[idx]) {
-            if (acb->aiocb_type == AIOCB_READ_UDATA) {
+        switch (acb->aiocb_type) {
+        case AIOCB_READ_UDATA:
+            if (!inode->data_vdi_id[idx]) {
+                qemu_iovec_memset(acb->qiov, done, 0, len);
                 goto done;
             }
-
-            create = 1;
-        } else if (acb->aiocb_type == AIOCB_WRITE_UDATA
-                   && !is_data_obj_writable(inode, idx)) {
-            /* Copy-On-Write */
-            create = 1;
-            old_oid = oid;
-            flags = SD_FLAG_CMD_COW;
+            break;
+        case AIOCB_WRITE_UDATA:
+            if (!inode->data_vdi_id[idx]) {
+                create = 1;
+            } else if (!is_data_obj_writable(inode, idx)) {
+                /* Copy-On-Write */
+                create = 1;
+                old_oid = oid;
+                flags = SD_FLAG_CMD_COW;
+            }
+            break;
+        default:
+            break;
         }
 
         if (create) {
@@ -1668,20 +1675,12 @@ static coroutine_fn int sd_co_readv(BlockDriverState *bs, int64_t sector_num,
                        int nb_sectors, QEMUIOVector *qiov)
 {
     SheepdogAIOCB *acb;
-    int i, ret;
+    int ret;
 
     acb = sd_aio_setup(bs, qiov, sector_num, nb_sectors, NULL, NULL);
     acb->aiocb_type = AIOCB_READ_UDATA;
     acb->aio_done_func = sd_finish_aiocb;
 
-    /*
-     * TODO: we can do better; we don't need to initialize
-     * blindly.
-     */
-    for (i = 0; i < qiov->niov; i++) {
-        memset(qiov->iov[i].iov_base, 0, qiov->iov[i].iov_len);
-    }
-
     ret = sd_co_rw_vector(acb);
     if (ret <= 0) {
         qemu_aio_release(acb);
commit cddd4ac7a2d55a76f238b04314fdd3bfee00e268
Author: MORITA Kazutaka <morita.kazutaka at lab.ntt.co.jp>
Date:   Thu Jul 5 01:41:06 2012 +0900

    sheepdog: always use coroutine-based network functions
    
    This reduces some code duplication.
    
    Signed-off-by: MORITA Kazutaka <morita.kazutaka at lab.ntt.co.jp>
    Signed-off-by: Kevin Wolf <kwolf at redhat.com>

diff --git a/block/sheepdog.c b/block/sheepdog.c
index 809df39..465dc97 100644
--- a/block/sheepdog.c
+++ b/block/sheepdog.c
@@ -498,26 +498,6 @@ success:
     return fd;
 }
 
-static int send_req(int sockfd, SheepdogReq *hdr, void *data,
-                    unsigned int *wlen)
-{
-    int ret;
-
-    ret = qemu_send_full(sockfd, hdr, sizeof(*hdr), 0);
-    if (ret < sizeof(*hdr)) {
-        error_report("failed to send a req, %s", strerror(errno));
-        return -errno;
-    }
-
-    ret = qemu_send_full(sockfd, data, *wlen, 0);
-    if (ret < *wlen) {
-        error_report("failed to send a req, %s", strerror(errno));
-        ret = -errno;
-    }
-
-    return ret;
-}
-
 static coroutine_fn int send_co_req(int sockfd, SheepdogReq *hdr, void *data,
                                     unsigned int *wlen)
 {
@@ -537,49 +517,6 @@ static coroutine_fn int send_co_req(int sockfd, SheepdogReq *hdr, void *data,
     return ret;
 }
 
-static coroutine_fn int do_co_req(int sockfd, SheepdogReq *hdr, void *data,
-                                  unsigned int *wlen, unsigned int *rlen);
-
-static int do_req(int sockfd, SheepdogReq *hdr, void *data,
-                  unsigned int *wlen, unsigned int *rlen)
-{
-    int ret;
-
-    if (qemu_in_coroutine()) {
-        return do_co_req(sockfd, hdr, data, wlen, rlen);
-    }
-
-    socket_set_block(sockfd);
-    ret = send_req(sockfd, hdr, data, wlen);
-    if (ret < 0) {
-        goto out;
-    }
-
-    ret = qemu_recv_full(sockfd, hdr, sizeof(*hdr), 0);
-    if (ret < sizeof(*hdr)) {
-        error_report("failed to get a rsp, %s", strerror(errno));
-        ret = -errno;
-        goto out;
-    }
-
-    if (*rlen > hdr->data_length) {
-        *rlen = hdr->data_length;
-    }
-
-    if (*rlen) {
-        ret = qemu_recv_full(sockfd, data, *rlen, 0);
-        if (ret < *rlen) {
-            error_report("failed to get the data, %s", strerror(errno));
-            ret = -errno;
-            goto out;
-        }
-    }
-    ret = 0;
-out:
-    socket_set_nonblock(sockfd);
-    return ret;
-}
-
 static void restart_co_req(void *opaque)
 {
     Coroutine *co = opaque;
@@ -587,11 +524,26 @@ static void restart_co_req(void *opaque)
     qemu_coroutine_enter(co, NULL);
 }
 
-static coroutine_fn int do_co_req(int sockfd, SheepdogReq *hdr, void *data,
-                                  unsigned int *wlen, unsigned int *rlen)
+typedef struct SheepdogReqCo {
+    int sockfd;
+    SheepdogReq *hdr;
+    void *data;
+    unsigned int *wlen;
+    unsigned int *rlen;
+    int ret;
+    bool finished;
+} SheepdogReqCo;
+
+static coroutine_fn void do_co_req(void *opaque)
 {
     int ret;
     Coroutine *co;
+    SheepdogReqCo *srco = opaque;
+    int sockfd = srco->sockfd;
+    SheepdogReq *hdr = srco->hdr;
+    void *data = srco->data;
+    unsigned int *wlen = srco->wlen;
+    unsigned int *rlen = srco->rlen;
 
     co = qemu_coroutine_self();
     qemu_aio_set_fd_handler(sockfd, NULL, restart_co_req, NULL, co);
@@ -627,7 +579,36 @@ static coroutine_fn int do_co_req(int sockfd, SheepdogReq *hdr, void *data,
 out:
     qemu_aio_set_fd_handler(sockfd, NULL, NULL, NULL, NULL);
     socket_set_nonblock(sockfd);
-    return ret;
+
+    srco->ret = ret;
+    srco->finished = true;
+}
+
+static int do_req(int sockfd, SheepdogReq *hdr, void *data,
+                  unsigned int *wlen, unsigned int *rlen)
+{
+    Coroutine *co;
+    SheepdogReqCo srco = {
+        .sockfd = sockfd,
+        .hdr = hdr,
+        .data = data,
+        .wlen = wlen,
+        .rlen = rlen,
+        .ret = 0,
+        .finished = false,
+    };
+
+    if (qemu_in_coroutine()) {
+        do_co_req(&srco);
+    } else {
+        co = qemu_coroutine_create(do_co_req);
+        qemu_coroutine_enter(co, &srco);
+        while (!srco.finished) {
+            qemu_aio_wait();
+        }
+    }
+
+    return srco.ret;
 }
 
 static int coroutine_fn add_aio_request(BDRVSheepdogState *s, AIOReq *aio_req,
commit 83617103984eb4d81cf46c94435f3da2c6f33b55
Author: malc <av1474 at comtv.ru>
Date:   Mon Jul 16 18:08:36 2012 +0400

    audio: Unbreak capturing in mixemu case
    
    Signed-off-by: malc <av1474 at comtv.ru>

diff --git a/audio/audio.c b/audio/audio.c
index 583ee51..1c77389 100644
--- a/audio/audio.c
+++ b/audio/audio.c
@@ -818,6 +818,7 @@ static int audio_attach_capture (HWVoiceOut *hw)
         sw->active = hw->enabled;
         sw->conv = noop_conv;
         sw->ratio = ((int64_t) hw_cap->info.freq << 32) / sw->info.freq;
+        sw->vol = nominal_volume;
         sw->rate = st_rate_start (sw->info.freq, hw_cap->info.freq);
         if (!sw->rate) {
             dolog ("Could not start rate conversion for `%s'\n", SW_NAME (sw));
commit 3437e545857aa15e583e314471e9c86fc3e9a89c
Author: Blue Swirl <blauwirbel at gmail.com>
Date:   Sat Jul 7 14:40:18 2012 +0000

    qemu-log: fix x86 and user logging
    
    5726c27fa913296aafab9f50b912cea5b3709271 broke
    x86 specific options and user emulation specific stdio buffering.
    
    Always enable all log items. They may not be useful for non-x86 targets,
    but there's no harm either.
    
    Fix user emulation buffering by passing around a flag.
    
    Signed-off-by: Blue Swirl <blauwirbel at gmail.com>

diff --git a/qemu-log.c b/qemu-log.c
index 1ec70e7..396aafd 100644
--- a/qemu-log.c
+++ b/qemu-log.c
@@ -52,7 +52,7 @@ void qemu_log_mask(int mask, const char *fmt, ...)
 }
 
 /* enable or disable low levels log */
-void cpu_set_log(int log_flags)
+void qemu_set_log(int log_flags, bool use_own_buffers)
 {
     qemu_loglevel = log_flags;
     if (qemu_loglevel && !qemu_logfile) {
@@ -61,19 +61,20 @@ void cpu_set_log(int log_flags)
             perror(logfilename);
             _exit(1);
         }
-#if !defined(CONFIG_SOFTMMU)
         /* must avoid mmap() usage of glibc by setting a buffer "by hand" */
-        {
+        if (use_own_buffers) {
             static char logfile_buf[4096];
+
             setvbuf(qemu_logfile, logfile_buf, _IOLBF, sizeof(logfile_buf));
-        }
-#elif defined(_WIN32)
-        /* Win32 doesn't support line-buffering, so use unbuffered output. */
-        setvbuf(qemu_logfile, NULL, _IONBF, 0);
+        } else {
+#if defined(_WIN32)
+            /* Win32 doesn't support line-buffering, so use unbuffered output. */
+            setvbuf(qemu_logfile, NULL, _IONBF, 0);
 #else
-        setvbuf(qemu_logfile, NULL, _IOLBF, 0);
+            setvbuf(qemu_logfile, NULL, _IOLBF, 0);
 #endif
-        log_append = 1;
+            log_append = 1;
+        }
     }
     if (!qemu_loglevel && qemu_logfile) {
         fclose(qemu_logfile);
@@ -99,10 +100,7 @@ const CPULogItem cpu_log_items[] = {
     { CPU_LOG_TB_OP, "op",
       "show micro ops for each compiled TB" },
     { CPU_LOG_TB_OP_OPT, "op_opt",
-      "show micro ops "
-#ifdef TARGET_I386
-      "before eflags optimization and "
-#endif
+      "show micro ops (x86 only: before eflags optimization) and\n"
       "after liveness analysis" },
     { CPU_LOG_INT, "int",
       "show interrupts/exceptions in short format" },
@@ -110,16 +108,12 @@ const CPULogItem cpu_log_items[] = {
       "show trace before each executed TB (lots of logs)" },
     { CPU_LOG_TB_CPU, "cpu",
       "show CPU state before block translation" },
-#ifdef TARGET_I386
     { CPU_LOG_PCALL, "pcall",
-      "show protected mode far calls/returns/exceptions" },
+      "x86 only: show protected mode far calls/returns/exceptions" },
     { CPU_LOG_RESET, "cpu_reset",
-      "show CPU state before CPU resets" },
-#endif
-#ifdef DEBUG_IOPORT
+      "x86 only: show CPU state before CPU resets" },
     { CPU_LOG_IOPORT, "ioport",
       "show all i/o ports accesses" },
-#endif
     { LOG_UNIMP, "unimp",
       "log unimplemented functionality" },
     { 0, NULL, NULL },
diff --git a/qemu-log.h b/qemu-log.h
index 4cdc7c7..5ccecf3 100644
--- a/qemu-log.h
+++ b/qemu-log.h
@@ -142,7 +142,17 @@ typedef struct CPULogItem {
 
 extern const CPULogItem cpu_log_items[];
 
-void cpu_set_log(int log_flags);
+void qemu_set_log(int log_flags, bool use_own_buffers);
+
+static inline void cpu_set_log(int log_flags)
+{
+#ifdef CONFIG_USER_ONLY
+    qemu_set_log(log_flags, true);
+#else
+    qemu_set_log(log_flags, false);
+#endif
+}
+
 void cpu_set_log_filename(const char *filename);
 int cpu_str_to_log_mask(const char *str);
 
commit 39a4ef1be680d7e60ee3a1cf6ff328dba0326365
Merge: 9aa0ff0... 8f67aa8...
Author: Blue Swirl <blauwirbel at gmail.com>
Date:   Sat Jul 14 10:58:22 2012 +0000

    Merge branch 'trivial-patches' of git://github.com/stefanha/qemu
    
    * 'trivial-patches' of git://github.com/stefanha/qemu:
      make: Remove 'build-all' rule
      qemu-keymaps: Finnish keyboard mapping broken
      vnc: add a more descriptive error message
      bitops: Fix documentation
      megasas: mark mfi_frame_desc as 'static'

commit 9aa0ff0bf9588f86846d1045662f5d75b91552cb
Author: Jan Kiszka <jan.kiszka at siemens.com>
Date:   Wed Jul 4 19:49:54 2012 +0200

    vga: Implement blinking of text cursor
    
    Let the text cursor blink at 1.875 Hz, the original VGA cursor
    frequency. No timer is used, instead we rely on the fact that the
    display is updated periodically.
    
    Signed-off-by: Jan Kiszka <jan.kiszka at siemens.com>
    Signed-off-by: Blue Swirl <blauwirbel at gmail.com>

diff --git a/hw/vga.c b/hw/vga.c
index acb3f7d..f82ced8 100644
--- a/hw/vga.c
+++ b/hw/vga.c
@@ -38,6 +38,9 @@
 
 //#define DEBUG_BOCHS_VBE
 
+/* 16 state changes per vertical frame @60 Hz */
+#define VGA_TEXT_CURSOR_PERIOD_MS       (1000 * 2 * 16 / 60)
+
 /*
  * Video Graphics Array (VGA)
  *
@@ -1300,6 +1303,7 @@ static void vga_draw_text(VGACommonState *s, int full_update)
     uint32_t *ch_attr_ptr;
     vga_draw_glyph8_func *vga_draw_glyph8;
     vga_draw_glyph9_func *vga_draw_glyph9;
+    int64_t now = qemu_get_clock_ms(vm_clock);
 
     /* compute font data address (in plane 2) */
     v = s->sr[VGA_SEQ_CHARACTER_MAP];
@@ -1370,6 +1374,10 @@ static void vga_draw_text(VGACommonState *s, int full_update)
         s->cursor_end = s->cr[VGA_CRTC_CURSOR_END];
     }
     cursor_ptr = s->vram_ptr + (s->start_addr + cursor_offset) * 4;
+    if (now >= s->cursor_blink_time) {
+        s->cursor_blink_time = now + VGA_TEXT_CURSOR_PERIOD_MS / 2;
+        s->cursor_visible_phase = !s->cursor_visible_phase;
+    }
 
     depth_index = get_depth_index(s->ds);
     if (cw == 16)
@@ -1390,7 +1398,7 @@ static void vga_draw_text(VGACommonState *s, int full_update)
         cx_max = -1;
         for(cx = 0; cx < width; cx++) {
             ch_attr = *(uint16_t *)src;
-            if (full_update || ch_attr != *ch_attr_ptr) {
+            if (full_update || ch_attr != *ch_attr_ptr || src == cursor_ptr) {
                 if (cx < cx_min)
                     cx_min = cx;
                 if (cx > cx_max)
@@ -1420,7 +1428,8 @@ static void vga_draw_text(VGACommonState *s, int full_update)
                                     font_ptr, cheight, fgcol, bgcol, dup9);
                 }
                 if (src == cursor_ptr &&
-                    !(s->cr[VGA_CRTC_CURSOR_START] & 0x20)) {
+                    !(s->cr[VGA_CRTC_CURSOR_START] & 0x20) &&
+                    s->cursor_visible_phase) {
                     int line_start, line_last, h;
                     /* draw the cursor */
                     line_start = s->cr[VGA_CRTC_CURSOR_START] & 0x1f;
@@ -1884,6 +1893,7 @@ static void vga_update_display(void *opaque)
         }
         if (graphic_mode != s->graphic_mode) {
             s->graphic_mode = graphic_mode;
+            s->cursor_blink_time = qemu_get_clock_ms(vm_clock);
             full_update = 1;
         }
         switch(graphic_mode) {
diff --git a/hw/vga_int.h b/hw/vga_int.h
index 3b38764..8938093 100644
--- a/hw/vga_int.h
+++ b/hw/vga_int.h
@@ -156,6 +156,8 @@ typedef struct VGACommonState {
     uint32_t last_scr_width, last_scr_height; /* in pixels */
     uint32_t last_depth; /* in bits */
     uint8_t cursor_start, cursor_end;
+    bool cursor_visible_phase;
+    int64_t cursor_blink_time;
     uint32_t cursor_offset;
     unsigned int (*rgb_to_pixel)(unsigned int r,
                                  unsigned int g, unsigned b);
commit bf1bed81c9c8e0c2f3b5f16de4757ee2b5fd610a
Author: Jan Kiszka <jan.kiszka at siemens.com>
Date:   Tue Jul 10 22:00:55 2012 +0200

    console: Implementing blinking of cursor
    
    Let the text console cursor blink at 2 HZ.
    
    Signed-off-by: Jan Kiszka <jan.kiszka at siemens.com>
    Signed-off-by: Blue Swirl <blauwirbel at gmail.com>

diff --git a/console.c b/console.c
index 6a463f5..4525cc7 100644
--- a/console.c
+++ b/console.c
@@ -28,6 +28,7 @@
 //#define DEBUG_CONSOLE
 #define DEFAULT_BACKSCROLL 512
 #define MAX_CONSOLES 12
+#define CONSOLE_CURSOR_PERIOD 500
 
 #define QEMU_RGBA(r, g, b, a) (((a) << 24) | ((r) << 16) | ((g) << 8) | (b))
 #define QEMU_RGB(r, g, b) QEMU_RGBA(r, g, b, 0xff)
@@ -139,6 +140,8 @@ struct TextConsole {
     TextCell *cells;
     int text_x[2], text_y[2], cursor_invalidate;
     int echo;
+    bool cursor_visible_phase;
+    QEMUTimer *cursor_timer;
 
     int update_x0;
     int update_y0;
@@ -615,7 +618,7 @@ static void console_show_cursor(TextConsole *s, int show)
             y += s->total_height;
         if (y < s->height) {
             c = &s->cells[y1 * s->width + x];
-            if (show) {
+            if (show && s->cursor_visible_phase) {
                 TextAttributes t_attrib = s->t_attrib_default;
                 t_attrib.invers = !(t_attrib.invers); /* invert fg and bg */
                 vga_putcharxy(s->ds, x, y, c->ch, &t_attrib);
@@ -1083,6 +1086,10 @@ void console_select(unsigned int index)
     s = consoles[index];
     if (s) {
         DisplayState *ds = s->ds;
+
+        if (active_console->cursor_timer) {
+            qemu_del_timer(active_console->cursor_timer);
+        }
         active_console = s;
         if (ds_get_bits_per_pixel(s->ds)) {
             ds->surface = qemu_resize_displaysurface(ds, s->g_width, s->g_height);
@@ -1090,6 +1097,10 @@ void console_select(unsigned int index)
             s->ds->surface->width = s->width;
             s->ds->surface->height = s->height;
         }
+        if (s->cursor_timer) {
+            qemu_mod_timer(s->cursor_timer,
+                   qemu_get_clock_ms(rt_clock) + CONSOLE_CURSOR_PERIOD / 2);
+        }
         dpy_resize(s->ds);
         vga_hw_invalidate();
     }
@@ -1454,6 +1465,16 @@ static void text_console_set_echo(CharDriverState *chr, bool echo)
     s->echo = echo;
 }
 
+static void text_console_update_cursor(void *opaque)
+{
+    TextConsole *s = opaque;
+
+    s->cursor_visible_phase = !s->cursor_visible_phase;
+    vga_hw_invalidate();
+    qemu_mod_timer(s->cursor_timer,
+                   qemu_get_clock_ms(rt_clock) + CONSOLE_CURSOR_PERIOD / 2);
+}
+
 static void text_console_do_init(CharDriverState *chr, DisplayState *ds)
 {
     TextConsole *s;
@@ -1482,6 +1503,9 @@ static void text_console_do_init(CharDriverState *chr, DisplayState *ds)
         s->g_height = ds_get_height(s->ds);
     }
 
+    s->cursor_timer =
+        qemu_new_timer_ms(rt_clock, text_console_update_cursor, s);
+
     s->hw_invalidate = text_console_invalidate;
     s->hw_text_update = text_console_update;
     s->hw = s;
commit 417c9d72d48275d19c60861896efd4962d21aca2
Author: Alexander Graf <agraf at suse.de>
Date:   Mon Jul 9 14:38:08 2012 +0200

    configure: add -Werror to QEMU_CFLAGS early
    
    We want all configure tests pass with -Werror if it is enabled. So we
    need to update QEMU_CFLAGS early on to make sure we also pass it in to
    all the compile test jobs.
    
    This fixes a warning-became-error bug in nss for me with the default
    configuration:
    
    In file included from /usr/include/nss3/pkcs11t.h:1780,
                     from /usr/include/nss3/keythi.h:41,
                     from /usr/include/nss3/keyt.h:41,
                     from /usr/include/nss3/pk11pub.h:43,
                     from libcacard/vcard_emul_nss.c:21:
    /usr/include/nss3/pkcs11n.h:365:26: error: "__GNUC_MINOR" is not defined
    
    Signed-off-by: Alexander Graf <agraf at suse.de>
    Acked-by: Gerd Hoffmann <kraxel at redhat.com>
    Signed-off-by: Blue Swirl <blauwirbel at gmail.com>

diff --git a/configure b/configure
index 32a8290..0a3896e 100755
--- a/configure
+++ b/configure
@@ -1139,10 +1139,26 @@ else
     exit 1
 fi
 
+# Consult white-list to determine whether to enable werror
+# by default.  Only enable by default for git builds
+z_version=`cut -f3 -d. $source_path/VERSION`
+
+if test -z "$werror" ; then
+    if test "$z_version" = "50" -a \
+        "$linux" = "yes" ; then
+        werror="yes"
+    else
+        werror="no"
+    fi
+fi
+
 gcc_flags="-Wold-style-declaration -Wold-style-definition -Wtype-limits"
 gcc_flags="-Wformat-security -Wformat-y2k -Winit-self -Wignored-qualifiers $gcc_flags"
 gcc_flags="-Wmissing-include-dirs -Wempty-body -Wnested-externs $gcc_flags"
 gcc_flags="-fstack-protector-all -Wendif-labels $gcc_flags"
+if test "$werror" = "yes" ; then
+    gcc_flags="-Werror $gcc_flags"
+fi
 cat > $TMPC << EOF
 int main(void) { return 0; }
 EOF
@@ -2573,7 +2589,7 @@ if test "$libiscsi" != "no" ; then
 #include <iscsi/iscsi.h>
 int main(void) { iscsi_unmap_sync(NULL,0,0,0,NULL,0); return 0; }
 EOF
-  if compile_prog "-Werror" "-liscsi" ; then
+  if compile_prog "" "-liscsi" ; then
     libiscsi="yes"
     LIBS="$LIBS -liscsi"
   else
@@ -2877,19 +2893,6 @@ if test "$debug" = "no" ; then
   CFLAGS="-O2 -D_FORTIFY_SOURCE=2 $CFLAGS"
 fi
 
-# Consult white-list to determine whether to enable werror
-# by default.  Only enable by default for git builds
-z_version=`cut -f3 -d. $source_path/VERSION`
-
-if test -z "$werror" ; then
-    if test "$z_version" = "50" -a \
-        "$linux" = "yes" ; then
-        werror="yes"
-    else
-        werror="no"
-    fi
-fi
-
 # Disable zero malloc errors for official releases unless explicitly told to
 # enable/disable
 if test -z "$zero_malloc" ; then
@@ -2900,10 +2903,6 @@ if test -z "$zero_malloc" ; then
     fi
 fi
 
-if test "$werror" = "yes" ; then
-    QEMU_CFLAGS="-Werror $QEMU_CFLAGS"
-fi
-
 if test "$solaris" = "no" ; then
     if $ld --version 2>/dev/null | grep "GNU ld" >/dev/null 2>/dev/null ; then
         LDFLAGS="-Wl,--warn-common $LDFLAGS"
commit 66f27e63ae3d91876d348e38fb5af4b48ae6b8fb
Author: Peter Maydell <peter.maydell at linaro.org>
Date:   Mon Jun 25 16:52:24 2012 +0100

    monitor: Use TARGET_PRI*PHYS to avoid TARGET_PHYS_ADDR_BITS ifdef
    
    Now we have TARGET_PRI*PHYS for printing target_phys_addr_t values,
    we can use them in monitor.c rather than having duplicate code
    in two arms of a TARGET_PHYS_ADDR_BITS ifdef.
    
    Signed-off-by: Peter Maydell <peter.maydell at linaro.org>
    Reviewed-by: Andreas Färber <afaerber at suse.de>
    Signed-off-by: Blue Swirl <blauwirbel at gmail.com>

diff --git a/monitor.c b/monitor.c
index f6107ba..188c03d 100644
--- a/monitor.c
+++ b/monitor.c
@@ -1262,45 +1262,24 @@ static void do_print(Monitor *mon, const QDict *qdict)
     int format = qdict_get_int(qdict, "format");
     target_phys_addr_t val = qdict_get_int(qdict, "val");
 
-#if TARGET_PHYS_ADDR_BITS == 32
     switch(format) {
     case 'o':
-        monitor_printf(mon, "%#o", val);
+        monitor_printf(mon, "%#" TARGET_PRIoPHYS, val);
         break;
     case 'x':
-        monitor_printf(mon, "%#x", val);
+        monitor_printf(mon, "%#" TARGET_PRIxPHYS, val);
         break;
     case 'u':
-        monitor_printf(mon, "%u", val);
+        monitor_printf(mon, "%" TARGET_PRIuPHYS, val);
         break;
     default:
     case 'd':
-        monitor_printf(mon, "%d", val);
+        monitor_printf(mon, "%" TARGET_PRIdPHYS, val);
         break;
     case 'c':
         monitor_printc(mon, val);
         break;
     }
-#else
-    switch(format) {
-    case 'o':
-        monitor_printf(mon, "%#" PRIo64, val);
-        break;
-    case 'x':
-        monitor_printf(mon, "%#" PRIx64, val);
-        break;
-    case 'u':
-        monitor_printf(mon, "%" PRIu64, val);
-        break;
-    default:
-    case 'd':
-        monitor_printf(mon, "%" PRId64, val);
-        break;
-    case 'c':
-        monitor_printc(mon, val);
-        break;
-    }
-#endif
     monitor_printf(mon, "\n");
 }
 
commit c1950a4e95c57c47a74d010c7c0727320ef2a550
Author: Peter Maydell <peter.maydell at linaro.org>
Date:   Mon Jun 25 16:52:23 2012 +0100

    hw/sh_serial: Use TARGET_PRIxPHYS rather than %x for physaddr
    
    Switch a format string from %x to TARGET_PRIxPHYS so that it will
    continue to work even if target_phys_addr_t is changed
    to 64 bits in the future.
    
    Signed-off-by: Peter Maydell <peter.maydell at linaro.org>
    Reviewed-by: Andreas Färber <afaerber at suse.de>
    Signed-off-by: Blue Swirl <blauwirbel at gmail.com>

diff --git a/hw/sh_serial.c b/hw/sh_serial.c
index 43b0eb1..1d1883d 100644
--- a/hw/sh_serial.c
+++ b/hw/sh_serial.c
@@ -186,7 +186,8 @@ static void sh_serial_write(void *opaque, target_phys_addr_t offs,
         }
     }
 
-    fprintf(stderr, "sh_serial: unsupported write to 0x%02x\n", offs);
+    fprintf(stderr, "sh_serial: unsupported write to 0x%02"
+            TARGET_PRIxPHYS "\n", offs);
     abort();
 }
 
@@ -287,7 +288,8 @@ static uint64_t sh_serial_read(void *opaque, target_phys_addr_t offs,
 #endif
 
     if (ret & ~((1 << 16) - 1)) {
-        fprintf(stderr, "sh_serial: unsupported read from 0x%02x\n", offs);
+        fprintf(stderr, "sh_serial: unsupported read from 0x%02"
+                TARGET_PRIxPHYS "\n", offs);
         abort();
     }
 
commit cdb30d446f6a643c48c4a6a8ecc5d9eb7c6d6647
Author: Peter Maydell <peter.maydell at linaro.org>
Date:   Mon Jun 25 16:52:22 2012 +0100

    hw/omap.h: Use TARGET_PRIxPHYS to define OMAP_FMT_plx
    
    Use the new TARGET_PRIxPHYS macro to avoid the need to define an
    OMAP_FMT_plx macro whose expansion depends directly on
    TARGET_PHYS_ADDR_BITS.
    
    Signed-off-by: Peter Maydell <peter.maydell at linaro.org>
    Acked-by: Andreas Färber <afaerber at suse.de>
    Signed-off-by: Blue Swirl <blauwirbel at gmail.com>

diff --git a/hw/omap.h b/hw/omap.h
index 3d98941..413851b 100644
--- a/hw/omap.h
+++ b/hw/omap.h
@@ -942,13 +942,7 @@ struct omap_mpu_state_s *omap2420_mpu_init(MemoryRegion *sysmem,
                 unsigned long sdram_size,
                 const char *core);
 
-# if TARGET_PHYS_ADDR_BITS == 32
-#  define OMAP_FMT_plx "%#08x"
-# elif TARGET_PHYS_ADDR_BITS == 64
-#  define OMAP_FMT_plx "%#08" PRIx64
-# else
-#  error TARGET_PHYS_ADDR_BITS undefined
-# endif
+#define OMAP_FMT_plx "%#08" TARGET_PRIxPHYS
 
 uint32_t omap_badwidth_read8(void *opaque, target_phys_addr_t addr);
 void omap_badwidth_write8(void *opaque, target_phys_addr_t addr,
commit 1e9be4b4fed08804e645e6465d38cdb686ebe9de
Author: Peter Maydell <peter.maydell at linaro.org>
Date:   Mon Jun 25 16:52:21 2012 +0100

    targphys.h: Define TARGET_PRI*PHYS format specifier macros
    
    Define a set of TARGET_PRI*PHYS format specifier macros for working
    with target_phys_addr_t types. These follow the standard pattern
    for such macros, and are more flexible than TARGET_FMT_plx, which
    does not allow specification of field widths.
    
    Suggested-by: Andreas Färber <afaerber at suse.de>
    Signed-off-by: Peter Maydell <peter.maydell at linaro.org>
    Acked-by: Andreas Färber <afaerber at suse.de>
    Signed-off-by: Blue Swirl <blauwirbel at gmail.com>

diff --git a/targphys.h b/targphys.h
index 95648d6..bd4938f 100644
--- a/targphys.h
+++ b/targphys.h
@@ -11,10 +11,26 @@
 typedef uint32_t target_phys_addr_t;
 #define TARGET_PHYS_ADDR_MAX UINT32_MAX
 #define TARGET_FMT_plx "%08x"
+/* Format strings for printing target_phys_addr_t types.
+ * These are recommended over the less flexible TARGET_FMT_plx,
+ * which is retained for the benefit of existing code.
+ */
+#define TARGET_PRIdPHYS PRId32
+#define TARGET_PRIiPHYS PRIi32
+#define TARGET_PRIoPHYS PRIo32
+#define TARGET_PRIuPHYS PRIu32
+#define TARGET_PRIxPHYS PRIx32
+#define TARGET_PRIXPHYS PRIX32
 #elif TARGET_PHYS_ADDR_BITS == 64
 typedef uint64_t target_phys_addr_t;
 #define TARGET_PHYS_ADDR_MAX UINT64_MAX
 #define TARGET_FMT_plx "%016" PRIx64
+#define TARGET_PRIdPHYS PRId64
+#define TARGET_PRIiPHYS PRIi64
+#define TARGET_PRIoPHYS PRIo64
+#define TARGET_PRIuPHYS PRIu64
+#define TARGET_PRIxPHYS PRIx64
+#define TARGET_PRIXPHYS PRIX64
 #endif
 #endif
 
commit 636bd289398d203b2be5542279d24459767d6d4c
Author: Peter Maydell <peter.maydell at linaro.org>
Date:   Mon Jun 25 04:55:55 2012 +0000

    disas: Fix printing of addresses in disassembly
    
    In our disassembly code, the bfd_vma type is always 64 bits,
    even if the target's virtual address width is only 32 bits. This
    means that when we print out addresses we need to truncate them
    to 32 bits, to avoid odd output which has incorrectly sign-extended
    a value to 64 bits, for instance this ARM example:
        0x80479a60:  e59f4088     ldr  r4, [pc, #136]  ; 0xffffffff80479a4f
    
    (It would also be possible to truncate before passing the address
    to info->print_address_func(), but truncating in the final print
    function is the same approach that binutils takes to this problem.)
    
    Signed-off-by: Peter Maydell <peter.maydell at linaro.org>
    Reviewed-by: Andreas Färber <afaerber at suse.de>
    Signed-off-by: Blue Swirl <blauwirbel at gmail.com>

diff --git a/disas.c b/disas.c
index 93d8d30..7b2acc9 100644
--- a/disas.c
+++ b/disas.c
@@ -64,6 +64,22 @@ generic_print_address (bfd_vma addr, struct disassemble_info *info)
     (*info->fprintf_func) (info->stream, "0x%" PRIx64, addr);
 }
 
+/* Print address in hex, truncated to the width of a target virtual address. */
+static void
+generic_print_target_address(bfd_vma addr, struct disassemble_info *info)
+{
+    uint64_t mask = ~0ULL >> (64 - TARGET_VIRT_ADDR_SPACE_BITS);
+    generic_print_address(addr & mask, info);
+}
+
+/* Print address in hex, truncated to the width of a host virtual address. */
+static void
+generic_print_host_address(bfd_vma addr, struct disassemble_info *info)
+{
+    uint64_t mask = ~0ULL >> (64 - (sizeof(void *) * 8));
+    generic_print_address(addr & mask, info);
+}
+
 /* Just return the given address.  */
 
 int
@@ -154,6 +170,7 @@ void target_disas(FILE *out, target_ulong code, target_ulong size, int flags)
     disasm_info.read_memory_func = target_read_memory;
     disasm_info.buffer_vma = code;
     disasm_info.buffer_length = size;
+    disasm_info.print_address_func = generic_print_target_address;
 
 #ifdef TARGET_WORDS_BIGENDIAN
     disasm_info.endian = BFD_ENDIAN_BIG;
@@ -274,6 +291,7 @@ void disas(FILE *out, void *code, unsigned long size)
     int (*print_insn)(bfd_vma pc, disassemble_info *info);
 
     INIT_DISASSEMBLE_INFO(disasm_info, out, fprintf);
+    disasm_info.print_address_func = generic_print_host_address;
 
     disasm_info.buffer = code;
     disasm_info.buffer_vma = (uintptr_t)code;
@@ -386,6 +404,7 @@ void monitor_disas(Monitor *mon, CPUArchState *env,
     monitor_disas_env = env;
     monitor_disas_is_physical = is_physical;
     disasm_info.read_memory_func = monitor_read_memory;
+    disasm_info.print_address_func = generic_print_target_address;
 
     disasm_info.buffer_vma = pc;
 
commit fabaaf1d1f3f793999257cb16b509e32dfc1de71
Author: Hervé Poussineau <hpoussin at reactos.org>
Date:   Mon Jul 9 12:02:31 2012 +0200

    esp: add AMD PCscsi emulation (PCI SCSI adapter)
    
    The PCI version is supported in lots of Operating Systems,
    and has been successfully tested on:
    - MS DOS 6.22 (using DC390 driver)
    - MS Windows 3.11 (using DC390 driver)
    - MS Windows 98 SE (using default driver)
    - MS Windows NT 3.1 (using DC390 driver)
    - MS Windows NT 4.0 (using default driver)
    
    Signed-off-by: Hervé Poussineau <hpoussin at reactos.org>
    Signed-off-by: Blue Swirl <blauwirbel at gmail.com>

diff --git a/default-configs/i386-softmmu.mak b/default-configs/i386-softmmu.mak
index 2c78175..fee8cde 100644
--- a/default-configs/i386-softmmu.mak
+++ b/default-configs/i386-softmmu.mak
@@ -25,3 +25,4 @@ CONFIG_HPET=y
 CONFIG_APPLESMC=y
 CONFIG_I8259=y
 CONFIG_PFLASH_CFI01=y
+CONFIG_ESP=y
diff --git a/hw/esp.c b/hw/esp.c
index ec40d93..c6422ad 100644
--- a/hw/esp.c
+++ b/hw/esp.c
@@ -2,6 +2,7 @@
  * QEMU ESP/NCR53C9x emulation
  *
  * Copyright (c) 2005-2006 Fabrice Bellard
+ * Copyright (c) 2012 Herve Poussineau
  *
  * Permission is hereby granted, free of charge, to any person obtaining a copy
  * of this software and associated documentation files (the "Software"), to deal
@@ -23,6 +24,7 @@
  */
 
 #include "sysbus.h"
+#include "pci.h"
 #include "scsi.h"
 #include "esp.h"
 #include "trace.h"
@@ -142,6 +144,7 @@ struct ESPState {
 #define CFG1_RESREPT 0x40
 
 #define TCHI_FAS100A 0x4
+#define TCHI_AM53C974 0x12
 
 static void esp_raise_irq(ESPState *s)
 {
@@ -820,9 +823,372 @@ static TypeInfo sysbus_esp_info = {
     .class_init    = sysbus_esp_class_init,
 };
 
+#define DMA_CMD   0x0
+#define DMA_STC   0x1
+#define DMA_SPA   0x2
+#define DMA_WBC   0x3
+#define DMA_WAC   0x4
+#define DMA_STAT  0x5
+#define DMA_SMDLA 0x6
+#define DMA_WMAC  0x7
+
+#define DMA_CMD_MASK   0x03
+#define DMA_CMD_DIAG   0x04
+#define DMA_CMD_MDL    0x10
+#define DMA_CMD_INTE_P 0x20
+#define DMA_CMD_INTE_D 0x40
+#define DMA_CMD_DIR    0x80
+
+#define DMA_STAT_PWDN    0x01
+#define DMA_STAT_ERROR   0x02
+#define DMA_STAT_ABORT   0x04
+#define DMA_STAT_DONE    0x08
+#define DMA_STAT_SCSIINT 0x10
+#define DMA_STAT_BCMBLT  0x20
+
+#define SBAC_STATUS 0x1000
+
+typedef struct PCIESPState {
+    PCIDevice dev;
+    MemoryRegion io;
+    uint32_t dma_regs[8];
+    uint32_t sbac;
+    ESPState esp;
+} PCIESPState;
+
+static void esp_pci_handle_idle(PCIESPState *pci, uint32_t val)
+{
+    trace_esp_pci_dma_idle(val);
+    esp_dma_enable(&pci->esp, 0, 0);
+}
+
+static void esp_pci_handle_blast(PCIESPState *pci, uint32_t val)
+{
+    trace_esp_pci_dma_blast(val);
+    qemu_log_mask(LOG_UNIMP, "am53c974: cmd BLAST not implemented\n");
+}
+
+static void esp_pci_handle_abort(PCIESPState *pci, uint32_t val)
+{
+    trace_esp_pci_dma_abort(val);
+    if (pci->esp.current_req) {
+        scsi_req_cancel(pci->esp.current_req);
+    }
+}
+
+static void esp_pci_handle_start(PCIESPState *pci, uint32_t val)
+{
+    trace_esp_pci_dma_start(val);
+
+    pci->dma_regs[DMA_WBC] = pci->dma_regs[DMA_STC];
+    pci->dma_regs[DMA_WAC] = pci->dma_regs[DMA_SPA];
+    pci->dma_regs[DMA_WMAC] = pci->dma_regs[DMA_SMDLA];
+
+    pci->dma_regs[DMA_STAT] &= ~(DMA_STAT_BCMBLT | DMA_STAT_SCSIINT
+                               | DMA_STAT_DONE | DMA_STAT_ABORT
+                               | DMA_STAT_ERROR | DMA_STAT_PWDN);
+
+    esp_dma_enable(&pci->esp, 0, 1);
+}
+
+static void esp_pci_dma_write(PCIESPState *pci, uint32_t saddr, uint32_t val)
+{
+    trace_esp_pci_dma_write(saddr, pci->dma_regs[saddr], val);
+    switch (saddr) {
+    case DMA_CMD:
+        pci->dma_regs[saddr] = val;
+        switch (val & DMA_CMD_MASK) {
+        case 0x0: /* IDLE */
+            esp_pci_handle_idle(pci, val);
+            break;
+        case 0x1: /* BLAST */
+            esp_pci_handle_blast(pci, val);
+            break;
+        case 0x2: /* ABORT */
+            esp_pci_handle_abort(pci, val);
+            break;
+        case 0x3: /* START */
+            esp_pci_handle_start(pci, val);
+            break;
+        default: /* can't happen */
+            abort();
+        }
+        break;
+    case DMA_STC:
+    case DMA_SPA:
+    case DMA_SMDLA:
+        pci->dma_regs[saddr] = val;
+        break;
+    case DMA_STAT:
+        if (!(pci->sbac & SBAC_STATUS)) {
+            /* clear some bits on write */
+            uint32_t mask = DMA_STAT_ERROR | DMA_STAT_ABORT | DMA_STAT_DONE;
+            pci->dma_regs[DMA_STAT] &= ~(val & mask);
+        }
+        break;
+    default:
+        trace_esp_pci_error_invalid_write_dma(val, saddr);
+        return;
+    }
+}
+
+static uint32_t esp_pci_dma_read(PCIESPState *pci, uint32_t saddr)
+{
+    uint32_t val;
+
+    val = pci->dma_regs[saddr];
+    if (saddr == DMA_STAT) {
+        if (pci->esp.rregs[ESP_RSTAT] & STAT_INT) {
+            val |= DMA_STAT_SCSIINT;
+        }
+        if (pci->sbac & SBAC_STATUS) {
+            pci->dma_regs[DMA_STAT] &= ~(DMA_STAT_ERROR | DMA_STAT_ABORT |
+                                         DMA_STAT_DONE);
+        }
+    }
+
+    trace_esp_pci_dma_read(saddr, val);
+    return val;
+}
+
+static void esp_pci_io_write(void *opaque, target_phys_addr_t addr,
+                             uint64_t val, unsigned int size)
+{
+    PCIESPState *pci = opaque;
+
+    if (size < 4 || addr & 3) {
+        /* need to upgrade request: we only support 4-bytes accesses */
+        uint32_t current = 0, mask;
+        int shift;
+
+        if (addr < 0x40) {
+            current = pci->esp.wregs[addr >> 2];
+        } else if (addr < 0x60) {
+            current = pci->dma_regs[(addr - 0x40) >> 2];
+        } else if (addr < 0x74) {
+            current = pci->sbac;
+        }
+
+        shift = (4 - size) * 8;
+        mask = (~(uint32_t)0 << shift) >> shift;
+
+        shift = ((4 - (addr & 3)) & 3) * 8;
+        val <<= shift;
+        val |= current & ~(mask << shift);
+        addr &= ~3;
+        size = 4;
+    }
+
+    if (addr < 0x40) {
+        /* SCSI core reg */
+        esp_reg_write(&pci->esp, addr >> 2, val);
+    } else if (addr < 0x60) {
+        /* PCI DMA CCB */
+        esp_pci_dma_write(pci, (addr - 0x40) >> 2, val);
+    } else if (addr == 0x70) {
+        /* DMA SCSI Bus and control */
+        trace_esp_pci_sbac_write(pci->sbac, val);
+        pci->sbac = val;
+    } else {
+        trace_esp_pci_error_invalid_write((int)addr);
+    }
+}
+
+static uint64_t esp_pci_io_read(void *opaque, target_phys_addr_t addr,
+                                unsigned int size)
+{
+    PCIESPState *pci = opaque;
+    uint32_t ret;
+
+    if (addr < 0x40) {
+        /* SCSI core reg */
+        ret = esp_reg_read(&pci->esp, addr >> 2);
+    } else if (addr < 0x60) {
+        /* PCI DMA CCB */
+        ret = esp_pci_dma_read(pci, (addr - 0x40) >> 2);
+    } else if (addr == 0x70) {
+        /* DMA SCSI Bus and control */
+        trace_esp_pci_sbac_read(pci->sbac);
+        ret = pci->sbac;
+    } else {
+        /* Invalid region */
+        trace_esp_pci_error_invalid_read((int)addr);
+        ret = 0;
+    }
+
+    /* give only requested data */
+    ret >>= (addr & 3) * 8;
+    ret &= ~(~(uint64_t)0 << (8 * size));
+
+    return ret;
+}
+
+static void esp_pci_dma_memory_rw(PCIESPState *pci, uint8_t *buf, int len,
+                                  DMADirection dir)
+{
+    dma_addr_t addr;
+    DMADirection expected_dir;
+
+    if (pci->dma_regs[DMA_CMD] & DMA_CMD_DIR) {
+        expected_dir = DMA_DIRECTION_FROM_DEVICE;
+    } else {
+        expected_dir = DMA_DIRECTION_TO_DEVICE;
+    }
+
+    if (dir != expected_dir) {
+        trace_esp_pci_error_invalid_dma_direction();
+        return;
+    }
+
+    if (pci->dma_regs[DMA_STAT] & DMA_CMD_MDL) {
+        qemu_log_mask(LOG_UNIMP, "am53c974: MDL transfer not implemented\n");
+    }
+
+    addr = pci->dma_regs[DMA_SPA];
+    if (pci->dma_regs[DMA_WBC] < len) {
+        len = pci->dma_regs[DMA_WBC];
+    }
+
+    pci_dma_rw(&pci->dev, addr, buf, len, dir);
+
+    /* update status registers */
+    pci->dma_regs[DMA_WBC] -= len;
+    pci->dma_regs[DMA_WAC] += len;
+}
+
+static void esp_pci_dma_memory_read(void *opaque, uint8_t *buf, int len)
+{
+    PCIESPState *pci = opaque;
+    esp_pci_dma_memory_rw(pci, buf, len, DMA_DIRECTION_TO_DEVICE);
+}
+
+static void esp_pci_dma_memory_write(void *opaque, uint8_t *buf, int len)
+{
+    PCIESPState *pci = opaque;
+    esp_pci_dma_memory_rw(pci, buf, len, DMA_DIRECTION_FROM_DEVICE);
+}
+
+static const MemoryRegionOps esp_pci_io_ops = {
+    .read = esp_pci_io_read,
+    .write = esp_pci_io_write,
+    .endianness = DEVICE_LITTLE_ENDIAN,
+    .impl = {
+        .min_access_size = 1,
+        .max_access_size = 4,
+    },
+};
+
+static void esp_pci_hard_reset(DeviceState *dev)
+{
+    PCIESPState *pci = DO_UPCAST(PCIESPState, dev.qdev, dev);
+    esp_hard_reset(&pci->esp);
+    pci->dma_regs[DMA_CMD] &= ~(DMA_CMD_DIR | DMA_CMD_INTE_D | DMA_CMD_INTE_P
+                              | DMA_CMD_MDL | DMA_CMD_DIAG | DMA_CMD_MASK);
+    pci->dma_regs[DMA_WBC] &= ~0xffff;
+    pci->dma_regs[DMA_WAC] = 0xffffffff;
+    pci->dma_regs[DMA_STAT] &= ~(DMA_STAT_BCMBLT | DMA_STAT_SCSIINT
+                               | DMA_STAT_DONE | DMA_STAT_ABORT
+                               | DMA_STAT_ERROR);
+    pci->dma_regs[DMA_WMAC] = 0xfffffffd;
+}
+
+static const VMStateDescription vmstate_esp_pci_scsi = {
+    .name = "pciespscsi",
+    .version_id = 0,
+    .minimum_version_id = 0,
+    .minimum_version_id_old = 0,
+    .fields = (VMStateField[]) {
+        VMSTATE_PCI_DEVICE(dev, PCIESPState),
+        VMSTATE_BUFFER_UNSAFE(dma_regs, PCIESPState, 0, 8 * sizeof(uint32_t)),
+        VMSTATE_STRUCT(esp, PCIESPState, 0, vmstate_esp, ESPState),
+        VMSTATE_END_OF_LIST()
+    }
+};
+
+static void esp_pci_command_complete(SCSIRequest *req, uint32_t status,
+                                     size_t resid)
+{
+    ESPState *s = req->hba_private;
+    PCIESPState *pci = container_of(s, PCIESPState, esp);
+
+    esp_command_complete(req, status, resid);
+    pci->dma_regs[DMA_WBC] = 0;
+    pci->dma_regs[DMA_STAT] |= DMA_STAT_DONE;
+}
+
+static const struct SCSIBusInfo esp_pci_scsi_info = {
+    .tcq = false,
+    .max_target = ESP_MAX_DEVS,
+    .max_lun = 7,
+
+    .transfer_data = esp_transfer_data,
+    .complete = esp_pci_command_complete,
+    .cancel = esp_request_cancelled,
+};
+
+static int esp_pci_scsi_init(PCIDevice *dev)
+{
+    PCIESPState *pci = DO_UPCAST(PCIESPState, dev, dev);
+    ESPState *s = &pci->esp;
+    uint8_t *pci_conf;
+
+    pci_conf = pci->dev.config;
+
+    /* Interrupt pin A */
+    pci_conf[PCI_INTERRUPT_PIN] = 0x01;
+
+    s->dma_memory_read = esp_pci_dma_memory_read;
+    s->dma_memory_write = esp_pci_dma_memory_write;
+    s->dma_opaque = pci;
+    s->chip_id = TCHI_AM53C974;
+    memory_region_init_io(&pci->io, &esp_pci_io_ops, pci, "esp-io", 0x80);
+
+    pci_register_bar(&pci->dev, 0, PCI_BASE_ADDRESS_SPACE_IO, &pci->io);
+    s->irq = pci->dev.irq[0];
+
+    scsi_bus_new(&s->bus, &dev->qdev, &esp_pci_scsi_info);
+    if (!dev->qdev.hotplugged) {
+        return scsi_bus_legacy_handle_cmdline(&s->bus);
+    }
+    return 0;
+}
+
+static int esp_pci_scsi_uninit(PCIDevice *d)
+{
+    PCIESPState *pci = DO_UPCAST(PCIESPState, dev, d);
+
+    memory_region_destroy(&pci->io);
+
+    return 0;
+}
+
+static void esp_pci_class_init(ObjectClass *klass, void *data)
+{
+    DeviceClass *dc = DEVICE_CLASS(klass);
+    PCIDeviceClass *k = PCI_DEVICE_CLASS(klass);
+
+    k->init = esp_pci_scsi_init;
+    k->exit = esp_pci_scsi_uninit;
+    k->vendor_id = PCI_VENDOR_ID_AMD;
+    k->device_id = PCI_DEVICE_ID_AMD_SCSI;
+    k->revision = 0x10;
+    k->class_id = PCI_CLASS_STORAGE_SCSI;
+    dc->desc = "AMD Am53c974 PCscsi-PCI SCSI adapter";
+    dc->reset = esp_pci_hard_reset;
+    dc->vmsd = &vmstate_esp_pci_scsi;
+}
+
+static TypeInfo esp_pci_info = {
+    .name = "am53c974",
+    .parent = TYPE_PCI_DEVICE,
+    .instance_size = sizeof(PCIESPState),
+    .class_init = esp_pci_class_init,
+};
+
 static void esp_register_types(void)
 {
     type_register_static(&sysbus_esp_info);
+    type_register_static(&esp_pci_info);
 }
 
 type_init(esp_register_types)
diff --git a/hw/pci_ids.h b/hw/pci_ids.h
index b4801d2..301bf1c 100644
--- a/hw/pci_ids.h
+++ b/hw/pci_ids.h
@@ -59,6 +59,7 @@
 
 #define PCI_VENDOR_ID_AMD                0x1022
 #define PCI_DEVICE_ID_AMD_LANCE          0x2000
+#define PCI_DEVICE_ID_AMD_SCSI           0x2020
 
 #define PCI_VENDOR_ID_TI                 0x104c
 
diff --git a/trace-events b/trace-events
index cfb9931..fc32bc6 100644
--- a/trace-events
+++ b/trace-events
@@ -760,6 +760,18 @@ esp_mem_writeb_cmd_selatn(uint32_t val) "Select with ATN (%2.2x)"
 esp_mem_writeb_cmd_selatns(uint32_t val) "Select with ATN & stop (%2.2x)"
 esp_mem_writeb_cmd_ensel(uint32_t val) "Enable selection (%2.2x)"
 esp_mem_writeb_cmd_dissel(uint32_t val) "Disable selection (%2.2x)"
+esp_pci_error_invalid_dma_direction(void) "invalid DMA transfer direction"
+esp_pci_error_invalid_read(uint32_t reg) "read access outside bounds (reg 0x%x)"
+esp_pci_error_invalid_write(uint32_t reg) "write access outside bounds (reg 0x%x)"
+esp_pci_error_invalid_write_dma(uint32_t val, uint32_t addr) "invalid write of 0x%02x at [0x%x]"
+esp_pci_dma_read(uint32_t saddr, uint32_t reg) "reg[%d]: 0x%8.8x"
+esp_pci_dma_write(uint32_t saddr, uint32_t reg, uint32_t val) "reg[%d]: 0x%8.8x -> 0x%8.8x"
+esp_pci_dma_idle(uint32_t val) "IDLE (%.8x)"
+esp_pci_dma_blast(uint32_t val) "BLAST (%.8x)"
+esp_pci_dma_abort(uint32_t val) "ABORT (%.8x)"
+esp_pci_dma_start(uint32_t val) "START (%.8x)"
+esp_pci_sbac_read(uint32_t reg) "sbac: 0x%8.8x"
+esp_pci_sbac_write(uint32_t reg, uint32_t val) "sbac: 0x%8.8x -> 0x%8.8x"
 
 # monitor.c
 handle_qmp_command(void *mon, const char *cmd_name) "mon %p cmd_name \"%s\""
commit 0883c5159f1df05d8761014f65451c3c3b77ebcf
Author: Hervé Poussineau <hpoussin at reactos.org>
Date:   Mon Jul 9 12:02:30 2012 +0200

    pci: add some stubs
    
    Cc: Michael S. Tsirkin <mst at redhat.com>
    Signed-off-by: Hervé Poussineau <hpoussin at reactos.org>
    Signed-off-by: Blue Swirl <blauwirbel at gmail.com>

diff --git a/hw/pci-stub.c b/hw/pci-stub.c
index 134c448..e083191 100644
--- a/hw/pci-stub.c
+++ b/hw/pci-stub.c
@@ -34,6 +34,21 @@ static void pci_error_message(Monitor *mon)
     monitor_printf(mon, "PCI devices not supported\n");
 }
 
+void pci_register_bar(PCIDevice *pci_dev, int region_num,
+                      uint8_t type, MemoryRegion *memory)
+{
+}
+
+const VMStateDescription vmstate_pci_device = {
+    .name = "PCIDeviceStub",
+    .version_id = 1,
+    .minimum_version_id = 1,
+    .minimum_version_id_old = 1,
+    .fields      = (VMStateField[]) {
+        VMSTATE_END_OF_LIST()
+    }
+};
+
 int do_pcie_aer_inject_error(Monitor *mon,
                              const QDict *qdict, QObject **ret_data)
 {
commit 3af4e9aa5615a0511ddbe301b14d30a63ac8492b
Author: Hervé Poussineau <hpoussin at reactos.org>
Date:   Mon Jul 9 12:02:29 2012 +0200

    esp: use trace framework instead of stderr output
    
    Signed-off-by: Hervé Poussineau <hpoussin at reactos.org>
    Signed-off-by: Blue Swirl <blauwirbel at gmail.com>

diff --git a/hw/esp.c b/hw/esp.c
index 796cdc1..ec40d93 100644
--- a/hw/esp.c
+++ b/hw/esp.c
@@ -26,6 +26,7 @@
 #include "scsi.h"
 #include "esp.h"
 #include "trace.h"
+#include "qemu-log.h"
 
 /*
  * On Sparc32, this is the ESP (NCR53C90) part of chip STP2000 (Master I/O),
@@ -35,9 +36,6 @@
  * http://www.ibiblio.org/pub/historic-linux/early-ports/Sparc/NCR/NCR53C9X.txt
  */
 
-#define ESP_ERROR(fmt, ...)                                             \
-    do { printf("ESP ERROR: %s: " fmt, __func__ , ## __VA_ARGS__); } while (0)
-
 #define ESP_REGS 16
 #define TI_BUFSZ 16
 
@@ -503,7 +501,8 @@ static uint64_t esp_reg_read(ESPState *s, uint32_t saddr)
             s->ti_size--;
             if ((s->rregs[ESP_RSTAT] & STAT_PIO_MASK) == 0) {
                 /* Data out.  */
-                ESP_ERROR("PIO data read not implemented\n");
+                qemu_log_mask(LOG_UNIMP,
+                              "esp: PIO data read not implemented\n");
                 s->rregs[ESP_FIFO] = 0;
             } else {
                 s->rregs[ESP_FIFO] = s->ti_buf[s->ti_rptr++];
@@ -543,7 +542,7 @@ static void esp_reg_write(ESPState *s, uint32_t saddr, uint64_t val)
         if (s->do_cmd) {
             s->cmdbuf[s->cmdlen++] = val & 0xff;
         } else if (s->ti_size == TI_BUFSZ - 1) {
-            ESP_ERROR("fifo overrun\n");
+            trace_esp_error_fifo_overrun();
         } else {
             s->ti_size++;
             s->ti_buf[s->ti_wptr++] = val & 0xff;
@@ -631,7 +630,7 @@ static void esp_reg_write(ESPState *s, uint32_t saddr, uint64_t val)
             esp_raise_irq(s);
             break;
         default:
-            ESP_ERROR("Unhandled ESP command (%2.2x)\n", (unsigned)val);
+            trace_esp_error_unhandled_command(val);
             break;
         }
         break;
@@ -646,7 +645,7 @@ static void esp_reg_write(ESPState *s, uint32_t saddr, uint64_t val)
         s->rregs[saddr] = val;
         break;
     default:
-        ESP_ERROR("invalid write of 0x%02x at [0x%x]\n", (unsigned)val, saddr);
+        trace_esp_error_invalid_write(val, saddr);
         return;
     }
     s->wregs[saddr] = val;
diff --git a/trace-events b/trace-events
index d1f7e4a..cfb9931 100644
--- a/trace-events
+++ b/trace-events
@@ -726,6 +726,9 @@ iscsi_aio_read16_cb(void *iscsi, int status, void *acb, int canceled) "iscsi %p
 iscsi_aio_readv(void *iscsi, int64_t sector_num, int nb_sectors, void *opaque, void *acb) "iscsi %p sector_num %"PRId64" nb_sectors %d opaque %p acb %p"
 
 # hw/esp.c
+esp_error_fifo_overrun(void) "FIFO overrun"
+esp_error_unhandled_command(uint32_t val) "unhandled command (%2.2x)"
+esp_error_invalid_write(uint32_t val, uint32_t addr) "invalid write of 0x%02x at [0x%x]"
 esp_raise_irq(void) "Raise IRQ"
 esp_lower_irq(void) "Lower IRQ"
 esp_dma_enable(void) "Raise enable"
commit a391fdbc7fdd573a5eb132a940ab14e42e3bc5b0
Author: Hervé Poussineau <hpoussin at reactos.org>
Date:   Mon Jul 9 12:02:28 2012 +0200

    esp: split esp code into generic chip emulation and sysbus layer
    
    Signed-off-by: Hervé Poussineau <hpoussin at reactos.org>
    Signed-off-by: Blue Swirl <blauwirbel at gmail.com>

diff --git a/hw/esp.c b/hw/esp.c
index d9dd2aa..796cdc1 100644
--- a/hw/esp.c
+++ b/hw/esp.c
@@ -44,12 +44,9 @@
 typedef struct ESPState ESPState;
 
 struct ESPState {
-    SysBusDevice busdev;
-    MemoryRegion iomem;
     uint8_t rregs[ESP_REGS];
     uint8_t wregs[ESP_REGS];
     qemu_irq irq;
-    uint32_t it_shift;
     uint8_t chip_id;
     int32_t ti_size;
     uint32_t ti_rptr, ti_wptr;
@@ -166,11 +163,8 @@ static void esp_lower_irq(ESPState *s)
     }
 }
 
-static void esp_dma_enable(void *opaque, int irq, int level)
+static void esp_dma_enable(ESPState *s, int irq, int level)
 {
-    DeviceState *d = opaque;
-    ESPState *s = container_of(d, ESPState, busdev.qdev);
-
     if (level) {
         s->dma_enabled = 1;
         trace_esp_dma_enable();
@@ -470,10 +464,8 @@ static void handle_ti(ESPState *s)
     }
 }
 
-static void esp_hard_reset(DeviceState *d)
+static void esp_hard_reset(ESPState *s)
 {
-    ESPState *s = container_of(d, ESPState, busdev.qdev);
-
     memset(s->rregs, 0, ESP_REGS);
     memset(s->wregs, 0, ESP_REGS);
     s->rregs[ESP_TCHI] = s->chip_id;
@@ -487,40 +479,23 @@ static void esp_hard_reset(DeviceState *d)
     s->rregs[ESP_CFG1] = 7;
 }
 
-static void esp_soft_reset(DeviceState *d)
+static void esp_soft_reset(ESPState *s)
 {
-    ESPState *s = container_of(d, ESPState, busdev.qdev);
-
     qemu_irq_lower(s->irq);
-    esp_hard_reset(d);
+    esp_hard_reset(s);
 }
 
-static void parent_esp_reset(void *opaque, int irq, int level)
+static void parent_esp_reset(ESPState *s, int irq, int level)
 {
     if (level) {
-        esp_soft_reset(opaque);
+        esp_soft_reset(s);
     }
 }
 
-static void esp_gpio_demux(void *opaque, int irq, int level)
+static uint64_t esp_reg_read(ESPState *s, uint32_t saddr)
 {
-    switch (irq) {
-    case 0:
-        parent_esp_reset(opaque, irq, level);
-        break;
-    case 1:
-        esp_dma_enable(opaque, irq, level);
-        break;
-    }
-}
+    uint32_t old_val;
 
-static uint64_t esp_mem_read(void *opaque, target_phys_addr_t addr,
-                             unsigned size)
-{
-    ESPState *s = opaque;
-    uint32_t saddr, old_val;
-
-    saddr = addr >> s->it_shift;
     trace_esp_mem_readb(saddr, s->rregs[saddr]);
     switch (saddr) {
     case ESP_FIFO:
@@ -556,13 +531,8 @@ static uint64_t esp_mem_read(void *opaque, target_phys_addr_t addr,
     return s->rregs[saddr];
 }
 
-static void esp_mem_write(void *opaque, target_phys_addr_t addr,
-                          uint64_t val, unsigned size)
+static void esp_reg_write(ESPState *s, uint32_t saddr, uint64_t val)
 {
-    ESPState *s = opaque;
-    uint32_t saddr;
-
-    saddr = addr >> s->it_shift;
     trace_esp_mem_writeb(saddr, s->wregs[saddr], val);
     switch (saddr) {
     case ESP_TCLO:
@@ -602,7 +572,7 @@ static void esp_mem_write(void *opaque, target_phys_addr_t addr,
             break;
         case CMD_RESET:
             trace_esp_mem_writeb_cmd_reset(val);
-            esp_soft_reset(&s->busdev.qdev);
+            esp_soft_reset(s);
             break;
         case CMD_BUSRESET:
             trace_esp_mem_writeb_cmd_bus_reset(val);
@@ -688,13 +658,6 @@ static bool esp_mem_accepts(void *opaque, target_phys_addr_t addr,
     return (size == 1) || (is_write && size == 4);
 }
 
-static const MemoryRegionOps esp_mem_ops = {
-    .read = esp_mem_read,
-    .write = esp_mem_write,
-    .endianness = DEVICE_NATIVE_ENDIAN,
-    .valid.accepts = esp_mem_accepts,
-};
-
 static const VMStateDescription vmstate_esp = {
     .name ="esp",
     .version_id = 3,
@@ -717,6 +680,40 @@ static const VMStateDescription vmstate_esp = {
     }
 };
 
+typedef struct {
+    SysBusDevice busdev;
+    MemoryRegion iomem;
+    uint32_t it_shift;
+    ESPState esp;
+} SysBusESPState;
+
+static void sysbus_esp_mem_write(void *opaque, target_phys_addr_t addr,
+                                 uint64_t val, unsigned int size)
+{
+    SysBusESPState *sysbus = opaque;
+    uint32_t saddr;
+
+    saddr = addr >> sysbus->it_shift;
+    esp_reg_write(&sysbus->esp, saddr, val);
+}
+
+static uint64_t sysbus_esp_mem_read(void *opaque, target_phys_addr_t addr,
+                                    unsigned int size)
+{
+    SysBusESPState *sysbus = opaque;
+    uint32_t saddr;
+
+    saddr = addr >> sysbus->it_shift;
+    return esp_reg_read(&sysbus->esp, saddr);
+}
+
+static const MemoryRegionOps sysbus_esp_mem_ops = {
+    .read = sysbus_esp_mem_read,
+    .write = sysbus_esp_mem_write,
+    .endianness = DEVICE_NATIVE_ENDIAN,
+    .valid.accepts = esp_mem_accepts,
+};
+
 void esp_init(target_phys_addr_t espaddr, int it_shift,
               ESPDMAMemoryReadWriteFunc dma_memory_read,
               ESPDMAMemoryReadWriteFunc dma_memory_write,
@@ -725,14 +722,16 @@ void esp_init(target_phys_addr_t espaddr, int it_shift,
 {
     DeviceState *dev;
     SysBusDevice *s;
+    SysBusESPState *sysbus;
     ESPState *esp;
 
     dev = qdev_create(NULL, "esp");
-    esp = DO_UPCAST(ESPState, busdev.qdev, dev);
+    sysbus = DO_UPCAST(SysBusESPState, busdev.qdev, dev);
+    esp = &sysbus->esp;
     esp->dma_memory_read = dma_memory_read;
     esp->dma_memory_write = dma_memory_write;
     esp->dma_opaque = dma_opaque;
-    esp->it_shift = it_shift;
+    sysbus->it_shift = it_shift;
     /* XXX for now until rc4030 has been changed to use DMA enable signal */
     esp->dma_enabled = 1;
     qdev_init_nofail(dev);
@@ -753,49 +752,78 @@ static const struct SCSIBusInfo esp_scsi_info = {
     .cancel = esp_request_cancelled
 };
 
-static int esp_init1(SysBusDevice *dev)
+static void sysbus_esp_gpio_demux(void *opaque, int irq, int level)
 {
-    ESPState *s = FROM_SYSBUS(ESPState, dev);
+    DeviceState *d = opaque;
+    SysBusESPState *sysbus = container_of(d, SysBusESPState, busdev.qdev);
+    ESPState *s = &sysbus->esp;
+
+    switch (irq) {
+    case 0:
+        parent_esp_reset(s, irq, level);
+        break;
+    case 1:
+        esp_dma_enable(opaque, irq, level);
+        break;
+    }
+}
+
+static int sysbus_esp_init(SysBusDevice *dev)
+{
+    SysBusESPState *sysbus = FROM_SYSBUS(SysBusESPState, dev);
+    ESPState *s = &sysbus->esp;
 
     sysbus_init_irq(dev, &s->irq);
-    assert(s->it_shift != -1);
+    assert(sysbus->it_shift != -1);
 
     s->chip_id = TCHI_FAS100A;
-    memory_region_init_io(&s->iomem, &esp_mem_ops, s,
-                          "esp", ESP_REGS << s->it_shift);
-    sysbus_init_mmio(dev, &s->iomem);
+    memory_region_init_io(&sysbus->iomem, &sysbus_esp_mem_ops, sysbus,
+                          "esp", ESP_REGS << sysbus->it_shift);
+    sysbus_init_mmio(dev, &sysbus->iomem);
 
-    qdev_init_gpio_in(&dev->qdev, esp_gpio_demux, 2);
+    qdev_init_gpio_in(&dev->qdev, sysbus_esp_gpio_demux, 2);
 
     scsi_bus_new(&s->bus, &dev->qdev, &esp_scsi_info);
     return scsi_bus_legacy_handle_cmdline(&s->bus);
 }
 
-static Property esp_properties[] = {
-    {.name = NULL},
+static void sysbus_esp_hard_reset(DeviceState *dev)
+{
+    SysBusESPState *sysbus = DO_UPCAST(SysBusESPState, busdev.qdev, dev);
+    esp_hard_reset(&sysbus->esp);
+}
+
+static const VMStateDescription vmstate_sysbus_esp_scsi = {
+    .name = "sysbusespscsi",
+    .version_id = 0,
+    .minimum_version_id = 0,
+    .minimum_version_id_old = 0,
+    .fields = (VMStateField[]) {
+        VMSTATE_STRUCT(esp, SysBusESPState, 0, vmstate_esp, ESPState),
+        VMSTATE_END_OF_LIST()
+    }
 };
 
-static void esp_class_init(ObjectClass *klass, void *data)
+static void sysbus_esp_class_init(ObjectClass *klass, void *data)
 {
     DeviceClass *dc = DEVICE_CLASS(klass);
     SysBusDeviceClass *k = SYS_BUS_DEVICE_CLASS(klass);
 
-    k->init = esp_init1;
-    dc->reset = esp_hard_reset;
-    dc->vmsd = &vmstate_esp;
-    dc->props = esp_properties;
+    k->init = sysbus_esp_init;
+    dc->reset = sysbus_esp_hard_reset;
+    dc->vmsd = &vmstate_sysbus_esp_scsi;
 }
 
-static TypeInfo esp_info = {
+static TypeInfo sysbus_esp_info = {
     .name          = "esp",
     .parent        = TYPE_SYS_BUS_DEVICE,
-    .instance_size = sizeof(ESPState),
-    .class_init    = esp_class_init,
+    .instance_size = sizeof(SysBusESPState),
+    .class_init    = sysbus_esp_class_init,
 };
 
 static void esp_register_types(void)
 {
-    type_register_static(&esp_info);
+    type_register_static(&sysbus_esp_info);
 }
 
 type_init(esp_register_types)
commit e6810db825887f5222ca5ede2e56563db7c8b599
Author: Hervé Poussineau <hpoussin at reactos.org>
Date:   Mon Jul 9 12:02:27 2012 +0200

    esp: use hba_private field instead of a complex cast
    
    Signed-off-by: Hervé Poussineau <hpoussin at reactos.org>
    Signed-off-by: Blue Swirl <blauwirbel at gmail.com>

diff --git a/hw/esp.c b/hw/esp.c
index a1f5b8a..d9dd2aa 100644
--- a/hw/esp.c
+++ b/hw/esp.c
@@ -186,7 +186,7 @@ static void esp_dma_enable(void *opaque, int irq, int level)
 
 static void esp_request_cancelled(SCSIRequest *req)
 {
-    ESPState *s = DO_UPCAST(ESPState, busdev.qdev, req->bus->qbus.parent);
+    ESPState *s = req->hba_private;
 
     if (req == s->current_req) {
         scsi_req_unref(s->current_req);
@@ -242,7 +242,7 @@ static void do_busid_cmd(ESPState *s, uint8_t *buf, uint8_t busid)
     trace_esp_do_busid_cmd(busid);
     lun = busid & 7;
     current_lun = scsi_device_find(&s->bus, 0, s->current_dev->id, lun);
-    s->current_req = scsi_req_new(current_lun, 0, lun, buf, NULL);
+    s->current_req = scsi_req_new(current_lun, 0, lun, buf, s);
     datalen = scsi_req_enqueue(s->current_req);
     s->ti_size = datalen;
     if (datalen != 0) {
@@ -396,7 +396,7 @@ static void esp_do_dma(ESPState *s)
 static void esp_command_complete(SCSIRequest *req, uint32_t status,
                                  size_t resid)
 {
-    ESPState *s = DO_UPCAST(ESPState, busdev.qdev, req->bus->qbus.parent);
+    ESPState *s = req->hba_private;
 
     trace_esp_command_complete();
     if (s->ti_size != 0) {
@@ -420,7 +420,7 @@ static void esp_command_complete(SCSIRequest *req, uint32_t status,
 
 static void esp_transfer_data(SCSIRequest *req, uint32_t len)
 {
-    ESPState *s = DO_UPCAST(ESPState, busdev.qdev, req->bus->qbus.parent);
+    ESPState *s = req->hba_private;
 
     trace_esp_transfer_data(s->dma_left, s->ti_size);
     s->async_len = len;
commit d32e4b3d73faa143ed006b2345130d94648dcde6
Author: Hervé Poussineau <hpoussin at reactos.org>
Date:   Mon Jul 9 12:02:26 2012 +0200

    esp: support future change of chip_id
    
    Signed-off-by: Hervé Poussineau <hpoussin at reactos.org>
    Signed-off-by: Blue Swirl <blauwirbel at gmail.com>

diff --git a/hw/esp.c b/hw/esp.c
index 85078e0..a1f5b8a 100644
--- a/hw/esp.c
+++ b/hw/esp.c
@@ -50,6 +50,7 @@ struct ESPState {
     uint8_t wregs[ESP_REGS];
     qemu_irq irq;
     uint32_t it_shift;
+    uint8_t chip_id;
     int32_t ti_size;
     uint32_t ti_rptr, ti_wptr;
     uint32_t status;
@@ -475,7 +476,7 @@ static void esp_hard_reset(DeviceState *d)
 
     memset(s->rregs, 0, ESP_REGS);
     memset(s->wregs, 0, ESP_REGS);
-    s->rregs[ESP_TCHI] = TCHI_FAS100A; // Indicate fas100a
+    s->rregs[ESP_TCHI] = s->chip_id;
     s->ti_size = 0;
     s->ti_rptr = 0;
     s->ti_wptr = 0;
@@ -759,6 +760,7 @@ static int esp_init1(SysBusDevice *dev)
     sysbus_init_irq(dev, &s->irq);
     assert(s->it_shift != -1);
 
+    s->chip_id = TCHI_FAS100A;
     memory_region_init_io(&s->iomem, &esp_mem_ops, s,
                           "esp", ESP_REGS << s->it_shift);
     sysbus_init_mmio(dev, &s->iomem);
commit 6915bff1a853196479c7c9427abb434919ef362d
Author: Hervé Poussineau <hpoussin at reactos.org>
Date:   Mon Jul 9 12:02:25 2012 +0200

    esp: implement Reset ATN command
    
    Signed-off-by: Hervé Poussineau <hpoussin at reactos.org>
    Signed-off-by: Blue Swirl <blauwirbel at gmail.com>

diff --git a/hw/esp.c b/hw/esp.c
index 985a2ee..85078e0 100644
--- a/hw/esp.c
+++ b/hw/esp.c
@@ -113,6 +113,7 @@ struct ESPState {
 #define CMD_MSGACC   0x12
 #define CMD_PAD      0x18
 #define CMD_SATN     0x1a
+#define CMD_RSTATN   0x1b
 #define CMD_SEL      0x41
 #define CMD_SELATN   0x42
 #define CMD_SELATNS  0x43
@@ -634,6 +635,9 @@ static void esp_mem_write(void *opaque, target_phys_addr_t addr,
         case CMD_SATN:
             trace_esp_mem_writeb_cmd_satn(val);
             break;
+        case CMD_RSTATN:
+            trace_esp_mem_writeb_cmd_rstatn(val);
+            break;
         case CMD_SEL:
             trace_esp_mem_writeb_cmd_sel(val);
             handle_s_without_atn(s);
diff --git a/trace-events b/trace-events
index ba89389..d1f7e4a 100644
--- a/trace-events
+++ b/trace-events
@@ -751,6 +751,7 @@ esp_mem_writeb_cmd_iccs(uint32_t val) "Initiator Command Complete Sequence (%2.2
 esp_mem_writeb_cmd_msgacc(uint32_t val) "Message Accepted (%2.2x)"
 esp_mem_writeb_cmd_pad(uint32_t val) "Transfer padding (%2.2x)"
 esp_mem_writeb_cmd_satn(uint32_t val) "Set ATN (%2.2x)"
+esp_mem_writeb_cmd_rstatn(uint32_t val) "Reset ATN (%2.2x)"
 esp_mem_writeb_cmd_sel(uint32_t val) "Select without ATN (%2.2x)"
 esp_mem_writeb_cmd_selatn(uint32_t val) "Select with ATN (%2.2x)"
 esp_mem_writeb_cmd_selatns(uint32_t val) "Select with ATN & stop (%2.2x)"
commit 6fe84c18357b7dd7ee2c1b1c3eb6c1a86ba1a286
Author: Hervé Poussineau <hpoussin at reactos.org>
Date:   Mon Jul 9 12:02:24 2012 +0200

    esp: implement Disable selection command
    
    Signed-off-by: Hervé Poussineau <hpoussin at reactos.org>
    Signed-off-by: Blue Swirl <blauwirbel at gmail.com>

diff --git a/hw/esp.c b/hw/esp.c
index ac91f00..985a2ee 100644
--- a/hw/esp.c
+++ b/hw/esp.c
@@ -117,6 +117,7 @@ struct ESPState {
 #define CMD_SELATN   0x42
 #define CMD_SELATNS  0x43
 #define CMD_ENSEL    0x44
+#define CMD_DISSEL   0x45
 
 #define STAT_DO 0x00
 #define STAT_DI 0x01
@@ -649,6 +650,11 @@ static void esp_mem_write(void *opaque, target_phys_addr_t addr,
             trace_esp_mem_writeb_cmd_ensel(val);
             s->rregs[ESP_RINTR] = 0;
             break;
+        case CMD_DISSEL:
+            trace_esp_mem_writeb_cmd_dissel(val);
+            s->rregs[ESP_RINTR] = 0;
+            esp_raise_irq(s);
+            break;
         default:
             ESP_ERROR("Unhandled ESP command (%2.2x)\n", (unsigned)val);
             break;
diff --git a/trace-events b/trace-events
index 1f9fc98..ba89389 100644
--- a/trace-events
+++ b/trace-events
@@ -755,6 +755,7 @@ esp_mem_writeb_cmd_sel(uint32_t val) "Select without ATN (%2.2x)"
 esp_mem_writeb_cmd_selatn(uint32_t val) "Select with ATN (%2.2x)"
 esp_mem_writeb_cmd_selatns(uint32_t val) "Select with ATN & stop (%2.2x)"
 esp_mem_writeb_cmd_ensel(uint32_t val) "Enable selection (%2.2x)"
+esp_mem_writeb_cmd_dissel(uint32_t val) "Disable selection (%2.2x)"
 
 # monitor.c
 handle_qmp_command(void *mon, const char *cmd_name) "mon %p cmd_name \"%s\""
commit 7246e160763306d254772353adb8e0836c3eac5b
Author: Hervé Poussineau <hpoussin at reactos.org>
Date:   Mon Jul 9 12:02:23 2012 +0200

    esp: delay Transfer Information command if dma is not enabled
    
    The same mechanism is already in place for some select commands.
    
    Signed-off-by: Hervé Poussineau <hpoussin at reactos.org>
    Signed-off-by: Blue Swirl <blauwirbel at gmail.com>

diff --git a/hw/esp.c b/hw/esp.c
index aff8de6..ac91f00 100644
--- a/hw/esp.c
+++ b/hw/esp.c
@@ -435,6 +435,11 @@ static void handle_ti(ESPState *s)
 {
     uint32_t dmalen, minlen;
 
+    if (s->dma && !s->dma_enabled) {
+        s->dma_cb = handle_ti;
+        return;
+    }
+
     dmalen = s->rregs[ESP_TCLO] | (s->rregs[ESP_TCMID] << 8);
     if (dmalen==0) {
       dmalen=0x10000;
commit 1b26eaa1382b333ef447ca27ff7ce166393cb46d
Author: Hervé Poussineau <hpoussin at reactos.org>
Date:   Mon Jul 9 12:02:22 2012 +0200

    esp: execute select commands immediately when it is a non-dma command
    
    Signed-off-by: Hervé Poussineau <hpoussin at reactos.org>
    Signed-off-by: Blue Swirl <blauwirbel at gmail.com>

diff --git a/hw/esp.c b/hw/esp.c
index 8d73e56..aff8de6 100644
--- a/hw/esp.c
+++ b/hw/esp.c
@@ -270,7 +270,7 @@ static void handle_satn(ESPState *s)
     uint8_t buf[32];
     int len;
 
-    if (!s->dma_enabled) {
+    if (s->dma && !s->dma_enabled) {
         s->dma_cb = handle_satn;
         return;
     }
@@ -284,7 +284,7 @@ static void handle_s_without_atn(ESPState *s)
     uint8_t buf[32];
     int len;
 
-    if (!s->dma_enabled) {
+    if (s->dma && !s->dma_enabled) {
         s->dma_cb = handle_s_without_atn;
         return;
     }
@@ -296,7 +296,7 @@ static void handle_s_without_atn(ESPState *s)
 
 static void handle_satn_stop(ESPState *s)
 {
-    if (!s->dma_enabled) {
+    if (s->dma && !s->dma_enabled) {
         s->dma_cb = handle_satn_stop;
         return;
     }
commit 638dfeda3ef558b6d743d43d089e1c4a8cec321a
Merge: 6e2fe79... fdec991...
Author: Blue Swirl <blauwirbel at gmail.com>
Date:   Sat Jul 14 10:07:37 2012 +0000

    Merge branch 's390-for-upstream' of git://repo.or.cz/qemu/agraf
    
    * 's390-for-upstream' of git://repo.or.cz/qemu/agraf:
      s390: autodetect map private

commit 6e2fe79da8853352e1cd401f86974c26b91ba3c8
Merge: c095855... 3dde962...
Author: Blue Swirl <blauwirbel at gmail.com>
Date:   Sat Jul 14 10:07:34 2012 +0000

    Merge branch 'target-arm.for-upstream' of git://git.linaro.org/people/pmaydell/qemu-arm
    
    * 'target-arm.for-upstream' of git://git.linaro.org/people/pmaydell/qemu-arm:
      target-arm: Add support for long format translation table walks
      target-arm: Implement TTBCR changes for LPAE
      target-arm: Implement long-descriptor PAR format
      target-arm: Use target_phys_addr_t in get_phys_addr()
      target-arm: Add 64 bit PAR, TTBR0, TTBR1 for LPAE
      target-arm: Add 64 bit variants of DBGDRAR and DBGDSAR for LPAE
      target-arm: Add AMAIR0, AMAIR1 LPAE cp15 registers
      target-arm: Extend feature flags to 64 bits
      target-arm: Implement privileged-execute-never (PXN)
      ARM: Make target_phys_addr_t 64 bits and physaddrs 40 bits
      hw/imx_avic.c: Avoid format error when target_phys_addr_t is 64 bits
      target-arm: Fix TCG temp handling in 64 bit cp writes
      target-arm: Fix some copy-and-paste errors in cp register names
      target-arm: Fix typo that meant TTBR1 accesses went to TTBR0
      target-arm: Fix CP15 based WFI

commit 208c9d1b7c23e112d2fb83660fa23f2918c4c15b
Author: Corey Bryant <coreyb at linux.vnet.ibm.com>
Date:   Fri Jun 22 14:36:09 2012 -0400

    qapi: Convert getfd and closefd
    
    Signed-off-by: Corey Bryant <coreyb at linux.vnet.ibm.com>
    Signed-off-by: Luiz Capitulino <lcapitulino at redhat.com>

diff --git a/hmp-commands.hx b/hmp-commands.hx
index f5d9d91..eea8b32 100644
--- a/hmp-commands.hx
+++ b/hmp-commands.hx
@@ -1236,8 +1236,7 @@ ETEXI
         .args_type  = "fdname:s",
         .params     = "getfd name",
         .help       = "receive a file descriptor via SCM rights and assign it a name",
-        .user_print = monitor_user_noop,
-        .mhandler.cmd_new = do_getfd,
+        .mhandler.cmd = hmp_getfd,
     },
 
 STEXI
@@ -1253,8 +1252,7 @@ ETEXI
         .args_type  = "fdname:s",
         .params     = "closefd name",
         .help       = "close a file descriptor previously passed via SCM rights",
-        .user_print = monitor_user_noop,
-        .mhandler.cmd_new = do_closefd,
+        .mhandler.cmd = hmp_closefd,
     },
 
 STEXI
diff --git a/hmp.c b/hmp.c
index 4c6d4ae..6b72a64 100644
--- a/hmp.c
+++ b/hmp.c
@@ -1002,3 +1002,21 @@ void hmp_netdev_del(Monitor *mon, const QDict *qdict)
     qmp_netdev_del(id, &err);
     hmp_handle_error(mon, &err);
 }
+
+void hmp_getfd(Monitor *mon, const QDict *qdict)
+{
+    const char *fdname = qdict_get_str(qdict, "fdname");
+    Error *errp = NULL;
+
+    qmp_getfd(fdname, &errp);
+    hmp_handle_error(mon, &errp);
+}
+
+void hmp_closefd(Monitor *mon, const QDict *qdict)
+{
+    const char *fdname = qdict_get_str(qdict, "fdname");
+    Error *errp = NULL;
+
+    qmp_closefd(fdname, &errp);
+    hmp_handle_error(mon, &errp);
+}
diff --git a/hmp.h b/hmp.h
index 79d138d..8d2b0d7 100644
--- a/hmp.h
+++ b/hmp.h
@@ -64,5 +64,7 @@ void hmp_device_del(Monitor *mon, const QDict *qdict);
 void hmp_dump_guest_memory(Monitor *mon, const QDict *qdict);
 void hmp_netdev_add(Monitor *mon, const QDict *qdict);
 void hmp_netdev_del(Monitor *mon, const QDict *qdict);
+void hmp_getfd(Monitor *mon, const QDict *qdict);
+void hmp_closefd(Monitor *mon, const QDict *qdict);
 
 #endif
diff --git a/monitor.c b/monitor.c
index f6107ba..522c88b 100644
--- a/monitor.c
+++ b/monitor.c
@@ -2328,48 +2328,45 @@ static void do_inject_mce(Monitor *mon, const QDict *qdict)
 }
 #endif
 
-static int do_getfd(Monitor *mon, const QDict *qdict, QObject **ret_data)
+void qmp_getfd(const char *fdname, Error **errp)
 {
-    const char *fdname = qdict_get_str(qdict, "fdname");
     mon_fd_t *monfd;
     int fd;
 
-    fd = qemu_chr_fe_get_msgfd(mon->chr);
+    fd = qemu_chr_fe_get_msgfd(cur_mon->chr);
     if (fd == -1) {
-        qerror_report(QERR_FD_NOT_SUPPLIED);
-        return -1;
+        error_set(errp, QERR_FD_NOT_SUPPLIED);
+        return;
     }
 
     if (qemu_isdigit(fdname[0])) {
-        qerror_report(QERR_INVALID_PARAMETER_VALUE, "fdname",
-                      "a name not starting with a digit");
-        return -1;
+        error_set(errp, QERR_INVALID_PARAMETER_VALUE, "fdname",
+                  "a name not starting with a digit");
+        return;
     }
 
-    QLIST_FOREACH(monfd, &mon->fds, next) {
+    QLIST_FOREACH(monfd, &cur_mon->fds, next) {
         if (strcmp(monfd->name, fdname) != 0) {
             continue;
         }
 
         close(monfd->fd);
         monfd->fd = fd;
-        return 0;
+        return;
     }
 
     monfd = g_malloc0(sizeof(mon_fd_t));
     monfd->name = g_strdup(fdname);
     monfd->fd = fd;
 
-    QLIST_INSERT_HEAD(&mon->fds, monfd, next);
-    return 0;
+    QLIST_INSERT_HEAD(&cur_mon->fds, monfd, next);
 }
 
-static int do_closefd(Monitor *mon, const QDict *qdict, QObject **ret_data)
+void qmp_closefd(const char *fdname, Error **errp)
 {
-    const char *fdname = qdict_get_str(qdict, "fdname");
     mon_fd_t *monfd;
 
-    QLIST_FOREACH(monfd, &mon->fds, next) {
+    QLIST_FOREACH(monfd, &cur_mon->fds, next) {
         if (strcmp(monfd->name, fdname) != 0) {
             continue;
         }
@@ -2378,11 +2375,10 @@ static int do_closefd(Monitor *mon, const QDict *qdict, QObject **ret_data)
         close(monfd->fd);
         g_free(monfd->name);
         g_free(monfd);
-        return 0;
+        return;
     }
 
-    qerror_report(QERR_FD_NOT_FOUND, fdname);
-    return -1;
+    error_set(errp, QERR_FD_NOT_FOUND, fdname);
 }
 
 static void do_loadvm(Monitor *mon, const QDict *qdict)
diff --git a/qapi-schema.json b/qapi-schema.json
index 5252452..a92adb1 100644
--- a/qapi-schema.json
+++ b/qapi-schema.json
@@ -1870,3 +1870,38 @@
 # Since: 0.14.0
 ##
 { 'command': 'netdev_del', 'data': {'id': 'str'} }
+
+##
+# @getfd:
+#
+# Receive a file descriptor via SCM rights and assign it a name
+#
+# @fdname: file descriptor name
+#
+# Returns: Nothing on success
+#          If file descriptor was not received, FdNotSupplied
+#          If @fdname is not valid, InvalidParameterType
+#
+# Since: 0.14.0
+#
+# Notes: If @fdname already exists, the file descriptor assigned to
+#        it will be closed and replaced by the received file
+#        descriptor.
+#        The 'closefd' command can be used to explicitly close the
+#        file descriptor when it is no longer needed.
+##
+{ 'command': 'getfd', 'data': {'fdname': 'str'} }
+
+##
+# @closefd:
+#
+# Close a file descriptor previously passed via SCM rights
+#
+# @fdname: file descriptor name
+#
+# Returns: Nothing on success
+#          If @fdname is not found, FdNotFound
+#
+# Since: 0.14.0
+##
+{ 'command': 'closefd', 'data': {'fdname': 'str'} }
diff --git a/qmp-commands.hx b/qmp-commands.hx
index 2e1a38e..e3cf3c5 100644
--- a/qmp-commands.hx
+++ b/qmp-commands.hx
@@ -873,8 +873,7 @@ EQMP
         .args_type  = "fdname:s",
         .params     = "getfd name",
         .help       = "receive a file descriptor via SCM rights and assign it a name",
-        .user_print = monitor_user_noop,
-        .mhandler.cmd_new = do_getfd,
+        .mhandler.cmd_new = qmp_marshal_input_getfd,
     },
 
 SQMP
@@ -892,6 +891,14 @@ Example:
 -> { "execute": "getfd", "arguments": { "fdname": "fd1" } }
 <- { "return": {} }
 
+Notes:
+
+(1) If the name specified by the "fdname" argument already exists,
+    the file descriptor assigned to it will be closed and replaced
+    by the received file descriptor.
+(2) The 'closefd' command can be used to explicitly close the file
+    descriptor when it is no longer needed.
+
 EQMP
 
     {
@@ -899,8 +906,7 @@ EQMP
         .args_type  = "fdname:s",
         .params     = "closefd name",
         .help       = "close a file descriptor previously passed via SCM rights",
-        .user_print = monitor_user_noop,
-        .mhandler.cmd_new = do_closefd,
+        .mhandler.cmd_new = qmp_marshal_input_closefd,
     },
 
 SQMP
commit 94c3db85b4cc1d4e078859834a761bcc9d988780
Author: Luiz Capitulino <lcapitulino at redhat.com>
Date:   Fri Jun 29 14:25:01 2012 -0300

    qapi: input_type_enum(): fix error message
    
    The enum string is pointed to by 'enum_str' not 'name'. This bug
    causes the error message to be:
    
    { "error": { "class": "InvalidParameter",
                 "desc": "Invalid parameter 'null'",
                 "data": { "name": "null" } } }
    
    Signed-off-by: Luiz Capitulino <lcapitulino at redhat.com>
    Reviewed-by: Amos Kong <akong at redhat.com>

diff --git a/qapi/qapi-visit-core.c b/qapi/qapi-visit-core.c
index ffffbf7..705eca9 100644
--- a/qapi/qapi-visit-core.c
+++ b/qapi/qapi-visit-core.c
@@ -298,7 +298,7 @@ void input_type_enum(Visitor *v, int *obj, const char *strings[],
     }
 
     if (strings[value] == NULL) {
-        error_set(errp, QERR_INVALID_PARAMETER, name ? name : "null");
+        error_set(errp, QERR_INVALID_PARAMETER, enum_str);
         g_free(enum_str);
         return;
     }
commit f5b0d93bcba712e1864c71c2f298c59a94efaa79
Author: Luiz Capitulino <lcapitulino at redhat.com>
Date:   Thu Jun 28 11:59:15 2012 -0300

    qmp: dump-guest-memory: improve schema doc
    
    Clarify a few points and makes it looks more like the other commands'
    documentation.
    
    Signed-off-by: Luiz Capitulino <lcapitulino at redhat.com>

diff --git a/qapi-schema.json b/qapi-schema.json
index 1ab5dbd..5252452 100644
--- a/qapi-schema.json
+++ b/qapi-schema.json
@@ -1789,34 +1789,36 @@
 #
 # Dump guest's memory to vmcore. It is a synchronous operation that can take
 # very long depending on the amount of guest memory. This command is only
-# supported only on i386 and x86_64
-#
-# @paging: if true, do paging to get guest's memory mapping. The @paging's
-# default value of @paging is false, If you want to use gdb to process the
-# core, please set @paging to true. The reason why the @paging's value is
-# false:
-#   1. guest machine in a catastrophic state can have corrupted memory,
-#      which we cannot trust.
-#   2. The guest machine can be in read-mode even if paging is enabled.
-#      For example: the guest machine uses ACPI to sleep, and ACPI sleep
-#      state goes in real-mode
+# supported on i386 and x86_64.
+#
+# @paging: if true, do paging to get guest's memory mapping. This allows
+# using gdb to process the core file. However, setting @paging to false
+# may be desirable because of two reasons:
+#
+#   1. The guest may be in a catastrophic state or can have corrupted
+#      memory, which cannot be trusted
+#   2. The guest can be in real-mode even if paging is enabled. For example,
+#      the guest uses ACPI to sleep, and ACPI sleep state goes in real-mode
+#
 # @protocol: the filename or file descriptor of the vmcore. The supported
-# protocol can be file or fd:
+# protocols are:
+#
 #   1. file: the protocol starts with "file:", and the following string is
 #      the file's path.
 #   2. fd: the protocol starts with "fd:", and the following string is the
 #      fd's name.
+#
 # @begin: #optional if specified, the starting physical address.
+#
 # @length: #optional if specified, the memory size, in bytes. If you don't
-# want to dump all guest's memory, please specify the start @begin and
-# @length
+# want to dump all guest's memory, please specify the start @begin and @length
 #
 # Returns: nothing on success
 #          If @begin contains an invalid address, InvalidParameter
 #          If only one of @begin and @length is specified, MissingParameter
 #          If @protocol stats with "fd:", and the fd cannot be found, FdNotFound
 #          If @protocol starts with "file:", and the file cannot be
-#          opened, OpenFileFailed
+#             opened, OpenFileFailed
 #          If @protocol does not start with "fd:" or "file:", InvalidParameter
 #          If an I/O error occurs while writing the file, IOError
 #          If the target does not support this command, Unsupported
commit 8f67aa8265b7aef104ffab6431048dec8d5656c7
Author: Stefan Weil <sw at weilnetz.de>
Date:   Mon Jul 9 20:36:36 2012 +0200

    make: Remove 'build-all' rule
    
    It is not needed, because the 'all' rule does the same.
    
    Signed-off-by: Stefan Weil <sw at weilnetz.de>
    Signed-off-by: Stefan Hajnoczi <stefanha at linux.vnet.ibm.com>

diff --git a/Makefile b/Makefile
index 34d6a9e..6eeabd0 100644
--- a/Makefile
+++ b/Makefile
@@ -6,7 +6,7 @@ BUILD_DIR=$(CURDIR)
 # All following code might depend on configuration variables
 ifneq ($(wildcard config-host.mak),)
 # Put the all: rule here so that config-host.mak can contain dependencies.
-all: build-all
+all:
 include config-host.mak
 include $(SRC_PATH)/rules.mak
 config-host.mak: $(SRC_PATH)/configure
@@ -31,7 +31,7 @@ Makefile: ;
 configure: ;
 
 .PHONY: all clean cscope distclean dvi html info install install-doc \
-	pdf recurse-all speed tar tarbin test build-all
+	pdf recurse-all speed tar tarbin test
 
 $(call set-vpath, $(SRC_PATH))
 
@@ -82,7 +82,7 @@ defconfig:
 
 -include config-all-devices.mak
 
-build-all: $(DOCS) $(TOOLS) $(HELPERS-y) recurse-all
+all: $(DOCS) $(TOOLS) $(HELPERS-y) recurse-all
 
 config-host.h: config-host.h-timestamp
 config-host.h-timestamp: config-host.mak
commit 0ef62ccd010b835858e81412e6c0cd52c60950dd
Author: Michael Tokarev <mjt at tls.msk.ru>
Date:   Thu Jul 12 12:59:12 2012 +0100

    qemu-keymaps: Finnish keyboard mapping broken
    
    As mentioned in http://bugs.debian.org/660154 , finnish keyboard mapping
    is kind of broken.  Fix it as Timo Sirainen suggests in #660154.
    
    Signed-off-by: Michael Tokarev <mjt at tls.msk.ru>
    Signed-off-by: Stefan Hajnoczi <stefanha at linux.vnet.ibm.com>

diff --git a/pc-bios/keymaps/fi b/pc-bios/keymaps/fi
index 2a4e0f0..4be7586 100644
--- a/pc-bios/keymaps/fi
+++ b/pc-bios/keymaps/fi
@@ -99,9 +99,7 @@ asterisk 0x2b shift
 acute 0x2b altgr
 multiply 0x2b shift altgr
 guillemotleft 0x2c altgr
-less 0x2c shift altgr
 guillemotright 0x2d altgr
-greater 0x2d shift altgr
 copyright 0x2e altgr
 leftdoublequotemark 0x2f altgr
 grave 0x2f shift altgr
commit 94b204ca4eb03ae01e5c05509a40903c779ea83c
Author: Amos Kong <akong at redhat.com>
Date:   Sat Jun 30 10:02:20 2012 +0800

    vnc: add a more descriptive error message
    
    Currently qemu outputs some low-level error in qemu-sockets.c
    when failed to start vnc server.
    eg. 'getaddrinfo(127.0.0.1,5902): Name or service not known'
    
    Some libvirt users could not know what's happened with this
    unclear error message. This patch added a more descriptive
    error message.
    
    Signed-off-by: Amos Kong <akong at redhat.com>
    Reviewed-by: Michael Tokarev <mjt at tls.msk.ru>
    Signed-off-by: Stefan Hajnoczi <stefanha at linux.vnet.ibm.com>

diff --git a/vl.c b/vl.c
index 2e140f5..46248b9 100644
--- a/vl.c
+++ b/vl.c
@@ -3584,8 +3584,11 @@ int main(int argc, char **argv, char **envp)
     /* init remote displays */
     if (vnc_display) {
         vnc_display_init(ds);
-        if (vnc_display_open(ds, vnc_display) < 0)
+        if (vnc_display_open(ds, vnc_display) < 0) {
+            fprintf(stderr, "Failed to start VNC server on `%s'\n",
+                    vnc_display);
             exit(1);
+        }
 
         if (show_vnc_port) {
             printf("VNC server running on `%s'\n", vnc_display_local_addr(ds));
commit ab411770440379765e492a8613c4ed6a0761e417
Author: Stefan Weil <sw at weilnetz.de>
Date:   Sun Jul 8 22:31:21 2012 +0200

    bitops: Fix documentation
    
    Signed-off-by: Stefan Weil <sw at weilnetz.de>
    Reviewed-by: Peter Maydell <peter.maydell at linaro.org>
    Signed-off-by: Stefan Hajnoczi <stefanha at linux.vnet.ibm.com>

diff --git a/bitops.h b/bitops.h
index b967ef3..c456232 100644
--- a/bitops.h
+++ b/bitops.h
@@ -319,8 +319,8 @@ static inline uint64_t extract64(uint64_t value, int start, int length)
  * @value. Bits of @value outside the bit field are not modified.
  * Bits of @fieldval above the least significant @length bits are
  * ignored. The bit field must lie entirely within the 32 bit word.
- * It is valid to request that all 64 bits are modified (ie @length
- * 64 and @start 0).
+ * It is valid to request that all 32 bits are modified (ie @length
+ * 32 and @start 0).
  *
  * Returns: the modified @value.
  */
@@ -334,7 +334,7 @@ static inline uint32_t deposit32(uint32_t value, int start, int length,
 }
 
 /**
- * deposit32:
+ * deposit64:
  * @value: initial value to insert bit field into
  * @start: the lowest bit in the bit field (numbered from 0)
  * @length: the length of the bit field
@@ -344,7 +344,7 @@ static inline uint32_t deposit32(uint32_t value, int start, int length,
  * by the @start and @length parameters, and return the modified
  * @value. Bits of @value outside the bit field are not modified.
  * Bits of @fieldval above the least significant @length bits are
- * ignored. The bit field must lie entirely within the 32 bit word.
+ * ignored. The bit field must lie entirely within the 64 bit word.
  * It is valid to request that all 64 bits are modified (ie @length
  * 64 and @start 0).
  *
commit a97ad268f137421fda1c84fa5898bd9a9850a472
Author: Hannes Reinecke <hare at suse.de>
Date:   Wed Jul 4 12:02:07 2012 +0200

    megasas: mark mfi_frame_desc as 'static'
    
    Suggested by blue swirl. Patch is on top of Paolo's
    scsi-next tree.
    
    Signed-off-by: Hannes Reinecke <hare at suse.de>
    Cc: Paolo Bonzini <pbonzini at redhat.com>
    Cc: Blue Swirl <blauwirbel at gmail.com>
    Signed-off-by: Stefan Hajnoczi <stefanha at linux.vnet.ibm.com>

diff --git a/hw/megasas.c b/hw/megasas.c
index b48836f..b99fa97 100644
--- a/hw/megasas.c
+++ b/hw/megasas.c
@@ -45,7 +45,7 @@
 #define MEGASAS_FLAG_USE_QUEUE64   2
 #define MEGASAS_MASK_USE_QUEUE64   (1 << MEGASAS_FLAG_USE_QUEUE64)
 
-const char *mfi_frame_desc[] = {
+static const char *mfi_frame_desc[] = {
     "MFI init", "LD Read", "LD Write", "LD SCSI", "PD SCSI",
     "MFI Doorbell", "MFI Abort", "MFI SMP", "MFI Stop"};
 
commit b45667760753a1fbc956547189a9edd0049630e5
Author: Gerd Hoffmann <kraxel at redhat.com>
Date:   Thu Feb 9 10:40:31 2012 +0100

    Add vgabios build rules to roms/Makefile
    
    This patch adds some glue to roms/Makefile to build vgabios binaries for
    qemu.  It covers both the lgpl'ed vgabios implementation used by qemu
    traditionally and the new seabios implementation.
    
    The purpose of this patch is to (a) document the vgabios build process
    and (b) simplify seavgabios testing for those who want to play with it.
    
    Signed-off-by: Gerd Hoffmann <kraxel at redhat.com>

diff --git a/roms/Makefile b/roms/Makefile
index 0114e6f..feb9c2b 100644
--- a/roms/Makefile
+++ b/roms/Makefile
@@ -1,10 +1,27 @@
 
+vgabios_variants := stdvga cirrus vmware qxl
+
 default:
 	@echo "nothing is build by default"
 	@echo "available build targets:"
 	@echo "  bios           -- update bios.bin (seabios)"
+	@echo "  seavgabios     -- update vgabios binaries (seabios)"
+	@echo "  lgplvgabios    -- update vgabios binaries (lgpl)"
 
 bios: config.seabios
 	sh configure-seabios.sh $<
 	make -C seabios out/bios.bin
 	cp seabios/out/bios.bin ../pc-bios/bios.bin
+
+seavgabios: $(patsubst %,seavgabios-%,$(vgabios_variants))
+
+seavgabios-%: config.vga.%
+	sh configure-seabios.sh $<
+	make -C seabios out/vgabios.bin
+	cp seabios/out/vgabios.bin ../pc-bios/vgabios-$*.bin
+
+lgplvgabios: $(patsubst %,lgplvgabios-%,$(vgabios_variants))
+
+lgplvgabios-%:
+	make -C vgabios vgabios-$*.bin
+	cp vgabios/VGABIOS-lgpl-latest.$*.bin ../pc-bios/vgabios-$*.bin
diff --git a/roms/config.vga.cirrus b/roms/config.vga.cirrus
new file mode 100644
index 0000000..c8fe582
--- /dev/null
+++ b/roms/config.vga.cirrus
@@ -0,0 +1,3 @@
+CONFIG_BUILD_VGABIOS=y
+CONFIG_VGA_CIRRUS=y
+CONFIG_VGA_PCI=y
diff --git a/roms/config.vga.isavga b/roms/config.vga.isavga
new file mode 100644
index 0000000..e55e294
--- /dev/null
+++ b/roms/config.vga.isavga
@@ -0,0 +1,3 @@
+CONFIG_BUILD_VGABIOS=y
+CONFIG_VGA_BOCHS=y
+CONFIG_VGA_PCI=n
diff --git a/roms/config.vga.qxl b/roms/config.vga.qxl
new file mode 100644
index 0000000..d393f0c
--- /dev/null
+++ b/roms/config.vga.qxl
@@ -0,0 +1,6 @@
+CONFIG_BUILD_VGABIOS=y
+CONFIG_VGA_BOCHS=y
+CONFIG_VGA_PCI=y
+CONFIG_OVERRIDE_PCI_ID=y
+CONFIG_VGA_VID=0x1b36
+CONFIG_VGA_DID=0x0100
diff --git a/roms/config.vga.stdvga b/roms/config.vga.stdvga
new file mode 100644
index 0000000..7d063b7
--- /dev/null
+++ b/roms/config.vga.stdvga
@@ -0,0 +1,3 @@
+CONFIG_BUILD_VGABIOS=y
+CONFIG_VGA_BOCHS=y
+CONFIG_VGA_PCI=y
diff --git a/roms/config.vga.vmware b/roms/config.vga.vmware
new file mode 100644
index 0000000..eb10427
--- /dev/null
+++ b/roms/config.vga.vmware
@@ -0,0 +1,6 @@
+CONFIG_BUILD_VGABIOS=y
+CONFIG_VGA_BOCHS=y
+CONFIG_VGA_PCI=y
+CONFIG_OVERRIDE_PCI_ID=y
+CONFIG_VGA_VID=0x15ad
+CONFIG_VGA_DID=0x0405
commit afb7a0b85be3a21eccd5ede0a41815b15c300b6b
Author: Gerd Hoffmann <kraxel at redhat.com>
Date:   Wed Jul 11 11:23:17 2012 +0200

    ehci: improve expire time calculation
    
    Move down the expire time calculation down in the frame timer, to the
    point where the timer is actually reloaded.  This way we'll notice any
    async_stepdown changes (especially resetting to 0 due to usb activity).
    
    Signed-off-by: Gerd Hoffmann <kraxel at redhat.com>

diff --git a/hw/usb/hcd-ehci.c b/hw/usb/hcd-ehci.c
index 6040e86..b043e7c 100644
--- a/hw/usb/hcd-ehci.c
+++ b/hw/usb/hcd-ehci.c
@@ -2372,7 +2372,7 @@ static void ehci_frame_timer(void *opaque)
 
     if (ehci_periodic_enabled(ehci) || ehci->pstate != EST_INACTIVE) {
         need_timer++;
-        expire_time = t_now + (get_ticks_per_sec() / FRAME_TIMER_FREQ);
+        ehci->async_stepdown = 0;
 
         if (frames > ehci->maxframes) {
             skipped_frames = frames - ehci->maxframes;
@@ -2391,8 +2391,6 @@ static void ehci_frame_timer(void *opaque)
         if (ehci->async_stepdown < ehci->maxframes / 2) {
             ehci->async_stepdown++;
         }
-        expire_time = t_now + (get_ticks_per_sec()
-                               * ehci->async_stepdown / FRAME_TIMER_FREQ);
         ehci_update_frindex(ehci, frames);
         ehci->last_run_ns += FRAME_TIMER_NS * frames;
     }
@@ -2402,7 +2400,7 @@ static void ehci_frame_timer(void *opaque)
      */
     if (ehci_async_enabled(ehci) || ehci->astate != EST_INACTIVE) {
         need_timer++;
-        qemu_bh_schedule(ehci->async_bh);
+        ehci_advance_async_state(ehci);
     }
 
     ehci_commit_irq(ehci);
@@ -2412,6 +2410,8 @@ static void ehci_frame_timer(void *opaque)
     }
 
     if (need_timer) {
+        expire_time = t_now + (get_ticks_per_sec()
+                               * (ehci->async_stepdown+1) / FRAME_TIMER_FREQ);
         qemu_mod_timer(ehci->frame_timer, expire_time);
     }
 }
commit 7efc17af9a08839a05771541959696875e06cf99
Author: Gerd Hoffmann <kraxel at redhat.com>
Date:   Wed Jul 11 11:06:05 2012 +0200

    ehci: implement Interrupt Threshold Control support
    
    Also reorganize and comment the irq functions while being at it.
    
    Signed-off-by: Gerd Hoffmann <kraxel at redhat.com>

diff --git a/hw/usb/hcd-ehci.c b/hw/usb/hcd-ehci.c
index 7c5f398..6040e86 100644
--- a/hw/usb/hcd-ehci.c
+++ b/hw/usb/hcd-ehci.c
@@ -420,6 +420,7 @@ struct EHCIState {
     USBPort ports[NB_PORTS];
     USBPort *companion_ports[NB_PORTS];
     uint32_t usbsts_pending;
+    uint32_t usbsts_frindex;
     EHCIQueueHead aqueues;
     EHCIQueueHead pqueues;
 
@@ -558,34 +559,45 @@ static inline void ehci_clear_usbsts(EHCIState *s, int mask)
     s->usbsts &= ~mask;
 }
 
-static inline void ehci_set_interrupt(EHCIState *s, int intr)
+/* update irq line */
+static inline void ehci_update_irq(EHCIState *s)
 {
     int level = 0;
 
-    // TODO honour interrupt threshold requests
-
-    ehci_set_usbsts(s, intr);
-
     if ((s->usbsts & USBINTR_MASK) & s->usbintr) {
         level = 1;
     }
 
-    trace_usb_ehci_interrupt(level, s->usbsts, s->usbintr);
+    trace_usb_ehci_irq(level, s->frindex, s->usbsts, s->usbintr);
     qemu_set_irq(s->irq, level);
 }
 
-static inline void ehci_record_interrupt(EHCIState *s, int intr)
+/* flag interrupt condition */
+static inline void ehci_raise_irq(EHCIState *s, int intr)
 {
     s->usbsts_pending |= intr;
 }
 
-static inline void ehci_commit_interrupt(EHCIState *s)
+/*
+ * Commit pending interrupts (added via ehci_raise_irq),
+ * at the rate allowed by "Interrupt Threshold Control".
+ */
+static inline void ehci_commit_irq(EHCIState *s)
 {
+    uint32_t itc;
+
     if (!s->usbsts_pending) {
         return;
     }
-    ehci_set_interrupt(s, s->usbsts_pending);
+    if (s->usbsts_frindex > s->frindex) {
+        return;
+    }
+
+    itc = (s->usbcmd >> 16) & 0xff;
+    s->usbsts |= s->usbsts_pending;
     s->usbsts_pending = 0;
+    s->usbsts_frindex = s->frindex + itc;
+    ehci_update_irq(s);
 }
 
 static void ehci_update_halt(EHCIState *s)
@@ -849,7 +861,8 @@ static void ehci_attach(USBPort *port)
     *portsc |= PORTSC_CONNECT;
     *portsc |= PORTSC_CSC;
 
-    ehci_set_interrupt(s, USBSTS_PCD);
+    ehci_raise_irq(s, USBSTS_PCD);
+    ehci_commit_irq(s);
 }
 
 static void ehci_detach(USBPort *port)
@@ -878,7 +891,8 @@ static void ehci_detach(USBPort *port)
     *portsc &= ~(PORTSC_CONNECT|PORTSC_PED);
     *portsc |= PORTSC_CSC;
 
-    ehci_set_interrupt(s, USBSTS_PCD);
+    ehci_raise_irq(s, USBSTS_PCD);
+    ehci_commit_irq(s);
 }
 
 static void ehci_child_detach(USBPort *port, USBDevice *child)
@@ -997,6 +1011,8 @@ static void ehci_reset(void *opaque)
 
     s->usbcmd = NB_MAXINTRATE << USBCMD_ITC_SH;
     s->usbsts = USBSTS_HALT;
+    s->usbsts_pending = 0;
+    s->usbsts_frindex = 0;
 
     s->astate = EST_INACTIVE;
     s->pstate = EST_INACTIVE;
@@ -1188,7 +1204,7 @@ static void ehci_mem_writel(void *ptr, target_phys_addr_t addr, uint32_t val)
         val &= USBSTS_RO_MASK;              // bits 6 through 31 are RO
         ehci_clear_usbsts(s, val);          // bits 0 through 5 are R/WC
         val = s->usbsts;
-        ehci_set_interrupt(s, 0);
+        ehci_update_irq(s);
         break;
 
     case USBINTR:
@@ -1419,18 +1435,18 @@ static void ehci_execute_complete(EHCIQueue *q)
         case USB_RET_NODEV:
             q->qh.token |= (QTD_TOKEN_HALT | QTD_TOKEN_XACTERR);
             set_field(&q->qh.token, 0, QTD_TOKEN_CERR);
-            ehci_record_interrupt(q->ehci, USBSTS_ERRINT);
+            ehci_raise_irq(q->ehci, USBSTS_ERRINT);
             break;
         case USB_RET_STALL:
             q->qh.token |= QTD_TOKEN_HALT;
-            ehci_record_interrupt(q->ehci, USBSTS_ERRINT);
+            ehci_raise_irq(q->ehci, USBSTS_ERRINT);
             break;
         case USB_RET_NAK:
             set_field(&q->qh.altnext_qtd, 0, QH_ALTNEXT_NAKCNT);
             return; /* We're not done yet with this transaction */
         case USB_RET_BABBLE:
             q->qh.token |= (QTD_TOKEN_HALT | QTD_TOKEN_BABBLE);
-            ehci_record_interrupt(q->ehci, USBSTS_ERRINT);
+            ehci_raise_irq(q->ehci, USBSTS_ERRINT);
             break;
         default:
             /* should not be triggerable */
@@ -1441,7 +1457,7 @@ static void ehci_execute_complete(EHCIQueue *q)
     } else if ((p->usb_status > p->tbytes) && (p->pid == USB_TOKEN_IN)) {
         p->usb_status = USB_RET_BABBLE;
         q->qh.token |= (QTD_TOKEN_HALT | QTD_TOKEN_BABBLE);
-        ehci_record_interrupt(q->ehci, USBSTS_ERRINT);
+        ehci_raise_irq(q->ehci, USBSTS_ERRINT);
     } else {
         // TODO check 4.12 for splits
 
@@ -1462,7 +1478,7 @@ static void ehci_execute_complete(EHCIQueue *q)
     q->qh.token &= ~QTD_TOKEN_ACTIVE;
 
     if (q->qh.token & QTD_TOKEN_IOC) {
-        ehci_record_interrupt(q->ehci, USBSTS_INT);
+        ehci_raise_irq(q->ehci, USBSTS_INT);
     }
 }
 
@@ -1597,12 +1613,12 @@ static int ehci_process_itd(EHCIState *ehci,
                     /* 3.3.2: XACTERR is only allowed on IN transactions */
                     if (dir) {
                         itd->transact[i] |= ITD_XACT_XACTERR;
-                        ehci_record_interrupt(ehci, USBSTS_ERRINT);
+                        ehci_raise_irq(ehci, USBSTS_ERRINT);
                     }
                     break;
                 case USB_RET_BABBLE:
                     itd->transact[i] |= ITD_XACT_BABBLE;
-                    ehci_record_interrupt(ehci, USBSTS_ERRINT);
+                    ehci_raise_irq(ehci, USBSTS_ERRINT);
                     break;
                 case USB_RET_NAK:
                     /* no data for us, so do a zero-length transfer */
@@ -1620,7 +1636,7 @@ static int ehci_process_itd(EHCIState *ehci,
                 }
             }
             if (itd->transact[i] & ITD_XACT_IOC) {
-                ehci_record_interrupt(ehci, USBSTS_INT);
+                ehci_raise_irq(ehci, USBSTS_INT);
             }
             itd->transact[i] &= ~ITD_XACT_ACTIVE;
         }
@@ -2253,7 +2269,7 @@ static void ehci_advance_async_state(EHCIState *ehci)
             ehci_queues_tag_unused_async(ehci);
             DPRINTF("ASYNC: doorbell request acknowledged\n");
             ehci->usbcmd &= ~USBCMD_IAAD;
-            ehci_set_interrupt(ehci, USBSTS_IAA);
+            ehci_raise_irq(ehci, USBSTS_IAA);
         }
         break;
 
@@ -2326,12 +2342,17 @@ static void ehci_update_frindex(EHCIState *ehci, int frames)
         ehci->frindex += 8;
 
         if (ehci->frindex == 0x00002000) {
-            ehci_set_interrupt(ehci, USBSTS_FLR);
+            ehci_raise_irq(ehci, USBSTS_FLR);
         }
 
         if (ehci->frindex == 0x00004000) {
-            ehci_set_interrupt(ehci, USBSTS_FLR);
+            ehci_raise_irq(ehci, USBSTS_FLR);
             ehci->frindex = 0;
+            if (ehci->usbsts_frindex > 0x00004000) {
+                ehci->usbsts_frindex -= 0x00004000;
+            } else {
+                ehci->usbsts_frindex = 0;
+            }
         }
     }
 }
@@ -2339,7 +2360,7 @@ static void ehci_update_frindex(EHCIState *ehci, int frames)
 static void ehci_frame_timer(void *opaque)
 {
     EHCIState *ehci = opaque;
-    int schedules = 0;
+    int need_timer = 0;
     int64_t expire_time, t_now;
     uint64_t ns_elapsed;
     int frames, skipped_frames;
@@ -2350,7 +2371,7 @@ static void ehci_frame_timer(void *opaque)
     frames = ns_elapsed / FRAME_TIMER_NS;
 
     if (ehci_periodic_enabled(ehci) || ehci->pstate != EST_INACTIVE) {
-        schedules++;
+        need_timer++;
         expire_time = t_now + (get_ticks_per_sec() / FRAME_TIMER_FREQ);
 
         if (frames > ehci->maxframes) {
@@ -2380,15 +2401,19 @@ static void ehci_frame_timer(void *opaque)
      *  called
      */
     if (ehci_async_enabled(ehci) || ehci->astate != EST_INACTIVE) {
-        schedules++;
+        need_timer++;
         qemu_bh_schedule(ehci->async_bh);
     }
 
-    if (schedules) {
-        qemu_mod_timer(ehci->frame_timer, expire_time);
+    ehci_commit_irq(ehci);
+    if (ehci->usbsts_pending) {
+        need_timer++;
+        ehci->async_stepdown = 0;
     }
 
-    ehci_commit_interrupt(ehci);
+    if (need_timer) {
+        qemu_mod_timer(ehci->frame_timer, expire_time);
+    }
 }
 
 static void ehci_async_bh(void *opaque)
diff --git a/trace-events b/trace-events
index 04b3d93..e45c7e5 100644
--- a/trace-events
+++ b/trace-events
@@ -258,7 +258,7 @@ usb_ehci_port_reset(uint32_t port, int enable) "reset port #%d - %d"
 usb_ehci_data(int rw, uint32_t cpage, uint32_t offset, uint32_t addr, uint32_t len, uint32_t bufpos) "write %d, cpage %d, offset 0x%03x, addr 0x%08x, len %d, bufpos %d"
 usb_ehci_queue_action(void *q, const char *action) "q %p: %s"
 usb_ehci_packet_action(void *q, void *p, const char *action) "q %p p %p: %s"
-usb_ehci_interrupt(uint32_t level, uint32_t sts, uint32_t mask) "level %d, sts 0x%x, mask 0x%x"
+usb_ehci_irq(uint32_t level, uint32_t frindex, uint32_t sts, uint32_t mask) "level %d, frindex 0x%04x, sts 0x%x, mask 0x%x"
 
 # hw/usb/hcd-uhci.c
 usb_uhci_reset(void) "=== RESET ==="
commit f0ad01f92ca02eee7cadbfd225c5de753ebd5fce
Author: Gerd Hoffmann <kraxel at redhat.com>
Date:   Tue Jul 10 18:00:50 2012 +0200

    ehci: raise irq in the frame timer
    
    With the async schedule being kicked from other places than the frame
    timer (commit 0f588df8b3688b00e77aabaa32e26ece5f19bd39) it may happen
    that we call ehci_commit_interrupt() more than once per frame.
    
    Move the call from the async schedule handler to the frame timer to
    restore old irq behavior, which is more correct.  Fixes regressions
    with some linux kernel versions.
    
    TODO: implement full Interrupt Threshold Control support.
    
    Signed-off-by: Gerd Hoffmann <kraxel at redhat.com>

diff --git a/hw/usb/hcd-ehci.c b/hw/usb/hcd-ehci.c
index 080f62c..7c5f398 100644
--- a/hw/usb/hcd-ehci.c
+++ b/hw/usb/hcd-ehci.c
@@ -2208,8 +2208,6 @@ static void ehci_advance_state(EHCIState *ehci, int async)
         }
     }
     while (again);
-
-    ehci_commit_interrupt(ehci);
 }
 
 static void ehci_advance_async_state(EHCIState *ehci)
@@ -2389,6 +2387,8 @@ static void ehci_frame_timer(void *opaque)
     if (schedules) {
         qemu_mod_timer(ehci->frame_timer, expire_time);
     }
+
+    ehci_commit_interrupt(ehci);
 }
 
 static void ehci_async_bh(void *opaque)
commit 75f151cd271bb0fd3b3b871f1850a673d534e65e
Author: Gerd Hoffmann <kraxel at redhat.com>
Date:   Tue Jul 10 12:51:07 2012 +0200

    uhci: initialize expire_time when loading v1 vmstate
    
    $subject says all: when loading old (v1) vmstate which doesn't contain
    expire_time initialize it with a reasonable default (current time).
    
    Signed-off-by: Gerd Hoffmann <kraxel at redhat.com>

diff --git a/hw/usb/hcd-uhci.c b/hw/usb/hcd-uhci.c
index 8f652d2..2aac8a2 100644
--- a/hw/usb/hcd-uhci.c
+++ b/hw/usb/hcd-uhci.c
@@ -388,11 +388,23 @@ static const VMStateDescription vmstate_uhci_port = {
     }
 };
 
+static int uhci_post_load(void *opaque, int version_id)
+{
+    UHCIState *s = opaque;
+
+    if (version_id < 2) {
+        s->expire_time = qemu_get_clock_ns(vm_clock) +
+            (get_ticks_per_sec() / FRAME_TIMER_FREQ);
+    }
+    return 0;
+}
+
 static const VMStateDescription vmstate_uhci = {
     .name = "uhci",
     .version_id = 2,
     .minimum_version_id = 1,
     .minimum_version_id_old = 1,
+    .post_load = uhci_post_load,
     .fields      = (VMStateField []) {
         VMSTATE_PCI_DEVICE(dev, UHCIState),
         VMSTATE_UINT8_EQUAL(num_ports_vmstate, UHCIState),
commit 0f58f68b58eb0528545553d2c44f6b8e472cedb0
Author: Gerd Hoffmann <kraxel at redhat.com>
Date:   Fri Jun 8 16:03:37 2012 +0200

    usb: add usb attached scsi emulation
    
    $subject says all.  First cut.
    
    It's a pure UAS (usb attached scsi) emulation, without BOT (bulk-only
    transport) compatibility.  If your guest can't handle it use usb-storage
    instead.
    
    The emulation works like any other scsi hba emulation (eps, lsi, virtio,
    megasas, ...).  It provides just the HBA where you can attach scsi
    devices as you like using '-device'.  A single scsi target with up to
    256 luns is supported.
    
    For now only usb 2.0 transport is supported.  This will change in the
    future though as I plan to use this as playground when codeing up &
    testing usb 3.0 transport and streams support in the qemu usb core and
    the xhci emulation.
    
    No migration support yet.  I'm planning to add usb 3.0 support first as
    this probably requires saving additional state.
    
    Special thanks go to Paolo for bringing the qemu scsi emulation into
    shape, so this can be added nicely without having to touch a single line
    of scsi code.
    
    Signed-off-by: Gerd Hoffmann <kraxel at redhat.com>

diff --git a/docs/usb-storage.txt b/docs/usb-storage.txt
new file mode 100644
index 0000000..ff97559
--- /dev/null
+++ b/docs/usb-storage.txt
@@ -0,0 +1,38 @@
+
+qemu usb storage emulation
+--------------------------
+
+Qemu has two emulations for usb storage devices.
+
+Number one emulates the classic bulk-only transport protocol which is
+used by 99% of the usb sticks on the marked today and is called
+"usb-storage".  Usage (hooking up to xhci, other host controllers work
+too):
+
+  qemu ${other_vm_args}                                \
+       -drive if=none,id=stick,file=/path/to/file.img  \
+       -device nec-usb-xhci,id=xhci                    \
+       -device usb-storage,bus=xhci.0,drive=stick
+
+
+Number two is the newer usb attached scsi transport.  This one doesn't
+automagically create a scsi disk, so you have to explicitly attach one
+manually.  Multiple logical units are supported.  Here is an example
+with tree logical units:
+
+  qemu ${other_vm_args}                                                \
+       -drive if=none,id=uas-disk1,file=/path/to/file1.img             \
+       -drive if=none,id=uas-disk2,file=/path/to/file2.img             \
+       -drive if=none,id=uas-cdrom,media=cdrom,file=/path/to/image.iso \
+       -device nec-usb-xhci,id=xhci                                    \
+       -device usb-uas,id=uas,bus=xhci.0                               \
+       -device scsi-hd,bus=uas.0,scsi-id=0,lun=0,drive=uas-disk1       \
+       -device scsi-hd,bus=uas.0,scsi-id=0,lun=1,drive=uas-disk2       \
+       -device scsi-cd,bus=uas.0,scsi-id=0,lun=5,drive=uas-cdrom
+
+
+enjoy,
+  Gerd
+
+--
+Gerd Hoffmann <kraxel at redhat.com>
diff --git a/hw/usb/Makefile.objs b/hw/usb/Makefile.objs
index 9c7ddf5..4225136 100644
--- a/hw/usb/Makefile.objs
+++ b/hw/usb/Makefile.objs
@@ -11,3 +11,4 @@ common-obj-y += core.o bus.o desc.o dev-hub.o
 common-obj-y += host-$(HOST_USB).o dev-bluetooth.o
 common-obj-y += dev-hid.o dev-storage.o dev-wacom.o
 common-obj-y += dev-serial.o dev-network.o dev-audio.o
+common-obj-y += dev-uas.o
diff --git a/hw/usb/dev-uas.c b/hw/usb/dev-uas.c
new file mode 100644
index 0000000..9b02ff4
--- /dev/null
+++ b/hw/usb/dev-uas.c
@@ -0,0 +1,779 @@
+/*
+ * UAS (USB Attached SCSI) emulation
+ *
+ * Copyright Red Hat, Inc. 2012
+ *
+ * Author: Gerd Hoffmann <kraxel at redhat.com>
+ *
+ * This work is licensed under the terms of the GNU GPL, version 2 or later.
+ * See the COPYING file in the top-level directory.
+ */
+
+#include "qemu-common.h"
+#include "qemu-option.h"
+#include "qemu-config.h"
+#include "trace.h"
+
+#include "hw/usb.h"
+#include "hw/usb/desc.h"
+#include "hw/scsi.h"
+#include "hw/scsi-defs.h"
+
+/* --------------------------------------------------------------------- */
+
+#define UAS_UI_COMMAND              0x01
+#define UAS_UI_SENSE                0x03
+#define UAS_UI_RESPONSE             0x04
+#define UAS_UI_TASK_MGMT            0x05
+#define UAS_UI_READ_READY           0x06
+#define UAS_UI_WRITE_READY          0x07
+
+#define UAS_RC_TMF_COMPLETE         0x00
+#define UAS_RC_INVALID_INFO_UNIT    0x02
+#define UAS_RC_TMF_NOT_SUPPORTED    0x04
+#define UAS_RC_TMF_FAILED           0x05
+#define UAS_RC_TMF_SUCCEEDED        0x08
+#define UAS_RC_INCORRECT_LUN        0x09
+#define UAS_RC_OVERLAPPED_TAG       0x0a
+
+#define UAS_TMF_ABORT_TASK          0x01
+#define UAS_TMF_ABORT_TASK_SET      0x02
+#define UAS_TMF_CLEAR_TASK_SET      0x04
+#define UAS_TMF_LOGICAL_UNIT_RESET  0x08
+#define UAS_TMF_I_T_NEXUS_RESET     0x10
+#define UAS_TMF_CLEAR_ACA           0x40
+#define UAS_TMF_QUERY_TASK          0x80
+#define UAS_TMF_QUERY_TASK_SET      0x81
+#define UAS_TMF_QUERY_ASYNC_EVENT   0x82
+
+#define UAS_PIPE_ID_COMMAND         0x01
+#define UAS_PIPE_ID_STATUS          0x02
+#define UAS_PIPE_ID_DATA_IN         0x03
+#define UAS_PIPE_ID_DATA_OUT        0x04
+
+typedef struct {
+    uint8_t    id;
+    uint8_t    reserved;
+    uint16_t   tag;
+} QEMU_PACKED  uas_ui_header;
+
+typedef struct {
+    uint8_t    prio_taskattr;   /* 6:3 priority, 2:0 task attribute   */
+    uint8_t    reserved_1;
+    uint8_t    add_cdb_length;  /* 7:2 additional adb length (dwords) */
+    uint8_t    reserved_2;
+    uint64_t   lun;
+    uint8_t    cdb[16];
+    uint8_t    add_cdb[];
+} QEMU_PACKED  uas_ui_command;
+
+typedef struct {
+    uint16_t   status_qualifier;
+    uint8_t    status;
+    uint8_t    reserved[7];
+    uint16_t   sense_length;
+    uint8_t    sense_data[18];
+} QEMU_PACKED  uas_ui_sense;
+
+typedef struct {
+    uint16_t   add_response_info;
+    uint8_t    response_code;
+} QEMU_PACKED  uas_ui_response;
+
+typedef struct {
+    uint8_t    function;
+    uint8_t    reserved;
+    uint16_t   task_tag;
+    uint64_t   lun;
+} QEMU_PACKED  uas_ui_task_mgmt;
+
+typedef struct {
+    uas_ui_header  hdr;
+    union {
+        uas_ui_command   command;
+        uas_ui_sense     sense;
+        uas_ui_task_mgmt task;
+        uas_ui_response  response;
+    };
+} QEMU_PACKED  uas_ui;
+
+/* --------------------------------------------------------------------- */
+
+typedef struct UASDevice UASDevice;
+typedef struct UASRequest UASRequest;
+typedef struct UASStatus UASStatus;
+
+struct UASDevice {
+    USBDevice                 dev;
+    SCSIBus                   bus;
+    UASRequest                *datain;
+    UASRequest                *dataout;
+    USBPacket                 *status;
+    QEMUBH                    *status_bh;
+    QTAILQ_HEAD(, UASStatus)  results;
+    QTAILQ_HEAD(, UASRequest) requests;
+};
+
+struct UASRequest {
+    uint16_t     tag;
+    uint64_t     lun;
+    UASDevice    *uas;
+    SCSIDevice   *dev;
+    SCSIRequest  *req;
+    USBPacket    *data;
+    bool         data_async;
+    bool         active;
+    bool         complete;
+    uint32_t     buf_off;
+    uint32_t     buf_size;
+    uint32_t     data_off;
+    uint32_t     data_size;
+    QTAILQ_ENTRY(UASRequest)  next;
+};
+
+struct UASStatus {
+    uas_ui                    status;
+    uint32_t                  length;
+    QTAILQ_ENTRY(UASStatus)   next;
+};
+
+/* --------------------------------------------------------------------- */
+
+enum {
+    STR_MANUFACTURER = 1,
+    STR_PRODUCT,
+    STR_SERIALNUMBER,
+    STR_CONFIG_HIGH,
+};
+
+static const USBDescStrings desc_strings = {
+    [STR_MANUFACTURER] = "QEMU",
+    [STR_PRODUCT]      = "USB Attached SCSI HBA",
+    [STR_SERIALNUMBER] = "27842",
+    [STR_CONFIG_HIGH]  = "High speed config (usb 2.0)",
+};
+
+static const USBDescIface desc_iface_high = {
+    .bInterfaceNumber              = 0,
+    .bNumEndpoints                 = 4,
+    .bInterfaceClass               = USB_CLASS_MASS_STORAGE,
+    .bInterfaceSubClass            = 0x06, /* SCSI */
+    .bInterfaceProtocol            = 0x62, /* UAS  */
+    .eps = (USBDescEndpoint[]) {
+        {
+            .bEndpointAddress      = USB_DIR_OUT | UAS_PIPE_ID_COMMAND,
+            .bmAttributes          = USB_ENDPOINT_XFER_BULK,
+            .wMaxPacketSize        = 512,
+            .extra = (uint8_t[]) {
+                0x04,  /*  u8  bLength */
+                0x24,  /*  u8  bDescriptorType */
+                UAS_PIPE_ID_COMMAND,
+                0x00,  /*  u8  bReserved */
+            },
+        },{
+            .bEndpointAddress      = USB_DIR_IN | UAS_PIPE_ID_STATUS,
+            .bmAttributes          = USB_ENDPOINT_XFER_BULK,
+            .wMaxPacketSize        = 512,
+            .extra = (uint8_t[]) {
+                0x04,  /*  u8  bLength */
+                0x24,  /*  u8  bDescriptorType */
+                UAS_PIPE_ID_STATUS,
+                0x00,  /*  u8  bReserved */
+            },
+        },{
+            .bEndpointAddress      = USB_DIR_IN | UAS_PIPE_ID_DATA_IN,
+            .bmAttributes          = USB_ENDPOINT_XFER_BULK,
+            .wMaxPacketSize        = 512,
+            .extra = (uint8_t[]) {
+                0x04,  /*  u8  bLength */
+                0x24,  /*  u8  bDescriptorType */
+                UAS_PIPE_ID_DATA_IN,
+                0x00,  /*  u8  bReserved */
+            },
+        },{
+            .bEndpointAddress      = USB_DIR_OUT | UAS_PIPE_ID_DATA_OUT,
+            .bmAttributes          = USB_ENDPOINT_XFER_BULK,
+            .wMaxPacketSize        = 512,
+            .extra = (uint8_t[]) {
+                0x04,  /*  u8  bLength */
+                0x24,  /*  u8  bDescriptorType */
+                UAS_PIPE_ID_DATA_OUT,
+                0x00,  /*  u8  bReserved */
+            },
+        },
+    }
+};
+
+static const USBDescDevice desc_device_high = {
+    .bcdUSB                        = 0x0200,
+    .bMaxPacketSize0               = 64,
+    .bNumConfigurations            = 1,
+    .confs = (USBDescConfig[]) {
+        {
+            .bNumInterfaces        = 1,
+            .bConfigurationValue   = 1,
+            .iConfiguration        = STR_CONFIG_HIGH,
+            .bmAttributes          = 0xc0,
+            .nif = 1,
+            .ifs = &desc_iface_high,
+        },
+    },
+};
+
+static const USBDesc desc = {
+    .id = {
+        .idVendor          = 0x46f4, /* CRC16() of "QEMU" */
+        .idProduct         = 0x0002,
+        .bcdDevice         = 0,
+        .iManufacturer     = STR_MANUFACTURER,
+        .iProduct          = STR_PRODUCT,
+        .iSerialNumber     = STR_SERIALNUMBER,
+    },
+    .high = &desc_device_high,
+    .str  = desc_strings,
+};
+
+/* --------------------------------------------------------------------- */
+
+static UASStatus *usb_uas_alloc_status(uint8_t id, uint16_t tag)
+{
+    UASStatus *st = g_new0(UASStatus, 1);
+
+    st->status.hdr.id = id;
+    st->status.hdr.tag = cpu_to_be16(tag);
+    st->length = sizeof(uas_ui_header);
+    return st;
+}
+
+static void usb_uas_send_status_bh(void *opaque)
+{
+    UASDevice *uas = opaque;
+    UASStatus *st = QTAILQ_FIRST(&uas->results);
+    USBPacket *p = uas->status;
+
+    assert(p != NULL);
+    assert(st != NULL);
+
+    uas->status = NULL;
+    usb_packet_copy(p, &st->status, st->length);
+    p->result = st->length;
+    QTAILQ_REMOVE(&uas->results, st, next);
+    g_free(st);
+
+    usb_packet_complete(&uas->dev, p);
+}
+
+static void usb_uas_queue_status(UASDevice *uas, UASStatus *st, int length)
+{
+    st->length += length;
+    QTAILQ_INSERT_TAIL(&uas->results, st, next);
+    if (uas->status) {
+        /*
+         * Just schedule bh make sure any in-flight data transaction
+         * is finished before completing (sending) the status packet.
+         */
+        qemu_bh_schedule(uas->status_bh);
+    } else {
+        USBEndpoint *ep = usb_ep_get(&uas->dev, USB_TOKEN_IN,
+                                     UAS_PIPE_ID_STATUS);
+        usb_wakeup(ep);
+    }
+}
+
+static void usb_uas_queue_response(UASDevice *uas, uint16_t tag,
+                                   uint8_t code, uint16_t add_info)
+{
+    UASStatus *st = usb_uas_alloc_status(UAS_UI_RESPONSE, tag);
+
+    trace_usb_uas_response(uas->dev.addr, tag, code);
+    st->status.response.response_code = code;
+    st->status.response.add_response_info = cpu_to_be16(add_info);
+    usb_uas_queue_status(uas, st, sizeof(uas_ui_response));
+}
+
+static void usb_uas_queue_sense(UASRequest *req, uint8_t status)
+{
+    UASStatus *st = usb_uas_alloc_status(UAS_UI_SENSE, req->tag);
+    int len, slen = 0;
+
+    trace_usb_uas_sense(req->uas->dev.addr, req->tag, status);
+    st->status.sense.status = status;
+    st->status.sense.status_qualifier = cpu_to_be16(0);
+    if (status != GOOD) {
+        slen = scsi_req_get_sense(req->req, st->status.sense.sense_data,
+                                  sizeof(st->status.sense.sense_data));
+        st->status.sense.sense_length = cpu_to_be16(slen);
+    }
+    len = sizeof(uas_ui_sense) - sizeof(st->status.sense.sense_data) + slen;
+    usb_uas_queue_status(req->uas, st, len);
+}
+
+static void usb_uas_queue_read_ready(UASRequest *req)
+{
+    UASStatus *st = usb_uas_alloc_status(UAS_UI_READ_READY, req->tag);
+
+    trace_usb_uas_read_ready(req->uas->dev.addr, req->tag);
+    usb_uas_queue_status(req->uas, st, 0);
+}
+
+static void usb_uas_queue_write_ready(UASRequest *req)
+{
+    UASStatus *st = usb_uas_alloc_status(UAS_UI_WRITE_READY, req->tag);
+
+    trace_usb_uas_write_ready(req->uas->dev.addr, req->tag);
+    usb_uas_queue_status(req->uas, st, 0);
+}
+
+/* --------------------------------------------------------------------- */
+
+static int usb_uas_get_lun(uint64_t lun64)
+{
+    return (lun64 >> 48) & 0xff;
+}
+
+static SCSIDevice *usb_uas_get_dev(UASDevice *uas, uint64_t lun64)
+{
+    if ((lun64 >> 56) != 0x00) {
+        return NULL;
+    }
+    return scsi_device_find(&uas->bus, 0, 0, usb_uas_get_lun(lun64));
+}
+
+static void usb_uas_complete_data_packet(UASRequest *req)
+{
+    USBPacket *p;
+
+    if (!req->data_async) {
+        return;
+    }
+    p = req->data;
+    req->data = NULL;
+    req->data_async = false;
+    usb_packet_complete(&req->uas->dev, p);
+}
+
+static void usb_uas_copy_data(UASRequest *req)
+{
+    uint32_t length;
+
+    length = MIN(req->buf_size - req->buf_off,
+                 req->data->iov.size - req->data->result);
+    trace_usb_uas_xfer_data(req->uas->dev.addr, req->tag, length,
+                            req->data->result, req->data->iov.size,
+                            req->buf_off, req->buf_size);
+    usb_packet_copy(req->data, scsi_req_get_buf(req->req) + req->buf_off,
+                    length);
+    req->buf_off += length;
+    req->data_off += length;
+
+    if (req->data->result == req->data->iov.size) {
+        usb_uas_complete_data_packet(req);
+    }
+    if (req->buf_size && req->buf_off == req->buf_size) {
+        req->buf_off = 0;
+        req->buf_size = 0;
+        scsi_req_continue(req->req);
+    }
+}
+
+static void usb_uas_start_next_transfer(UASDevice *uas)
+{
+    UASRequest *req;
+
+    QTAILQ_FOREACH(req, &uas->requests, next) {
+        if (req->active || req->complete) {
+            continue;
+        }
+        if (req->req->cmd.mode == SCSI_XFER_FROM_DEV && uas->datain == NULL) {
+            uas->datain = req;
+            usb_uas_queue_read_ready(req);
+            req->active = true;
+            return;
+        }
+        if (req->req->cmd.mode == SCSI_XFER_TO_DEV && uas->dataout == NULL) {
+            uas->dataout = req;
+            usb_uas_queue_write_ready(req);
+            req->active = true;
+            return;
+        }
+    }
+}
+
+static UASRequest *usb_uas_alloc_request(UASDevice *uas, uas_ui *ui)
+{
+    UASRequest *req;
+
+    req = g_new0(UASRequest, 1);
+    req->uas = uas;
+    req->tag = be16_to_cpu(ui->hdr.tag);
+    req->lun = be64_to_cpu(ui->command.lun);
+    req->dev = usb_uas_get_dev(req->uas, req->lun);
+    return req;
+}
+
+static void usb_uas_scsi_free_request(SCSIBus *bus, void *priv)
+{
+    UASRequest *req = priv;
+    UASDevice *uas = req->uas;
+
+    if (req == uas->datain) {
+        uas->datain = NULL;
+    }
+    if (req == uas->dataout) {
+        uas->dataout = NULL;
+    }
+    QTAILQ_REMOVE(&uas->requests, req, next);
+    g_free(req);
+}
+
+static UASRequest *usb_uas_find_request(UASDevice *uas, uint16_t tag)
+{
+    UASRequest *req;
+
+    QTAILQ_FOREACH(req, &uas->requests, next) {
+        if (req->tag == tag) {
+            return req;
+        }
+    }
+    return NULL;
+}
+
+static void usb_uas_scsi_transfer_data(SCSIRequest *r, uint32_t len)
+{
+    UASRequest *req = r->hba_private;
+
+    trace_usb_uas_scsi_data(req->uas->dev.addr, req->tag, len);
+    req->buf_off = 0;
+    req->buf_size = len;
+    if (req->data) {
+        usb_uas_copy_data(req);
+    } else {
+        usb_uas_start_next_transfer(req->uas);
+    }
+}
+
+static void usb_uas_scsi_command_complete(SCSIRequest *r,
+                                          uint32_t status, size_t resid)
+{
+    UASRequest *req = r->hba_private;
+    UASDevice *uas = req->uas;
+
+    trace_usb_uas_scsi_complete(req->uas->dev.addr, req->tag, status, resid);
+    req->complete = true;
+    if (req->data) {
+        usb_uas_complete_data_packet(req);
+    }
+    usb_uas_queue_sense(req, status);
+    scsi_req_unref(req->req);
+    usb_uas_start_next_transfer(uas);
+}
+
+static void usb_uas_scsi_request_cancelled(SCSIRequest *r)
+{
+    UASRequest *req = r->hba_private;
+
+    /* FIXME: queue notification to status pipe? */
+    scsi_req_unref(req->req);
+}
+
+static const struct SCSIBusInfo usb_uas_scsi_info = {
+    .tcq = true,
+    .max_target = 0,
+    .max_lun = 255,
+
+    .transfer_data = usb_uas_scsi_transfer_data,
+    .complete = usb_uas_scsi_command_complete,
+    .cancel = usb_uas_scsi_request_cancelled,
+    .free_request = usb_uas_scsi_free_request,
+};
+
+/* --------------------------------------------------------------------- */
+
+static void usb_uas_handle_reset(USBDevice *dev)
+{
+    UASDevice *uas = DO_UPCAST(UASDevice, dev, dev);
+    UASRequest *req, *nreq;
+    UASStatus *st, *nst;
+
+    trace_usb_uas_reset(dev->addr);
+    QTAILQ_FOREACH_SAFE(req, &uas->requests, next, nreq) {
+        scsi_req_cancel(req->req);
+    }
+    QTAILQ_FOREACH_SAFE(st, &uas->results, next, nst) {
+        QTAILQ_REMOVE(&uas->results, st, next);
+        g_free(st);
+    }
+}
+
+static int usb_uas_handle_control(USBDevice *dev, USBPacket *p,
+               int request, int value, int index, int length, uint8_t *data)
+{
+    int ret;
+
+    ret = usb_desc_handle_control(dev, p, request, value, index, length, data);
+    if (ret >= 0) {
+        return ret;
+    }
+    fprintf(stderr, "%s: unhandled control request\n", __func__);
+    return USB_RET_STALL;
+}
+
+static void usb_uas_cancel_io(USBDevice *dev, USBPacket *p)
+{
+    UASDevice *uas = DO_UPCAST(UASDevice, dev, dev);
+    UASRequest *req, *nreq;
+
+    if (uas->status == p) {
+        uas->status = NULL;
+        qemu_bh_cancel(uas->status_bh);
+        return;
+    }
+    QTAILQ_FOREACH_SAFE(req, &uas->requests, next, nreq) {
+        if (req->data == p) {
+            req->data = NULL;
+            return;
+        }
+    }
+    assert(!"canceled usb packet not found");
+}
+
+static void usb_uas_command(UASDevice *uas, uas_ui *ui)
+{
+    UASRequest *req;
+    uint32_t len;
+
+    req = usb_uas_find_request(uas, be16_to_cpu(ui->hdr.tag));
+    if (req) {
+        goto overlapped_tag;
+    }
+    req = usb_uas_alloc_request(uas, ui);
+    if (req->dev == NULL) {
+        goto bad_target;
+    }
+
+    trace_usb_uas_command(uas->dev.addr, req->tag,
+                          usb_uas_get_lun(req->lun),
+                          req->lun >> 32, req->lun & 0xffffffff);
+    QTAILQ_INSERT_TAIL(&uas->requests, req, next);
+    req->req = scsi_req_new(req->dev, req->tag,
+                            usb_uas_get_lun(req->lun),
+                            ui->command.cdb, req);
+    len = scsi_req_enqueue(req->req);
+    if (len) {
+        req->data_size = len;
+        scsi_req_continue(req->req);
+    }
+    return;
+
+overlapped_tag:
+    usb_uas_queue_response(uas, req->tag, UAS_RC_OVERLAPPED_TAG, 0);
+    return;
+
+bad_target:
+    /*
+     * FIXME: Seems to upset linux, is this wrong?
+     * NOTE: Happens only with no scsi devices at the bus, not sure
+     *       this is a valid UAS setup in the first place.
+     */
+    usb_uas_queue_response(uas, req->tag, UAS_RC_INVALID_INFO_UNIT, 0);
+    g_free(req);
+    return;
+}
+
+static void usb_uas_task(UASDevice *uas, uas_ui *ui)
+{
+    uint16_t tag = be16_to_cpu(ui->hdr.tag);
+    uint64_t lun64 = be64_to_cpu(ui->task.lun);
+    SCSIDevice *dev = usb_uas_get_dev(uas, lun64);
+    int lun = usb_uas_get_lun(lun64);
+    UASRequest *req;
+    uint16_t task_tag;
+
+    req = usb_uas_find_request(uas, be16_to_cpu(ui->hdr.tag));
+    if (req) {
+        goto overlapped_tag;
+    }
+
+    switch (ui->task.function) {
+    case UAS_TMF_ABORT_TASK:
+        task_tag = be16_to_cpu(ui->task.task_tag);
+        trace_usb_uas_tmf_abort_task(uas->dev.addr, tag, task_tag);
+        if (dev == NULL) {
+            goto bad_target;
+        }
+        if (dev->lun != lun) {
+            goto incorrect_lun;
+        }
+        req = usb_uas_find_request(uas, task_tag);
+        if (req && req->dev == dev) {
+            scsi_req_cancel(req->req);
+        }
+        usb_uas_queue_response(uas, tag, UAS_RC_TMF_COMPLETE, 0);
+        break;
+
+    case UAS_TMF_LOGICAL_UNIT_RESET:
+        trace_usb_uas_tmf_logical_unit_reset(uas->dev.addr, tag, lun);
+        if (dev == NULL) {
+            goto bad_target;
+        }
+        if (dev->lun != lun) {
+            goto incorrect_lun;
+        }
+        qdev_reset_all(&dev->qdev);
+        usb_uas_queue_response(uas, tag, UAS_RC_TMF_COMPLETE, 0);
+        break;
+
+    default:
+        trace_usb_uas_tmf_unsupported(uas->dev.addr, tag, ui->task.function);
+        usb_uas_queue_response(uas, tag, UAS_RC_TMF_NOT_SUPPORTED, 0);
+        break;
+    }
+    return;
+
+overlapped_tag:
+    usb_uas_queue_response(uas, req->tag, UAS_RC_OVERLAPPED_TAG, 0);
+    return;
+
+bad_target:
+    /* FIXME: correct?  [see long comment in usb_uas_command()] */
+    usb_uas_queue_response(uas, tag, UAS_RC_INVALID_INFO_UNIT, 0);
+    return;
+
+incorrect_lun:
+    usb_uas_queue_response(uas, tag, UAS_RC_INCORRECT_LUN, 0);
+    return;
+}
+
+static int usb_uas_handle_data(USBDevice *dev, USBPacket *p)
+{
+    UASDevice *uas = DO_UPCAST(UASDevice, dev, dev);
+    uas_ui ui;
+    UASStatus *st;
+    UASRequest *req;
+    int length, ret = 0;
+
+    switch (p->ep->nr) {
+    case UAS_PIPE_ID_COMMAND:
+        length = MIN(sizeof(ui), p->iov.size);
+        usb_packet_copy(p, &ui, length);
+        switch (ui.hdr.id) {
+        case UAS_UI_COMMAND:
+            usb_uas_command(uas, &ui);
+            ret = length;
+            break;
+        case UAS_UI_TASK_MGMT:
+            usb_uas_task(uas, &ui);
+            ret = length;
+            break;
+        default:
+            fprintf(stderr, "%s: unknown command ui: id 0x%x\n",
+                    __func__, ui.hdr.id);
+            ret = USB_RET_STALL;
+            break;
+        }
+        break;
+    case UAS_PIPE_ID_STATUS:
+        st = QTAILQ_FIRST(&uas->results);
+        if (st == NULL) {
+            assert(uas->status == NULL);
+            uas->status = p;
+            ret = USB_RET_ASYNC;
+            break;
+        }
+        usb_packet_copy(p, &st->status, st->length);
+        ret = st->length;
+        QTAILQ_REMOVE(&uas->results, st, next);
+        g_free(st);
+        break;
+    case UAS_PIPE_ID_DATA_IN:
+    case UAS_PIPE_ID_DATA_OUT:
+        req = (p->ep->nr == UAS_PIPE_ID_DATA_IN) ? uas->datain : uas->dataout;
+        if (req == NULL) {
+            fprintf(stderr, "%s: no inflight request\n", __func__);
+            ret = USB_RET_STALL;
+            break;
+        }
+        scsi_req_ref(req->req);
+        req->data = p;
+        usb_uas_copy_data(req);
+        if (p->result == p->iov.size || req->complete) {
+            req->data = NULL;
+            ret = p->result;
+        } else {
+            req->data_async = true;
+            ret = USB_RET_ASYNC;
+        }
+        scsi_req_unref(req->req);
+        usb_uas_start_next_transfer(uas);
+        break;
+    default:
+        fprintf(stderr, "%s: invalid endpoint %d\n", __func__, p->ep->nr);
+        ret = USB_RET_STALL;
+        break;
+    }
+    return ret;
+}
+
+static void usb_uas_handle_destroy(USBDevice *dev)
+{
+    UASDevice *uas = DO_UPCAST(UASDevice, dev, dev);
+
+    qemu_bh_delete(uas->status_bh);
+}
+
+static int usb_uas_init(USBDevice *dev)
+{
+    UASDevice *uas = DO_UPCAST(UASDevice, dev, dev);
+
+    usb_desc_create_serial(dev);
+    usb_desc_init(dev);
+
+    QTAILQ_INIT(&uas->results);
+    QTAILQ_INIT(&uas->requests);
+    uas->status_bh = qemu_bh_new(usb_uas_send_status_bh, uas);
+
+    scsi_bus_new(&uas->bus, &uas->dev.qdev, &usb_uas_scsi_info);
+
+    return 0;
+}
+
+static const VMStateDescription vmstate_usb_uas = {
+    .name = "usb-uas",
+    .unmigratable = 1,
+    .fields = (VMStateField[]) {
+        VMSTATE_USB_DEVICE(dev, UASDevice),
+        VMSTATE_END_OF_LIST()
+    }
+};
+
+static void usb_uas_class_initfn(ObjectClass *klass, void *data)
+{
+    DeviceClass *dc = DEVICE_CLASS(klass);
+    USBDeviceClass *uc = USB_DEVICE_CLASS(klass);
+
+    uc->init           = usb_uas_init;
+    uc->product_desc   = desc_strings[STR_PRODUCT];
+    uc->usb_desc       = &desc;
+    uc->cancel_packet  = usb_uas_cancel_io;
+    uc->handle_attach  = usb_desc_attach;
+    uc->handle_reset   = usb_uas_handle_reset;
+    uc->handle_control = usb_uas_handle_control;
+    uc->handle_data    = usb_uas_handle_data;
+    uc->handle_destroy = usb_uas_handle_destroy;
+    dc->fw_name = "storage";
+    dc->vmsd = &vmstate_usb_uas;
+}
+
+static TypeInfo uas_info = {
+    .name          = "usb-uas",
+    .parent        = TYPE_USB_DEVICE,
+    .instance_size = sizeof(UASDevice),
+    .class_init    = usb_uas_class_initfn,
+};
+
+static void usb_uas_register_types(void)
+{
+    type_register_static(&uas_info);
+}
+
+type_init(usb_uas_register_types)
diff --git a/trace-events b/trace-events
index 1f9fc98..04b3d93 100644
--- a/trace-events
+++ b/trace-events
@@ -347,6 +347,20 @@ usb_hub_clear_port_feature(int addr, int nr, const char *f) "dev %d, port %d, fe
 usb_hub_attach(int addr, int nr) "dev %d, port %d"
 usb_hub_detach(int addr, int nr) "dev %d, port %d"
 
+# hw/usb/dev-uas.c
+usb_uas_reset(int addr) "dev %d"
+usb_uas_command(int addr, uint16_t tag, int lun, uint32_t lun64_1, uint32_t lun64_2) "dev %d, tag 0x%x, lun %d, lun64 %08x-%08x"
+usb_uas_response(int addr, uint16_t tag, uint8_t code) "dev %d, tag 0x%x, code 0x%x"
+usb_uas_sense(int addr, uint16_t tag, uint8_t status) "dev %d, tag 0x%x, status 0x%x"
+usb_uas_read_ready(int addr, uint16_t tag) "dev %d, tag 0x%x"
+usb_uas_write_ready(int addr, uint16_t tag) "dev %d, tag 0x%x"
+usb_uas_xfer_data(int addr, uint16_t tag, uint32_t copy, uint32_t uoff, uint32_t usize, uint32_t soff, uint32_t ssize) "dev %d, tag 0x%x, copy %d, usb-pkt %d/%d, scsi-buf %d/%d"
+usb_uas_scsi_data(int addr, uint16_t tag, uint32_t bytes) "dev %d, tag 0x%x, bytes %d"
+usb_uas_scsi_complete(int addr, uint16_t tag, uint32_t status, uint32_t resid) "dev %d, tag 0x%x, status 0x%x, residue %d"
+usb_uas_tmf_abort_task(int addr, uint16_t tag, uint16_t task_tag) "dev %d, tag 0x%x, task-tag 0x%x"
+usb_uas_tmf_logical_unit_reset(int addr, uint16_t tag, int lun) "dev %d, tag 0x%x, lun %d"
+usb_uas_tmf_unsupported(int addr, uint16_t tag, uint32_t function) "dev %d, tag 0x%x, function 0x%x"
+
 # hw/usb/host-linux.c
 usb_host_open_started(int bus, int addr) "dev %d:%d"
 usb_host_open_success(int bus, int addr) "dev %d:%d"
commit 15b2bd1847239fe0b4a1041b69a631741d2e273a
Author: Paolo Bonzini <pbonzini at redhat.com>
Date:   Thu Jul 5 17:16:30 2012 +0200

    virtio: move common irqfd handling out of virtio-pci
    
    All transports can use the same event handler for the irqfd, though the
    exact mechanics of the assignment will be specific.  Note that there
    are three states: handled by the kernel, handled in userspace, disabled.
    
    This also lets virtio use event_notifier_set_handler.
    
    Signed-off-by: Paolo Bonzini <pbonzini at redhat.com>
    Signed-off-by: Avi Kivity <avi at redhat.com>

diff --git a/hw/virtio-pci.c b/hw/virtio-pci.c
index 36770fd..a66c946 100644
--- a/hw/virtio-pci.c
+++ b/hw/virtio-pci.c
@@ -496,25 +496,15 @@ static unsigned virtio_pci_get_features(void *opaque)
     return proxy->host_features;
 }
 
-static void virtio_pci_guest_notifier_read(void *opaque)
-{
-    VirtQueue *vq = opaque;
-    EventNotifier *n = virtio_queue_get_guest_notifier(vq);
-    if (event_notifier_test_and_clear(n)) {
-        virtio_irq(vq);
-    }
-}
-
 static int kvm_virtio_pci_vq_vector_use(VirtIOPCIProxy *proxy,
                                         unsigned int queue_no,
                                         unsigned int vector,
                                         MSIMessage msg)
 {
     VirtQueue *vq = virtio_get_queue(proxy->vdev, queue_no);
+    EventNotifier *n = virtio_queue_get_guest_notifier(vq);
     VirtIOIRQFD *irqfd = &proxy->vector_irqfd[vector];
-    int fd, ret;
-
-    fd = event_notifier_get_fd(virtio_queue_get_guest_notifier(vq));
+    int ret;
 
     if (irqfd->users == 0) {
         ret = kvm_irqchip_add_msi_route(kvm_state, msg);
@@ -525,7 +515,7 @@ static int kvm_virtio_pci_vq_vector_use(VirtIOPCIProxy *proxy,
     }
     irqfd->users++;
 
-    ret = kvm_irqchip_add_irqfd(kvm_state, fd, irqfd->virq);
+    ret = kvm_irqchip_add_irq_notifier(kvm_state, n, irqfd->virq);
     if (ret < 0) {
         if (--irqfd->users == 0) {
             kvm_irqchip_release_virq(kvm_state, irqfd->virq);
@@ -533,8 +523,7 @@ static int kvm_virtio_pci_vq_vector_use(VirtIOPCIProxy *proxy,
         return ret;
     }
 
-    qemu_set_fd_handler(fd, NULL, NULL, NULL);
-
+    virtio_queue_set_guest_notifier_fd_handler(vq, true, true);
     return 0;
 }
 
@@ -543,19 +532,18 @@ static void kvm_virtio_pci_vq_vector_release(VirtIOPCIProxy *proxy,
                                              unsigned int vector)
 {
     VirtQueue *vq = virtio_get_queue(proxy->vdev, queue_no);
+    EventNotifier *n = virtio_queue_get_guest_notifier(vq);
     VirtIOIRQFD *irqfd = &proxy->vector_irqfd[vector];
-    int fd, ret;
-
-    fd = event_notifier_get_fd(virtio_queue_get_guest_notifier(vq));
+    int ret;
 
-    ret = kvm_irqchip_remove_irqfd(kvm_state, fd, irqfd->virq);
+    ret = kvm_irqchip_remove_irq_notifier(kvm_state, n, irqfd->virq);
     assert(ret == 0);
 
     if (--irqfd->users == 0) {
         kvm_irqchip_release_virq(kvm_state, irqfd->virq);
     }
 
-    qemu_set_fd_handler(fd, virtio_pci_guest_notifier_read, NULL, vq);
+    virtio_queue_set_guest_notifier_fd_handler(vq, true, false);
 }
 
 static int kvm_virtio_pci_vector_use(PCIDevice *dev, unsigned vector,
@@ -617,14 +605,9 @@ static int virtio_pci_set_guest_notifier(void *opaque, int n, bool assign)
         if (r < 0) {
             return r;
         }
-        qemu_set_fd_handler(event_notifier_get_fd(notifier),
-                            virtio_pci_guest_notifier_read, NULL, vq);
+        virtio_queue_set_guest_notifier_fd_handler(vq, true, false);
     } else {
-        qemu_set_fd_handler(event_notifier_get_fd(notifier),
-                            NULL, NULL, NULL);
-        /* Test and clear notifier before closing it,
-         * in case poll callback didn't have time to run. */
-        virtio_pci_guest_notifier_read(vq);
+        virtio_queue_set_guest_notifier_fd_handler(vq, false, false);
         event_notifier_cleanup(notifier);
     }
 
diff --git a/hw/virtio.c b/hw/virtio.c
index 197edf0..d146f86 100644
--- a/hw/virtio.c
+++ b/hw/virtio.c
@@ -984,6 +984,30 @@ VirtQueue *virtio_get_queue(VirtIODevice *vdev, int n)
     return vdev->vq + n;
 }
 
+static void virtio_queue_guest_notifier_read(EventNotifier *n)
+{
+    VirtQueue *vq = container_of(n, VirtQueue, guest_notifier);
+    if (event_notifier_test_and_clear(n)) {
+        virtio_irq(vq);
+    }
+}
+
+void virtio_queue_set_guest_notifier_fd_handler(VirtQueue *vq, bool assign,
+                                                bool with_irqfd)
+{
+    if (assign && !with_irqfd) {
+        event_notifier_set_handler(&vq->guest_notifier,
+                                   virtio_queue_guest_notifier_read);
+    } else {
+        event_notifier_set_handler(&vq->guest_notifier, NULL);
+    }
+    if (!assign) {
+        /* Test and clear notifier before closing it,
+         * in case poll callback didn't have time to run. */
+        virtio_queue_guest_notifier_read(&vq->guest_notifier);
+    }
+}
+
 EventNotifier *virtio_queue_get_guest_notifier(VirtQueue *vq)
 {
     return &vq->guest_notifier;
diff --git a/hw/virtio.h b/hw/virtio.h
index 2949485..96f4dbb 100644
--- a/hw/virtio.h
+++ b/hw/virtio.h
@@ -231,6 +231,8 @@ void virtio_queue_set_last_avail_idx(VirtIODevice *vdev, int n, uint16_t idx);
 VirtQueue *virtio_get_queue(VirtIODevice *vdev, int n);
 int virtio_queue_get_id(VirtQueue *vq);
 EventNotifier *virtio_queue_get_guest_notifier(VirtQueue *vq);
+void virtio_queue_set_guest_notifier_fd_handler(VirtQueue *vq, bool assign,
+                                                bool with_irqfd);
 EventNotifier *virtio_queue_get_host_notifier(VirtQueue *vq);
 void virtio_queue_set_host_notifier_fd_handler(VirtQueue *vq, bool assign);
 void virtio_queue_notify_vq(VirtQueue *vq);
diff --git a/kvm-all.c b/kvm-all.c
index 5a386b4..add24a1 100644
--- a/kvm-all.c
+++ b/kvm-all.c
@@ -1163,11 +1163,21 @@ int kvm_irqchip_add_irqfd(KVMState *s, int fd, int virq)
     return kvm_irqchip_assign_irqfd(s, fd, virq, true);
 }
 
+int kvm_irqchip_add_irq_notifier(KVMState *s, EventNotifier *n, int virq)
+{
+    return kvm_irqchip_add_irqfd(s, event_notifier_get_fd(n), virq);
+}
+
 int kvm_irqchip_remove_irqfd(KVMState *s, int fd, int virq)
 {
     return kvm_irqchip_assign_irqfd(s, fd, virq, false);
 }
 
+int kvm_irqchip_remove_irq_notifier(KVMState *s, EventNotifier *n, int virq)
+{
+    return kvm_irqchip_remove_irqfd(s, event_notifier_get_fd(n), virq);
+}
+
 static int kvm_irqchip_create(KVMState *s)
 {
     QemuOptsList *list = qemu_find_opts("machine");
diff --git a/kvm-stub.c b/kvm-stub.c
index ec9a364..d23b11c 100644
--- a/kvm-stub.c
+++ b/kvm-stub.c
@@ -147,7 +147,17 @@ int kvm_irqchip_add_irqfd(KVMState *s, int fd, int virq)
     return -ENOSYS;
 }
 
+int kvm_irqchip_add_irq_notifier(KVMState *s, EventNotifier *n, int virq)
+{
+    return -ENOSYS;
+}
+
 int kvm_irqchip_remove_irqfd(KVMState *s, int fd, int virq)
 {
     return -ENOSYS;
 }
+
+int kvm_irqchip_remove_irq_notifier(KVMState *s, EventNotifier *n, int virq)
+{
+    return -ENOSYS;
+}
diff --git a/kvm.h b/kvm.h
index 9c7b0ea..99003f4 100644
--- a/kvm.h
+++ b/kvm.h
@@ -218,4 +218,6 @@ void kvm_irqchip_release_virq(KVMState *s, int virq);
 
 int kvm_irqchip_add_irqfd(KVMState *s, int fd, int virq);
 int kvm_irqchip_remove_irqfd(KVMState *s, int fd, int virq);
+int kvm_irqchip_add_irq_notifier(KVMState *s, EventNotifier *n, int virq);
+int kvm_irqchip_remove_irq_notifier(KVMState *s, EventNotifier *n, int virq);
 #endif
commit b1f416aa8d870fab71030abc9401cfc77b948e8e
Author: Paolo Bonzini <pbonzini at redhat.com>
Date:   Thu Jul 5 17:16:29 2012 +0200

    virtio: move common ioeventfd handling out of virtio-pci
    
    All transports can use the same event handler for the ioeventfd, though
    the exact setup (address/memory region) will be specific.
    
    This lets virtio use event_notifier_set_handler.
    
    Signed-off-by: Paolo Bonzini <pbonzini at redhat.com>
    Signed-off-by: Avi Kivity <avi at redhat.com>

diff --git a/hw/virtio-pci.c b/hw/virtio-pci.c
index a555728..36770fd 100644
--- a/hw/virtio-pci.c
+++ b/hw/virtio-pci.c
@@ -173,46 +173,18 @@ static int virtio_pci_set_host_notifier_internal(VirtIOPCIProxy *proxy,
                          __func__, r);
             return r;
         }
+        virtio_queue_set_host_notifier_fd_handler(vq, true);
         memory_region_add_eventfd(&proxy->bar, VIRTIO_PCI_QUEUE_NOTIFY, 2,
                                   true, n, notifier);
     } else {
         memory_region_del_eventfd(&proxy->bar, VIRTIO_PCI_QUEUE_NOTIFY, 2,
                                   true, n, notifier);
-        /* Handle the race condition where the guest kicked and we deassigned
-         * before we got around to handling the kick.
-         */
-        if (event_notifier_test_and_clear(notifier)) {
-            virtio_queue_notify_vq(vq);
-        }
-
+        virtio_queue_set_host_notifier_fd_handler(vq, false);
         event_notifier_cleanup(notifier);
     }
     return r;
 }
 
-static void virtio_pci_host_notifier_read(void *opaque)
-{
-    VirtQueue *vq = opaque;
-    EventNotifier *n = virtio_queue_get_host_notifier(vq);
-    if (event_notifier_test_and_clear(n)) {
-        virtio_queue_notify_vq(vq);
-    }
-}
-
-static void virtio_pci_set_host_notifier_fd_handler(VirtIOPCIProxy *proxy,
-                                                    int n, bool assign)
-{
-    VirtQueue *vq = virtio_get_queue(proxy->vdev, n);
-    EventNotifier *notifier = virtio_queue_get_host_notifier(vq);
-    if (assign) {
-        qemu_set_fd_handler(event_notifier_get_fd(notifier),
-                            virtio_pci_host_notifier_read, NULL, vq);
-    } else {
-        qemu_set_fd_handler(event_notifier_get_fd(notifier),
-                            NULL, NULL, NULL);
-    }
-}
-
 static void virtio_pci_start_ioeventfd(VirtIOPCIProxy *proxy)
 {
     int n, r;
@@ -232,8 +204,6 @@ static void virtio_pci_start_ioeventfd(VirtIOPCIProxy *proxy)
         if (r < 0) {
             goto assign_error;
         }
-
-        virtio_pci_set_host_notifier_fd_handler(proxy, n, true);
     }
     proxy->ioeventfd_started = true;
     return;
@@ -244,7 +214,6 @@ assign_error:
             continue;
         }
 
-        virtio_pci_set_host_notifier_fd_handler(proxy, n, false);
         r = virtio_pci_set_host_notifier_internal(proxy, n, false);
         assert(r >= 0);
     }
@@ -266,7 +235,6 @@ static void virtio_pci_stop_ioeventfd(VirtIOPCIProxy *proxy)
             continue;
         }
 
-        virtio_pci_set_host_notifier_fd_handler(proxy, n, false);
         r = virtio_pci_set_host_notifier_internal(proxy, n, false);
         assert(r >= 0);
     }
diff --git a/hw/virtio.c b/hw/virtio.c
index 168abe4..197edf0 100644
--- a/hw/virtio.c
+++ b/hw/virtio.c
@@ -988,6 +988,28 @@ EventNotifier *virtio_queue_get_guest_notifier(VirtQueue *vq)
 {
     return &vq->guest_notifier;
 }
+
+static void virtio_queue_host_notifier_read(EventNotifier *n)
+{
+    VirtQueue *vq = container_of(n, VirtQueue, host_notifier);
+    if (event_notifier_test_and_clear(n)) {
+        virtio_queue_notify_vq(vq);
+    }
+}
+
+void virtio_queue_set_host_notifier_fd_handler(VirtQueue *vq, bool assign)
+{
+    if (assign) {
+        event_notifier_set_handler(&vq->host_notifier,
+                                   virtio_queue_host_notifier_read);
+    } else {
+        event_notifier_set_handler(&vq->host_notifier, NULL);
+        /* Test and clear notifier before after disabling event,
+         * in case poll callback didn't have time to run. */
+        virtio_queue_host_notifier_read(&vq->host_notifier);
+    }
+}
+
 EventNotifier *virtio_queue_get_host_notifier(VirtQueue *vq)
 {
     return &vq->host_notifier;
diff --git a/hw/virtio.h b/hw/virtio.h
index 85aabe5..2949485 100644
--- a/hw/virtio.h
+++ b/hw/virtio.h
@@ -232,6 +232,7 @@ VirtQueue *virtio_get_queue(VirtIODevice *vdev, int n);
 int virtio_queue_get_id(VirtQueue *vq);
 EventNotifier *virtio_queue_get_guest_notifier(VirtQueue *vq);
 EventNotifier *virtio_queue_get_host_notifier(VirtQueue *vq);
+void virtio_queue_set_host_notifier_fd_handler(VirtQueue *vq, bool assign);
 void virtio_queue_notify_vq(VirtQueue *vq);
 void virtio_irq(VirtQueue *vq);
 #endif
commit 6bf819f0a2a77dc8504651f369293f0efac54fe5
Author: Paolo Bonzini <pbonzini at redhat.com>
Date:   Thu Jul 5 17:16:28 2012 +0200

    event_notifier: add event_notifier_set_handler
    
    Win32 event notifiers are not file descriptors, so they will not be able
    to use qemu_set_fd_handler.  But even if for now we only have a POSIX
    version of EventNotifier, we can add a specific function that wraps
    the call.
    
    The wrapper passes the EventNotifier as the opaque value so that it will
    be used with container_of.
    
    Signed-off-by: Paolo Bonzini <pbonzini at redhat.com>
    Signed-off-by: Avi Kivity <avi at redhat.com>

diff --git a/event_notifier.c b/event_notifier.c
index 99c376c..2c207e1 100644
--- a/event_notifier.c
+++ b/event_notifier.c
@@ -12,6 +12,7 @@
 
 #include "qemu-common.h"
 #include "event_notifier.h"
+#include "qemu-char.h"
 
 #ifdef CONFIG_EVENTFD
 #include <sys/eventfd.h>
@@ -45,6 +46,12 @@ int event_notifier_get_fd(EventNotifier *e)
     return e->fd;
 }
 
+int event_notifier_set_handler(EventNotifier *e,
+                               EventNotifierHandler *handler)
+{
+    return qemu_set_fd_handler(e->fd, (IOHandler *)handler, NULL, e);
+}
+
 int event_notifier_set(EventNotifier *e)
 {
     uint64_t value = 1;
diff --git a/event_notifier.h b/event_notifier.h
index fd3d942..f0ec2f2 100644
--- a/event_notifier.h
+++ b/event_notifier.h
@@ -19,11 +19,14 @@ struct EventNotifier {
     int fd;
 };
 
+typedef void EventNotifierHandler(EventNotifier *);
+
 void event_notifier_init_fd(EventNotifier *, int fd);
 int event_notifier_init(EventNotifier *, int active);
 void event_notifier_cleanup(EventNotifier *);
 int event_notifier_get_fd(EventNotifier *);
 int event_notifier_set(EventNotifier *);
 int event_notifier_test_and_clear(EventNotifier *);
+int event_notifier_set_handler(EventNotifier *, EventNotifierHandler *);
 
 #endif
commit 753d5e14c4cd9e545242971c5d149fe5da0a5ba1
Author: Paolo Bonzini <pbonzini at redhat.com>
Date:   Thu Jul 5 17:16:27 2012 +0200

    memory: pass EventNotifier, not eventfd
    
    Under Win32, EventNotifiers will not have event_notifier_get_fd, so we
    cannot call it in common code such as hw/virtio-pci.c.  Pass a pointer to
    the notifier, and only retrieve the file descriptor in kvm-specific code.
    
    Signed-off-by: Paolo Bonzini <pbonzini at redhat.com>
    Signed-off-by: Avi Kivity <avi at redhat.com>

diff --git a/exec.c b/exec.c
index 8244d54..29b5078 100644
--- a/exec.c
+++ b/exec.c
@@ -3212,13 +3212,13 @@ static void core_log_global_stop(MemoryListener *listener)
 
 static void core_eventfd_add(MemoryListener *listener,
                              MemoryRegionSection *section,
-                             bool match_data, uint64_t data, int fd)
+                             bool match_data, uint64_t data, EventNotifier *e)
 {
 }
 
 static void core_eventfd_del(MemoryListener *listener,
                              MemoryRegionSection *section,
-                             bool match_data, uint64_t data, int fd)
+                             bool match_data, uint64_t data, EventNotifier *e)
 {
 }
 
@@ -3278,13 +3278,13 @@ static void io_log_global_stop(MemoryListener *listener)
 
 static void io_eventfd_add(MemoryListener *listener,
                            MemoryRegionSection *section,
-                           bool match_data, uint64_t data, int fd)
+                           bool match_data, uint64_t data, EventNotifier *e)
 {
 }
 
 static void io_eventfd_del(MemoryListener *listener,
                            MemoryRegionSection *section,
-                           bool match_data, uint64_t data, int fd)
+                           bool match_data, uint64_t data, EventNotifier *e)
 {
 }
 
diff --git a/hw/ivshmem.c b/hw/ivshmem.c
index 19e164a..bba21c5 100644
--- a/hw/ivshmem.c
+++ b/hw/ivshmem.c
@@ -350,7 +350,7 @@ static void ivshmem_add_eventfd(IVShmemState *s, int posn, int i)
                               4,
                               true,
                               (posn << 16) | i,
-                              event_notifier_get_fd(&s->peers[posn].eventfds[i]));
+                              &s->peers[posn].eventfds[i]);
 }
 
 static void ivshmem_del_eventfd(IVShmemState *s, int posn, int i)
@@ -360,7 +360,7 @@ static void ivshmem_del_eventfd(IVShmemState *s, int posn, int i)
                               4,
                               true,
                               (posn << 16) | i,
-                              event_notifier_get_fd(&s->peers[posn].eventfds[i]));
+                              &s->peers[posn].eventfds[i]);
 }
 
 static void close_guest_eventfds(IVShmemState *s, int posn)
diff --git a/hw/vhost.c b/hw/vhost.c
index 43664e7..0fd8da8 100644
--- a/hw/vhost.c
+++ b/hw/vhost.c
@@ -737,13 +737,13 @@ static void vhost_virtqueue_cleanup(struct vhost_dev *dev,
 
 static void vhost_eventfd_add(MemoryListener *listener,
                               MemoryRegionSection *section,
-                              bool match_data, uint64_t data, int fd)
+                              bool match_data, uint64_t data, EventNotifier *e)
 {
 }
 
 static void vhost_eventfd_del(MemoryListener *listener,
                               MemoryRegionSection *section,
-                              bool match_data, uint64_t data, int fd)
+                              bool match_data, uint64_t data, EventNotifier *e)
 {
 }
 
diff --git a/hw/virtio-pci.c b/hw/virtio-pci.c
index 9342eed..a555728 100644
--- a/hw/virtio-pci.c
+++ b/hw/virtio-pci.c
@@ -174,10 +174,10 @@ static int virtio_pci_set_host_notifier_internal(VirtIOPCIProxy *proxy,
             return r;
         }
         memory_region_add_eventfd(&proxy->bar, VIRTIO_PCI_QUEUE_NOTIFY, 2,
-                                  true, n, event_notifier_get_fd(notifier));
+                                  true, n, notifier);
     } else {
         memory_region_del_eventfd(&proxy->bar, VIRTIO_PCI_QUEUE_NOTIFY, 2,
-                                  true, n, event_notifier_get_fd(notifier));
+                                  true, n, notifier);
         /* Handle the race condition where the guest kicked and we deassigned
          * before we got around to handling the kick.
          */
diff --git a/hw/xen_pt.c b/hw/xen_pt.c
index 3b6d186..fdf68aa 100644
--- a/hw/xen_pt.c
+++ b/hw/xen_pt.c
@@ -634,7 +634,7 @@ static void xen_pt_log_global_fns(MemoryListener *l)
 }
 
 static void xen_pt_eventfd_fns(MemoryListener *l, MemoryRegionSection *s,
-                               bool match_data, uint64_t data, int fd)
+                               bool match_data, uint64_t data, EventNotifier *n)
 {
 }
 
diff --git a/kvm-all.c b/kvm-all.c
index a0c33b3..5a386b4 100644
--- a/kvm-all.c
+++ b/kvm-all.c
@@ -32,6 +32,7 @@
 #include "bswap.h"
 #include "memory.h"
 #include "exec-memory.h"
+#include "event_notifier.h"
 
 /* This check must be after config-host.h is included */
 #ifdef CONFIG_EVENTFD
@@ -800,23 +801,29 @@ static void kvm_io_ioeventfd_del(MemoryRegionSection *section,
 
 static void kvm_eventfd_add(MemoryListener *listener,
                             MemoryRegionSection *section,
-                            bool match_data, uint64_t data, int fd)
+                            bool match_data, uint64_t data,
+                            EventNotifier *e)
 {
     if (section->address_space == get_system_memory()) {
-        kvm_mem_ioeventfd_add(section, match_data, data, fd);
+        kvm_mem_ioeventfd_add(section, match_data, data,
+			      event_notifier_get_fd(e));
     } else {
-        kvm_io_ioeventfd_add(section, match_data, data, fd);
+        kvm_io_ioeventfd_add(section, match_data, data,
+			     event_notifier_get_fd(e));
     }
 }
 
 static void kvm_eventfd_del(MemoryListener *listener,
                             MemoryRegionSection *section,
-                            bool match_data, uint64_t data, int fd)
+                            bool match_data, uint64_t data,
+                            EventNotifier *e)
 {
     if (section->address_space == get_system_memory()) {
-        kvm_mem_ioeventfd_del(section, match_data, data, fd);
+        kvm_mem_ioeventfd_del(section, match_data, data,
+			      event_notifier_get_fd(e));
     } else {
-        kvm_io_ioeventfd_del(section, match_data, data, fd);
+        kvm_io_ioeventfd_del(section, match_data, data,
+			     event_notifier_get_fd(e));
     }
 }
 
diff --git a/memory.c b/memory.c
index aab4a31..643871b 100644
--- a/memory.c
+++ b/memory.c
@@ -156,7 +156,7 @@ struct MemoryRegionIoeventfd {
     AddrRange addr;
     bool match_data;
     uint64_t data;
-    int fd;
+    EventNotifier *e;
 };
 
 static bool memory_region_ioeventfd_before(MemoryRegionIoeventfd a,
@@ -181,9 +181,9 @@ static bool memory_region_ioeventfd_before(MemoryRegionIoeventfd a,
             return false;
         }
     }
-    if (a.fd < b.fd) {
+    if (a.e < b.e) {
         return true;
-    } else if (a.fd > b.fd) {
+    } else if (a.e > b.e) {
         return false;
     }
     return false;
@@ -597,7 +597,7 @@ static void address_space_add_del_ioeventfds(AddressSpace *as,
                 .size = int128_get64(fd->addr.size),
             };
             MEMORY_LISTENER_CALL(eventfd_del, Forward, &section,
-                                 fd->match_data, fd->data, fd->fd);
+                                 fd->match_data, fd->data, fd->e);
             ++iold;
         } else if (inew < fds_new_nb
                    && (iold == fds_old_nb
@@ -610,7 +610,7 @@ static void address_space_add_del_ioeventfds(AddressSpace *as,
                 .size = int128_get64(fd->addr.size),
             };
             MEMORY_LISTENER_CALL(eventfd_add, Reverse, &section,
-                                 fd->match_data, fd->data, fd->fd);
+                                 fd->match_data, fd->data, fd->e);
             ++inew;
         } else {
             ++iold;
@@ -1195,14 +1195,14 @@ void memory_region_add_eventfd(MemoryRegion *mr,
                                unsigned size,
                                bool match_data,
                                uint64_t data,
-                               int fd)
+                               EventNotifier *e)
 {
     MemoryRegionIoeventfd mrfd = {
         .addr.start = int128_make64(addr),
         .addr.size = int128_make64(size),
         .match_data = match_data,
         .data = data,
-        .fd = fd,
+        .e = e,
     };
     unsigned i;
 
@@ -1225,14 +1225,14 @@ void memory_region_del_eventfd(MemoryRegion *mr,
                                unsigned size,
                                bool match_data,
                                uint64_t data,
-                               int fd)
+                               EventNotifier *e)
 {
     MemoryRegionIoeventfd mrfd = {
         .addr.start = int128_make64(addr),
         .addr.size = int128_make64(size),
         .match_data = match_data,
         .data = data,
-        .fd = fd,
+        .e = e,
     };
     unsigned i;
 
diff --git a/memory.h b/memory.h
index 740c48e..bd1bbae 100644
--- a/memory.h
+++ b/memory.h
@@ -198,9 +198,9 @@ struct MemoryListener {
     void (*log_global_start)(MemoryListener *listener);
     void (*log_global_stop)(MemoryListener *listener);
     void (*eventfd_add)(MemoryListener *listener, MemoryRegionSection *section,
-                        bool match_data, uint64_t data, int fd);
+                        bool match_data, uint64_t data, EventNotifier *e);
     void (*eventfd_del)(MemoryListener *listener, MemoryRegionSection *section,
-                        bool match_data, uint64_t data, int fd);
+                        bool match_data, uint64_t data, EventNotifier *e);
     /* Lower = earlier (during add), later (during del) */
     unsigned priority;
     MemoryRegion *address_space_filter;
@@ -541,7 +541,7 @@ void memory_region_add_eventfd(MemoryRegion *mr,
                                unsigned size,
                                bool match_data,
                                uint64_t data,
-                               int fd);
+                               EventNotifier *e);
 
 /**
  * memory_region_del_eventfd: Cancel an eventfd.
@@ -561,7 +561,8 @@ void memory_region_del_eventfd(MemoryRegion *mr,
                                unsigned size,
                                bool match_data,
                                uint64_t data,
-                               int fd);
+                               EventNotifier *e);
+
 /**
  * memory_region_add_subregion: Add a subregion to a container.
  *
diff --git a/xen-all.c b/xen-all.c
index 59f2323..61def2e 100644
--- a/xen-all.c
+++ b/xen-all.c
@@ -560,13 +560,15 @@ static void xen_log_global_stop(MemoryListener *listener)
 
 static void xen_eventfd_add(MemoryListener *listener,
                             MemoryRegionSection *section,
-                            bool match_data, uint64_t data, int fd)
+                            bool match_data, uint64_t data,
+                            EventNotifier *e)
 {
 }
 
 static void xen_eventfd_del(MemoryListener *listener,
                             MemoryRegionSection *section,
-                            bool match_data, uint64_t data, int fd)
+                            bool match_data, uint64_t data,
+                            EventNotifier *e)
 {
 }
 
commit b6a1f3a56921c80cd04d8130e713028c7c91edc1
Author: Paolo Bonzini <pbonzini at redhat.com>
Date:   Thu Jul 5 17:16:26 2012 +0200

    ivshmem: wrap ivshmem_del_eventfd loops with transaction
    
    Signed-off-by: Paolo Bonzini <pbonzini at redhat.com>
    Signed-off-by: Avi Kivity <avi at redhat.com>

diff --git a/hw/ivshmem.c b/hw/ivshmem.c
index 3cdbea2..19e164a 100644
--- a/hw/ivshmem.c
+++ b/hw/ivshmem.c
@@ -369,8 +369,12 @@ static void close_guest_eventfds(IVShmemState *s, int posn)
 
     guest_curr_max = s->peers[posn].nb_eventfds;
 
+    memory_region_transaction_begin();
     for (i = 0; i < guest_curr_max; i++) {
         ivshmem_del_eventfd(s, posn, i);
+    }
+    memory_region_transaction_commit();
+    for (i = 0; i < guest_curr_max; i++) {
         event_notifier_cleanup(&s->peers[posn].eventfds[i]);
     }
 
commit 563027cc0c94aa4846c18f9d665a4c90f8c42ba8
Author: Paolo Bonzini <pbonzini at redhat.com>
Date:   Thu Jul 5 17:16:25 2012 +0200

    ivshmem: use EventNotifier and memory API
    
    All of ivshmem's usage of eventfd now has a corresponding API in
    EventNotifier.  Simplify the code by using it, and also use the
    memory API consistently to set up and tear down the ioeventfds.
    
    Signed-off-by: Paolo Bonzini <pbonzini at redhat.com>
    Signed-off-by: Avi Kivity <avi at redhat.com>

diff --git a/hw/ivshmem.c b/hw/ivshmem.c
index 05559b6..3cdbea2 100644
--- a/hw/ivshmem.c
+++ b/hw/ivshmem.c
@@ -23,6 +23,7 @@
 #include "kvm.h"
 #include "migration.h"
 #include "qerror.h"
+#include "event_notifier.h"
 
 #include <sys/mman.h>
 #include <sys/types.h>
@@ -45,7 +46,7 @@
 
 typedef struct Peer {
     int nb_eventfds;
-    int *eventfds;
+    EventNotifier *eventfds;
 } Peer;
 
 typedef struct EventfdEntry {
@@ -63,7 +64,6 @@ typedef struct IVShmemState {
     CharDriverState *server_chr;
     MemoryRegion ivshmem_mmio;
 
-    pcibus_t mmio_addr;
     /* We might need to register the BAR before we actually have the memory.
      * So prepare a container MemoryRegion for the BAR immediately and
      * add a subregion when we have the memory.
@@ -168,7 +168,6 @@ static void ivshmem_io_write(void *opaque, target_phys_addr_t addr,
 {
     IVShmemState *s = opaque;
 
-    uint64_t write_one = 1;
     uint16_t dest = val >> 16;
     uint16_t vector = val & 0xff;
 
@@ -194,12 +193,8 @@ static void ivshmem_io_write(void *opaque, target_phys_addr_t addr,
 
             /* check doorbell range */
             if (vector < s->peers[dest].nb_eventfds) {
-                IVSHMEM_DPRINTF("Writing %" PRId64 " to VM %d on vector %d\n",
-                                                    write_one, dest, vector);
-                if (write(s->peers[dest].eventfds[vector],
-                                                    &(write_one), 8) != 8) {
-                    IVSHMEM_DPRINTF("error writing to eventfd\n");
-                }
+                IVSHMEM_DPRINTF("Notifying VM %d on vector %d\n", dest, vector);
+                event_notifier_set(&s->peers[dest].eventfds[vector]);
             }
             break;
         default:
@@ -279,12 +274,13 @@ static void fake_irqfd(void *opaque, const uint8_t *buf, int size) {
     msix_notify(pdev, entry->vector);
 }
 
-static CharDriverState* create_eventfd_chr_device(void * opaque, int eventfd,
-                                                                    int vector)
+static CharDriverState* create_eventfd_chr_device(void * opaque, EventNotifier *n,
+                                                  int vector)
 {
     /* create a event character device based on the passed eventfd */
     IVShmemState *s = opaque;
     CharDriverState * chr;
+    int eventfd = event_notifier_get_fd(n);
 
     chr = qemu_chr_open_eventfd(eventfd);
 
@@ -347,6 +343,26 @@ static void create_shared_memory_BAR(IVShmemState *s, int fd) {
     pci_register_bar(&s->dev, 2, PCI_BASE_ADDRESS_SPACE_MEMORY, &s->bar);
 }
 
+static void ivshmem_add_eventfd(IVShmemState *s, int posn, int i)
+{
+    memory_region_add_eventfd(&s->ivshmem_mmio,
+                              DOORBELL,
+                              4,
+                              true,
+                              (posn << 16) | i,
+                              event_notifier_get_fd(&s->peers[posn].eventfds[i]));
+}
+
+static void ivshmem_del_eventfd(IVShmemState *s, int posn, int i)
+{
+    memory_region_del_eventfd(&s->ivshmem_mmio,
+                              DOORBELL,
+                              4,
+                              true,
+                              (posn << 16) | i,
+                              event_notifier_get_fd(&s->peers[posn].eventfds[i]));
+}
+
 static void close_guest_eventfds(IVShmemState *s, int posn)
 {
     int i, guest_curr_max;
@@ -354,9 +370,8 @@ static void close_guest_eventfds(IVShmemState *s, int posn)
     guest_curr_max = s->peers[posn].nb_eventfds;
 
     for (i = 0; i < guest_curr_max; i++) {
-        kvm_set_ioeventfd_mmio(s->peers[posn].eventfds[i],
-                    s->mmio_addr + DOORBELL, (posn << 16) | i, 0, 4);
-        close(s->peers[posn].eventfds[i]);
+        ivshmem_del_eventfd(s, posn, i);
+        event_notifier_cleanup(&s->peers[posn].eventfds[i]);
     }
 
     g_free(s->peers[posn].eventfds);
@@ -369,12 +384,7 @@ static void setup_ioeventfds(IVShmemState *s) {
 
     for (i = 0; i <= s->max_peer; i++) {
         for (j = 0; j < s->peers[i].nb_eventfds; j++) {
-            memory_region_add_eventfd(&s->ivshmem_mmio,
-                                      DOORBELL,
-                                      4,
-                                      true,
-                                      (i << 16) | j,
-                                      s->peers[i].eventfds[j]);
+            ivshmem_add_eventfd(s, i, j);
         }
     }
 }
@@ -476,14 +486,14 @@ static void ivshmem_read(void *opaque, const uint8_t * buf, int flags)
 
     if (guest_max_eventfd == 0) {
         /* one eventfd per MSI vector */
-        s->peers[incoming_posn].eventfds = (int *) g_malloc(s->vectors *
-                                                                sizeof(int));
+        s->peers[incoming_posn].eventfds = g_new(EventNotifier, s->vectors);
     }
 
     /* this is an eventfd for a particular guest VM */
     IVSHMEM_DPRINTF("eventfds[%ld][%d] = %d\n", incoming_posn,
                                             guest_max_eventfd, incoming_fd);
-    s->peers[incoming_posn].eventfds[guest_max_eventfd] = incoming_fd;
+    event_notifier_init_fd(&s->peers[incoming_posn].eventfds[guest_max_eventfd],
+                           incoming_fd);
 
     /* increment count for particular guest */
     s->peers[incoming_posn].nb_eventfds++;
@@ -495,15 +505,12 @@ static void ivshmem_read(void *opaque, const uint8_t * buf, int flags)
 
     if (incoming_posn == s->vm_id) {
         s->eventfd_chr[guest_max_eventfd] = create_eventfd_chr_device(s,
-                   s->peers[s->vm_id].eventfds[guest_max_eventfd],
+                   &s->peers[s->vm_id].eventfds[guest_max_eventfd],
                    guest_max_eventfd);
     }
 
     if (ivshmem_has_feature(s, IVSHMEM_IOEVENTFD)) {
-        if (kvm_set_ioeventfd_mmio(incoming_fd, s->mmio_addr + DOORBELL,
-                        (incoming_posn << 16) | guest_max_eventfd, 1, 4) < 0) {
-            fprintf(stderr, "ivshmem: ioeventfd not available\n");
-        }
+        ivshmem_add_eventfd(s, incoming_posn, guest_max_eventfd);
     }
 
     return;
commit e80c262be7f821051a6d89b39fe21d951848dece
Author: Paolo Bonzini <pbonzini at redhat.com>
Date:   Thu Jul 5 17:16:24 2012 +0200

    event_notifier: add event_notifier_init_fd
    
    Signed-off-by: Paolo Bonzini <pbonzini at redhat.com>
    Signed-off-by: Avi Kivity <avi at redhat.com>

diff --git a/event_notifier.c b/event_notifier.c
index c339bfe..99c376c 100644
--- a/event_notifier.c
+++ b/event_notifier.c
@@ -10,11 +10,18 @@
  * See the COPYING file in the top-level directory.
  */
 
+#include "qemu-common.h"
 #include "event_notifier.h"
+
 #ifdef CONFIG_EVENTFD
 #include <sys/eventfd.h>
 #endif
 
+void event_notifier_init_fd(EventNotifier *e, int fd)
+{
+    e->fd = fd;
+}
+
 int event_notifier_init(EventNotifier *e, int active)
 {
 #ifdef CONFIG_EVENTFD
diff --git a/event_notifier.h b/event_notifier.h
index 9b2edf4..fd3d942 100644
--- a/event_notifier.h
+++ b/event_notifier.h
@@ -16,9 +16,10 @@
 #include "qemu-common.h"
 
 struct EventNotifier {
-	int fd;
+    int fd;
 };
 
+void event_notifier_init_fd(EventNotifier *, int fd);
 int event_notifier_init(EventNotifier *, int active);
 void event_notifier_cleanup(EventNotifier *);
 int event_notifier_get_fd(EventNotifier *);
commit ebe7acea532fba4a0ad7aaf74e59bff729867d93
Author: Paolo Bonzini <pbonzini at redhat.com>
Date:   Thu Jul 5 17:16:23 2012 +0200

    event_notifier: remove event_notifier_test
    
    The function is useless (and unused).
    
    Signed-off-by: Paolo Bonzini <pbonzini at redhat.com>
    Signed-off-by: Avi Kivity <avi at redhat.com>

diff --git a/event_notifier.c b/event_notifier.c
index 2b210f4..c339bfe 100644
--- a/event_notifier.c
+++ b/event_notifier.c
@@ -51,18 +51,3 @@ int event_notifier_test_and_clear(EventNotifier *e)
     int r = read(e->fd, &value, sizeof(value));
     return r == sizeof(value);
 }
-
-int event_notifier_test(EventNotifier *e)
-{
-    uint64_t value;
-    int r = read(e->fd, &value, sizeof(value));
-    if (r == sizeof(value)) {
-        /* restore previous value. */
-        int s = write(e->fd, &value, sizeof(value));
-        /* never blocks because we use EFD_SEMAPHORE.
-         * If we didn't we'd get EAGAIN on overflow
-         * and we'd have to write code to ignore it. */
-        assert(s == sizeof(value));
-    }
-    return r == sizeof(value);
-}
diff --git a/event_notifier.h b/event_notifier.h
index efca852..9b2edf4 100644
--- a/event_notifier.h
+++ b/event_notifier.h
@@ -24,6 +24,5 @@ void event_notifier_cleanup(EventNotifier *);
 int event_notifier_get_fd(EventNotifier *);
 int event_notifier_set(EventNotifier *);
 int event_notifier_test_and_clear(EventNotifier *);
-int event_notifier_test(EventNotifier *);
 
 #endif
commit 2ec10b952b40d287037a50387a8b66d9ccc5124b
Author: Paolo Bonzini <pbonzini at redhat.com>
Date:   Thu Jul 5 17:16:22 2012 +0200

    event_notifier: add event_notifier_set
    
    EventNotifier right now cannot be used as an inter-thread communication
    primitive.  It only works if something else (the kernel) sets the eventfd.
    Add a primitive to signal an EventNotifier that another thread is waiting
    on.
    
    Signed-off-by: Paolo Bonzini <pbonzini at redhat.com>
    Signed-off-by: Avi Kivity <avi at redhat.com>

diff --git a/event_notifier.c b/event_notifier.c
index 0b82981..2b210f4 100644
--- a/event_notifier.c
+++ b/event_notifier.c
@@ -38,6 +38,13 @@ int event_notifier_get_fd(EventNotifier *e)
     return e->fd;
 }
 
+int event_notifier_set(EventNotifier *e)
+{
+    uint64_t value = 1;
+    int r = write(e->fd, &value, sizeof(value));
+    return r == sizeof(value);
+}
+
 int event_notifier_test_and_clear(EventNotifier *e)
 {
     uint64_t value;
diff --git a/event_notifier.h b/event_notifier.h
index 886222c..efca852 100644
--- a/event_notifier.h
+++ b/event_notifier.h
@@ -22,6 +22,7 @@ struct EventNotifier {
 int event_notifier_init(EventNotifier *, int active);
 void event_notifier_cleanup(EventNotifier *);
 int event_notifier_get_fd(EventNotifier *);
+int event_notifier_set(EventNotifier *);
 int event_notifier_test_and_clear(EventNotifier *);
 int event_notifier_test(EventNotifier *);
 
commit 3dde962f39717737b1031de129754f21eb77979f
Author: Peter Maydell <peter.maydell at linaro.org>
Date:   Thu Jul 12 10:59:12 2012 +0000

    target-arm: Add support for long format translation table walks
    
    Implement the actual table walk code for LPAE's long format
    translation tables.
    
    Signed-off-by: Peter Maydell <peter.maydell at linaro.org>

diff --git a/target-arm/helper.c b/target-arm/helper.c
index 72b44b0..5727da2 100644
--- a/target-arm/helper.c
+++ b/target-arm/helper.c
@@ -3,6 +3,7 @@
 #include "helper.h"
 #include "host-utils.h"
 #include "sysemu.h"
+#include "bitops.h"
 
 #ifndef CONFIG_USER_ONLY
 static inline int get_phys_addr(CPUARMState *env, uint32_t address,
@@ -2184,6 +2185,184 @@ do_fault:
     return code | (domain << 4);
 }
 
+/* Fault type for long-descriptor MMU fault reporting; this corresponds
+ * to bits [5..2] in the STATUS field in long-format DFSR/IFSR.
+ */
+typedef enum {
+    translation_fault = 1,
+    access_fault = 2,
+    permission_fault = 3,
+} MMUFaultType;
+
+static int get_phys_addr_lpae(CPUARMState *env, uint32_t address,
+                              int access_type, int is_user,
+                              target_phys_addr_t *phys_ptr, int *prot,
+                              target_ulong *page_size_ptr)
+{
+    /* Read an LPAE long-descriptor translation table. */
+    MMUFaultType fault_type = translation_fault;
+    uint32_t level = 1;
+    uint32_t epd;
+    uint32_t tsz;
+    uint64_t ttbr;
+    int ttbr_select;
+    int n;
+    target_phys_addr_t descaddr;
+    uint32_t tableattrs;
+    target_ulong page_size;
+    uint32_t attrs;
+
+    /* Determine whether this address is in the region controlled by
+     * TTBR0 or TTBR1 (or if it is in neither region and should fault).
+     * This is a Non-secure PL0/1 stage 1 translation, so controlled by
+     * TTBCR/TTBR0/TTBR1 in accordance with ARM ARM DDI0406C table B-32:
+     */
+    uint32_t t0sz = extract32(env->cp15.c2_control, 0, 3);
+    uint32_t t1sz = extract32(env->cp15.c2_control, 16, 3);
+    if (t0sz && !extract32(address, 32 - t0sz, t0sz)) {
+        /* there is a ttbr0 region and we are in it (high bits all zero) */
+        ttbr_select = 0;
+    } else if (t1sz && !extract32(~address, 32 - t1sz, t1sz)) {
+        /* there is a ttbr1 region and we are in it (high bits all one) */
+        ttbr_select = 1;
+    } else if (!t0sz) {
+        /* ttbr0 region is "everything not in the ttbr1 region" */
+        ttbr_select = 0;
+    } else if (!t1sz) {
+        /* ttbr1 region is "everything not in the ttbr0 region" */
+        ttbr_select = 1;
+    } else {
+        /* in the gap between the two regions, this is a Translation fault */
+        fault_type = translation_fault;
+        goto do_fault;
+    }
+
+    /* Note that QEMU ignores shareability and cacheability attributes,
+     * so we don't need to do anything with the SH, ORGN, IRGN fields
+     * in the TTBCR.  Similarly, TTBCR:A1 selects whether we get the
+     * ASID from TTBR0 or TTBR1, but QEMU's TLB doesn't currently
+     * implement any ASID-like capability so we can ignore it (instead
+     * we will always flush the TLB any time the ASID is changed).
+     */
+    if (ttbr_select == 0) {
+        ttbr = ((uint64_t)env->cp15.c2_base0_hi << 32) | env->cp15.c2_base0;
+        epd = extract32(env->cp15.c2_control, 7, 1);
+        tsz = t0sz;
+    } else {
+        ttbr = ((uint64_t)env->cp15.c2_base1_hi << 32) | env->cp15.c2_base1;
+        epd = extract32(env->cp15.c2_control, 23, 1);
+        tsz = t1sz;
+    }
+
+    if (epd) {
+        /* Translation table walk disabled => Translation fault on TLB miss */
+        goto do_fault;
+    }
+
+    /* If the region is small enough we will skip straight to a 2nd level
+     * lookup. This affects the number of bits of the address used in
+     * combination with the TTBR to find the first descriptor. ('n' here
+     * matches the usage in the ARM ARM sB3.6.6, where bits [39..n] are
+     * from the TTBR, [n-1..3] from the vaddr, and [2..0] always zero).
+     */
+    if (tsz > 1) {
+        level = 2;
+        n = 14 - tsz;
+    } else {
+        n = 5 - tsz;
+    }
+
+    /* Clear the vaddr bits which aren't part of the within-region address,
+     * so that we don't have to special case things when calculating the
+     * first descriptor address.
+     */
+    address &= (0xffffffffU >> tsz);
+
+    /* Now we can extract the actual base address from the TTBR */
+    descaddr = extract64(ttbr, 0, 40);
+    descaddr &= ~((1ULL << n) - 1);
+
+    tableattrs = 0;
+    for (;;) {
+        uint64_t descriptor;
+
+        descaddr |= ((address >> (9 * (4 - level))) & 0xff8);
+        descriptor = ldq_phys(descaddr);
+        if (!(descriptor & 1) ||
+            (!(descriptor & 2) && (level == 3))) {
+            /* Invalid, or the Reserved level 3 encoding */
+            goto do_fault;
+        }
+        descaddr = descriptor & 0xfffffff000ULL;
+
+        if ((descriptor & 2) && (level < 3)) {
+            /* Table entry. The top five bits are attributes which  may
+             * propagate down through lower levels of the table (and
+             * which are all arranged so that 0 means "no effect", so
+             * we can gather them up by ORing in the bits at each level).
+             */
+            tableattrs |= extract64(descriptor, 59, 5);
+            level++;
+            continue;
+        }
+        /* Block entry at level 1 or 2, or page entry at level 3.
+         * These are basically the same thing, although the number
+         * of bits we pull in from the vaddr varies.
+         */
+        page_size = (1 << (39 - (9 * level)));
+        descaddr |= (address & (page_size - 1));
+        /* Extract attributes from the descriptor and merge with table attrs */
+        attrs = extract64(descriptor, 2, 10)
+            | (extract64(descriptor, 52, 12) << 10);
+        attrs |= extract32(tableattrs, 0, 2) << 11; /* XN, PXN */
+        attrs |= extract32(tableattrs, 3, 1) << 5; /* APTable[1] => AP[2] */
+        /* The sense of AP[1] vs APTable[0] is reversed, as APTable[0] == 1
+         * means "force PL1 access only", which means forcing AP[1] to 0.
+         */
+        if (extract32(tableattrs, 2, 1)) {
+            attrs &= ~(1 << 4);
+        }
+        /* Since we're always in the Non-secure state, NSTable is ignored. */
+        break;
+    }
+    /* Here descaddr is the final physical address, and attributes
+     * are all in attrs.
+     */
+    fault_type = access_fault;
+    if ((attrs & (1 << 8)) == 0) {
+        /* Access flag */
+        goto do_fault;
+    }
+    fault_type = permission_fault;
+    if (is_user && !(attrs & (1 << 4))) {
+        /* Unprivileged access not enabled */
+        goto do_fault;
+    }
+    *prot = PAGE_READ | PAGE_WRITE | PAGE_EXEC;
+    if (attrs & (1 << 12) || (!is_user && (attrs & (1 << 11)))) {
+        /* XN or PXN */
+        if (access_type == 2) {
+            goto do_fault;
+        }
+        *prot &= ~PAGE_EXEC;
+    }
+    if (attrs & (1 << 5)) {
+        /* Write access forbidden */
+        if (access_type == 1) {
+            goto do_fault;
+        }
+        *prot &= ~PAGE_WRITE;
+    }
+
+    *phys_ptr = descaddr;
+    *page_size_ptr = page_size;
+    return 0;
+
+do_fault:
+    /* Long-descriptor format IFSR/DFSR value */
+    return (1 << 9) | (fault_type << 2) | level;
+}
+
 static int get_phys_addr_mpu(CPUARMState *env, uint32_t address,
                              int access_type, int is_user,
                              target_phys_addr_t *phys_ptr, int *prot)
@@ -2287,6 +2466,9 @@ static inline int get_phys_addr(CPUARMState *env, uint32_t address,
         *page_size = TARGET_PAGE_SIZE;
 	return get_phys_addr_mpu(env, address, access_type, is_user, phys_ptr,
 				 prot);
+    } else if (extended_addresses_enabled(env)) {
+        return get_phys_addr_lpae(env, address, access_type, is_user, phys_ptr,
+                                  prot, page_size);
     } else if (env->cp15.c1_sys & (1 << 23)) {
         return get_phys_addr_v6(env, address, access_type, is_user, phys_ptr,
                                 prot, page_size);
commit e42c4db3a3de213f6a374dbdc7e75767dc3bfac2
Author: Peter Maydell <peter.maydell at linaro.org>
Date:   Thu Jul 12 10:59:11 2012 +0000

    target-arm: Implement TTBCR changes for LPAE
    
    Implement the changes to the TTBCR register required for LPAE:
     * many fewer bits should be RAZ/WI
     * since TTBCR changes can result in a change of ASID, we must
       flush the TLB on writes to it
    
    Signed-off-by: Peter Maydell <peter.maydell at linaro.org>

diff --git a/target-arm/helper.c b/target-arm/helper.c
index 110858d..72b44b0 100644
--- a/target-arm/helper.c
+++ b/target-arm/helper.c
@@ -692,7 +692,20 @@ static const ARMCPRegInfo pmsav5_cp_reginfo[] = {
 static int vmsa_ttbcr_write(CPUARMState *env, const ARMCPRegInfo *ri,
                             uint64_t value)
 {
-    value &= 7;
+    if (arm_feature(env, ARM_FEATURE_LPAE)) {
+        value &= ~((7 << 19) | (3 << 14) | (0xf << 3));
+        /* With LPAE the TTBCR could result in a change of ASID
+         * via the TTBCR.A1 bit, so do a TLB flush.
+         */
+        tlb_flush(env, 1);
+    } else {
+        value &= 7;
+    }
+    /* Note that we always calculate c2_mask and c2_base_mask, but
+     * they are only used for short-descriptor tables (ie if EAE is 0);
+     * for long-descriptor tables the TTBCR fields are used differently
+     * and the c2_mask and c2_base_mask values are meaningless.
+     */
     env->cp15.c2_control = value;
     env->cp15.c2_mask = ~(((uint32_t)0xffffffffu) >> value);
     env->cp15.c2_base_mask = ~((uint32_t)0x3fffu >> value);
commit 702a9357897293e804d2ac7550227d0d07ed9fc9
Author: Peter Maydell <peter.maydell at linaro.org>
Date:   Thu Jul 12 10:59:10 2012 +0000

    target-arm: Implement long-descriptor PAR format
    
    Implement the different format of the PAR when long descriptor
    translation tables are in use. Note that we assume that
    get_phys_addr() returns a long-descriptor format DFSR value on
    failure if long descriptors are in use; this added subtlety tips
    the balance and makes it worth adding a comment documenting the
    API to get_phys_addr().
    
    Signed-off-by: Peter Maydell <peter.maydell at linaro.org>

diff --git a/target-arm/helper.c b/target-arm/helper.c
index d66bc3e..110858d 100644
--- a/target-arm/helper.c
+++ b/target-arm/helper.c
@@ -503,6 +503,17 @@ static int par_write(CPUARMState *env, const ARMCPRegInfo *ri, uint64_t value)
 
 #ifndef CONFIG_USER_ONLY
 /* get_phys_addr() isn't present for user-mode-only targets */
+
+/* Return true if extended addresses are enabled, ie this is an
+ * LPAE implementation and we are using the long-descriptor translation
+ * table format because the TTBCR EAE bit is set.
+ */
+static inline bool extended_addresses_enabled(CPUARMState *env)
+{
+    return arm_feature(env, ARM_FEATURE_LPAE)
+        && (env->cp15.c2_control & (1 << 31));
+}
+
 static int ats_write(CPUARMState *env, const ARMCPRegInfo *ri, uint64_t value)
 {
     target_phys_addr_t phys_addr;
@@ -517,20 +528,45 @@ static int ats_write(CPUARMState *env, const ARMCPRegInfo *ri, uint64_t value)
     }
     ret = get_phys_addr(env, value, access_type, is_user,
                         &phys_addr, &prot, &page_size);
-    if (ret == 0) {
-        /* We do not set any attribute bits in the PAR */
-        if (page_size == (1 << 24)
-            && arm_feature(env, ARM_FEATURE_V7)) {
-            env->cp15.c7_par = (phys_addr & 0xff000000) | 1 << 1;
+    if (extended_addresses_enabled(env)) {
+        /* ret is a DFSR/IFSR value for the long descriptor
+         * translation table format, but with WnR always clear.
+         * Convert it to a 64-bit PAR.
+         */
+        uint64_t par64 = (1 << 11); /* LPAE bit always set */
+        if (ret == 0) {
+            par64 |= phys_addr & ~0xfffULL;
+            /* We don't set the ATTR or SH fields in the PAR. */
         } else {
-            env->cp15.c7_par = phys_addr & 0xfffff000;
+            par64 |= 1; /* F */
+            par64 |= (ret & 0x3f) << 1; /* FS */
+            /* Note that S2WLK and FSTAGE are always zero, because we don't
+             * implement virtualization and therefore there can't be a stage 2
+             * fault.
+             */
         }
+        env->cp15.c7_par = par64;
+        env->cp15.c7_par_hi = par64 >> 32;
     } else {
-        env->cp15.c7_par = ((ret & (10 << 1)) >> 5) |
-            ((ret & (12 << 1)) >> 6) |
-            ((ret & 0xf) << 1) | 1;
+        /* ret is a DFSR/IFSR value for the short descriptor
+         * translation table format (with WnR always clear).
+         * Convert it to a 32-bit PAR.
+         */
+        if (ret == 0) {
+            /* We do not set any attribute bits in the PAR */
+            if (page_size == (1 << 24)
+                && arm_feature(env, ARM_FEATURE_V7)) {
+                env->cp15.c7_par = (phys_addr & 0xff000000) | 1 << 1;
+            } else {
+                env->cp15.c7_par = phys_addr & 0xfffff000;
+            }
+        } else {
+            env->cp15.c7_par = ((ret & (10 << 1)) >> 5) |
+                ((ret & (12 << 1)) >> 6) |
+                ((ret & 0xf) << 1) | 1;
+        }
+        env->cp15.c7_par_hi = 0;
     }
-    env->cp15.c7_par_hi = 0;
     return 0;
 }
 #endif
@@ -2196,6 +2232,29 @@ static int get_phys_addr_mpu(CPUARMState *env, uint32_t address,
     return 0;
 }
 
+/* get_phys_addr - get the physical address for this virtual address
+ *
+ * Find the physical address corresponding to the given virtual address,
+ * by doing a translation table walk on MMU based systems or using the
+ * MPU state on MPU based systems.
+ *
+ * Returns 0 if the translation was successful. Otherwise, phys_ptr,
+ * prot and page_size are not filled in, and the return value provides
+ * information on why the translation aborted, in the format of a
+ * DFSR/IFSR fault register, with the following caveats:
+ *  * we honour the short vs long DFSR format differences.
+ *  * the WnR bit is never set (the caller must do this).
+ *  * for MPU based systems we don't bother to return a full FSR format
+ *    value.
+ *
+ * @env: CPUARMState
+ * @address: virtual address to get physical address for
+ * @access_type: 0 for read, 1 for write, 2 for execute
+ * @is_user: 0 for privileged access, 1 for user
+ * @phys_ptr: set to the physical address corresponding to the virtual address
+ * @prot: set to the permissions for the page containing phys_ptr
+ * @page_size: set to the size of the page containing phys_ptr
+ */
 static inline int get_phys_addr(CPUARMState *env, uint32_t address,
                                 int access_type, int is_user,
                                 target_phys_addr_t *phys_ptr, int *prot,
commit 77a71dd1cb561a920fba63d734cbacdc1357c490
Author: Peter Maydell <peter.maydell at linaro.org>
Date:   Thu Jul 12 10:59:09 2012 +0000

    target-arm: Use target_phys_addr_t in get_phys_addr()
    
    In the implementation of get_phys_addr(), consistently use
    target_phys_addr_t to hold the physical address rather than
    uint32_t.
    
    Signed-off-by: Peter Maydell <peter.maydell at linaro.org>

diff --git a/target-arm/helper.c b/target-arm/helper.c
index 6bb6767..d66bc3e 100644
--- a/target-arm/helper.c
+++ b/target-arm/helper.c
@@ -7,7 +7,7 @@
 #ifndef CONFIG_USER_ONLY
 static inline int get_phys_addr(CPUARMState *env, uint32_t address,
                                 int access_type, int is_user,
-                                uint32_t *phys_ptr, int *prot,
+                                target_phys_addr_t *phys_ptr, int *prot,
                                 target_ulong *page_size);
 #endif
 
@@ -505,7 +505,7 @@ static int par_write(CPUARMState *env, const ARMCPRegInfo *ri, uint64_t value)
 /* get_phys_addr() isn't present for user-mode-only targets */
 static int ats_write(CPUARMState *env, const ARMCPRegInfo *ri, uint64_t value)
 {
-    uint32_t phys_addr;
+    target_phys_addr_t phys_addr;
     target_ulong page_size;
     int prot;
     int ret, is_user = ri->opc2 & 2;
@@ -1929,8 +1929,8 @@ static uint32_t get_level1_table_address(CPUARMState *env, uint32_t address)
 }
 
 static int get_phys_addr_v5(CPUARMState *env, uint32_t address, int access_type,
-			    int is_user, uint32_t *phys_ptr, int *prot,
-                            target_ulong *page_size)
+                            int is_user, target_phys_addr_t *phys_ptr,
+                            int *prot, target_ulong *page_size)
 {
     int code;
     uint32_t table;
@@ -1939,7 +1939,7 @@ static int get_phys_addr_v5(CPUARMState *env, uint32_t address, int access_type,
     int ap;
     int domain;
     int domain_prot;
-    uint32_t phys_addr;
+    target_phys_addr_t phys_addr;
 
     /* Pagetable walk.  */
     /* Lookup l1 descriptor.  */
@@ -2024,8 +2024,8 @@ do_fault:
 }
 
 static int get_phys_addr_v6(CPUARMState *env, uint32_t address, int access_type,
-			    int is_user, uint32_t *phys_ptr, int *prot,
-                            target_ulong *page_size)
+                            int is_user, target_phys_addr_t *phys_ptr,
+                            int *prot, target_ulong *page_size)
 {
     int code;
     uint32_t table;
@@ -2036,7 +2036,7 @@ static int get_phys_addr_v6(CPUARMState *env, uint32_t address, int access_type,
     int ap;
     int domain = 0;
     int domain_prot;
-    uint32_t phys_addr;
+    target_phys_addr_t phys_addr;
 
     /* Pagetable walk.  */
     /* Lookup l1 descriptor.  */
@@ -2135,8 +2135,9 @@ do_fault:
     return code | (domain << 4);
 }
 
-static int get_phys_addr_mpu(CPUARMState *env, uint32_t address, int access_type,
-			     int is_user, uint32_t *phys_ptr, int *prot)
+static int get_phys_addr_mpu(CPUARMState *env, uint32_t address,
+                             int access_type, int is_user,
+                             target_phys_addr_t *phys_ptr, int *prot)
 {
     int n;
     uint32_t mask;
@@ -2197,7 +2198,7 @@ static int get_phys_addr_mpu(CPUARMState *env, uint32_t address, int access_type
 
 static inline int get_phys_addr(CPUARMState *env, uint32_t address,
                                 int access_type, int is_user,
-                                uint32_t *phys_ptr, int *prot,
+                                target_phys_addr_t *phys_ptr, int *prot,
                                 target_ulong *page_size)
 {
     /* Fast Context Switch Extension.  */
@@ -2226,7 +2227,7 @@ static inline int get_phys_addr(CPUARMState *env, uint32_t address,
 int cpu_arm_handle_mmu_fault (CPUARMState *env, target_ulong address,
                               int access_type, int mmu_idx)
 {
-    uint32_t phys_addr;
+    target_phys_addr_t phys_addr;
     target_ulong page_size;
     int prot;
     int ret, is_user;
@@ -2236,7 +2237,7 @@ int cpu_arm_handle_mmu_fault (CPUARMState *env, target_ulong address,
                         &page_size);
     if (ret == 0) {
         /* Map a single [sub]page.  */
-        phys_addr &= ~(uint32_t)0x3ff;
+        phys_addr &= ~(target_phys_addr_t)0x3ff;
         address &= ~(uint32_t)0x3ff;
         tlb_set_page (env, address, phys_addr, prot, mmu_idx, page_size);
         return 0;
@@ -2258,7 +2259,7 @@ int cpu_arm_handle_mmu_fault (CPUARMState *env, target_ulong address,
 
 target_phys_addr_t cpu_get_phys_page_debug(CPUARMState *env, target_ulong addr)
 {
-    uint32_t phys_addr;
+    target_phys_addr_t phys_addr;
     target_ulong page_size;
     int prot;
     int ret;
commit 891a2fe72031b7f9d4d2f5f8539206dbd1d6c3ec
Author: Peter Maydell <peter.maydell at linaro.org>
Date:   Thu Jul 12 10:59:09 2012 +0000

    target-arm: Add 64 bit PAR, TTBR0, TTBR1 for LPAE
    
    Under LPAE, the cp15 registers PAR, TTBR0 and TTBR1 are extended
    to 64 bits, with a 64 bit (MRRC/MCRR) access path to read the
    full width of the register. Add the state fields for the top
    half and the 64 bit access path. Actual use of the top half of
    the register will come with the addition of the long-descriptor
    translation table format support.
    
    For the PAR we also need to correct the masking applied for
    32 bit writes (there are no bits reserved if LPAE is implemented)
    and clear the high half when doing a 32 bit result VA-to-PA
    lookup.
    
    Signed-off-by: Peter Maydell <peter.maydell at linaro.org>

diff --git a/target-arm/cpu.h b/target-arm/cpu.h
index 3c5d2be..191895c 100644
--- a/target-arm/cpu.h
+++ b/target-arm/cpu.h
@@ -113,7 +113,9 @@ typedef struct CPUARMState {
         uint32_t c1_xscaleauxcr; /* XScale auxiliary control register.  */
         uint32_t c1_scr; /* secure config register.  */
         uint32_t c2_base0; /* MMU translation table base 0.  */
-        uint32_t c2_base1; /* MMU translation table base 1.  */
+        uint32_t c2_base0_hi; /* MMU translation table base 0, high 32 bits */
+        uint32_t c2_base1; /* MMU translation table base 0.  */
+        uint32_t c2_base1_hi; /* MMU translation table base 1, high 32 bits */
         uint32_t c2_control; /* MMU translation table base control.  */
         uint32_t c2_mask; /* MMU translation table base selection mask.  */
         uint32_t c2_base_mask; /* MMU translation table base 0 mask. */
@@ -127,6 +129,7 @@ typedef struct CPUARMState {
         uint32_t c6_insn; /* Fault address registers.  */
         uint32_t c6_data;
         uint32_t c7_par;  /* Translation result. */
+        uint32_t c7_par_hi;  /* Translation result, high 32 bits */
         uint32_t c9_insn; /* Cache lockdown registers.  */
         uint32_t c9_data;
         uint32_t c9_pmcr; /* performance monitor control register */
@@ -638,7 +641,7 @@ static inline CPUARMState *cpu_init(const char *cpu_model)
 #define cpu_signal_handler cpu_arm_signal_handler
 #define cpu_list arm_cpu_list
 
-#define CPU_SAVE_VERSION 8
+#define CPU_SAVE_VERSION 9
 
 /* MMU modes definitions */
 #define MMU_MODE0_SUFFIX _kernel
diff --git a/target-arm/helper.c b/target-arm/helper.c
index 0cf7b8d..6bb6767 100644
--- a/target-arm/helper.c
+++ b/target-arm/helper.c
@@ -491,7 +491,9 @@ static const ARMCPRegInfo generic_timer_cp_reginfo[] = {
 
 static int par_write(CPUARMState *env, const ARMCPRegInfo *ri, uint64_t value)
 {
-    if (arm_feature(env, ARM_FEATURE_V7)) {
+    if (arm_feature(env, ARM_FEATURE_LPAE)) {
+        env->cp15.c7_par = value;
+    } else if (arm_feature(env, ARM_FEATURE_V7)) {
         env->cp15.c7_par = value & 0xfffff6ff;
     } else {
         env->cp15.c7_par = value & 0xfffff1ff;
@@ -528,6 +530,7 @@ static int ats_write(CPUARMState *env, const ARMCPRegInfo *ri, uint64_t value)
             ((ret & (12 << 1)) >> 6) |
             ((ret & 0xf) << 1) | 1;
     }
+    env->cp15.c7_par_hi = 0;
     return 0;
 }
 #endif
@@ -871,6 +874,69 @@ static const ARMCPRegInfo mpidr_cp_reginfo[] = {
     REGINFO_SENTINEL
 };
 
+static int par64_read(CPUARMState *env, const ARMCPRegInfo *ri, uint64_t *value)
+{
+    *value = ((uint64_t)env->cp15.c7_par_hi << 32) | env->cp15.c7_par;
+    return 0;
+}
+
+static int par64_write(CPUARMState *env, const ARMCPRegInfo *ri, uint64_t value)
+{
+    env->cp15.c7_par_hi = value >> 32;
+    env->cp15.c7_par = value;
+    return 0;
+}
+
+static void par64_reset(CPUARMState *env, const ARMCPRegInfo *ri)
+{
+    env->cp15.c7_par_hi = 0;
+    env->cp15.c7_par = 0;
+}
+
+static int ttbr064_read(CPUARMState *env, const ARMCPRegInfo *ri,
+                        uint64_t *value)
+{
+    *value = ((uint64_t)env->cp15.c2_base0_hi << 32) | env->cp15.c2_base0;
+    return 0;
+}
+
+static int ttbr064_write(CPUARMState *env, const ARMCPRegInfo *ri,
+                         uint64_t value)
+{
+    env->cp15.c2_base0_hi = value >> 32;
+    env->cp15.c2_base0 = value;
+    /* Writes to the 64 bit format TTBRs may change the ASID */
+    tlb_flush(env, 1);
+    return 0;
+}
+
+static void ttbr064_reset(CPUARMState *env, const ARMCPRegInfo *ri)
+{
+    env->cp15.c2_base0_hi = 0;
+    env->cp15.c2_base0 = 0;
+}
+
+static int ttbr164_read(CPUARMState *env, const ARMCPRegInfo *ri,
+                        uint64_t *value)
+{
+    *value = ((uint64_t)env->cp15.c2_base1_hi << 32) | env->cp15.c2_base1;
+    return 0;
+}
+
+static int ttbr164_write(CPUARMState *env, const ARMCPRegInfo *ri,
+                         uint64_t value)
+{
+    env->cp15.c2_base1_hi = value >> 32;
+    env->cp15.c2_base1 = value;
+    return 0;
+}
+
+static void ttbr164_reset(CPUARMState *env, const ARMCPRegInfo *ri)
+{
+    env->cp15.c2_base1_hi = 0;
+    env->cp15.c2_base1 = 0;
+}
+
 static const ARMCPRegInfo lpae_cp_reginfo[] = {
     /* NOP AMAIR0/1: the override is because these clash with tha rather
      * broadly specified TLB_LOCKDOWN entry in the generic cp_reginfo.
@@ -886,6 +952,15 @@ static const ARMCPRegInfo lpae_cp_reginfo[] = {
       .access = PL0_R, .type = ARM_CP_CONST|ARM_CP_64BIT, .resetvalue = 0 },
     { .name = "DBGDSAR", .cp = 14, .crm = 2, .opc1 = 0,
       .access = PL0_R, .type = ARM_CP_CONST|ARM_CP_64BIT, .resetvalue = 0 },
+    { .name = "PAR", .cp = 15, .crm = 7, .opc1 = 0,
+      .access = PL1_RW, .type = ARM_CP_64BIT,
+      .readfn = par64_read, .writefn = par64_write, .resetfn = par64_reset },
+    { .name = "TTBR0", .cp = 15, .crm = 2, .opc1 = 0,
+      .access = PL1_RW, .type = ARM_CP_64BIT, .readfn = ttbr064_read,
+      .writefn = ttbr064_write, .resetfn = ttbr064_reset },
+    { .name = "TTBR1", .cp = 15, .crm = 2, .opc1 = 1,
+      .access = PL1_RW, .type = ARM_CP_64BIT, .readfn = ttbr164_read,
+      .writefn = ttbr164_write, .resetfn = ttbr164_reset },
     REGINFO_SENTINEL
 };
 
diff --git a/target-arm/machine.c b/target-arm/machine.c
index 429cbc8..68dca7f 100644
--- a/target-arm/machine.c
+++ b/target-arm/machine.c
@@ -27,7 +27,9 @@ void cpu_save(QEMUFile *f, void *opaque)
     qemu_put_be32(f, env->cp15.c1_xscaleauxcr);
     qemu_put_be32(f, env->cp15.c1_scr);
     qemu_put_be32(f, env->cp15.c2_base0);
+    qemu_put_be32(f, env->cp15.c2_base0_hi);
     qemu_put_be32(f, env->cp15.c2_base1);
+    qemu_put_be32(f, env->cp15.c2_base1_hi);
     qemu_put_be32(f, env->cp15.c2_control);
     qemu_put_be32(f, env->cp15.c2_mask);
     qemu_put_be32(f, env->cp15.c2_base_mask);
@@ -42,6 +44,7 @@ void cpu_save(QEMUFile *f, void *opaque)
     qemu_put_be32(f, env->cp15.c6_insn);
     qemu_put_be32(f, env->cp15.c6_data);
     qemu_put_be32(f, env->cp15.c7_par);
+    qemu_put_be32(f, env->cp15.c7_par_hi);
     qemu_put_be32(f, env->cp15.c9_insn);
     qemu_put_be32(f, env->cp15.c9_data);
     qemu_put_be32(f, env->cp15.c9_pmcr);
@@ -144,7 +147,9 @@ int cpu_load(QEMUFile *f, void *opaque, int version_id)
     env->cp15.c1_xscaleauxcr = qemu_get_be32(f);
     env->cp15.c1_scr = qemu_get_be32(f);
     env->cp15.c2_base0 = qemu_get_be32(f);
+    env->cp15.c2_base0_hi = qemu_get_be32(f);
     env->cp15.c2_base1 = qemu_get_be32(f);
+    env->cp15.c2_base1_hi = qemu_get_be32(f);
     env->cp15.c2_control = qemu_get_be32(f);
     env->cp15.c2_mask = qemu_get_be32(f);
     env->cp15.c2_base_mask = qemu_get_be32(f);
@@ -159,6 +164,7 @@ int cpu_load(QEMUFile *f, void *opaque, int version_id)
     env->cp15.c6_insn = qemu_get_be32(f);
     env->cp15.c6_data = qemu_get_be32(f);
     env->cp15.c7_par = qemu_get_be32(f);
+    env->cp15.c7_par_hi = qemu_get_be32(f);
     env->cp15.c9_insn = qemu_get_be32(f);
     env->cp15.c9_data = qemu_get_be32(f);
     env->cp15.c9_pmcr = qemu_get_be32(f);
commit f9fc619a0deaf2b61fe6f48034c94ca7e38801bb
Author: Peter Maydell <peter.maydell at linaro.org>
Date:   Thu Jul 12 10:59:08 2012 +0000

    target-arm: Add 64 bit variants of DBGDRAR and DBGDSAR for LPAE
    
    LPAE extends the DBGDRAR and DBGDSAR debug registers to 64 bits; we
    only implement these as dummy RAZ versions; provide dummies for
    the 64 bit accesses as well.
    
    Signed-off-by: Peter Maydell <peter.maydell at linaro.org>

diff --git a/target-arm/helper.c b/target-arm/helper.c
index e96404a..0cf7b8d 100644
--- a/target-arm/helper.c
+++ b/target-arm/helper.c
@@ -881,6 +881,11 @@ static const ARMCPRegInfo lpae_cp_reginfo[] = {
     { .name = "AMAIR1", .cp = 15, .crn = 10, .crm = 3, .opc1 = 0, .opc2 = 1,
       .access = PL1_RW, .type = ARM_CP_CONST | ARM_CP_OVERRIDE,
       .resetvalue = 0 },
+    /* 64 bit access versions of the (dummy) debug registers */
+    { .name = "DBGDRAR", .cp = 14, .crm = 1, .opc1 = 0,
+      .access = PL0_R, .type = ARM_CP_CONST|ARM_CP_64BIT, .resetvalue = 0 },
+    { .name = "DBGDSAR", .cp = 14, .crm = 2, .opc1 = 0,
+      .access = PL0_R, .type = ARM_CP_CONST|ARM_CP_64BIT, .resetvalue = 0 },
     REGINFO_SENTINEL
 };
 
commit 7ac681cf2aafcef4b17f0f6007e1f4a2520528db
Author: Peter Maydell <peter.maydell at linaro.org>
Date:   Thu Jul 12 10:59:07 2012 +0000

    target-arm: Add AMAIR0, AMAIR1 LPAE cp15 registers
    
    Add implementations of the AMAIR0 and AMAIR1 LPAE
    Auxiliary Memory Attribute Indirection Registers.
    These are implementation defined and we choose to
    implement them as RAZ/WI, matching the Cortex-A7
    and Cortex-A15.
    
    Signed-off-by: Peter Maydell <peter.maydell at linaro.org>

diff --git a/target-arm/helper.c b/target-arm/helper.c
index e51b038..e96404a 100644
--- a/target-arm/helper.c
+++ b/target-arm/helper.c
@@ -871,6 +871,19 @@ static const ARMCPRegInfo mpidr_cp_reginfo[] = {
     REGINFO_SENTINEL
 };
 
+static const ARMCPRegInfo lpae_cp_reginfo[] = {
+    /* NOP AMAIR0/1: the override is because these clash with tha rather
+     * broadly specified TLB_LOCKDOWN entry in the generic cp_reginfo.
+     */
+    { .name = "AMAIR0", .cp = 15, .crn = 10, .crm = 3, .opc1 = 0, .opc2 = 0,
+      .access = PL1_RW, .type = ARM_CP_CONST | ARM_CP_OVERRIDE,
+      .resetvalue = 0 },
+    { .name = "AMAIR1", .cp = 15, .crn = 10, .crm = 3, .opc1 = 0, .opc2 = 1,
+      .access = PL1_RW, .type = ARM_CP_CONST | ARM_CP_OVERRIDE,
+      .resetvalue = 0 },
+    REGINFO_SENTINEL
+};
+
 static int sctlr_write(CPUARMState *env, const ARMCPRegInfo *ri, uint64_t value)
 {
     env->cp15.c1_sys = value;
@@ -1016,6 +1029,9 @@ void register_cp_regs_for_features(ARMCPU *cpu)
     if (arm_feature(env, ARM_FEATURE_MPIDR)) {
         define_arm_cp_regs(cpu, mpidr_cp_reginfo);
     }
+    if (arm_feature(env, ARM_FEATURE_LPAE)) {
+        define_arm_cp_regs(cpu, lpae_cp_reginfo);
+    }
     /* Slightly awkwardly, the OMAP and StrongARM cores need all of
      * cp15 crn=0 to be writes-ignored, whereas for other cores they should
      * be read-only (ie write causes UNDEF exception).
commit 918f5dca18d62d014bc84fde726a88bd7e8d3615
Author: Peter Maydell <peter.maydell at linaro.org>
Date:   Thu Jul 12 10:59:06 2012 +0000

    target-arm: Extend feature flags to 64 bits
    
    Extend feature flags to 64 bits, as we've just run out of space
    in the 32 bit integer we were using for them.
    
    Signed-off-by: Peter Maydell <peter.maydell at linaro.org>

diff --git a/target-arm/cpu.c b/target-arm/cpu.c
index 526e725..b00f5fa 100644
--- a/target-arm/cpu.c
+++ b/target-arm/cpu.c
@@ -129,7 +129,7 @@ static void arm_cpu_reset(CPUState *s)
 
 static inline void set_feature(CPUARMState *env, int feature)
 {
-    env->features |= 1u << feature;
+    env->features |= 1ULL << feature;
 }
 
 static void arm_cpu_initfn(Object *obj)
diff --git a/target-arm/cpu.h b/target-arm/cpu.h
index 82cad4b..3c5d2be 100644
--- a/target-arm/cpu.h
+++ b/target-arm/cpu.h
@@ -221,7 +221,7 @@ typedef struct CPUARMState {
     /* These fields after the common ones so they are preserved on reset.  */
 
     /* Internal CPU feature flags.  */
-    uint32_t features;
+    uint64_t features;
 
     void *nvic;
     const struct arm_boot_info *boot_info;
@@ -392,7 +392,7 @@ enum arm_features {
 
 static inline int arm_feature(CPUARMState *env, int feature)
 {
-    return (env->features & (1u << feature)) != 0;
+    return (env->features & (1ULL << feature)) != 0;
 }
 
 void arm_cpu_list(FILE *f, fprintf_function cpu_fprintf);
@@ -638,7 +638,7 @@ static inline CPUARMState *cpu_init(const char *cpu_model)
 #define cpu_signal_handler cpu_arm_signal_handler
 #define cpu_list arm_cpu_list
 
-#define CPU_SAVE_VERSION 7
+#define CPU_SAVE_VERSION 8
 
 /* MMU modes definitions */
 #define MMU_MODE0_SUFFIX _kernel
diff --git a/target-arm/machine.c b/target-arm/machine.c
index a2a75fb..429cbc8 100644
--- a/target-arm/machine.c
+++ b/target-arm/machine.c
@@ -60,7 +60,7 @@ void cpu_save(QEMUFile *f, void *opaque)
     qemu_put_be32(f, env->cp15.c15_diagnostic);
     qemu_put_be32(f, env->cp15.c15_power_diagnostic);
 
-    qemu_put_be32(f, env->features);
+    qemu_put_be64(f, env->features);
 
     if (arm_feature(env, ARM_FEATURE_VFP)) {
         for (i = 0;  i < 16; i++) {
@@ -177,7 +177,7 @@ int cpu_load(QEMUFile *f, void *opaque, int version_id)
     env->cp15.c15_diagnostic = qemu_get_be32(f);
     env->cp15.c15_power_diagnostic = qemu_get_be32(f);
 
-    env->features = qemu_get_be32(f);
+    env->features = qemu_get_be64(f);
 
     if (arm_feature(env, ARM_FEATURE_VFP)) {
         for (i = 0;  i < 16; i++) {
commit de9b05b807918d40db9e26ddd6a54ad2978ac5b7
Author: Peter Maydell <peter.maydell at linaro.org>
Date:   Thu Jul 12 10:59:05 2012 +0000

    target-arm: Implement privileged-execute-never (PXN)
    
    Implement the privileged-execute-never (PXN) translation table bit.
    It is implementation-defined whether this is implemented, so we give
    it its own ARM_FEATURE_ flag. LPAE requires PXN, so add also an
    LPAE feature flag and the implication logic, as a placeholder
    for actually implementing LPAE at a later date.
    
    Signed-off-by: Peter Maydell <peter.maydell at linaro.org>

diff --git a/target-arm/cpu.c b/target-arm/cpu.c
index ae57953..526e725 100644
--- a/target-arm/cpu.c
+++ b/target-arm/cpu.c
@@ -192,6 +192,9 @@ void arm_cpu_realize(ARMCPU *cpu)
     if (arm_feature(env, ARM_FEATURE_VFP3)) {
         set_feature(env, ARM_FEATURE_VFP);
     }
+    if (arm_feature(env, ARM_FEATURE_LPAE)) {
+        set_feature(env, ARM_FEATURE_PXN);
+    }
 
     register_cp_regs_for_features(cpu);
 }
@@ -532,6 +535,7 @@ static void cortex_a15_initfn(Object *obj)
     set_feature(&cpu->env, ARM_FEATURE_V7MP);
     set_feature(&cpu->env, ARM_FEATURE_GENERIC_TIMER);
     set_feature(&cpu->env, ARM_FEATURE_DUMMY_C15_REGS);
+    set_feature(&cpu->env, ARM_FEATURE_LPAE);
     cpu->midr = 0x412fc0f1;
     cpu->reset_fpsid = 0x410430f0;
     cpu->mvfr0 = 0x10110222;
diff --git a/target-arm/cpu.h b/target-arm/cpu.h
index aadfca0..82cad4b 100644
--- a/target-arm/cpu.h
+++ b/target-arm/cpu.h
@@ -386,6 +386,8 @@ enum arm_features {
     ARM_FEATURE_CACHE_DIRTY_REG, /* 1136/1176 cache dirty status register */
     ARM_FEATURE_CACHE_BLOCK_OPS, /* v6 optional cache block operations */
     ARM_FEATURE_MPIDR, /* has cp15 MPIDR */
+    ARM_FEATURE_PXN, /* has Privileged Execute Never bit */
+    ARM_FEATURE_LPAE, /* has Large Physical Address Extension */
 };
 
 static inline int arm_feature(CPUARMState *env, int feature)
diff --git a/target-arm/helper.c b/target-arm/helper.c
index 0015bee..e51b038 100644
--- a/target-arm/helper.c
+++ b/target-arm/helper.c
@@ -1935,9 +1935,10 @@ static int get_phys_addr_v6(CPUARMState *env, uint32_t address, int access_type,
     uint32_t table;
     uint32_t desc;
     uint32_t xn;
+    uint32_t pxn = 0;
     int type;
     int ap;
-    int domain;
+    int domain = 0;
     int domain_prot;
     uint32_t phys_addr;
 
@@ -1946,27 +1947,27 @@ static int get_phys_addr_v6(CPUARMState *env, uint32_t address, int access_type,
     table = get_level1_table_address(env, address);
     desc = ldl_phys(table);
     type = (desc & 3);
-    if (type == 0) {
-        /* Section translation fault.  */
+    if (type == 0 || (type == 3 && !arm_feature(env, ARM_FEATURE_PXN))) {
+        /* Section translation fault, or attempt to use the encoding
+         * which is Reserved on implementations without PXN.
+         */
         code = 5;
-        domain = 0;
         goto do_fault;
-    } else if (type == 2 && (desc & (1 << 18))) {
-        /* Supersection.  */
-        domain = 0;
-    } else {
-        /* Section or page.  */
+    }
+    if ((type == 1) || !(desc & (1 << 18))) {
+        /* Page or Section.  */
         domain = (desc >> 5) & 0x0f;
     }
     domain_prot = (env->cp15.c3 >> (domain * 2)) & 3;
     if (domain_prot == 0 || domain_prot == 2) {
-        if (type == 2)
+        if (type != 1) {
             code = 9; /* Section domain fault.  */
-        else
+        } else {
             code = 11; /* Page domain fault.  */
+        }
         goto do_fault;
     }
-    if (type == 2) {
+    if (type != 1) {
         if (desc & (1 << 18)) {
             /* Supersection.  */
             phys_addr = (desc & 0xff000000) | (address & 0x00ffffff);
@@ -1978,8 +1979,12 @@ static int get_phys_addr_v6(CPUARMState *env, uint32_t address, int access_type,
         }
         ap = ((desc >> 10) & 3) | ((desc >> 13) & 4);
         xn = desc & (1 << 4);
+        pxn = desc & 1;
         code = 13;
     } else {
+        if (arm_feature(env, ARM_FEATURE_PXN)) {
+            pxn = (desc >> 2) & 1;
+        }
         /* Lookup l2 entry.  */
         table = (desc & 0xfffffc00) | ((address >> 10) & 0x3fc);
         desc = ldl_phys(table);
@@ -2007,6 +2012,9 @@ static int get_phys_addr_v6(CPUARMState *env, uint32_t address, int access_type,
     if (domain_prot == 3) {
         *prot = PAGE_READ | PAGE_WRITE | PAGE_EXEC;
     } else {
+        if (pxn && !is_user) {
+            xn = 1;
+        }
         if (xn && access_type == 2)
             goto do_fault;
 
commit 3cc0cd61f4adfecf2c0de392fe61a7e323e496ba
Author: Peter Maydell <peter.maydell at linaro.org>
Date:   Thu Jul 12 10:59:03 2012 +0000

    ARM: Make target_phys_addr_t 64 bits and physaddrs 40 bits
    
    Make target_phys_addr_t 64 bits for ARM targets, and set
    TARGET_PHYS_ADDR_SPACE_BITS to 40.  This should have no effect for ARM
    boards where physical addresses really are 32 bits (except perhaps a
    slight performance hit on 32 bit hosts for system emulation) but allows
    us to implement the Large Physical Address Extensions for Cortex-A15,
    which mean 40 bit physical addresses.
    
    Signed-off-by: Peter Maydell <peter.maydell at linaro.org>

diff --git a/configure b/configure
index 500fe24..32a8290 100755
--- a/configure
+++ b/configure
@@ -3571,7 +3571,7 @@ case "$target_arch2" in
     bflt="yes"
     target_nptl="yes"
     gdb_xml_files="arm-core.xml arm-vfp.xml arm-vfp3.xml arm-neon.xml"
-    target_phys_bits=32
+    target_phys_bits=64
     target_llong_alignment=4
     target_libs_softmmu="$fdt_libs"
   ;;
diff --git a/target-arm/cpu.h b/target-arm/cpu.h
index 33afa18..aadfca0 100644
--- a/target-arm/cpu.h
+++ b/target-arm/cpu.h
@@ -619,7 +619,7 @@ static inline bool cp_access_ok(CPUARMState *env,
 #define TARGET_PAGE_BITS 10
 #endif
 
-#define TARGET_PHYS_ADDR_SPACE_BITS 32
+#define TARGET_PHYS_ADDR_SPACE_BITS 40
 #define TARGET_VIRT_ADDR_SPACE_BITS 32
 
 static inline CPUARMState *cpu_init(const char *cpu_model)
commit 40291d61461c4619928a83a640205d71c72b155a
Author: Peter Maydell <peter.maydell at linaro.org>
Date:   Thu Jul 12 10:59:02 2012 +0000

    hw/imx_avic.c: Avoid format error when target_phys_addr_t is 64 bits
    
    Add a missing cast to avoid gcc complaining about format string
    errors when printing an expression based on a target_phys_addr_t.
    
    Signed-off-by: Peter Maydell <peter.maydell at linaro.org>
    Reviewed-by: Peter Chubb <peter.chubb at nicta.com.au>

diff --git a/hw/imx_avic.c b/hw/imx_avic.c
index 25f47f3..4f010e8 100644
--- a/hw/imx_avic.c
+++ b/hw/imx_avic.c
@@ -267,7 +267,7 @@ static void imx_avic_write(void *opaque, target_phys_addr_t offset,
     /* Vector Registers not yet supported */
     if (offset >= 0x100 && offset <= 0x2fc) {
         IPRINTF("imx_avic_write to vector register %d ignored\n",
-                (offset - 0x100) >> 2);
+                (unsigned int)((offset - 0x100) >> 2));
         return;
     }
 
commit ed336850e830711a3b940a1d311b5958f439f342
Author: Peter Maydell <peter.maydell at linaro.org>
Date:   Thu Jul 12 10:59:04 2012 +0000

    target-arm: Fix TCG temp handling in 64 bit cp writes
    
    Fix errors in the TCG temp handling in the 64 bit coprocessor
    write path: we were reusing a 32 bit temp after it had been
    freed by store_reg(), and failing to free a 64 bit temp.
    
    This bug has no visible effect at this point because there
    aren't any non-NOP 64 bit registers yet; it needs to be fixed
    as a prerequisite for the 64 bit registers in LPAE support.
    
    Signed-off-by: Peter Maydell <peter.maydell at linaro.org>

diff --git a/target-arm/translate.c b/target-arm/translate.c
index f39b9ca..29008a4 100644
--- a/target-arm/translate.c
+++ b/target-arm/translate.c
@@ -6263,7 +6263,9 @@ static int disas_coproc_insn(CPUARMState * env, DisasContext *s, uint32_t insn)
                 tcg_gen_trunc_i64_i32(tmp, tmp64);
                 store_reg(s, rt, tmp);
                 tcg_gen_shri_i64(tmp64, tmp64, 32);
+                tmp = tcg_temp_new_i32();
                 tcg_gen_trunc_i64_i32(tmp, tmp64);
+                tcg_temp_free_i64(tmp64);
                 store_reg(s, rt2, tmp);
             } else {
                 TCGv tmp;
commit 091fd17ce8ebdc2922d536e13d2bb96f8acc83f0
Author: Peter Maydell <peter.maydell at linaro.org>
Date:   Thu Jul 12 10:58:36 2012 +0000

    target-arm: Fix some copy-and-paste errors in cp register names
    
    Fix a couple of cases where cp register names were copy-and-pasted.
    These are harmless since we don't use the name for anything (except
    debugging convenience) but could be confusing.
    
    Signed-off-by: Peter Maydell <peter.maydell at linaro.org>
    Reviewed-by: Igor Mitsyanko <i.mitsyanko at samsung.com>

diff --git a/target-arm/helper.c b/target-arm/helper.c
index ca5d8e9..0015bee 100644
--- a/target-arm/helper.c
+++ b/target-arm/helper.c
@@ -216,9 +216,9 @@ static const ARMCPRegInfo v6_cp_reginfo[] = {
       .access = PL1_W, .type = ARM_CP_NOP },
     { .name = "ISB", .cp = 15, .crn = 7, .crm = 5, .opc1 = 0, .opc2 = 4,
       .access = PL0_W, .type = ARM_CP_NOP },
-    { .name = "ISB", .cp = 15, .crn = 7, .crm = 10, .opc1 = 0, .opc2 = 4,
+    { .name = "DSB", .cp = 15, .crn = 7, .crm = 10, .opc1 = 0, .opc2 = 4,
       .access = PL0_W, .type = ARM_CP_NOP },
-    { .name = "ISB", .cp = 15, .crn = 7, .crm = 10, .opc1 = 0, .opc2 = 5,
+    { .name = "DMB", .cp = 15, .crn = 7, .crm = 10, .opc1 = 0, .opc2 = 5,
       .access = PL0_W, .type = ARM_CP_NOP },
     { .name = "IFAR", .cp = 15, .crn = 6, .crm = 0, .opc1 = 0, .opc2 = 2,
       .access = PL1_RW, .fieldoffset = offsetof(CPUARMState, cp15.c6_insn),
@@ -346,7 +346,7 @@ static const ARMCPRegInfo v7_cp_reginfo[] = {
      */
     { .name = "DBGDRAR", .cp = 14, .crn = 1, .crm = 0, .opc1 = 0, .opc2 = 0,
       .access = PL0_R, .type = ARM_CP_CONST, .resetvalue = 0 },
-    { .name = "DBGDRAR", .cp = 14, .crn = 2, .crm = 0, .opc1 = 0, .opc2 = 0,
+    { .name = "DBGDSAR", .cp = 14, .crn = 2, .crm = 0, .opc1 = 0, .opc2 = 0,
       .access = PL0_R, .type = ARM_CP_CONST, .resetvalue = 0 },
     /* the old v6 WFI, UNPREDICTABLE in v7 but we choose to NOP */
     { .name = "NOP", .cp = 15, .crn = 7, .crm = 0, .opc1 = 0, .opc2 = 4,
commit 81a60ada7e85c334c9516cad89d25a7dd889f399
Author: Peter Maydell <peter.maydell at linaro.org>
Date:   Thu Jul 12 10:58:36 2012 +0000

    target-arm: Fix typo that meant TTBR1 accesses went to TTBR0
    
    Fix a copy-and-paste error in the register description for TTBR1
    that meant it was a duplicate of TTBR0 rather than affecting the
    correct bit of CPU state.
    
    Signed-off-by: Peter Maydell <peter.maydell at linaro.org>

diff --git a/target-arm/helper.c b/target-arm/helper.c
index 2309923..ca5d8e9 100644
--- a/target-arm/helper.c
+++ b/target-arm/helper.c
@@ -679,7 +679,7 @@ static const ARMCPRegInfo vmsa_cp_reginfo[] = {
       .fieldoffset = offsetof(CPUARMState, cp15.c2_base0), .resetvalue = 0, },
     { .name = "TTBR1", .cp = 15, .crn = 2, .crm = 0, .opc1 = 0, .opc2 = 1,
       .access = PL1_RW,
-      .fieldoffset = offsetof(CPUARMState, cp15.c2_base0), .resetvalue = 0, },
+      .fieldoffset = offsetof(CPUARMState, cp15.c2_base1), .resetvalue = 0, },
     { .name = "TTBCR", .cp = 15, .crn = 2, .crm = 0, .opc1 = 0, .opc2 = 2,
       .access = PL1_RW, .writefn = vmsa_ttbcr_write,
       .resetfn = vmsa_ttbcr_reset,
commit 2bee5105481637f9603bc71ef7cbb81e8da9cd68
Author: Paul Brook <paul at codesourcery.com>
Date:   Thu Jul 12 10:58:35 2012 +0000

    target-arm: Fix CP15 based WFI
    
    The coprocessor register rework broke cp15 based WFI instructions.
    We incorrectly fall through the normal register write case, which
    incorrectly adds a forced block termination.  We've already done
    a special version of this (DISAS_WFI), so return immediately.
    
    Signed-off-by: Paul Brook <paul at codesourcery.com>
    Reviewed-by: Peter Maydell <peter.maydell at linaro.org>
    Signed-off-by: Peter Maydell <peter.maydell at linaro.org>

diff --git a/target-arm/translate.c b/target-arm/translate.c
index a2a0ecd..f39b9ca 100644
--- a/target-arm/translate.c
+++ b/target-arm/translate.c
@@ -6236,7 +6236,7 @@ static int disas_coproc_insn(CPUARMState * env, DisasContext *s, uint32_t insn)
             }
             gen_set_pc_im(s->pc);
             s->is_jmp = DISAS_WFI;
-            break;
+            return 0;
         default:
             break;
         }
commit c0958559b1a589a0d189c45ea1adaa6b345f4256
Author: Stefan Weil <sw at weilnetz.de>
Date:   Wed Jul 11 07:09:05 2012 +0200

    iov: Fix do_send_recv() for MinGW (also fixes a build breakage)
    
    Commit 25e5e4c7 broke compilation for non POSIX hosts (e.g. MinGW)
    because it partially replaced "ret" by "count".
    
    It also changed the handling of EINTR in a wrong way.
    
    The patch restores the old code for these two changes.
    
    Signed-off-by: Stefan Weil <sw at weilnetz.de>
    Signed-off-by: Anthony Liguori <aliguori at us.ibm.com>

diff --git a/iov.c b/iov.c
index 7cc08f0..b333061 100644
--- a/iov.c
+++ b/iov.c
@@ -114,9 +114,9 @@ do_send_recv(int sockfd, struct iovec *iov, unsigned iov_cnt, bool do_send)
 #else
     /* else send piece-by-piece */
     /*XXX Note: windows has WSASend() and WSARecv() */
-    unsigned i;
-    size_t count = 0;
-    for (i = 0; i < iov_cnt; ++i) {
+    unsigned i = 0;
+    ssize_t ret = 0;
+    while (i < iov_cnt) {
         ssize_t r = do_send
             ? send(sockfd, iov[i].iov_base, iov[i].iov_len, 0)
             : recv(sockfd, iov[i].iov_base, iov[i].iov_len, 0);
@@ -130,12 +130,13 @@ do_send_recv(int sockfd, struct iovec *iov, unsigned iov_cnt, bool do_send)
             /* else it is some "other" error,
              * only return if there was no data processed. */
             if (ret == 0) {
-                return -1;
+                ret = -1;
             }
             break;
         }
+        i++;
     }
-    return count;
+    return ret;
 #endif
 }
 
commit 31783203c3b74c11015b20194d57dada559940cf
Author: Peter Maydell <peter.maydell at linaro.org>
Date:   Fri May 25 13:07:01 2012 +0100

    qemu_find_file: check name as a straight path even if it has no '/'
    
    Make qemu_find_file() check for the passed in name as a straight
    pathname even if it doesn't have any path separator character in it.
    This means that "-bios foo", "-dtb foo" etc will find a file 'foo'
    in the current directory.
    This removes an inconsistency with -kernel and -initrd, which both
    accept plain filenames as meaning files in the current directory.
    It's also less confusing for the user than an undocumented restriction
    that "this option accepts a filename, except for the special case
    where the filename you pass happens not to have a '/' in it, in
    which case we'll ignore it."
    
    Signed-off-by: Peter Maydell <peter.maydell at linaro.org>
    Signed-off-by: Anthony Liguori <aliguori at us.ibm.com>

diff --git a/vl.c b/vl.c
index 1329c30..2e140f5 100644
--- a/vl.c
+++ b/vl.c
@@ -1795,9 +1795,8 @@ char *qemu_find_file(int type, const char *name)
     const char *subdir;
     char *buf;
 
-    /* If name contains path separators then try it as a straight path.  */
-    if ((strchr(name, '/') || strchr(name, '\\'))
-        && access(name, R_OK) == 0) {
+    /* Try the name as a straight path first */
+    if (access(name, R_OK) == 0) {
         return g_strdup(name);
     }
     switch (type) {
commit fdec9918578ec38738ecf250fa2c2656a44796b5
Author: Christian Borntraeger <borntraeger at de.ibm.com>
Date:   Fri Jun 15 05:10:30 2012 +0000

    s390: autodetect map private
    
    By default qemu will use MAP_PRIVATE for guest pages. This will write
    protect pages and thus break on s390 systems that dont support this feature.
    Therefore qemu has a hack to always use MAP_SHARED for s390. But MAP_SHARED
    has other problems (no dirty pages tracking, a lot more swap overhead etc.)
    Newer systems allow the distinction via KVM_CAP_S390_COW. With this feature
    qemu can use the standard qemu alloc if available, otherwise it will use
    the old s390 hack.
    
    Signed-off-by: Christian Borntraeger <borntraeger at de.ibm.com>
    Signed-off-by: Jens Freimann <jfrei at linux.vnet.ibm.com>
    Acked-by: Jan Kiszka <jan.kiszka at siemens.com>
    Signed-off-by: Alexander Graf <agraf at suse.de>

diff --git a/exec.c b/exec.c
index dd4833d..c9fa17d 100644
--- a/exec.c
+++ b/exec.c
@@ -2536,26 +2536,14 @@ ram_addr_t qemu_ram_alloc_from_ptr(ram_addr_t size, void *host,
             exit(1);
 #endif
         } else {
-#if defined(TARGET_S390X) && defined(CONFIG_KVM)
-            /* S390 KVM requires the topmost vma of the RAM to be smaller than
-               an system defined value, which is at least 256GB. Larger systems
-               have larger values. We put the guest between the end of data
-               segment (system break) and this value. We use 32GB as a base to
-               have enough room for the system break to grow. */
-            new_block->host = mmap((void*)0x800000000, size,
-                                   PROT_EXEC|PROT_READ|PROT_WRITE,
-                                   MAP_SHARED | MAP_ANONYMOUS | MAP_FIXED, -1, 0);
-            if (new_block->host == MAP_FAILED) {
-                fprintf(stderr, "Allocating RAM failed\n");
-                abort();
-            }
-#else
             if (xen_enabled()) {
                 xen_ram_alloc(new_block->offset, size, mr);
+            } else if (kvm_enabled()) {
+                /* some s390/kvm configurations have special constraints */
+                new_block->host = kvm_vmalloc(size);
             } else {
                 new_block->host = qemu_vmalloc(size);
             }
-#endif
             qemu_madvise(new_block->host, size, QEMU_MADV_MERGEABLE);
         }
     }
diff --git a/kvm-all.c b/kvm-all.c
index f8e4328..1016ca4 100644
--- a/kvm-all.c
+++ b/kvm-all.c
@@ -1655,6 +1655,19 @@ int kvm_allows_irq0_override(void)
     return !kvm_irqchip_in_kernel() || kvm_has_gsi_routing();
 }
 
+void *kvm_vmalloc(ram_addr_t size)
+{
+#ifdef TARGET_S390X
+    void *mem;
+
+    mem = kvm_arch_vmalloc(size);
+    if (mem) {
+        return mem;
+    }
+#endif
+    return qemu_vmalloc(size);
+}
+
 void kvm_setup_guest_memory(void *start, size_t size)
 {
     if (!kvm_has_sync_mmu()) {
diff --git a/kvm.h b/kvm.h
index 9c7b0ea..ddc7c53 100644
--- a/kvm.h
+++ b/kvm.h
@@ -70,6 +70,8 @@ int kvm_init_vcpu(CPUArchState *env);
 int kvm_cpu_exec(CPUArchState *env);
 
 #if !defined(CONFIG_USER_ONLY)
+void *kvm_vmalloc(ram_addr_t size);
+void *kvm_arch_vmalloc(ram_addr_t size);
 void kvm_setup_guest_memory(void *start, size_t size);
 
 int kvm_coalesce_mmio_region(target_phys_addr_t start, ram_addr_t size);
diff --git a/oslib-posix.c b/oslib-posix.c
index 6b7ba64..dbeb627 100644
--- a/oslib-posix.c
+++ b/oslib-posix.c
@@ -41,6 +41,9 @@ extern int daemon(int, int);
       therefore we need special code which handles running on Valgrind. */
 #  define QEMU_VMALLOC_ALIGN (512 * 4096)
 #  define CONFIG_VALGRIND
+#elif defined(__linux__) && defined(__s390x__)
+   /* Use 1 MiB (segment size) alignment so gmap can be used by KVM. */
+#  define QEMU_VMALLOC_ALIGN (256 * 4096)
 #else
 #  define QEMU_VMALLOC_ALIGN getpagesize()
 #endif
diff --git a/target-s390x/kvm.c b/target-s390x/kvm.c
index ec08dd0..47008c2 100644
--- a/target-s390x/kvm.c
+++ b/target-s390x/kvm.c
@@ -135,6 +135,41 @@ int kvm_arch_get_registers(CPUS390XState *env)
     return 0;
 }
 
+/*
+ * Legacy layout for s390:
+ * Older S390 KVM requires the topmost vma of the RAM to be
+ * smaller than an system defined value, which is at least 256GB.
+ * Larger systems have larger values. We put the guest between
+ * the end of data segment (system break) and this value. We
+ * use 32GB as a base to have enough room for the system break
+ * to grow. We also have to use MAP parameters that avoid
+ * read-only mapping of guest pages.
+ */
+static void *legacy_s390_alloc(ram_addr_t size)
+{
+    void *mem;
+
+    mem = mmap((void *) 0x800000000ULL, size,
+               PROT_EXEC|PROT_READ|PROT_WRITE,
+               MAP_SHARED | MAP_ANONYMOUS | MAP_FIXED, -1, 0);
+    if (mem == MAP_FAILED) {
+        fprintf(stderr, "Allocating RAM failed\n");
+        abort();
+    }
+    return mem;
+}
+
+void *kvm_arch_vmalloc(ram_addr_t size)
+{
+    /* Can we use the standard allocation ? */
+    if (kvm_check_extension(kvm_state, KVM_CAP_S390_GMAP) &&
+        kvm_check_extension(kvm_state, KVM_CAP_S390_COW)) {
+        return NULL;
+    } else {
+        return legacy_s390_alloc(size);
+    }
+}
+
 int kvm_arch_insert_sw_breakpoint(CPUS390XState *env, struct kvm_sw_breakpoint *bp)
 {
     static const uint8_t diag_501[] = {0x83, 0x24, 0x05, 0x01};
commit 8e86b93c2b69a7369aa62a6daec203fe5e757497
Author: Paolo Bonzini <pbonzini at redhat.com>
Date:   Mon Jul 9 12:06:28 2012 +0200

    scsi: add free_request callback
    
    Most device models have a simple lifecycle for the hba_private field
    and they can free it when a request is completed or cancelled.
    However, in some cases it may be simpler to tie the lifetime
    of hba_private to that of the included SCSIRequest.  This patch
    adds a free_request callback to SCSIBusInfo that lets an HBA
    device model do exactly that.
    
    Normally, device models use req->hba_private == NULL to flag requests
    that have been completed already.  Device models that use free_request
    will still need to track this using a flag.  This is the reason why
    "converting" existing HBAs to use free_request adds complexity and
    makes little sense.  It is simply an additional convenience that is
    provided by the SCSI layer.  USB-attached storage will be the first
    user.
    
    Signed-off-by: Paolo Bonzini <pbonzini at redhat.com>
    Signed-off-by: Gerd Hoffmann <kraxel at redhat.com>

diff --git a/hw/scsi-bus.c b/hw/scsi-bus.c
index 5ad1013..dc74063 100644
--- a/hw/scsi-bus.c
+++ b/hw/scsi-bus.c
@@ -1354,6 +1354,7 @@ static const char *scsi_command_name(uint8_t cmd)
 
 SCSIRequest *scsi_req_ref(SCSIRequest *req)
 {
+    assert(req->refcount > 0);
     req->refcount++;
     return req;
 }
@@ -1362,6 +1363,10 @@ void scsi_req_unref(SCSIRequest *req)
 {
     assert(req->refcount > 0);
     if (--req->refcount == 0) {
+        SCSIBus *bus = DO_UPCAST(SCSIBus, qbus, req->dev->qdev.parent_bus);
+        if (bus->info->free_request && req->hba_private) {
+            bus->info->free_request(bus, req->hba_private);
+        }
         if (req->ops->free_req) {
             req->ops->free_req(req);
         }
diff --git a/hw/scsi.h b/hw/scsi.h
index 76f06d4..367a346 100644
--- a/hw/scsi.h
+++ b/hw/scsi.h
@@ -134,6 +134,7 @@ struct SCSIBusInfo {
 
     void (*save_request)(QEMUFile *f, SCSIRequest *req);
     void *(*load_request)(QEMUFile *f, SCSIRequest *req);
+    void (*free_request)(SCSIBus *bus, void *priv);
 };
 
 #define TYPE_SCSI_BUS "SCSI"
commit 5d62c43a17edaa7f6a88821c9086e6c8e0e5327d
Author: Jan Kiszka <jan.kiszka at siemens.com>
Date:   Mon Jul 9 16:42:32 2012 +0200

    apic: Defer interrupt updates to VCPU thread
    
    KVM performs TPR raising asynchronously to QEMU, specifically outside
    QEMU's global lock. When an interrupt is injected into the APIC and TPR
    is checked to decide if this can be delivered, a stale TPR value may be
    used, causing spurious interrupts in the end.
    
    Fix this by deferring apic_update_irq to the context of the target VCPU.
    We introduce a new interrupt flag for this, CPU_INTERRUPT_POLL. When it
    is set, the VCPU calls apic_poll_irq before checking for further pending
    interrupts. To avoid special-casing KVM, we also implement this logic
    for TCG mode.
    
    Signed-off-by: Jan Kiszka <jan.kiszka at siemens.com>
    Signed-off-by: Avi Kivity <avi at redhat.com>

diff --git a/cpu-exec.c b/cpu-exec.c
index 08c35f7..fc185a4 100644
--- a/cpu-exec.c
+++ b/cpu-exec.c
@@ -288,6 +288,12 @@ int cpu_exec(CPUArchState *env)
                     }
 #endif
 #if defined(TARGET_I386)
+#if !defined(CONFIG_USER_ONLY)
+                    if (interrupt_request & CPU_INTERRUPT_POLL) {
+                        env->interrupt_request &= ~CPU_INTERRUPT_POLL;
+                        apic_poll_irq(env->apic_state);
+                    }
+#endif
                     if (interrupt_request & CPU_INTERRUPT_INIT) {
                             cpu_svm_check_intercept_param(env, SVM_EXIT_INIT,
                                                           0);
diff --git a/hw/apic.c b/hw/apic.c
index 5b8f3e8..385555e 100644
--- a/hw/apic.c
+++ b/hw/apic.c
@@ -16,6 +16,7 @@
  * You should have received a copy of the GNU Lesser General Public
  * License along with this library; if not, see <http://www.gnu.org/licenses/>
  */
+#include "qemu-thread.h"
 #include "apic_internal.h"
 #include "apic.h"
 #include "ioapic.h"
@@ -361,7 +362,9 @@ static void apic_update_irq(APICCommonState *s)
     if (!(s->spurious_vec & APIC_SV_ENABLE)) {
         return;
     }
-    if (apic_irq_pending(s) > 0) {
+    if (!qemu_cpu_is_self(s->cpu_env)) {
+        cpu_interrupt(s->cpu_env, CPU_INTERRUPT_POLL);
+    } else if (apic_irq_pending(s) > 0) {
         cpu_interrupt(s->cpu_env, CPU_INTERRUPT_HARD);
     }
 }
diff --git a/hw/apic.h b/hw/apic.h
index 62179ce..a89542b 100644
--- a/hw/apic.h
+++ b/hw/apic.h
@@ -20,6 +20,7 @@ void apic_init_reset(DeviceState *s);
 void apic_sipi(DeviceState *s);
 void apic_handle_tpr_access_report(DeviceState *d, target_ulong ip,
                                    TPRAccess access);
+void apic_poll_irq(DeviceState *d);
 
 /* pc.c */
 int cpu_is_bsp(CPUX86State *env);
diff --git a/hw/apic_internal.h b/hw/apic_internal.h
index 60a6a8b..4d8ff49 100644
--- a/hw/apic_internal.h
+++ b/hw/apic_internal.h
@@ -141,7 +141,6 @@ void apic_report_irq_delivered(int delivered);
 bool apic_next_timer(APICCommonState *s, int64_t current_time);
 void apic_enable_tpr_access_reporting(DeviceState *d, bool enable);
 void apic_enable_vapic(DeviceState *d, target_phys_addr_t paddr);
-void apic_poll_irq(DeviceState *d);
 
 void vapic_report_tpr_access(DeviceState *dev, void *cpu, target_ulong ip,
                              TPRAccess access);
diff --git a/target-i386/cpu.h b/target-i386/cpu.h
index 33d221e..2a61c81 100644
--- a/target-i386/cpu.h
+++ b/target-i386/cpu.h
@@ -478,6 +478,7 @@
                                  for syscall instruction */
 
 /* i386-specific interrupt pending bits.  */
+#define CPU_INTERRUPT_POLL      CPU_INTERRUPT_TGT_EXT_1
 #define CPU_INTERRUPT_SMI       CPU_INTERRUPT_TGT_EXT_2
 #define CPU_INTERRUPT_NMI       CPU_INTERRUPT_TGT_EXT_3
 #define CPU_INTERRUPT_MCE       CPU_INTERRUPT_TGT_EXT_4
@@ -1048,7 +1049,8 @@ static inline void cpu_clone_regs(CPUX86State *env, target_ulong newsp)
 
 static inline bool cpu_has_work(CPUX86State *env)
 {
-    return ((env->interrupt_request & CPU_INTERRUPT_HARD) &&
+    return ((env->interrupt_request & (CPU_INTERRUPT_HARD |
+                                       CPU_INTERRUPT_POLL)) &&
             (env->eflags & IF_MASK)) ||
            (env->interrupt_request & (CPU_INTERRUPT_NMI |
                                       CPU_INTERRUPT_INIT |
diff --git a/target-i386/kvm.c b/target-i386/kvm.c
index 52b577f..e53c2f6 100644
--- a/target-i386/kvm.c
+++ b/target-i386/kvm.c
@@ -1732,6 +1732,10 @@ int kvm_arch_process_async_events(CPUX86State *env)
         return 0;
     }
 
+    if (env->interrupt_request & CPU_INTERRUPT_POLL) {
+        env->interrupt_request &= ~CPU_INTERRUPT_POLL;
+        apic_poll_irq(env->apic_state);
+    }
     if (((env->interrupt_request & CPU_INTERRUPT_HARD) &&
          (env->eflags & IF_MASK)) ||
         (env->interrupt_request & CPU_INTERRUPT_NMI)) {
commit a94820ddc36f8c452b37f9dcb323f55ffdbc75f9
Author: Jan Kiszka <jan.kiszka at siemens.com>
Date:   Mon Jul 9 16:42:31 2012 +0200

    apic: Reevaluate pending interrupts on LVT_LINT0 changes
    
    When the guest modifies the LVT_LINT0 register, we need to check if some
    pending PIC interrupt can now be delivered.
    
    Signed-off-by: Jan Kiszka <jan.kiszka at siemens.com>
    Signed-off-by: Avi Kivity <avi at redhat.com>

diff --git a/hw/apic.c b/hw/apic.c
index e65a35f..5b8f3e8 100644
--- a/hw/apic.c
+++ b/hw/apic.c
@@ -532,6 +532,15 @@ static void apic_deliver(DeviceState *d, uint8_t dest, uint8_t dest_mode,
     apic_bus_deliver(deliver_bitmask, delivery_mode, vector_num, trigger_mode);
 }
 
+static bool apic_check_pic(APICCommonState *s)
+{
+    if (!apic_accept_pic_intr(&s->busdev.qdev) || !pic_get_output(isa_pic)) {
+        return false;
+    }
+    apic_deliver_pic_intr(&s->busdev.qdev, 1);
+    return true;
+}
+
 int apic_get_interrupt(DeviceState *d)
 {
     APICCommonState *s = DO_UPCAST(APICCommonState, busdev.qdev, d);
@@ -559,9 +568,7 @@ int apic_get_interrupt(DeviceState *d)
     apic_sync_vapic(s, SYNC_TO_VAPIC);
 
     /* re-inject if there is still a pending PIC interrupt */
-    if (apic_accept_pic_intr(&s->busdev.qdev) && pic_get_output(isa_pic)) {
-        apic_deliver_pic_intr(&s->busdev.qdev, 1);
-    }
+    apic_check_pic(s);
 
     apic_update_irq(s);
 
@@ -804,8 +811,11 @@ static void apic_mem_writel(void *opaque, target_phys_addr_t addr, uint32_t val)
         {
             int n = index - 0x32;
             s->lvt[n] = val;
-            if (n == APIC_LVT_TIMER)
+            if (n == APIC_LVT_TIMER) {
                 apic_timer_update(s, qemu_get_clock_ns(vm_clock));
+            } else if (n == APIC_LVT_LINT0 && apic_check_pic(s)) {
+                apic_update_irq(s);
+            }
         }
         break;
     case 0x38:
commit 3db3659bf60094657e1465cc809acb09551816ee
Author: Jan Kiszka <jan.kiszka at siemens.com>
Date:   Mon Jul 9 16:42:30 2012 +0200

    apic: Resolve potential endless loop around apic_update_irq
    
    Commit d96e173769 refactored the reinjection of pending PIC interrupts.
    However, it missed the potential loop of apic_update_irq ->
    apic_deliver_pic_intr -> apic_local_deliver -> apic_set_irq ->
    apic_update_irq that /could/ occur if LINT0 is injected as APIC_DM_FIXED
    and that vector is currently blocked via TPR.
    
    Resolve this by reinjecting only where it matters: inside
    apic_get_interrupt. This function may clear a vector while a
    PIC-originated reason still exists.
    
    Signed-off-by: Jan Kiszka <jan.kiszka at siemens.com>
    Signed-off-by: Avi Kivity <avi at redhat.com>

diff --git a/hw/apic.c b/hw/apic.c
index 60552df..e65a35f 100644
--- a/hw/apic.c
+++ b/hw/apic.c
@@ -363,9 +363,6 @@ static void apic_update_irq(APICCommonState *s)
     }
     if (apic_irq_pending(s) > 0) {
         cpu_interrupt(s->cpu_env, CPU_INTERRUPT_HARD);
-    } else if (apic_accept_pic_intr(&s->busdev.qdev) &&
-               pic_get_output(isa_pic)) {
-        apic_deliver_pic_intr(&s->busdev.qdev, 1);
     }
 }
 
@@ -560,7 +557,14 @@ int apic_get_interrupt(DeviceState *d)
     reset_bit(s->irr, intno);
     set_bit(s->isr, intno);
     apic_sync_vapic(s, SYNC_TO_VAPIC);
+
+    /* re-inject if there is still a pending PIC interrupt */
+    if (apic_accept_pic_intr(&s->busdev.qdev) && pic_get_output(isa_pic)) {
+        apic_deliver_pic_intr(&s->busdev.qdev, 1);
+    }
+
     apic_update_irq(s);
+
     return intno;
 }
 
commit 92336855975805d88c7979f53bc05c2d47abab04
Author: Anthony Liguori <aliguori at us.ibm.com>
Date:   Mon Jul 9 18:16:16 2012 -0500

    megasas: disable due to build breakage
    
    The Buildbot has detected a new failure on builder default_i386_rhel61 while
    building qemu.
    
    Full details are available at:
     http://buildbot.b1-systems.de/qemu/builders/default_i386_rhel61/builds/304
    
    The proper fix is non-trivial so let's disable the build by default until it's
    fixed properly.
    
    Signed-off-by: Anthony Liguori <aliguori at us.ibm.com>

diff --git a/default-configs/pci.mak b/default-configs/pci.mak
index 4b49c00..9d3e1db 100644
--- a/default-configs/pci.mak
+++ b/default-configs/pci.mak
@@ -10,7 +10,6 @@ CONFIG_EEPRO100_PCI=y
 CONFIG_PCNET_PCI=y
 CONFIG_PCNET_COMMON=y
 CONFIG_LSI_SCSI_PCI=y
-CONFIG_MEGASAS_SCSI_PCI=y
 CONFIG_RTL8139_PCI=y
 CONFIG_E1000_PCI=y
 CONFIG_IDE_CORE=y
commit 23797df3d9f08031d19aaaa1d2863d5feebe3d8b
Merge: 3f6e9a5... 25e5e4c...
Author: Anthony Liguori <aliguori at us.ibm.com>
Date:   Mon Jul 9 12:35:06 2012 -0500

    Merge remote-tracking branch 'mjt/mjt-iov2' into staging
    
    * mjt/mjt-iov2:
      rewrite iov_send_recv() and move it to iov.c
      cleanup qemu_co_sendv(), qemu_co_recvv() and friends
      export iov_send_recv() and use it in iov_send() and iov_recv()
      rename qemu_sendv to iov_send, change proto and move declarations to iov.h
      change qemu_iovec_to_buf() to match other to,from_buf functions
      consolidate qemu_iovec_copy() and qemu_iovec_concat() and make them consistent
      allow qemu_iovec_from_buffer() to specify offset from which to start copying
      consolidate qemu_iovec_memset{,_skip}() into single function and use existing iov_memset()
      rewrite iov_* functions
      change iov_* function prototypes to be more appropriate
      virtio-serial-bus: use correct lengths in control_out() message
    
    Conflicts:
    	tests/Makefile
    
    Signed-off-by: Anthony Liguori <aliguori at us.ibm.com>

diff --cc Makefile
index bad0e31,017836b..34d6a9e
--- a/Makefile
+++ b/Makefile
@@@ -154,9 -151,11 +154,10 @@@ vscclient$(EXESUF): $(libcacard-y) $(os
  ######################################################################
  
  qemu-img.o: qemu-img-cmds.h
 -qemu-img.o qemu-tool.o qemu-nbd.o qemu-io.o cmd.o qemu-ga.o: $(GENERATED_HEADERS)
  
  tools-obj-y = $(oslib-obj-y) $(trace-obj-y) qemu-tool.o qemu-timer.o \
- 	qemu-timer-common.o main-loop.o notify.o iohandler.o cutils.o async.o
+ 	qemu-timer-common.o main-loop.o notify.o \
+ 	iohandler.o cutils.o iov.o async.o
  tools-obj-$(CONFIG_POSIX) += compatfd.o
  
  qemu-img$(EXESUF): qemu-img.o $(tools-obj-y) $(block-obj-y)
diff --cc tests/Makefile
index d66ab19,7340bc5..d687ecc
--- a/tests/Makefile
+++ b/tests/Makefile
@@@ -13,7 -13,7 +13,8 @@@ check-unit-y += tests/test-qmp-commands
  check-unit-y += tests/test-string-input-visitor$(EXESUF)
  check-unit-y += tests/test-string-output-visitor$(EXESUF)
  check-unit-y += tests/test-coroutine$(EXESUF)
 +check-unit-y += tests/test-visitor-serialization$(EXESUF)
+ check-unit-y += tests/test-iov$(EXESUF)
  
  check-block-$(CONFIG_POSIX) += tests/qemu-iotests-quick.sh
  
commit 3f6e9a5fad982713440c636f5f7b786e1cc86ca2
Merge: 537cf40... 45f33f0...
Author: Anthony Liguori <aliguori at us.ibm.com>
Date:   Mon Jul 9 11:57:34 2012 -0500

    Merge remote-tracking branch 'quintela/migration-anthony-v2' into staging
    
    * quintela/migration-anthony-v2:
      Maintain the number of dirty pages
      dirty bitmap: abstract its use
      Exit loop if we have been there too long
      Only calculate expected_time for stage 2
      Only TCG needs TLB handling
      No need to iterate if we already are over the limit
      Add tracepoints for savevm section start/end
      Add spent time for migration
      Add migration_end function
      Add debugging infrastructure
      Add save_block_hdr function
      Add MigrationParams structure
      Add missing check for host_from_stream_offset return value for RAM_SAVE_FLAG_PAGE

commit 537cf409421efe68b0df645d8bbb627b2702dd1f
Merge: 715cc00... 22a61f3...
Author: Anthony Liguori <aliguori at us.ibm.com>
Date:   Mon Jul 9 11:56:43 2012 -0500

    Merge remote-tracking branch 'kiszka/queues/slirp' into staging
    
    * kiszka/queues/slirp:
      slirp: Improve error reporting of inaccessible smb directories
      slirp: Ensure smbd and shared directory exist when enable smb
      slirp: add 'cmd:' target for guestfwd
      slirp: Enforce host-side user of smb share

commit 22a61f365df83d5d7884cceb1c462295977cb2db
Author: Jan Kiszka <jan.kiszka at siemens.com>
Date:   Fri Jul 6 08:40:48 2012 +0200

    slirp: Improve error reporting of inaccessible smb directories
    
    Instead of guessing, print the error code returned by access.
    
    Signed-off-by: Jan Kiszka <jan.kiszka at siemens.com>

diff --git a/net/slirp.c b/net/slirp.c
index eb80889..b82eab0 100644
--- a/net/slirp.c
+++ b/net/slirp.c
@@ -504,8 +504,8 @@ static int slirp_smb(SlirpState* s, const char *exported_dir,
     }
 
     if (access(exported_dir, R_OK | X_OK)) {
-        error_report("no such directory '%s', or you do not have permission "
-                     "to access it, please check it", exported_dir);
+        error_report("error accessing shared directory '%s': %s",
+                     exported_dir, strerror(errno));
         return -1;
     }
 
commit 927d811b282ffdf5386bd63f435c1507634ba49a
Author: Dunrong Huang <riegamaths at gmail.com>
Date:   Fri Jul 6 14:04:43 2012 +0800

    slirp: Ensure smbd and shared directory exist when enable smb
    
    Users may pass the following parameters to qemu:
        $ qemu-kvm -net nic -net user,smb= ...
        $ qemu-kvm -net nic -net user,smb ...
        $ qemu-kvm -net nic -net user,smb=bad_directory ...
    
    In these cases, qemu started successfully while samba server
    failed to start. Users will confuse since samba server
    failed silently without any indication of what it did wrong.
    
    To avoid it, we check whether the shared directory exist and
    if users have permission to access this directory when QEMU's
    "built-in" SMB server is enabled.
    
    Signed-off-by: Dunrong Huang <riegamaths at gmail.com>
    Signed-off-by: Jan Kiszka <jan.kiszka at siemens.com>

diff --git a/net/slirp.c b/net/slirp.c
index 180147e..eb80889 100644
--- a/net/slirp.c
+++ b/net/slirp.c
@@ -497,6 +497,18 @@ static int slirp_smb(SlirpState* s, const char *exported_dir,
         return -1;
     }
 
+    if (access(CONFIG_SMBD_COMMAND, F_OK)) {
+        error_report("could not find '%s', please install it",
+                     CONFIG_SMBD_COMMAND);
+        return -1;
+    }
+
+    if (access(exported_dir, R_OK | X_OK)) {
+        error_report("no such directory '%s', or you do not have permission "
+                     "to access it, please check it", exported_dir);
+        return -1;
+    }
+
     snprintf(s->smb_dir, sizeof(s->smb_dir), "/tmp/qemu-smb.%ld-%d",
              (long)getpid(), instance++);
     if (mkdir(s->smb_dir, 0700) < 0) {
commit b412eb61bfd400ad70afe11ac3a5fb2931124804
Author: Alexander Graf <agraf at suse.de>
Date:   Sun Jun 3 09:45:01 2012 +0200

    slirp: add 'cmd:' target for guestfwd
    
    When using guestfwd=, Qemu only connects the virtual server's TCP port
    to a single chardev. This is useless in most cases, as we usually want
    to have more than a single connection from the guest to the outside world.
    
    This patch adds a new cmd: target to guestfwd= that allows for execution
    of a command on every TCP connection. This leverages the same code as
    the -smb parameter, just that here the command is user defined.
    
    Reported-by: Sascha Wilde <wilde at intevation.de>
    Signed-off-by: Alexander Graf <agraf at suse.de>
    Signed-off-by: Jan Kiszka <jan.kiszka at siemens.com>

diff --git a/net/slirp.c b/net/slirp.c
index a43b576..180147e 100644
--- a/net/slirp.c
+++ b/net/slirp.c
@@ -626,25 +626,35 @@ static int slirp_guestfwd(SlirpState *s, const char *config_str,
 
     fwd = g_malloc(sizeof(struct GuestFwd));
     snprintf(buf, sizeof(buf), "guestfwd.tcp.%d", port);
-    fwd->hd = qemu_chr_new(buf, p, NULL);
-    if (!fwd->hd) {
-        error_report("could not open guest forwarding device '%s'", buf);
-        g_free(fwd);
-        return -1;
-    }
 
-    if (slirp_add_exec(s->slirp, 3, fwd->hd, &server, port) < 0) {
-        error_report("conflicting/invalid host:port in guest forwarding "
-                     "rule '%s'", config_str);
-        g_free(fwd);
-        return -1;
-    }
-    fwd->server = server;
-    fwd->port = port;
-    fwd->slirp = s->slirp;
+    if ((strlen(p) > 4) && !strncmp(p, "cmd:", 4)) {
+        if (slirp_add_exec(s->slirp, 0, &p[4], &server, port) < 0) {
+            error_report("conflicting/invalid host:port in guest forwarding "
+                         "rule '%s'", config_str);
+            g_free(fwd);
+            return -1;
+        }
+    } else {
+        fwd->hd = qemu_chr_new(buf, p, NULL);
+        if (!fwd->hd) {
+            error_report("could not open guest forwarding device '%s'", buf);
+            g_free(fwd);
+            return -1;
+        }
+
+        if (slirp_add_exec(s->slirp, 3, fwd->hd, &server, port) < 0) {
+            error_report("conflicting/invalid host:port in guest forwarding "
+                         "rule '%s'", config_str);
+            g_free(fwd);
+            return -1;
+        }
+        fwd->server = server;
+        fwd->port = port;
+        fwd->slirp = s->slirp;
 
-    qemu_chr_add_handlers(fwd->hd, guestfwd_can_read, guestfwd_read,
-                          NULL, fwd);
+        qemu_chr_add_handlers(fwd->hd, guestfwd_can_read, guestfwd_read,
+                              NULL, fwd);
+    }
     return 0;
 
  fail_syntax:
diff --git a/qemu-options.hx b/qemu-options.hx
index 8b66264..ecf7ca1 100644
--- a/qemu-options.hx
+++ b/qemu-options.hx
@@ -1421,8 +1421,28 @@ Then when you use on the host @code{telnet localhost 5555}, you
 connect to the guest telnet server.
 
 @item guestfwd=[tcp]:@var{server}:@var{port}- at var{dev}
+ at item guestfwd=[tcp]:@var{server}:@var{port}- at var{cmd:command}
 Forward guest TCP connections to the IP address @var{server} on port @var{port}
-to the character device @var{dev}. This option can be given multiple times.
+to the character device @var{dev} or to a program executed by @var{cmd:command}
+which gets spawned for each connection. This option can be given multiple times.
+
+You can either use a chardev directly and have that one used throughout Qemu's
+lifetime, like in the following example:
+
+ at example
+# open 10.10.1.1:4321 on bootup, connect 10.0.2.100:1234 to it whenever
+# the guest accesses it
+qemu -net user,guestfwd=tcp:10.0.2.100:1234-tcp:10.10.1.1:4321 [...]
+ at end example
+
+Or you can execute a command on every TCP connection established by the guest,
+so that Qemu behaves similar to an inetd process for that virtual server:
+
+ at example
+# call "netcat 10.10.1.1 4321" on every TCP connection to 10.0.2.100:1234
+# and connect the TCP stream to its stdin/stdout
+qemu -net 'user,guestfwd=tcp:10.0.2.100:1234-cmd:netcat 10.10.1.1 4321'
+ at end example
 
 @end table
 
commit 1cb1c5d10bb9e180bd3f7be2c10b212ed86a97b4
Author: Jan Kiszka <jan.kiszka at siemens.com>
Date:   Thu Jul 5 19:35:57 2012 +0200

    slirp: Enforce host-side user of smb share
    
    Windows 7 (and possibly other versions) cannot connect to the samba
    share if the exported host directory is not world-readable. This can be
    resolved by forcing the username used for access checks to the one
    under which QEMU and smbd are running.
    
    Signed-off-by: Jan Kiszka <jan.kiszka at siemens.com>

diff --git a/net/slirp.c b/net/slirp.c
index 37b6ccf..a43b576 100644
--- a/net/slirp.c
+++ b/net/slirp.c
@@ -26,6 +26,7 @@
 #include "config-host.h"
 
 #ifndef _WIN32
+#include <pwd.h>
 #include <sys/wait.h>
 #endif
 #include "net.h"
@@ -487,8 +488,15 @@ static int slirp_smb(SlirpState* s, const char *exported_dir,
     static int instance;
     char smb_conf[128];
     char smb_cmdline[128];
+    struct passwd *passwd;
     FILE *f;
 
+    passwd = getpwuid(geteuid());
+    if (!passwd) {
+        error_report("failed to retrieve user name");
+        return -1;
+    }
+
     snprintf(s->smb_dir, sizeof(s->smb_dir), "/tmp/qemu-smb.%ld-%d",
              (long)getpid(), instance++);
     if (mkdir(s->smb_dir, 0700) < 0) {
@@ -517,14 +525,16 @@ static int slirp_smb(SlirpState* s, const char *exported_dir,
             "[qemu]\n"
             "path=%s\n"
             "read only=no\n"
-            "guest ok=yes\n",
+            "guest ok=yes\n"
+            "force user=%s\n",
             s->smb_dir,
             s->smb_dir,
             s->smb_dir,
             s->smb_dir,
             s->smb_dir,
             s->smb_dir,
-            exported_dir
+            exported_dir,
+            passwd->pw_name
             );
     fclose(f);
 
commit 715cc00ce133a2774d0d91fb66d706df990ea342
Merge: fe0cb8e... 07d27a4...
Author: Anthony Liguori <aliguori at us.ibm.com>
Date:   Mon Jul 9 10:29:40 2012 -0500

    Merge remote-tracking branch 'kwolf/for-anthony' into staging
    
    * kwolf/for-anthony: (24 commits)
      block: Factor bdrv_read_unthrottled() out of guess_disk_lchs()
      qtest: Tidy up temporary files properly
      fdc: Drop broken code for user-defined floppy geometry
      fdc_test: introduce test_sense_interrupt
      fdc_test: update media_change test
      fdc: fix interrupt handling
      fdc: rewrite seek and DSKCHG bit handling
      block: introduce bdrv_swap, implement bdrv_append on top of it
      block: copy over job and dirty bitmap fields in bdrv_append
      raw: hook into blkdebug
      blkdebug: optionally tie errors to a specific sector
      blkdebug: store list of active rules
      blkdebug: pass getlength to underlying file
      blkdebug: tiny cleanup
      blkdebug: remove sync i/o events
      sheepdog: traverse pending_list from the first for each time
      sheepdog: split outstanding list into inflight and pending
      sheepdog: make sure we don't free aiocb before sending all requests
      sheepdog: use coroutine based socket functions in coroutine context
      sheepdog: restart I/O when socket becomes ready in do_co_req()
      ...

commit 07d27a442e01870ea6fc2d6ffbe1df61dccaafc4
Author: Markus Armbruster <armbru at redhat.com>
Date:   Fri Jun 29 17:34:29 2012 +0200

    block: Factor bdrv_read_unthrottled() out of guess_disk_lchs()
    
    To prepare move of guess_disk_lchs() into hw/, where it poking
    BlockDriverState member io_limits_enabled directly would be unclean.
    
    Signed-off-by: Markus Armbruster <armbru at redhat.com>
    Signed-off-by: Kevin Wolf <kwolf at redhat.com>

diff --git a/block.c b/block.c
index f2540b9..b410ed6 100644
--- a/block.c
+++ b/block.c
@@ -1639,6 +1639,20 @@ int bdrv_read(BlockDriverState *bs, int64_t sector_num,
     return bdrv_rw_co(bs, sector_num, buf, nb_sectors, false);
 }
 
+/* Just like bdrv_read(), but with I/O throttling temporarily disabled */
+int bdrv_read_unthrottled(BlockDriverState *bs, int64_t sector_num,
+                          uint8_t *buf, int nb_sectors)
+{
+    bool enabled;
+    int ret;
+
+    enabled = bs->io_limits_enabled;
+    bs->io_limits_enabled = false;
+    ret = bdrv_read(bs, 0, buf, 1);
+    bs->io_limits_enabled = enabled;
+    return ret;
+}
+
 #define BITS_PER_LONG  (sizeof(unsigned long) * 8)
 
 static void set_dirty_bitmap(BlockDriverState *bs, int64_t sector_num,
@@ -2136,11 +2150,10 @@ static int guess_disk_lchs(BlockDriverState *bs,
                            int *pcylinders, int *pheads, int *psectors)
 {
     uint8_t buf[BDRV_SECTOR_SIZE];
-    int ret, i, heads, sectors, cylinders;
+    int i, heads, sectors, cylinders;
     struct partition *p;
     uint32_t nr_sects;
     uint64_t nb_sectors;
-    bool enabled;
 
     bdrv_get_geometry(bs, &nb_sectors);
 
@@ -2149,12 +2162,9 @@ static int guess_disk_lchs(BlockDriverState *bs,
      * but also in async I/O mode. So the I/O throttling function has to
      * be disabled temporarily here, not permanently.
      */
-    enabled = bs->io_limits_enabled;
-    bs->io_limits_enabled = false;
-    ret = bdrv_read(bs, 0, buf, 1);
-    bs->io_limits_enabled = enabled;
-    if (ret < 0)
+    if (bdrv_read_unthrottled(bs, 0, buf, 1) < 0) {
         return -1;
+    }
     /* test msdos magic */
     if (buf[510] != 0x55 || buf[511] != 0xaa)
         return -1;
diff --git a/block.h b/block.h
index 3af93c6..e34d942 100644
--- a/block.h
+++ b/block.h
@@ -142,6 +142,8 @@ bool bdrv_dev_is_tray_open(BlockDriverState *bs);
 bool bdrv_dev_is_medium_locked(BlockDriverState *bs);
 int bdrv_read(BlockDriverState *bs, int64_t sector_num,
               uint8_t *buf, int nb_sectors);
+int bdrv_read_unthrottled(BlockDriverState *bs, int64_t sector_num,
+                          uint8_t *buf, int nb_sectors);
 int bdrv_write(BlockDriverState *bs, int64_t sector_num,
                const uint8_t *buf, int nb_sectors);
 int bdrv_pread(BlockDriverState *bs, int64_t offset,
commit bb494a505e17dd06a07a662b8c800f255ac387c4
Author: Markus Armbruster <armbru at redhat.com>
Date:   Fri Jun 29 17:34:27 2012 +0200

    qtest: Tidy up temporary files properly
    
    Each test litters /tmp with several files: a pid file and two
    sockets.  Tidy up.
    
    Signed-off-by: Markus Armbruster <armbru at redhat.com>
    Signed-off-by: Kevin Wolf <kwolf at redhat.com>

diff --git a/tests/libqtest.c b/tests/libqtest.c
index 071b6be..02d0392 100644
--- a/tests/libqtest.c
+++ b/tests/libqtest.c
@@ -40,6 +40,7 @@ struct QTestState
     bool irq_level[MAX_IRQ];
     GString *rx;
     gchar *pid_file;
+    char *socket_path, *qmp_socket_path;
 };
 
 #define g_assert_no_errno(ret) do { \
@@ -88,8 +89,6 @@ QTestState *qtest_init(const char *extra_args)
 {
     QTestState *s;
     int sock, qmpsock, ret, i;
-    gchar *socket_path;
-    gchar *qmp_socket_path;
     gchar *pid_file;
     gchar *command;
     const char *qemu_binary;
@@ -98,14 +97,14 @@ QTestState *qtest_init(const char *extra_args)
     qemu_binary = getenv("QTEST_QEMU_BINARY");
     g_assert(qemu_binary != NULL);
 
-    socket_path = g_strdup_printf("/tmp/qtest-%d.sock", getpid());
-    qmp_socket_path = g_strdup_printf("/tmp/qtest-%d.qmp", getpid());
-    pid_file = g_strdup_printf("/tmp/qtest-%d.pid", getpid());
-
     s = g_malloc(sizeof(*s));
 
-    sock = init_socket(socket_path);
-    qmpsock = init_socket(qmp_socket_path);
+    s->socket_path = g_strdup_printf("/tmp/qtest-%d.sock", getpid());
+    s->qmp_socket_path = g_strdup_printf("/tmp/qtest-%d.qmp", getpid());
+    pid_file = g_strdup_printf("/tmp/qtest-%d.pid", getpid());
+
+    sock = init_socket(s->socket_path);
+    qmpsock = init_socket(s->qmp_socket_path);
 
     pid = fork();
     if (pid == 0) {
@@ -115,8 +114,8 @@ QTestState *qtest_init(const char *extra_args)
                                   "-qmp unix:%s,nowait "
                                   "-pidfile %s "
                                   "-machine accel=qtest "
-                                  "%s", qemu_binary, socket_path,
-                                  qmp_socket_path, pid_file,
+                                  "%s", qemu_binary, s->socket_path,
+                                  s->qmp_socket_path, pid_file,
                                   extra_args ?: "");
 
         ret = system(command);
@@ -133,9 +132,6 @@ QTestState *qtest_init(const char *extra_args)
         s->irq_level[i] = false;
     }
 
-    g_free(socket_path);
-    g_free(qmp_socket_path);
-
     /* Read the QMP greeting and then do the handshake */
     qtest_qmp(s, "");
     qtest_qmp(s, "{ 'execute': 'qmp_capabilities' }");
@@ -160,6 +156,13 @@ void qtest_quit(QTestState *s)
 
         fclose(f);
     }
+
+    unlink(s->pid_file);
+    unlink(s->socket_path);
+    unlink(s->qmp_socket_path);
+    g_free(s->pid_file);
+    g_free(s->socket_path);
+    g_free(s->qmp_socket_path);
 }
 
 static void socket_sendf(int fd, const char *fmt, va_list ap)
commit fe0cb8ef84f8bc00ab00f71748aa0e84be7f2bbe
Merge: ffd6e7a... c32da15...
Author: Anthony Liguori <aliguori at us.ibm.com>
Date:   Mon Jul 9 09:51:33 2012 -0500

    Merge remote-tracking branch 'kraxel/usb.55' into staging
    
    * kraxel/usb.55:
      usb-host: add trace events for iso xfers
      usb: fix interface initialization
      usb: split endpoint init and reset
      usb-redir: Correctly handle the usb_redir_babble usbredir status
      ehci: Kick async schedule on wakeup in the non companion case
      usb-ehci: Fix an assert whenever isoc transfers are used
      ehci: don't flush cache on doorbell rings.
      ehci: fix td writeback
      ehci: fix ehci_qh_do_overlay

commit ffd6e7a0725bf7f5dab894a1a8cbe6d99baab604
Merge: 8665817... 9ce1bb2...
Author: Anthony Liguori <aliguori at us.ibm.com>
Date:   Mon Jul 9 09:51:19 2012 -0500

    Merge remote-tracking branch 'bonzini/scsi-next' into staging
    
    * bonzini/scsi-next:
      scsi: Fix transfer length for READ POSITION commands.
      scsi: Add basic support for SCSI media changer commands.
      scsi: Ensure command and transfer lengths are set for all SCSI devices
      scsi: Fix LOAD_UNLOAD
      scsi: Fix data length == SCSI_SENSE_BUF_SIZE
      virtio-scsi: do not crash on adding buffers to the event queue
      megasas: LSI Megaraid SAS HBA emulation
      megasas: Add header file
      ISCSI: force use of sg for SMC and SSC devices
      ISCSI: Add SCSI passthrough via scsi-generic to libiscsi
      scsi-disk: implement READ DISC INFORMATION
      atapi: implement READ DISC INFORMATION
      scsi: add a qdev property for the disk's WWN
      scsi: simplify handling of the VPD page length field

commit 8665817e892c1ed6cec415a65b56eb9944894fbc
Merge: 84988cf... f595e73...
Author: Anthony Liguori <aliguori at us.ibm.com>
Date:   Mon Jul 9 09:51:06 2012 -0500

    Merge remote-tracking branch 'stefanha/trivial-patches' into staging
    
    * stefanha/trivial-patches:
      configure: Remove help for --disable-vnc-thread, --enable-vnc-thread
      cpu-common.h: Remove a pointless ifndef CONFIG_USER_ONLY
      cpu-common.h: Remove unnecessary guard on including targphys.h

commit 1f69c2b022710222ff0379678e49f8bfb6c91233
Author: Markus Armbruster <armbru at redhat.com>
Date:   Fri Jun 29 17:34:23 2012 +0200

    fdc: Drop broken code for user-defined floppy geometry
    
    bdrv_get_floppy_geometry_hint() fails to store through its parameter
    drive when bs has a geometry hint.  Makes fd_revalidate() assign
    random crap to drv->drive.
    
    Has been broken that way for ages.  Harmless, because:
    
    * The only way to set a geometry hint is -drive if=none,cyls=...
      Since commit c219331e, probably unintentional.
    
    * The only use of drv->drive is as argument to another
      bdrv_get_floppy_geometry_hint().  Which doesn't use it, since the
      geometry hint is still there.
    
    Drop the broken code, ignore -drive parameter cyls, heads and secs for
    floppies even with if=none, just like before commit c219331e.  Matches
    -help, which explains cyls, heads, secs as "hard disk physical
    geometry".
    
    Signed-off-by: Markus Armbruster <armbru at redhat.com>
    Signed-off-by: Kevin Wolf <kwolf at redhat.com>

diff --git a/block.c b/block.c
index 29857db..f2540b9 100644
--- a/block.c
+++ b/block.c
@@ -2337,46 +2337,40 @@ void bdrv_get_floppy_geometry_hint(BlockDriverState *bs, int *nb_heads,
     uint64_t nb_sectors, size;
     int i, first_match, match;
 
-    bdrv_get_geometry_hint(bs, nb_heads, max_track, last_sect);
-    if (*nb_heads != 0 && *max_track != 0 && *last_sect != 0) {
-        /* User defined disk */
-        *rate = FDRIVE_RATE_500K;
-    } else {
-        bdrv_get_geometry(bs, &nb_sectors);
-        match = -1;
-        first_match = -1;
-        for (i = 0; ; i++) {
-            parse = &fd_formats[i];
-            if (parse->drive == FDRIVE_DRV_NONE) {
+    bdrv_get_geometry(bs, &nb_sectors);
+    match = -1;
+    first_match = -1;
+    for (i = 0; ; i++) {
+        parse = &fd_formats[i];
+        if (parse->drive == FDRIVE_DRV_NONE) {
+            break;
+        }
+        if (drive_in == parse->drive ||
+            drive_in == FDRIVE_DRV_NONE) {
+            size = (parse->max_head + 1) * parse->max_track *
+                parse->last_sect;
+            if (nb_sectors == size) {
+                match = i;
                 break;
             }
-            if (drive_in == parse->drive ||
-                drive_in == FDRIVE_DRV_NONE) {
-                size = (parse->max_head + 1) * parse->max_track *
-                    parse->last_sect;
-                if (nb_sectors == size) {
-                    match = i;
-                    break;
-                }
-                if (first_match == -1) {
-                    first_match = i;
-                }
-            }
-        }
-        if (match == -1) {
             if (first_match == -1) {
-                match = 1;
-            } else {
-                match = first_match;
+                first_match = i;
             }
-            parse = &fd_formats[match];
         }
-        *nb_heads = parse->max_head + 1;
-        *max_track = parse->max_track;
-        *last_sect = parse->last_sect;
-        *drive = parse->drive;
-        *rate = parse->rate;
     }
+    if (match == -1) {
+        if (first_match == -1) {
+            match = 1;
+        } else {
+            match = first_match;
+        }
+        parse = &fd_formats[match];
+    }
+    *nb_heads = parse->max_head + 1;
+    *max_track = parse->max_track;
+    *last_sect = parse->last_sect;
+    *drive = parse->drive;
+    *rate = parse->rate;
 }
 
 int bdrv_get_translation_hint(BlockDriverState *bs)
diff --git a/hw/fdc.c b/hw/fdc.c
index e28841c..edf0706 100644
--- a/hw/fdc.c
+++ b/hw/fdc.c
@@ -191,9 +191,6 @@ static void fd_revalidate(FDrive *drv)
                                       &last_sect, drv->drive, &drive, &rate);
         if (!bdrv_is_inserted(drv->bs)) {
             FLOPPY_DPRINTF("No disk in drive\n");
-        } else if (nb_heads != 0 && max_track != 0 && last_sect != 0) {
-            FLOPPY_DPRINTF("User defined disk (%d %d %d)\n",
-                           nb_heads - 1, max_track, last_sect);
         } else {
             FLOPPY_DPRINTF("Floppy disk (%d h %d t %d s) %s\n", nb_heads,
                            max_track, last_sect, ro ? "ro" : "rw");
commit b3ce604eeaa77970fa53838e7df2bc85344f2554
Author: Pavel Hrdina <phrdina at redhat.com>
Date:   Wed Jul 4 11:18:35 2012 +0200

    fdc_test: introduce test_sense_interrupt
    
    Calling sense interrupt status while there is no interrupt should
    return invalid command (0x80).
    
    Read command should always returns in st0 seek_end bit set to 1.
    
    Signed-off-by: Pavel Hrdina <phrdina at redhat.com>
    Signed-off-by: Kevin Wolf <kwolf at redhat.com>

diff --git a/tests/fdc-test.c b/tests/fdc-test.c
index 5f52f6c..585fb0e 100644
--- a/tests/fdc-test.c
+++ b/tests/fdc-test.c
@@ -142,7 +142,7 @@ static uint8_t send_read_command(void)
     }
 
     st0 = floppy_recv();
-    if (st0 != 0x40) {
+    if (st0 != 0x60) {
         ret = 1;
     }
 
@@ -259,6 +259,28 @@ static void test_media_change(void)
     assert_bit_set(dir, DSKCHG);
 }
 
+static void test_sense_interrupt(void)
+{
+    int drive = 0;
+    int head = 0;
+    int cyl = 0;
+    int ret = 0;
+
+    floppy_send(CMD_SENSE_INT);
+    ret = floppy_recv();
+    g_assert(ret == 0x80);
+
+    floppy_send(CMD_SEEK);
+    floppy_send(head << 2 | drive);
+    g_assert(!get_irq(FLOPPY_IRQ));
+    floppy_send(cyl);
+
+    floppy_send(CMD_SENSE_INT);
+    ret = floppy_recv();
+    g_assert(ret == 0x20);
+    floppy_recv();
+}
+
 /* success if no crash or abort */
 static void fuzz_registers(void)
 {
@@ -306,6 +328,7 @@ int main(int argc, char **argv)
     qtest_add_func("/fdc/no_media_on_start", test_no_media_on_start);
     qtest_add_func("/fdc/read_without_media", test_read_without_media);
     qtest_add_func("/fdc/media_change", test_media_change);
+    qtest_add_func("/fdc/sense_interrupt", test_sense_interrupt);
     qtest_add_func("/fdc/fuzz-registers", fuzz_registers);
 
     ret = g_test_run();
commit 59240c349c64448cc79cb6400aae2186e3f9243e
Author: Pavel Hrdina <phrdina at redhat.com>
Date:   Wed Jul 4 16:26:04 2012 +0200

    fdc_test: update media_change test
    
    After rewrite DSKCHG bit handling the test has to be updated. Now
    is needed to seek to different track to clear DSKCHG bit.
    
    Signed-off-by: Pavel Hrdina <phrdina at redhat.com>
    Signed-off-by: Kevin Wolf <kwolf at redhat.com>

diff --git a/tests/fdc-test.c b/tests/fdc-test.c
index 610e2f1..5f52f6c 100644
--- a/tests/fdc-test.c
+++ b/tests/fdc-test.c
@@ -156,19 +156,16 @@ static uint8_t send_read_command(void)
     return ret;
 }
 
-static void send_step_pulse(void)
+static void send_step_pulse(int cyl)
 {
     int drive = 0;
     int head = 0;
-    static int cyl = 0;
 
     floppy_send(CMD_SEEK);
     floppy_send(head << 2 | drive);
     g_assert(!get_irq(FLOPPY_IRQ));
     floppy_send(cyl);
     ack_irq();
-
-    cyl = (cyl + 1) % 4;
 }
 
 static uint8_t cmos_read(uint8_t reg)
@@ -195,8 +192,7 @@ static void test_no_media_on_start(void)
     assert_bit_set(dir, DSKCHG);
     dir = inb(FLOPPY_BASE + reg_dir);
     assert_bit_set(dir, DSKCHG);
-    send_step_pulse();
-    send_step_pulse();
+    send_step_pulse(1);
     dir = inb(FLOPPY_BASE + reg_dir);
     assert_bit_set(dir, DSKCHG);
     dir = inb(FLOPPY_BASE + reg_dir);
@@ -227,7 +223,14 @@ static void test_media_change(void)
     dir = inb(FLOPPY_BASE + reg_dir);
     assert_bit_set(dir, DSKCHG);
 
-    send_step_pulse();
+    send_step_pulse(0);
+    dir = inb(FLOPPY_BASE + reg_dir);
+    assert_bit_set(dir, DSKCHG);
+    dir = inb(FLOPPY_BASE + reg_dir);
+    assert_bit_set(dir, DSKCHG);
+
+    /* Step to next track should clear DSKCHG bit. */
+    send_step_pulse(1);
     dir = inb(FLOPPY_BASE + reg_dir);
     assert_bit_clear(dir, DSKCHG);
     dir = inb(FLOPPY_BASE + reg_dir);
@@ -243,7 +246,13 @@ static void test_media_change(void)
     dir = inb(FLOPPY_BASE + reg_dir);
     assert_bit_set(dir, DSKCHG);
 
-    send_step_pulse();
+    send_step_pulse(0);
+    dir = inb(FLOPPY_BASE + reg_dir);
+    assert_bit_set(dir, DSKCHG);
+    dir = inb(FLOPPY_BASE + reg_dir);
+    assert_bit_set(dir, DSKCHG);
+
+    send_step_pulse(1);
     dir = inb(FLOPPY_BASE + reg_dir);
     assert_bit_set(dir, DSKCHG);
     dir = inb(FLOPPY_BASE + reg_dir);
commit 2fee00885a9ea4db69bbfc1ba8ccf95f2ae9aec6
Author: Pavel Hrdina <phrdina at redhat.com>
Date:   Fri Jun 22 12:33:55 2012 +0200

    fdc: fix interrupt handling
    
    If you call the SENSE INTERRUPT STATUS command while there is no interrupt
    waiting you get as result unknown command.
    
    Fixed status0 register handling for read/write/format commands.
    
    Signed-off-by: Pavel Hrdina <phrdina at redhat.com>
    Signed-off-by: Kevin Wolf <kwolf at redhat.com>

diff --git a/hw/fdc.c b/hw/fdc.c
index 0270264..e28841c 100644
--- a/hw/fdc.c
+++ b/hw/fdc.c
@@ -307,6 +307,9 @@ enum {
 };
 
 enum {
+    FD_SR0_DS0      = 0x01,
+    FD_SR0_DS1      = 0x02,
+    FD_SR0_HEAD     = 0x04,
     FD_SR0_EQPMT    = 0x10,
     FD_SR0_SEEK     = 0x20,
     FD_SR0_ABNTERM  = 0x40,
@@ -972,14 +975,15 @@ static void fdctrl_reset_fifo(FDCtrl *fdctrl)
 }
 
 /* Set FIFO status for the host to read */
-static void fdctrl_set_fifo(FDCtrl *fdctrl, int fifo_len, int do_irq)
+static void fdctrl_set_fifo(FDCtrl *fdctrl, int fifo_len, uint8_t status0)
 {
     fdctrl->data_dir = FD_DIR_READ;
     fdctrl->data_len = fifo_len;
     fdctrl->data_pos = 0;
     fdctrl->msr |= FD_MSR_CMDBUSY | FD_MSR_RQM | FD_MSR_DIO;
-    if (do_irq)
-        fdctrl_raise_irq(fdctrl, 0x00);
+    if (status0) {
+        fdctrl_raise_irq(fdctrl, status0);
+    }
 }
 
 /* Set an error: unimplemented/unknown command */
@@ -1044,10 +1048,12 @@ static void fdctrl_stop_transfer(FDCtrl *fdctrl, uint8_t status0,
     FDrive *cur_drv;
 
     cur_drv = get_cur_drv(fdctrl);
+    fdctrl->status0 = status0 | FD_SR0_SEEK | (cur_drv->head << 2) |
+                      GET_CUR_DRV(fdctrl);
+
     FLOPPY_DPRINTF("transfer status: %02x %02x %02x (%02x)\n",
-                   status0, status1, status2,
-                   status0 | (cur_drv->head << 2) | GET_CUR_DRV(fdctrl));
-    fdctrl->fifo[0] = status0 | (cur_drv->head << 2) | GET_CUR_DRV(fdctrl);
+                   status0, status1, status2, fdctrl->status0);
+    fdctrl->fifo[0] = fdctrl->status0;
     fdctrl->fifo[1] = status1;
     fdctrl->fifo[2] = status2;
     fdctrl->fifo[3] = cur_drv->track;
@@ -1060,7 +1066,7 @@ static void fdctrl_stop_transfer(FDCtrl *fdctrl, uint8_t status0,
     }
     fdctrl->msr |= FD_MSR_RQM | FD_MSR_DIO;
     fdctrl->msr &= ~FD_MSR_NONDMA;
-    fdctrl_set_fifo(fdctrl, 7, 1);
+    fdctrl_set_fifo(fdctrl, 7, fdctrl->status0);
 }
 
 /* Prepare a data transfer (either DMA or FIFO) */
@@ -1175,7 +1181,7 @@ static void fdctrl_start_transfer(FDCtrl *fdctrl, int direction)
     if (direction != FD_DIR_WRITE)
         fdctrl->msr |= FD_MSR_DIO;
     /* IO based transfer: calculate len */
-    fdctrl_raise_irq(fdctrl, 0x00);
+    fdctrl_raise_irq(fdctrl, FD_SR0_SEEK);
 
     return;
 }
@@ -1604,16 +1610,18 @@ static void fdctrl_handle_sense_interrupt_status(FDCtrl *fdctrl, int direction)
 {
     FDrive *cur_drv = get_cur_drv(fdctrl);
 
-    if(fdctrl->reset_sensei > 0) {
+    if (fdctrl->reset_sensei > 0) {
         fdctrl->fifo[0] =
             FD_SR0_RDYCHG + FD_RESET_SENSEI_COUNT - fdctrl->reset_sensei;
         fdctrl->reset_sensei--;
+    } else if (!(fdctrl->sra & FD_SRA_INTPEND)) {
+        fdctrl->fifo[0] = FD_SR0_INVCMD;
+        fdctrl_set_fifo(fdctrl, 1, 0);
+        return;
     } else {
-        /* XXX: status0 handling is broken for read/write
-           commands, so we do this hack. It should be suppressed
-           ASAP */
         fdctrl->fifo[0] =
-            FD_SR0_SEEK | (cur_drv->head << 2) | GET_CUR_DRV(fdctrl);
+                (fdctrl->status0 & ~(FD_SR0_HEAD | FD_SR0_DS1 | FD_SR0_DS0))
+                | GET_CUR_DRV(fdctrl);
     }
 
     fdctrl->fifo[1] = cur_drv->track;
commit 6be01b1e0b14ad4809c9aec273c6109b91d2df1c
Author: Pavel Hrdina <phrdina at redhat.com>
Date:   Fri Jun 22 12:33:54 2012 +0200

    fdc: rewrite seek and DSKCHG bit handling
    
    This bit is cleared on every successful seek to a different track (cylinder).
    The seek is also called on revalidate or on read/write/format commands which
    also clear the DSKCHG bit.
    
    Signed-off-by: Pavel Hrdina <phrdina at redhat.com>
    Signed-off-by: Kevin Wolf <kwolf at redhat.com>

diff --git a/hw/fdc.c b/hw/fdc.c
index 5b3224b..0270264 100644
--- a/hw/fdc.c
+++ b/hw/fdc.c
@@ -153,8 +153,12 @@ static int fd_seek(FDrive *drv, uint8_t head, uint8_t track, uint8_t sect,
         }
 #endif
         drv->head = head;
-        if (drv->track != track)
+        if (drv->track != track) {
+            if (drv->bs != NULL && bdrv_is_inserted(drv->bs)) {
+                drv->media_changed = 0;
+            }
             ret = 1;
+        }
         drv->track = track;
         drv->sect = sect;
     }
@@ -170,9 +174,7 @@ static int fd_seek(FDrive *drv, uint8_t head, uint8_t track, uint8_t sect,
 static void fd_recalibrate(FDrive *drv)
 {
     FLOPPY_DPRINTF("recalibrate\n");
-    drv->head = 0;
-    drv->track = 0;
-    drv->sect = 1;
+    fd_seek(drv, 0, 0, 1, 1);
 }
 
 /* Revalidate a disk drive after a disk change */
@@ -711,14 +713,6 @@ static void fdctrl_raise_irq(FDCtrl *fdctrl, uint8_t status0)
         qemu_set_irq(fdctrl->irq, 1);
         fdctrl->sra |= FD_SRA_INTPEND;
     }
-    if (status0 & FD_SR0_SEEK) {
-        FDrive *cur_drv;
-        /* A seek clears the disk change line (if a disk is inserted) */
-        cur_drv = get_cur_drv(fdctrl);
-        if (cur_drv->bs != NULL && bdrv_is_inserted(cur_drv->bs)) {
-            cur_drv->media_changed = 0;
-        }
-    }
 
     fdctrl->reset_sensei = 0;
     fdctrl->status0 = status0;
@@ -997,7 +991,10 @@ static void fdctrl_unimplemented(FDCtrl *fdctrl, int direction)
     fdctrl_set_fifo(fdctrl, 1, 0);
 }
 
-/* Seek to next sector */
+/* Seek to next sector
+ * returns 0 when end of track reached (for DBL_SIDES on head 1)
+ * otherwise returns 1
+ */
 static int fdctrl_seek_to_next_sect(FDCtrl *fdctrl, FDrive *cur_drv)
 {
     FLOPPY_DPRINTF("seek to next sector (%d %02x %02x => %d)\n",
@@ -1005,30 +1002,39 @@ static int fdctrl_seek_to_next_sect(FDCtrl *fdctrl, FDrive *cur_drv)
                    fd_sector(cur_drv));
     /* XXX: cur_drv->sect >= cur_drv->last_sect should be an
        error in fact */
-    if (cur_drv->sect >= cur_drv->last_sect ||
-        cur_drv->sect == fdctrl->eot) {
-        cur_drv->sect = 1;
+    uint8_t new_head = cur_drv->head;
+    uint8_t new_track = cur_drv->track;
+    uint8_t new_sect = cur_drv->sect;
+
+    int ret = 1;
+
+    if (new_sect >= cur_drv->last_sect ||
+        new_sect == fdctrl->eot) {
+        new_sect = 1;
         if (FD_MULTI_TRACK(fdctrl->data_state)) {
-            if (cur_drv->head == 0 &&
+            if (new_head == 0 &&
                 (cur_drv->flags & FDISK_DBL_SIDES) != 0) {
-                cur_drv->head = 1;
+                new_head = 1;
             } else {
-                cur_drv->head = 0;
-                cur_drv->track++;
-                if ((cur_drv->flags & FDISK_DBL_SIDES) == 0)
-                    return 0;
+                new_head = 0;
+                new_track++;
+                if ((cur_drv->flags & FDISK_DBL_SIDES) == 0) {
+                    ret = 0;
+                }
             }
         } else {
-            cur_drv->track++;
-            return 0;
+            new_track++;
+            ret = 0;
+        }
+        if (ret == 1) {
+            FLOPPY_DPRINTF("seek to next track (%d %02x %02x => %d)\n",
+                    new_head, new_track, new_sect, fd_sector(cur_drv));
         }
-        FLOPPY_DPRINTF("seek to next track (%d %02x %02x => %d)\n",
-                       cur_drv->head, cur_drv->track,
-                       cur_drv->sect, fd_sector(cur_drv));
     } else {
-        cur_drv->sect++;
+        new_sect++;
     }
-    return 1;
+    fd_seek(cur_drv, new_head, new_track, new_sect, 1);
+    return ret;
 }
 
 /* Callback for transfer end (stop or abort) */
@@ -1626,11 +1632,7 @@ static void fdctrl_handle_seek(FDCtrl *fdctrl, int direction)
     /* The seek command just sends step pulses to the drive and doesn't care if
      * there is a medium inserted of if it's banging the head against the drive.
      */
-    if (fdctrl->fifo[2] > cur_drv->max_track) {
-        cur_drv->track = cur_drv->max_track;
-    } else {
-        cur_drv->track = fdctrl->fifo[2];
-    }
+    fd_seek(cur_drv, cur_drv->head, fdctrl->fifo[2], cur_drv->sect, 1);
     /* Raise Interrupt */
     fdctrl_raise_irq(fdctrl, FD_SR0_SEEK);
 }
@@ -1695,9 +1697,10 @@ static void fdctrl_handle_relative_seek_out(FDCtrl *fdctrl, int direction)
     SET_CUR_DRV(fdctrl, fdctrl->fifo[1] & FD_DOR_SELMASK);
     cur_drv = get_cur_drv(fdctrl);
     if (fdctrl->fifo[2] + cur_drv->track >= cur_drv->max_track) {
-        cur_drv->track = cur_drv->max_track - 1;
+        fd_seek(cur_drv, cur_drv->head, cur_drv->max_track - 1,
+                cur_drv->sect, 1);
     } else {
-        cur_drv->track += fdctrl->fifo[2];
+        fd_seek(cur_drv, cur_drv->head, fdctrl->fifo[2], cur_drv->sect, 1);
     }
     fdctrl_reset_fifo(fdctrl);
     /* Raise Interrupt */
@@ -1711,9 +1714,9 @@ static void fdctrl_handle_relative_seek_in(FDCtrl *fdctrl, int direction)
     SET_CUR_DRV(fdctrl, fdctrl->fifo[1] & FD_DOR_SELMASK);
     cur_drv = get_cur_drv(fdctrl);
     if (fdctrl->fifo[2] > cur_drv->track) {
-        cur_drv->track = 0;
+        fd_seek(cur_drv, cur_drv->head, 0, cur_drv->sect, 1);
     } else {
-        cur_drv->track -= fdctrl->fifo[2];
+        fd_seek(cur_drv, cur_drv->head, fdctrl->fifo[2], cur_drv->sect, 1);
     }
     fdctrl_reset_fifo(fdctrl);
     /* Raise Interrupt */
commit 4ddc07cac2bd794e4ff17717551e66589e71e714
Author: Paolo Bonzini <pbonzini at redhat.com>
Date:   Thu Jun 14 16:55:02 2012 +0200

    block: introduce bdrv_swap, implement bdrv_append on top of it
    
    The new function can be made a bit nicer than bdrv_append.  It swaps the
    whole contents, and then swaps back (using the usual t=a;a=b;b=t idiom)
    the fields that need to stay on top.  Thus, it does not need explicit
    bdrv_detach_dev, bdrv_iostatus_disable, etc.
    
    Signed-off-by: Paolo Bonzini <pbonzini at redhat.com>
    Signed-off-by: Kevin Wolf <kwolf at redhat.com>

diff --git a/block.c b/block.c
index 702821d..29857db 100644
--- a/block.c
+++ b/block.c
@@ -971,116 +971,130 @@ static void bdrv_rebind(BlockDriverState *bs)
     }
 }
 
-/*
- * Add new bs contents at the top of an image chain while the chain is
- * live, while keeping required fields on the top layer.
- *
- * This will modify the BlockDriverState fields, and swap contents
- * between bs_new and bs_top. Both bs_new and bs_top are modified.
- *
- * bs_new is required to be anonymous.
- *
- * This function does not create any image files.
- */
-void bdrv_append(BlockDriverState *bs_new, BlockDriverState *bs_top)
+static void bdrv_move_feature_fields(BlockDriverState *bs_dest,
+                                     BlockDriverState *bs_src)
 {
-    BlockDriverState tmp;
-
-    /* bs_new must be anonymous */
-    assert(bs_new->device_name[0] == '\0');
-
-    tmp = *bs_new;
-
-    /* there are some fields that need to stay on the top layer: */
-    tmp.open_flags        = bs_top->open_flags;
+    /* move some fields that need to stay attached to the device */
+    bs_dest->open_flags         = bs_src->open_flags;
 
     /* dev info */
-    tmp.dev_ops           = bs_top->dev_ops;
-    tmp.dev_opaque        = bs_top->dev_opaque;
-    tmp.dev               = bs_top->dev;
-    tmp.buffer_alignment  = bs_top->buffer_alignment;
-    tmp.copy_on_read      = bs_top->copy_on_read;
+    bs_dest->dev_ops            = bs_src->dev_ops;
+    bs_dest->dev_opaque         = bs_src->dev_opaque;
+    bs_dest->dev                = bs_src->dev;
+    bs_dest->buffer_alignment   = bs_src->buffer_alignment;
+    bs_dest->copy_on_read       = bs_src->copy_on_read;
 
-    tmp.enable_write_cache = bs_top->enable_write_cache;
+    bs_dest->enable_write_cache = bs_src->enable_write_cache;
 
     /* i/o timing parameters */
-    tmp.slice_time        = bs_top->slice_time;
-    tmp.slice_start       = bs_top->slice_start;
-    tmp.slice_end         = bs_top->slice_end;
-    tmp.io_limits         = bs_top->io_limits;
-    tmp.io_base           = bs_top->io_base;
-    tmp.throttled_reqs    = bs_top->throttled_reqs;
-    tmp.block_timer       = bs_top->block_timer;
-    tmp.io_limits_enabled = bs_top->io_limits_enabled;
+    bs_dest->slice_time         = bs_src->slice_time;
+    bs_dest->slice_start        = bs_src->slice_start;
+    bs_dest->slice_end          = bs_src->slice_end;
+    bs_dest->io_limits          = bs_src->io_limits;
+    bs_dest->io_base            = bs_src->io_base;
+    bs_dest->throttled_reqs     = bs_src->throttled_reqs;
+    bs_dest->block_timer        = bs_src->block_timer;
+    bs_dest->io_limits_enabled  = bs_src->io_limits_enabled;
 
     /* geometry */
-    tmp.cyls              = bs_top->cyls;
-    tmp.heads             = bs_top->heads;
-    tmp.secs              = bs_top->secs;
-    tmp.translation       = bs_top->translation;
+    bs_dest->cyls               = bs_src->cyls;
+    bs_dest->heads              = bs_src->heads;
+    bs_dest->secs               = bs_src->secs;
+    bs_dest->translation        = bs_src->translation;
 
     /* r/w error */
-    tmp.on_read_error     = bs_top->on_read_error;
-    tmp.on_write_error    = bs_top->on_write_error;
+    bs_dest->on_read_error      = bs_src->on_read_error;
+    bs_dest->on_write_error     = bs_src->on_write_error;
 
     /* i/o status */
-    tmp.iostatus_enabled  = bs_top->iostatus_enabled;
-    tmp.iostatus          = bs_top->iostatus;
+    bs_dest->iostatus_enabled   = bs_src->iostatus_enabled;
+    bs_dest->iostatus           = bs_src->iostatus;
 
     /* dirty bitmap */
-    tmp.dirty_count       = bs_top->dirty_count;
-    tmp.dirty_bitmap      = bs_top->dirty_bitmap;
-    assert(bs_new->dirty_bitmap == NULL);
+    bs_dest->dirty_count        = bs_src->dirty_count;
+    bs_dest->dirty_bitmap       = bs_src->dirty_bitmap;
 
     /* job */
-    tmp.in_use            = bs_top->in_use;
-    tmp.job               = bs_top->job;
-    assert(bs_new->job == NULL);
+    bs_dest->in_use             = bs_src->in_use;
+    bs_dest->job                = bs_src->job;
 
     /* keep the same entry in bdrv_states */
-    pstrcpy(tmp.device_name, sizeof(tmp.device_name), bs_top->device_name);
-    tmp.list = bs_top->list;
+    pstrcpy(bs_dest->device_name, sizeof(bs_dest->device_name),
+            bs_src->device_name);
+    bs_dest->list = bs_src->list;
+}
 
-    /* The contents of 'tmp' will become bs_top, as we are
-     * swapping bs_new and bs_top contents. */
-    tmp.backing_hd = bs_new;
-    pstrcpy(tmp.backing_file, sizeof(tmp.backing_file), bs_top->filename);
-    pstrcpy(tmp.backing_format, sizeof(tmp.backing_format),
-            bs_top->drv ? bs_top->drv->format_name : "");
-
-    /* swap contents of the fixed new bs and the current top */
-    *bs_new = *bs_top;
-    *bs_top = tmp;
-
-    /* device_name[] was carried over from the old bs_top.  bs_new
-     * shouldn't be in bdrv_states, so we need to make device_name[]
-     * reflect the anonymity of bs_new
-     */
-    bs_new->device_name[0] = '\0';
+/*
+ * Swap bs contents for two image chains while they are live,
+ * while keeping required fields on the BlockDriverState that is
+ * actually attached to a device.
+ *
+ * This will modify the BlockDriverState fields, and swap contents
+ * between bs_new and bs_old. Both bs_new and bs_old are modified.
+ *
+ * bs_new is required to be anonymous.
+ *
+ * This function does not create any image files.
+ */
+void bdrv_swap(BlockDriverState *bs_new, BlockDriverState *bs_old)
+{
+    BlockDriverState tmp;
 
-    /* clear the copied fields in the new backing file */
-    bdrv_detach_dev(bs_new, bs_new->dev);
+    /* bs_new must be anonymous and shouldn't have anything fancy enabled */
+    assert(bs_new->device_name[0] == '\0');
+    assert(bs_new->dirty_bitmap == NULL);
+    assert(bs_new->job == NULL);
+    assert(bs_new->dev == NULL);
+    assert(bs_new->in_use == 0);
+    assert(bs_new->io_limits_enabled == false);
+    assert(bs_new->block_timer == NULL);
 
-    bs_new->job                = NULL;
-    bs_new->in_use             = 0;
-    bs_new->dirty_bitmap       = NULL;
-    bs_new->dirty_count        = 0;
+    tmp = *bs_new;
+    *bs_new = *bs_old;
+    *bs_old = tmp;
 
-    qemu_co_queue_init(&bs_new->throttled_reqs);
-    memset(&bs_new->io_base,   0, sizeof(bs_new->io_base));
-    memset(&bs_new->io_limits, 0, sizeof(bs_new->io_limits));
-    bdrv_iostatus_disable(bs_new);
+    /* there are some fields that should not be swapped, move them back */
+    bdrv_move_feature_fields(&tmp, bs_old);
+    bdrv_move_feature_fields(bs_old, bs_new);
+    bdrv_move_feature_fields(bs_new, &tmp);
 
-    /* we don't use bdrv_io_limits_disable() for this, because we don't want
-     * to affect or delete the block_timer, as it has been moved to bs_top */
-    bs_new->io_limits_enabled = false;
-    bs_new->block_timer       = NULL;
-    bs_new->slice_time        = 0;
-    bs_new->slice_start       = 0;
-    bs_new->slice_end         = 0;
+    /* bs_new shouldn't be in bdrv_states even after the swap!  */
+    assert(bs_new->device_name[0] == '\0');
+
+    /* Check a few fields that should remain attached to the device */
+    assert(bs_new->dev == NULL);
+    assert(bs_new->job == NULL);
+    assert(bs_new->in_use == 0);
+    assert(bs_new->io_limits_enabled == false);
+    assert(bs_new->block_timer == NULL);
 
     bdrv_rebind(bs_new);
-    bdrv_rebind(bs_top);
+    bdrv_rebind(bs_old);
+}
+
+/*
+ * Add new bs contents at the top of an image chain while the chain is
+ * live, while keeping required fields on the top layer.
+ *
+ * This will modify the BlockDriverState fields, and swap contents
+ * between bs_new and bs_top. Both bs_new and bs_top are modified.
+ *
+ * bs_new is required to be anonymous.
+ *
+ * This function does not create any image files.
+ */
+void bdrv_append(BlockDriverState *bs_new, BlockDriverState *bs_top)
+{
+    bdrv_swap(bs_new, bs_top);
+
+    /* The contents of 'tmp' will become bs_top, as we are
+     * swapping bs_new and bs_top contents. */
+    bs_top->backing_hd = bs_new;
+    bs_top->open_flags &= ~BDRV_O_NO_BACKING;
+    pstrcpy(bs_top->backing_file, sizeof(bs_top->backing_file),
+            bs_new->filename);
+    pstrcpy(bs_top->backing_format, sizeof(bs_top->backing_format),
+            bs_new->drv ? bs_new->drv->format_name : "");
 }
 
 void bdrv_delete(BlockDriverState *bs)
diff --git a/block.h b/block.h
index 42e30d6..3af93c6 100644
--- a/block.h
+++ b/block.h
@@ -122,6 +122,7 @@ int bdrv_create(BlockDriver *drv, const char* filename,
 int bdrv_create_file(const char* filename, QEMUOptionParameter *options);
 BlockDriverState *bdrv_new(const char *device_name);
 void bdrv_make_anon(BlockDriverState *bs);
+void bdrv_swap(BlockDriverState *bs_new, BlockDriverState *bs_old);
 void bdrv_append(BlockDriverState *bs_new, BlockDriverState *bs_top);
 void bdrv_delete(BlockDriverState *bs);
 int bdrv_parse_cache_flags(const char *mode, int *flags);
commit a9fc4408e3511a073583a18b98a26765ff1e21d7
Author: Paolo Bonzini <pbonzini at redhat.com>
Date:   Thu Jun 14 16:55:01 2012 +0200

    block: copy over job and dirty bitmap fields in bdrv_append
    
    While these should not be in use at the time a transaction is started,
    a command in the prepare phase of a transaction might have added them,
    so they need to be brought over.
    
    Signed-off-by: Paolo Bonzini <pbonzini at redhat.com>
    Signed-off-by: Kevin Wolf <kwolf at redhat.com>

diff --git a/block.c b/block.c
index 0acdcac..702821d 100644
--- a/block.c
+++ b/block.c
@@ -1027,6 +1027,16 @@ void bdrv_append(BlockDriverState *bs_new, BlockDriverState *bs_top)
     tmp.iostatus_enabled  = bs_top->iostatus_enabled;
     tmp.iostatus          = bs_top->iostatus;
 
+    /* dirty bitmap */
+    tmp.dirty_count       = bs_top->dirty_count;
+    tmp.dirty_bitmap      = bs_top->dirty_bitmap;
+    assert(bs_new->dirty_bitmap == NULL);
+
+    /* job */
+    tmp.in_use            = bs_top->in_use;
+    tmp.job               = bs_top->job;
+    assert(bs_new->job == NULL);
+
     /* keep the same entry in bdrv_states */
     pstrcpy(tmp.device_name, sizeof(tmp.device_name), bs_top->device_name);
     tmp.list = bs_top->list;
@@ -1051,6 +1061,11 @@ void bdrv_append(BlockDriverState *bs_new, BlockDriverState *bs_top)
     /* clear the copied fields in the new backing file */
     bdrv_detach_dev(bs_new, bs_new->dev);
 
+    bs_new->job                = NULL;
+    bs_new->in_use             = 0;
+    bs_new->dirty_bitmap       = NULL;
+    bs_new->dirty_count        = 0;
+
     qemu_co_queue_init(&bs_new->throttled_reqs);
     memset(&bs_new->io_base,   0, sizeof(bs_new->io_base));
     memset(&bs_new->io_limits, 0, sizeof(bs_new->io_limits));
commit 5c171afa4cff41101ac3e5b0cd703fd211aaa253
Author: Paolo Bonzini <pbonzini at redhat.com>
Date:   Wed Jun 6 08:10:44 2012 +0200

    raw: hook into blkdebug
    
    Signed-off-by: Paolo Bonzini <pbonzini at redhat.com>
    Signed-off-by: Kevin Wolf <kwolf at redhat.com>

diff --git a/block/raw.c b/block/raw.c
index 09d9b48..ff34ea4 100644
--- a/block/raw.c
+++ b/block/raw.c
@@ -12,12 +12,14 @@ static int raw_open(BlockDriverState *bs, int flags)
 static int coroutine_fn raw_co_readv(BlockDriverState *bs, int64_t sector_num,
                                      int nb_sectors, QEMUIOVector *qiov)
 {
+    BLKDBG_EVENT(bs->file, BLKDBG_READ_AIO);
     return bdrv_co_readv(bs->file, sector_num, nb_sectors, qiov);
 }
 
 static int coroutine_fn raw_co_writev(BlockDriverState *bs, int64_t sector_num,
                                       int nb_sectors, QEMUIOVector *qiov)
 {
+    BLKDBG_EVENT(bs->file, BLKDBG_WRITE_AIO);
     return bdrv_co_writev(bs->file, sector_num, nb_sectors, qiov);
 }
 
commit e4780db4293ed4380ce93ad77881b46f5ae59786
Author: Paolo Bonzini <pbonzini at redhat.com>
Date:   Wed Jun 6 08:10:43 2012 +0200

    blkdebug: optionally tie errors to a specific sector
    
    This makes blkdebug scripts more powerful, and independent of the
    exact sequence of operations performed by streaming.
    
    Signed-off-by: Paolo Bonzini <pbonzini at redhat.com>
    Signed-off-by: Kevin Wolf <kwolf at redhat.com>

diff --git a/block/blkdebug.c b/block/blkdebug.c
index d12ebbf..59dcea0 100644
--- a/block/blkdebug.c
+++ b/block/blkdebug.c
@@ -59,6 +59,7 @@ typedef struct BlkdebugRule {
             int error;
             int immediately;
             int once;
+            int64_t sector;
         } inject;
         struct {
             int new_state;
@@ -85,6 +86,10 @@ static QemuOptsList inject_error_opts = {
             .type = QEMU_OPT_NUMBER,
         },
         {
+            .name = "sector",
+            .type = QEMU_OPT_NUMBER,
+        },
+        {
             .name = "once",
             .type = QEMU_OPT_BOOL,
         },
@@ -213,6 +218,7 @@ static int add_rule(QemuOpts *opts, void *opaque)
         rule->options.inject.once  = qemu_opt_get_bool(opts, "once", 0);
         rule->options.inject.immediately =
             qemu_opt_get_bool(opts, "immediately", 0);
+        rule->options.inject.sector = qemu_opt_get_number(opts, "sector", -1);
         break;
 
     case ACTION_SET_STATE:
@@ -343,7 +349,15 @@ static BlockDriverAIOCB *blkdebug_aio_readv(BlockDriverState *bs,
     BlockDriverCompletionFunc *cb, void *opaque)
 {
     BDRVBlkdebugState *s = bs->opaque;
-    BlkdebugRule *rule = QSIMPLEQ_FIRST(&s->active_rules);
+    BlkdebugRule *rule = NULL;
+
+    QSIMPLEQ_FOREACH(rule, &s->active_rules, active_next) {
+        if (rule->options.inject.sector == -1 ||
+            (rule->options.inject.sector >= sector_num &&
+             rule->options.inject.sector < sector_num + nb_sectors)) {
+            break;
+        }
+    }
 
     if (rule && rule->options.inject.error) {
         return inject_error(bs, cb, opaque, rule);
@@ -357,7 +371,15 @@ static BlockDriverAIOCB *blkdebug_aio_writev(BlockDriverState *bs,
     BlockDriverCompletionFunc *cb, void *opaque)
 {
     BDRVBlkdebugState *s = bs->opaque;
-    BlkdebugRule *rule = QSIMPLEQ_FIRST(&s->active_rules);
+    BlkdebugRule *rule = NULL;
+
+    QSIMPLEQ_FOREACH(rule, &s->active_rules, active_next) {
+        if (rule->options.inject.sector == -1 ||
+            (rule->options.inject.sector >= sector_num &&
+             rule->options.inject.sector < sector_num + nb_sectors)) {
+            break;
+        }
+    }
 
     if (rule && rule->options.inject.error) {
         return inject_error(bs, cb, opaque, rule);
commit 571cd43e57beb1f8fd42c60bd3c69777f8ecdc51
Author: Paolo Bonzini <pbonzini at redhat.com>
Date:   Wed Jun 6 08:10:42 2012 +0200

    blkdebug: store list of active rules
    
    This prepares for the next patch, where some active rules may actually
    not trigger depending on input to readv/writev.  Store the active rules
    in a SIMPLEQ (so that it can be emptied easily with QSIMPLEQ_INIT), and
    fetch the errno/once/immediately arguments from there.
    
    Signed-off-by: Paolo Bonzini <pbonzini at redhat.com>
    Signed-off-by: Kevin Wolf <kwolf at redhat.com>

diff --git a/block/blkdebug.c b/block/blkdebug.c
index b084a23..d12ebbf 100644
--- a/block/blkdebug.c
+++ b/block/blkdebug.c
@@ -26,24 +26,10 @@
 #include "block_int.h"
 #include "module.h"
 
-typedef struct BlkdebugVars {
-    int state;
-
-    /* If inject_errno != 0, an error is injected for requests */
-    int inject_errno;
-
-    /* Decides if all future requests fail (false) or only the next one and
-     * after the next request inject_errno is reset to 0 (true) */
-    bool inject_once;
-
-    /* Decides if aio_readv/writev fails right away (true) or returns an error
-     * return value only in the callback (false) */
-    bool inject_immediately;
-} BlkdebugVars;
-
 typedef struct BDRVBlkdebugState {
-    BlkdebugVars vars;
-    QLIST_HEAD(list, BlkdebugRule) rules[BLKDBG_EVENT_MAX];
+    int state;
+    QLIST_HEAD(, BlkdebugRule) rules[BLKDBG_EVENT_MAX];
+    QSIMPLEQ_HEAD(, BlkdebugRule) active_rules;
 } BDRVBlkdebugState;
 
 typedef struct BlkdebugAIOCB {
@@ -79,6 +65,7 @@ typedef struct BlkdebugRule {
         } set_state;
     } options;
     QLIST_ENTRY(BlkdebugRule) next;
+    QSIMPLEQ_ENTRY(BlkdebugRule) active_next;
 } BlkdebugRule;
 
 static QemuOptsList inject_error_opts = {
@@ -300,7 +287,7 @@ static int blkdebug_open(BlockDriverState *bs, const char *filename, int flags)
     filename = c + 1;
 
     /* Set initial state */
-    s->vars.state = 1;
+    s->state = 1;
 
     /* Open the backing file */
     ret = bdrv_file_open(&bs->file, filename, flags);
@@ -326,18 +313,18 @@ static void blkdebug_aio_cancel(BlockDriverAIOCB *blockacb)
 }
 
 static BlockDriverAIOCB *inject_error(BlockDriverState *bs,
-    BlockDriverCompletionFunc *cb, void *opaque)
+    BlockDriverCompletionFunc *cb, void *opaque, BlkdebugRule *rule)
 {
     BDRVBlkdebugState *s = bs->opaque;
-    int error = s->vars.inject_errno;
+    int error = rule->options.inject.error;
     struct BlkdebugAIOCB *acb;
     QEMUBH *bh;
 
-    if (s->vars.inject_once) {
-        s->vars.inject_errno = 0;
+    if (rule->options.inject.once) {
+        QSIMPLEQ_INIT(&s->active_rules);
     }
 
-    if (s->vars.inject_immediately) {
+    if (rule->options.inject.immediately) {
         return NULL;
     }
 
@@ -356,9 +343,10 @@ static BlockDriverAIOCB *blkdebug_aio_readv(BlockDriverState *bs,
     BlockDriverCompletionFunc *cb, void *opaque)
 {
     BDRVBlkdebugState *s = bs->opaque;
+    BlkdebugRule *rule = QSIMPLEQ_FIRST(&s->active_rules);
 
-    if (s->vars.inject_errno) {
-        return inject_error(bs, cb, opaque);
+    if (rule && rule->options.inject.error) {
+        return inject_error(bs, cb, opaque, rule);
     }
 
     return bdrv_aio_readv(bs->file, sector_num, qiov, nb_sectors, cb, opaque);
@@ -369,9 +357,10 @@ static BlockDriverAIOCB *blkdebug_aio_writev(BlockDriverState *bs,
     BlockDriverCompletionFunc *cb, void *opaque)
 {
     BDRVBlkdebugState *s = bs->opaque;
+    BlkdebugRule *rule = QSIMPLEQ_FIRST(&s->active_rules);
 
-    if (s->vars.inject_errno) {
-        return inject_error(bs, cb, opaque);
+    if (rule && rule->options.inject.error) {
+        return inject_error(bs, cb, opaque, rule);
     }
 
     return bdrv_aio_writev(bs->file, sector_num, qiov, nb_sectors, cb, opaque);
@@ -391,41 +380,45 @@ static void blkdebug_close(BlockDriverState *bs)
     }
 }
 
-static void process_rule(BlockDriverState *bs, struct BlkdebugRule *rule,
-    BlkdebugVars *old_vars)
+static bool process_rule(BlockDriverState *bs, struct BlkdebugRule *rule,
+    int old_state, bool injected)
 {
     BDRVBlkdebugState *s = bs->opaque;
-    BlkdebugVars *vars = &s->vars;
 
     /* Only process rules for the current state */
-    if (rule->state && rule->state != old_vars->state) {
-        return;
+    if (rule->state && rule->state != old_state) {
+        return injected;
     }
 
     /* Take the action */
     switch (rule->action) {
     case ACTION_INJECT_ERROR:
-        vars->inject_errno       = rule->options.inject.error;
-        vars->inject_once        = rule->options.inject.once;
-        vars->inject_immediately = rule->options.inject.immediately;
+        if (!injected) {
+            QSIMPLEQ_INIT(&s->active_rules);
+            injected = true;
+        }
+        QSIMPLEQ_INSERT_HEAD(&s->active_rules, rule, active_next);
         break;
 
     case ACTION_SET_STATE:
-        vars->state              = rule->options.set_state.new_state;
+        s->state = rule->options.set_state.new_state;
         break;
     }
+    return injected;
 }
 
 static void blkdebug_debug_event(BlockDriverState *bs, BlkDebugEvent event)
 {
     BDRVBlkdebugState *s = bs->opaque;
     struct BlkdebugRule *rule;
-    BlkdebugVars old_vars = s->vars;
+    int old_state = s->state;
+    bool injected;
 
     assert((int)event >= 0 && event < BLKDBG_EVENT_MAX);
 
+    injected = false;
     QLIST_FOREACH(rule, &s->rules[event], next) {
-        process_rule(bs, rule, &old_vars);
+        injected = process_rule(bs, rule, old_state, injected);
     }
 }
 
commit e130225587cb0d48b2c0b7c04b6bf9c95fe75ac9
Author: Paolo Bonzini <pbonzini at redhat.com>
Date:   Wed Jun 6 08:10:41 2012 +0200

    blkdebug: pass getlength to underlying file
    
    This is required when using blkdebug with raw format.  Unlike qcow2/QED,
    raw asks blkdebug for the length of the file, it doesn't get it from
    a header.
    
    Signed-off-by: Paolo Bonzini <pbonzini at redhat.com>
    Signed-off-by: Kevin Wolf <kwolf at redhat.com>

diff --git a/block/blkdebug.c b/block/blkdebug.c
index 1f79ef2..b084a23 100644
--- a/block/blkdebug.c
+++ b/block/blkdebug.c
@@ -429,6 +429,11 @@ static void blkdebug_debug_event(BlockDriverState *bs, BlkDebugEvent event)
     }
 }
 
+static int64_t blkdebug_getlength(BlockDriverState *bs)
+{
+    return bdrv_getlength(bs->file);
+}
+
 static BlockDriver bdrv_blkdebug = {
     .format_name        = "blkdebug",
     .protocol_name      = "blkdebug",
@@ -437,6 +442,7 @@ static BlockDriver bdrv_blkdebug = {
 
     .bdrv_file_open     = blkdebug_open,
     .bdrv_close         = blkdebug_close,
+    .bdrv_getlength     = blkdebug_getlength,
 
     .bdrv_aio_readv     = blkdebug_aio_readv,
     .bdrv_aio_writev    = blkdebug_aio_writev,
commit 368e8dd10a24a529612f37ba7370262f5ea5a814
Author: Paolo Bonzini <pbonzini at redhat.com>
Date:   Wed Jun 6 08:10:40 2012 +0200

    blkdebug: tiny cleanup
    
    Signed-off-by: Paolo Bonzini <pbonzini at redhat.com>
    Signed-off-by: Kevin Wolf <kwolf at redhat.com>

diff --git a/block/blkdebug.c b/block/blkdebug.c
index 1eff940..1f79ef2 100644
--- a/block/blkdebug.c
+++ b/block/blkdebug.c
@@ -361,9 +361,7 @@ static BlockDriverAIOCB *blkdebug_aio_readv(BlockDriverState *bs,
         return inject_error(bs, cb, opaque);
     }
 
-    BlockDriverAIOCB *acb =
-        bdrv_aio_readv(bs->file, sector_num, qiov, nb_sectors, cb, opaque);
-    return acb;
+    return bdrv_aio_readv(bs->file, sector_num, qiov, nb_sectors, cb, opaque);
 }
 
 static BlockDriverAIOCB *blkdebug_aio_writev(BlockDriverState *bs,
@@ -376,9 +374,7 @@ static BlockDriverAIOCB *blkdebug_aio_writev(BlockDriverState *bs,
         return inject_error(bs, cb, opaque);
     }
 
-    BlockDriverAIOCB *acb =
-        bdrv_aio_writev(bs->file, sector_num, qiov, nb_sectors, cb, opaque);
-    return acb;
+    return bdrv_aio_writev(bs->file, sector_num, qiov, nb_sectors, cb, opaque);
 }
 
 static void blkdebug_close(BlockDriverState *bs)
commit 820100fd15b66880df75415c6086a7ffeee7bf14
Author: Paolo Bonzini <pbonzini at redhat.com>
Date:   Wed Jun 6 08:10:39 2012 +0200

    blkdebug: remove sync i/o events
    
    These are unused, except (by mistake more or less) in QED.
    
    Signed-off-by: Paolo Bonzini <pbonzini at redhat.com>
    Signed-off-by: Kevin Wolf <kwolf at redhat.com>

diff --git a/block.h b/block.h
index d135652..42e30d6 100644
--- a/block.h
+++ b/block.h
@@ -395,9 +395,7 @@ typedef enum {
     BLKDBG_L2_ALLOC_COW_READ,
     BLKDBG_L2_ALLOC_WRITE,
 
-    BLKDBG_READ,
     BLKDBG_READ_AIO,
-    BLKDBG_READ_BACKING,
     BLKDBG_READ_BACKING_AIO,
     BLKDBG_READ_COMPRESSED,
 
diff --git a/block/blkdebug.c b/block/blkdebug.c
index e56e37d..1eff940 100644
--- a/block/blkdebug.c
+++ b/block/blkdebug.c
@@ -147,9 +147,7 @@ static const char *event_names[BLKDBG_EVENT_MAX] = {
     [BLKDBG_L2_ALLOC_COW_READ]              = "l2_alloc.cow_read",
     [BLKDBG_L2_ALLOC_WRITE]                 = "l2_alloc.write",
 
-    [BLKDBG_READ]                           = "read",
     [BLKDBG_READ_AIO]                       = "read_aio",
-    [BLKDBG_READ_BACKING]                   = "read_backing",
     [BLKDBG_READ_BACKING_AIO]               = "read_backing_aio",
     [BLKDBG_READ_COMPRESSED]                = "read_compressed",
 
diff --git a/block/qed.c b/block/qed.c
index ab59724..dd2832a 100644
--- a/block/qed.c
+++ b/block/qed.c
@@ -748,7 +748,7 @@ static void qed_read_backing_file(BDRVQEDState *s, uint64_t pos,
     /* If the read straddles the end of the backing file, shorten it */
     size = MIN((uint64_t)backing_length - pos, qiov->size);
 
-    BLKDBG_EVENT(s->bs->file, BLKDBG_READ_BACKING);
+    BLKDBG_EVENT(s->bs->file, BLKDBG_READ_BACKING_AIO);
     bdrv_aio_readv(s->bs->backing_hd, pos / BDRV_SECTOR_SIZE,
                    qiov, size / BDRV_SECTOR_SIZE, cb, opaque);
 }
commit 7dc1cde05bd8c63789edc03fedb71d2d68da1d4f
Author: MORITA Kazutaka <morita.kazutaka at lab.ntt.co.jp>
Date:   Wed Jun 27 07:26:23 2012 +0900

    sheepdog: traverse pending_list from the first for each time
    
    The pending list can be modified in other coroutine context
    sd_co_rw_vector, so we need to traverse the list from the first again
    after we send the pending request.
    
    Signed-off-by: MORITA Kazutaka <morita.kazutaka at lab.ntt.co.jp>
    Signed-off-by: Kevin Wolf <kwolf at redhat.com>

diff --git a/block/sheepdog.c b/block/sheepdog.c
index f6cd517..6e73efb 100644
--- a/block/sheepdog.c
+++ b/block/sheepdog.c
@@ -634,21 +634,31 @@ static int coroutine_fn add_aio_request(BDRVSheepdogState *s, AIOReq *aio_req,
                            struct iovec *iov, int niov, int create,
                            enum AIOCBState aiocb_type);
 
+
+static AIOReq *find_pending_req(BDRVSheepdogState *s, uint64_t oid)
+{
+    AIOReq *aio_req;
+
+    QLIST_FOREACH(aio_req, &s->pending_aio_head, aio_siblings) {
+        if (aio_req->oid == oid) {
+            return aio_req;
+        }
+    }
+
+    return NULL;
+}
+
 /*
  * This function searchs pending requests to the object `oid', and
  * sends them.
  */
 static void coroutine_fn send_pending_req(BDRVSheepdogState *s, uint64_t oid)
 {
-    AIOReq *aio_req, *next;
+    AIOReq *aio_req;
     SheepdogAIOCB *acb;
     int ret;
 
-    QLIST_FOREACH_SAFE(aio_req, &s->pending_aio_head, aio_siblings, next) {
-        if (aio_req->oid != oid) {
-            continue;
-        }
-
+    while ((aio_req = find_pending_req(s, oid)) != NULL) {
         acb = aio_req->aiocb;
         /* move aio_req from pending list to inflight one */
         QLIST_REMOVE(aio_req, aio_siblings);
commit c292ee6a67924061345975c02cd25b18f7054c4d
Author: MORITA Kazutaka <morita.kazutaka at lab.ntt.co.jp>
Date:   Wed Jun 27 07:26:22 2012 +0900

    sheepdog: split outstanding list into inflight and pending
    
    outstanding_list_head is used for both pending and inflight requests.
    This patch splits it and improves readability.
    
    Signed-off-by: MORITA Kazutaka <morita.kazutaka at lab.ntt.co.jp>
    Signed-off-by: Kevin Wolf <kwolf at redhat.com>

diff --git a/block/sheepdog.c b/block/sheepdog.c
index d4e5e3a..f6cd517 100644
--- a/block/sheepdog.c
+++ b/block/sheepdog.c
@@ -259,7 +259,7 @@ typedef struct AIOReq {
     uint8_t flags;
     uint32_t id;
 
-    QLIST_ENTRY(AIOReq) outstanding_aio_siblings;
+    QLIST_ENTRY(AIOReq) aio_siblings;
 } AIOReq;
 
 enum AIOCBState {
@@ -305,7 +305,8 @@ typedef struct BDRVSheepdogState {
     Coroutine *co_recv;
 
     uint32_t aioreq_seq_num;
-    QLIST_HEAD(outstanding_aio_head, AIOReq) outstanding_aio_head;
+    QLIST_HEAD(inflight_aio_head, AIOReq) inflight_aio_head;
+    QLIST_HEAD(pending_aio_head, AIOReq) pending_aio_head;
 } BDRVSheepdogState;
 
 static const char * sd_strerror(int err)
@@ -356,7 +357,7 @@ static const char * sd_strerror(int err)
  * Sheepdog I/O handling:
  *
  * 1. In sd_co_rw_vector, we send the I/O requests to the server and
- *    link the requests to the outstanding_list in the
+ *    link the requests to the inflight_list in the
  *    BDRVSheepdogState.  The function exits without waiting for
  *    receiving the response.
  *
@@ -384,9 +385,6 @@ static inline AIOReq *alloc_aio_req(BDRVSheepdogState *s, SheepdogAIOCB *acb,
     aio_req->flags = flags;
     aio_req->id = s->aioreq_seq_num++;
 
-    QLIST_INSERT_HEAD(&s->outstanding_aio_head, aio_req,
-                      outstanding_aio_siblings);
-
     acb->nr_pending++;
     return aio_req;
 }
@@ -395,7 +393,7 @@ static inline void free_aio_req(BDRVSheepdogState *s, AIOReq *aio_req)
 {
     SheepdogAIOCB *acb = aio_req->aiocb;
 
-    QLIST_REMOVE(aio_req, outstanding_aio_siblings);
+    QLIST_REMOVE(aio_req, aio_siblings);
     g_free(aio_req);
 
     acb->nr_pending--;
@@ -640,22 +638,21 @@ static int coroutine_fn add_aio_request(BDRVSheepdogState *s, AIOReq *aio_req,
  * This function searchs pending requests to the object `oid', and
  * sends them.
  */
-static void coroutine_fn send_pending_req(BDRVSheepdogState *s, uint64_t oid, uint32_t id)
+static void coroutine_fn send_pending_req(BDRVSheepdogState *s, uint64_t oid)
 {
     AIOReq *aio_req, *next;
     SheepdogAIOCB *acb;
     int ret;
 
-    QLIST_FOREACH_SAFE(aio_req, &s->outstanding_aio_head,
-                       outstanding_aio_siblings, next) {
-        if (id == aio_req->id) {
-            continue;
-        }
+    QLIST_FOREACH_SAFE(aio_req, &s->pending_aio_head, aio_siblings, next) {
         if (aio_req->oid != oid) {
             continue;
         }
 
         acb = aio_req->aiocb;
+        /* move aio_req from pending list to inflight one */
+        QLIST_REMOVE(aio_req, aio_siblings);
+        QLIST_INSERT_HEAD(&s->inflight_aio_head, aio_req, aio_siblings);
         ret = add_aio_request(s, aio_req, acb->qiov->iov,
                               acb->qiov->niov, 0, acb->aiocb_type);
         if (ret < 0) {
@@ -684,7 +681,7 @@ static void coroutine_fn aio_read_response(void *opaque)
     SheepdogAIOCB *acb;
     unsigned long idx;
 
-    if (QLIST_EMPTY(&s->outstanding_aio_head)) {
+    if (QLIST_EMPTY(&s->inflight_aio_head)) {
         goto out;
     }
 
@@ -695,8 +692,8 @@ static void coroutine_fn aio_read_response(void *opaque)
         goto out;
     }
 
-    /* find the right aio_req from the outstanding_aio list */
-    QLIST_FOREACH(aio_req, &s->outstanding_aio_head, outstanding_aio_siblings) {
+    /* find the right aio_req from the inflight aio list */
+    QLIST_FOREACH(aio_req, &s->inflight_aio_head, aio_siblings) {
         if (aio_req->id == rsp.id) {
             break;
         }
@@ -734,7 +731,7 @@ static void coroutine_fn aio_read_response(void *opaque)
              * create requests are not allowed, so we search the
              * pending requests here.
              */
-            send_pending_req(s, vid_to_data_oid(s->inode.vdi_id, idx), rsp.id);
+            send_pending_req(s, vid_to_data_oid(s->inode.vdi_id, idx));
         }
         break;
     case AIOCB_READ_UDATA:
@@ -786,7 +783,8 @@ static int aio_flush_request(void *opaque)
 {
     BDRVSheepdogState *s = opaque;
 
-    return !QLIST_EMPTY(&s->outstanding_aio_head);
+    return !QLIST_EMPTY(&s->inflight_aio_head) ||
+        !QLIST_EMPTY(&s->pending_aio_head);
 }
 
 static int set_nodelay(int fd)
@@ -1103,7 +1101,8 @@ static int sd_open(BlockDriverState *bs, const char *filename, int flags)
 
     strstart(filename, "sheepdog:", (const char **)&filename);
 
-    QLIST_INIT(&s->outstanding_aio_head);
+    QLIST_INIT(&s->inflight_aio_head);
+    QLIST_INIT(&s->pending_aio_head);
     s->fd = -1;
 
     memset(vdi, 0, sizeof(vdi));
@@ -1465,6 +1464,7 @@ static void coroutine_fn sd_write_done(SheepdogAIOCB *acb)
         iov.iov_len = sizeof(s->inode);
         aio_req = alloc_aio_req(s, acb, vid_to_vdi_oid(s->inode.vdi_id),
                                 data_len, offset, 0, 0, offset);
+        QLIST_INSERT_HEAD(&s->inflight_aio_head, aio_req, aio_siblings);
         ret = add_aio_request(s, aio_req, &iov, 1, 0, AIOCB_WRITE_UDATA);
         if (ret) {
             free_aio_req(s, aio_req);
@@ -1533,7 +1533,7 @@ out:
  * Send I/O requests to the server.
  *
  * This function sends requests to the server, links the requests to
- * the outstanding_list in BDRVSheepdogState, and exits without
+ * the inflight_list in BDRVSheepdogState, and exits without
  * waiting the response.  The responses are received in the
  * `aio_read_response' function which is called from the main loop as
  * a fd handler.
@@ -1606,11 +1606,7 @@ static int coroutine_fn sd_co_rw_vector(void *p)
 
         if (create) {
             AIOReq *areq;
-            QLIST_FOREACH(areq, &s->outstanding_aio_head,
-                          outstanding_aio_siblings) {
-                if (areq == aio_req) {
-                    continue;
-                }
+            QLIST_FOREACH(areq, &s->inflight_aio_head, aio_siblings) {
                 if (areq->oid == oid) {
                     /*
                      * Sheepdog cannot handle simultaneous create
@@ -1620,11 +1616,14 @@ static int coroutine_fn sd_co_rw_vector(void *p)
                      */
                     aio_req->flags = 0;
                     aio_req->base_oid = 0;
+                    QLIST_INSERT_HEAD(&s->pending_aio_head, aio_req,
+                                      aio_siblings);
                     goto done;
                 }
             }
         }
 
+        QLIST_INSERT_HEAD(&s->inflight_aio_head, aio_req, aio_siblings);
         ret = add_aio_request(s, aio_req, acb->qiov->iov, acb->qiov->niov,
                               create, acb->aiocb_type);
         if (ret < 0) {
commit 1d732d7d7ca1731b6b77e791ca57743449620fe3
Author: MORITA Kazutaka <morita.kazutaka at lab.ntt.co.jp>
Date:   Wed Jun 27 07:26:21 2012 +0900

    sheepdog: make sure we don't free aiocb before sending all requests
    
    This patch increments the pending counter before sending requests, and
    make sures that aiocb is not freed while sending them.
    
    Signed-off-by: MORITA Kazutaka <morita.kazutaka at lab.ntt.co.jp>
    Signed-off-by: Kevin Wolf <kwolf at redhat.com>

diff --git a/block/sheepdog.c b/block/sheepdog.c
index 5dc1d7a..d4e5e3a 100644
--- a/block/sheepdog.c
+++ b/block/sheepdog.c
@@ -260,7 +260,6 @@ typedef struct AIOReq {
     uint32_t id;
 
     QLIST_ENTRY(AIOReq) outstanding_aio_siblings;
-    QLIST_ENTRY(AIOReq) aioreq_siblings;
 } AIOReq;
 
 enum AIOCBState {
@@ -283,8 +282,7 @@ struct SheepdogAIOCB {
     void (*aio_done_func)(SheepdogAIOCB *);
 
     int canceled;
-
-    QLIST_HEAD(aioreq_head, AIOReq) aioreq_head;
+    int nr_pending;
 };
 
 typedef struct BDRVSheepdogState {
@@ -388,19 +386,19 @@ static inline AIOReq *alloc_aio_req(BDRVSheepdogState *s, SheepdogAIOCB *acb,
 
     QLIST_INSERT_HEAD(&s->outstanding_aio_head, aio_req,
                       outstanding_aio_siblings);
-    QLIST_INSERT_HEAD(&acb->aioreq_head, aio_req, aioreq_siblings);
 
+    acb->nr_pending++;
     return aio_req;
 }
 
-static inline int free_aio_req(BDRVSheepdogState *s, AIOReq *aio_req)
+static inline void free_aio_req(BDRVSheepdogState *s, AIOReq *aio_req)
 {
     SheepdogAIOCB *acb = aio_req->aiocb;
+
     QLIST_REMOVE(aio_req, outstanding_aio_siblings);
-    QLIST_REMOVE(aio_req, aioreq_siblings);
     g_free(aio_req);
 
-    return !QLIST_EMPTY(&acb->aioreq_head);
+    acb->nr_pending--;
 }
 
 static void coroutine_fn sd_finish_aiocb(SheepdogAIOCB *acb)
@@ -446,7 +444,7 @@ static SheepdogAIOCB *sd_aio_setup(BlockDriverState *bs, QEMUIOVector *qiov,
     acb->canceled = 0;
     acb->coroutine = qemu_coroutine_self();
     acb->ret = 0;
-    QLIST_INIT(&acb->aioreq_head);
+    acb->nr_pending = 0;
     return acb;
 }
 
@@ -663,7 +661,7 @@ static void coroutine_fn send_pending_req(BDRVSheepdogState *s, uint64_t oid, ui
         if (ret < 0) {
             error_report("add_aio_request is failed");
             free_aio_req(s, aio_req);
-            if (QLIST_EMPTY(&acb->aioreq_head)) {
+            if (!acb->nr_pending) {
                 sd_finish_aiocb(acb);
             }
         }
@@ -684,7 +682,6 @@ static void coroutine_fn aio_read_response(void *opaque)
     int ret;
     AIOReq *aio_req = NULL;
     SheepdogAIOCB *acb;
-    int rest;
     unsigned long idx;
 
     if (QLIST_EMPTY(&s->outstanding_aio_head)) {
@@ -755,8 +752,8 @@ static void coroutine_fn aio_read_response(void *opaque)
         error_report("%s", sd_strerror(rsp.result));
     }
 
-    rest = free_aio_req(s, aio_req);
-    if (!rest) {
+    free_aio_req(s, aio_req);
+    if (!acb->nr_pending) {
         /*
          * We've finished all requests which belong to the AIOCB, so
          * we can switch back to sd_co_readv/writev now.
@@ -1568,6 +1565,12 @@ static int coroutine_fn sd_co_rw_vector(void *p)
         }
     }
 
+    /*
+     * Make sure we don't free the aiocb before we are done with all requests.
+     * This additional reference is dropped at the end of this function.
+     */
+    acb->nr_pending++;
+
     while (done != total) {
         uint8_t flags = 0;
         uint64_t old_oid = 0;
@@ -1636,7 +1639,7 @@ static int coroutine_fn sd_co_rw_vector(void *p)
         done += len;
     }
 out:
-    if (QLIST_EMPTY(&acb->aioreq_head)) {
+    if (!--acb->nr_pending) {
         return acb->ret;
     }
     return 1;
commit b97564f4c5457b218c7dd56dde0554ce4765cae9
Author: MORITA Kazutaka <morita.kazutaka at lab.ntt.co.jp>
Date:   Wed Jun 27 07:26:20 2012 +0900

    sheepdog: use coroutine based socket functions in coroutine context
    
    This removes blocking network I/Os in coroutine context.
    
    Signed-off-by: MORITA Kazutaka <morita.kazutaka at lab.ntt.co.jp>
    Signed-off-by: Kevin Wolf <kwolf at redhat.com>

diff --git a/block/sheepdog.c b/block/sheepdog.c
index 0b49c6d..5dc1d7a 100644
--- a/block/sheepdog.c
+++ b/block/sheepdog.c
@@ -541,11 +541,18 @@ static coroutine_fn int send_co_req(int sockfd, SheepdogReq *hdr, void *data,
     return ret;
 }
 
+static coroutine_fn int do_co_req(int sockfd, SheepdogReq *hdr, void *data,
+                                  unsigned int *wlen, unsigned int *rlen);
+
 static int do_req(int sockfd, SheepdogReq *hdr, void *data,
                   unsigned int *wlen, unsigned int *rlen)
 {
     int ret;
 
+    if (qemu_in_coroutine()) {
+        return do_co_req(sockfd, hdr, data, wlen, rlen);
+    }
+
     socket_set_block(sockfd);
     ret = send_req(sockfd, hdr, data, wlen);
     if (ret < 0) {
@@ -1642,7 +1649,6 @@ static coroutine_fn int sd_co_writev(BlockDriverState *bs, int64_t sector_num,
     int ret;
 
     if (bs->growable && sector_num + nb_sectors > bs->total_sectors) {
-        /* TODO: shouldn't block here */
         ret = sd_truncate(bs, (sector_num + nb_sectors) * SECTOR_SIZE);
         if (ret < 0) {
             return ret;
@@ -1710,7 +1716,7 @@ static int coroutine_fn sd_co_flush_to_disk(BlockDriverState *bs)
     hdr.opcode = SD_OP_FLUSH_VDI;
     hdr.oid = vid_to_vdi_oid(inode->vdi_id);
 
-    ret = do_co_req(s->flush_fd, (SheepdogReq *)&hdr, NULL, &wlen, &rlen);
+    ret = do_req(s->flush_fd, (SheepdogReq *)&hdr, NULL, &wlen, &rlen);
     if (ret) {
         error_report("failed to send a request to the sheep");
         return ret;
commit 2dfcca3b6828052cadd30c66a1a840bf0fc6670c
Author: MORITA Kazutaka <morita.kazutaka at lab.ntt.co.jp>
Date:   Wed Jun 27 07:26:19 2012 +0900

    sheepdog: restart I/O when socket becomes ready in do_co_req()
    
    Currently, no one reenters the yielded coroutine.  This fixes it.
    
    Signed-off-by: MORITA Kazutaka <morita.kazutaka at lab.ntt.co.jp>
    Signed-off-by: Kevin Wolf <kwolf at redhat.com>

diff --git a/block/sheepdog.c b/block/sheepdog.c
index afd06aa..0b49c6d 100644
--- a/block/sheepdog.c
+++ b/block/sheepdog.c
@@ -577,10 +577,21 @@ out:
     return ret;
 }
 
+static void restart_co_req(void *opaque)
+{
+    Coroutine *co = opaque;
+
+    qemu_coroutine_enter(co, NULL);
+}
+
 static coroutine_fn int do_co_req(int sockfd, SheepdogReq *hdr, void *data,
                                   unsigned int *wlen, unsigned int *rlen)
 {
     int ret;
+    Coroutine *co;
+
+    co = qemu_coroutine_self();
+    qemu_aio_set_fd_handler(sockfd, NULL, restart_co_req, NULL, co);
 
     socket_set_block(sockfd);
     ret = send_co_req(sockfd, hdr, data, wlen);
@@ -588,6 +599,8 @@ static coroutine_fn int do_co_req(int sockfd, SheepdogReq *hdr, void *data,
         goto out;
     }
 
+    qemu_aio_set_fd_handler(sockfd, restart_co_req, NULL, NULL, co);
+
     ret = qemu_co_recv(sockfd, hdr, sizeof(*hdr));
     if (ret < sizeof(*hdr)) {
         error_report("failed to get a rsp, %s", strerror(errno));
@@ -609,6 +622,7 @@ static coroutine_fn int do_co_req(int sockfd, SheepdogReq *hdr, void *data,
     }
     ret = 0;
 out:
+    qemu_aio_set_fd_handler(sockfd, NULL, NULL, NULL, NULL);
     socket_set_nonblock(sockfd);
     return ret;
 }
commit 1b6ac9985aba27142d7dd6460bf20fc6ade92c00
Author: MORITA Kazutaka <morita.kazutaka at lab.ntt.co.jp>
Date:   Wed Jun 27 07:26:18 2012 +0900

    sheepdog: fix dprintf format strings
    
    This fixes warnings about dprintf format in debug mode.
    
    Signed-off-by: MORITA Kazutaka <morita.kazutaka at lab.ntt.co.jp>
    Signed-off-by: Kevin Wolf <kwolf at redhat.com>

diff --git a/block/sheepdog.c b/block/sheepdog.c
index 8877f45..afd06aa 100644
--- a/block/sheepdog.c
+++ b/block/sheepdog.c
@@ -1571,11 +1571,11 @@ static int coroutine_fn sd_co_rw_vector(void *p)
         }
 
         if (create) {
-            dprintf("update ino (%" PRIu32") %" PRIu64 " %" PRIu64
-                    " %" PRIu64 "\n", inode->vdi_id, oid,
+            dprintf("update ino (%" PRIu32 ") %" PRIu64 " %" PRIu64 " %ld\n",
+                    inode->vdi_id, oid,
                     vid_to_data_oid(inode->data_vdi_id[idx], idx), idx);
             oid = vid_to_data_oid(inode->vdi_id, idx);
-            dprintf("new oid %lx\n", oid);
+            dprintf("new oid %" PRIx64 "\n", oid);
         }
 
         aio_req = alloc_aio_req(s, acb, oid, len, offset, flags, old_oid, done);
@@ -1726,7 +1726,7 @@ static int sd_snapshot_create(BlockDriverState *bs, QEMUSnapshotInfo *sn_info)
     SheepdogInode *inode;
     unsigned int datalen;
 
-    dprintf("sn_info: name %s id_str %s s: name %s vm_state_size %d "
+    dprintf("sn_info: name %s id_str %s s: name %s vm_state_size %" PRId64 " "
             "is_snapshot %d\n", sn_info->name, sn_info->id_str,
             s->name, sn_info->vm_state_size, s->is_snapshot);
 
commit 04d4abe96ca07b851fb74125390b1b626126aa86
Author: Stefan Hajnoczi <stefanha at linux.vnet.ibm.com>
Date:   Wed Jun 27 18:03:13 2012 +0100

    blockdev: warn when copy_on_read=on and readonly=on
    
    If the image is read-only then it's not possible to copy read data into
    it.  Therefore copy-on-read is automatically disabled for read-only
    images.
    
    Up until now this behavior was silent, add a warning so the user knows
    why copy-on-read is not working.
    
    Signed-off-by: Stefan Hajnoczi <stefanha at linux.vnet.ibm.com>
    Signed-off-by: Kevin Wolf <kwolf at redhat.com>

diff --git a/blockdev.c b/blockdev.c
index 9e0a72a..a85a429 100644
--- a/blockdev.c
+++ b/blockdev.c
@@ -609,6 +609,10 @@ DriveInfo *drive_init(QemuOpts *opts, int default_to_scsi)
 
     bdrv_flags |= ro ? 0 : BDRV_O_RDWR;
 
+    if (ro && copy_on_read) {
+        error_report("warning: disabling copy_on_read on readonly drive");
+    }
+
     ret = bdrv_open(dinfo->bdrv, file, bdrv_flags, drv);
     if (ret < 0) {
         error_report("could not open disk image %s: %s",
commit 206e6d8551839008b6858cf8f500d2e644d2b561
Author: Stefan Hajnoczi <stefanha at linux.vnet.ibm.com>
Date:   Mon Jun 18 14:00:57 2012 +0100

    qcow2: preserve free_byte_offset when qcow2_alloc_bytes() fails
    
    When qcow2_alloc_clusters() error handling code was introduced in commit
    5d757b563d59142ca81e1073a8e8396750a0ad1a, the value of free_byte_offset
    was clobbered in the error case.  This patch keeps free_byte_offset at 0
    so we will try to allocate clusters again next time this function is
    called.
    
    Signed-off-by: Stefan Hajnoczi <stefanha at linux.vnet.ibm.com>
    Signed-off-by: Kevin Wolf <kwolf at redhat.com>

diff --git a/block/qcow2-refcount.c b/block/qcow2-refcount.c
index 66f3915..5e3f915 100644
--- a/block/qcow2-refcount.c
+++ b/block/qcow2-refcount.c
@@ -627,10 +627,11 @@ int64_t qcow2_alloc_bytes(BlockDriverState *bs, int size)
     BLKDBG_EVENT(bs->file, BLKDBG_CLUSTER_ALLOC_BYTES);
     assert(size > 0 && size <= s->cluster_size);
     if (s->free_byte_offset == 0) {
-        s->free_byte_offset = qcow2_alloc_clusters(bs, s->cluster_size);
-        if (s->free_byte_offset < 0) {
-            return s->free_byte_offset;
+        offset = qcow2_alloc_clusters(bs, s->cluster_size);
+        if (offset < 0) {
+            return offset;
         }
+        s->free_byte_offset = offset;
     }
  redo:
     free_in_cluster = s->cluster_size -
commit b35278f75450e57c134a153e6da9744c1db8382f
Author: Stefan Hajnoczi <stefanha at linux.vnet.ibm.com>
Date:   Fri Jun 15 16:41:07 2012 +0100

    qcow2: fix #ifdef'd qcow2_check_refcounts() callers
    
    The DEBUG_ALLOC qcow2.h macro enables additional consistency checks
    throughout the code.  This makes it easier to spot corruptions that are
    introduced during development.  Since consistency check is an expensive
    operation the DEBUG_ALLOC macro is used to compile checks out in normal
    builds and qcow2_check_refcounts() calls missed the addition of a new
    function argument.
    
    Signed-off-by: Stefan Hajnoczi <stefanha at linux.vnet.ibm.com>
    Signed-off-by: Kevin Wolf <kwolf at redhat.com>

diff --git a/block/qcow2-snapshot.c b/block/qcow2-snapshot.c
index 4561a2a..4e7c93b 100644
--- a/block/qcow2-snapshot.c
+++ b/block/qcow2-snapshot.c
@@ -405,7 +405,7 @@ int qcow2_snapshot_create(BlockDriverState *bs, QEMUSnapshotInfo *sn_info)
 #ifdef DEBUG_ALLOC
     {
       BdrvCheckResult result = {0};
-      qcow2_check_refcounts(bs, &result);
+      qcow2_check_refcounts(bs, &result, 0);
     }
 #endif
     return 0;
@@ -522,7 +522,7 @@ int qcow2_snapshot_goto(BlockDriverState *bs, const char *snapshot_id)
 #ifdef DEBUG_ALLOC
     {
         BdrvCheckResult result = {0};
-        qcow2_check_refcounts(bs, &result);
+        qcow2_check_refcounts(bs, &result, 0);
     }
 #endif
     return 0;
@@ -582,7 +582,7 @@ int qcow2_snapshot_delete(BlockDriverState *bs, const char *snapshot_id)
 #ifdef DEBUG_ALLOC
     {
         BdrvCheckResult result = {0};
-        qcow2_check_refcounts(bs, &result);
+        qcow2_check_refcounts(bs, &result, 0);
     }
 #endif
     return 0;
diff --git a/block/qcow2.c b/block/qcow2.c
index 2c1cd0a..5be5ace 100644
--- a/block/qcow2.c
+++ b/block/qcow2.c
@@ -415,7 +415,7 @@ static int qcow2_open(BlockDriverState *bs, int flags)
 #ifdef DEBUG_ALLOC
     {
         BdrvCheckResult result = {0};
-        qcow2_check_refcounts(bs, &result);
+        qcow2_check_refcounts(bs, &result, 0);
     }
 #endif
     return ret;
commit c32da15188e12af1299f057fc0fb31e8018674b0
Author: Gerd Hoffmann <kraxel at redhat.com>
Date:   Tue Jul 3 15:43:49 2012 +0200

    usb-host: add trace events for iso xfers
    
    Replace iso transfer fprintf's with trace points.  Also rename existing
    tracepoints so they all match usb_host_iso_*.
    
    Signed-off-by: Gerd Hoffmann <kraxel at redhat.com>

diff --git a/hw/usb/host-linux.c b/hw/usb/host-linux.c
index 9ba8925..d55be87 100644
--- a/hw/usb/host-linux.c
+++ b/hw/usb/host-linux.c
@@ -213,7 +213,7 @@ static int is_iso_started(USBHostDevice *s, int pid, int ep)
 
 static void clear_iso_started(USBHostDevice *s, int pid, int ep)
 {
-    trace_usb_host_ep_stop_iso(s->bus_num, s->addr, ep);
+    trace_usb_host_iso_stop(s->bus_num, s->addr, ep);
     get_endp(s, pid, ep)->iso_started = 0;
 }
 
@@ -221,7 +221,7 @@ static void set_iso_started(USBHostDevice *s, int pid, int ep)
 {
     struct endp_data *e = get_endp(s, pid, ep);
 
-    trace_usb_host_ep_start_iso(s->bus_num, s->addr, ep);
+    trace_usb_host_iso_start(s->bus_num, s->addr, ep);
     if (!e->iso_started) {
         e->iso_started = 1;
         e->inflight = 0;
@@ -319,7 +319,8 @@ static void async_complete(void *opaque)
         if (r < 0) {
             if (errno == EAGAIN) {
                 if (urbs > 2) {
-                    fprintf(stderr, "husb: %d iso urbs finished at once\n", urbs);
+                    /* indicates possible latency issues */
+                    trace_usb_host_iso_many_urbs(s->bus_num, s->addr, urbs);
                 }
                 return;
             }
@@ -352,7 +353,8 @@ static void async_complete(void *opaque)
             urbs++;
             inflight = change_iso_inflight(s, pid, ep, -1);
             if (inflight == 0 && is_iso_started(s, pid, ep)) {
-                fprintf(stderr, "husb: out of buffers for iso stream\n");
+                /* can be latency issues, or simply end of stream */
+                trace_usb_host_iso_out_of_bufs(s->bus_num, s->addr, ep);
             }
             continue;
         }
diff --git a/trace-events b/trace-events
index c935ba2..c33d58c 100644
--- a/trace-events
+++ b/trace-events
@@ -368,8 +368,10 @@ usb_host_urb_complete(int bus, int addr, void *aurb, int status, int length, int
 usb_host_urb_canceled(int bus, int addr, void *aurb) "dev %d:%d, aurb %p"
 usb_host_ep_set_halt(int bus, int addr, int ep) "dev %d:%d, ep %d"
 usb_host_ep_clear_halt(int bus, int addr, int ep) "dev %d:%d, ep %d"
-usb_host_ep_start_iso(int bus, int addr, int ep) "dev %d:%d, ep %d"
-usb_host_ep_stop_iso(int bus, int addr, int ep) "dev %d:%d, ep %d"
+usb_host_iso_start(int bus, int addr, int ep) "dev %d:%d, ep %d"
+usb_host_iso_stop(int bus, int addr, int ep) "dev %d:%d, ep %d"
+usb_host_iso_out_of_bufs(int bus, int addr, int ep) "dev %d:%d, ep %d"
+usb_host_iso_many_urbs(int bus, int addr, int count) "dev %d:%d, count %d"
 usb_host_reset(int bus, int addr) "dev %d:%d"
 usb_host_auto_scan_enabled(void)
 usb_host_auto_scan_disabled(void)
commit 7c37e6a4c4972ad3cdb2478a0249757ee3a1bf70
Author: Gerd Hoffmann <kraxel at redhat.com>
Date:   Tue Jul 3 10:15:08 2012 +0200

    usb: fix interface initialization
    
    zero is a valid interface number, so don't use it when resetting the
    endpoints.
    
    Signed-off-by: Gerd Hoffmann <kraxel at redhat.com>

diff --git a/hw/usb.h b/hw/usb.h
index 9cd2f89..7ed8fb8 100644
--- a/hw/usb.h
+++ b/hw/usb.h
@@ -145,6 +145,8 @@
 #define USB_ENDPOINT_XFER_INT		3
 #define USB_ENDPOINT_XFER_INVALID     255
 
+#define USB_INTERFACE_INVALID         255
+
 typedef struct USBBus USBBus;
 typedef struct USBBusOps USBBusOps;
 typedef struct USBPort USBPort;
diff --git a/hw/usb/core.c b/hw/usb/core.c
index fe15be0..0614f76 100644
--- a/hw/usb/core.c
+++ b/hw/usb/core.c
@@ -566,8 +566,8 @@ void usb_ep_reset(USBDevice *dev)
         dev->ep_out[ep].pid = USB_TOKEN_OUT;
         dev->ep_in[ep].type = USB_ENDPOINT_XFER_INVALID;
         dev->ep_out[ep].type = USB_ENDPOINT_XFER_INVALID;
-        dev->ep_in[ep].ifnum = 0;
-        dev->ep_out[ep].ifnum = 0;
+        dev->ep_in[ep].ifnum = USB_INTERFACE_INVALID;
+        dev->ep_out[ep].ifnum = USB_INTERFACE_INVALID;
         dev->ep_in[ep].dev = dev;
         dev->ep_out[ep].dev = dev;
         dev->ep_in[ep].pipeline = false;
commit 19deaa089cb874912767bc6071f3b7372d3ff961
Author: Gerd Hoffmann <kraxel at redhat.com>
Date:   Tue Jul 3 10:11:21 2012 +0200

    usb: split endpoint init and reset
    
    Create a new usb_ep_reset() function to reset endpoint state, without
    re-initialiting the queues, so we don't unlink in-flight packets just
    because usb-host has to re-parse the descriptor tables.
    
    Signed-off-by: Gerd Hoffmann <kraxel at redhat.com>

diff --git a/hw/usb.h b/hw/usb.h
index a5623d3..9cd2f89 100644
--- a/hw/usb.h
+++ b/hw/usb.h
@@ -363,6 +363,7 @@ void usb_packet_complete(USBDevice *dev, USBPacket *p);
 void usb_cancel_packet(USBPacket * p);
 
 void usb_ep_init(USBDevice *dev);
+void usb_ep_reset(USBDevice *dev);
 void usb_ep_dump(USBDevice *dev);
 struct USBEndpoint *usb_ep_get(USBDevice *dev, int pid, int ep);
 uint8_t usb_ep_get_type(USBDevice *dev, int pid, int ep);
diff --git a/hw/usb/core.c b/hw/usb/core.c
index 0e02da7..fe15be0 100644
--- a/hw/usb/core.c
+++ b/hw/usb/core.c
@@ -550,7 +550,7 @@ void usb_packet_cleanup(USBPacket *p)
     qemu_iovec_destroy(&p->iov);
 }
 
-void usb_ep_init(USBDevice *dev)
+void usb_ep_reset(USBDevice *dev)
 {
     int ep;
 
@@ -559,7 +559,6 @@ void usb_ep_init(USBDevice *dev)
     dev->ep_ctl.ifnum = 0;
     dev->ep_ctl.dev = dev;
     dev->ep_ctl.pipeline = false;
-    QTAILQ_INIT(&dev->ep_ctl.queue);
     for (ep = 0; ep < USB_MAX_ENDPOINTS; ep++) {
         dev->ep_in[ep].nr = ep + 1;
         dev->ep_out[ep].nr = ep + 1;
@@ -573,6 +572,16 @@ void usb_ep_init(USBDevice *dev)
         dev->ep_out[ep].dev = dev;
         dev->ep_in[ep].pipeline = false;
         dev->ep_out[ep].pipeline = false;
+    }
+}
+
+void usb_ep_init(USBDevice *dev)
+{
+    int ep;
+
+    usb_ep_reset(dev);
+    QTAILQ_INIT(&dev->ep_ctl.queue);
+    for (ep = 0; ep < USB_MAX_ENDPOINTS; ep++) {
         QTAILQ_INIT(&dev->ep_in[ep].queue);
         QTAILQ_INIT(&dev->ep_out[ep].queue);
     }
diff --git a/hw/usb/host-linux.c b/hw/usb/host-linux.c
index 5479fb5..9ba8925 100644
--- a/hw/usb/host-linux.c
+++ b/hw/usb/host-linux.c
@@ -1136,7 +1136,7 @@ static int usb_linux_update_endp_table(USBHostDevice *s)
     USBDescriptor *d;
     bool active = false;
 
-    usb_ep_init(&s->dev);
+    usb_ep_reset(&s->dev);
 
     for (i = 0;; i += d->bLength) {
         if (i+2 >= s->descr_len) {
@@ -1239,7 +1239,7 @@ static int usb_linux_update_endp_table(USBHostDevice *s)
     return 0;
 
 error:
-    usb_ep_init(&s->dev);
+    usb_ep_reset(&s->dev);
     return 1;
 }
 
@@ -1326,6 +1326,7 @@ static int usb_host_open(USBHostDevice *dev, int bus_num,
         goto fail;
     }
 
+    usb_ep_init(&dev->dev);
     ret = usb_linux_update_endp_table(dev);
     if (ret) {
         goto fail;
commit adae502c0ae4572ef08f71cb5b5ed5a8e90299fe
Author: Hans de Goede <hdegoede at redhat.com>
Date:   Fri Jul 6 12:09:32 2012 +0200

    usb-redir: Correctly handle the usb_redir_babble usbredir status
    
    Signed-off-by: Hans de Goede <hdegoede at redhat.com>
    Signed-off-by: Gerd Hoffmann <kraxel at redhat.com>

diff --git a/hw/usb/redirect.c b/hw/usb/redirect.c
index d949f04..10b4fbb 100644
--- a/hw/usb/redirect.c
+++ b/hw/usb/redirect.c
@@ -1033,6 +1033,8 @@ static int usbredir_handle_status(USBRedirDevice *dev,
     case usb_redir_inval:
         WARNING("got invalid param error from usb-host?\n");
         return USB_RET_NAK;
+    case usb_redir_babble:
+        return USB_RET_BABBLE;
     case usb_redir_ioerror:
     case usb_redir_timeout:
     default:
commit 379521175c6adecd48afcfde647c224f9586c9c0
Author: Hans de Goede <hdegoede at redhat.com>
Date:   Fri Jul 6 16:53:39 2012 +0200

    ehci: Kick async schedule on wakeup in the non companion case
    
    Commit 0f588df8b3688b00e77aabaa32e26ece5f19bd39, added code
    to ehci_wakeup to kick the async schedule on wakeup, but the else
    was positioned wrong making it trigger for devices which are routed
    to the companion rather then to the ehci controller itself.
    
    This patch fixes this. Note that the "programming style" with using the
    return at the end of the companion block matches how the companion case
    is handled in the other ports ops, and is done this way for consistency.
    
    Signed-off-by: Hans de Goede <hdegoede at redhat.com>
    Signed-off-by: Gerd Hoffmann <kraxel at redhat.com>

diff --git a/hw/usb/hcd-ehci.c b/hw/usb/hcd-ehci.c
index f612610..080f62c 100644
--- a/hw/usb/hcd-ehci.c
+++ b/hw/usb/hcd-ehci.c
@@ -905,10 +905,11 @@ static void ehci_wakeup(USBPort *port)
         USBPort *companion = s->companion_ports[port->index];
         if (companion->ops->wakeup) {
             companion->ops->wakeup(companion);
-        } else {
-            qemu_bh_schedule(s->async_bh);
         }
+        return;
     }
+
+    qemu_bh_schedule(s->async_bh);
 }
 
 static int ehci_register_companion(USBBus *bus, USBPort *ports[],
commit 7341ea075c09258b98a1d0efc60efd402cbfc9b4
Author: Hans de Goede <hdegoede at redhat.com>
Date:   Fri Jul 6 12:09:33 2012 +0200

    usb-ehci: Fix an assert whenever isoc transfers are used
    
    hcd-ehci.c is missing an usb_packet_init() call for the ipacket UsbPacket
    it uses for isoc transfers, triggering an assert (taking the entire vm down)
    in usb_packet_setup as soon as any isoc transfers are done by a high speed
    USB device.
    
    Signed-off-by: Hans de Goede <hdegoede at redhat.com>
    Signed-off-by: Gerd Hoffmann <kraxel at redhat.com>

diff --git a/hw/usb/hcd-ehci.c b/hw/usb/hcd-ehci.c
index 0bdfbe8..f612610 100644
--- a/hw/usb/hcd-ehci.c
+++ b/hw/usb/hcd-ehci.c
@@ -2581,6 +2581,7 @@ static int usb_ehci_initfn(PCIDevice *dev)
     s->async_bh = qemu_bh_new(ehci_async_bh, s);
     QTAILQ_INIT(&s->aqueues);
     QTAILQ_INIT(&s->pqueues);
+    usb_packet_init(&s->ipacket);
 
     qemu_register_reset(ehci_reset, s);
 
commit 9bc3a3a216e2689bfcdd36c3e079333bbdbf3ba0
Author: Gerd Hoffmann <kraxel at redhat.com>
Date:   Wed Jun 20 13:14:08 2012 +0200

    ehci: don't flush cache on doorbell rings.
    
    Commit 4be23939ab0d7019c7e59a37485b416fbbf0f073 makes ehci instantly
    zap any unlinked queue heads when the guest rings the doorbell.
    
    While hacking up uas support this turned out to be a problem.  The linux
    kernel can unlink and instantly relink the very same queue head, thereby
    killing any async packets in flight.  That alone isn't an issue yet, the
    packet will canceled and resubmitted and everything is fine.  We'll run
    into trouble though in case the async packet is completed already, so we
    can't cancel it any more.  The transaction is simply lost then.
    
    usb_ehci_qh_ptrs q (nil) - QH @ 39c4f000: next 39c4f122 qtds 00000000,00000001,39c50000
    usb_ehci_qh_fields QH @ 39c4f000 - rl 0, mplen 0, eps 0, ep 0, dev 0
    usb_ehci_qh_ptrs q 0x7f95feba90a0 - QH @ 39c4f000: next 39c4f122 qtds 00000000,00000001,39c50000
    usb_ehci_qh_fields QH @ 39c4f000 - rl 0, mplen 0, eps 0, ep 0, dev 0
    usb_ehci_qh_ptrs q 0x7f95fe515210 - QH @ 39c4f120: next 39c4f0c2 qtds 29dbce40,29dbc4e0,00000009
    usb_ehci_qh_fields QH @ 39c4f120 - rl 4, mplen 512, eps 2, ep 1, dev 2
    usb_ehci_packet_action q 0x7f95fe515210 p 0x7f95fdec32a0: alloc
    usb_packet_state_change bus 0, port 2, ep 1, packet 0x7f95fdec32e0, state undef -> setup
    usb_ehci_packet_action q 0x7f95fe515210 p 0x7f95fdec32a0: process
    usb_uas_command dev 2, tag 0x2, lun 0, lun64 00000000-00000000
    scsi_req_parsed target 0 lun 0 tag 2 command 42 dir 2 length 16384
    scsi_req_parsed_lba target 0 lun 0 tag 2 command 42 lba 5933312
    scsi_req_alloc target 0 lun 0 tag 2
    scsi_req_continue target 0 lun 0 tag 2
    scsi_req_data target 0 lun 0 tag 2 len 16384
    usb_uas_scsi_data dev 2, tag 0x2, bytes 16384
    usb_uas_write_ready dev 2, tag 0x2
    usb_packet_state_change bus 0, port 2, ep 1, packet 0x7f95fdec32e0, state setup -> complete
    usb_ehci_packet_action q 0x7f95fe515210 p 0x7f95fdec32a0: free
    usb_ehci_qh_ptrs q 0x7f95fdec3210 - QH @ 39c4f0c0: next 39c4f002 qtds 29dbce40,00000001,00000009
    usb_ehci_qh_fields QH @ 39c4f0c0 - rl 4, mplen 512, eps 2, ep 2, dev 2
    usb_ehci_queue_action q 0x7f95fe5152a0: free
    usb_packet_state_change bus 0, port 2, ep 2, packet 0x7f95feba9170, state async -> complete
    ^^^ async packets completes.
    usb_ehci_packet_action q 0x7f95fdec3210 p 0x7f95feba9130: wakeup
    
    usb_ehci_qh_ptrs q (nil) - QH @ 39c4f000: next 39c4f122 qtds 00000000,00000001,39c50000
    usb_ehci_qh_fields QH @ 39c4f000 - rl 0, mplen 0, eps 0, ep 0, dev 0
    usb_ehci_qh_ptrs q 0x7f95feba90a0 - QH @ 39c4f000: next 39c4f122 qtds 00000000,00000001,39c50000
    usb_ehci_qh_fields QH @ 39c4f000 - rl 0, mplen 0, eps 0, ep 0, dev 0
    usb_ehci_qh_ptrs q 0x7f95fe515210 - QH @ 39c4f120: next 39c4f002 qtds 29dbc4e0,29dbc8a0,00000009
    usb_ehci_qh_fields QH @ 39c4f120 - rl 4, mplen 512, eps 2, ep 1, dev 2
    usb_ehci_queue_action q 0x7f95fdec3210: free
    usb_ehci_packet_action q 0x7f95fdec3210 p 0x7f95feba9130: free
    ^^^ endpoint #2 queue head removed from schedule, doorbell makes ehci zap the queue,
        the (completed) usb packet is freed too and gets lost.
    
    usb_ehci_qh_ptrs q (nil) - QH @ 39c4f000: next 39c4f0c2 qtds 00000000,00000001,39c50000
    usb_ehci_qh_fields QH @ 39c4f000 - rl 0, mplen 0, eps 0, ep 0, dev 0
    usb_ehci_qh_ptrs q 0x7f95feba90a0 - QH @ 39c4f000: next 39c4f0c2 qtds 00000000,00000001,39c50000
    usb_ehci_qh_fields QH @ 39c4f000 - rl 0, mplen 0, eps 0, ep 0, dev 0
    usb_ehci_queue_action q 0x7f9600dff570: alloc
    usb_ehci_qh_ptrs q 0x7f9600dff570 - QH @ 39c4f0c0: next 39c4f122 qtds 29dbce40,00000001,00000009
    usb_ehci_qh_fields QH @ 39c4f0c0 - rl 4, mplen 512, eps 2, ep 2, dev 2
    usb_ehci_packet_action q 0x7f9600dff570 p 0x7f95feba9130: alloc
    usb_packet_state_change bus 0, port 2, ep 2, packet 0x7f95feba9170, state undef -> setup
    usb_ehci_packet_action q 0x7f9600dff570 p 0x7f95feba9130: process
    usb_packet_state_change bus 0, port 2, ep 2, packet 0x7f95feba9170, state setup -> async
    usb_ehci_packet_action q 0x7f9600dff570 p 0x7f95feba9130: async
    ^^^ linux kernel relinked the queue head, ehci creates a new usb packet,
        but we should have delivered the completed one instead.
    usb_ehci_qh_ptrs q 0x7f95fe515210 - QH @ 39c4f120: next 39c4f002 qtds 29dbc4e0,29dbc8a0,00000009
    usb_ehci_qh_fields QH @ 39c4f120 - rl 4, mplen 512, eps 2, ep 1, dev 2
    
    So instead of instantly zapping the queue we'll set a flag that the
    queue needs revalidation in case we'll see it again in the schedule.
    ehci then checks that the queue head fields addressing / describing the
    endpoint and the qtd pointer match the cached content before reusing it.
    
    Cc: Hans de Goede <hdegoede at redhat.com>
    Signed-off-by: Gerd Hoffmann <kraxel at redhat.com>

diff --git a/hw/usb/hcd-ehci.c b/hw/usb/hcd-ehci.c
index 1406b84..0bdfbe8 100644
--- a/hw/usb/hcd-ehci.c
+++ b/hw/usb/hcd-ehci.c
@@ -365,6 +365,7 @@ struct EHCIQueue {
     uint32_t seen;
     uint64_t ts;
     int async;
+    int revalidate;
 
     /* cached data from guest - needs to be flushed
      * when guest removes an entry (doorbell, handshake sequence)
@@ -775,7 +776,18 @@ static EHCIQueue *ehci_find_queue_by_qh(EHCIState *ehci, uint32_t addr,
     return NULL;
 }
 
-static void ehci_queues_rip_unused(EHCIState *ehci, int async, int flush)
+static void ehci_queues_tag_unused_async(EHCIState *ehci)
+{
+    EHCIQueue *q;
+
+    QTAILQ_FOREACH(q, &ehci->aqueues, next) {
+        if (!q->seen) {
+            q->revalidate = 1;
+        }
+    }
+}
+
+static void ehci_queues_rip_unused(EHCIState *ehci, int async)
 {
     EHCIQueueHead *head = async ? &ehci->aqueues : &ehci->pqueues;
     uint64_t maxage = FRAME_TIMER_NS * ehci->maxframes * 4;
@@ -787,7 +799,7 @@ static void ehci_queues_rip_unused(EHCIState *ehci, int async, int flush)
             q->ts = ehci->last_run_ns;
             continue;
         }
-        if (!flush && ehci->last_run_ns < q->ts + maxage) {
+        if (ehci->last_run_ns < q->ts + maxage) {
             continue;
         }
         ehci_free_queue(q);
@@ -1631,7 +1643,7 @@ static int ehci_state_waitlisthead(EHCIState *ehci,  int async)
         ehci_set_usbsts(ehci, USBSTS_REC);
     }
 
-    ehci_queues_rip_unused(ehci, async, 0);
+    ehci_queues_rip_unused(ehci, async);
 
     /*  Find the head of the list (4.9.1.1) */
     for(i = 0; i < MAX_QH; i++) {
@@ -1716,6 +1728,7 @@ static EHCIQueue *ehci_state_fetchqh(EHCIState *ehci, int async)
     EHCIPacket *p;
     uint32_t entry, devaddr;
     EHCIQueue *q;
+    EHCIqh qh;
 
     entry = ehci_get_fetch_addr(ehci, async);
     q = ehci_find_queue_by_qh(ehci, entry, async);
@@ -1733,7 +1746,17 @@ static EHCIQueue *ehci_state_fetchqh(EHCIState *ehci, int async)
     }
 
     get_dwords(ehci, NLPTR_GET(q->qhaddr),
-               (uint32_t *) &q->qh, sizeof(EHCIqh) >> 2);
+               (uint32_t *) &qh, sizeof(EHCIqh) >> 2);
+    if (q->revalidate && (q->qh.epchar      != qh.epchar ||
+                          q->qh.epcap       != qh.epcap  ||
+                          q->qh.current_qtd != qh.current_qtd)) {
+        ehci_free_queue(q);
+        q = ehci_alloc_queue(ehci, entry, async);
+        q->seen++;
+        p = NULL;
+    }
+    q->qh = qh;
+    q->revalidate = 0;
     ehci_trace_qh(q, NLPTR_GET(q->qhaddr), &q->qh);
 
     devaddr = get_field(q->qh.epchar, QH_EPCHAR_DEVADDR);
@@ -2228,7 +2251,7 @@ static void ehci_advance_async_state(EHCIState *ehci)
          */
         if (ehci->usbcmd & USBCMD_IAAD) {
             /* Remove all unseen qhs from the async qhs queue */
-            ehci_queues_rip_unused(ehci, async, 1);
+            ehci_queues_tag_unused_async(ehci);
             DPRINTF("ASYNC: doorbell request acknowledged\n");
             ehci->usbcmd &= ~USBCMD_IAAD;
             ehci_set_interrupt(ehci, USBSTS_IAA);
@@ -2281,7 +2304,7 @@ static void ehci_advance_periodic_state(EHCIState *ehci)
         ehci_set_fetch_addr(ehci, async,entry);
         ehci_set_state(ehci, async, EST_FETCHENTRY);
         ehci_advance_state(ehci, async);
-        ehci_queues_rip_unused(ehci, async, 0);
+        ehci_queues_rip_unused(ehci, async);
         break;
 
     default:
commit 4ed1c57a64992d84376b446b0c60edff2486681b
Author: Gerd Hoffmann <kraxel at redhat.com>
Date:   Tue Jun 19 13:53:28 2012 +0200

    ehci: fix td writeback
    
    Only write back the dwords the hc is supposed to update.  Should not
    make a difference in theory as the guest must not touch the td while
    it is active to avoid races.  But it is still more correct.
    
    Signed-off-by: Gerd Hoffmann <kraxel at redhat.com>

diff --git a/hw/usb/hcd-ehci.c b/hw/usb/hcd-ehci.c
index 7de47e5..1406b84 100644
--- a/hw/usb/hcd-ehci.c
+++ b/hw/usb/hcd-ehci.c
@@ -2070,6 +2070,7 @@ out:
 static int ehci_state_writeback(EHCIQueue *q)
 {
     EHCIPacket *p = QTAILQ_FIRST(&q->packets);
+    uint32_t *qtd, addr;
     int again = 0;
 
     /*  Write back the QTD from the QH area */
@@ -2077,8 +2078,9 @@ static int ehci_state_writeback(EHCIQueue *q)
     assert(p->qtdaddr == q->qtdaddr);
 
     ehci_trace_qtd(q, NLPTR_GET(p->qtdaddr), (EHCIqtd *) &q->qh.next_qtd);
-    put_dwords(q->ehci, NLPTR_GET(p->qtdaddr), (uint32_t *) &q->qh.next_qtd,
-               sizeof(EHCIqtd) >> 2);
+    qtd = (uint32_t *) &q->qh.next_qtd;
+    addr = NLPTR_GET(p->qtdaddr);
+    put_dwords(q->ehci, addr + 2 * sizeof(uint32_t), qtd + 2, 2);
     ehci_free_packet(p);
 
     /*
commit a5e0139ab69feec9c9b8a4558369c283685e3f5a
Author: Gerd Hoffmann <kraxel at redhat.com>
Date:   Tue Jun 19 16:23:32 2012 +0200

    ehci: fix ehci_qh_do_overlay
    
    Use ehci_flush_qh to make sure we touch inly the fields the hc is
    allowed to touch.
    
    Signed-off-by: Gerd Hoffmann <kraxel at redhat.com>

diff --git a/hw/usb/hcd-ehci.c b/hw/usb/hcd-ehci.c
index 1582c2c..7de47e5 100644
--- a/hw/usb/hcd-ehci.c
+++ b/hw/usb/hcd-ehci.c
@@ -1246,6 +1246,23 @@ static inline int put_dwords(EHCIState *ehci, uint32_t addr,
     return 1;
 }
 
+/*
+ *  Write the qh back to guest physical memory.  This step isn't
+ *  in the EHCI spec but we need to do it since we don't share
+ *  physical memory with our guest VM.
+ *
+ *  The first three dwords are read-only for the EHCI, so skip them
+ *  when writing back the qh.
+ */
+static void ehci_flush_qh(EHCIQueue *q)
+{
+    uint32_t *qh = (uint32_t *) &q->qh;
+    uint32_t dwords = sizeof(EHCIqh) >> 2;
+    uint32_t addr = NLPTR_GET(q->qhaddr);
+
+    put_dwords(q->ehci, addr + 3 * sizeof(uint32_t), qh + 3, dwords - 3);
+}
+
 // 4.10.2
 
 static int ehci_qh_do_overlay(EHCIQueue *q)
@@ -1293,8 +1310,7 @@ static int ehci_qh_do_overlay(EHCIQueue *q)
     q->qh.bufptr[1] &= ~BUFPTR_CPROGMASK_MASK;
     q->qh.bufptr[2] &= ~BUFPTR_FRAMETAG_MASK;
 
-    put_dwords(q->ehci, NLPTR_GET(q->qhaddr), (uint32_t *) &q->qh,
-               sizeof(EHCIqh) >> 2);
+    ehci_flush_qh(q);
 
     return 0;
 }
@@ -1600,23 +1616,6 @@ static int ehci_process_itd(EHCIState *ehci,
 }
 
 
-/*
- *  Write the qh back to guest physical memory.  This step isn't
- *  in the EHCI spec but we need to do it since we don't share
- *  physical memory with our guest VM.
- *
- *  The first three dwords are read-only for the EHCI, so skip them
- *  when writing back the qh.
- */
-static void ehci_flush_qh(EHCIQueue *q)
-{
-    uint32_t *qh = (uint32_t *) &q->qh;
-    uint32_t dwords = sizeof(EHCIqh) >> 2;
-    uint32_t addr = NLPTR_GET(q->qhaddr);
-
-    put_dwords(q->ehci, addr + 3 * sizeof(uint32_t), qh + 3, dwords - 3);
-}
-
 /*  This state is the entry point for asynchronous schedule
  *  processing.  Entry here consitutes a EHCI start event state (4.8.5)
  */
commit 84988cf910a6881f2180fdcec516b60f8f0dc8c4
Author: Peter Maydell <peter.maydell at linaro.org>
Date:   Fri Jul 6 15:48:00 2012 +0100

    bitops.h: Add functions to extract and deposit bitfields
    
    Add functions deposit32(), deposit64(), extract32() and extract64()
    to extract and deposit bitfields in 32 and 64 bit words. Based on
    ideas by Jia Liu and Avi Kivity.
    
    Suggested-by: Jia Liu <proljc at gmail.com>
    Suggested-by: Avi Kivity <avi at redhat.com>
    Signed-off-by: Peter Maydell <peter.maydell at linaro.org>
    Reviewed-by: Eric Blake <eblake at redhat.com>
    Reviewed-by: Andreas Färber <afaerber at suse.de>
    Signed-off-by: Blue Swirl <blauwirbel at gmail.com>

diff --git a/bitops.h b/bitops.h
index 07d1a06..b967ef3 100644
--- a/bitops.h
+++ b/bitops.h
@@ -269,4 +269,94 @@ static inline unsigned long hweight_long(unsigned long w)
     return count;
 }
 
+/**
+ * extract32:
+ * @value: the value to extract the bit field from
+ * @start: the lowest bit in the bit field (numbered from 0)
+ * @length: the length of the bit field
+ *
+ * Extract from the 32 bit input @value the bit field specified by the
+ * @start and @length parameters, and return it. The bit field must
+ * lie entirely within the 32 bit word. It is valid to request that
+ * all 32 bits are returned (ie @length 32 and @start 0).
+ *
+ * Returns: the value of the bit field extracted from the input value.
+ */
+static inline uint32_t extract32(uint32_t value, int start, int length)
+{
+    assert(start >= 0 && length > 0 && length <= 32 - start);
+    return (value >> start) & (~0U >> (32 - length));
+}
+
+/**
+ * extract64:
+ * @value: the value to extract the bit field from
+ * @start: the lowest bit in the bit field (numbered from 0)
+ * @length: the length of the bit field
+ *
+ * Extract from the 64 bit input @value the bit field specified by the
+ * @start and @length parameters, and return it. The bit field must
+ * lie entirely within the 64 bit word. It is valid to request that
+ * all 64 bits are returned (ie @length 64 and @start 0).
+ *
+ * Returns: the value of the bit field extracted from the input value.
+ */
+static inline uint64_t extract64(uint64_t value, int start, int length)
+{
+    assert(start >= 0 && length > 0 && length <= 64 - start);
+    return (value >> start) & (~0ULL >> (64 - length));
+}
+
+/**
+ * deposit32:
+ * @value: initial value to insert bit field into
+ * @start: the lowest bit in the bit field (numbered from 0)
+ * @length: the length of the bit field
+ * @fieldval: the value to insert into the bit field
+ *
+ * Deposit @fieldval into the 32 bit @value at the bit field specified
+ * by the @start and @length parameters, and return the modified
+ * @value. Bits of @value outside the bit field are not modified.
+ * Bits of @fieldval above the least significant @length bits are
+ * ignored. The bit field must lie entirely within the 32 bit word.
+ * It is valid to request that all 64 bits are modified (ie @length
+ * 64 and @start 0).
+ *
+ * Returns: the modified @value.
+ */
+static inline uint32_t deposit32(uint32_t value, int start, int length,
+                                 uint32_t fieldval)
+{
+    uint32_t mask;
+    assert(start >= 0 && length > 0 && length <= 32 - start);
+    mask = (~0U >> (32 - length)) << start;
+    return (value & ~mask) | ((fieldval << start) & mask);
+}
+
+/**
+ * deposit32:
+ * @value: initial value to insert bit field into
+ * @start: the lowest bit in the bit field (numbered from 0)
+ * @length: the length of the bit field
+ * @fieldval: the value to insert into the bit field
+ *
+ * Deposit @fieldval into the 64 bit @value at the bit field specified
+ * by the @start and @length parameters, and return the modified
+ * @value. Bits of @value outside the bit field are not modified.
+ * Bits of @fieldval above the least significant @length bits are
+ * ignored. The bit field must lie entirely within the 32 bit word.
+ * It is valid to request that all 64 bits are modified (ie @length
+ * 64 and @start 0).
+ *
+ * Returns: the modified @value.
+ */
+static inline uint64_t deposit64(uint64_t value, int start, int length,
+                                 uint64_t fieldval)
+{
+    uint64_t mask;
+    assert(start >= 0 && length > 0 && length <= 64 - start);
+    mask = (~0ULL >> (64 - length)) << start;
+    return (value & ~mask) | ((fieldval << start) & mask);
+}
+
 #endif
commit bedc2ac1a746e61e2a42c98603922c488b82cddb
Author: Peter Maydell <peter.maydell at linaro.org>
Date:   Thu Jul 5 22:29:00 2012 +0100

    target-i386: make it clearer that op table accesses don't overrun
    
    Rephrase some of the expressions used to select an entry
    in the SSE op table arrays so that it's clearer that they
    don't overrun the op table array size.
    
    Signed-off-by: Peter Maydell <peter.maydell at linaro.org>
    Reviewed-by: Stefan Weil <sw at weilnetz.de>
    Signed-off-by: Blue Swirl <blauwirbel at gmail.com>

diff --git a/target-i386/translate.c b/target-i386/translate.c
index 5899e09..1988dae 100644
--- a/target-i386/translate.c
+++ b/target-i386/translate.c
@@ -2964,16 +2964,16 @@ static const SSEFunc_0_pl sse_op_table3aq[] = {
 
 static const SSEFunc_i_p sse_op_table3bi[] = {
     gen_helper_cvttss2si,
-    gen_helper_cvttsd2si,
     gen_helper_cvtss2si,
+    gen_helper_cvttsd2si,
     gen_helper_cvtsd2si
 };
 
 #ifdef TARGET_X86_64
 static const SSEFunc_l_p sse_op_table3bq[] = {
     gen_helper_cvttss2sq,
-    gen_helper_cvttsd2sq,
     gen_helper_cvtss2sq,
+    gen_helper_cvttsd2sq,
     gen_helper_cvtsd2sq
 };
 #endif
@@ -3571,12 +3571,12 @@ static void gen_sse(DisasContext *s, int b, target_ulong pc_start, int rex_r)
             op1_offset = offsetof(CPUX86State,xmm_regs[reg]);
             tcg_gen_addi_ptr(cpu_ptr0, cpu_env, op1_offset);
             if (ot == OT_LONG) {
-                SSEFunc_0_pi sse_fn_pi = sse_op_table3ai[(b >> 8) - 2];
+                SSEFunc_0_pi sse_fn_pi = sse_op_table3ai[(b >> 8) & 1];
                 tcg_gen_trunc_tl_i32(cpu_tmp2_i32, cpu_T[0]);
                 sse_fn_pi(cpu_ptr0, cpu_tmp2_i32);
             } else {
 #ifdef TARGET_X86_64
-                SSEFunc_0_pl sse_fn_pl = sse_op_table3aq[(b >> 8) - 2];
+                SSEFunc_0_pl sse_fn_pl = sse_op_table3aq[(b >> 8) & 1];
                 sse_fn_pl(cpu_ptr0, cpu_T[0]);
 #else
                 goto illegal_op;
@@ -3635,13 +3635,13 @@ static void gen_sse(DisasContext *s, int b, target_ulong pc_start, int rex_r)
             tcg_gen_addi_ptr(cpu_ptr0, cpu_env, op2_offset);
             if (ot == OT_LONG) {
                 SSEFunc_i_p sse_fn_i_p =
-                    sse_op_table3bi[(b >> 8) - 2 + (b & 1) * 2];
+                    sse_op_table3bi[((b >> 7) & 2) | (b & 1)];
                 sse_fn_i_p(cpu_tmp2_i32, cpu_ptr0);
                 tcg_gen_extu_i32_tl(cpu_T[0], cpu_tmp2_i32);
             } else {
 #ifdef TARGET_X86_64
                 SSEFunc_l_p sse_fn_l_p =
-                    sse_op_table3bq[(b >> 8) - 2 + (b & 1) * 2];
+                    sse_op_table3bq[((b >> 7) & 2) | (b & 1)];
                 sse_fn_l_p(cpu_T[0], cpu_ptr0);
 #else
                 goto illegal_op;
commit 96d7073fb058e6f05257cd9041ffbbd736f6ccec
Author: Peter Maydell <peter.maydell at linaro.org>
Date:   Thu Jul 5 22:28:59 2012 +0100

    target-i386: Remove confusing X86_64_DEF macro
    
    The X86_64_DEF macro is a confusing way of making some terms
    in a conditional only appear if TARGET_X86_64 is defined. We
    only use it in two places, and in both cases this is for making
    the same test, so abstract that check out into a function
    where we can use a more conventional #ifdef.
    
    Signed-off-by: Peter Maydell <peter.maydell at linaro.org>
    Signed-off-by: Blue Swirl <blauwirbel at gmail.com>

diff --git a/target-i386/translate.c b/target-i386/translate.c
index 8d696ea..5899e09 100644
--- a/target-i386/translate.c
+++ b/target-i386/translate.c
@@ -38,12 +38,10 @@
 #define PREFIX_ADR    0x10
 
 #ifdef TARGET_X86_64
-#define X86_64_DEF(...)  __VA_ARGS__
 #define CODE64(s) ((s)->code64)
 #define REX_X(s) ((s)->rex_x)
 #define REX_B(s) ((s)->rex_b)
 #else
-#define X86_64_DEF(...)
 #define CODE64(s) 0
 #define REX_X(s) 0
 #define REX_B(s) 0
@@ -265,11 +263,30 @@ static inline void gen_op_andl_A0_ffff(void)
 #define REG_LH_OFFSET 4
 #endif
 
+/* In instruction encodings for byte register accesses the
+ * register number usually indicates "low 8 bits of register N";
+ * however there are some special cases where N 4..7 indicates
+ * [AH, CH, DH, BH], ie "bits 15..8 of register N-4". Return
+ * true for this special case, false otherwise.
+ */
+static inline bool byte_reg_is_xH(int reg)
+{
+    if (reg < 4) {
+        return false;
+    }
+#ifdef TARGET_X86_64
+    if (reg >= 8 || x86_64_hregs) {
+        return false;
+    }
+#endif
+    return true;
+}
+
 static inline void gen_op_mov_reg_v(int ot, int reg, TCGv t0)
 {
     switch(ot) {
     case OT_BYTE:
-        if (reg < 4 X86_64_DEF( || reg >= 8 || x86_64_hregs)) {
+        if (!byte_reg_is_xH(reg)) {
             tcg_gen_deposit_tl(cpu_regs[reg], cpu_regs[reg], t0, 0, 8);
         } else {
             tcg_gen_deposit_tl(cpu_regs[reg - 4], cpu_regs[reg - 4], t0, 8, 8);
@@ -324,19 +341,11 @@ static inline void gen_op_mov_reg_A0(int size, int reg)
 
 static inline void gen_op_mov_v_reg(int ot, TCGv t0, int reg)
 {
-    switch(ot) {
-    case OT_BYTE:
-        if (reg < 4 X86_64_DEF( || reg >= 8 || x86_64_hregs)) {
-            goto std_case;
-        } else {
-            tcg_gen_shri_tl(t0, cpu_regs[reg - 4], 8);
-            tcg_gen_ext8u_tl(t0, t0);
-        }
-        break;
-    default:
-    std_case:
+    if (ot == OT_BYTE && byte_reg_is_xH(reg)) {
+        tcg_gen_shri_tl(t0, cpu_regs[reg - 4], 8);
+        tcg_gen_ext8u_tl(t0, t0);
+    } else {
         tcg_gen_mov_tl(t0, cpu_regs[reg]);
-        break;
     }
 }
 
commit a87dacc89ad7a033578851ca5e0b7525968dbc1c
Author: Peter Maydell <peter.maydell at linaro.org>
Date:   Thu Jul 5 22:28:58 2012 +0100

    target-i386: Remove unused macros
    
    Commit 11f8cdb removed all the uses of the X86_64_ONLY
    macro. The BUGGY_64() macro has been unused for a long time:
    it originally marked some ops which couldn't be enabled
    because of issues with the pre-TCG code generation scheme.
    Remove the now-unnecessary definitions of both macros.
    
    Signed-off-by: Peter Maydell <peter.maydell at linaro.org>
    Reviewed-by: Stefan Weil <sw at weilnetz.de>
    Signed-off-by: Blue Swirl <blauwirbel at gmail.com>

diff --git a/target-i386/translate.c b/target-i386/translate.c
index a00a6a1..8d696ea 100644
--- a/target-i386/translate.c
+++ b/target-i386/translate.c
@@ -38,17 +38,11 @@
 #define PREFIX_ADR    0x10
 
 #ifdef TARGET_X86_64
-#define X86_64_ONLY(x) x
 #define X86_64_DEF(...)  __VA_ARGS__
 #define CODE64(s) ((s)->code64)
 #define REX_X(s) ((s)->rex_x)
 #define REX_B(s) ((s)->rex_b)
-/* XXX: gcc generates push/pop in some opcodes, so we cannot use them */
-#if 1
-#define BUGGY_64(x) NULL
-#endif
 #else
-#define X86_64_ONLY(x) NULL
 #define X86_64_DEF(...)
 #define CODE64(s) 0
 #define REX_X(s) 0
commit eeae63a7aa3ca6a36c90ee2cce770be497fe1377
Author: Eduardo Habkost <ehabkost at redhat.com>
Date:   Wed Jul 4 16:10:47 2012 -0300

    .gitignore update
    
    Makes sure the following files are ignored:
    
      libcacard/.libs/
      libcacard/libcacard.la
      libcacard/libcacard.pc
      libcacard/libcacard/
      libcacard/osdep.lo
      libcacard/oslib-posix.lo
      libcacard/qemu-thread-posix.lo
      libcacard/qemu-timer-common.lo
      libcacard/trace.lo
      libcacard/trace/
      tests/test-visitor-serialization
      vscclient
    
    Signed-off-by: Eduardo Habkost <ehabkost at redhat.com>
    Signed-off-by: Blue Swirl <blauwirbel at gmail.com>

diff --git a/.gitignore b/.gitignore
index 9859c7d..824c0d2 100644
--- a/.gitignore
+++ b/.gitignore
@@ -41,12 +41,14 @@ qemu-io
 qemu-ga
 qemu-bridge-helper
 qemu-monitor.texi
+vscclient
 QMP/qmp-commands.txt
 test-coroutine
 test-qmp-input-visitor
 test-qmp-output-visitor
 test-string-input-visitor
 test-string-output-visitor
+test-visitor-serialization
 fsdev/virtfs-proxy-helper.1
 fsdev/virtfs-proxy-helper.pod
 .gdbinit
@@ -69,6 +71,10 @@ fsdev/virtfs-proxy-helper.pod
 *.vr
 *.d
 *.o
+*.lo
+*.la
+*.pc
+.libs
 *.swp
 *.orig
 .pc
commit fa73f99119f939b8816c889f9a83710d3a74a36a
Merge: 11f8cdb... 8279e04...
Author: Blue Swirl <blauwirbel at gmail.com>
Date:   Sat Jul 7 09:00:38 2012 +0000

    Merge branch 'arm-devs.for-upstream' of git://git.linaro.org/people/pmaydell/qemu-arm
    
    * 'arm-devs.for-upstream' of git://git.linaro.org/people/pmaydell/qemu-arm:
      hw/cadence_gem: Make rx_desc_addr and tx_desc_addr uint32_t
      i.MX31: KZM-ARM11-01 evaluation board
      i.MX31: Interrupt Controller
      i.MX31: Timers
      i.MX31: Clock Control Module
      i.MX: UART support
      Exynos4: add RTC device
      hw/exynos4210.c: Fix misleading initialization of IROM mirror
      hw/exynos4210_pwm.c: Fix STOP status in tick handler.
      ARM: hw/exynos4210_mct.c: Fix a bug which hangs Linux kernel.

commit 11f8cdbc64e44103480b008a155ace2d0b8a8359
Author: Stefan Weil <sw at weilnetz.de>
Date:   Fri Jun 29 22:38:20 2012 +0200

    target-i386: Fix compilation with --enable-debug
    
    commit c4baa0503d9623f1ce891f525ccd140c598bc29a improved SSE table
    type safety which now raises compiler errors when latest QEMU was
    configured with --enable-debug.
    
    Fix this by splitting the SSE tables even further to separate
    helper functions with different signatures.
    
    Instead of crashing by calling address 0, the code now jumps to
    label illegal_op.
    
    Signed-off-by: Stefan Weil <sw at weilnetz.de>
    Reviewed-by: Peter Maydell <peter.maydell at linaro.org>
    Signed-off-by: Blue Swirl <blauwirbel at gmail.com>

diff --git a/target-i386/translate.c b/target-i386/translate.c
index a902f4a..a00a6a1 100644
--- a/target-i386/translate.c
+++ b/target-i386/translate.c
@@ -2947,25 +2947,34 @@ static const SSEFunc_0_pp sse_op_table2[3 * 8][2] = {
     [16 + 7] = { NULL, gen_helper_pslldq_xmm },
 };
 
-static const SSEFunc_0_pi sse_op_table3a[4] = {
+static const SSEFunc_0_pi sse_op_table3ai[] = {
     gen_helper_cvtsi2ss,
-    gen_helper_cvtsi2sd,
-    X86_64_ONLY(gen_helper_cvtsq2ss),
-    X86_64_ONLY(gen_helper_cvtsq2sd),
+    gen_helper_cvtsi2sd
 };
 
-static const SSEFunc_i_p sse_op_table3b[4 * 2] = {
+#ifdef TARGET_X86_64
+static const SSEFunc_0_pl sse_op_table3aq[] = {
+    gen_helper_cvtsq2ss,
+    gen_helper_cvtsq2sd
+};
+#endif
+
+static const SSEFunc_i_p sse_op_table3bi[] = {
     gen_helper_cvttss2si,
     gen_helper_cvttsd2si,
-    X86_64_ONLY(gen_helper_cvttss2sq),
-    X86_64_ONLY(gen_helper_cvttsd2sq),
-
     gen_helper_cvtss2si,
-    gen_helper_cvtsd2si,
-    X86_64_ONLY(gen_helper_cvtss2sq),
-    X86_64_ONLY(gen_helper_cvtsd2sq),
+    gen_helper_cvtsd2si
 };
 
+#ifdef TARGET_X86_64
+static const SSEFunc_l_p sse_op_table3bq[] = {
+    gen_helper_cvttss2sq,
+    gen_helper_cvttsd2sq,
+    gen_helper_cvtss2sq,
+    gen_helper_cvtsd2sq
+};
+#endif
+
 static const SSEFunc_0_pp sse_op_table4[8][4] = {
     SSE_FOP(cmpeq),
     SSE_FOP(cmplt),
@@ -3097,10 +3106,6 @@ static void gen_sse(DisasContext *s, int b, target_ulong pc_start, int rex_r)
 {
     int b1, op1_offset, op2_offset, is_xmm, val, ot;
     int modrm, mod, rm, reg, reg_addr, offset_addr;
-    SSEFunc_i_p sse_fn_i_p;
-    SSEFunc_l_p sse_fn_l_p;
-    SSEFunc_0_pi sse_fn_pi;
-    SSEFunc_0_pl sse_fn_pl;
     SSEFunc_0_pp sse_fn_pp;
     SSEFunc_0_ppi sse_fn_ppi;
     SSEFunc_0_ppt sse_fn_ppt;
@@ -3563,14 +3568,16 @@ static void gen_sse(DisasContext *s, int b, target_ulong pc_start, int rex_r)
             op1_offset = offsetof(CPUX86State,xmm_regs[reg]);
             tcg_gen_addi_ptr(cpu_ptr0, cpu_env, op1_offset);
             if (ot == OT_LONG) {
-                sse_fn_pi = sse_op_table3a[(s->dflag == 2) * 2 +
-                                           ((b >> 8) - 2)];
+                SSEFunc_0_pi sse_fn_pi = sse_op_table3ai[(b >> 8) - 2];
                 tcg_gen_trunc_tl_i32(cpu_tmp2_i32, cpu_T[0]);
                 sse_fn_pi(cpu_ptr0, cpu_tmp2_i32);
             } else {
-                sse_fn_pl = sse_op_table3a[(s->dflag == 2) * 2 +
-                                           ((b >> 8) - 2)];
+#ifdef TARGET_X86_64
+                SSEFunc_0_pl sse_fn_pl = sse_op_table3aq[(b >> 8) - 2];
                 sse_fn_pl(cpu_ptr0, cpu_T[0]);
+#else
+                goto illegal_op;
+#endif
             }
             break;
         case 0x02c: /* cvttps2pi */
@@ -3624,16 +3631,18 @@ static void gen_sse(DisasContext *s, int b, target_ulong pc_start, int rex_r)
             }
             tcg_gen_addi_ptr(cpu_ptr0, cpu_env, op2_offset);
             if (ot == OT_LONG) {
-                sse_fn_i_p = sse_op_table3b[(s->dflag == 2) * 2 +
-                                            ((b >> 8) - 2) +
-                                            (b & 1) * 4];
+                SSEFunc_i_p sse_fn_i_p =
+                    sse_op_table3bi[(b >> 8) - 2 + (b & 1) * 2];
                 sse_fn_i_p(cpu_tmp2_i32, cpu_ptr0);
                 tcg_gen_extu_i32_tl(cpu_T[0], cpu_tmp2_i32);
             } else {
-                sse_fn_l_p = sse_op_table3b[(s->dflag == 2) * 2 +
-                                            ((b >> 8) - 2) +
-                                            (b & 1) * 4];
+#ifdef TARGET_X86_64
+                SSEFunc_l_p sse_fn_l_p =
+                    sse_op_table3bq[(b >> 8) - 2 + (b & 1) * 2];
                 sse_fn_l_p(cpu_T[0], cpu_ptr0);
+#else
+                goto illegal_op;
+#endif
             }
             gen_op_mov_reg_T0(ot, reg);
             break;
commit 7cf1b0fd95657e722b2ad290649eee88d1365786
Author: Alex Williamson <alex.williamson at redhat.com>
Date:   Tue Jul 3 22:39:34 2012 -0600

    pci: Unregister BARs before device exit
    
    BARs are registered in init functions from memory regions created
    by the drivers.  Exit functions destroy those memory regions.
    By unregistering the io regions after exit(), we're calling
    memory_region_del_subregion on freed memory.  Don't do that.  The
    option rom comes along for the ride because it's more symmetric
    to how it's created.
    
    Signed-off-by: Alex Williamson <alex.williamson at redhat.com>
    Signed-off-by: Michael S. Tsirkin <mst at redhat.com>

diff --git a/hw/pci.c b/hw/pci.c
index f783362..ef7607e 100644
--- a/hw/pci.c
+++ b/hw/pci.c
@@ -838,12 +838,13 @@ static int pci_unregister_device(DeviceState *dev)
     PCIDevice *pci_dev = PCI_DEVICE(dev);
     PCIDeviceClass *pc = PCI_DEVICE_GET_CLASS(pci_dev);
 
+    pci_unregister_io_regions(pci_dev);
+    pci_del_option_rom(pci_dev);
+
     if (pc->exit) {
         pc->exit(pci_dev);
     }
 
-    pci_unregister_io_regions(pci_dev);
-    pci_del_option_rom(pci_dev);
     do_pci_unregister_device(pci_dev);
     return 0;
 }
commit f90c2bcdbc69e41e575f868b984c3e2de8f51bac
Author: Alex Williamson <alex.williamson at redhat.com>
Date:   Tue Jul 3 22:39:27 2012 -0600

    pci: convert PCIUnregisterFunc to void
    
    Not a single driver has any possibility of failure on their
    exit function, let's keep it that way.
    
    Signed-off-by: Alex Williamson <alex.williamson at redhat.com>
    Signed-off-by: Michael S. Tsirkin <mst at redhat.com>

diff --git a/hw/ac97.c b/hw/ac97.c
index e791b9d..0f561fa 100644
--- a/hw/ac97.c
+++ b/hw/ac97.c
@@ -1319,13 +1319,12 @@ static int ac97_initfn (PCIDevice *dev)
     return 0;
 }
 
-static int ac97_exitfn (PCIDevice *dev)
+static void ac97_exitfn (PCIDevice *dev)
 {
     AC97LinkState *s = DO_UPCAST (AC97LinkState, dev, dev);
 
     memory_region_destroy (&s->io_nam);
     memory_region_destroy (&s->io_nabm);
-    return 0;
 }
 
 int ac97_init (PCIBus *bus)
diff --git a/hw/e1000.c b/hw/e1000.c
index 4573f13..6c5bc44 100644
--- a/hw/e1000.c
+++ b/hw/e1000.c
@@ -1192,7 +1192,7 @@ e1000_cleanup(VLANClientState *nc)
     s->nic = NULL;
 }
 
-static int
+static void
 pci_e1000_uninit(PCIDevice *dev)
 {
     E1000State *d = DO_UPCAST(E1000State, dev, dev);
@@ -1202,7 +1202,6 @@ pci_e1000_uninit(PCIDevice *dev)
     memory_region_destroy(&d->mmio);
     memory_region_destroy(&d->io);
     qemu_del_vlan_client(&d->nic->nc);
-    return 0;
 }
 
 static NetClientInfo net_e1000_info = {
diff --git a/hw/eepro100.c b/hw/eepro100.c
index 6279ae3..9745ad5 100644
--- a/hw/eepro100.c
+++ b/hw/eepro100.c
@@ -1831,7 +1831,7 @@ static void nic_cleanup(VLANClientState *nc)
     s->nic = NULL;
 }
 
-static int pci_nic_uninit(PCIDevice *pci_dev)
+static void pci_nic_uninit(PCIDevice *pci_dev)
 {
     EEPRO100State *s = DO_UPCAST(EEPRO100State, dev, pci_dev);
 
@@ -1841,7 +1841,6 @@ static int pci_nic_uninit(PCIDevice *pci_dev)
     vmstate_unregister(&pci_dev->qdev, s->vmstate, s);
     eeprom93xx_free(&pci_dev->qdev, s->eeprom);
     qemu_del_vlan_client(&s->nic->nc);
-    return 0;
 }
 
 static NetClientInfo net_eepro100_info = {
diff --git a/hw/es1370.c b/hw/es1370.c
index 573f747..e34234c 100644
--- a/hw/es1370.c
+++ b/hw/es1370.c
@@ -1018,12 +1018,11 @@ static int es1370_initfn (PCIDevice *dev)
     return 0;
 }
 
-static int es1370_exitfn (PCIDevice *dev)
+static void es1370_exitfn (PCIDevice *dev)
 {
     ES1370State *s = DO_UPCAST (ES1370State, dev, dev);
 
     memory_region_destroy (&s->io);
-    return 0;
 }
 
 int es1370_init (PCIBus *bus)
diff --git a/hw/ide/cmd646.c b/hw/ide/cmd646.c
index bf8ece4..4ff3624 100644
--- a/hw/ide/cmd646.c
+++ b/hw/ide/cmd646.c
@@ -295,7 +295,7 @@ static int pci_cmd646_ide_initfn(PCIDevice *dev)
     return 0;
 }
 
-static int pci_cmd646_ide_exitfn(PCIDevice *dev)
+static void pci_cmd646_ide_exitfn(PCIDevice *dev)
 {
     PCIIDEState *d = DO_UPCAST(PCIIDEState, dev, dev);
     unsigned i;
@@ -309,8 +309,6 @@ static int pci_cmd646_ide_exitfn(PCIDevice *dev)
         memory_region_destroy(&d->cmd646_bar[i].data);
     }
     memory_region_destroy(&d->bmdma_bar);
-
-    return 0;
 }
 
 void pci_cmd646_ide_init(PCIBus *bus, DriveInfo **hd_table,
diff --git a/hw/ide/ich.c b/hw/ide/ich.c
index e3eaaea..c3a425b 100644
--- a/hw/ide/ich.c
+++ b/hw/ide/ich.c
@@ -132,15 +132,13 @@ static int pci_ich9_ahci_init(PCIDevice *dev)
     return 0;
 }
 
-static int pci_ich9_uninit(PCIDevice *dev)
+static void pci_ich9_uninit(PCIDevice *dev)
 {
     struct AHCIPCIState *d;
     d = DO_UPCAST(struct AHCIPCIState, card, dev);
 
     msi_uninit(dev);
     ahci_uninit(&d->ahci);
-
-    return 0;
 }
 
 static void ich_ahci_class_init(ObjectClass *klass, void *data)
diff --git a/hw/ide/piix.c b/hw/ide/piix.c
index bcaa400..455c1b2 100644
--- a/hw/ide/piix.c
+++ b/hw/ide/piix.c
@@ -199,7 +199,7 @@ PCIDevice *pci_piix3_xen_ide_init(PCIBus *bus, DriveInfo **hd_table, int devfn)
     return dev;
 }
 
-static int pci_piix_ide_exitfn(PCIDevice *dev)
+static void pci_piix_ide_exitfn(PCIDevice *dev)
 {
     PCIIDEState *d = DO_UPCAST(PCIIDEState, dev, dev);
     unsigned i;
@@ -211,8 +211,6 @@ static int pci_piix_ide_exitfn(PCIDevice *dev)
         memory_region_destroy(&d->bmdma[i].addr_ioport);
     }
     memory_region_destroy(&d->bmdma_bar);
-
-    return 0;
 }
 
 /* hd_table must contain 4 block drivers */
diff --git a/hw/ide/via.c b/hw/ide/via.c
index eec5136..3e25085 100644
--- a/hw/ide/via.c
+++ b/hw/ide/via.c
@@ -189,7 +189,7 @@ static int vt82c686b_ide_initfn(PCIDevice *dev)
     return 0;
 }
 
-static int vt82c686b_ide_exitfn(PCIDevice *dev)
+static void vt82c686b_ide_exitfn(PCIDevice *dev)
 {
     PCIIDEState *d = DO_UPCAST(PCIIDEState, dev, dev);
     unsigned i;
@@ -201,8 +201,6 @@ static int vt82c686b_ide_exitfn(PCIDevice *dev)
         memory_region_destroy(&d->bmdma[i].addr_ioport);
     }
     memory_region_destroy(&d->bmdma_bar);
-
-    return 0;
 }
 
 void vt82c686b_ide_init(PCIBus *bus, DriveInfo **hd_table, int devfn)
diff --git a/hw/intel-hda.c b/hw/intel-hda.c
index 8f3b70b..04bed5e 100644
--- a/hw/intel-hda.c
+++ b/hw/intel-hda.c
@@ -1144,13 +1144,12 @@ static int intel_hda_init(PCIDevice *pci)
     return 0;
 }
 
-static int intel_hda_exit(PCIDevice *pci)
+static void intel_hda_exit(PCIDevice *pci)
 {
     IntelHDAState *d = DO_UPCAST(IntelHDAState, pci, pci);
 
     msi_uninit(&d->pci);
     memory_region_destroy(&d->mmio);
-    return 0;
 }
 
 static int intel_hda_post_load(void *opaque, int version)
diff --git a/hw/ioh3420.c b/hw/ioh3420.c
index 0a2601c..94a537c 100644
--- a/hw/ioh3420.c
+++ b/hw/ioh3420.c
@@ -96,7 +96,6 @@ static int ioh3420_initfn(PCIDevice *d)
     PCIEPort *p = DO_UPCAST(PCIEPort, br, br);
     PCIESlot *s = DO_UPCAST(PCIESlot, port, p);
     int rc;
-    int tmp;
 
     rc = pci_bridge_initfn(d);
     if (rc < 0) {
@@ -144,12 +143,11 @@ err_pcie_cap:
 err_msi:
     msi_uninit(d);
 err_bridge:
-    tmp = pci_bridge_exitfn(d);
-    assert(!tmp);
+    pci_bridge_exitfn(d);
     return rc;
 }
 
-static int ioh3420_exitfn(PCIDevice *d)
+static void ioh3420_exitfn(PCIDevice *d)
 {
     PCIBridge* br = DO_UPCAST(PCIBridge, dev, d);
     PCIEPort *p = DO_UPCAST(PCIEPort, br, br);
@@ -159,7 +157,7 @@ static int ioh3420_exitfn(PCIDevice *d)
     pcie_chassis_del_slot(s);
     pcie_cap_exit(d);
     msi_uninit(d);
-    return pci_bridge_exitfn(d);
+    pci_bridge_exitfn(d);
 }
 
 PCIESlot *ioh3420_init(PCIBus *bus, int devfn, bool multifunction,
diff --git a/hw/ivshmem.c b/hw/ivshmem.c
index 8b49eee..7d4123c 100644
--- a/hw/ivshmem.c
+++ b/hw/ivshmem.c
@@ -760,7 +760,7 @@ static int pci_ivshmem_init(PCIDevice *dev)
     return 0;
 }
 
-static int pci_ivshmem_uninit(PCIDevice *dev)
+static void pci_ivshmem_uninit(PCIDevice *dev)
 {
     IVShmemState *s = DO_UPCAST(IVShmemState, dev, dev);
 
@@ -775,8 +775,6 @@ static int pci_ivshmem_uninit(PCIDevice *dev)
     memory_region_destroy(&s->ivshmem);
     memory_region_destroy(&s->bar);
     unregister_savevm(&dev->qdev, "ivshmem", s);
-
-    return 0;
 }
 
 static Property ivshmem_properties[] = {
diff --git a/hw/lsi53c895a.c b/hw/lsi53c895a.c
index f022a02..9205f65 100644
--- a/hw/lsi53c895a.c
+++ b/hw/lsi53c895a.c
@@ -2070,15 +2070,13 @@ static const VMStateDescription vmstate_lsi_scsi = {
     }
 };
 
-static int lsi_scsi_uninit(PCIDevice *d)
+static void lsi_scsi_uninit(PCIDevice *d)
 {
     LSIState *s = DO_UPCAST(LSIState, dev, d);
 
     memory_region_destroy(&s->mmio_io);
     memory_region_destroy(&s->ram_io);
     memory_region_destroy(&s->io_io);
-
-    return 0;
 }
 
 static const struct SCSIBusInfo lsi_scsi_info = {
diff --git a/hw/ne2000.c b/hw/ne2000.c
index d02e60c..afadbdb 100644
--- a/hw/ne2000.c
+++ b/hw/ne2000.c
@@ -744,14 +744,13 @@ static int pci_ne2000_init(PCIDevice *pci_dev)
     return 0;
 }
 
-static int pci_ne2000_exit(PCIDevice *pci_dev)
+static void pci_ne2000_exit(PCIDevice *pci_dev)
 {
     PCINE2000State *d = DO_UPCAST(PCINE2000State, dev, pci_dev);
     NE2000State *s = &d->ne2000;
 
     memory_region_destroy(&s->io);
     qemu_del_vlan_client(&s->nic->nc);
-    return 0;
 }
 
 static Property ne2000_properties[] = {
diff --git a/hw/pci.c b/hw/pci.c
index d5c664c..f783362 100644
--- a/hw/pci.c
+++ b/hw/pci.c
@@ -837,12 +837,10 @@ static int pci_unregister_device(DeviceState *dev)
 {
     PCIDevice *pci_dev = PCI_DEVICE(dev);
     PCIDeviceClass *pc = PCI_DEVICE_GET_CLASS(pci_dev);
-    int ret = 0;
 
-    if (pc->exit)
-        ret = pc->exit(pci_dev);
-    if (ret)
-        return ret;
+    if (pc->exit) {
+        pc->exit(pci_dev);
+    }
 
     pci_unregister_io_regions(pci_dev);
     pci_del_option_rom(pci_dev);
diff --git a/hw/pci.h b/hw/pci.h
index 44ae871..6983b2f 100644
--- a/hw/pci.h
+++ b/hw/pci.h
@@ -85,7 +85,7 @@ typedef uint32_t PCIConfigReadFunc(PCIDevice *pci_dev,
                                    uint32_t address, int len);
 typedef void PCIMapIORegionFunc(PCIDevice *pci_dev, int region_num,
                                 pcibus_t addr, pcibus_t size, int type);
-typedef int PCIUnregisterFunc(PCIDevice *pci_dev);
+typedef void PCIUnregisterFunc(PCIDevice *pci_dev);
 
 typedef struct PCIIORegion {
     pcibus_t addr; /* current PCI mapping address. -1 means not mapped */
diff --git a/hw/pci_bridge.c b/hw/pci_bridge.c
index e0832b4..0125fd9 100644
--- a/hw/pci_bridge.c
+++ b/hw/pci_bridge.c
@@ -333,7 +333,7 @@ int pci_bridge_initfn(PCIDevice *dev)
 }
 
 /* default qdev clean up function for PCI-to-PCI bridge */
-int pci_bridge_exitfn(PCIDevice *pci_dev)
+void pci_bridge_exitfn(PCIDevice *pci_dev)
 {
     PCIBridge *s = DO_UPCAST(PCIBridge, dev, pci_dev);
     assert(QLIST_EMPTY(&s->sec_bus.child));
@@ -342,7 +342,6 @@ int pci_bridge_exitfn(PCIDevice *pci_dev)
     memory_region_destroy(&s->address_space_mem);
     memory_region_destroy(&s->address_space_io);
     /* qbus_free() is called automatically by qdev_free() */
-    return 0;
 }
 
 /*
diff --git a/hw/pci_bridge.h b/hw/pci_bridge.h
index 84411a6..a00accc 100644
--- a/hw/pci_bridge.h
+++ b/hw/pci_bridge.h
@@ -44,7 +44,7 @@ void pci_bridge_reset_reg(PCIDevice *dev);
 void pci_bridge_reset(DeviceState *qdev);
 
 int pci_bridge_initfn(PCIDevice *pci_dev);
-int pci_bridge_exitfn(PCIDevice *pci_dev);
+void pci_bridge_exitfn(PCIDevice *pci_dev);
 
 
 /*
diff --git a/hw/pci_bridge_dev.c b/hw/pci_bridge_dev.c
index 1cc1d20..f706396 100644
--- a/hw/pci_bridge_dev.c
+++ b/hw/pci_bridge_dev.c
@@ -52,7 +52,8 @@ static int pci_bridge_dev_initfn(PCIDevice *dev)
 {
     PCIBridge *br = DO_UPCAST(PCIBridge, dev, dev);
     PCIBridgeDev *bridge_dev = DO_UPCAST(PCIBridgeDev, bridge, br);
-    int err, ret;
+    int err;
+
     pci_bridge_map_irq(br, NULL, pci_bridge_dev_map_irq_fn);
     err = pci_bridge_initfn(dev);
     if (err) {
@@ -86,26 +87,22 @@ slotid_error:
     shpc_cleanup(dev, &bridge_dev->bar);
 shpc_error:
     memory_region_destroy(&bridge_dev->bar);
-    ret = pci_bridge_exitfn(dev);
-    assert(!ret);
+    pci_bridge_exitfn(dev);
 bridge_error:
     return err;
 }
 
-static int pci_bridge_dev_exitfn(PCIDevice *dev)
+static void pci_bridge_dev_exitfn(PCIDevice *dev)
 {
     PCIBridge *br = DO_UPCAST(PCIBridge, dev, dev);
     PCIBridgeDev *bridge_dev = DO_UPCAST(PCIBridgeDev, bridge, br);
-    int ret;
     if (msi_present(dev)) {
         msi_uninit(dev);
     }
     slotid_cap_cleanup(dev);
     shpc_cleanup(dev, &bridge_dev->bar);
     memory_region_destroy(&bridge_dev->bar);
-    ret = pci_bridge_exitfn(dev);
-    assert(!ret);
-    return 0;
+    pci_bridge_exitfn(dev);
 }
 
 static void pci_bridge_dev_write_config(PCIDevice *d,
diff --git a/hw/pcnet-pci.c b/hw/pcnet-pci.c
index 34d73aa..5439db3 100644
--- a/hw/pcnet-pci.c
+++ b/hw/pcnet-pci.c
@@ -271,7 +271,7 @@ static void pci_pcnet_cleanup(VLANClientState *nc)
     pcnet_common_cleanup(d);
 }
 
-static int pci_pcnet_uninit(PCIDevice *dev)
+static void pci_pcnet_uninit(PCIDevice *dev)
 {
     PCIPCNetState *d = DO_UPCAST(PCIPCNetState, pci_dev, dev);
 
@@ -280,7 +280,6 @@ static int pci_pcnet_uninit(PCIDevice *dev)
     qemu_del_timer(d->state.poll_timer);
     qemu_free_timer(d->state.poll_timer);
     qemu_del_vlan_client(&d->state.nic->nc);
-    return 0;
 }
 
 static NetClientInfo net_pci_pcnet_info = {
diff --git a/hw/rtl8139.c b/hw/rtl8139.c
index 060404c..a7a3f27 100644
--- a/hw/rtl8139.c
+++ b/hw/rtl8139.c
@@ -3427,7 +3427,7 @@ static void rtl8139_cleanup(VLANClientState *nc)
     s->nic = NULL;
 }
 
-static int pci_rtl8139_uninit(PCIDevice *dev)
+static void pci_rtl8139_uninit(PCIDevice *dev)
 {
     RTL8139State *s = DO_UPCAST(RTL8139State, dev, dev);
 
@@ -3440,7 +3440,6 @@ static int pci_rtl8139_uninit(PCIDevice *dev)
     qemu_del_timer(s->timer);
     qemu_free_timer(s->timer);
     qemu_del_vlan_client(&s->nic->nc);
-    return 0;
 }
 
 static NetClientInfo net_rtl8139_info = {
diff --git a/hw/usb/hcd-uhci.c b/hw/usb/hcd-uhci.c
index 9e211a0..04aabd9 100644
--- a/hw/usb/hcd-uhci.c
+++ b/hw/usb/hcd-uhci.c
@@ -1233,12 +1233,11 @@ static int usb_uhci_vt82c686b_initfn(PCIDevice *dev)
     return usb_uhci_common_initfn(dev);
 }
 
-static int usb_uhci_exit(PCIDevice *dev)
+static void usb_uhci_exit(PCIDevice *dev)
 {
     UHCIState *s = DO_UPCAST(UHCIState, dev, dev);
 
     memory_region_destroy(&s->io_bar);
-    return 0;
 }
 
 static Property uhci_properties[] = {
diff --git a/hw/virtio-pci.c b/hw/virtio-pci.c
index 3dca37f..6ed21b7 100644
--- a/hw/virtio-pci.c
+++ b/hw/virtio-pci.c
@@ -828,22 +828,21 @@ static int virtio_blk_init_pci(PCIDevice *pci_dev)
     return 0;
 }
 
-static int virtio_exit_pci(PCIDevice *pci_dev)
+static void virtio_exit_pci(PCIDevice *pci_dev)
 {
     VirtIOPCIProxy *proxy = DO_UPCAST(VirtIOPCIProxy, pci_dev, pci_dev);
 
     memory_region_destroy(&proxy->bar);
     msix_uninit_exclusive_bar(pci_dev);
-    return 0;
 }
 
-static int virtio_blk_exit_pci(PCIDevice *pci_dev)
+static void virtio_blk_exit_pci(PCIDevice *pci_dev)
 {
     VirtIOPCIProxy *proxy = DO_UPCAST(VirtIOPCIProxy, pci_dev, pci_dev);
 
     virtio_pci_stop_ioeventfd(proxy);
     virtio_blk_exit(proxy->vdev);
-    return virtio_exit_pci(pci_dev);
+    virtio_exit_pci(pci_dev);
 }
 
 static int virtio_serial_init_pci(PCIDevice *pci_dev)
@@ -868,13 +867,13 @@ static int virtio_serial_init_pci(PCIDevice *pci_dev)
     return 0;
 }
 
-static int virtio_serial_exit_pci(PCIDevice *pci_dev)
+static void virtio_serial_exit_pci(PCIDevice *pci_dev)
 {
     VirtIOPCIProxy *proxy = DO_UPCAST(VirtIOPCIProxy, pci_dev, pci_dev);
 
     virtio_pci_stop_ioeventfd(proxy);
     virtio_serial_exit(proxy->vdev);
-    return virtio_exit_pci(pci_dev);
+    virtio_exit_pci(pci_dev);
 }
 
 static int virtio_net_init_pci(PCIDevice *pci_dev)
@@ -892,13 +891,13 @@ static int virtio_net_init_pci(PCIDevice *pci_dev)
     return 0;
 }
 
-static int virtio_net_exit_pci(PCIDevice *pci_dev)
+static void virtio_net_exit_pci(PCIDevice *pci_dev)
 {
     VirtIOPCIProxy *proxy = DO_UPCAST(VirtIOPCIProxy, pci_dev, pci_dev);
 
     virtio_pci_stop_ioeventfd(proxy);
     virtio_net_exit(proxy->vdev);
-    return virtio_exit_pci(pci_dev);
+    virtio_exit_pci(pci_dev);
 }
 
 static int virtio_balloon_init_pci(PCIDevice *pci_dev)
@@ -919,13 +918,13 @@ static int virtio_balloon_init_pci(PCIDevice *pci_dev)
     return 0;
 }
 
-static int virtio_balloon_exit_pci(PCIDevice *pci_dev)
+static void virtio_balloon_exit_pci(PCIDevice *pci_dev)
 {
     VirtIOPCIProxy *proxy = DO_UPCAST(VirtIOPCIProxy, pci_dev, pci_dev);
 
     virtio_pci_stop_ioeventfd(proxy);
     virtio_balloon_exit(proxy->vdev);
-    return virtio_exit_pci(pci_dev);
+    virtio_exit_pci(pci_dev);
 }
 
 static Property virtio_blk_properties[] = {
@@ -1074,12 +1073,12 @@ static int virtio_scsi_init_pci(PCIDevice *pci_dev)
     return 0;
 }
 
-static int virtio_scsi_exit_pci(PCIDevice *pci_dev)
+static void virtio_scsi_exit_pci(PCIDevice *pci_dev)
 {
     VirtIOPCIProxy *proxy = DO_UPCAST(VirtIOPCIProxy, pci_dev, pci_dev);
 
     virtio_scsi_exit(proxy->vdev);
-    return virtio_exit_pci(pci_dev);
+    virtio_exit_pci(pci_dev);
 }
 
 static Property virtio_scsi_properties[] = {
diff --git a/hw/wdt_i6300esb.c b/hw/wdt_i6300esb.c
index 15c69db..4a83474 100644
--- a/hw/wdt_i6300esb.c
+++ b/hw/wdt_i6300esb.c
@@ -411,13 +411,11 @@ static int i6300esb_init(PCIDevice *dev)
     return 0;
 }
 
-static int i6300esb_exit(PCIDevice *dev)
+static void i6300esb_exit(PCIDevice *dev)
 {
     I6300State *d = DO_UPCAST(I6300State, dev, dev);
 
     memory_region_destroy(&d->io_mem);
-
-    return 0;
 }
 
 static WatchdogTimerModel model = {
diff --git a/hw/xio3130_downstream.c b/hw/xio3130_downstream.c
index 56d1b35..0d8a5e7 100644
--- a/hw/xio3130_downstream.c
+++ b/hw/xio3130_downstream.c
@@ -60,7 +60,6 @@ static int xio3130_downstream_initfn(PCIDevice *d)
     PCIEPort *p = DO_UPCAST(PCIEPort, br, br);
     PCIESlot *s = DO_UPCAST(PCIESlot, port, p);
     int rc;
-    int tmp;
 
     rc = pci_bridge_initfn(d);
     if (rc < 0) {
@@ -108,12 +107,11 @@ err_pcie_cap:
 err_msi:
     msi_uninit(d);
 err_bridge:
-    tmp = pci_bridge_exitfn(d);
-    assert(!tmp);
+    pci_bridge_exitfn(d);
     return rc;
 }
 
-static int xio3130_downstream_exitfn(PCIDevice *d)
+static void xio3130_downstream_exitfn(PCIDevice *d)
 {
     PCIBridge* br = DO_UPCAST(PCIBridge, dev, d);
     PCIEPort *p = DO_UPCAST(PCIEPort, br, br);
@@ -123,7 +121,7 @@ static int xio3130_downstream_exitfn(PCIDevice *d)
     pcie_chassis_del_slot(s);
     pcie_cap_exit(d);
     msi_uninit(d);
-    return pci_bridge_exitfn(d);
+    pci_bridge_exitfn(d);
 }
 
 PCIESlot *xio3130_downstream_init(PCIBus *bus, int devfn, bool multifunction,
diff --git a/hw/xio3130_upstream.c b/hw/xio3130_upstream.c
index 7972581..d46b86c 100644
--- a/hw/xio3130_upstream.c
+++ b/hw/xio3130_upstream.c
@@ -56,7 +56,6 @@ static int xio3130_upstream_initfn(PCIDevice *d)
     PCIBridge* br = DO_UPCAST(PCIBridge, dev, d);
     PCIEPort *p = DO_UPCAST(PCIEPort, br, br);
     int rc;
-    int tmp;
 
     rc = pci_bridge_initfn(d);
     if (rc < 0) {
@@ -95,17 +94,16 @@ err:
 err_msi:
     msi_uninit(d);
 err_bridge:
-    tmp =  pci_bridge_exitfn(d);
-    assert(!tmp);
+    pci_bridge_exitfn(d);
     return rc;
 }
 
-static int xio3130_upstream_exitfn(PCIDevice *d)
+static void xio3130_upstream_exitfn(PCIDevice *d)
 {
     pcie_aer_exit(d);
     pcie_cap_exit(d);
     msi_uninit(d);
-    return pci_bridge_exitfn(d);
+    pci_bridge_exitfn(d);
 }
 
 PCIEPort *xio3130_upstream_init(PCIBus *bus, int devfn, bool multifunction,
commit 8279e04257de022f40e8aaf2c9b6e55a33c10b26
Author: Peter Maydell <peter.maydell at linaro.org>
Date:   Wed Jul 4 10:50:58 2012 +0000

    hw/cadence_gem: Make rx_desc_addr and tx_desc_addr uint32_t
    
    Make the state fields rx_desc_addr and tx_desc_addr uint32_t;
    this matches the VMStateDescription, and also conforms to how
    hardware works: the registers don't magically become larger
    if the device is attached to a CPU with a larger physical
    address size. It also fixes a compile failure if the
    target_phys_addr_t type is changed to 64 bits.
    
    Signed-off-by: Peter Maydell <peter.maydell at linaro.org>
    Reviewed-by: Peter A. G. Crosthwaite <peter.crosthwaite at petalogix.com>

diff --git a/hw/cadence_gem.c b/hw/cadence_gem.c
index dbde392..87143ca 100644
--- a/hw/cadence_gem.c
+++ b/hw/cadence_gem.c
@@ -339,8 +339,8 @@ typedef struct {
     uint8_t phy_loop; /* Are we in phy loopback? */
 
     /* The current DMA descriptor pointers */
-    target_phys_addr_t rx_desc_addr;
-    target_phys_addr_t tx_desc_addr;
+    uint32_t rx_desc_addr;
+    uint32_t tx_desc_addr;
 
 } GemState;
 
commit 0325559d05f663fcddfbd88bc00224a27008246e
Author: Peter Chubb <peter.chubb at nicta.com.au>
Date:   Wed Jul 4 10:43:34 2012 +0000

    i.MX31: KZM-ARM11-01 evaluation board
    
    Board support for Kyoto Micro's KZM-ARM11-01, an evaluation board built
    around the Freescale i.MX31.
    
    Signed-off-by: Philip O'Sullivan <philipo at ok-labs.com>
    Signed-off-by: Peter Chubb <peter.chubb at nicta.com.au>
    Signed-off-by: Peter Maydell <peter.maydell at linaro.org>

diff --git a/MAINTAINERS b/MAINTAINERS
index 2a514fd..30ed56d 100644
--- a/MAINTAINERS
+++ b/MAINTAINERS
@@ -207,6 +207,12 @@ M: qemu-devel at nongnu.org
 S: Orphan
 F: hw/gumstix.c
 
+i.MX31
+M: Peter Chubb <peter.chubb at nicta.com.au>
+S: Odd fixes
+F: hw/imx*
+F: hw/kzm.c
+
 Integrator CP
 M: Paul Brook <paul at codesourcery.com>
 M: Peter Maydell <peter.maydell at linaro.org>
diff --git a/hw/arm/Makefile.objs b/hw/arm/Makefile.objs
index 15b9357..236786e 100644
--- a/hw/arm/Makefile.objs
+++ b/hw/arm/Makefile.objs
@@ -36,6 +36,7 @@ obj-y += vexpress.o
 obj-y += strongarm.o
 obj-y += collie.o
 obj-y += imx_serial.o imx_ccm.o imx_timer.o imx_avic.o
+obj-y += kzm.o
 obj-y += pl041.o lm4549.o
 obj-$(CONFIG_FDT) += ../device_tree.o
 
diff --git a/hw/kzm.c b/hw/kzm.c
new file mode 100644
index 0000000..08aaf43
--- /dev/null
+++ b/hw/kzm.c
@@ -0,0 +1,154 @@
+/*
+ * KZM Board System emulation.
+ *
+ * Copyright (c) 2008 OKL and 2011 NICTA
+ * Written by Hans at OK-Labs
+ * Updated by Peter Chubb.
+ *
+ * This code is licenced under the GPL, version 2 or later.
+ * See the file `COPYING' in the top level directory.
+ *
+ * It (partially) emulates a Kyoto Microcomputer
+ * KZM-ARM11-01 evaluation board, with a Freescale
+ * i.MX31 SoC
+ */
+
+#include "sysbus.h"
+#include "exec-memory.h"
+#include "hw.h"
+#include "arm-misc.h"
+#include "devices.h"
+#include "net.h"
+#include "sysemu.h"
+#include "boards.h"
+#include "pc.h" /* for the FPGA UART that emulates a 16550 */
+#include "imx.h"
+
+    /* Memory map for Kzm Emulation Baseboard:
+     * 0x00000000-0x00003fff 16k secure ROM       IGNORED
+     * 0x00004000-0x00407fff Reserved             IGNORED
+     * 0x00404000-0x00407fff ROM                  IGNORED
+     * 0x00408000-0x0fffffff Reserved             IGNORED
+     * 0x10000000-0x1fffbfff RAM aliasing         IGNORED
+     * 0x1fffc000-0x1fffffff RAM                  EMULATED
+     * 0x20000000-0x2fffffff Reserved             IGNORED
+     * 0x30000000-0x7fffffff I.MX31 Internal Register Space
+     *   0x43f00000 IO_AREA0
+     *   0x43f90000 UART1                         EMULATED
+     *   0x43f94000 UART2                         EMULATED
+     *   0x68000000 AVIC                          EMULATED
+     *   0x53f80000 CCM                           EMULATED
+     *   0x53f94000 PIT 1                         EMULATED
+     *   0x53f98000 PIT 2                         EMULATED
+     *   0x53f90000 GPT                           EMULATED
+     * 0x80000000-0x87ffffff RAM                  EMULATED
+     * 0x88000000-0x8fffffff RAM Aliasing         EMULATED
+     * 0xa0000000-0xafffffff NAND Flash           IGNORED
+     * 0xb0000000-0xb3ffffff Unavailable          IGNORED
+     * 0xb4000000-0xb4000fff 8-bit free space     IGNORED
+     * 0xb4001000-0xb400100f Board control        IGNORED
+     *  0xb4001003           DIP switch
+     * 0xb4001010-0xb400101f 7-segment LED        IGNORED
+     * 0xb4001020-0xb400102f LED                  IGNORED
+     * 0xb4001030-0xb400103f LED                  IGNORED
+     * 0xb4001040-0xb400104f FPGA, UART           EMULATED
+     * 0xb4001050-0xb400105f FPGA, UART           EMULATED
+     * 0xb4001060-0xb40fffff FPGA                 IGNORED
+     * 0xb6000000-0xb61fffff LAN controller       EMULATED
+     * 0xb6200000-0xb62fffff FPGA NAND Controller IGNORED
+     * 0xb6300000-0xb7ffffff Free                 IGNORED
+     * 0xb8000000-0xb8004fff Memory control registers IGNORED
+     * 0xc0000000-0xc3ffffff PCMCIA/CF            IGNORED
+     * 0xc4000000-0xffffffff Reserved             IGNORED
+     */
+
+#define KZM_RAMADDRESS (0x80000000)
+#define KZM_FPGA       (0xb4001040)
+
+static struct arm_boot_info kzm_binfo = {
+    .loader_start = KZM_RAMADDRESS,
+    .board_id = 1722,
+};
+
+static void kzm_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)
+{
+    ARMCPU *cpu;
+    MemoryRegion *address_space_mem = get_system_memory();
+    MemoryRegion *ram = g_new(MemoryRegion, 1);
+    MemoryRegion *sram = g_new(MemoryRegion, 1);
+    MemoryRegion *ram_alias = g_new(MemoryRegion, 1);
+    qemu_irq *cpu_pic;
+    DeviceState *dev;
+    DeviceState *ccm;
+
+    if (!cpu_model) {
+        cpu_model = "arm1136";
+    }
+
+    cpu = cpu_arm_init(cpu_model);
+    if (!cpu) {
+        fprintf(stderr, "Unable to find CPU definition\n");
+        exit(1);
+    }
+
+    /* On a real system, the first 16k is a `secure boot rom' */
+
+    memory_region_init_ram(ram, "kzm.ram", ram_size);
+    vmstate_register_ram_global(ram);
+    memory_region_add_subregion(address_space_mem, KZM_RAMADDRESS, ram);
+
+    memory_region_init_alias(ram_alias, "ram.alias", ram, 0, ram_size);
+    memory_region_add_subregion(address_space_mem, 0x88000000, ram_alias);
+
+    memory_region_init_ram(sram, "kzm.sram", 0x4000);
+    memory_region_add_subregion(address_space_mem, 0x1FFFC000, sram);
+
+    cpu_pic = arm_pic_init_cpu(cpu);
+    dev = sysbus_create_varargs("imx_avic", 0x68000000,
+                                cpu_pic[ARM_PIC_CPU_IRQ],
+                                cpu_pic[ARM_PIC_CPU_FIQ], NULL);
+
+
+    imx_serial_create(0, 0x43f90000, qdev_get_gpio_in(dev, 45));
+    imx_serial_create(1, 0x43f94000, qdev_get_gpio_in(dev, 32));
+
+    ccm = sysbus_create_simple("imx_ccm", 0x53f80000, NULL);
+
+    imx_timerp_create(0x53f94000, qdev_get_gpio_in(dev, 28), ccm);
+    imx_timerp_create(0x53f98000, qdev_get_gpio_in(dev, 27), ccm);
+    imx_timerg_create(0x53f90000, qdev_get_gpio_in(dev, 29), ccm);
+
+    if (nd_table[0].vlan) {
+        lan9118_init(&nd_table[0], 0xb6000000, qdev_get_gpio_in(dev, 52));
+    }
+
+    if (serial_hds[2]) { /* touchscreen */
+        serial_mm_init(address_space_mem, KZM_FPGA+0x10, 0,
+                       qdev_get_gpio_in(dev, 52),
+                       14745600, serial_hds[2],
+                       DEVICE_NATIVE_ENDIAN);
+    }
+
+    kzm_binfo.ram_size = ram_size;
+    kzm_binfo.kernel_filename = kernel_filename;
+    kzm_binfo.kernel_cmdline = kernel_cmdline;
+    kzm_binfo.initrd_filename = initrd_filename;
+    kzm_binfo.nb_cpus = 1;
+    arm_load_kernel(cpu, &kzm_binfo);
+}
+
+static QEMUMachine kzm_machine = {
+    .name = "kzm",
+    .desc = "ARM KZM Emulation Baseboard (ARM1136)",
+    .init = kzm_init,
+};
+
+static void kzm_machine_init(void)
+{
+    qemu_register_machine(&kzm_machine);
+}
+
+machine_init(kzm_machine_init)
commit ff53d4c661006c56fafa941fcfe4b385fd11d724
Author: Peter Chubb <peter.chubb at nicta.com.au>
Date:   Wed Jul 4 10:43:34 2012 +0000

    i.MX31: Interrupt Controller
    
    Implement the Freescale i.MX31 advanced vectored interrupt controller, at least
    to the extent it is used by Linux 3.x
    
    Vectors are not implemented.
    
    Signed-off-by: Philip O'Sullivan <philipo at ok-labs.com>
    Signed-off-by: Peter Chubb <peter.chubb at nicta.com.au>
    Signed-off-by: Peter Maydell <peter.maydell at linaro.org>

diff --git a/hw/arm/Makefile.objs b/hw/arm/Makefile.objs
index 4109162..15b9357 100644
--- a/hw/arm/Makefile.objs
+++ b/hw/arm/Makefile.objs
@@ -35,7 +35,7 @@ obj-y += framebuffer.o
 obj-y += vexpress.o
 obj-y += strongarm.o
 obj-y += collie.o
-obj-y += imx_serial.o imx_ccm.o imx_timer.o
+obj-y += imx_serial.o imx_ccm.o imx_timer.o imx_avic.o
 obj-y += pl041.o lm4549.o
 obj-$(CONFIG_FDT) += ../device_tree.o
 
diff --git a/hw/imx_avic.c b/hw/imx_avic.c
new file mode 100644
index 0000000..25f47f3
--- /dev/null
+++ b/hw/imx_avic.c
@@ -0,0 +1,408 @@
+/*
+ * i.MX31 Vectored Interrupt Controller
+ *
+ * Note this is NOT the PL192 provided by ARM, but
+ * a custom implementation by Freescale.
+ *
+ * Copyright (c) 2008 OKL
+ * Copyright (c) 2011 NICTA Pty Ltd
+ * Originally Written by Hans Jiang
+ *
+ * This code is licenced under the GPL version 2 or later.  See
+ * the COPYING file in the top-level directory.
+ *
+ * TODO: implement vectors.
+ */
+
+#include "hw.h"
+#include "sysbus.h"
+#include "host-utils.h"
+
+#define DEBUG_INT 1
+#undef DEBUG_INT /* comment out for debugging */
+
+#ifdef DEBUG_INT
+#define DPRINTF(fmt, args...) \
+do { printf("imx_avic: " fmt , ##args); } while (0)
+#else
+#define DPRINTF(fmt, args...) do {} while (0)
+#endif
+
+/*
+ * Define to 1 for messages about attempts to
+ * access unimplemented registers or similar.
+ */
+#define DEBUG_IMPLEMENTATION 1
+#if DEBUG_IMPLEMENTATION
+#  define IPRINTF(fmt, args...) \
+    do  { fprintf(stderr, "imx_avic: " fmt, ##args); } while (0)
+#else
+#  define IPRINTF(fmt, args...) do {} while (0)
+#endif
+
+#define IMX_AVIC_NUM_IRQS 64
+
+/* Interrupt Control Bits */
+#define ABFLAG (1<<25)
+#define ABFEN (1<<24)
+#define NIDIS (1<<22) /* Normal Interrupt disable */
+#define FIDIS (1<<21) /* Fast interrupt disable */
+#define NIAD  (1<<20) /* Normal Interrupt Arbiter Rise ARM level */
+#define FIAD  (1<<19) /* Fast Interrupt Arbiter Rise ARM level */
+#define NM    (1<<18) /* Normal interrupt mode */
+
+
+#define PRIO_PER_WORD (sizeof(uint32_t) * 8 / 4)
+#define PRIO_WORDS (IMX_AVIC_NUM_IRQS/PRIO_PER_WORD)
+
+typedef struct {
+    SysBusDevice busdev;
+    MemoryRegion iomem;
+    uint64_t pending;
+    uint64_t enabled;
+    uint64_t is_fiq;
+    uint32_t intcntl;
+    uint32_t intmask;
+    qemu_irq irq;
+    qemu_irq fiq;
+    uint32_t prio[PRIO_WORDS]; /* Priorities are 4-bits each */
+} IMXAVICState;
+
+static const VMStateDescription vmstate_imx_avic = {
+    .name = "imx-avic",
+    .version_id = 1,
+    .minimum_version_id = 1,
+    .minimum_version_id_old = 1,
+    .fields = (VMStateField[]) {
+        VMSTATE_UINT64(pending, IMXAVICState),
+        VMSTATE_UINT64(enabled, IMXAVICState),
+        VMSTATE_UINT64(is_fiq, IMXAVICState),
+        VMSTATE_UINT32(intcntl, IMXAVICState),
+        VMSTATE_UINT32(intmask, IMXAVICState),
+        VMSTATE_UINT32_ARRAY(prio, IMXAVICState, PRIO_WORDS),
+        VMSTATE_END_OF_LIST()
+    },
+};
+
+
+
+static inline int imx_avic_prio(IMXAVICState *s, int irq)
+{
+    uint32_t word = irq / PRIO_PER_WORD;
+    uint32_t part = 4 * (irq % PRIO_PER_WORD);
+    return 0xf & (s->prio[word] >> part);
+}
+
+static inline void imx_avic_set_prio(IMXAVICState *s, int irq, int prio)
+{
+    uint32_t word = irq / PRIO_PER_WORD;
+    uint32_t part = 4 * (irq % PRIO_PER_WORD);
+    uint32_t mask = ~(0xf << part);
+    s->prio[word] &= mask;
+    s->prio[word] |= prio << part;
+}
+
+/* Update interrupts.  */
+static void imx_avic_update(IMXAVICState *s)
+{
+    int i;
+    uint64_t new = s->pending & s->enabled;
+    uint64_t flags;
+
+    flags = new & s->is_fiq;
+    qemu_set_irq(s->fiq, !!flags);
+
+    flags = new & ~s->is_fiq;
+    if (!flags || (s->intmask == 0x1f)) {
+        qemu_set_irq(s->irq, !!flags);
+        return;
+    }
+
+    /*
+     * Take interrupt if there's a pending interrupt with
+     * priority higher than the value of intmask
+     */
+    for (i = 0; i < IMX_AVIC_NUM_IRQS; i++) {
+        if (flags & (1UL << i)) {
+            if (imx_avic_prio(s, i) > s->intmask) {
+                qemu_set_irq(s->irq, 1);
+                return;
+            }
+        }
+    }
+    qemu_set_irq(s->irq, 0);
+}
+
+static void imx_avic_set_irq(void *opaque, int irq, int level)
+{
+    IMXAVICState *s = (IMXAVICState *)opaque;
+
+    if (level) {
+        DPRINTF("Raising IRQ %d, prio %d\n",
+                irq, imx_avic_prio(s, irq));
+        s->pending |= (1ULL << irq);
+    } else {
+        DPRINTF("Clearing IRQ %d, prio %d\n",
+                irq, imx_avic_prio(s, irq));
+        s->pending &= ~(1ULL << irq);
+    }
+
+    imx_avic_update(s);
+}
+
+
+static uint64_t imx_avic_read(void *opaque,
+                             target_phys_addr_t offset, unsigned size)
+{
+    IMXAVICState *s = (IMXAVICState *)opaque;
+
+
+    DPRINTF("read(offset = 0x%x)\n", offset >> 2);
+    switch (offset >> 2) {
+    case 0: /* INTCNTL */
+        return s->intcntl;
+
+    case 1: /* Normal Interrupt Mask Register, NIMASK */
+        return s->intmask;
+
+    case 2: /* Interrupt Enable Number Register, INTENNUM */
+    case 3: /* Interrupt Disable Number Register, INTDISNUM */
+        return 0;
+
+    case 4: /* Interrupt Enabled Number Register High */
+        return s->enabled >> 32;
+
+    case 5: /* Interrupt Enabled Number Register Low */
+        return s->enabled & 0xffffffffULL;
+
+    case 6: /* Interrupt Type Register High */
+        return s->is_fiq >> 32;
+
+    case 7: /* Interrupt Type Register Low */
+        return s->is_fiq & 0xffffffffULL;
+
+    case 8: /* Normal Interrupt Priority Register 7 */
+    case 9: /* Normal Interrupt Priority Register 6 */
+    case 10:/* Normal Interrupt Priority Register 5 */
+    case 11:/* Normal Interrupt Priority Register 4 */
+    case 12:/* Normal Interrupt Priority Register 3 */
+    case 13:/* Normal Interrupt Priority Register 2 */
+    case 14:/* Normal Interrupt Priority Register 1 */
+    case 15:/* Normal Interrupt Priority Register 0 */
+        return s->prio[15-(offset>>2)];
+
+    case 16: /* Normal interrupt vector and status register */
+    {
+        /*
+         * This returns the highest priority
+         * outstanding interrupt.  Where there is more than
+         * one pending IRQ with the same priority,
+         * take the highest numbered one.
+         */
+        uint64_t flags = s->pending & s->enabled & ~s->is_fiq;
+        int i;
+        int prio = -1;
+        int irq = -1;
+        for (i = 63; i >= 0; --i) {
+            if (flags & (1ULL<<i)) {
+                int irq_prio = imx_avic_prio(s, i);
+                if (irq_prio > prio) {
+                    irq = i;
+                    prio = irq_prio;
+                }
+            }
+        }
+        if (irq >= 0) {
+            imx_avic_set_irq(s, irq, 0);
+            return irq << 16 | prio;
+        }
+        return 0xffffffffULL;
+    }
+    case 17:/* Fast Interrupt vector and status register */
+    {
+        uint64_t flags = s->pending & s->enabled & s->is_fiq;
+        int i = ctz64(flags);
+        if (i < 64) {
+            imx_avic_set_irq(opaque, i, 0);
+            return i;
+        }
+        return 0xffffffffULL;
+    }
+    case 18:/* Interrupt source register high */
+        return s->pending >> 32;
+
+    case 19:/* Interrupt source register low */
+        return s->pending & 0xffffffffULL;
+
+    case 20:/* Interrupt Force Register high */
+    case 21:/* Interrupt Force Register low */
+        return 0;
+
+    case 22:/* Normal Interrupt Pending Register High */
+        return (s->pending & s->enabled & ~s->is_fiq) >> 32;
+
+    case 23:/* Normal Interrupt Pending Register Low */
+        return (s->pending & s->enabled & ~s->is_fiq) & 0xffffffffULL;
+
+    case 24: /* Fast Interrupt Pending Register High  */
+        return (s->pending & s->enabled & s->is_fiq) >> 32;
+
+    case 25: /* Fast Interrupt Pending Register Low  */
+        return (s->pending & s->enabled & s->is_fiq) & 0xffffffffULL;
+
+    case 0x40:            /* AVIC vector 0, use for WFI WAR */
+        return 0x4;
+
+    default:
+        IPRINTF("imx_avic_read: Bad offset 0x%x\n", (int)offset);
+        return 0;
+    }
+}
+
+static void imx_avic_write(void *opaque, target_phys_addr_t offset,
+                          uint64_t val, unsigned size)
+{
+    IMXAVICState *s = (IMXAVICState *)opaque;
+
+    /* Vector Registers not yet supported */
+    if (offset >= 0x100 && offset <= 0x2fc) {
+        IPRINTF("imx_avic_write to vector register %d ignored\n",
+                (offset - 0x100) >> 2);
+        return;
+    }
+
+    DPRINTF("imx_avic_write(0x%x) = %x\n",
+            (unsigned int)offset>>2, (unsigned int)val);
+    switch (offset >> 2) {
+    case 0: /* Interrupt Control Register, INTCNTL */
+        s->intcntl = val & (ABFEN | NIDIS | FIDIS | NIAD | FIAD | NM);
+        if (s->intcntl & ABFEN) {
+            s->intcntl &= ~(val & ABFLAG);
+        }
+        break;
+
+    case 1: /* Normal Interrupt Mask Register, NIMASK */
+        s->intmask = val & 0x1f;
+        break;
+
+    case 2: /* Interrupt Enable Number Register, INTENNUM */
+        DPRINTF("enable(%d)\n", (int)val);
+        val &= 0x3f;
+        s->enabled |= (1ULL << val);
+        break;
+
+    case 3: /* Interrupt Disable Number Register, INTDISNUM */
+        DPRINTF("disable(%d)\n", (int)val);
+        val &= 0x3f;
+        s->enabled &= ~(1ULL << val);
+        break;
+
+    case 4: /* Interrupt Enable Number Register High */
+        s->enabled = (s->enabled & 0xffffffffULL) | (val << 32);
+        break;
+
+    case 5: /* Interrupt Enable Number Register Low */
+        s->enabled = (s->enabled & 0xffffffff00000000ULL) | val;
+        break;
+
+    case 6: /* Interrupt Type Register High */
+        s->is_fiq = (s->is_fiq & 0xffffffffULL) | (val << 32);
+        break;
+
+    case 7: /* Interrupt Type Register Low */
+        s->is_fiq = (s->is_fiq & 0xffffffff00000000ULL) | val;
+        break;
+
+    case 8: /* Normal Interrupt Priority Register 7 */
+    case 9: /* Normal Interrupt Priority Register 6 */
+    case 10:/* Normal Interrupt Priority Register 5 */
+    case 11:/* Normal Interrupt Priority Register 4 */
+    case 12:/* Normal Interrupt Priority Register 3 */
+    case 13:/* Normal Interrupt Priority Register 2 */
+    case 14:/* Normal Interrupt Priority Register 1 */
+    case 15:/* Normal Interrupt Priority Register 0 */
+        s->prio[15-(offset>>2)] = val;
+        break;
+
+        /* Read-only registers, writes ignored */
+    case 16:/* Normal Interrupt Vector and Status register */
+    case 17:/* Fast Interrupt vector and status register */
+    case 18:/* Interrupt source register high */
+    case 19:/* Interrupt source register low */
+        return;
+
+    case 20:/* Interrupt Force Register high */
+        s->pending = (s->pending & 0xffffffffULL) | (val << 32);
+        break;
+
+    case 21:/* Interrupt Force Register low */
+        s->pending = (s->pending & 0xffffffff00000000ULL) | val;
+        break;
+
+    case 22:/* Normal Interrupt Pending Register High */
+    case 23:/* Normal Interrupt Pending Register Low */
+    case 24: /* Fast Interrupt Pending Register High  */
+    case 25: /* Fast Interrupt Pending Register Low  */
+        return;
+
+    default:
+        IPRINTF("imx_avic_write: Bad offset %x\n", (int)offset);
+    }
+    imx_avic_update(s);
+}
+
+static const MemoryRegionOps imx_avic_ops = {
+    .read = imx_avic_read,
+    .write = imx_avic_write,
+    .endianness = DEVICE_NATIVE_ENDIAN,
+};
+
+static void imx_avic_reset(DeviceState *dev)
+{
+    IMXAVICState *s = container_of(dev, IMXAVICState, busdev.qdev);
+    s->pending = 0;
+    s->enabled = 0;
+    s->is_fiq = 0;
+    s->intmask = 0x1f;
+    s->intcntl = 0;
+    memset(s->prio, 0, sizeof s->prio);
+}
+
+static int imx_avic_init(SysBusDevice *dev)
+{
+    IMXAVICState *s = FROM_SYSBUS(IMXAVICState, dev);;
+
+    memory_region_init_io(&s->iomem, &imx_avic_ops, s, "imx_avic", 0x1000);
+    sysbus_init_mmio(dev, &s->iomem);
+
+    qdev_init_gpio_in(&dev->qdev, imx_avic_set_irq, IMX_AVIC_NUM_IRQS);
+    sysbus_init_irq(dev, &s->irq);
+    sysbus_init_irq(dev, &s->fiq);
+
+    return 0;
+}
+
+
+static void imx_avic_class_init(ObjectClass *klass, void *data)
+{
+    DeviceClass *dc = DEVICE_CLASS(klass);
+    SysBusDeviceClass *k = SYS_BUS_DEVICE_CLASS(klass);
+    k->init = imx_avic_init;
+    dc->vmsd = &vmstate_imx_avic;
+    dc->reset = imx_avic_reset;
+    dc->desc = "i.MX Advanced Vector Interrupt Controller";
+}
+
+static const TypeInfo imx_avic_info = {
+    .name = "imx_avic",
+    .parent = TYPE_SYS_BUS_DEVICE,
+    .instance_size = sizeof(IMXAVICState),
+    .class_init = imx_avic_class_init,
+};
+
+static void imx_avic_register_types(void)
+{
+    type_register_static(&imx_avic_info);
+}
+
+type_init(imx_avic_register_types)
commit 78d1404dcc9082fa52240cd04f822d54566d6849
Author: Peter Chubb <peter.chubb at nicta.com.au>
Date:   Wed Jul 4 10:43:33 2012 +0000

    i.MX31: Timers
    
    Implement the timers on the Freescale i.MX31 SoC.
    This is not a complete implementation, but gives enough for
    Linux to boot and run. In particular external triggers, which are
    not useful under QEMU, are not implemented.
    
    Signed-off-by: Philip O'Sullivan <philipo at ok-labs.com>
    Signed-off-by: Peter Chubb <peter.chubb at nicta.com.au>
    Signed-off-by: Peter Maydell <peter.maydell at linaro.org>

diff --git a/hw/arm/Makefile.objs b/hw/arm/Makefile.objs
index 110f2f1..4109162 100644
--- a/hw/arm/Makefile.objs
+++ b/hw/arm/Makefile.objs
@@ -35,7 +35,7 @@ obj-y += framebuffer.o
 obj-y += vexpress.o
 obj-y += strongarm.o
 obj-y += collie.o
-obj-y += imx_serial.o imx_ccm.o
+obj-y += imx_serial.o imx_ccm.o imx_timer.o
 obj-y += pl041.o lm4549.o
 obj-$(CONFIG_FDT) += ../device_tree.o
 
diff --git a/hw/imx.h b/hw/imx.h
index 707e943..ccf586f 100644
--- a/hw/imx.h
+++ b/hw/imx.h
@@ -23,4 +23,12 @@ typedef enum  {
 
 uint32_t imx_clock_frequency(DeviceState *s, IMXClk clock);
 
+void imx_timerp_create(const target_phys_addr_t addr,
+                      qemu_irq irq,
+                      DeviceState *ccm);
+void imx_timerg_create(const target_phys_addr_t addr,
+                      qemu_irq irq,
+                      DeviceState *ccm);
+
+
 #endif /* IMX_H */
diff --git a/hw/imx_timer.c b/hw/imx_timer.c
new file mode 100644
index 0000000..16215cc
--- /dev/null
+++ b/hw/imx_timer.c
@@ -0,0 +1,689 @@
+/*
+ * IMX31 Timer
+ *
+ * Copyright (c) 2008 OK Labs
+ * Copyright (c) 2011 NICTA Pty Ltd
+ * Originally Written by Hans Jiang
+ * Updated by Peter Chubb
+ *
+ * This code is licenced under GPL version 2 or later.  See
+ * the COPYING file in the top-level directory.
+ *
+ */
+
+#include "hw.h"
+#include "qemu-timer.h"
+#include "ptimer.h"
+#include "sysbus.h"
+#include "imx.h"
+
+//#define DEBUG_TIMER 1
+#ifdef DEBUG_TIMER
+#  define DPRINTF(fmt, args...) \
+      do { printf("imx_timer: " fmt , ##args); } while (0)
+#else
+#  define DPRINTF(fmt, args...) do {} while (0)
+#endif
+
+/*
+ * Define to 1 for messages about attempts to
+ * access unimplemented registers or similar.
+ */
+#define DEBUG_IMPLEMENTATION 1
+#if DEBUG_IMPLEMENTATION
+#  define IPRINTF(fmt, args...)                                         \
+    do  { fprintf(stderr, "imx_timer: " fmt, ##args); } while (0)
+#else
+#  define IPRINTF(fmt, args...) do {} while (0)
+#endif
+
+/*
+ * GPT : General purpose timer
+ *
+ * This timer counts up continuously while it is enabled, resetting itself
+ * to 0 when it reaches TIMER_MAX (in freerun mode) or when it
+ * reaches the value of ocr1 (in periodic mode).  WE simulate this using a
+ * QEMU ptimer counting down from ocr1 and reloading from ocr1 in
+ * periodic mode, or counting from ocr1 to zero, then TIMER_MAX - ocr1.
+ * waiting_rov is set when counting from TIMER_MAX.
+ *
+ * In the real hardware, there are three comparison registers that can
+ * trigger interrupts, and compare channel 1 can be used to
+ * force-reset the timer. However, this is a `bare-bones'
+ * implementation: only what Linux 3.x uses has been implemented
+ * (free-running timer from 0 to OCR1 or TIMER_MAX) .
+ */
+
+
+#define TIMER_MAX  0XFFFFFFFFUL
+
+/* Control register.  Not all of these bits have any effect (yet) */
+#define GPT_CR_EN     (1 << 0)  /* GPT Enable */
+#define GPT_CR_ENMOD  (1 << 1)  /* GPT Enable Mode */
+#define GPT_CR_DBGEN  (1 << 2)  /* GPT Debug mode enable */
+#define GPT_CR_WAITEN (1 << 3)  /* GPT Wait Mode Enable  */
+#define GPT_CR_DOZEN  (1 << 4)  /* GPT Doze mode enable */
+#define GPT_CR_STOPEN (1 << 5)  /* GPT Stop Mode Enable */
+#define GPT_CR_CLKSRC_SHIFT (6)
+#define GPT_CR_CLKSRC_MASK  (0x7)
+
+#define GPT_CR_FRR    (1 << 9)  /* Freerun or Restart */
+#define GPT_CR_SWR    (1 << 15) /* Software Reset */
+#define GPT_CR_IM1    (3 << 16) /* Input capture channel 1 mode (2 bits) */
+#define GPT_CR_IM2    (3 << 18) /* Input capture channel 2 mode (2 bits) */
+#define GPT_CR_OM1    (7 << 20) /* Output Compare Channel 1 Mode (3 bits) */
+#define GPT_CR_OM2    (7 << 23) /* Output Compare Channel 2 Mode (3 bits) */
+#define GPT_CR_OM3    (7 << 26) /* Output Compare Channel 3 Mode (3 bits) */
+#define GPT_CR_FO1    (1 << 29) /* Force Output Compare Channel 1 */
+#define GPT_CR_FO2    (1 << 30) /* Force Output Compare Channel 2 */
+#define GPT_CR_FO3    (1 << 31) /* Force Output Compare Channel 3 */
+
+#define GPT_SR_OF1  (1 << 0)
+#define GPT_SR_ROV  (1 << 5)
+
+#define GPT_IR_OF1IE  (1 << 0)
+#define GPT_IR_ROVIE  (1 << 5)
+
+typedef struct {
+    SysBusDevice busdev;
+    ptimer_state *timer;
+    MemoryRegion iomem;
+    DeviceState *ccm;
+
+    uint32_t cr;
+    uint32_t pr;
+    uint32_t sr;
+    uint32_t ir;
+    uint32_t ocr1;
+    uint32_t cnt;
+
+    uint32_t waiting_rov;
+    qemu_irq irq;
+} IMXTimerGState;
+
+static const VMStateDescription vmstate_imx_timerg = {
+    .name = "imx-timerg",
+    .version_id = 1,
+    .minimum_version_id = 1,
+    .minimum_version_id_old = 1,
+    .fields      = (VMStateField[]) {
+        VMSTATE_UINT32(cr, IMXTimerGState),
+        VMSTATE_UINT32(pr, IMXTimerGState),
+        VMSTATE_UINT32(sr, IMXTimerGState),
+        VMSTATE_UINT32(ir, IMXTimerGState),
+        VMSTATE_UINT32(ocr1, IMXTimerGState),
+        VMSTATE_UINT32(cnt, IMXTimerGState),
+        VMSTATE_UINT32(waiting_rov, IMXTimerGState),
+        VMSTATE_PTIMER(timer, IMXTimerGState),
+        VMSTATE_END_OF_LIST()
+    }
+};
+
+static const IMXClk imx_timerg_clocks[] = {
+    NOCLK,    /* 000 No clock source */
+    IPG,      /* 001 ipg_clk, 532MHz*/
+    IPG,      /* 010 ipg_clk_highfreq */
+    NOCLK,    /* 011 not defined */
+    CLK_32k,  /* 100 ipg_clk_32k */
+    NOCLK,    /* 101 not defined */
+    NOCLK,    /* 110 not defined */
+    NOCLK,    /* 111 not defined */
+};
+
+
+static void imx_timerg_set_freq(IMXTimerGState *s)
+{
+    int clksrc;
+    uint32_t freq;
+
+    clksrc = (s->cr >> GPT_CR_CLKSRC_SHIFT) & GPT_CR_CLKSRC_MASK;
+    freq = imx_clock_frequency(s->ccm, imx_timerg_clocks[clksrc]) / (1 + s->pr);
+
+    DPRINTF("Setting gtimer clksrc %d to frequency %d\n", clksrc, freq);
+    if (freq) {
+        ptimer_set_freq(s->timer, freq);
+    }
+}
+
+static void imx_timerg_update(IMXTimerGState *s)
+{
+    uint32_t flags = s->sr & s->ir & (GPT_SR_OF1 | GPT_SR_ROV);
+
+    DPRINTF("g-timer SR: %s %s IR=%s %s, %s\n",
+            s->sr & GPT_SR_OF1 ? "OF1" : "",
+            s->sr & GPT_SR_ROV ? "ROV" : "",
+            s->ir & GPT_SR_OF1 ? "OF1" : "",
+            s->ir & GPT_SR_ROV ? "ROV" : "",
+            s->cr & GPT_CR_EN ? "CR_EN" : "Not Enabled");
+
+
+    qemu_set_irq(s->irq, (s->cr & GPT_CR_EN) && flags);
+}
+
+static uint32_t imx_timerg_update_counts(IMXTimerGState *s)
+{
+    uint64_t target = s->waiting_rov ? TIMER_MAX : s->ocr1;
+    uint64_t cnt = ptimer_get_count(s->timer);
+    s->cnt = target - cnt;
+    return s->cnt;
+}
+
+static void imx_timerg_reload(IMXTimerGState *s, uint32_t timeout)
+{
+    uint64_t diff_cnt;
+
+    if (!(s->cr & GPT_CR_FRR)) {
+        IPRINTF("IMX_timerg_reload --- called in reset-mode\n");
+        return;
+    }
+
+    /*
+     * For small timeouts, qemu sometimes runs too slow.
+     * Better deliver a late interrupt than none.
+     *
+     * In Reset mode (FRR bit clear)
+     * the ptimer reloads itself from OCR1;
+     * in free-running mode we need to fake
+     * running from 0 to ocr1 to TIMER_MAX
+     */
+    if (timeout > s->cnt) {
+        diff_cnt = timeout - s->cnt;
+    } else {
+        diff_cnt = 0;
+    }
+    ptimer_set_count(s->timer, diff_cnt);
+}
+
+static uint64_t imx_timerg_read(void *opaque, target_phys_addr_t offset,
+                                unsigned size)
+{
+    IMXTimerGState *s = (IMXTimerGState *)opaque;
+
+    DPRINTF("g-read(offset=%x)", offset >> 2);
+    switch (offset >> 2) {
+    case 0: /* Control Register */
+        DPRINTF(" cr = %x\n", s->cr);
+        return s->cr;
+
+    case 1: /* prescaler */
+        DPRINTF(" pr = %x\n", s->pr);
+        return s->pr;
+
+    case 2: /* Status Register */
+        DPRINTF(" sr = %x\n", s->sr);
+        return s->sr;
+
+    case 3: /* Interrupt Register */
+        DPRINTF(" ir = %x\n", s->ir);
+        return s->ir;
+
+    case 4: /* Output Compare Register 1 */
+        DPRINTF(" ocr1 = %x\n", s->ocr1);
+        return s->ocr1;
+
+
+    case 9: /* cnt */
+        imx_timerg_update_counts(s);
+        DPRINTF(" cnt = %x\n", s->cnt);
+        return s->cnt;
+    }
+
+    IPRINTF("imx_timerg_read: Bad offset %x\n",
+            (int)offset >> 2);
+    return 0;
+}
+
+static void imx_timerg_reset(DeviceState *dev)
+{
+    IMXTimerGState *s = container_of(dev, IMXTimerGState, busdev.qdev);
+
+    /*
+     * Soft reset doesn't touch some bits; hard reset clears them
+     */
+    s->cr &= ~(GPT_CR_EN|GPT_CR_DOZEN|GPT_CR_WAITEN|GPT_CR_DBGEN);
+    s->sr = 0;
+    s->pr = 0;
+    s->ir = 0;
+    s->cnt = 0;
+    s->ocr1 = TIMER_MAX;
+    ptimer_stop(s->timer);
+    ptimer_set_limit(s->timer, TIMER_MAX, 1);
+    imx_timerg_set_freq(s);
+}
+
+static void imx_timerg_write(void *opaque, target_phys_addr_t offset,
+                             uint64_t value, unsigned size)
+{
+    IMXTimerGState *s = (IMXTimerGState *)opaque;
+    DPRINTF("g-write(offset=%x, value = 0x%x)\n", (unsigned int)offset >> 2,
+            (unsigned int)value);
+
+    switch (offset >> 2) {
+    case 0: {
+        uint32_t oldcr = s->cr;
+        /* CR */
+        if (value & GPT_CR_SWR) { /* force reset */
+            value &= ~GPT_CR_SWR;
+            imx_timerg_reset(&s->busdev.qdev);
+            imx_timerg_update(s);
+        }
+
+        s->cr = value & ~0x7c00;
+        imx_timerg_set_freq(s);
+        if ((oldcr ^ value) & GPT_CR_EN) {
+            if (value & GPT_CR_EN) {
+                if (value & GPT_CR_ENMOD) {
+                    ptimer_set_count(s->timer, s->ocr1);
+                    s->cnt = 0;
+                }
+                ptimer_run(s->timer,
+                           (value & GPT_CR_FRR) && (s->ocr1 != TIMER_MAX));
+            } else {
+                ptimer_stop(s->timer);
+            };
+        }
+        return;
+    }
+
+    case 1: /* Prescaler */
+        s->pr = value & 0xfff;
+        imx_timerg_set_freq(s);
+        return;
+
+    case 2: /* SR */
+        /*
+         * No point in implementing the status register bits to do with
+         * external interrupt sources.
+         */
+        value &= GPT_SR_OF1 | GPT_SR_ROV;
+        s->sr &= ~value;
+        imx_timerg_update(s);
+        return;
+
+    case 3: /* IR -- interrupt register */
+        s->ir = value & 0x3f;
+        imx_timerg_update(s);
+        return;
+
+    case 4: /* OCR1 -- output compare register */
+        /* In non-freerun mode, reset count when this register is written */
+        if (!(s->cr & GPT_CR_FRR)) {
+            s->waiting_rov = 0;
+            ptimer_set_limit(s->timer, value, 1);
+        } else {
+            imx_timerg_update_counts(s);
+            if (value > s->cnt) {
+                s->waiting_rov = 0;
+                imx_timerg_reload(s, value);
+            } else {
+                s->waiting_rov = 1;
+                imx_timerg_reload(s, TIMER_MAX - s->cnt);
+            }
+        }
+        s->ocr1 = value;
+        return;
+
+    default:
+        IPRINTF("imx_timerg_write: Bad offset %x\n",
+                (int)offset >> 2);
+    }
+}
+
+static void imx_timerg_timeout(void *opaque)
+{
+    IMXTimerGState *s = (IMXTimerGState *)opaque;
+
+    DPRINTF("imx_timerg_timeout, waiting rov=%d\n", s->waiting_rov);
+    if (s->cr & GPT_CR_FRR) {
+        /*
+         * Free running timer from 0 -> TIMERMAX
+         * Generates interrupt at TIMER_MAX and at cnt==ocr1
+         * If ocr1 == TIMER_MAX, then no need to reload timer.
+         */
+        if (s->ocr1 == TIMER_MAX) {
+            DPRINTF("s->ocr1 == TIMER_MAX, FRR\n");
+            s->sr |= GPT_SR_OF1 | GPT_SR_ROV;
+            imx_timerg_update(s);
+            return;
+        }
+
+        if (s->waiting_rov) {
+            /*
+             * We were waiting for cnt==TIMER_MAX
+             */
+            s->sr |= GPT_SR_ROV;
+            s->waiting_rov = 0;
+            s->cnt = 0;
+            imx_timerg_reload(s, s->ocr1);
+        } else {
+            /* Must have got a cnt==ocr1 timeout. */
+            s->sr |= GPT_SR_OF1;
+            s->cnt = s->ocr1;
+            s->waiting_rov = 1;
+            imx_timerg_reload(s, TIMER_MAX);
+        }
+        imx_timerg_update(s);
+        return;
+    }
+
+    s->sr |= GPT_SR_OF1;
+    imx_timerg_update(s);
+}
+
+static const MemoryRegionOps imx_timerg_ops = {
+    .read = imx_timerg_read,
+    .write = imx_timerg_write,
+    .endianness = DEVICE_NATIVE_ENDIAN,
+};
+
+
+static int imx_timerg_init(SysBusDevice *dev)
+{
+    IMXTimerGState *s = FROM_SYSBUS(IMXTimerGState, dev);
+    QEMUBH *bh;
+
+    sysbus_init_irq(dev, &s->irq);
+    memory_region_init_io(&s->iomem, &imx_timerg_ops,
+                          s, "imxg-timer",
+                          0x00001000);
+    sysbus_init_mmio(dev, &s->iomem);
+
+    bh = qemu_bh_new(imx_timerg_timeout, s);
+    s->timer = ptimer_init(bh);
+
+    /* Hard reset resets extra bits in CR */
+    s->cr = 0;
+    return 0;
+}
+
+
+
+/*
+ * EPIT: Enhanced periodic interrupt timer
+ */
+
+#define CR_EN       (1 << 0)
+#define CR_ENMOD    (1 << 1)
+#define CR_OCIEN    (1 << 2)
+#define CR_RLD      (1 << 3)
+#define CR_PRESCALE_SHIFT (4)
+#define CR_PRESCALE_MASK  (0xfff)
+#define CR_SWR      (1 << 16)
+#define CR_IOVW     (1 << 17)
+#define CR_DBGEN    (1 << 18)
+#define CR_EPIT     (1 << 19)
+#define CR_DOZEN    (1 << 20)
+#define CR_STOPEN   (1 << 21)
+#define CR_CLKSRC_SHIFT (24)
+#define CR_CLKSRC_MASK  (0x3 << CR_CLKSRC_SHIFT)
+
+
+/*
+ * Exact clock frequencies vary from board to board.
+ * These are typical.
+ */
+static const IMXClk imx_timerp_clocks[] =  {
+    0,        /* disabled */
+    IPG, /* ipg_clk, ~532MHz */
+    IPG, /* ipg_clk_highfreq */
+    CLK_32k,    /* ipg_clk_32k -- ~32kHz */
+};
+
+typedef struct {
+    SysBusDevice busdev;
+    ptimer_state *timer;
+    MemoryRegion iomem;
+    DeviceState *ccm;
+
+    uint32_t cr;
+    uint32_t lr;
+    uint32_t cmp;
+
+    uint32_t freq;
+    int int_level;
+    qemu_irq irq;
+} IMXTimerPState;
+
+/*
+ * Update interrupt status
+ */
+static void imx_timerp_update(IMXTimerPState *s)
+{
+    if (s->int_level && (s->cr & CR_OCIEN)) {
+        qemu_irq_raise(s->irq);
+    } else {
+        qemu_irq_lower(s->irq);
+    }
+}
+
+static void imx_timerp_reset(DeviceState *dev)
+{
+    IMXTimerPState *s = container_of(dev, IMXTimerPState, busdev.qdev);
+
+    s->cr = 0;
+    s->lr = TIMER_MAX;
+    s->int_level = 0;
+    s->cmp = 0;
+    ptimer_stop(s->timer);
+    ptimer_set_count(s->timer, TIMER_MAX);
+}
+
+static uint64_t imx_timerp_read(void *opaque, target_phys_addr_t offset,
+                                unsigned size)
+{
+    IMXTimerPState *s = (IMXTimerPState *)opaque;
+
+    DPRINTF("p-read(offset=%x)", offset >> 2);
+    switch (offset >> 2) {
+    case 0: /* Control Register */
+        DPRINTF("cr %x\n", s->cr);
+        return s->cr;
+
+    case 1: /* Status Register */
+        DPRINTF("int_level %x\n", s->int_level);
+        return s->int_level;
+
+    case 2: /* LR - ticks*/
+        DPRINTF("lr %x\n", s->lr);
+        return s->lr;
+
+    case 3: /* CMP */
+        DPRINTF("cmp %x\n", s->cmp);
+        return s->cmp;
+
+    case 4: /* CNT */
+        return ptimer_get_count(s->timer);
+    }
+    IPRINTF("imx_timerp_read: Bad offset %x\n",
+            (int)offset >> 2);
+    return 0;
+}
+
+static void set_timerp_freq(IMXTimerPState *s)
+{
+    int clksrc;
+    unsigned prescaler;
+    uint32_t freq;
+
+    clksrc = (s->cr & CR_CLKSRC_MASK) >> CR_CLKSRC_SHIFT;
+    prescaler = 1 + ((s->cr >> CR_PRESCALE_SHIFT) & CR_PRESCALE_MASK);
+    freq = imx_clock_frequency(s->ccm, imx_timerp_clocks[clksrc]) / prescaler;
+
+    s->freq = freq;
+    DPRINTF("Setting ptimer frequency to %u\n", freq);
+
+    if (freq) {
+        ptimer_set_freq(s->timer, freq);
+    }
+}
+
+static void imx_timerp_write(void *opaque, target_phys_addr_t offset,
+                             uint64_t value, unsigned size)
+{
+    IMXTimerPState *s = (IMXTimerPState *)opaque;
+    DPRINTF("p-write(offset=%x, value = %x)\n", (unsigned int)offset >> 2,
+            (unsigned int)value);
+
+    switch (offset >> 2) {
+    case 0: /* CR */
+        if (value & CR_SWR) {
+            imx_timerp_reset(&s->busdev.qdev);
+            value &= ~CR_SWR;
+        }
+        s->cr = value & 0x03ffffff;
+        set_timerp_freq(s);
+
+        if (s->freq && (s->cr & CR_EN)) {
+            if (!(s->cr & CR_ENMOD)) {
+                ptimer_set_count(s->timer, s->lr);
+            }
+            ptimer_run(s->timer, 0);
+        } else {
+            ptimer_stop(s->timer);
+        }
+        break;
+
+    case 1: /* SR - ACK*/
+        s->int_level = 0;
+        imx_timerp_update(s);
+        break;
+
+    case 2: /* LR - set ticks */
+        s->lr = value;
+        ptimer_set_limit(s->timer, value, !!(s->cr & CR_IOVW));
+        break;
+
+    case 3: /* CMP */
+        s->cmp = value;
+        if (value) {
+            IPRINTF(
+                "Values for EPIT comparison other than zero not supported\n"
+            );
+        }
+        break;
+
+    default:
+        IPRINTF("imx_timerp_write: Bad offset %x\n",
+                   (int)offset >> 2);
+    }
+}
+
+static void imx_timerp_tick(void *opaque)
+{
+    IMXTimerPState *s = (IMXTimerPState *)opaque;
+
+   DPRINTF("imxp tick\n");
+    if (!(s->cr & CR_RLD)) {
+        ptimer_set_count(s->timer, TIMER_MAX);
+    }
+    s->int_level = 1;
+    imx_timerp_update(s);
+}
+
+void imx_timerp_create(const target_phys_addr_t addr,
+                              qemu_irq irq,
+                              DeviceState *ccm)
+{
+    IMXTimerPState *pp;
+    DeviceState *dev;
+
+    dev = sysbus_create_simple("imx_timerp", addr, irq);
+    pp = container_of(dev, IMXTimerPState, busdev.qdev);
+    pp->ccm = ccm;
+}
+
+static const MemoryRegionOps imx_timerp_ops = {
+  .read = imx_timerp_read,
+  .write = imx_timerp_write,
+  .endianness = DEVICE_NATIVE_ENDIAN,
+};
+
+static const VMStateDescription vmstate_imx_timerp = {
+    .name = "imx-timerp",
+    .version_id = 1,
+    .minimum_version_id = 1,
+    .minimum_version_id_old = 1,
+    .fields      = (VMStateField[]) {
+        VMSTATE_UINT32(cr, IMXTimerPState),
+        VMSTATE_UINT32(lr, IMXTimerPState),
+        VMSTATE_UINT32(cmp, IMXTimerPState),
+        VMSTATE_UINT32(freq, IMXTimerPState),
+        VMSTATE_INT32(int_level, IMXTimerPState),
+        VMSTATE_PTIMER(timer, IMXTimerPState),
+        VMSTATE_END_OF_LIST()
+    }
+};
+
+static int imx_timerp_init(SysBusDevice *dev)
+{
+    IMXTimerPState *s = FROM_SYSBUS(IMXTimerPState, dev);
+    QEMUBH *bh;
+
+    DPRINTF("imx_timerp_init\n");
+
+    sysbus_init_irq(dev, &s->irq);
+    memory_region_init_io(&s->iomem, &imx_timerp_ops,
+                          s, "imxp-timer",
+                          0x00001000);
+    sysbus_init_mmio(dev, &s->iomem);
+
+    bh = qemu_bh_new(imx_timerp_tick, s);
+    s->timer = ptimer_init(bh);
+
+    return 0;
+}
+
+
+void imx_timerg_create(const target_phys_addr_t addr,
+                              qemu_irq irq,
+                              DeviceState *ccm)
+{
+    IMXTimerGState *pp;
+    DeviceState *dev;
+
+    dev = sysbus_create_simple("imx_timerg", addr, irq);
+    pp = container_of(dev, IMXTimerGState, busdev.qdev);
+    pp->ccm = ccm;
+}
+
+static void imx_timerg_class_init(ObjectClass *klass, void *data)
+{
+    DeviceClass *dc  = DEVICE_CLASS(klass);
+    SysBusDeviceClass *k = SYS_BUS_DEVICE_CLASS(klass);
+    k->init = imx_timerg_init;
+    dc->vmsd = &vmstate_imx_timerg;
+    dc->reset = imx_timerg_reset;
+    dc->desc = "i.MX general timer";
+}
+
+static void imx_timerp_class_init(ObjectClass *klass, void *data)
+{
+    DeviceClass *dc  = DEVICE_CLASS(klass);
+    SysBusDeviceClass *k = SYS_BUS_DEVICE_CLASS(klass);
+    k->init = imx_timerp_init;
+    dc->vmsd = &vmstate_imx_timerp;
+    dc->reset = imx_timerp_reset;
+    dc->desc = "i.MX periodic timer";
+}
+
+static const TypeInfo imx_timerp_info = {
+    .name = "imx_timerp",
+    .parent = TYPE_SYS_BUS_DEVICE,
+    .instance_size = sizeof(IMXTimerPState),
+    .class_init = imx_timerp_class_init,
+};
+
+static const TypeInfo imx_timerg_info = {
+    .name = "imx_timerg",
+    .parent = TYPE_SYS_BUS_DEVICE,
+    .instance_size = sizeof(IMXTimerGState),
+    .class_init = imx_timerg_class_init,
+};
+
+static void imx_timer_register_types(void)
+{
+    type_register_static(&imx_timerp_info);
+    type_register_static(&imx_timerg_info);
+}
+
+type_init(imx_timer_register_types)
commit bcc181b0ad84bfa2369f39c55c63752820d49284
Author: Peter Chubb <peter.chubb at nicta.com.au>
Date:   Wed Jul 4 10:43:33 2012 +0000

    i.MX31: Clock Control Module
    
    For Linux to be able to work out how fast its clocks are going, so
    that timer ticks come approximately at the right time, it needs to
    be able to query the clock control module (CCM).
    
    This is the start of a CCM implementation.  It currently knows only about
    the MCU, HSP and IPG clocks --- i.e., the ones used to feed the periodic
    and general purpose timers.
    
    Signed-off-by: Peter Chubb <peter.chubb at nicta.com.au>
    Signed-off-by: Peter Maydell <peter.maydell at linaro.org>

diff --git a/hw/arm/Makefile.objs b/hw/arm/Makefile.objs
index 2f8ff9a..110f2f1 100644
--- a/hw/arm/Makefile.objs
+++ b/hw/arm/Makefile.objs
@@ -35,7 +35,7 @@ obj-y += framebuffer.o
 obj-y += vexpress.o
 obj-y += strongarm.o
 obj-y += collie.o
-obj-y += imx_serial.o
+obj-y += imx_serial.o imx_ccm.o
 obj-y += pl041.o lm4549.o
 obj-$(CONFIG_FDT) += ../device_tree.o
 
diff --git a/hw/imx.h b/hw/imx.h
index c1023cc..707e943 100644
--- a/hw/imx.h
+++ b/hw/imx.h
@@ -13,4 +13,14 @@
 
 void imx_serial_create(int uart, const target_phys_addr_t addr, qemu_irq irq);
 
+typedef enum  {
+    NOCLK,
+    MCU,
+    HSP,
+    IPG,
+    CLK_32k
+} IMXClk;
+
+uint32_t imx_clock_frequency(DeviceState *s, IMXClk clock);
+
 #endif /* IMX_H */
diff --git a/hw/imx_ccm.c b/hw/imx_ccm.c
new file mode 100644
index 0000000..10952c6
--- /dev/null
+++ b/hw/imx_ccm.c
@@ -0,0 +1,321 @@
+/*
+ * IMX31 Clock Control Module
+ *
+ * Copyright (C) 2012 NICTA
+ *
+ * This work is licensed under the terms of the GNU GPL, version 2 or later.
+ * See the COPYING file in the top-level directory.
+ *
+ * To get the timer frequencies right, we need to emulate at least part of
+ * the CCM.
+ */
+
+#include "hw.h"
+#include "sysbus.h"
+#include "sysemu.h"
+#include "imx.h"
+
+#define CKIH_FREQ 26000000 /* 26MHz crystal input */
+#define CKIL_FREQ    32768 /* nominal 32khz clock */
+
+
+//#define DEBUG_CCM 1
+#ifdef DEBUG_CCM
+#define DPRINTF(fmt, args...) \
+do { printf("imx_ccm: " fmt , ##args); } while (0)
+#else
+#define DPRINTF(fmt, args...) do {} while (0)
+#endif
+
+static int imx_ccm_post_load(void *opaque, int version_id);
+
+typedef struct {
+    SysBusDevice busdev;
+    MemoryRegion iomem;
+
+    uint32_t ccmr;
+    uint32_t pdr0;
+    uint32_t pdr1;
+    uint32_t mpctl;
+    uint32_t spctl;
+    uint32_t cgr[3];
+    uint32_t pmcr0;
+    uint32_t pmcr1;
+
+    /* Frequencies precalculated on register changes */
+    uint32_t pll_refclk_freq;
+    uint32_t mcu_clk_freq;
+    uint32_t hsp_clk_freq;
+    uint32_t ipg_clk_freq;
+} IMXCCMState;
+
+static const VMStateDescription vmstate_imx_ccm = {
+    .name = "imx-ccm",
+    .version_id = 1,
+    .minimum_version_id = 1,
+    .minimum_version_id_old = 1,
+    .fields = (VMStateField[]) {
+        VMSTATE_UINT32(ccmr, IMXCCMState),
+        VMSTATE_UINT32(pdr0, IMXCCMState),
+        VMSTATE_UINT32(pdr1, IMXCCMState),
+        VMSTATE_UINT32(mpctl, IMXCCMState),
+        VMSTATE_UINT32(spctl, IMXCCMState),
+        VMSTATE_UINT32_ARRAY(cgr, IMXCCMState, 3),
+        VMSTATE_UINT32(pmcr0, IMXCCMState),
+        VMSTATE_UINT32(pmcr1, IMXCCMState),
+        VMSTATE_UINT32(pll_refclk_freq, IMXCCMState),
+    },
+    .post_load = imx_ccm_post_load,
+};
+
+/* CCMR */
+#define CCMR_FPME (1<<0)
+#define CCMR_MPE  (1<<3)
+#define CCMR_MDS  (1<<7)
+#define CCMR_FPMF (1<<26)
+#define CCMR_PRCS (3<<1)
+
+/* PDR0 */
+#define PDR0_MCU_PODF_SHIFT (0)
+#define PDR0_MCU_PODF_MASK (0x7)
+#define PDR0_MAX_PODF_SHIFT (3)
+#define PDR0_MAX_PODF_MASK (0x7)
+#define PDR0_IPG_PODF_SHIFT (6)
+#define PDR0_IPG_PODF_MASK (0x3)
+#define PDR0_NFC_PODF_SHIFT (8)
+#define PDR0_NFC_PODF_MASK (0x7)
+#define PDR0_HSP_PODF_SHIFT (11)
+#define PDR0_HSP_PODF_MASK (0x7)
+#define PDR0_PER_PODF_SHIFT (16)
+#define PDR0_PER_PODF_MASK (0x1f)
+#define PDR0_CSI_PODF_SHIFT (23)
+#define PDR0_CSI_PODF_MASK (0x1ff)
+
+#define EXTRACT(value, name) (((value) >> PDR0_##name##_PODF_SHIFT) \
+                              & PDR0_##name##_PODF_MASK)
+#define INSERT(value, name) (((value) & PDR0_##name##_PODF_MASK) << \
+                             PDR0_##name##_PODF_SHIFT)
+/* PLL control registers */
+#define PD(v) (((v) >> 26) & 0xf)
+#define MFD(v) (((v) >> 16) & 0x3ff)
+#define MFI(v) (((v) >> 10) & 0xf);
+#define MFN(v) ((v) & 0x3ff)
+
+#define PLL_PD(x)               (((x) & 0xf) << 26)
+#define PLL_MFD(x)              (((x) & 0x3ff) << 16)
+#define PLL_MFI(x)              (((x) & 0xf) << 10)
+#define PLL_MFN(x)              (((x) & 0x3ff) << 0)
+
+uint32_t imx_clock_frequency(DeviceState *dev, IMXClk clock)
+{
+    IMXCCMState *s = container_of(dev, IMXCCMState, busdev.qdev);
+
+    switch (clock) {
+    case NOCLK:
+        return 0;
+    case MCU:
+        return s->mcu_clk_freq;
+    case HSP:
+        return s->hsp_clk_freq;
+    case IPG:
+        return s->ipg_clk_freq;
+    case CLK_32k:
+        return CKIL_FREQ;
+    }
+    return 0;
+}
+
+/*
+ * Calculate PLL output frequency
+ */
+static uint32_t calc_pll(uint32_t pllreg, uint32_t base_freq)
+{
+    int32_t mfn = MFN(pllreg);  /* Numerator */
+    uint32_t mfi = MFI(pllreg); /* Integer part */
+    uint32_t mfd = 1 + MFD(pllreg); /* Denominator */
+    uint32_t pd = 1 + PD(pllreg);   /* Pre-divider */
+
+    if (mfi < 5) {
+        mfi = 5;
+    }
+    /* mfn is 10-bit signed twos-complement */
+    mfn <<= 32 - 10;
+    mfn >>= 32 - 10;
+
+    return ((2 * (base_freq >> 10) * (mfi * mfd + mfn)) /
+            (mfd * pd)) << 10;
+}
+
+static void update_clocks(IMXCCMState *s)
+{
+    /*
+     * If we ever emulate more clocks, this should switch to a data-driven
+     * approach
+     */
+
+    if ((s->ccmr & CCMR_PRCS) == 1) {
+        s->pll_refclk_freq = CKIL_FREQ * 1024;
+    } else {
+        s->pll_refclk_freq = CKIH_FREQ;
+    }
+
+    /* ipg_clk_arm aka MCU clock */
+    if ((s->ccmr & CCMR_MDS) || !(s->ccmr & CCMR_MPE)) {
+        s->mcu_clk_freq = s->pll_refclk_freq;
+    } else {
+        s->mcu_clk_freq = calc_pll(s->mpctl, s->pll_refclk_freq);
+    }
+
+    /* High-speed clock */
+    s->hsp_clk_freq = s->mcu_clk_freq / (1 + EXTRACT(s->pdr0, HSP));
+    s->ipg_clk_freq = s->hsp_clk_freq / (1 + EXTRACT(s->pdr0, IPG));
+
+    DPRINTF("Clocks: mcu %uMHz, HSP %uMHz, IPG %uHz\n",
+            s->mcu_clk_freq / 1000000,
+            s->hsp_clk_freq / 1000000,
+            s->ipg_clk_freq);
+}
+
+static void imx_ccm_reset(DeviceState *dev)
+{
+    IMXCCMState *s = container_of(dev, IMXCCMState, busdev.qdev);
+
+    s->ccmr = 0x074b0b7b;
+    s->pdr0 = 0xff870b48;
+    s->pdr1 = 0x49fcfe7f;
+    s->mpctl = PLL_PD(1) | PLL_MFD(0) | PLL_MFI(6) | PLL_MFN(0);
+    s->cgr[0] = s->cgr[1] = s->cgr[2] = 0xffffffff;
+    s->spctl = PLL_PD(1) | PLL_MFD(4) | PLL_MFI(0xc) | PLL_MFN(1);
+    s->pmcr0 = 0x80209828;
+
+    update_clocks(s);
+}
+
+static uint64_t imx_ccm_read(void *opaque, target_phys_addr_t offset,
+                                unsigned size)
+{
+    IMXCCMState *s = (IMXCCMState *)opaque;
+
+    DPRINTF("read(offset=%x)", offset >> 2);
+    switch (offset >> 2) {
+    case 0: /* CCMR */
+        DPRINTF(" ccmr = 0x%x\n", s->ccmr);
+        return s->ccmr;
+    case 1:
+        DPRINTF(" pdr0 = 0x%x\n", s->pdr0);
+        return s->pdr0;
+    case 2:
+        DPRINTF(" pdr1 = 0x%x\n", s->pdr1);
+        return s->pdr1;
+    case 4:
+        DPRINTF(" mpctl = 0x%x\n", s->mpctl);
+        return s->mpctl;
+    case 6:
+        DPRINTF(" spctl = 0x%x\n", s->spctl);
+        return s->spctl;
+    case 8:
+        DPRINTF(" cgr0 = 0x%x\n", s->cgr[0]);
+        return s->cgr[0];
+    case 9:
+        DPRINTF(" cgr1 = 0x%x\n", s->cgr[1]);
+        return s->cgr[1];
+    case 10:
+        DPRINTF(" cgr2 = 0x%x\n", s->cgr[2]);
+        return s->cgr[2];
+    case 18: /* LTR1 */
+        return 0x00004040;
+    case 23:
+        DPRINTF(" pcmr0 = 0x%x\n", s->pmcr0);
+        return s->pmcr0;
+    }
+    DPRINTF(" return 0\n");
+    return 0;
+}
+
+static void imx_ccm_write(void *opaque, target_phys_addr_t offset,
+                          uint64_t value, unsigned size)
+{
+    IMXCCMState *s = (IMXCCMState *)opaque;
+
+    DPRINTF("write(offset=%x, value = %x)\n",
+            offset >> 2, (unsigned int)value);
+    switch (offset >> 2) {
+    case 0:
+        s->ccmr = CCMR_FPMF | (value & 0x3b6fdfff);
+        break;
+    case 1:
+        s->pdr0 = value & 0xff9f3fff;
+        break;
+    case 2:
+        s->pdr1 = value;
+        break;
+    case 4:
+        s->mpctl = value & 0xbfff3fff;
+        break;
+    case 6:
+        s->spctl = value & 0xbfff3fff;
+        break;
+    case 8:
+        s->cgr[0] = value;
+        return;
+    case 9:
+        s->cgr[1] = value;
+        return;
+    case 10:
+        s->cgr[2] = value;
+        return;
+
+    default:
+        return;
+    }
+    update_clocks(s);
+}
+
+static const struct MemoryRegionOps imx_ccm_ops = {
+    .read = imx_ccm_read,
+    .write = imx_ccm_write,
+    .endianness = DEVICE_NATIVE_ENDIAN,
+};
+
+static int imx_ccm_init(SysBusDevice *dev)
+{
+    IMXCCMState *s = FROM_SYSBUS(typeof(*s), dev);
+
+    memory_region_init_io(&s->iomem, &imx_ccm_ops, s, "imx_ccm", 0x1000);
+    sysbus_init_mmio(dev, &s->iomem);
+
+    return 0;
+}
+
+static int imx_ccm_post_load(void *opaque, int version_id)
+{
+    IMXCCMState *s = (IMXCCMState *)opaque;
+
+    update_clocks(s);
+    return 0;
+}
+
+static void imx_ccm_class_init(ObjectClass *klass, void *data)
+{
+    DeviceClass *dc = DEVICE_CLASS(klass);
+    SysBusDeviceClass *sbc = SYS_BUS_DEVICE_CLASS(klass);
+
+    sbc->init = imx_ccm_init;
+    dc->reset = imx_ccm_reset;
+    dc->vmsd = &vmstate_imx_ccm;
+    dc->desc = "i.MX Clock Control Module";
+}
+
+static TypeInfo imx_ccm_info = {
+    .name = "imx_ccm",
+    .parent = TYPE_SYS_BUS_DEVICE,
+    .instance_size = sizeof(IMXCCMState),
+    .class_init = imx_ccm_class_init,
+};
+
+static void imx_ccm_register_types(void)
+{
+    type_register_static(&imx_ccm_info);
+}
+
+type_init(imx_ccm_register_types)
commit 40b6f91151e7538ffeec5316300030140b09c16c
Author: Peter Chubb <peter.chubb at nicta.com.au>
Date:   Wed Jul 4 10:43:33 2012 +0000

    i.MX: UART support
    
    Implement the Freescale i.MX UART.  This uart is used in a variety of
    SoCs, including some by Motorola, as well as in the Freescale i.MX
    series.
    
    This patch gives only a `bare-bones' implementation, enough to run Linux
    or OKL4, but that's about it.
    
    Signed-off-by: Philip O'Sullivan <philipo at ok-labs.com>
    Signed-off-by: Peter Chubb <peter.chubb at nicta.com.au>
    Signed-off-by: Peter Maydell <peter.maydell at linaro.org>

diff --git a/hw/arm/Makefile.objs b/hw/arm/Makefile.objs
index 0fdb832..2f8ff9a 100644
--- a/hw/arm/Makefile.objs
+++ b/hw/arm/Makefile.objs
@@ -35,6 +35,7 @@ obj-y += framebuffer.o
 obj-y += vexpress.o
 obj-y += strongarm.o
 obj-y += collie.o
+obj-y += imx_serial.o
 obj-y += pl041.o lm4549.o
 obj-$(CONFIG_FDT) += ../device_tree.o
 
diff --git a/hw/imx.h b/hw/imx.h
new file mode 100644
index 0000000..c1023cc
--- /dev/null
+++ b/hw/imx.h
@@ -0,0 +1,16 @@
+/*
+ * i.MX31 emulation
+ *
+ * Copyright (C) 2012 Peter Chubb
+ * NICTA
+ *
+ * This code is released under the GPL, version 2.0 or later
+ * See the file `../COPYING' for details.
+ */
+
+#ifndef IMX_H
+#define IMX_H
+
+void imx_serial_create(int uart, const target_phys_addr_t addr, qemu_irq irq);
+
+#endif /* IMX_H */
diff --git a/hw/imx_serial.c b/hw/imx_serial.c
new file mode 100644
index 0000000..d4eae43
--- /dev/null
+++ b/hw/imx_serial.c
@@ -0,0 +1,467 @@
+/*
+ * IMX31 UARTS
+ *
+ * Copyright (c) 2008 OKL
+ * Originally Written by Hans Jiang
+ * Copyright (c) 2011 NICTA Pty Ltd.
+ *
+ * This work is licensed under the terms of the GNU GPL, version 2 or later.
+ * See the COPYING file in the top-level directory.
+ *
+ * This is a `bare-bones' implementation of the IMX series serial ports.
+ * TODO:
+ *  -- implement FIFOs.  The real hardware has 32 word transmit
+ *                       and receive FIFOs; we currently use a 1-char buffer
+ *  -- implement DMA
+ *  -- implement BAUD-rate and modem lines, for when the backend
+ *     is a real serial device.
+ */
+
+#include "hw.h"
+#include "sysbus.h"
+#include "sysemu.h"
+#include "qemu-char.h"
+#include "imx.h"
+
+//#define DEBUG_SERIAL 1
+#ifdef DEBUG_SERIAL
+#define DPRINTF(fmt, args...) \
+do { printf("imx_serial: " fmt , ##args); } while (0)
+#else
+#define DPRINTF(fmt, args...) do {} while (0)
+#endif
+
+/*
+ * Define to 1 for messages about attempts to
+ * access unimplemented registers or similar.
+ */
+//#define DEBUG_IMPLEMENTATION 1
+#ifdef DEBUG_IMPLEMENTATION
+#  define IPRINTF(fmt, args...) \
+    do  { fprintf(stderr, "imx_serial: " fmt, ##args); } while (0)
+#else
+#  define IPRINTF(fmt, args...) do {} while (0)
+#endif
+
+typedef struct {
+    SysBusDevice busdev;
+    MemoryRegion iomem;
+    int32_t readbuff;
+
+    uint32_t usr1;
+    uint32_t usr2;
+    uint32_t ucr1;
+    uint32_t ucr2;
+    uint32_t uts1;
+
+    /*
+     * The registers below are implemented just so that the
+     * guest OS sees what it has written
+     */
+    uint32_t onems;
+    uint32_t ufcr;
+    uint32_t ubmr;
+    uint32_t ubrc;
+    uint32_t ucr3;
+
+    qemu_irq irq;
+    CharDriverState *chr;
+} IMXSerialState;
+
+static const VMStateDescription vmstate_imx_serial = {
+    .name = "imx-serial",
+    .version_id = 1,
+    .minimum_version_id = 1,
+    .minimum_version_id_old = 1,
+    .fields = (VMStateField[]) {
+        VMSTATE_INT32(readbuff, IMXSerialState),
+        VMSTATE_UINT32(usr1, IMXSerialState),
+        VMSTATE_UINT32(usr2, IMXSerialState),
+        VMSTATE_UINT32(ucr1, IMXSerialState),
+        VMSTATE_UINT32(uts1, IMXSerialState),
+        VMSTATE_UINT32(onems, IMXSerialState),
+        VMSTATE_UINT32(ufcr, IMXSerialState),
+        VMSTATE_UINT32(ubmr, IMXSerialState),
+        VMSTATE_UINT32(ubrc, IMXSerialState),
+        VMSTATE_UINT32(ucr3, IMXSerialState),
+        VMSTATE_END_OF_LIST()
+    },
+};
+
+
+#define URXD_CHARRDY    (1<<15)   /* character read is valid */
+#define URXD_ERR        (1<<14)   /* Character has error */
+#define URXD_BRK        (1<<11)   /* Break received */
+
+#define USR1_PARTYER    (1<<15)   /* Parity Error */
+#define USR1_RTSS       (1<<14)   /* RTS pin status */
+#define USR1_TRDY       (1<<13)   /* Tx ready */
+#define USR1_RTSD       (1<<12)   /* RTS delta: pin changed state */
+#define USR1_ESCF       (1<<11)   /* Escape sequence interrupt */
+#define USR1_FRAMERR    (1<<10)   /* Framing error  */
+#define USR1_RRDY       (1<<9)    /* receiver ready */
+#define USR1_AGTIM      (1<<8)    /* Aging timer interrupt */
+#define USR1_DTRD       (1<<7)    /* DTR changed */
+#define USR1_RXDS       (1<<6)    /* Receiver is idle */
+#define USR1_AIRINT     (1<<5)    /* Aysnch IR interrupt */
+#define USR1_AWAKE      (1<<4)    /* Falling edge detected on RXd pin */
+
+#define USR2_ADET       (1<<15)   /* Autobaud complete */
+#define USR2_TXFE       (1<<14)   /* Transmit FIFO empty */
+#define USR2_DTRF       (1<<13)   /* DTR/DSR transition */
+#define USR2_IDLE       (1<<12)   /* UART has been idle for too long */
+#define USR2_ACST       (1<<11)   /* Autobaud counter stopped */
+#define USR2_RIDELT     (1<<10)   /* Ring Indicator delta */
+#define USR2_RIIN       (1<<9)    /* Ring Indicator Input */
+#define USR2_IRINT      (1<<8)    /* Serial Infrared Interrupt */
+#define USR2_WAKE       (1<<7)    /* Start bit detected */
+#define USR2_DCDDELT    (1<<6)    /* Data Carrier Detect delta */
+#define USR2_DCDIN      (1<<5)    /* Data Carrier Detect Input */
+#define USR2_RTSF       (1<<4)    /* RTS transition */
+#define USR2_TXDC       (1<<3)    /* Transmission complete */
+#define USR2_BRCD       (1<<2)    /* Break condition detected */
+#define USR2_ORE        (1<<1)    /* Overrun error */
+#define USR2_RDR        (1<<0)    /* Receive data ready */
+
+#define UCR1_TRDYEN     (1<<13)   /* Tx Ready Interrupt Enable */
+#define UCR1_RRDYEN     (1<<9)    /* Rx Ready Interrupt Enable */
+#define UCR1_TXMPTYEN   (1<<6)    /* Tx Empty Interrupt Enable */
+#define UCR1_UARTEN     (1<<0)    /* UART Enable */
+
+#define UCR2_TXEN       (1<<2)    /* Transmitter enable */
+#define UCR2_RXEN       (1<<1)    /* Receiver enable */
+#define UCR2_SRST       (1<<0)    /* Reset complete */
+
+#define UTS1_TXEMPTY    (1<<6)
+#define UTS1_RXEMPTY    (1<<5)
+#define UTS1_TXFULL     (1<<4)
+#define UTS1_RXFULL     (1<<3)
+
+static void imx_update(IMXSerialState *s)
+{
+    uint32_t flags;
+
+    flags = (s->usr1 & s->ucr1) & (USR1_TRDY|USR1_RRDY);
+    if (!(s->ucr1 & UCR1_TXMPTYEN)) {
+        flags &= ~USR1_TRDY;
+    }
+
+    qemu_set_irq(s->irq, !!flags);
+}
+
+static void imx_serial_reset(IMXSerialState *s)
+{
+
+    s->usr1 = USR1_TRDY | USR1_RXDS;
+    /*
+     * Fake attachment of a terminal: assert RTS.
+     */
+    s->usr1 |= USR1_RTSS;
+    s->usr2 = USR2_TXFE | USR2_TXDC | USR2_DCDIN;
+    s->uts1 = UTS1_RXEMPTY | UTS1_TXEMPTY;
+    s->ucr1 = 0;
+    s->ucr2 = UCR2_SRST;
+    s->ucr3 = 0x700;
+    s->ubmr = 0;
+    s->ubrc = 4;
+    s->readbuff = URXD_ERR;
+}
+
+static void imx_serial_reset_at_boot(DeviceState *dev)
+{
+    IMXSerialState *s = container_of(dev, IMXSerialState, busdev.qdev);
+
+    imx_serial_reset(s);
+
+    /*
+     * enable the uart on boot, so messages from the linux decompresser
+     * are visible.  On real hardware this is done by the boot rom
+     * before anything else is loaded.
+     */
+    s->ucr1 = UCR1_UARTEN;
+    s->ucr2 = UCR2_TXEN;
+
+}
+
+static uint64_t imx_serial_read(void *opaque, target_phys_addr_t offset,
+                                unsigned size)
+{
+    IMXSerialState *s = (IMXSerialState *)opaque;
+    uint32_t c;
+
+    DPRINTF("read(offset=%x)\n", offset >> 2);
+    switch (offset >> 2) {
+    case 0x0: /* URXD */
+        c = s->readbuff;
+        if (!(s->uts1 & UTS1_RXEMPTY)) {
+            /* Character is valid */
+            c |= URXD_CHARRDY;
+            s->usr1 &= ~USR1_RRDY;
+            s->usr2 &= ~USR2_RDR;
+            s->uts1 |= UTS1_RXEMPTY;
+            imx_update(s);
+            qemu_chr_accept_input(s->chr);
+        }
+        return c;
+
+    case 0x20: /* UCR1 */
+        return s->ucr1;
+
+    case 0x21: /* UCR2 */
+        return s->ucr2;
+
+    case 0x25: /* USR1 */
+        return s->usr1;
+
+    case 0x26: /* USR2 */
+        return s->usr2;
+
+    case 0x2A: /* BRM Modulator */
+        return s->ubmr;
+
+    case 0x2B: /* Baud Rate Count */
+        return s->ubrc;
+
+    case 0x2d: /* Test register */
+        return s->uts1;
+
+    case 0x24: /* UFCR */
+        return s->ufcr;
+
+    case 0x2c:
+        return s->onems;
+
+    case 0x22: /* UCR3 */
+        return s->ucr3;
+
+    case 0x23: /* UCR4 */
+    case 0x29: /* BRM Incremental */
+        return 0x0; /* TODO */
+
+    default:
+        IPRINTF("imx_serial_read: bad offset: 0x%x\n", (int)offset);
+        return 0;
+    }
+}
+
+static void imx_serial_write(void *opaque, target_phys_addr_t offset,
+                      uint64_t value, unsigned size)
+{
+    IMXSerialState *s = (IMXSerialState *)opaque;
+    unsigned char ch;
+
+    DPRINTF("write(offset=%x, value = %x) to %s\n",
+            offset >> 2,
+            (unsigned int)value, s->chr ? s->chr->label : "NODEV");
+
+    switch (offset >> 2) {
+    case 0x10: /* UTXD */
+        ch = value;
+        if (s->ucr2 & UCR2_TXEN) {
+            if (s->chr) {
+                qemu_chr_fe_write(s->chr, &ch, 1);
+            }
+            s->usr1 &= ~USR1_TRDY;
+            imx_update(s);
+            s->usr1 |= USR1_TRDY;
+            imx_update(s);
+        }
+        break;
+
+    case 0x20: /* UCR1 */
+        s->ucr1 = value & 0xffff;
+        DPRINTF("write(ucr1=%x)\n", (unsigned int)value);
+        imx_update(s);
+        break;
+
+    case 0x21: /* UCR2 */
+        /*
+         * Only a few bits in control register 2 are implemented as yet.
+         * If it's intended to use a real serial device as a back-end, this
+         * register will have to be implemented more fully.
+         */
+        if (!(value & UCR2_SRST)) {
+            imx_serial_reset(s);
+            imx_update(s);
+            value |= UCR2_SRST;
+        }
+        if (value & UCR2_RXEN) {
+            if (!(s->ucr2 & UCR2_RXEN)) {
+                qemu_chr_accept_input(s->chr);
+            }
+        }
+        s->ucr2 = value & 0xffff;
+        break;
+
+    case 0x25: /* USR1 */
+        value &= USR1_AWAKE | USR1_AIRINT | USR1_DTRD | USR1_AGTIM |
+            USR1_FRAMERR | USR1_ESCF | USR1_RTSD | USR1_PARTYER;
+        s->usr1 &= ~value;
+        break;
+
+    case 0x26: /* USR2 */
+       /*
+        * Writing 1 to some bits clears them; all other
+        * values are ignored
+        */
+        value &= USR2_ADET | USR2_DTRF | USR2_IDLE | USR2_ACST |
+            USR2_RIDELT | USR2_IRINT | USR2_WAKE |
+            USR2_DCDDELT | USR2_RTSF | USR2_BRCD | USR2_ORE;
+        s->usr2 &= ~value;
+        break;
+
+        /*
+         * Linux expects to see what it writes to these registers
+         * We don't currently alter the baud rate
+         */
+    case 0x29: /* UBIR */
+        s->ubrc = value & 0xffff;
+        break;
+
+    case 0x2a: /* UBMR */
+        s->ubmr = value & 0xffff;
+        break;
+
+    case 0x2c: /* One ms reg */
+        s->onems = value & 0xffff;
+        break;
+
+    case 0x24: /* FIFO control register */
+        s->ufcr = value & 0xffff;
+        break;
+
+    case 0x22: /* UCR3 */
+        s->ucr3 = value & 0xffff;
+        break;
+
+    case 0x2d: /* UTS1 */
+    case 0x23: /* UCR4 */
+        IPRINTF("Unimplemented Register %x written to\n", offset >> 2);
+        /* TODO */
+        break;
+
+    default:
+        IPRINTF("imx_serial_write: Bad offset 0x%x\n", (int)offset);
+    }
+}
+
+static int imx_can_receive(void *opaque)
+{
+    IMXSerialState *s = (IMXSerialState *)opaque;
+    return !(s->usr1 & USR1_RRDY);
+}
+
+static void imx_put_data(void *opaque, uint32_t value)
+{
+    IMXSerialState *s = (IMXSerialState *)opaque;
+    DPRINTF("received char\n");
+    s->usr1 |= USR1_RRDY;
+    s->usr2 |= USR2_RDR;
+    s->uts1 &= ~UTS1_RXEMPTY;
+    s->readbuff = value;
+    imx_update(s);
+}
+
+static void imx_receive(void *opaque, const uint8_t *buf, int size)
+{
+    imx_put_data(opaque, *buf);
+}
+
+static void imx_event(void *opaque, int event)
+{
+    if (event == CHR_EVENT_BREAK) {
+        imx_put_data(opaque, URXD_BRK);
+    }
+}
+
+
+static const struct MemoryRegionOps imx_serial_ops = {
+    .read = imx_serial_read,
+    .write = imx_serial_write,
+    .endianness = DEVICE_NATIVE_ENDIAN,
+};
+
+static int imx_serial_init(SysBusDevice *dev)
+{
+    IMXSerialState *s = FROM_SYSBUS(IMXSerialState, dev);
+
+
+    memory_region_init_io(&s->iomem, &imx_serial_ops, s, "imx-serial", 0x1000);
+    sysbus_init_mmio(dev, &s->iomem);
+    sysbus_init_irq(dev, &s->irq);
+
+    if (s->chr) {
+        qemu_chr_add_handlers(s->chr, imx_can_receive, imx_receive,
+                              imx_event, s);
+    } else {
+        DPRINTF("No char dev for uart at 0x%lx\n",
+                (unsigned long)s->iomem.ram_addr);
+    }
+
+    return 0;
+}
+
+void imx_serial_create(int uart, const target_phys_addr_t addr, qemu_irq irq)
+{
+    DeviceState *dev;
+    SysBusDevice *bus;
+    CharDriverState *chr;
+    const char chr_name[] = "serial";
+    char label[ARRAY_SIZE(chr_name) + 1];
+
+    dev = qdev_create(NULL, "imx-serial");
+
+    if (uart >= MAX_SERIAL_PORTS) {
+        hw_error("Cannot assign uart %d: QEMU supports only %d ports\n",
+                 uart, MAX_SERIAL_PORTS);
+    }
+    chr = serial_hds[uart];
+    if (!chr) {
+        snprintf(label, ARRAY_SIZE(label), "%s%d", chr_name, uart);
+        chr = qemu_chr_new(label, "null", NULL);
+        if (!(chr)) {
+            hw_error("Can't assign serial port to imx-uart%d.\n", uart);
+        }
+    }
+
+    qdev_prop_set_chr(dev, "chardev", chr);
+    bus = sysbus_from_qdev(dev);
+    qdev_init_nofail(dev);
+    if (addr != (target_phys_addr_t)-1) {
+        sysbus_mmio_map(bus, 0, addr);
+    }
+    sysbus_connect_irq(bus, 0, irq);
+
+}
+
+
+static Property imx32_serial_properties[] = {
+    DEFINE_PROP_CHR("chardev", IMXSerialState, chr),
+    DEFINE_PROP_END_OF_LIST(),
+};
+
+static void imx_serial_class_init(ObjectClass *klass, void *data)
+{
+    DeviceClass *dc = DEVICE_CLASS(klass);
+    SysBusDeviceClass *k = SYS_BUS_DEVICE_CLASS(klass);
+
+    k->init = imx_serial_init;
+    dc->vmsd = &vmstate_imx_serial;
+    dc->reset = imx_serial_reset_at_boot;
+    dc->desc = "i.MX series UART";
+    dc->props = imx32_serial_properties;
+}
+
+static TypeInfo imx_serial_info = {
+    .name = "imx-serial",
+    .parent = TYPE_SYS_BUS_DEVICE,
+    .instance_size = sizeof(IMXSerialState),
+    .class_init = imx_serial_class_init,
+};
+
+static void imx_serial_register_types(void)
+{
+    type_register_static(&imx_serial_info);
+}
+
+type_init(imx_serial_register_types)
commit 7bdf43a7538f3c198338e41255fdbe1a851f2203
Author: Oleg Ogurtsov <o.ogurtsov at samsung.com>
Date:   Wed Jul 4 10:43:32 2012 +0000

    Exynos4: add RTC device
    
    Signed-off-by: Oleg Ogurtsov <o.ogurtsov at samsung.com>
    Signed-off-by: Peter Maydell <peter.maydell at linaro.org>

diff --git a/hw/arm/Makefile.objs b/hw/arm/Makefile.objs
index 88ff47d..0fdb832 100644
--- a/hw/arm/Makefile.objs
+++ b/hw/arm/Makefile.objs
@@ -11,6 +11,7 @@ obj-y += realview_gic.o realview.o arm_sysctl.o arm11mpcore.o a9mpcore.o
 obj-y += exynos4210_gic.o exynos4210_combiner.o exynos4210.o
 obj-y += exynos4_boards.o exynos4210_uart.o exynos4210_pwm.o
 obj-y += exynos4210_pmu.o exynos4210_mct.o exynos4210_fimd.o
+obj-y += exynos4210_rtc.o
 obj-y += arm_l2x0.o
 obj-y += arm_mptimer.o a15mpcore.o
 obj-y += armv7m.o armv7m_nvic.o stellaris.o pl022.o stellaris_enet.o
diff --git a/hw/exynos4210.c b/hw/exynos4210.c
index 80a00b9..7c58c90 100644
--- a/hw/exynos4210.c
+++ b/hw/exynos4210.c
@@ -33,6 +33,9 @@
 /* PWM */
 #define EXYNOS4210_PWM_BASE_ADDR       0x139D0000
 
+/* RTC */
+#define EXYNOS4210_RTC_BASE_ADDR       0x10070000
+
 /* MCT */
 #define EXYNOS4210_MCT_BASE_ADDR       0x10050000
 
@@ -258,6 +261,11 @@ Exynos4210State *exynos4210_init(MemoryRegion *system_mem,
                           s->irq_table[exynos4210_get_irq(22, 3)],
                           s->irq_table[exynos4210_get_irq(22, 4)],
                           NULL);
+    /* RTC */
+    sysbus_create_varargs("exynos4210.rtc", EXYNOS4210_RTC_BASE_ADDR,
+                          s->irq_table[exynos4210_get_irq(23, 0)],
+                          s->irq_table[exynos4210_get_irq(23, 1)],
+                          NULL);
 
     /* Multi Core Timer */
     dev = qdev_create(NULL, "exynos4210.mct");
diff --git a/hw/exynos4210_rtc.c b/hw/exynos4210_rtc.c
new file mode 100644
index 0000000..f781020
--- /dev/null
+++ b/hw/exynos4210_rtc.c
@@ -0,0 +1,595 @@
+/*
+ * Samsung exynos4210 Real Time Clock
+ *
+ * Copyright (c) 2012 Samsung Electronics Co., Ltd.
+ *  Ogurtsov Oleg <o.ogurtsov at samsung.com>
+ *
+ *  This program is free software; you can redistribute it and/or modify it
+ *  under the terms of the GNU General Public License as published by the
+ *  Free Software Foundation; either version 2 of the License, or
+ *  (at your option) any later version.
+ *
+ *  This program is distributed in the hope that it will be useful, but WITHOUT
+ *  ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ *  FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
+ *  for more details.
+ *
+ *  You should have received a copy of the GNU General Public License along
+ *  with this program; if not, see <http://www.gnu.org/licenses/>.
+ *
+ */
+
+/* Description:
+ * Register RTCCON:
+ *  CLKSEL Bit[1] not used
+ *  CLKOUTEN Bit[9] not used
+ */
+
+#include "sysbus.h"
+#include "qemu-timer.h"
+#include "qemu-common.h"
+#include "ptimer.h"
+
+#include "hw.h"
+#include "qemu-timer.h"
+#include "sysemu.h"
+
+#include "exynos4210.h"
+
+#define DEBUG_RTC 0
+
+#if DEBUG_RTC
+#define DPRINTF(fmt, ...) \
+        do { fprintf(stdout, "RTC: [%24s:%5d] " fmt, __func__, __LINE__, \
+                ## __VA_ARGS__); } while (0)
+#else
+#define DPRINTF(fmt, ...) do {} while (0)
+#endif
+
+#define     EXYNOS4210_RTC_REG_MEM_SIZE     0x0100
+
+#define     INTP            0x0030
+#define     RTCCON          0x0040
+#define     TICCNT          0x0044
+#define     RTCALM          0x0050
+#define     ALMSEC          0x0054
+#define     ALMMIN          0x0058
+#define     ALMHOUR         0x005C
+#define     ALMDAY          0x0060
+#define     ALMMON          0x0064
+#define     ALMYEAR         0x0068
+#define     BCDSEC          0x0070
+#define     BCDMIN          0x0074
+#define     BCDHOUR         0x0078
+#define     BCDDAY          0x007C
+#define     BCDDAYWEEK      0x0080
+#define     BCDMON          0x0084
+#define     BCDYEAR         0x0088
+#define     CURTICNT        0x0090
+
+#define     TICK_TIMER_ENABLE   0x0100
+#define     TICNT_THRESHHOLD    2
+
+
+#define     RTC_ENABLE          0x0001
+
+#define     INTP_TICK_ENABLE    0x0001
+#define     INTP_ALM_ENABLE     0x0002
+
+#define     ALARM_INT_ENABLE    0x0040
+
+#define     RTC_BASE_FREQ       32768
+
+typedef struct Exynos4210RTCState {
+    SysBusDevice busdev;
+    MemoryRegion iomem;
+
+    /* registers */
+    uint32_t    reg_intp;
+    uint32_t    reg_rtccon;
+    uint32_t    reg_ticcnt;
+    uint32_t    reg_rtcalm;
+    uint32_t    reg_almsec;
+    uint32_t    reg_almmin;
+    uint32_t    reg_almhour;
+    uint32_t    reg_almday;
+    uint32_t    reg_almmon;
+    uint32_t    reg_almyear;
+    uint32_t    reg_curticcnt;
+
+    ptimer_state    *ptimer;        /* tick timer */
+    ptimer_state    *ptimer_1Hz;    /* clock timer */
+    uint32_t        freq;
+
+    qemu_irq        tick_irq;   /* Time Tick Generator irq */
+    qemu_irq        alm_irq;    /* alarm irq */
+
+    struct tm   current_tm;     /* current time */
+} Exynos4210RTCState;
+
+#define TICCKSEL(value) ((value & (0x0F << 4)) >> 4)
+
+/*** VMState ***/
+static const VMStateDescription vmstate_exynos4210_rtc_state = {
+    .name = "exynos4210.rtc",
+    .version_id = 1,
+    .minimum_version_id = 1,
+    .minimum_version_id_old = 1,
+    .fields = (VMStateField[]) {
+        VMSTATE_UINT32(reg_intp, Exynos4210RTCState),
+        VMSTATE_UINT32(reg_rtccon, Exynos4210RTCState),
+        VMSTATE_UINT32(reg_ticcnt, Exynos4210RTCState),
+        VMSTATE_UINT32(reg_rtcalm, Exynos4210RTCState),
+        VMSTATE_UINT32(reg_almsec, Exynos4210RTCState),
+        VMSTATE_UINT32(reg_almmin, Exynos4210RTCState),
+        VMSTATE_UINT32(reg_almhour, Exynos4210RTCState),
+        VMSTATE_UINT32(reg_almday, Exynos4210RTCState),
+        VMSTATE_UINT32(reg_almmon, Exynos4210RTCState),
+        VMSTATE_UINT32(reg_almyear, Exynos4210RTCState),
+        VMSTATE_UINT32(reg_curticcnt, Exynos4210RTCState),
+        VMSTATE_PTIMER(ptimer, Exynos4210RTCState),
+        VMSTATE_PTIMER(ptimer_1Hz, Exynos4210RTCState),
+        VMSTATE_UINT32(freq, Exynos4210RTCState),
+        VMSTATE_INT32(current_tm.tm_sec, Exynos4210RTCState),
+        VMSTATE_INT32(current_tm.tm_min, Exynos4210RTCState),
+        VMSTATE_INT32(current_tm.tm_hour, Exynos4210RTCState),
+        VMSTATE_INT32(current_tm.tm_wday, Exynos4210RTCState),
+        VMSTATE_INT32(current_tm.tm_mday, Exynos4210RTCState),
+        VMSTATE_INT32(current_tm.tm_mon, Exynos4210RTCState),
+        VMSTATE_INT32(current_tm.tm_year, Exynos4210RTCState),
+        VMSTATE_END_OF_LIST()
+    }
+};
+
+#define BCD3DIGITS(x) \
+    ((uint32_t)to_bcd((uint8_t)x) + \
+    ((uint32_t)to_bcd((uint8_t)((x % 1000) / 100)) << 8))
+
+static void check_alarm_raise(Exynos4210RTCState *s)
+{
+    unsigned int alarm_raise = 0;
+    struct tm stm = s->current_tm;
+
+    if ((s->reg_rtcalm & 0x01) &&
+        (to_bcd((uint8_t)stm.tm_sec) == (uint8_t)s->reg_almsec)) {
+        alarm_raise = 1;
+    }
+    if ((s->reg_rtcalm & 0x02) &&
+        (to_bcd((uint8_t)stm.tm_min) == (uint8_t)s->reg_almmin)) {
+        alarm_raise = 1;
+    }
+    if ((s->reg_rtcalm & 0x04) &&
+        (to_bcd((uint8_t)stm.tm_hour) == (uint8_t)s->reg_almhour)) {
+        alarm_raise = 1;
+    }
+    if ((s->reg_rtcalm & 0x08) &&
+        (to_bcd((uint8_t)stm.tm_mday) == (uint8_t)s->reg_almday)) {
+        alarm_raise = 1;
+    }
+    if ((s->reg_rtcalm & 0x10) &&
+         (to_bcd((uint8_t)stm.tm_mon) == (uint8_t)s->reg_almmon)) {
+        alarm_raise = 1;
+    }
+    if ((s->reg_rtcalm & 0x20) &&
+        (BCD3DIGITS(stm.tm_year) == s->reg_almyear)) {
+        alarm_raise = 1;
+    }
+
+    if (alarm_raise) {
+        DPRINTF("ALARM IRQ\n");
+        /* set irq status */
+        s->reg_intp |= INTP_ALM_ENABLE;
+        qemu_irq_raise(s->alm_irq);
+    }
+}
+
+/*
+ * RTC update frequency
+ * Parameters:
+ *     reg_value - current RTCCON register or his new value
+ */
+static void exynos4210_rtc_update_freq(Exynos4210RTCState *s,
+                                       uint32_t reg_value)
+{
+    uint32_t freq;
+
+    freq = s->freq;
+    /* set frequncy for time generator */
+    s->freq = RTC_BASE_FREQ / (1 << TICCKSEL(reg_value));
+
+    if (freq != s->freq) {
+        ptimer_set_freq(s->ptimer, s->freq);
+        DPRINTF("freq=%dHz\n", s->freq);
+    }
+}
+
+/* month is between 0 and 11. */
+static int get_days_in_month(int month, int year)
+{
+    static const int days_tab[12] = {
+        31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31
+    };
+    int d;
+    if ((unsigned)month >= 12) {
+        return 31;
+    }
+    d = days_tab[month];
+    if (month == 1) {
+        if ((year % 4) == 0 && ((year % 100) != 0 || (year % 400) == 0)) {
+            d++;
+        }
+    }
+    return d;
+}
+
+/* update 'tm' to the next second */
+static void rtc_next_second(struct tm *tm)
+{
+    int days_in_month;
+
+    tm->tm_sec++;
+    if ((unsigned)tm->tm_sec >= 60) {
+        tm->tm_sec = 0;
+        tm->tm_min++;
+        if ((unsigned)tm->tm_min >= 60) {
+            tm->tm_min = 0;
+            tm->tm_hour++;
+            if ((unsigned)tm->tm_hour >= 24) {
+                tm->tm_hour = 0;
+                /* next day */
+                tm->tm_wday++;
+                if ((unsigned)tm->tm_wday >= 7) {
+                    tm->tm_wday = 0;
+                }
+                days_in_month = get_days_in_month(tm->tm_mon,
+                                                  tm->tm_year + 1900);
+                tm->tm_mday++;
+                if (tm->tm_mday < 1) {
+                    tm->tm_mday = 1;
+                } else if (tm->tm_mday > days_in_month) {
+                    tm->tm_mday = 1;
+                    tm->tm_mon++;
+                    if (tm->tm_mon >= 12) {
+                        tm->tm_mon = 0;
+                        tm->tm_year++;
+                    }
+                }
+            }
+        }
+    }
+}
+
+/*
+ * tick handler
+ */
+static void exynos4210_rtc_tick(void *opaque)
+{
+    Exynos4210RTCState *s = (Exynos4210RTCState *)opaque;
+
+    DPRINTF("TICK IRQ\n");
+    /* set irq status */
+    s->reg_intp |= INTP_TICK_ENABLE;
+    /* raise IRQ */
+    qemu_irq_raise(s->tick_irq);
+
+    /* restart timer */
+    ptimer_set_count(s->ptimer, s->reg_ticcnt);
+    ptimer_run(s->ptimer, 1);
+}
+
+/*
+ * 1Hz clock handler
+ */
+static void exynos4210_rtc_1Hz_tick(void *opaque)
+{
+    Exynos4210RTCState *s = (Exynos4210RTCState *)opaque;
+
+    rtc_next_second(&s->current_tm);
+    /* DPRINTF("1Hz tick\n"); */
+
+    /* raise IRQ */
+    if (s->reg_rtcalm & ALARM_INT_ENABLE) {
+        check_alarm_raise(s);
+    }
+
+    ptimer_set_count(s->ptimer_1Hz, RTC_BASE_FREQ);
+    ptimer_run(s->ptimer_1Hz, 1);
+}
+
+/*
+ * RTC Read
+ */
+static uint64_t exynos4210_rtc_read(void *opaque, target_phys_addr_t offset,
+        unsigned size)
+{
+    uint32_t value = 0;
+    Exynos4210RTCState *s = (Exynos4210RTCState *)opaque;
+
+    switch (offset) {
+    case INTP:
+        value = s->reg_intp;
+        break;
+    case RTCCON:
+        value = s->reg_rtccon;
+        break;
+    case TICCNT:
+        value = s->reg_ticcnt;
+        break;
+    case RTCALM:
+        value = s->reg_rtcalm;
+        break;
+    case ALMSEC:
+        value = s->reg_almsec;
+        break;
+    case ALMMIN:
+        value = s->reg_almmin;
+        break;
+    case ALMHOUR:
+        value = s->reg_almhour;
+        break;
+    case ALMDAY:
+        value = s->reg_almday;
+        break;
+    case ALMMON:
+        value = s->reg_almmon;
+        break;
+    case ALMYEAR:
+        value = s->reg_almyear;
+        break;
+
+    case BCDSEC:
+        value = (uint32_t)to_bcd((uint8_t)s->current_tm.tm_sec);
+        break;
+    case BCDMIN:
+        value = (uint32_t)to_bcd((uint8_t)s->current_tm.tm_min);
+        break;
+    case BCDHOUR:
+        value = (uint32_t)to_bcd((uint8_t)s->current_tm.tm_hour);
+        break;
+    case BCDDAYWEEK:
+        value = (uint32_t)to_bcd((uint8_t)s->current_tm.tm_wday);
+        break;
+    case BCDDAY:
+        value = (uint32_t)to_bcd((uint8_t)s->current_tm.tm_mday);
+        break;
+    case BCDMON:
+        value = (uint32_t)to_bcd((uint8_t)s->current_tm.tm_mon + 1);
+        break;
+    case BCDYEAR:
+        value = BCD3DIGITS(s->current_tm.tm_year);
+        break;
+
+    case CURTICNT:
+        s->reg_curticcnt = ptimer_get_count(s->ptimer);
+        value = s->reg_curticcnt;
+        break;
+
+    default:
+        fprintf(stderr,
+                "[exynos4210.rtc: bad read offset " TARGET_FMT_plx "]\n",
+                offset);
+        break;
+    }
+    return value;
+}
+
+/*
+ * RTC Write
+ */
+static void exynos4210_rtc_write(void *opaque, target_phys_addr_t offset,
+        uint64_t value, unsigned size)
+{
+    Exynos4210RTCState *s = (Exynos4210RTCState *)opaque;
+
+    switch (offset) {
+    case INTP:
+        if (value & INTP_ALM_ENABLE) {
+            qemu_irq_lower(s->alm_irq);
+            s->reg_intp &= (~INTP_ALM_ENABLE);
+        }
+        if (value & INTP_TICK_ENABLE) {
+            qemu_irq_lower(s->tick_irq);
+            s->reg_intp &= (~INTP_TICK_ENABLE);
+        }
+        break;
+    case RTCCON:
+        if (value & RTC_ENABLE) {
+            exynos4210_rtc_update_freq(s, value);
+        }
+        if ((value & RTC_ENABLE) > (s->reg_rtccon & RTC_ENABLE)) {
+            /* clock timer */
+            ptimer_set_count(s->ptimer_1Hz, RTC_BASE_FREQ);
+            ptimer_run(s->ptimer_1Hz, 1);
+            DPRINTF("run clock timer\n");
+        }
+        if ((value & RTC_ENABLE) < (s->reg_rtccon & RTC_ENABLE)) {
+            /* tick timer */
+            ptimer_stop(s->ptimer);
+            /* clock timer */
+            ptimer_stop(s->ptimer_1Hz);
+            DPRINTF("stop all timers\n");
+        }
+        if (value & RTC_ENABLE) {
+            if ((value & TICK_TIMER_ENABLE) >
+                (s->reg_rtccon & TICK_TIMER_ENABLE) &&
+                (s->reg_ticcnt)) {
+                ptimer_set_count(s->ptimer, s->reg_ticcnt);
+                ptimer_run(s->ptimer, 1);
+                DPRINTF("run tick timer\n");
+            }
+            if ((value & TICK_TIMER_ENABLE) <
+                (s->reg_rtccon & TICK_TIMER_ENABLE)) {
+                ptimer_stop(s->ptimer);
+            }
+        }
+        s->reg_rtccon = value;
+        break;
+    case TICCNT:
+        if (value > TICNT_THRESHHOLD) {
+            s->reg_ticcnt = value;
+        } else {
+            fprintf(stderr,
+                    "[exynos4210.rtc: bad TICNT value %u ]\n",
+                    (uint32_t)value);
+        }
+        break;
+
+    case RTCALM:
+        s->reg_rtcalm = value;
+        break;
+    case ALMSEC:
+        s->reg_almsec = (value & 0x7f);
+        break;
+    case ALMMIN:
+        s->reg_almmin = (value & 0x7f);
+        break;
+    case ALMHOUR:
+        s->reg_almhour = (value & 0x3f);
+        break;
+    case ALMDAY:
+        s->reg_almday = (value & 0x3f);
+        break;
+    case ALMMON:
+        s->reg_almmon = (value & 0x1f);
+        break;
+    case ALMYEAR:
+        s->reg_almyear = (value & 0x0fff);
+        break;
+
+    case BCDSEC:
+        if (s->reg_rtccon & RTC_ENABLE) {
+            s->current_tm.tm_sec = (int)from_bcd((uint8_t)value);
+        }
+        break;
+    case BCDMIN:
+        if (s->reg_rtccon & RTC_ENABLE) {
+            s->current_tm.tm_min = (int)from_bcd((uint8_t)value);
+        }
+        break;
+    case BCDHOUR:
+        if (s->reg_rtccon & RTC_ENABLE) {
+            s->current_tm.tm_hour = (int)from_bcd((uint8_t)value);
+        }
+        break;
+    case BCDDAYWEEK:
+        if (s->reg_rtccon & RTC_ENABLE) {
+            s->current_tm.tm_wday = (int)from_bcd((uint8_t)value);
+        }
+        break;
+    case BCDDAY:
+        if (s->reg_rtccon & RTC_ENABLE) {
+            s->current_tm.tm_mday = (int)from_bcd((uint8_t)value);
+        }
+        break;
+    case BCDMON:
+        if (s->reg_rtccon & RTC_ENABLE) {
+            s->current_tm.tm_mon = (int)from_bcd((uint8_t)value) - 1;
+        }
+        break;
+    case BCDYEAR:
+        if (s->reg_rtccon & RTC_ENABLE) {
+            /* 3 digits */
+            s->current_tm.tm_year = (int)from_bcd((uint8_t)value) +
+                    (int)from_bcd((uint8_t)((value >> 8) & 0x0f)) * 100;
+        }
+        break;
+
+    default:
+        fprintf(stderr,
+                "[exynos4210.rtc: bad write offset " TARGET_FMT_plx "]\n",
+                offset);
+        break;
+
+    }
+}
+
+/*
+ * Set default values to timer fields and registers
+ */
+static void exynos4210_rtc_reset(DeviceState *d)
+{
+    Exynos4210RTCState *s = (Exynos4210RTCState *)d;
+
+    struct tm tm;
+
+    qemu_get_timedate(&tm, 0);
+    s->current_tm = tm;
+
+    DPRINTF("Get time from host: %d-%d-%d %2d:%02d:%02d\n",
+            s->current_tm.tm_year, s->current_tm.tm_mon, s->current_tm.tm_mday,
+            s->current_tm.tm_hour, s->current_tm.tm_min, s->current_tm.tm_sec);
+
+    s->reg_intp = 0;
+    s->reg_rtccon = 0;
+    s->reg_ticcnt = 0;
+    s->reg_rtcalm = 0;
+    s->reg_almsec = 0;
+    s->reg_almmin = 0;
+    s->reg_almhour = 0;
+    s->reg_almday = 0;
+    s->reg_almmon = 0;
+    s->reg_almyear = 0;
+
+    s->reg_curticcnt = 0;
+
+    exynos4210_rtc_update_freq(s, s->reg_rtccon);
+    ptimer_stop(s->ptimer);
+    ptimer_stop(s->ptimer_1Hz);
+}
+
+static const MemoryRegionOps exynos4210_rtc_ops = {
+    .read = exynos4210_rtc_read,
+    .write = exynos4210_rtc_write,
+    .endianness = DEVICE_NATIVE_ENDIAN,
+};
+
+/*
+ * RTC timer initialization
+ */
+static int exynos4210_rtc_init(SysBusDevice *dev)
+{
+    Exynos4210RTCState *s = FROM_SYSBUS(Exynos4210RTCState, dev);
+    QEMUBH *bh;
+
+    bh = qemu_bh_new(exynos4210_rtc_tick, s);
+    s->ptimer = ptimer_init(bh);
+    ptimer_set_freq(s->ptimer, RTC_BASE_FREQ);
+    exynos4210_rtc_update_freq(s, 0);
+
+    bh = qemu_bh_new(exynos4210_rtc_1Hz_tick, s);
+    s->ptimer_1Hz = ptimer_init(bh);
+    ptimer_set_freq(s->ptimer_1Hz, RTC_BASE_FREQ);
+
+    sysbus_init_irq(dev, &s->alm_irq);
+    sysbus_init_irq(dev, &s->tick_irq);
+
+    memory_region_init_io(&s->iomem, &exynos4210_rtc_ops, s, "exynos4210-rtc",
+            EXYNOS4210_RTC_REG_MEM_SIZE);
+    sysbus_init_mmio(dev, &s->iomem);
+
+    return 0;
+}
+
+static void exynos4210_rtc_class_init(ObjectClass *klass, void *data)
+{
+    DeviceClass *dc = DEVICE_CLASS(klass);
+    SysBusDeviceClass *k = SYS_BUS_DEVICE_CLASS(klass);
+
+    k->init = exynos4210_rtc_init;
+    dc->reset = exynos4210_rtc_reset;
+    dc->vmsd = &vmstate_exynos4210_rtc_state;
+}
+
+static const TypeInfo exynos4210_rtc_info = {
+    .name          = "exynos4210.rtc",
+    .parent        = TYPE_SYS_BUS_DEVICE,
+    .instance_size = sizeof(Exynos4210RTCState),
+    .class_init    = exynos4210_rtc_class_init,
+};
+
+static void exynos4210_rtc_register_types(void)
+{
+    type_register_static(&exynos4210_rtc_info);
+}
+
+type_init(exynos4210_rtc_register_types)
commit 7892df069addf28304190935748e8d59982180bd
Author: Evgeny Voevodin <e.voevodin at samsung.com>
Date:   Wed Jul 4 10:43:32 2012 +0000

    hw/exynos4210.c: Fix misleading initialization of IROM mirror
    
    We want to mirror whole IROM and should pass zero instead of
    EXYNOS4210_IROM_BASE_ADDR (though it equals to zero too) since
    memory_region_init_alias takes an offset within an original
    region as an argument.
    
    Signed-off-by: Evgeny Voevodin <e.voevodin at samsung.com>
    Reviewed-by: Peter Maydell <peter.maydell at linaro.org>
    Signed-off-by: Peter Maydell <peter.maydell at linaro.org>

diff --git a/hw/exynos4210.c b/hw/exynos4210.c
index 9c20b3f..80a00b9 100644
--- a/hw/exynos4210.c
+++ b/hw/exynos4210.c
@@ -216,7 +216,7 @@ Exynos4210State *exynos4210_init(MemoryRegion *system_mem,
     /* mirror of iROM */
     memory_region_init_alias(&s->irom_alias_mem, "exynos4210.irom_alias",
                              &s->irom_mem,
-                             EXYNOS4210_IROM_BASE_ADDR,
+                             0,
                              EXYNOS4210_IROM_SIZE);
     memory_region_set_readonly(&s->irom_alias_mem, true);
     memory_region_add_subregion(system_mem, EXYNOS4210_IROM_MIRROR_BASE_ADDR,
commit b631bc37d97344bb35f54d6af6a12df35a6764d8
Author: Evgeny Voevodin <e.voevodin at samsung.com>
Date:   Wed Jul 4 10:43:31 2012 +0000

    hw/exynos4210_pwm.c: Fix STOP status in tick handler.
    
    START/STOP bit was not cleaned correctly.
    
    Signed-off-by: Evgeny Voevodin <e.voevodin at samsung.com>
    Reviewed-by: Peter Maydell <peter.maydell at linaro.org>
    Signed-off-by: Peter Maydell <peter.maydell at linaro.org>

diff --git a/hw/exynos4210_pwm.c b/hw/exynos4210_pwm.c
index 6243e59..0c22828 100644
--- a/hw/exynos4210_pwm.c
+++ b/hw/exynos4210_pwm.c
@@ -200,7 +200,7 @@ static void exynos4210_pwm_tick(void *opaque)
         ptimer_run(p->timer[id].ptimer, 1);
     } else {
         /* stop timer, set status to STOP, see Basic Timer Operation */
-        p->reg_tcon = ~TCON_TIMER_START(id);
+        p->reg_tcon &= ~TCON_TIMER_START(id);
         ptimer_stop(p->timer[id].ptimer);
     }
 }
commit 2e2aafc0f6c0964b736d81cb7b13a2a1a3d8a564
Author: Stanislav Vorobiov <s.vorobiov at samsung.com>
Date:   Wed Jul 4 10:43:30 2012 +0000

    ARM: hw/exynos4210_mct.c: Fix a bug which hangs Linux kernel.
    
    After some long period of time Linux kernel hanged due to
    ptimer_get_count may return 0 before timer interrupt occurs,
    thus, causing FRC to jump back in time
    
    Signed-off-by: Evgeny Voevodin <e.voevodin at samsung.com>
    Signed-off-by: Peter Maydell <peter.maydell at linaro.org>

diff --git a/hw/exynos4210_mct.c b/hw/exynos4210_mct.c
index 7474fcf..7a22b1f 100644
--- a/hw/exynos4210_mct.c
+++ b/hw/exynos4210_mct.c
@@ -376,10 +376,6 @@ static uint64_t exynos4210_gfrc_get_count(Exynos4210MCTGT *s)
 {
     uint64_t count = 0;
     count = ptimer_get_count(s->ptimer_frc);
-    if (!count) {
-        /* Timer event was generated and s->reg.cnt holds adequate value */
-        return s->reg.cnt;
-    }
     count = s->count - count;
     return s->reg.cnt + count;
 }
commit a75b3e0f641a68b7cdd4bbe4ed1b60f963bf2b62
Author: Liu, Jinsong <jinsong.liu at intel.com>
Date:   Tue Jul 3 02:35:10 2012 +0800

    kvm: expose tsc deadline timer feature to guest
    
    This patch exposes tsc deadline timer feature to guest if
    1). in-kernel irqchip is used, and
    2). kvm has emulated tsc deadline timer, and
    3). user authorize the feature exposing via -cpu or +/- tsc-deadline
    
    Signed-off-by: Liu, Jinsong <jinsong.liu at intel.com>
    Reviewed-by: Eduardo Habkost <ehabkost at redhat.com>
    Acked-by: Jan Kiszka <jan.kiszka at siemens.com>
    Signed-off-by: Marcelo Tosatti <mtosatti at redhat.com>

diff --git a/target-i386/cpu.h b/target-i386/cpu.h
index f257c97..33d221e 100644
--- a/target-i386/cpu.h
+++ b/target-i386/cpu.h
@@ -400,6 +400,7 @@
 #define CPUID_EXT_X2APIC   (1 << 21)
 #define CPUID_EXT_MOVBE    (1 << 22)
 #define CPUID_EXT_POPCNT   (1 << 23)
+#define CPUID_EXT_TSC_DEADLINE_TIMER (1 << 24)
 #define CPUID_EXT_XSAVE    (1 << 26)
 #define CPUID_EXT_OSXSAVE  (1 << 27)
 #define CPUID_EXT_HYPERVISOR  (1 << 31)
diff --git a/target-i386/kvm.c b/target-i386/kvm.c
index 0d0d8f6..52b577f 100644
--- a/target-i386/kvm.c
+++ b/target-i386/kvm.c
@@ -361,8 +361,13 @@ int kvm_arch_init_vcpu(CPUX86State *env)
     env->cpuid_features &= kvm_arch_get_supported_cpuid(s, 1, 0, R_EDX);
 
     i = env->cpuid_ext_features & CPUID_EXT_HYPERVISOR;
+    j = env->cpuid_ext_features & CPUID_EXT_TSC_DEADLINE_TIMER;
     env->cpuid_ext_features &= kvm_arch_get_supported_cpuid(s, 1, 0, R_ECX);
     env->cpuid_ext_features |= i;
+    if (j && kvm_irqchip_in_kernel() &&
+        kvm_check_extension(s, KVM_CAP_TSC_DEADLINE_TIMER)) {
+        env->cpuid_ext_features |= CPUID_EXT_TSC_DEADLINE_TIMER;
+    }
 
     env->cpuid_ext2_features &= kvm_arch_get_supported_cpuid(s, 0x80000001,
                                                              0, R_EDX);
commit bfee7546df51c08e395dc8a7676a5c7f20186fee
Author: Michael S. Tsirkin <mst at redhat.com>
Date:   Sun Jul 1 18:08:30 2012 +0300

    kvm_pv_eoi: add flag support
    
    Support the new PV EOI flag in kvm - it recently got merged
    into kvm.git. Set by default with -cpu kvm.
    Set for -cpu qemu by adding +kvm_pv_eoi.
    Clear by adding -kvm_pv_eoi to -cpu option.
    
    Signed-off-by: Michael S. Tsirkin <mst at redhat.com>
    Signed-off-by: Marcelo Tosatti <mtosatti at redhat.com>

diff --git a/target-i386/cpu.c b/target-i386/cpu.c
index 5521709..b3bcbac 100644
--- a/target-i386/cpu.c
+++ b/target-i386/cpu.c
@@ -77,7 +77,7 @@ static const char *ext3_feature_name[] = {
 };
 
 static const char *kvm_feature_name[] = {
-    "kvmclock", "kvm_nopiodelay", "kvm_mmu", "kvmclock", "kvm_asyncpf", NULL, NULL, NULL,
+    "kvmclock", "kvm_nopiodelay", "kvm_mmu", "kvmclock", "kvm_asyncpf", NULL, "kvm_pv_eoi", NULL,
     NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL,
     NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL,
     NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL,
commit 9ce1bb2d36f24af79d2757497acbaf4dc4a2e302
Author: Christian Hoff <christian.hoff at de.ibm.com>
Date:   Thu Jun 14 15:55:28 2012 +0200

    scsi: Fix transfer length for READ POSITION commands.
    
    The transfer length depends on the specific service action
    code, as defined in the SCSI stream commands spec section 7.7.
    Up to now only the extended form was supported.
    
    Signed-off-by: Christian Hoff <christian.hoff at de.ibm.com>
    Signed-off-by: Christian Borntraeger <borntraeger at de.ibm.com>
    Signed-off-by: Paolo Bonzini <pbonzini at redhat.com>

diff --git a/hw/scsi-bus.c b/hw/scsi-bus.c
index 9c64e30..5ad1013 100644
--- a/hw/scsi-bus.c
+++ b/hw/scsi-bus.c
@@ -901,7 +901,21 @@ static int scsi_req_stream_length(SCSICommand *cmd, SCSIDevice *dev, uint8_t *bu
         cmd->xfer = buf[13] | (buf[12] << 8);
         break;
     case READ_POSITION:
-        cmd->xfer = buf[8] | (buf[7] << 8);
+        switch (buf[1] & 0x1f) /* operation code */ {
+        case SHORT_FORM_BLOCK_ID:
+        case SHORT_FORM_VENDOR_SPECIFIC:
+            cmd->xfer = 20;
+            break;
+        case LONG_FORM:
+            cmd->xfer = 32;
+            break;
+        case EXTENDED_FORM:
+            cmd->xfer = buf[8] | (buf[7] << 8);
+            break;
+        default:
+            return -1;
+        }
+
         break;
     case FORMAT_UNIT:
         cmd->xfer = buf[4] | (buf[3] << 8);
diff --git a/hw/scsi-defs.h b/hw/scsi-defs.h
index ade82a4..8a73f74 100644
--- a/hw/scsi-defs.h
+++ b/hw/scsi-defs.h
@@ -147,6 +147,14 @@
 #define SAI_READ_CAPACITY_16  0x10
 
 /*
+ * READ POSITION service action codes
+ */
+#define SHORT_FORM_BLOCK_ID  0x00
+#define SHORT_FORM_VENDOR_SPECIFIC 0x01
+#define LONG_FORM            0x06
+#define EXTENDED_FORM        0x08
+
+/*
  *  SAM Status codes
  */
 
commit 40723a99b8c406143f27538846103f98942e4e24
Author: Christian Hoff <christian.hoff at de.ibm.com>
Date:   Thu Jun 14 15:55:27 2012 +0200

    scsi: Add basic support for SCSI media changer commands.
    
    This adds basic support for SCSI media changer commands.
    Not all commands are supported as of now, but enough to cover
    basic functionality.
    
    Signed-off-by: Christian Hoff <christian.hoff at de.ibm.com>
    Signed-off-by: Christian Borntraeger <borntraeger at de.ibm.com>
    Signed-off-by: Paolo Bonzini <pbonzini at redhat.com>

diff --git a/hw/scsi-bus.c b/hw/scsi-bus.c
index 4ec9b52..9c64e30 100644
--- a/hw/scsi-bus.c
+++ b/hw/scsi-bus.c
@@ -770,7 +770,6 @@ static int scsi_req_length(SCSICommand *cmd, SCSIDevice *dev, uint8_t *buf)
     case SET_CD_SPEED:
     case SET_LIMITS:
     case WRITE_LONG_10:
-    case MOVE_MEDIUM:
     case UPDATE_BLOCK:
     case RESERVE_TRACK:
     case SET_READ_AHEAD:
@@ -914,6 +913,29 @@ static int scsi_req_stream_length(SCSICommand *cmd, SCSIDevice *dev, uint8_t *bu
     return 0;
 }
 
+static int scsi_req_medium_changer_length(SCSICommand *cmd, SCSIDevice *dev, uint8_t *buf)
+{
+    switch (buf[0]) {
+    /* medium changer commands */
+    case EXCHANGE_MEDIUM:
+    case INITIALIZE_ELEMENT_STATUS:
+    case INITIALIZE_ELEMENT_STATUS_WITH_RANGE:
+    case MOVE_MEDIUM:
+    case POSITION_TO_ELEMENT:
+        cmd->xfer = 0;
+        break;
+    case READ_ELEMENT_STATUS:
+        cmd->xfer = buf[9] | (buf[8] << 8) | (buf[7] << 16);
+        break;
+
+    /* generic commands */
+    default:
+        return scsi_req_length(cmd, dev, buf);
+    }
+    return 0;
+}
+
+
 static void scsi_cmd_xfer_mode(SCSICommand *cmd)
 {
     if (!cmd->xfer) {
@@ -1011,11 +1033,18 @@ int scsi_req_parse(SCSICommand *cmd, SCSIDevice *dev, uint8_t *buf)
         return -1;
     }
 
-    if (dev->type == TYPE_TAPE) {
+    switch (dev->type) {
+    case TYPE_TAPE:
         rc = scsi_req_stream_length(cmd, dev, buf);
-    } else {
+        break;
+    case TYPE_MEDIUM_CHANGER:
+        rc = scsi_req_medium_changer_length(cmd, dev, buf);
+        break;
+    default:
         rc = scsi_req_length(cmd, dev, buf);
+        break;
     }
+
     if (rc != 0)
         return rc;
 
@@ -1193,7 +1222,8 @@ static const char *scsi_command_name(uint8_t cmd)
         [ REQUEST_SENSE            ] = "REQUEST_SENSE",
         [ FORMAT_UNIT              ] = "FORMAT_UNIT",
         [ READ_BLOCK_LIMITS        ] = "READ_BLOCK_LIMITS",
-        [ REASSIGN_BLOCKS          ] = "REASSIGN_BLOCKS",
+        [ REASSIGN_BLOCKS          ] = "REASSIGN_BLOCKS/INITIALIZE ELEMENT STATUS",
+        /* LOAD_UNLOAD and INITIALIZE_ELEMENT_STATUS use the same operation code */
         [ READ_6                   ] = "READ_6",
         [ WRITE_6                  ] = "WRITE_6",
         [ SET_CAPACITY             ] = "SET_CAPACITY",
@@ -1218,7 +1248,8 @@ static const char *scsi_command_name(uint8_t cmd)
         [ READ_CAPACITY_10         ] = "READ_CAPACITY_10",
         [ READ_10                  ] = "READ_10",
         [ WRITE_10                 ] = "WRITE_10",
-        [ SEEK_10                  ] = "SEEK_10",
+        [ SEEK_10                  ] = "SEEK_10/POSITION_TO_ELEMENT",
+        /* SEEK_10 and POSITION_TO_ELEMENT use the same operation code */
         [ WRITE_VERIFY_10          ] = "WRITE_VERIFY_10",
         [ VERIFY_10                ] = "VERIFY_10",
         [ SEARCH_HIGH              ] = "SEARCH_HIGH",
@@ -1229,7 +1260,8 @@ static const char *scsi_command_name(uint8_t cmd)
         /* READ_POSITION and PRE_FETCH use the same operation code */
         [ SYNCHRONIZE_CACHE        ] = "SYNCHRONIZE_CACHE",
         [ LOCK_UNLOCK_CACHE        ] = "LOCK_UNLOCK_CACHE",
-        [ READ_DEFECT_DATA         ] = "READ_DEFECT_DATA",
+        [ READ_DEFECT_DATA         ] = "READ_DEFECT_DATA/INITIALIZE_ELEMENT_STATUS_WITH_RANGE",
+        /* READ_DEFECT_DATA and INITIALIZE_ELEMENT_STATUS_WITH_RANGE use the same operation code */
         [ MEDIUM_SCAN              ] = "MEDIUM_SCAN",
         [ COMPARE                  ] = "COMPARE",
         [ COPY_VERIFY              ] = "COPY_VERIFY",
@@ -1274,6 +1306,7 @@ static const char *scsi_command_name(uint8_t cmd)
         [ REPORT_LUNS              ] = "REPORT_LUNS",
         [ BLANK                    ] = "BLANK",
         [ MOVE_MEDIUM              ] = "MOVE_MEDIUM",
+        [ EXCHANGE_MEDIUM          ] = "EXCHANGE MEDIUM",
         [ LOAD_UNLOAD              ] = "LOAD_UNLOAD",
         [ READ_12                  ] = "READ_12",
         [ WRITE_12                 ] = "WRITE_12",
diff --git a/hw/scsi-defs.h b/hw/scsi-defs.h
index 6578bb9..ade82a4 100644
--- a/hw/scsi-defs.h
+++ b/hw/scsi-defs.h
@@ -29,6 +29,7 @@
 #define REQUEST_SENSE         0x03
 #define FORMAT_UNIT           0x04
 #define READ_BLOCK_LIMITS     0x05
+#define INITIALIZE_ELEMENT_STATUS 0x07
 #define REASSIGN_BLOCKS       0x07
 #define READ_6                0x08
 #define WRITE_6               0x0a
@@ -54,6 +55,7 @@
 #define WRITE_10              0x2a
 #define SEEK_10               0x2b
 #define LOCATE_10             0x2b
+#define POSITION_TO_ELEMENT   0x2b
 #define WRITE_VERIFY_10       0x2e
 #define VERIFY_10             0x2f
 #define SEARCH_HIGH           0x30
@@ -64,6 +66,7 @@
 #define READ_POSITION         0x34
 #define SYNCHRONIZE_CACHE     0x35
 #define LOCK_UNLOCK_CACHE     0x36
+#define INITIALIZE_ELEMENT_STATUS_WITH_RANGE 0x37
 #define READ_DEFECT_DATA      0x37
 #define MEDIUM_SCAN           0x38
 #define COMPARE               0x39
@@ -118,6 +121,7 @@
 #define MAINTENANCE_IN        0xa3
 #define MAINTENANCE_OUT       0xa4
 #define MOVE_MEDIUM           0xa5
+#define EXCHANGE_MEDIUM       0xa6
 #define SET_READ_AHEAD        0xa7
 #define READ_12               0xa8
 #define WRITE_12              0xaa
commit 28b70c9dbdce0d517ade9c04c7d7ae05c8b76d2f
Author: Paolo Bonzini <pbonzini at redhat.com>
Date:   Thu Jun 14 16:13:49 2012 +0200

    scsi: Ensure command and transfer lengths are set for all SCSI devices
    
    scsi-generic relies on those values to be correct, so it is important that
    those values are initialized properly for all device types.
    
    Reported-by: Christian Hoff <christian.hoff at de.ibm.com>
    Reported-by: Christian Borntraeger <borntraeger at de.ibm.com>
    Signed-off-by: Paolo Bonzini <pbonzini at redhat.com>

diff --git a/hw/scsi-bus.c b/hw/scsi-bus.c
index 2d4429c..4ec9b52 100644
--- a/hw/scsi-bus.c
+++ b/hw/scsi-bus.c
@@ -734,20 +734,16 @@ static int scsi_req_length(SCSICommand *cmd, SCSIDevice *dev, uint8_t *buf)
     switch (buf[0] >> 5) {
     case 0:
         cmd->xfer = buf[4];
-        cmd->len = 6;
         break;
     case 1:
     case 2:
         cmd->xfer = lduw_be_p(&buf[7]);
-        cmd->len = 10;
         break;
     case 4:
         cmd->xfer = ldl_be_p(&buf[10]) & 0xffffffffULL;
-        cmd->len = 16;
         break;
     case 5:
         cmd->xfer = ldl_be_p(&buf[6]) & 0xffffffffULL;
-        cmd->len = 12;
         break;
     default:
         return -1;
@@ -884,7 +880,6 @@ static int scsi_req_stream_length(SCSICommand *cmd, SCSIDevice *dev, uint8_t *bu
     case READ_REVERSE:
     case RECOVER_BUFFERED_DATA:
     case WRITE_6:
-        cmd->len = 6;
         cmd->xfer = buf[4] | (buf[3] << 8) | (buf[2] << 16);
         if (buf[1] & 0x01) { /* fixed */
             cmd->xfer *= dev->blocksize;
@@ -894,7 +889,6 @@ static int scsi_req_stream_length(SCSICommand *cmd, SCSIDevice *dev, uint8_t *bu
     case READ_REVERSE_16:
     case VERIFY_16:
     case WRITE_16:
-        cmd->len = 16;
         cmd->xfer = buf[14] | (buf[13] << 8) | (buf[12] << 16);
         if (buf[1] & 0x01) { /* fixed */
             cmd->xfer *= dev->blocksize;
@@ -902,7 +896,6 @@ static int scsi_req_stream_length(SCSICommand *cmd, SCSIDevice *dev, uint8_t *bu
         break;
     case REWIND:
     case LOAD_UNLOAD:
-        cmd->len = 6;
         cmd->xfer = 0;
         break;
     case SPACE_16:
@@ -1000,6 +993,24 @@ int scsi_req_parse(SCSICommand *cmd, SCSIDevice *dev, uint8_t *buf)
 {
     int rc;
 
+    switch (buf[0] >> 5) {
+    case 0:
+        cmd->len = 6;
+        break;
+    case 1:
+    case 2:
+        cmd->len = 10;
+        break;
+    case 4:
+        cmd->len = 16;
+        break;
+    case 5:
+        cmd->len = 12;
+        break;
+    default:
+        return -1;
+    }
+
     if (dev->type == TYPE_TAPE) {
         rc = scsi_req_stream_length(cmd, dev, buf);
     } else {
commit 15e58a21a8f48b6a00081587fa1fa23aa9159dfd
Author: Christian Hoff <christian.hoff at de.ibm.com>
Date:   Thu Jun 14 15:55:26 2012 +0200

    scsi: Fix LOAD_UNLOAD
    
    Change operation code of LOAD_UNLOAD command to 0x1b as described in
    section 7.3 of the SCSI Stream Commands spec.
    
    Signed-off-by: Christian Hoff <christian.hoff at de.ibm.com>
    Signed-off-by: Christian Borntraeger <borntraeger at de.ibm.com>
    Signed-off-by: Paolo Bonzini <pbonzini at redhat.com>

diff --git a/hw/scsi-bus.c b/hw/scsi-bus.c
index 4e95eee..2d4429c 100644
--- a/hw/scsi-bus.c
+++ b/hw/scsi-bus.c
@@ -771,7 +771,6 @@ static int scsi_req_length(SCSICommand *cmd, SCSIDevice *dev, uint8_t *buf)
     case SYNCHRONIZE_CACHE_16:
     case LOCATE_16:
     case LOCK_UNLOCK_CACHE:
-    case LOAD_UNLOAD:
     case SET_CD_SPEED:
     case SET_LIMITS:
     case WRITE_LONG_10:
@@ -902,7 +901,7 @@ static int scsi_req_stream_length(SCSICommand *cmd, SCSIDevice *dev, uint8_t *bu
         }
         break;
     case REWIND:
-    case START_STOP:
+    case LOAD_UNLOAD:
         cmd->len = 6;
         cmd->xfer = 0;
         break;
@@ -1200,7 +1199,8 @@ static const char *scsi_command_name(uint8_t cmd)
         [ COPY                     ] = "COPY",
         [ ERASE                    ] = "ERASE",
         [ MODE_SENSE               ] = "MODE_SENSE",
-        [ START_STOP               ] = "START_STOP",
+        [ START_STOP               ] = "START_STOP/LOAD_UNLOAD",
+        /* LOAD_UNLOAD and START_STOP use the same operation code */
         [ RECEIVE_DIAGNOSTIC       ] = "RECEIVE_DIAGNOSTIC",
         [ SEND_DIAGNOSTIC          ] = "SEND_DIAGNOSTIC",
         [ ALLOW_MEDIUM_REMOVAL     ] = "ALLOW_MEDIUM_REMOVAL",
diff --git a/hw/scsi-defs.h b/hw/scsi-defs.h
index 3c9f1b5..6578bb9 100644
--- a/hw/scsi-defs.h
+++ b/hw/scsi-defs.h
@@ -44,6 +44,7 @@
 #define COPY                  0x18
 #define ERASE                 0x19
 #define MODE_SENSE            0x1a
+#define LOAD_UNLOAD           0x1b
 #define START_STOP            0x1b
 #define RECEIVE_DIAGNOSTIC    0x1c
 #define SEND_DIAGNOSTIC       0x1d
@@ -117,7 +118,6 @@
 #define MAINTENANCE_IN        0xa3
 #define MAINTENANCE_OUT       0xa4
 #define MOVE_MEDIUM           0xa5
-#define LOAD_UNLOAD           0xa6
 #define SET_READ_AHEAD        0xa7
 #define READ_12               0xa8
 #define WRITE_12              0xaa
commit 335f560f9c7b63ede973d7b9712438f39ee2df61
Author: Christian Hoff <christian.hoff at de.ibm.com>
Date:   Thu Jun 14 15:55:25 2012 +0200

    scsi: Fix data length == SCSI_SENSE_BUF_SIZE
    
    Fix the edge case where the sense data length is exactly the same
    as SCSI_SENSE_BUF_SIZE.
    This makes SCSI requests work that use all of the available 95 byte
    sense data.
    
    Signed-off-by: Christian Hoff <christian.hoff at de.ibm.com>
    Signed-off-by: Christian Borntraeger <borntraeger at de.ibm.com>
    Signed-off-by: Paolo Bonzini <pbonzini at redhat.com>

diff --git a/hw/scsi-bus.c b/hw/scsi-bus.c
index 14e2f73..4e95eee 100644
--- a/hw/scsi-bus.c
+++ b/hw/scsi-bus.c
@@ -1389,7 +1389,7 @@ void scsi_req_complete(SCSIRequest *req, int status)
     assert(req->status == -1);
     req->status = status;
 
-    assert(req->sense_len < sizeof(req->sense));
+    assert(req->sense_len <= sizeof(req->sense));
     if (status == GOOD) {
         req->sense_len = 0;
     }
commit 619d7ae952bb61ec27ec21fe4a383a8d4dd4cd70
Author: Paolo Bonzini <pbonzini at redhat.com>
Date:   Tue Jun 12 18:37:25 2012 +0200

    virtio-scsi: do not crash on adding buffers to the event queue
    
    The event queue is not supported yet and the handler does not
    have to do much anyway when buffers are added.  However, the
    handler is called unconditionally by the virtio layer, and this
    results in a crash as soon as buffers are added to the event
    queue because we pass NULL.
    
    Reported-by: Bryan Venteicher <bryanv at daemoninthecloset.org>
    Signed-off-by: Paolo Bonzini <pbonzini at redhat.com>

diff --git a/hw/virtio-scsi.c b/hw/virtio-scsi.c
index e1a767e..0a5ac40 100644
--- a/hw/virtio-scsi.c
+++ b/hw/virtio-scsi.c
@@ -405,6 +405,10 @@ static void virtio_scsi_handle_ctrl(VirtIODevice *vdev, VirtQueue *vq)
     }
 }
 
+static void virtio_scsi_handle_event(VirtIODevice *vdev, VirtQueue *vq)
+{
+}
+
 static void virtio_scsi_command_complete(SCSIRequest *r, uint32_t status,
                                          size_t resid)
 {
@@ -609,7 +613,7 @@ VirtIODevice *virtio_scsi_init(DeviceState *dev, VirtIOSCSIConf *proxyconf)
     s->ctrl_vq = virtio_add_queue(&s->vdev, VIRTIO_SCSI_VQ_SIZE,
                                    virtio_scsi_handle_ctrl);
     s->event_vq = virtio_add_queue(&s->vdev, VIRTIO_SCSI_VQ_SIZE,
-                                   NULL);
+                                   virtio_scsi_handle_event);
     for (i = 0; i < s->conf->num_queues; i++) {
         s->cmd_vqs[i] = virtio_add_queue(&s->vdev, VIRTIO_SCSI_VQ_SIZE,
                                          virtio_scsi_handle_cmd);
commit e8f943c3bcc2a578bfd30b825f2ebaf345c63a09
Author: Hannes Reinecke <hare at suse.de>
Date:   Tue May 29 13:51:17 2012 +0200

    megasas: LSI Megaraid SAS HBA emulation
    
    This patch adds an emulation for the LSI Megaraid SAS 8708EM2 HBA.
    I've tested it to work with Linux, Windows Vista, and Windows7.
    
    Signed-off-by: Hannes Reinecke <hare at suse.de>
    [ Squashed trivial changes from Andreas Faerber, rebased over IOMMU
      and QBus changes - Paolo ]
    Signed-off-by: Paolo Bonzini <pbonzini at redhat.com>

diff --git a/default-configs/pci.mak b/default-configs/pci.mak
index 9d3e1db..4b49c00 100644
--- a/default-configs/pci.mak
+++ b/default-configs/pci.mak
@@ -10,6 +10,7 @@ CONFIG_EEPRO100_PCI=y
 CONFIG_PCNET_PCI=y
 CONFIG_PCNET_COMMON=y
 CONFIG_LSI_SCSI_PCI=y
+CONFIG_MEGASAS_SCSI_PCI=y
 CONFIG_RTL8139_PCI=y
 CONFIG_E1000_PCI=y
 CONFIG_IDE_CORE=y
diff --git a/hw/Makefile.objs b/hw/Makefile.objs
index 3d77259..9a350de 100644
--- a/hw/Makefile.objs
+++ b/hw/Makefile.objs
@@ -86,6 +86,7 @@ hw-obj-$(CONFIG_OPENCORES_ETH) += opencores_eth.o
 
 # SCSI layer
 hw-obj-$(CONFIG_LSI_SCSI_PCI) += lsi53c895a.o
+hw-obj-$(CONFIG_MEGASAS_SCSI_PCI) += megasas.o
 hw-obj-$(CONFIG_ESP) += esp.o
 
 hw-obj-y += sysbus.o isa-bus.o
diff --git a/hw/megasas.c b/hw/megasas.c
new file mode 100644
index 0000000..b48836f
--- /dev/null
+++ b/hw/megasas.c
@@ -0,0 +1,2198 @@
+/*
+ * QEMU MegaRAID SAS 8708EM2 Host Bus Adapter emulation
+ * Based on the linux driver code at drivers/scsi/megaraid
+ *
+ * Copyright (c) 2009-2012 Hannes Reinecke, SUSE Labs
+ *
+ * This library is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Lesser General Public
+ * License as published by the Free Software Foundation; either
+ * version 2 of the License, or (at your option) any later version.
+ *
+ * This library is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
+ * Lesser General Public License for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public
+ * License along with this library; if not, see <http://www.gnu.org/licenses/>.
+ */
+
+#include "hw.h"
+#include "pci.h"
+#include "dma.h"
+#include "msix.h"
+#include "iov.h"
+#include "scsi.h"
+#include "scsi-defs.h"
+#include "block_int.h"
+#include "trace.h"
+
+#include "mfi.h"
+
+#define MEGASAS_VERSION "1.70"
+#define MEGASAS_MAX_FRAMES 2048         /* Firmware limit at 65535 */
+#define MEGASAS_DEFAULT_FRAMES 1000     /* Windows requires this */
+#define MEGASAS_MAX_SGE 128             /* Firmware limit */
+#define MEGASAS_DEFAULT_SGE 80
+#define MEGASAS_MAX_SECTORS 0xFFFF      /* No real limit */
+#define MEGASAS_MAX_ARRAYS 128
+
+#define MEGASAS_FLAG_USE_JBOD      0
+#define MEGASAS_MASK_USE_JBOD      (1 << MEGASAS_FLAG_USE_JBOD)
+#define MEGASAS_FLAG_USE_MSIX      1
+#define MEGASAS_MASK_USE_MSIX      (1 << MEGASAS_FLAG_USE_MSIX)
+#define MEGASAS_FLAG_USE_QUEUE64   2
+#define MEGASAS_MASK_USE_QUEUE64   (1 << MEGASAS_FLAG_USE_QUEUE64)
+
+const char *mfi_frame_desc[] = {
+    "MFI init", "LD Read", "LD Write", "LD SCSI", "PD SCSI",
+    "MFI Doorbell", "MFI Abort", "MFI SMP", "MFI Stop"};
+
+typedef struct MegasasCmd {
+    uint32_t index;
+    uint16_t flags;
+    uint16_t count;
+    uint64_t context;
+
+    target_phys_addr_t pa;
+    target_phys_addr_t pa_size;
+    union mfi_frame *frame;
+    SCSIRequest *req;
+    QEMUSGList qsg;
+    void *iov_buf;
+    size_t iov_size;
+    size_t iov_offset;
+    struct MegasasState *state;
+} MegasasCmd;
+
+typedef struct MegasasState {
+    PCIDevice dev;
+    MemoryRegion mmio_io;
+    MemoryRegion port_io;
+    MemoryRegion queue_io;
+    uint32_t frame_hi;
+
+    int fw_state;
+    uint32_t fw_sge;
+    uint32_t fw_cmds;
+    uint32_t flags;
+    int fw_luns;
+    int intr_mask;
+    int doorbell;
+    int busy;
+
+    MegasasCmd *event_cmd;
+    int event_locale;
+    int event_class;
+    int event_count;
+    int shutdown_event;
+    int boot_event;
+
+    uint64_t reply_queue_pa;
+    void *reply_queue;
+    int reply_queue_len;
+    int reply_queue_head;
+    int reply_queue_tail;
+    uint64_t consumer_pa;
+    uint64_t producer_pa;
+
+    MegasasCmd frames[MEGASAS_MAX_FRAMES];
+
+    SCSIBus bus;
+} MegasasState;
+
+#define MEGASAS_INTR_DISABLED_MASK 0xFFFFFFFF
+
+static bool megasas_intr_enabled(MegasasState *s)
+{
+    if ((s->intr_mask & MEGASAS_INTR_DISABLED_MASK) !=
+        MEGASAS_INTR_DISABLED_MASK) {
+        return true;
+    }
+    return false;
+}
+
+static bool megasas_use_queue64(MegasasState *s)
+{
+    return s->flags & MEGASAS_MASK_USE_QUEUE64;
+}
+
+static bool megasas_use_msix(MegasasState *s)
+{
+    return s->flags & MEGASAS_MASK_USE_MSIX;
+}
+
+static bool megasas_is_jbod(MegasasState *s)
+{
+    return s->flags & MEGASAS_MASK_USE_JBOD;
+}
+
+static void megasas_frame_set_cmd_status(unsigned long frame, uint8_t v)
+{
+    stb_phys(frame + offsetof(struct mfi_frame_header, cmd_status), v);
+}
+
+static void megasas_frame_set_scsi_status(unsigned long frame, uint8_t v)
+{
+    stb_phys(frame + offsetof(struct mfi_frame_header, scsi_status), v);
+}
+
+/*
+ * Context is considered opaque, but the HBA firmware is running
+ * in little endian mode. So convert it to little endian, too.
+ */
+static uint64_t megasas_frame_get_context(unsigned long frame)
+{
+    return ldq_le_phys(frame + offsetof(struct mfi_frame_header, context));
+}
+
+static bool megasas_frame_is_ieee_sgl(MegasasCmd *cmd)
+{
+    return cmd->flags & MFI_FRAME_IEEE_SGL;
+}
+
+static bool megasas_frame_is_sgl64(MegasasCmd *cmd)
+{
+    return cmd->flags & MFI_FRAME_SGL64;
+}
+
+static bool megasas_frame_is_sense64(MegasasCmd *cmd)
+{
+    return cmd->flags & MFI_FRAME_SENSE64;
+}
+
+static uint64_t megasas_sgl_get_addr(MegasasCmd *cmd,
+                                     union mfi_sgl *sgl)
+{
+    uint64_t addr;
+
+    if (megasas_frame_is_ieee_sgl(cmd)) {
+        addr = le64_to_cpu(sgl->sg_skinny->addr);
+    } else if (megasas_frame_is_sgl64(cmd)) {
+        addr = le64_to_cpu(sgl->sg64->addr);
+    } else {
+        addr = le32_to_cpu(sgl->sg32->addr);
+    }
+    return addr;
+}
+
+static uint32_t megasas_sgl_get_len(MegasasCmd *cmd,
+                                    union mfi_sgl *sgl)
+{
+    uint32_t len;
+
+    if (megasas_frame_is_ieee_sgl(cmd)) {
+        len = le32_to_cpu(sgl->sg_skinny->len);
+    } else if (megasas_frame_is_sgl64(cmd)) {
+        len = le32_to_cpu(sgl->sg64->len);
+    } else {
+        len = le32_to_cpu(sgl->sg32->len);
+    }
+    return len;
+}
+
+static union mfi_sgl *megasas_sgl_next(MegasasCmd *cmd,
+                                       union mfi_sgl *sgl)
+{
+    uint8_t *next = (uint8_t *)sgl;
+
+    if (megasas_frame_is_ieee_sgl(cmd)) {
+        next += sizeof(struct mfi_sg_skinny);
+    } else if (megasas_frame_is_sgl64(cmd)) {
+        next += sizeof(struct mfi_sg64);
+    } else {
+        next += sizeof(struct mfi_sg32);
+    }
+
+    if (next >= (uint8_t *)cmd->frame + cmd->pa_size) {
+        return NULL;
+    }
+    return (union mfi_sgl *)next;
+}
+
+static void megasas_soft_reset(MegasasState *s);
+
+static int megasas_map_sgl(MegasasState *s, MegasasCmd *cmd, union mfi_sgl *sgl)
+{
+    int i;
+    int iov_count = 0;
+    size_t iov_size = 0;
+
+    cmd->flags = le16_to_cpu(cmd->frame->header.flags);
+    iov_count = cmd->frame->header.sge_count;
+    if (iov_count > MEGASAS_MAX_SGE) {
+        trace_megasas_iovec_sgl_overflow(cmd->index, iov_count,
+                                         MEGASAS_MAX_SGE);
+        return iov_count;
+    }
+    qemu_sglist_init(&cmd->qsg, iov_count, pci_dma_context(&s->dev));
+    for (i = 0; i < iov_count; i++) {
+        dma_addr_t iov_pa, iov_size_p;
+
+        if (!sgl) {
+            trace_megasas_iovec_sgl_underflow(cmd->index, i);
+            goto unmap;
+        }
+        iov_pa = megasas_sgl_get_addr(cmd, sgl);
+        iov_size_p = megasas_sgl_get_len(cmd, sgl);
+        if (!iov_pa || !iov_size_p) {
+            trace_megasas_iovec_sgl_invalid(cmd->index, i,
+                                            iov_pa, iov_size_p);
+            goto unmap;
+        }
+        qemu_sglist_add(&cmd->qsg, iov_pa, iov_size_p);
+        sgl = megasas_sgl_next(cmd, sgl);
+        iov_size += (size_t)iov_size_p;
+    }
+    if (cmd->iov_size > iov_size) {
+        trace_megasas_iovec_overflow(cmd->index, iov_size, cmd->iov_size);
+    } else if (cmd->iov_size < iov_size) {
+        trace_megasas_iovec_underflow(cmd->iov_size, iov_size, cmd->iov_size);
+    }
+    cmd->iov_offset = 0;
+    return 0;
+unmap:
+    qemu_sglist_destroy(&cmd->qsg);
+    return iov_count - i;
+}
+
+static void megasas_unmap_sgl(MegasasCmd *cmd)
+{
+    qemu_sglist_destroy(&cmd->qsg);
+    cmd->iov_offset = 0;
+}
+
+/*
+ * passthrough sense and io sense are at the same offset
+ */
+static int megasas_build_sense(MegasasCmd *cmd, uint8_t *sense_ptr,
+    uint8_t sense_len)
+{
+    uint32_t pa_hi = 0, pa_lo;
+    target_phys_addr_t pa;
+
+    if (sense_len > cmd->frame->header.sense_len) {
+        sense_len = cmd->frame->header.sense_len;
+    }
+    if (sense_len) {
+        pa_lo = le32_to_cpu(cmd->frame->pass.sense_addr_lo);
+        if (megasas_frame_is_sense64(cmd)) {
+            pa_hi = le32_to_cpu(cmd->frame->pass.sense_addr_hi);
+        }
+        pa = ((uint64_t) pa_hi << 32) | pa_lo;
+        cpu_physical_memory_write(pa, sense_ptr, sense_len);
+        cmd->frame->header.sense_len = sense_len;
+    }
+    return sense_len;
+}
+
+static void megasas_write_sense(MegasasCmd *cmd, SCSISense sense)
+{
+    uint8_t sense_buf[SCSI_SENSE_BUF_SIZE];
+    uint8_t sense_len = 18;
+
+    memset(sense_buf, 0, sense_len);
+    sense_buf[0] = 0xf0;
+    sense_buf[2] = sense.key;
+    sense_buf[7] = 10;
+    sense_buf[12] = sense.asc;
+    sense_buf[13] = sense.ascq;
+    megasas_build_sense(cmd, sense_buf, sense_len);
+}
+
+static void megasas_copy_sense(MegasasCmd *cmd)
+{
+    uint8_t sense_buf[SCSI_SENSE_BUF_SIZE];
+    uint8_t sense_len;
+
+    sense_len = scsi_req_get_sense(cmd->req, sense_buf,
+                                   SCSI_SENSE_BUF_SIZE);
+    megasas_build_sense(cmd, sense_buf, sense_len);
+}
+
+/*
+ * Format an INQUIRY CDB
+ */
+static int megasas_setup_inquiry(uint8_t *cdb, int pg, int len)
+{
+    memset(cdb, 0, 6);
+    cdb[0] = INQUIRY;
+    if (pg > 0) {
+        cdb[1] = 0x1;
+        cdb[2] = pg;
+    }
+    cdb[3] = (len >> 8) & 0xff;
+    cdb[4] = (len & 0xff);
+    return len;
+}
+
+/*
+ * Encode lba and len into a READ_16/WRITE_16 CDB
+ */
+static void megasas_encode_lba(uint8_t *cdb, uint64_t lba,
+                               uint32_t len, bool is_write)
+{
+    memset(cdb, 0x0, 16);
+    if (is_write) {
+        cdb[0] = WRITE_16;
+    } else {
+        cdb[0] = READ_16;
+    }
+    cdb[2] = (lba >> 56) & 0xff;
+    cdb[3] = (lba >> 48) & 0xff;
+    cdb[4] = (lba >> 40) & 0xff;
+    cdb[5] = (lba >> 32) & 0xff;
+    cdb[6] = (lba >> 24) & 0xff;
+    cdb[7] = (lba >> 16) & 0xff;
+    cdb[8] = (lba >> 8) & 0xff;
+    cdb[9] = (lba) & 0xff;
+    cdb[10] = (len >> 24) & 0xff;
+    cdb[11] = (len >> 16) & 0xff;
+    cdb[12] = (len >> 8) & 0xff;
+    cdb[13] = (len) & 0xff;
+}
+
+/*
+ * Utility functions
+ */
+static uint64_t megasas_fw_time(void)
+{
+    struct tm curtime;
+    uint64_t bcd_time;
+
+    qemu_get_timedate(&curtime, 0);
+    bcd_time = ((uint64_t)curtime.tm_sec & 0xff) << 48 |
+        ((uint64_t)curtime.tm_min & 0xff)  << 40 |
+        ((uint64_t)curtime.tm_hour & 0xff) << 32 |
+        ((uint64_t)curtime.tm_mday & 0xff) << 24 |
+        ((uint64_t)curtime.tm_mon & 0xff)  << 16 |
+        ((uint64_t)(curtime.tm_year + 1900) & 0xffff);
+
+    return bcd_time;
+}
+
+static uint64_t megasas_gen_sas_addr(uint64_t id)
+{
+    uint64_t addr;
+
+    addr = 0x5001a4aULL << 36;
+    addr |= id & 0xfffffffff;
+
+    return addr;
+}
+
+/*
+ * Frame handling
+ */
+static int megasas_next_index(MegasasState *s, int index, int limit)
+{
+    index++;
+    if (index == limit) {
+        index = 0;
+    }
+    return index;
+}
+
+static MegasasCmd *megasas_lookup_frame(MegasasState *s,
+    target_phys_addr_t frame)
+{
+    MegasasCmd *cmd = NULL;
+    int num = 0, index;
+
+    index = s->reply_queue_head;
+
+    while (num < s->fw_cmds) {
+        if (s->frames[index].pa && s->frames[index].pa == frame) {
+            cmd = &s->frames[index];
+            break;
+        }
+        index = megasas_next_index(s, index, s->fw_cmds);
+        num++;
+    }
+
+    return cmd;
+}
+
+static MegasasCmd *megasas_next_frame(MegasasState *s,
+    target_phys_addr_t frame)
+{
+    MegasasCmd *cmd = NULL;
+    int num = 0, index;
+
+    cmd = megasas_lookup_frame(s, frame);
+    if (cmd) {
+        trace_megasas_qf_found(cmd->index, cmd->pa);
+        return cmd;
+    }
+    index = s->reply_queue_head;
+    num = 0;
+    while (num < s->fw_cmds) {
+        if (!s->frames[index].pa) {
+            cmd = &s->frames[index];
+            break;
+        }
+        index = megasas_next_index(s, index, s->fw_cmds);
+        num++;
+    }
+    if (!cmd) {
+        trace_megasas_qf_failed(frame);
+    }
+    trace_megasas_qf_new(index, cmd);
+    return cmd;
+}
+
+static MegasasCmd *megasas_enqueue_frame(MegasasState *s,
+    target_phys_addr_t frame, uint64_t context, int count)
+{
+    MegasasCmd *cmd = NULL;
+    int frame_size = MFI_FRAME_SIZE * 16;
+    target_phys_addr_t frame_size_p = frame_size;
+
+    cmd = megasas_next_frame(s, frame);
+    /* All frames busy */
+    if (!cmd) {
+        return NULL;
+    }
+    if (!cmd->pa) {
+        cmd->pa = frame;
+        /* Map all possible frames */
+        cmd->frame = cpu_physical_memory_map(frame, &frame_size_p, 0);
+        if (frame_size_p != frame_size) {
+            trace_megasas_qf_map_failed(cmd->index, (unsigned long)frame);
+            if (cmd->frame) {
+                cpu_physical_memory_unmap(cmd->frame, frame_size_p, 0, 0);
+                cmd->frame = NULL;
+                cmd->pa = 0;
+            }
+            s->event_count++;
+            return NULL;
+        }
+        cmd->pa_size = frame_size_p;
+        cmd->context = context;
+        if (!megasas_use_queue64(s)) {
+            cmd->context &= (uint64_t)0xFFFFFFFF;
+        }
+    }
+    cmd->count = count;
+    s->busy++;
+
+    trace_megasas_qf_enqueue(cmd->index, cmd->count, cmd->context,
+                             s->reply_queue_head, s->busy);
+
+    return cmd;
+}
+
+static void megasas_complete_frame(MegasasState *s, uint64_t context)
+{
+    int tail, queue_offset;
+
+    /* Decrement busy count */
+    s->busy--;
+
+    if (s->reply_queue_pa) {
+        /*
+         * Put command on the reply queue.
+         * Context is opaque, but emulation is running in
+         * little endian. So convert it.
+         */
+        tail = s->reply_queue_head;
+        if (megasas_use_queue64(s)) {
+            queue_offset = tail * sizeof(uint64_t);
+            stq_le_phys(s->reply_queue_pa + queue_offset, context);
+        } else {
+            queue_offset = tail * sizeof(uint32_t);
+            stl_le_phys(s->reply_queue_pa + queue_offset, context);
+        }
+        s->reply_queue_head = megasas_next_index(s, tail, s->fw_cmds);
+        trace_megasas_qf_complete(context, tail, queue_offset,
+                                  s->busy, s->doorbell);
+    }
+
+    if (megasas_intr_enabled(s)) {
+        /* Notify HBA */
+        s->doorbell++;
+        if (s->doorbell == 1) {
+            if (msix_enabled(&s->dev)) {
+                trace_megasas_msix_raise(0);
+                msix_notify(&s->dev, 0);
+            } else {
+                trace_megasas_irq_raise();
+                qemu_irq_raise(s->dev.irq[0]);
+            }
+        }
+    } else {
+        trace_megasas_qf_complete_noirq(context);
+    }
+}
+
+static void megasas_reset_frames(MegasasState *s)
+{
+    int i;
+    MegasasCmd *cmd;
+
+    for (i = 0; i < s->fw_cmds; i++) {
+        cmd = &s->frames[i];
+        if (cmd->pa) {
+            cpu_physical_memory_unmap(cmd->frame, cmd->pa_size, 0, 0);
+            cmd->frame = NULL;
+            cmd->pa = 0;
+        }
+    }
+}
+
+static void megasas_abort_command(MegasasCmd *cmd)
+{
+    if (cmd->req) {
+        scsi_req_abort(cmd->req, ABORTED_COMMAND);
+        cmd->req = NULL;
+    }
+}
+
+static int megasas_init_firmware(MegasasState *s, MegasasCmd *cmd)
+{
+    uint32_t pa_hi, pa_lo;
+    target_phys_addr_t iq_pa, initq_size;
+    struct mfi_init_qinfo *initq;
+    uint32_t flags;
+    int ret = MFI_STAT_OK;
+
+    pa_lo = le32_to_cpu(cmd->frame->init.qinfo_new_addr_lo);
+    pa_hi = le32_to_cpu(cmd->frame->init.qinfo_new_addr_hi);
+    iq_pa = (((uint64_t) pa_hi << 32) | pa_lo);
+    trace_megasas_init_firmware((uint64_t)iq_pa);
+    initq_size = sizeof(*initq);
+    initq = cpu_physical_memory_map(iq_pa, &initq_size, 0);
+    if (!initq || initq_size != sizeof(*initq)) {
+        trace_megasas_initq_map_failed(cmd->index);
+        s->event_count++;
+        ret = MFI_STAT_MEMORY_NOT_AVAILABLE;
+        goto out;
+    }
+    s->reply_queue_len = le32_to_cpu(initq->rq_entries) & 0xFFFF;
+    if (s->reply_queue_len > s->fw_cmds) {
+        trace_megasas_initq_mismatch(s->reply_queue_len, s->fw_cmds);
+        s->event_count++;
+        ret = MFI_STAT_INVALID_PARAMETER;
+        goto out;
+    }
+    pa_lo = le32_to_cpu(initq->rq_addr_lo);
+    pa_hi = le32_to_cpu(initq->rq_addr_hi);
+    s->reply_queue_pa = ((uint64_t) pa_hi << 32) | pa_lo;
+    pa_lo = le32_to_cpu(initq->ci_addr_lo);
+    pa_hi = le32_to_cpu(initq->ci_addr_hi);
+    s->consumer_pa = ((uint64_t) pa_hi << 32) | pa_lo;
+    pa_lo = le32_to_cpu(initq->pi_addr_lo);
+    pa_hi = le32_to_cpu(initq->pi_addr_hi);
+    s->producer_pa = ((uint64_t) pa_hi << 32) | pa_lo;
+    s->reply_queue_head = ldl_le_phys(s->producer_pa);
+    s->reply_queue_tail = ldl_le_phys(s->consumer_pa);
+    flags = le32_to_cpu(initq->flags);
+    if (flags & MFI_QUEUE_FLAG_CONTEXT64) {
+        s->flags |= MEGASAS_MASK_USE_QUEUE64;
+    }
+    trace_megasas_init_queue((unsigned long)s->reply_queue_pa,
+                             s->reply_queue_len, s->reply_queue_head,
+                             s->reply_queue_tail, flags);
+    megasas_reset_frames(s);
+    s->fw_state = MFI_FWSTATE_OPERATIONAL;
+out:
+    if (initq) {
+        cpu_physical_memory_unmap(initq, initq_size, 0, 0);
+    }
+    return ret;
+}
+
+static int megasas_map_dcmd(MegasasState *s, MegasasCmd *cmd)
+{
+    dma_addr_t iov_pa, iov_size;
+
+    cmd->flags = le16_to_cpu(cmd->frame->header.flags);
+    if (!cmd->frame->header.sge_count) {
+        trace_megasas_dcmd_zero_sge(cmd->index);
+        cmd->iov_size = 0;
+        return 0;
+    } else if (cmd->frame->header.sge_count > 1) {
+        trace_megasas_dcmd_invalid_sge(cmd->index,
+                                       cmd->frame->header.sge_count);
+        cmd->iov_size = 0;
+        return -1;
+    }
+    iov_pa = megasas_sgl_get_addr(cmd, &cmd->frame->dcmd.sgl);
+    iov_size = megasas_sgl_get_len(cmd, &cmd->frame->dcmd.sgl);
+    qemu_sglist_init(&cmd->qsg, 1, pci_dma_context(&s->dev));
+    qemu_sglist_add(&cmd->qsg, iov_pa, iov_size);
+    cmd->iov_size = iov_size;
+    return cmd->iov_size;
+}
+
+static void megasas_finish_dcmd(MegasasCmd *cmd, uint32_t iov_size)
+{
+    trace_megasas_finish_dcmd(cmd->index, iov_size);
+
+    if (cmd->frame->header.sge_count) {
+        qemu_sglist_destroy(&cmd->qsg);
+    }
+    if (iov_size > cmd->iov_size) {
+        if (megasas_frame_is_ieee_sgl(cmd)) {
+            cmd->frame->dcmd.sgl.sg_skinny->len = cpu_to_le32(iov_size);
+        } else if (megasas_frame_is_sgl64(cmd)) {
+            cmd->frame->dcmd.sgl.sg64->len = cpu_to_le32(iov_size);
+        } else {
+            cmd->frame->dcmd.sgl.sg32->len = cpu_to_le32(iov_size);
+        }
+    }
+    cmd->iov_size = 0;
+    return;
+}
+
+static int megasas_ctrl_get_info(MegasasState *s, MegasasCmd *cmd)
+{
+    struct mfi_ctrl_info info;
+    size_t dcmd_size = sizeof(info);
+    BusChild *kid;
+    int num_ld_disks = 0;
+
+    QTAILQ_FOREACH(kid, &s->bus.qbus.children, sibling) {
+        num_ld_disks++;
+    }
+
+    memset(&info, 0x0, cmd->iov_size);
+    if (cmd->iov_size < dcmd_size) {
+        trace_megasas_dcmd_invalid_xfer_len(cmd->index, cmd->iov_size,
+                                            dcmd_size);
+        return MFI_STAT_INVALID_PARAMETER;
+    }
+
+    info.pci.vendor = cpu_to_le16(PCI_VENDOR_ID_LSI_LOGIC);
+    info.pci.device = cpu_to_le16(PCI_DEVICE_ID_LSI_SAS1078);
+    info.pci.subvendor = cpu_to_le16(PCI_VENDOR_ID_LSI_LOGIC);
+    info.pci.subdevice = cpu_to_le16(0x1013);
+
+    info.host.type = MFI_INFO_HOST_PCIX;
+    info.device.type = MFI_INFO_DEV_SAS3G;
+    info.device.port_count = 2;
+    info.device.port_addr[0] = cpu_to_le64(megasas_gen_sas_addr((uint64_t)s));
+
+    memcpy(info.product_name, "MegaRAID SAS 8708EM2", 20);
+    snprintf(info.serial_number, 32, "QEMU%08lx",
+             (unsigned long)s & 0xFFFFFFFF);
+    snprintf(info.package_version, 0x60, "%s-QEMU", QEMU_VERSION);
+    memcpy(info.image_component[0].name, "APP", 3);
+    memcpy(info.image_component[0].version, MEGASAS_VERSION "-QEMU", 9);
+    memcpy(info.image_component[0].build_date, __DATE__, 11);
+    memcpy(info.image_component[0].build_time, __TIME__, 8);
+    info.image_component_count = 1;
+    if (s->dev.has_rom) {
+        uint8_t biosver[32];
+        uint8_t *ptr;
+
+        ptr = memory_region_get_ram_ptr(&s->dev.rom);
+        memcpy(biosver, ptr + 0x41, 31);
+        qemu_put_ram_ptr(ptr);
+        memcpy(info.image_component[1].name, "BIOS", 4);
+        memcpy(info.image_component[1].version, biosver,
+               strlen((const char *)biosver));
+        info.image_component_count++;
+    }
+    info.current_fw_time = cpu_to_le32(megasas_fw_time());
+    info.max_arms = 32;
+    info.max_spans = 8;
+    info.max_arrays = MEGASAS_MAX_ARRAYS;
+    info.max_lds = s->fw_luns;
+    info.max_cmds = cpu_to_le16(s->fw_cmds);
+    info.max_sg_elements = cpu_to_le16(s->fw_sge);
+    info.max_request_size = cpu_to_le32(MEGASAS_MAX_SECTORS);
+    info.lds_present = cpu_to_le16(num_ld_disks);
+    info.pd_present = cpu_to_le16(num_ld_disks);
+    info.pd_disks_present = cpu_to_le16(num_ld_disks);
+    info.hw_present = cpu_to_le32(MFI_INFO_HW_NVRAM |
+                                   MFI_INFO_HW_MEM |
+                                   MFI_INFO_HW_FLASH);
+    info.memory_size = cpu_to_le16(512);
+    info.nvram_size = cpu_to_le16(32);
+    info.flash_size = cpu_to_le16(16);
+    info.raid_levels = cpu_to_le32(MFI_INFO_RAID_0);
+    info.adapter_ops = cpu_to_le32(MFI_INFO_AOPS_RBLD_RATE |
+                                    MFI_INFO_AOPS_SELF_DIAGNOSTIC |
+                                    MFI_INFO_AOPS_MIXED_ARRAY);
+    info.ld_ops = cpu_to_le32(MFI_INFO_LDOPS_DISK_CACHE_POLICY |
+                               MFI_INFO_LDOPS_ACCESS_POLICY |
+                               MFI_INFO_LDOPS_IO_POLICY |
+                               MFI_INFO_LDOPS_WRITE_POLICY |
+                               MFI_INFO_LDOPS_READ_POLICY);
+    info.max_strips_per_io = cpu_to_le16(s->fw_sge);
+    info.stripe_sz_ops.min = 3;
+    info.stripe_sz_ops.max = ffs(MEGASAS_MAX_SECTORS + 1) - 1;
+    info.properties.pred_fail_poll_interval = cpu_to_le16(300);
+    info.properties.intr_throttle_cnt = cpu_to_le16(16);
+    info.properties.intr_throttle_timeout = cpu_to_le16(50);
+    info.properties.rebuild_rate = 30;
+    info.properties.patrol_read_rate = 30;
+    info.properties.bgi_rate = 30;
+    info.properties.cc_rate = 30;
+    info.properties.recon_rate = 30;
+    info.properties.cache_flush_interval = 4;
+    info.properties.spinup_drv_cnt = 2;
+    info.properties.spinup_delay = 6;
+    info.properties.ecc_bucket_size = 15;
+    info.properties.ecc_bucket_leak_rate = cpu_to_le16(1440);
+    info.properties.expose_encl_devices = 1;
+    info.properties.OnOffProperties = cpu_to_le32(MFI_CTRL_PROP_EnableJBOD);
+    info.pd_ops = cpu_to_le32(MFI_INFO_PDOPS_FORCE_ONLINE |
+                               MFI_INFO_PDOPS_FORCE_OFFLINE);
+    info.pd_mix_support = cpu_to_le32(MFI_INFO_PDMIX_SAS |
+                                       MFI_INFO_PDMIX_SATA |
+                                       MFI_INFO_PDMIX_LD);
+
+    cmd->iov_size -= dma_buf_read((uint8_t *)&info, dcmd_size, &cmd->qsg);
+    return MFI_STAT_OK;
+}
+
+static int megasas_mfc_get_defaults(MegasasState *s, MegasasCmd *cmd)
+{
+    struct mfi_defaults info;
+    size_t dcmd_size = sizeof(struct mfi_defaults);
+
+    memset(&info, 0x0, dcmd_size);
+    if (cmd->iov_size < dcmd_size) {
+        trace_megasas_dcmd_invalid_xfer_len(cmd->index, cmd->iov_size,
+                                            dcmd_size);
+        return MFI_STAT_INVALID_PARAMETER;
+    }
+
+    info.sas_addr = cpu_to_le64(megasas_gen_sas_addr((uint64_t)s));
+    info.stripe_size = 3;
+    info.flush_time = 4;
+    info.background_rate = 30;
+    info.allow_mix_in_enclosure = 1;
+    info.allow_mix_in_ld = 1;
+    info.direct_pd_mapping = 1;
+    /* Enable for BIOS support */
+    info.bios_enumerate_lds = 1;
+    info.disable_ctrl_r = 1;
+    info.expose_enclosure_devices = 1;
+    info.disable_preboot_cli = 1;
+    info.cluster_disable = 1;
+
+    cmd->iov_size -= dma_buf_read((uint8_t *)&info, dcmd_size, &cmd->qsg);
+    return MFI_STAT_OK;
+}
+
+static int megasas_dcmd_get_bios_info(MegasasState *s, MegasasCmd *cmd)
+{
+    struct mfi_bios_data info;
+    size_t dcmd_size = sizeof(info);
+
+    memset(&info, 0x0, dcmd_size);
+    if (cmd->iov_size < dcmd_size) {
+        trace_megasas_dcmd_invalid_xfer_len(cmd->index, cmd->iov_size,
+                                            dcmd_size);
+        return MFI_STAT_INVALID_PARAMETER;
+    }
+    info.continue_on_error = 1;
+    info.verbose = 1;
+    if (megasas_is_jbod(s)) {
+        info.expose_all_drives = 1;
+    }
+
+    cmd->iov_size -= dma_buf_read((uint8_t *)&info, dcmd_size, &cmd->qsg);
+    return MFI_STAT_OK;
+}
+
+static int megasas_dcmd_get_fw_time(MegasasState *s, MegasasCmd *cmd)
+{
+    uint64_t fw_time;
+    size_t dcmd_size = sizeof(fw_time);
+
+    fw_time = cpu_to_le64(megasas_fw_time());
+
+    cmd->iov_size -= dma_buf_read((uint8_t *)&fw_time, dcmd_size, &cmd->qsg);
+    return MFI_STAT_OK;
+}
+
+static int megasas_dcmd_set_fw_time(MegasasState *s, MegasasCmd *cmd)
+{
+    uint64_t fw_time;
+
+    /* This is a dummy; setting of firmware time is not allowed */
+    memcpy(&fw_time, cmd->frame->dcmd.mbox, sizeof(fw_time));
+
+    trace_megasas_dcmd_set_fw_time(cmd->index, fw_time);
+    fw_time = cpu_to_le64(megasas_fw_time());
+    return MFI_STAT_OK;
+}
+
+static int megasas_event_info(MegasasState *s, MegasasCmd *cmd)
+{
+    struct mfi_evt_log_state info;
+    size_t dcmd_size = sizeof(info);
+
+    memset(&info, 0, dcmd_size);
+
+    info.newest_seq_num = cpu_to_le32(s->event_count);
+    info.shutdown_seq_num = cpu_to_le32(s->shutdown_event);
+    info.boot_seq_num = cpu_to_le32(s->boot_event);
+
+    cmd->iov_size -= dma_buf_read((uint8_t *)&info, dcmd_size, &cmd->qsg);
+    return MFI_STAT_OK;
+}
+
+static int megasas_event_wait(MegasasState *s, MegasasCmd *cmd)
+{
+    union mfi_evt event;
+
+    if (cmd->iov_size < sizeof(struct mfi_evt_detail)) {
+        trace_megasas_dcmd_invalid_xfer_len(cmd->index, cmd->iov_size,
+                                            sizeof(struct mfi_evt_detail));
+        return MFI_STAT_INVALID_PARAMETER;
+    }
+    s->event_count = cpu_to_le32(cmd->frame->dcmd.mbox[0]);
+    event.word = cpu_to_le32(cmd->frame->dcmd.mbox[4]);
+    s->event_locale = event.members.locale;
+    s->event_class = event.members.class;
+    s->event_cmd = cmd;
+    /* Decrease busy count; event frame doesn't count here */
+    s->busy--;
+    cmd->iov_size = sizeof(struct mfi_evt_detail);
+    return MFI_STAT_INVALID_STATUS;
+}
+
+static int megasas_dcmd_pd_get_list(MegasasState *s, MegasasCmd *cmd)
+{
+    struct mfi_pd_list info;
+    size_t dcmd_size = sizeof(info);
+    BusChild *kid;
+    uint32_t offset, dcmd_limit, num_pd_disks = 0, max_pd_disks;
+    uint16_t sdev_id;
+
+    memset(&info, 0, dcmd_size);
+    offset = 8;
+    dcmd_limit = offset + sizeof(struct mfi_pd_address);
+    if (cmd->iov_size < dcmd_limit) {
+        trace_megasas_dcmd_invalid_xfer_len(cmd->index, cmd->iov_size,
+                                            dcmd_limit);
+        return MFI_STAT_INVALID_PARAMETER;
+    }
+
+    max_pd_disks = (cmd->iov_size - offset) / sizeof(struct mfi_pd_address);
+    if (max_pd_disks > s->fw_luns) {
+        max_pd_disks = s->fw_luns;
+    }
+
+    QTAILQ_FOREACH(kid, &s->bus.qbus.children, sibling) {
+        SCSIDevice *sdev = DO_UPCAST(SCSIDevice, qdev, kid->child);
+
+        sdev_id = ((sdev->id & 0xFF) >> 8) | (sdev->lun & 0xFF);
+        info.addr[num_pd_disks].device_id = cpu_to_le16(sdev_id);
+        info.addr[num_pd_disks].encl_device_id = 0xFFFF;
+        info.addr[num_pd_disks].encl_index = 0;
+        info.addr[num_pd_disks].slot_number = (sdev->id & 0xFF);
+        info.addr[num_pd_disks].scsi_dev_type = sdev->type;
+        info.addr[num_pd_disks].connect_port_bitmap = 0x1;
+        info.addr[num_pd_disks].sas_addr[0] =
+            cpu_to_le64(megasas_gen_sas_addr((uint64_t)sdev));
+        num_pd_disks++;
+        offset += sizeof(struct mfi_pd_address);
+    }
+    trace_megasas_dcmd_pd_get_list(cmd->index, num_pd_disks,
+                                   max_pd_disks, offset);
+
+    info.size = cpu_to_le32(offset);
+    info.count = cpu_to_le32(num_pd_disks);
+
+    cmd->iov_size -= dma_buf_read((uint8_t *)&info, offset, &cmd->qsg);
+    return MFI_STAT_OK;
+}
+
+static int megasas_dcmd_pd_list_query(MegasasState *s, MegasasCmd *cmd)
+{
+    uint16_t flags;
+
+    /* mbox0 contains flags */
+    flags = le16_to_cpu(cmd->frame->dcmd.mbox[0]);
+    trace_megasas_dcmd_pd_list_query(cmd->index, flags);
+    if (flags == MR_PD_QUERY_TYPE_ALL ||
+        megasas_is_jbod(s)) {
+        return megasas_dcmd_pd_get_list(s, cmd);
+    }
+
+    return MFI_STAT_OK;
+}
+
+static int megasas_pd_get_info_submit(SCSIDevice *sdev, int lun,
+                                      MegasasCmd *cmd)
+{
+    struct mfi_pd_info *info = cmd->iov_buf;
+    size_t dcmd_size = sizeof(struct mfi_pd_info);
+    BlockConf *conf = &sdev->conf;
+    uint64_t pd_size;
+    uint16_t sdev_id = ((sdev->id & 0xFF) >> 8) | (lun & 0xFF);
+    uint8_t cmdbuf[6];
+    SCSIRequest *req;
+    size_t len, resid;
+
+    if (!cmd->iov_buf) {
+        cmd->iov_buf = g_malloc(dcmd_size);
+        memset(cmd->iov_buf, 0, dcmd_size);
+        info = cmd->iov_buf;
+        info->inquiry_data[0] = 0x7f; /* Force PQual 0x3, PType 0x1f */
+        info->vpd_page83[0] = 0x7f;
+        megasas_setup_inquiry(cmdbuf, 0, sizeof(info->inquiry_data));
+        req = scsi_req_new(sdev, cmd->index, lun, cmdbuf, cmd);
+        if (!req) {
+            trace_megasas_dcmd_req_alloc_failed(cmd->index,
+                                                "PD get info std inquiry");
+            g_free(cmd->iov_buf);
+            cmd->iov_buf = NULL;
+            return MFI_STAT_FLASH_ALLOC_FAIL;
+        }
+        trace_megasas_dcmd_internal_submit(cmd->index,
+                                           "PD get info std inquiry", lun);
+        len = scsi_req_enqueue(req);
+        if (len > 0) {
+            cmd->iov_size = len;
+            scsi_req_continue(req);
+        }
+        return MFI_STAT_INVALID_STATUS;
+    } else if (info->inquiry_data[0] != 0x7f && info->vpd_page83[0] == 0x7f) {
+        megasas_setup_inquiry(cmdbuf, 0x83, sizeof(info->vpd_page83));
+        req = scsi_req_new(sdev, cmd->index, lun, cmdbuf, cmd);
+        if (!req) {
+            trace_megasas_dcmd_req_alloc_failed(cmd->index,
+                                                "PD get info vpd inquiry");
+            return MFI_STAT_FLASH_ALLOC_FAIL;
+        }
+        trace_megasas_dcmd_internal_submit(cmd->index,
+                                           "PD get info vpd inquiry", lun);
+        len = scsi_req_enqueue(req);
+        if (len > 0) {
+            cmd->iov_size = len;
+            scsi_req_continue(req);
+        }
+        return MFI_STAT_INVALID_STATUS;
+    }
+    /* Finished, set FW state */
+    if ((info->inquiry_data[0] >> 5) == 0) {
+        if (megasas_is_jbod(cmd->state)) {
+            info->fw_state = cpu_to_le16(MFI_PD_STATE_SYSTEM);
+        } else {
+            info->fw_state = cpu_to_le16(MFI_PD_STATE_ONLINE);
+        }
+    } else {
+        info->fw_state = cpu_to_le16(MFI_PD_STATE_OFFLINE);
+    }
+
+    info->ref.v.device_id = cpu_to_le16(sdev_id);
+    info->state.ddf.pd_type = cpu_to_le16(MFI_PD_DDF_TYPE_IN_VD|
+                                          MFI_PD_DDF_TYPE_INTF_SAS);
+    bdrv_get_geometry(conf->bs, &pd_size);
+    info->raw_size = cpu_to_le64(pd_size);
+    info->non_coerced_size = cpu_to_le64(pd_size);
+    info->coerced_size = cpu_to_le64(pd_size);
+    info->encl_device_id = 0xFFFF;
+    info->slot_number = (sdev->id & 0xFF);
+    info->path_info.count = 1;
+    info->path_info.sas_addr[0] =
+        cpu_to_le64(megasas_gen_sas_addr((uint64_t)sdev));
+    info->connected_port_bitmap = 0x1;
+    info->device_speed = 1;
+    info->link_speed = 1;
+    resid = dma_buf_read(cmd->iov_buf, dcmd_size, &cmd->qsg);
+    g_free(cmd->iov_buf);
+    cmd->iov_size = dcmd_size - resid;
+    cmd->iov_buf = NULL;
+    return MFI_STAT_OK;
+}
+
+static int megasas_dcmd_pd_get_info(MegasasState *s, MegasasCmd *cmd)
+{
+    size_t dcmd_size = sizeof(struct mfi_pd_info);
+    uint16_t pd_id;
+    SCSIDevice *sdev = NULL;
+    int retval = MFI_STAT_DEVICE_NOT_FOUND;
+
+    if (cmd->iov_size < dcmd_size) {
+        return MFI_STAT_INVALID_PARAMETER;
+    }
+
+    /* mbox0 has the ID */
+    pd_id = le16_to_cpu(cmd->frame->dcmd.mbox[0]);
+    sdev = scsi_device_find(&s->bus, 0, pd_id, 0);
+    trace_megasas_dcmd_pd_get_info(cmd->index, pd_id);
+
+    if (sdev) {
+        /* Submit inquiry */
+        retval = megasas_pd_get_info_submit(sdev, pd_id, cmd);
+    }
+
+    return retval;
+}
+
+static int megasas_dcmd_ld_get_list(MegasasState *s, MegasasCmd *cmd)
+{
+    struct mfi_ld_list info;
+    size_t dcmd_size = sizeof(info), resid;
+    uint32_t num_ld_disks = 0, max_ld_disks = s->fw_luns;
+    uint64_t ld_size;
+    BusChild *kid;
+
+    memset(&info, 0, dcmd_size);
+    if (cmd->iov_size < dcmd_size) {
+        trace_megasas_dcmd_invalid_xfer_len(cmd->index, cmd->iov_size,
+                                            dcmd_size);
+        return MFI_STAT_INVALID_PARAMETER;
+    }
+
+    if (megasas_is_jbod(s)) {
+        max_ld_disks = 0;
+    }
+    QTAILQ_FOREACH(kid, &s->bus.qbus.children, sibling) {
+        SCSIDevice *sdev = DO_UPCAST(SCSIDevice, qdev, kid->child);
+        BlockConf *conf = &sdev->conf;
+
+        if (num_ld_disks >= max_ld_disks) {
+            break;
+        }
+        /* Logical device size is in blocks */
+        bdrv_get_geometry(conf->bs, &ld_size);
+        info.ld_list[num_ld_disks].ld.v.target_id = sdev->id;
+        info.ld_list[num_ld_disks].state = MFI_LD_STATE_OPTIMAL;
+        info.ld_list[num_ld_disks].size = cpu_to_le64(ld_size);
+        num_ld_disks++;
+    }
+    info.ld_count = cpu_to_le32(num_ld_disks);
+    trace_megasas_dcmd_ld_get_list(cmd->index, num_ld_disks, max_ld_disks);
+
+    resid = dma_buf_read((uint8_t *)&info, dcmd_size, &cmd->qsg);
+    cmd->iov_size = dcmd_size - resid;
+    return MFI_STAT_OK;
+}
+
+static int megasas_ld_get_info_submit(SCSIDevice *sdev, int lun,
+                                      MegasasCmd *cmd)
+{
+    struct mfi_ld_info *info = cmd->iov_buf;
+    size_t dcmd_size = sizeof(struct mfi_ld_info);
+    uint8_t cdb[6];
+    SCSIRequest *req;
+    ssize_t len, resid;
+    BlockConf *conf = &sdev->conf;
+    uint16_t sdev_id = ((sdev->id & 0xFF) >> 8) | (lun & 0xFF);
+    uint64_t ld_size;
+
+    if (!cmd->iov_buf) {
+        cmd->iov_buf = g_malloc(dcmd_size);
+        memset(cmd->iov_buf, 0x0, dcmd_size);
+        info = cmd->iov_buf;
+        megasas_setup_inquiry(cdb, 0x83, sizeof(info->vpd_page83));
+        req = scsi_req_new(sdev, cmd->index, lun, cdb, cmd);
+        if (!req) {
+            trace_megasas_dcmd_req_alloc_failed(cmd->index,
+                                                "LD get info vpd inquiry");
+            g_free(cmd->iov_buf);
+            cmd->iov_buf = NULL;
+            return MFI_STAT_FLASH_ALLOC_FAIL;
+        }
+        trace_megasas_dcmd_internal_submit(cmd->index,
+                                           "LD get info vpd inquiry", lun);
+        len = scsi_req_enqueue(req);
+        if (len > 0) {
+            cmd->iov_size = len;
+            scsi_req_continue(req);
+        }
+        return MFI_STAT_INVALID_STATUS;
+    }
+
+    info->ld_config.params.state = MFI_LD_STATE_OPTIMAL;
+    info->ld_config.properties.ld.v.target_id = lun;
+    info->ld_config.params.stripe_size = 3;
+    info->ld_config.params.num_drives = 1;
+    info->ld_config.params.is_consistent = 1;
+    /* Logical device size is in blocks */
+    bdrv_get_geometry(conf->bs, &ld_size);
+    info->size = cpu_to_le64(ld_size);
+    memset(info->ld_config.span, 0, sizeof(info->ld_config.span));
+    info->ld_config.span[0].start_block = 0;
+    info->ld_config.span[0].num_blocks = info->size;
+    info->ld_config.span[0].array_ref = cpu_to_le16(sdev_id);
+
+    resid = dma_buf_read(cmd->iov_buf, dcmd_size, &cmd->qsg);
+    g_free(cmd->iov_buf);
+    cmd->iov_size = dcmd_size - resid;
+    cmd->iov_buf = NULL;
+    return MFI_STAT_OK;
+}
+
+static int megasas_dcmd_ld_get_info(MegasasState *s, MegasasCmd *cmd)
+{
+    struct mfi_ld_info info;
+    size_t dcmd_size = sizeof(info);
+    uint16_t ld_id;
+    uint32_t max_ld_disks = s->fw_luns;
+    SCSIDevice *sdev = NULL;
+    int retval = MFI_STAT_DEVICE_NOT_FOUND;
+
+    if (cmd->iov_size < dcmd_size) {
+        return MFI_STAT_INVALID_PARAMETER;
+    }
+
+    /* mbox0 has the ID */
+    ld_id = le16_to_cpu(cmd->frame->dcmd.mbox[0]);
+    trace_megasas_dcmd_ld_get_info(cmd->index, ld_id);
+
+    if (megasas_is_jbod(s)) {
+        return MFI_STAT_DEVICE_NOT_FOUND;
+    }
+
+    if (ld_id < max_ld_disks) {
+        sdev = scsi_device_find(&s->bus, 0, ld_id, 0);
+    }
+
+    if (sdev) {
+        retval = megasas_ld_get_info_submit(sdev, ld_id, cmd);
+    }
+
+    return retval;
+}
+
+static int megasas_dcmd_cfg_read(MegasasState *s, MegasasCmd *cmd)
+{
+    uint8_t data[4096];
+    struct mfi_config_data *info;
+    int num_pd_disks = 0, array_offset, ld_offset;
+    BusChild *kid;
+
+    if (cmd->iov_size > 4096) {
+        return MFI_STAT_INVALID_PARAMETER;
+    }
+
+    QTAILQ_FOREACH(kid, &s->bus.qbus.children, sibling) {
+        num_pd_disks++;
+    }
+    info = (struct mfi_config_data *)&data;
+    /*
+     * Array mapping:
+     * - One array per SCSI device
+     * - One logical drive per SCSI device
+     *   spanning the entire device
+     */
+    info->array_count = num_pd_disks;
+    info->array_size = sizeof(struct mfi_array) * num_pd_disks;
+    info->log_drv_count = num_pd_disks;
+    info->log_drv_size = sizeof(struct mfi_ld_config) * num_pd_disks;
+    info->spares_count = 0;
+    info->spares_size = sizeof(struct mfi_spare);
+    info->size = sizeof(struct mfi_config_data) + info->array_size +
+        info->log_drv_size;
+    if (info->size > 4096) {
+        return MFI_STAT_INVALID_PARAMETER;
+    }
+
+    array_offset = sizeof(struct mfi_config_data);
+    ld_offset = array_offset + sizeof(struct mfi_array) * num_pd_disks;
+
+    QTAILQ_FOREACH(kid, &s->bus.qbus.children, sibling) {
+        SCSIDevice *sdev = DO_UPCAST(SCSIDevice, qdev, kid->child);
+        BlockConf *conf = &sdev->conf;
+        uint16_t sdev_id = ((sdev->id & 0xFF) >> 8) | (sdev->lun & 0xFF);
+        struct mfi_array *array;
+        struct mfi_ld_config *ld;
+        uint64_t pd_size;
+        int i;
+
+        array = (struct mfi_array *)(data + array_offset);
+        bdrv_get_geometry(conf->bs, &pd_size);
+        array->size = cpu_to_le64(pd_size);
+        array->num_drives = 1;
+        array->array_ref = cpu_to_le16(sdev_id);
+        array->pd[0].ref.v.device_id = cpu_to_le16(sdev_id);
+        array->pd[0].ref.v.seq_num = 0;
+        array->pd[0].fw_state = MFI_PD_STATE_ONLINE;
+        array->pd[0].encl.pd = 0xFF;
+        array->pd[0].encl.slot = (sdev->id & 0xFF);
+        for (i = 1; i < MFI_MAX_ROW_SIZE; i++) {
+            array->pd[i].ref.v.device_id = 0xFFFF;
+            array->pd[i].ref.v.seq_num = 0;
+            array->pd[i].fw_state = MFI_PD_STATE_UNCONFIGURED_GOOD;
+            array->pd[i].encl.pd = 0xFF;
+            array->pd[i].encl.slot = 0xFF;
+        }
+        array_offset += sizeof(struct mfi_array);
+        ld = (struct mfi_ld_config *)(data + ld_offset);
+        memset(ld, 0, sizeof(struct mfi_ld_config));
+        ld->properties.ld.v.target_id = (sdev->id & 0xFF);
+        ld->properties.default_cache_policy = MR_LD_CACHE_READ_AHEAD |
+            MR_LD_CACHE_READ_ADAPTIVE;
+        ld->properties.current_cache_policy = MR_LD_CACHE_READ_AHEAD |
+            MR_LD_CACHE_READ_ADAPTIVE;
+        ld->params.state = MFI_LD_STATE_OPTIMAL;
+        ld->params.stripe_size = 3;
+        ld->params.num_drives = 1;
+        ld->params.span_depth = 1;
+        ld->params.is_consistent = 1;
+        ld->span[0].start_block = 0;
+        ld->span[0].num_blocks = cpu_to_le64(pd_size);
+        ld->span[0].array_ref = cpu_to_le16(sdev_id);
+        ld_offset += sizeof(struct mfi_ld_config);
+    }
+
+    cmd->iov_size -= dma_buf_read((uint8_t *)data, info->size, &cmd->qsg);
+    return MFI_STAT_OK;
+}
+
+static int megasas_dcmd_get_properties(MegasasState *s, MegasasCmd *cmd)
+{
+    struct mfi_ctrl_props info;
+    size_t dcmd_size = sizeof(info);
+
+    memset(&info, 0x0, dcmd_size);
+    if (cmd->iov_size < dcmd_size) {
+        trace_megasas_dcmd_invalid_xfer_len(cmd->index, cmd->iov_size,
+                                            dcmd_size);
+        return MFI_STAT_INVALID_PARAMETER;
+    }
+    info.pred_fail_poll_interval = cpu_to_le16(300);
+    info.intr_throttle_cnt = cpu_to_le16(16);
+    info.intr_throttle_timeout = cpu_to_le16(50);
+    info.rebuild_rate = 30;
+    info.patrol_read_rate = 30;
+    info.bgi_rate = 30;
+    info.cc_rate = 30;
+    info.recon_rate = 30;
+    info.cache_flush_interval = 4;
+    info.spinup_drv_cnt = 2;
+    info.spinup_delay = 6;
+    info.ecc_bucket_size = 15;
+    info.ecc_bucket_leak_rate = cpu_to_le16(1440);
+    info.expose_encl_devices = 1;
+
+    cmd->iov_size -= dma_buf_read((uint8_t *)&info, dcmd_size, &cmd->qsg);
+    return MFI_STAT_OK;
+}
+
+static int megasas_cache_flush(MegasasState *s, MegasasCmd *cmd)
+{
+    qemu_aio_flush();
+    return MFI_STAT_OK;
+}
+
+static int megasas_ctrl_shutdown(MegasasState *s, MegasasCmd *cmd)
+{
+    s->fw_state = MFI_FWSTATE_READY;
+    return MFI_STAT_OK;
+}
+
+static int megasas_cluster_reset_ld(MegasasState *s, MegasasCmd *cmd)
+{
+    return MFI_STAT_INVALID_DCMD;
+}
+
+static int megasas_dcmd_set_properties(MegasasState *s, MegasasCmd *cmd)
+{
+    uint8_t *dummy = g_malloc(cmd->iov_size);
+
+    dma_buf_write(dummy, cmd->iov_size, &cmd->qsg);
+
+    trace_megasas_dcmd_dump_frame(0,
+            dummy[0x00], dummy[0x01], dummy[0x02], dummy[0x03],
+            dummy[0x04], dummy[0x05], dummy[0x06], dummy[0x07]);
+    trace_megasas_dcmd_dump_frame(1,
+            dummy[0x08], dummy[0x09], dummy[0x0a], dummy[0x0b],
+            dummy[0x0c], dummy[0x0d], dummy[0x0e], dummy[0x0f]);
+    trace_megasas_dcmd_dump_frame(2,
+            dummy[0x10], dummy[0x11], dummy[0x12], dummy[0x13],
+            dummy[0x14], dummy[0x15], dummy[0x16], dummy[0x17]);
+    trace_megasas_dcmd_dump_frame(3,
+            dummy[0x18], dummy[0x19], dummy[0x1a], dummy[0x1b],
+            dummy[0x1c], dummy[0x1d], dummy[0x1e], dummy[0x1f]);
+    trace_megasas_dcmd_dump_frame(4,
+            dummy[0x20], dummy[0x21], dummy[0x22], dummy[0x23],
+            dummy[0x24], dummy[0x25], dummy[0x26], dummy[0x27]);
+    trace_megasas_dcmd_dump_frame(5,
+            dummy[0x28], dummy[0x29], dummy[0x2a], dummy[0x2b],
+            dummy[0x2c], dummy[0x2d], dummy[0x2e], dummy[0x2f]);
+    trace_megasas_dcmd_dump_frame(6,
+            dummy[0x30], dummy[0x31], dummy[0x32], dummy[0x33],
+            dummy[0x34], dummy[0x35], dummy[0x36], dummy[0x37]);
+    trace_megasas_dcmd_dump_frame(7,
+            dummy[0x38], dummy[0x39], dummy[0x3a], dummy[0x3b],
+            dummy[0x3c], dummy[0x3d], dummy[0x3e], dummy[0x3f]);
+    g_free(dummy);
+    return MFI_STAT_OK;
+}
+
+static int megasas_dcmd_dummy(MegasasState *s, MegasasCmd *cmd)
+{
+    trace_megasas_dcmd_dummy(cmd->index, cmd->iov_size);
+    return MFI_STAT_OK;
+}
+
+static const struct dcmd_cmd_tbl_t {
+    int opcode;
+    const char *desc;
+    int (*func)(MegasasState *s, MegasasCmd *cmd);
+} dcmd_cmd_tbl[] = {
+    { MFI_DCMD_CTRL_MFI_HOST_MEM_ALLOC, "CTRL_HOST_MEM_ALLOC",
+      megasas_dcmd_dummy },
+    { MFI_DCMD_CTRL_GET_INFO, "CTRL_GET_INFO",
+      megasas_ctrl_get_info },
+    { MFI_DCMD_CTRL_GET_PROPERTIES, "CTRL_GET_PROPERTIES",
+      megasas_dcmd_get_properties },
+    { MFI_DCMD_CTRL_SET_PROPERTIES, "CTRL_SET_PROPERTIES",
+      megasas_dcmd_set_properties },
+    { MFI_DCMD_CTRL_ALARM_GET, "CTRL_ALARM_GET",
+      megasas_dcmd_dummy },
+    { MFI_DCMD_CTRL_ALARM_ENABLE, "CTRL_ALARM_ENABLE",
+      megasas_dcmd_dummy },
+    { MFI_DCMD_CTRL_ALARM_DISABLE, "CTRL_ALARM_DISABLE",
+      megasas_dcmd_dummy },
+    { MFI_DCMD_CTRL_ALARM_SILENCE, "CTRL_ALARM_SILENCE",
+      megasas_dcmd_dummy },
+    { MFI_DCMD_CTRL_ALARM_TEST, "CTRL_ALARM_TEST",
+      megasas_dcmd_dummy },
+    { MFI_DCMD_CTRL_EVENT_GETINFO, "CTRL_EVENT_GETINFO",
+      megasas_event_info },
+    { MFI_DCMD_CTRL_EVENT_GET, "CTRL_EVENT_GET",
+      megasas_dcmd_dummy },
+    { MFI_DCMD_CTRL_EVENT_WAIT, "CTRL_EVENT_WAIT",
+      megasas_event_wait },
+    { MFI_DCMD_CTRL_SHUTDOWN, "CTRL_SHUTDOWN",
+      megasas_ctrl_shutdown },
+    { MFI_DCMD_HIBERNATE_STANDBY, "CTRL_STANDBY",
+      megasas_dcmd_dummy },
+    { MFI_DCMD_CTRL_GET_TIME, "CTRL_GET_TIME",
+      megasas_dcmd_get_fw_time },
+    { MFI_DCMD_CTRL_SET_TIME, "CTRL_SET_TIME",
+      megasas_dcmd_set_fw_time },
+    { MFI_DCMD_CTRL_BIOS_DATA_GET, "CTRL_BIOS_DATA_GET",
+      megasas_dcmd_get_bios_info },
+    { MFI_DCMD_CTRL_FACTORY_DEFAULTS, "CTRL_FACTORY_DEFAULTS",
+      megasas_dcmd_dummy },
+    { MFI_DCMD_CTRL_MFC_DEFAULTS_GET, "CTRL_MFC_DEFAULTS_GET",
+      megasas_mfc_get_defaults },
+    { MFI_DCMD_CTRL_MFC_DEFAULTS_SET, "CTRL_MFC_DEFAULTS_SET",
+      megasas_dcmd_dummy },
+    { MFI_DCMD_CTRL_CACHE_FLUSH, "CTRL_CACHE_FLUSH",
+      megasas_cache_flush },
+    { MFI_DCMD_PD_GET_LIST, "PD_GET_LIST",
+      megasas_dcmd_pd_get_list },
+    { MFI_DCMD_PD_LIST_QUERY, "PD_LIST_QUERY",
+      megasas_dcmd_pd_list_query },
+    { MFI_DCMD_PD_GET_INFO, "PD_GET_INFO",
+      megasas_dcmd_pd_get_info },
+    { MFI_DCMD_PD_STATE_SET, "PD_STATE_SET",
+      megasas_dcmd_dummy },
+    { MFI_DCMD_PD_REBUILD, "PD_REBUILD",
+      megasas_dcmd_dummy },
+    { MFI_DCMD_PD_BLINK, "PD_BLINK",
+      megasas_dcmd_dummy },
+    { MFI_DCMD_PD_UNBLINK, "PD_UNBLINK",
+      megasas_dcmd_dummy },
+    { MFI_DCMD_LD_GET_LIST, "LD_GET_LIST",
+      megasas_dcmd_ld_get_list},
+    { MFI_DCMD_LD_GET_INFO, "LD_GET_INFO",
+      megasas_dcmd_ld_get_info },
+    { MFI_DCMD_LD_GET_PROP, "LD_GET_PROP",
+      megasas_dcmd_dummy },
+    { MFI_DCMD_LD_SET_PROP, "LD_SET_PROP",
+      megasas_dcmd_dummy },
+    { MFI_DCMD_LD_DELETE, "LD_DELETE",
+      megasas_dcmd_dummy },
+    { MFI_DCMD_CFG_READ, "CFG_READ",
+      megasas_dcmd_cfg_read },
+    { MFI_DCMD_CFG_ADD, "CFG_ADD",
+      megasas_dcmd_dummy },
+    { MFI_DCMD_CFG_CLEAR, "CFG_CLEAR",
+      megasas_dcmd_dummy },
+    { MFI_DCMD_CFG_FOREIGN_READ, "CFG_FOREIGN_READ",
+      megasas_dcmd_dummy },
+    { MFI_DCMD_CFG_FOREIGN_IMPORT, "CFG_FOREIGN_IMPORT",
+      megasas_dcmd_dummy },
+    { MFI_DCMD_BBU_STATUS, "BBU_STATUS",
+      megasas_dcmd_dummy },
+    { MFI_DCMD_BBU_CAPACITY_INFO, "BBU_CAPACITY_INFO",
+      megasas_dcmd_dummy },
+    { MFI_DCMD_BBU_DESIGN_INFO, "BBU_DESIGN_INFO",
+      megasas_dcmd_dummy },
+    { MFI_DCMD_BBU_PROP_GET, "BBU_PROP_GET",
+      megasas_dcmd_dummy },
+    { MFI_DCMD_CLUSTER, "CLUSTER",
+      megasas_dcmd_dummy },
+    { MFI_DCMD_CLUSTER_RESET_ALL, "CLUSTER_RESET_ALL",
+      megasas_dcmd_dummy },
+    { MFI_DCMD_CLUSTER_RESET_LD, "CLUSTER_RESET_LD",
+      megasas_cluster_reset_ld },
+    { -1, NULL, NULL }
+};
+
+static int megasas_handle_dcmd(MegasasState *s, MegasasCmd *cmd)
+{
+    int opcode, len;
+    int retval = 0;
+    const struct dcmd_cmd_tbl_t *cmdptr = dcmd_cmd_tbl;
+
+    opcode = le32_to_cpu(cmd->frame->dcmd.opcode);
+    trace_megasas_handle_dcmd(cmd->index, opcode);
+    len = megasas_map_dcmd(s, cmd);
+    if (len < 0) {
+        return MFI_STAT_MEMORY_NOT_AVAILABLE;
+    }
+    while (cmdptr->opcode != -1 && cmdptr->opcode != opcode) {
+        cmdptr++;
+    }
+    if (cmdptr->opcode == -1) {
+        trace_megasas_dcmd_unhandled(cmd->index, opcode, len);
+        retval = megasas_dcmd_dummy(s, cmd);
+    } else {
+        trace_megasas_dcmd_enter(cmd->index, cmdptr->desc, len);
+        retval = cmdptr->func(s, cmd);
+    }
+    if (retval != MFI_STAT_INVALID_STATUS) {
+        megasas_finish_dcmd(cmd, len);
+    }
+    return retval;
+}
+
+static int megasas_finish_internal_dcmd(MegasasCmd *cmd,
+                                        SCSIRequest *req)
+{
+    int opcode;
+    int retval = MFI_STAT_OK;
+    int lun = req->lun;
+
+    opcode = le32_to_cpu(cmd->frame->dcmd.opcode);
+    scsi_req_unref(req);
+    trace_megasas_dcmd_internal_finish(cmd->index, opcode, lun);
+    switch (opcode) {
+    case MFI_DCMD_PD_GET_INFO:
+        retval = megasas_pd_get_info_submit(req->dev, lun, cmd);
+        break;
+    case MFI_DCMD_LD_GET_INFO:
+        retval = megasas_ld_get_info_submit(req->dev, lun, cmd);
+        break;
+    default:
+        trace_megasas_dcmd_internal_invalid(cmd->index, opcode);
+        retval = MFI_STAT_INVALID_DCMD;
+        break;
+    }
+    if (retval != MFI_STAT_INVALID_STATUS) {
+        megasas_finish_dcmd(cmd, cmd->iov_size);
+    }
+    return retval;
+}
+
+static int megasas_enqueue_req(MegasasCmd *cmd, bool is_write)
+{
+    int len;
+
+    len = scsi_req_enqueue(cmd->req);
+    if (len < 0) {
+        len = -len;
+    }
+    if (len > 0) {
+        if (len > cmd->iov_size) {
+            if (is_write) {
+                trace_megasas_iov_write_overflow(cmd->index, len,
+                                                 cmd->iov_size);
+            } else {
+                trace_megasas_iov_read_overflow(cmd->index, len,
+                                                cmd->iov_size);
+            }
+        }
+        if (len < cmd->iov_size) {
+            if (is_write) {
+                trace_megasas_iov_write_underflow(cmd->index, len,
+                                                  cmd->iov_size);
+            } else {
+                trace_megasas_iov_read_underflow(cmd->index, len,
+                                                 cmd->iov_size);
+            }
+            cmd->iov_size = len;
+        }
+        scsi_req_continue(cmd->req);
+    }
+    return len;
+}
+
+static int megasas_handle_scsi(MegasasState *s, MegasasCmd *cmd,
+                               bool is_logical)
+{
+    uint8_t *cdb;
+    int len;
+    bool is_write;
+    struct SCSIDevice *sdev = NULL;
+
+    cdb = cmd->frame->pass.cdb;
+
+    if (cmd->frame->header.target_id < s->fw_luns) {
+        sdev = scsi_device_find(&s->bus, 0, cmd->frame->header.target_id,
+                                cmd->frame->header.lun_id);
+    }
+    cmd->iov_size = le32_to_cpu(cmd->frame->header.data_len);
+    trace_megasas_handle_scsi(mfi_frame_desc[cmd->frame->header.frame_cmd],
+                              is_logical, cmd->frame->header.target_id,
+                              cmd->frame->header.lun_id, sdev, cmd->iov_size);
+
+    if (!sdev || (megasas_is_jbod(s) && is_logical)) {
+        trace_megasas_scsi_target_not_present(
+            mfi_frame_desc[cmd->frame->header.frame_cmd], is_logical,
+            cmd->frame->header.target_id, cmd->frame->header.lun_id);
+        return MFI_STAT_DEVICE_NOT_FOUND;
+    }
+
+    if (cmd->frame->header.cdb_len > 16) {
+        trace_megasas_scsi_invalid_cdb_len(
+                mfi_frame_desc[cmd->frame->header.frame_cmd], is_logical,
+                cmd->frame->header.target_id, cmd->frame->header.lun_id,
+                cmd->frame->header.cdb_len);
+        megasas_write_sense(cmd, SENSE_CODE(INVALID_OPCODE));
+        cmd->frame->header.scsi_status = CHECK_CONDITION;
+        s->event_count++;
+        return MFI_STAT_SCSI_DONE_WITH_ERROR;
+    }
+
+    if (megasas_map_sgl(s, cmd, &cmd->frame->pass.sgl)) {
+        megasas_write_sense(cmd, SENSE_CODE(TARGET_FAILURE));
+        cmd->frame->header.scsi_status = CHECK_CONDITION;
+        s->event_count++;
+        return MFI_STAT_SCSI_DONE_WITH_ERROR;
+    }
+
+    cmd->req = scsi_req_new(sdev, cmd->index,
+                            cmd->frame->header.lun_id, cdb, cmd);
+    if (!cmd->req) {
+        trace_megasas_scsi_req_alloc_failed(
+                mfi_frame_desc[cmd->frame->header.frame_cmd],
+                cmd->frame->header.target_id, cmd->frame->header.lun_id);
+        megasas_write_sense(cmd, SENSE_CODE(NO_SENSE));
+        cmd->frame->header.scsi_status = BUSY;
+        s->event_count++;
+        return MFI_STAT_SCSI_DONE_WITH_ERROR;
+    }
+
+    is_write = (cmd->req->cmd.mode == SCSI_XFER_TO_DEV);
+    len = megasas_enqueue_req(cmd, is_write);
+    if (len > 0) {
+        if (is_write) {
+            trace_megasas_scsi_write_start(cmd->index, len);
+        } else {
+            trace_megasas_scsi_read_start(cmd->index, len);
+        }
+    } else {
+        trace_megasas_scsi_nodata(cmd->index);
+    }
+    return MFI_STAT_INVALID_STATUS;
+}
+
+static int megasas_handle_io(MegasasState *s, MegasasCmd *cmd)
+{
+    uint32_t lba_count, lba_start_hi, lba_start_lo;
+    uint64_t lba_start;
+    bool is_write = (cmd->frame->header.frame_cmd == MFI_CMD_LD_WRITE);
+    uint8_t cdb[16];
+    int len;
+    struct SCSIDevice *sdev = NULL;
+
+    lba_count = le32_to_cpu(cmd->frame->io.header.data_len);
+    lba_start_lo = le32_to_cpu(cmd->frame->io.lba_lo);
+    lba_start_hi = le32_to_cpu(cmd->frame->io.lba_hi);
+    lba_start = ((uint64_t)lba_start_hi << 32) | lba_start_lo;
+
+    if (cmd->frame->header.target_id < s->fw_luns) {
+        sdev = scsi_device_find(&s->bus, 0, cmd->frame->header.target_id,
+                                cmd->frame->header.lun_id);
+    }
+
+    trace_megasas_handle_io(cmd->index,
+                            mfi_frame_desc[cmd->frame->header.frame_cmd],
+                            cmd->frame->header.target_id,
+                            cmd->frame->header.lun_id,
+                            (unsigned long)lba_start, (unsigned long)lba_count);
+    if (!sdev) {
+        trace_megasas_io_target_not_present(cmd->index,
+            mfi_frame_desc[cmd->frame->header.frame_cmd],
+            cmd->frame->header.target_id, cmd->frame->header.lun_id);
+        return MFI_STAT_DEVICE_NOT_FOUND;
+    }
+
+    if (cmd->frame->header.cdb_len > 16) {
+        trace_megasas_scsi_invalid_cdb_len(
+            mfi_frame_desc[cmd->frame->header.frame_cmd], 1,
+            cmd->frame->header.target_id, cmd->frame->header.lun_id,
+            cmd->frame->header.cdb_len);
+        megasas_write_sense(cmd, SENSE_CODE(INVALID_OPCODE));
+        cmd->frame->header.scsi_status = CHECK_CONDITION;
+        s->event_count++;
+        return MFI_STAT_SCSI_DONE_WITH_ERROR;
+    }
+
+    cmd->iov_size = lba_count * sdev->blocksize;
+    if (megasas_map_sgl(s, cmd, &cmd->frame->io.sgl)) {
+        megasas_write_sense(cmd, SENSE_CODE(TARGET_FAILURE));
+        cmd->frame->header.scsi_status = CHECK_CONDITION;
+        s->event_count++;
+        return MFI_STAT_SCSI_DONE_WITH_ERROR;
+    }
+
+    megasas_encode_lba(cdb, lba_start, lba_count, is_write);
+    cmd->req = scsi_req_new(sdev, cmd->index,
+                            cmd->frame->header.lun_id, cdb, cmd);
+    if (!cmd->req) {
+        trace_megasas_scsi_req_alloc_failed(
+            mfi_frame_desc[cmd->frame->header.frame_cmd],
+            cmd->frame->header.target_id, cmd->frame->header.lun_id);
+        megasas_write_sense(cmd, SENSE_CODE(NO_SENSE));
+        cmd->frame->header.scsi_status = BUSY;
+        s->event_count++;
+        return MFI_STAT_SCSI_DONE_WITH_ERROR;
+    }
+    len = megasas_enqueue_req(cmd, is_write);
+    if (len > 0) {
+        if (is_write) {
+            trace_megasas_io_write_start(cmd->index, lba_start, lba_count, len);
+        } else {
+            trace_megasas_io_read_start(cmd->index, lba_start, lba_count, len);
+        }
+    }
+    return MFI_STAT_INVALID_STATUS;
+}
+
+static int megasas_finish_internal_command(MegasasCmd *cmd,
+                                           SCSIRequest *req, size_t resid)
+{
+    int retval = MFI_STAT_INVALID_CMD;
+
+    if (cmd->frame->header.frame_cmd == MFI_CMD_DCMD) {
+        cmd->iov_size -= resid;
+        retval = megasas_finish_internal_dcmd(cmd, req);
+    }
+    return retval;
+}
+
+static QEMUSGList *megasas_get_sg_list(SCSIRequest *req)
+{
+    MegasasCmd *cmd = req->hba_private;
+
+    if (cmd->frame->header.frame_cmd == MFI_CMD_DCMD) {
+        return NULL;
+    } else {
+        return &cmd->qsg;
+    }
+}
+
+static void megasas_xfer_complete(SCSIRequest *req, uint32_t len)
+{
+    MegasasCmd *cmd = req->hba_private;
+    uint8_t *buf;
+    uint32_t opcode;
+
+    trace_megasas_io_complete(cmd->index, len);
+
+    if (cmd->frame->header.frame_cmd != MFI_CMD_DCMD) {
+        scsi_req_continue(req);
+        return;
+    }
+
+    buf = scsi_req_get_buf(req);
+    opcode = le32_to_cpu(cmd->frame->dcmd.opcode);
+    if (opcode == MFI_DCMD_PD_GET_INFO && cmd->iov_buf) {
+        struct mfi_pd_info *info = cmd->iov_buf;
+
+        if (info->inquiry_data[0] == 0x7f) {
+            memset(info->inquiry_data, 0, sizeof(info->inquiry_data));
+            memcpy(info->inquiry_data, buf, len);
+        } else if (info->vpd_page83[0] == 0x7f) {
+            memset(info->vpd_page83, 0, sizeof(info->vpd_page83));
+            memcpy(info->vpd_page83, buf, len);
+        }
+        scsi_req_continue(req);
+    } else if (opcode == MFI_DCMD_LD_GET_INFO) {
+        struct mfi_ld_info *info = cmd->iov_buf;
+
+        if (cmd->iov_buf) {
+            memcpy(info->vpd_page83, buf, sizeof(info->vpd_page83));
+            scsi_req_continue(req);
+        }
+    }
+}
+
+static void megasas_command_complete(SCSIRequest *req, uint32_t status,
+                                     size_t resid)
+{
+    MegasasCmd *cmd = req->hba_private;
+    uint8_t cmd_status = MFI_STAT_OK;
+
+    trace_megasas_command_complete(cmd->index, status, resid);
+
+    if (cmd->req != req) {
+        /*
+         * Internal command complete
+         */
+        cmd_status = megasas_finish_internal_command(cmd, req, resid);
+        if (cmd_status == MFI_STAT_INVALID_STATUS) {
+            return;
+        }
+    } else {
+        req->status = status;
+        trace_megasas_scsi_complete(cmd->index, req->status,
+                                    cmd->iov_size, req->cmd.xfer);
+        if (req->status != GOOD) {
+            cmd_status = MFI_STAT_SCSI_DONE_WITH_ERROR;
+        }
+        if (req->status == CHECK_CONDITION) {
+            megasas_copy_sense(cmd);
+        }
+
+        megasas_unmap_sgl(cmd);
+        cmd->frame->header.scsi_status = req->status;
+        scsi_req_unref(cmd->req);
+        cmd->req = NULL;
+    }
+    cmd->frame->header.cmd_status = cmd_status;
+    megasas_complete_frame(cmd->state, cmd->context);
+}
+
+static void megasas_command_cancel(SCSIRequest *req)
+{
+    MegasasCmd *cmd = req->hba_private;
+
+    if (cmd) {
+        megasas_abort_command(cmd);
+    } else {
+        scsi_req_unref(req);
+    }
+}
+
+static int megasas_handle_abort(MegasasState *s, MegasasCmd *cmd)
+{
+    uint64_t abort_ctx = le64_to_cpu(cmd->frame->abort.abort_context);
+    target_phys_addr_t abort_addr, addr_hi, addr_lo;
+    MegasasCmd *abort_cmd;
+
+    addr_hi = le32_to_cpu(cmd->frame->abort.abort_mfi_addr_hi);
+    addr_lo = le32_to_cpu(cmd->frame->abort.abort_mfi_addr_lo);
+    abort_addr = ((uint64_t)addr_hi << 32) | addr_lo;
+
+    abort_cmd = megasas_lookup_frame(s, abort_addr);
+    if (!abort_cmd) {
+        trace_megasas_abort_no_cmd(cmd->index, abort_ctx);
+        s->event_count++;
+        return MFI_STAT_OK;
+    }
+    if (!megasas_use_queue64(s)) {
+        abort_ctx &= (uint64_t)0xFFFFFFFF;
+    }
+    if (abort_cmd->context != abort_ctx) {
+        trace_megasas_abort_invalid_context(cmd->index, abort_cmd->index,
+                                            abort_cmd->context);
+        s->event_count++;
+        return MFI_STAT_ABORT_NOT_POSSIBLE;
+    }
+    trace_megasas_abort_frame(cmd->index, abort_cmd->index);
+    megasas_abort_command(abort_cmd);
+    if (!s->event_cmd || abort_cmd != s->event_cmd) {
+        s->event_cmd = NULL;
+    }
+    s->event_count++;
+    return MFI_STAT_OK;
+}
+
+static void megasas_handle_frame(MegasasState *s, uint64_t frame_addr,
+                                 uint32_t frame_count)
+{
+    uint8_t frame_status = MFI_STAT_INVALID_CMD;
+    uint64_t frame_context;
+    MegasasCmd *cmd;
+
+    /*
+     * Always read 64bit context, top bits will be
+     * masked out if required in megasas_enqueue_frame()
+     */
+    frame_context = megasas_frame_get_context(frame_addr);
+
+    cmd = megasas_enqueue_frame(s, frame_addr, frame_context, frame_count);
+    if (!cmd) {
+        /* reply queue full */
+        trace_megasas_frame_busy(frame_addr);
+        megasas_frame_set_scsi_status(frame_addr, BUSY);
+        megasas_frame_set_cmd_status(frame_addr, MFI_STAT_SCSI_DONE_WITH_ERROR);
+        megasas_complete_frame(s, frame_context);
+        s->event_count++;
+        return;
+    }
+    switch (cmd->frame->header.frame_cmd) {
+    case MFI_CMD_INIT:
+        frame_status = megasas_init_firmware(s, cmd);
+        break;
+    case MFI_CMD_DCMD:
+        frame_status = megasas_handle_dcmd(s, cmd);
+        break;
+    case MFI_CMD_ABORT:
+        frame_status = megasas_handle_abort(s, cmd);
+        break;
+    case MFI_CMD_PD_SCSI_IO:
+        frame_status = megasas_handle_scsi(s, cmd, 0);
+        break;
+    case MFI_CMD_LD_SCSI_IO:
+        frame_status = megasas_handle_scsi(s, cmd, 1);
+        break;
+    case MFI_CMD_LD_READ:
+    case MFI_CMD_LD_WRITE:
+        frame_status = megasas_handle_io(s, cmd);
+        break;
+    default:
+        trace_megasas_unhandled_frame_cmd(cmd->index,
+                                          cmd->frame->header.frame_cmd);
+        s->event_count++;
+        break;
+    }
+    if (frame_status != MFI_STAT_INVALID_STATUS) {
+        if (cmd->frame) {
+            cmd->frame->header.cmd_status = frame_status;
+        } else {
+            megasas_frame_set_cmd_status(frame_addr, frame_status);
+        }
+        megasas_complete_frame(s, cmd->context);
+    }
+}
+
+static uint64_t megasas_mmio_read(void *opaque, target_phys_addr_t addr,
+                                  unsigned size)
+{
+    MegasasState *s = opaque;
+    uint32_t retval = 0;
+
+    switch (addr) {
+    case MFI_IDB:
+        retval = 0;
+        break;
+    case MFI_OMSG0:
+    case MFI_OSP0:
+        retval = (megasas_use_msix(s) ? MFI_FWSTATE_MSIX_SUPPORTED : 0) |
+            (s->fw_state & MFI_FWSTATE_MASK) |
+            ((s->fw_sge & 0xff) << 16) |
+            (s->fw_cmds & 0xFFFF);
+        break;
+    case MFI_OSTS:
+        if (megasas_intr_enabled(s) && s->doorbell) {
+            retval = MFI_1078_RM | 1;
+        }
+        break;
+    case MFI_OMSK:
+        retval = s->intr_mask;
+        break;
+    case MFI_ODCR0:
+        retval = s->doorbell;
+        break;
+    default:
+        trace_megasas_mmio_invalid_readl(addr);
+        break;
+    }
+    trace_megasas_mmio_readl(addr, retval);
+    return retval;
+}
+
+static void megasas_mmio_write(void *opaque, target_phys_addr_t addr,
+                               uint64_t val, unsigned size)
+{
+    MegasasState *s = opaque;
+    uint64_t frame_addr;
+    uint32_t frame_count;
+    int i;
+
+    trace_megasas_mmio_writel(addr, val);
+    switch (addr) {
+    case MFI_IDB:
+        if (val & MFI_FWINIT_ABORT) {
+            /* Abort all pending cmds */
+            for (i = 0; i < s->fw_cmds; i++) {
+                megasas_abort_command(&s->frames[i]);
+            }
+        }
+        if (val & MFI_FWINIT_READY) {
+            /* move to FW READY */
+            megasas_soft_reset(s);
+        }
+        if (val & MFI_FWINIT_MFIMODE) {
+            /* discard MFIs */
+        }
+        break;
+    case MFI_OMSK:
+        s->intr_mask = val;
+        if (!megasas_intr_enabled(s) && !msix_enabled(&s->dev)) {
+            trace_megasas_irq_lower();
+            qemu_irq_lower(s->dev.irq[0]);
+        }
+        if (megasas_intr_enabled(s)) {
+            trace_megasas_intr_enabled();
+        } else {
+            trace_megasas_intr_disabled();
+        }
+        break;
+    case MFI_ODCR0:
+        s->doorbell = 0;
+        if (s->producer_pa && megasas_intr_enabled(s)) {
+            /* Update reply queue pointer */
+            trace_megasas_qf_update(s->reply_queue_head, s->busy);
+            stl_le_phys(s->producer_pa, s->reply_queue_head);
+            if (!msix_enabled(&s->dev)) {
+                trace_megasas_irq_lower();
+                qemu_irq_lower(s->dev.irq[0]);
+            }
+        }
+        break;
+    case MFI_IQPH:
+        /* Received high 32 bits of a 64 bit MFI frame address */
+        s->frame_hi = val;
+        break;
+    case MFI_IQPL:
+        /* Received low 32 bits of a 64 bit MFI frame address */
+    case MFI_IQP:
+        /* Received 32 bit MFI frame address */
+        frame_addr = (val & ~0x1F);
+        /* Add possible 64 bit offset */
+        frame_addr |= ((uint64_t)s->frame_hi << 32);
+        s->frame_hi = 0;
+        frame_count = (val >> 1) & 0xF;
+        megasas_handle_frame(s, frame_addr, frame_count);
+        break;
+    default:
+        trace_megasas_mmio_invalid_writel(addr, val);
+        break;
+    }
+}
+
+static const MemoryRegionOps megasas_mmio_ops = {
+    .read = megasas_mmio_read,
+    .write = megasas_mmio_write,
+    .endianness = DEVICE_LITTLE_ENDIAN,
+    .impl = {
+        .min_access_size = 8,
+        .max_access_size = 8,
+    }
+};
+
+static uint64_t megasas_port_read(void *opaque, target_phys_addr_t addr,
+                                  unsigned size)
+{
+    return megasas_mmio_read(opaque, addr & 0xff, size);
+}
+
+static void megasas_port_write(void *opaque, target_phys_addr_t addr,
+                               uint64_t val, unsigned size)
+{
+    megasas_mmio_write(opaque, addr & 0xff, val, size);
+}
+
+static const MemoryRegionOps megasas_port_ops = {
+    .read = megasas_port_read,
+    .write = megasas_port_write,
+    .endianness = DEVICE_LITTLE_ENDIAN,
+    .impl = {
+        .min_access_size = 4,
+        .max_access_size = 4,
+    }
+};
+
+static uint64_t megasas_queue_read(void *opaque, target_phys_addr_t addr,
+                                   unsigned size)
+{
+    return 0;
+}
+
+static const MemoryRegionOps megasas_queue_ops = {
+    .read = megasas_queue_read,
+    .endianness = DEVICE_LITTLE_ENDIAN,
+    .impl = {
+        .min_access_size = 8,
+        .max_access_size = 8,
+    }
+};
+
+static void megasas_soft_reset(MegasasState *s)
+{
+    int i;
+    MegasasCmd *cmd;
+
+    trace_megasas_reset();
+    for (i = 0; i < s->fw_cmds; i++) {
+        cmd = &s->frames[i];
+        megasas_abort_command(cmd);
+    }
+    megasas_reset_frames(s);
+    s->reply_queue_len = s->fw_cmds;
+    s->reply_queue_pa = 0;
+    s->consumer_pa = 0;
+    s->producer_pa = 0;
+    s->fw_state = MFI_FWSTATE_READY;
+    s->doorbell = 0;
+    s->intr_mask = MEGASAS_INTR_DISABLED_MASK;
+    s->frame_hi = 0;
+    s->flags &= ~MEGASAS_MASK_USE_QUEUE64;
+    s->event_count++;
+    s->boot_event = s->event_count;
+}
+
+static void megasas_scsi_reset(DeviceState *dev)
+{
+    MegasasState *s = DO_UPCAST(MegasasState, dev.qdev, dev);
+
+    megasas_soft_reset(s);
+}
+
+static const VMStateDescription vmstate_megasas = {
+    .name = "megasas",
+    .version_id = 0,
+    .minimum_version_id = 0,
+    .minimum_version_id_old = 0,
+    .fields      = (VMStateField[]) {
+        VMSTATE_PCI_DEVICE(dev, MegasasState),
+
+        VMSTATE_INT32(fw_state, MegasasState),
+        VMSTATE_INT32(intr_mask, MegasasState),
+        VMSTATE_INT32(doorbell, MegasasState),
+        VMSTATE_UINT64(reply_queue_pa, MegasasState),
+        VMSTATE_UINT64(consumer_pa, MegasasState),
+        VMSTATE_UINT64(producer_pa, MegasasState),
+        VMSTATE_END_OF_LIST()
+    }
+};
+
+static int megasas_scsi_uninit(PCIDevice *d)
+{
+    MegasasState *s = DO_UPCAST(MegasasState, dev, d);
+
+#ifdef USE_MSIX
+    msix_uninit(&s->dev, &s->mmio_io);
+#endif
+    memory_region_destroy(&s->mmio_io);
+    memory_region_destroy(&s->port_io);
+    memory_region_destroy(&s->queue_io);
+    return 0;
+}
+
+static const struct SCSIBusInfo megasas_scsi_info = {
+    .tcq = true,
+    .max_target = MFI_MAX_LD,
+    .max_lun = 255,
+
+    .transfer_data = megasas_xfer_complete,
+    .get_sg_list = megasas_get_sg_list,
+    .complete = megasas_command_complete,
+    .cancel = megasas_command_cancel,
+};
+
+static int megasas_scsi_init(PCIDevice *dev)
+{
+    MegasasState *s = DO_UPCAST(MegasasState, dev, dev);
+    uint8_t *pci_conf;
+    int i, bar_type;
+
+    pci_conf = s->dev.config;
+
+    /* PCI latency timer = 0 */
+    pci_conf[PCI_LATENCY_TIMER] = 0;
+    /* Interrupt pin 1 */
+    pci_conf[PCI_INTERRUPT_PIN] = 0x01;
+
+    memory_region_init_io(&s->mmio_io, &megasas_mmio_ops, s,
+                          "megasas-mmio", 0x4000);
+    memory_region_init_io(&s->port_io, &megasas_port_ops, s,
+                          "megasas-io", 256);
+    memory_region_init_io(&s->queue_io, &megasas_queue_ops, s,
+                          "megasas-queue", 0x40000);
+
+#ifdef USE_MSIX
+    /* MSI-X support is currently broken */
+    if (megasas_use_msix(s) &&
+        msix_init(&s->dev, 15, &s->mmio_io, 0, 0x2000)) {
+        s->flags &= ~MEGASAS_MASK_USE_MSIX;
+    }
+#else
+    s->flags &= ~MEGASAS_MASK_USE_MSIX;
+#endif
+
+    bar_type = PCI_BASE_ADDRESS_SPACE_MEMORY | PCI_BASE_ADDRESS_MEM_TYPE_64;
+    pci_register_bar(&s->dev, 0, bar_type, &s->mmio_io);
+    pci_register_bar(&s->dev, 2, PCI_BASE_ADDRESS_SPACE_IO, &s->port_io);
+    pci_register_bar(&s->dev, 3, bar_type, &s->queue_io);
+
+    if (megasas_use_msix(s)) {
+        msix_vector_use(&s->dev, 0);
+    }
+
+    if (s->fw_sge >= MEGASAS_MAX_SGE - MFI_PASS_FRAME_SIZE) {
+        s->fw_sge = MEGASAS_MAX_SGE - MFI_PASS_FRAME_SIZE;
+    } else if (s->fw_sge >= 128 - MFI_PASS_FRAME_SIZE) {
+        s->fw_sge = 128 - MFI_PASS_FRAME_SIZE;
+    } else {
+        s->fw_sge = 64 - MFI_PASS_FRAME_SIZE;
+    }
+    if (s->fw_cmds > MEGASAS_MAX_FRAMES) {
+        s->fw_cmds = MEGASAS_MAX_FRAMES;
+    }
+    trace_megasas_init(s->fw_sge, s->fw_cmds,
+                       megasas_use_msix(s) ? "MSI-X" : "INTx",
+                       megasas_is_jbod(s) ? "jbod" : "raid");
+    s->fw_luns = (MFI_MAX_LD > MAX_SCSI_DEVS) ?
+        MAX_SCSI_DEVS : MFI_MAX_LD;
+    s->producer_pa = 0;
+    s->consumer_pa = 0;
+    for (i = 0; i < s->fw_cmds; i++) {
+        s->frames[i].index = i;
+        s->frames[i].context = -1;
+        s->frames[i].pa = 0;
+        s->frames[i].state = s;
+    }
+
+    scsi_bus_new(&s->bus, &dev->qdev, &megasas_scsi_info);
+    scsi_bus_legacy_handle_cmdline(&s->bus);
+    return 0;
+}
+
+static Property megasas_properties[] = {
+    DEFINE_PROP_UINT32("max_sge", MegasasState, fw_sge,
+                       MEGASAS_DEFAULT_SGE),
+    DEFINE_PROP_UINT32("max_cmds", MegasasState, fw_cmds,
+                       MEGASAS_DEFAULT_FRAMES),
+#ifdef USE_MSIX
+    DEFINE_PROP_BIT("use_msix", MegasasState, flags,
+                    MEGASAS_FLAG_USE_MSIX, false),
+#endif
+    DEFINE_PROP_BIT("use_jbod", MegasasState, flags,
+                    MEGASAS_FLAG_USE_JBOD, false),
+    DEFINE_PROP_END_OF_LIST(),
+};
+
+static void megasas_class_init(ObjectClass *oc, void *data)
+{
+    DeviceClass *dc = DEVICE_CLASS(oc);
+    PCIDeviceClass *pc = PCI_DEVICE_CLASS(oc);
+
+    pc->init = megasas_scsi_init;
+    pc->exit = megasas_scsi_uninit;
+    pc->vendor_id = PCI_VENDOR_ID_LSI_LOGIC;
+    pc->device_id = PCI_DEVICE_ID_LSI_SAS1078;
+    pc->subsystem_vendor_id = PCI_VENDOR_ID_LSI_LOGIC;
+    pc->subsystem_id = 0x1013;
+    pc->class_id = PCI_CLASS_STORAGE_RAID;
+    dc->props = megasas_properties;
+    dc->reset = megasas_scsi_reset;
+    dc->vmsd = &vmstate_megasas;
+    dc->desc = "LSI MegaRAID SAS 1078";
+}
+
+static const TypeInfo megasas_info = {
+    .name  = "megasas",
+    .parent = TYPE_PCI_DEVICE,
+    .instance_size = sizeof(MegasasState),
+    .class_init = megasas_class_init,
+};
+
+static void megasas_register_types(void)
+{
+    type_register_static(&megasas_info);
+}
+
+type_init(megasas_register_types)
diff --git a/hw/pci_ids.h b/hw/pci_ids.h
index 649e6b3..b4801d2 100644
--- a/hw/pci_ids.h
+++ b/hw/pci_ids.h
@@ -15,6 +15,7 @@
 
 #define PCI_CLASS_STORAGE_SCSI           0x0100
 #define PCI_CLASS_STORAGE_IDE            0x0101
+#define PCI_CLASS_STORAGE_RAID           0x0104
 #define PCI_CLASS_STORAGE_SATA           0x0106
 #define PCI_CLASS_STORAGE_OTHER          0x0180
 
@@ -47,6 +48,7 @@
 
 #define PCI_VENDOR_ID_LSI_LOGIC          0x1000
 #define PCI_DEVICE_ID_LSI_53C895A        0x0012
+#define PCI_DEVICE_ID_LSI_SAS1078        0x0060
 
 #define PCI_VENDOR_ID_DEC                0x1011
 #define PCI_DEVICE_ID_DEC_21154          0x0026
diff --git a/trace-events b/trace-events
index c935ba2..bd0ca7e 100644
--- a/trace-events
+++ b/trace-events
@@ -512,6 +512,85 @@ lm32_uart_irq_state(int level) "irq state %d"
 # hw/lm32_sys.c
 lm32_sys_memory_write(uint32_t addr, uint32_t value) "addr 0x%08x value 0x%08x"
 
+# hw/megasas.c
+megasas_init_firmware(uint64_t pa) "pa %" PRIx64 " "
+megasas_init_queue(uint64_t queue_pa, int queue_len, uint64_t head, uint64_t tail, uint32_t flags) "queue at %" PRIx64 " len %d head %" PRIx64 " tail %" PRIx64 " flags %x"
+megasas_initq_map_failed(int frame) "scmd %d: failed to map queue"
+megasas_initq_mismatch(int queue_len, int fw_cmds) "queue size %d max fw cmds %d"
+megasas_qf_found(unsigned int index, uint64_t pa) "found mapped frame %x pa %" PRIx64 ""
+megasas_qf_new(unsigned int index, void *cmd) "return new frame %x cmd %p"
+megasas_qf_failed(unsigned long pa) "all frames busy for frame %lx"
+megasas_qf_enqueue(unsigned int index, unsigned int count, uint64_t context, unsigned int tail, int busy) "enqueue frame %x count %d context %" PRIx64 " tail %x busy %d"
+megasas_qf_update(unsigned int head, unsigned int busy) "update reply queue head %x busy %d"
+megasas_qf_dequeue(unsigned int index) "dequeue frame %x"
+megasas_qf_map_failed(int cmd, unsigned long frame) "scmd %d: frame %lu"
+megasas_qf_complete_noirq(uint64_t context) "context %" PRIx64 " "
+megasas_qf_complete(uint64_t context, unsigned int tail, unsigned int offset, int busy, unsigned int doorbell) "context %" PRIx64 " tail %x offset %d busy %d doorbell %x"
+megasas_handle_frame(const char *cmd, uint64_t addr, uint64_t context, uint32_t count) "MFI cmd %s addr %" PRIx64 " context %" PRIx64 " count %d"
+megasas_frame_busy(uint64_t addr) "frame %" PRIx64 " busy"
+megasas_unhandled_frame_cmd(int cmd, uint8_t frame_cmd) "scmd %d: Unhandled MFI cmd %x"
+megasas_handle_scsi(const char *frame, int bus, int dev, int lun, void *sdev, unsigned long size) "%s dev %x/%x/%x sdev %p xfer %lu"
+megasas_scsi_target_not_present(const char *frame, int bus, int dev, int lun) "%s dev %x/%x/%x target not present"
+megasas_scsi_invalid_cdb_len(const char *frame, int bus, int dev, int lun, int len) "%s dev %x/%x/%x invalid cdb len %d"
+megasas_iov_read_overflow(int cmd, int bytes, int len) "scmd %d: %d/%d bytes"
+megasas_iov_write_overflow(int cmd, int bytes, int len) "scmd %d: %d/%d bytes"
+megasas_iov_read_underflow(int cmd, int bytes, int len) "scmd %d: %d/%d bytes"
+megasas_iov_write_underflow(int cmd, int bytes, int len) "scmd %d: %d/%d bytes"
+megasas_scsi_req_alloc_failed(const char *frame, int dev, int lun) "%s dev %x/%x req allocation failed"
+megasas_scsi_read_start(int cmd, int len) "scmd %d: transfer %d bytes of data"
+megasas_scsi_write_start(int cmd, int len) "scmd %d: transfer %d bytes of data"
+megasas_scsi_nodata(int cmd) "scmd %d: no data to be transferred"
+megasas_scsi_complete(int cmd, uint32_t status, int len, int xfer) "scmd %d: finished with status %x, len %u/%u"
+megasas_command_complete(int cmd, uint32_t status, uint32_t resid) "scmd %d: command completed, status %x, residual %d"
+megasas_handle_io(int cmd, const char *frame, int dev, int lun, unsigned long lba, unsigned long count) "scmd %d: %s dev %x/%x lba %lx count %lu"
+megasas_io_target_not_present(int cmd, const char *frame, int dev, int lun) "scmd %d: %s dev 1/%x/%x LUN not present"
+megasas_io_read_start(int cmd, unsigned long lba, unsigned long count, unsigned long len) "scmd %d: start LBA %lx %lu blocks (%lu bytes)"
+megasas_io_write_start(int cmd, unsigned long lba, unsigned long count, unsigned long len) "scmd %d: start LBA %lx %lu blocks (%lu bytes)"
+megasas_io_complete(int cmd, uint32_t len) "scmd %d: %d bytes completed"
+megasas_io_read(int cmd, int bytes, int len, unsigned long offset) "scmd %d: %d/%d bytes, iov offset %lu"
+megasas_io_write(int cmd, int bytes, int len, unsigned long offset) "scmd %d: %d/%d bytes, iov offset %lu"
+megasas_io_continue(int cmd, int bytes) "scmd %d: %d bytes left"
+megasas_iovec_map_failed(int cmd, int index, unsigned long iov_size) "scmd %d: iovec %d size %lu"
+megasas_iovec_sgl_overflow(int cmd, int index, int limit) "scmd %d: iovec count %d limit %d"
+megasas_iovec_sgl_underflow(int cmd, int index) "scmd %d: iovec count %d"
+megasas_iovec_sgl_invalid(int cmd, int index, uint64_t pa, uint32_t len) "scmd %d: element %d pa %" PRIx64 " len %u"
+megasas_iovec_overflow(int cmd, int len, int limit) "scmd %d: len %d limit %d"
+megasas_iovec_underflow(int cmd, int len, int limit) "scmd %d: len %d limit %d"
+megasas_handle_dcmd(int cmd, int opcode) "scmd %d: MFI DCMD opcode %x"
+megasas_finish_dcmd(int cmd, int size) "scmd %d: MFI DCMD wrote %d bytes"
+megasas_dcmd_req_alloc_failed(int cmd, const char *desc) "scmd %d: %s alloc failed"
+megasas_dcmd_internal_submit(int cmd, const char *desc, int dev) "scmd %d: %s to dev %d"
+megasas_dcmd_internal_finish(int cmd, int opcode, int lun) "scmd %d: DCMD finish internal cmd %x lun %d"
+megasas_dcmd_internal_invalid(int cmd, int opcode) "scmd %d: Invalid internal DCMD %x"
+megasas_dcmd_unhandled(int cmd, int opcode, int len) "scmd %d: opcode %x, len %d"
+megasas_dcmd_zero_sge(int cmd) "scmd %d: zero DCMD sge count"
+megasas_dcmd_invalid_sge(int cmd, int count) "scmd %d: invalid DCMD sge count %d"
+megasas_dcmd_map_failed(int cmd) "scmd %d: Failed to map DCMD buffer"
+megasas_dcmd_invalid_xfer_len(int cmd, unsigned long size, unsigned long max) "scmd %d: invalid xfer len %ld, max %ld"
+megasas_dcmd_enter(int cmd, const char *dcmd, int len) "scmd %d: DCMD %s len %d"
+megasas_dcmd_dummy(int cmd, unsigned long size) "scmd %d: DCMD dummy xfer len %ld"
+megasas_dcmd_set_fw_time(int cmd, unsigned long time) "scmd %d: Set FW time %lx"
+megasas_dcmd_pd_get_list(int cmd, int num, int max, int offset) "scmd %d: DCMD PD get list: %d / %d PDs, size %d"
+megasas_dcmd_ld_get_list(int cmd, int num, int max) "scmd %d: DCMD LD get list: found %d / %d LDs"
+megasas_dcmd_ld_get_info(int cmd, int ld_id) "scmd %d: DCMD LD get info for dev %d"
+megasas_dcmd_pd_get_info(int cmd, int pd_id) "scmd %d: DCMD PD get info for dev %d"
+megasas_dcmd_pd_list_query(int cmd, int flags) "scmd %d: DCMD PD list query flags %x"
+megasas_dcmd_dump_frame(int offset, char f0, char f1, char f2, char f3, char f4, char f5, char f6, char f7) "0x%x: %02x %02x %02x %02x %02x %02x %02x %02x"
+megasas_abort_frame(int cmd, int abort_cmd) "scmd %d: aborting frame %x"
+megasas_abort_no_cmd(int cmd, uint64_t context) "scmd %d: no active command for frame context %" PRIx64 ""
+megasas_abort_invalid_context(int cmd, uint64_t context, int abort_cmd) "scmd %d: invalid frame context %" PRIx64 " for abort frame %x"
+megasas_reset(void) "Reset"
+megasas_init(int sges, int cmds, const char *intr, const char *mode) "Using %d sges, %d cmds, %s, %s mode"
+megasas_msix_raise(int vector) "vector %d"
+megasas_irq_lower(void) "INTx"
+megasas_irq_raise(void) "INTx"
+megasas_intr_enabled(void) "Interrupts enabled"
+megasas_intr_disabled(void) "Interrupts disabled"
+megasas_mmio_readl(unsigned long addr, uint32_t val) "addr 0x%lx: 0x%x"
+megasas_mmio_invalid_readl(unsigned long addr) "addr 0x%lx"
+megasas_mmio_writel(uint32_t addr, uint32_t val) "addr 0x%x: 0x%x"
+megasas_mmio_invalid_writel(uint32_t addr, uint32_t val) "addr 0x%x: 0x%x"
+
 # hw/milkymist-ac97.c
 milkymist_ac97_memory_read(uint32_t addr, uint32_t value) "addr %08x value %08x"
 milkymist_ac97_memory_write(uint32_t addr, uint32_t value) "addr %08x value %08x"
commit f595e73713e9b206ac624afd0e48cc927857a3c0
Author: Stefan Weil <sw at weilnetz.de>
Date:   Thu Jun 28 17:56:37 2012 +0200

    configure: Remove help for --disable-vnc-thread, --enable-vnc-thread
    
    Commit 2624bab836662d37f08336408a99d97652fc9c4d removed these
    configure arguments. Now the help text for both is removed, too.
    
    Signed-off-by: Stefan Weil <sw at weilnetz.de>
    Signed-off-by: Stefan Hajnoczi <stefanha at linux.vnet.ibm.com>

diff --git a/configure b/configure
index 9f071b7..500fe24 100755
--- a/configure
+++ b/configure
@@ -1043,8 +1043,6 @@ echo "  --disable-vnc-jpeg       disable JPEG lossy compression for VNC server"
 echo "  --enable-vnc-jpeg        enable JPEG lossy compression for VNC server"
 echo "  --disable-vnc-png        disable PNG compression for VNC server (default)"
 echo "  --enable-vnc-png         enable PNG compression for VNC server"
-echo "  --disable-vnc-thread     disable threaded VNC server"
-echo "  --enable-vnc-thread      enable threaded VNC server"
 echo "  --disable-curses         disable curses output"
 echo "  --enable-curses          enable curses output"
 echo "  --disable-curl           disable curl connectivity"
commit e58998c66d158dea6221e84c2738301ff7a7c434
Author: Peter Maydell <peter.maydell at linaro.org>
Date:   Fri Jun 22 12:30:59 2012 +0100

    cpu-common.h: Remove a pointless ifndef CONFIG_USER_ONLY
    
    Remove an ifndef CONFIG_USER_ONLY guard that was pointless
    because it is already inside an if !defined(CONFIG_USER_ONLY).
    
    Signed-off-by: Peter Maydell <peter.maydell at linaro.org>
    Acked-by: Andreas Färber <afaerber at suse.de>
    Signed-off-by: Stefan Hajnoczi <stefanha at linux.vnet.ibm.com>

diff --git a/cpu-common.h b/cpu-common.h
index 321037f..85548de 100644
--- a/cpu-common.h
+++ b/cpu-common.h
@@ -69,9 +69,7 @@ void cpu_physical_memory_unmap(void *buffer, target_phys_addr_t len,
 void *cpu_register_map_client(void *opaque, void (*callback)(void *opaque));
 void cpu_unregister_map_client(void *cookie);
 
-#ifndef CONFIG_USER_ONLY
 bool cpu_physical_memory_is_io(target_phys_addr_t phys_addr);
-#endif
 
 /* Coalesced MMIO regions are areas where write operations can be reordered.
  * This usually implies that write operations are side-effect free.  This allows
commit 72aaa6cec44568a8a09f9e233387024dd2807823
Author: Peter Maydell <peter.maydell at linaro.org>
Date:   Fri Jun 22 12:30:58 2012 +0100

    cpu-common.h: Remove unnecessary guard on including targphys.h
    
    There's no need to make the include of targphys.h conditional
    on whether TARGET_PHYS_ADDR_BITS is defined, because targphys.h
    itself checks that and does nothing if it isn't.
    
    Signed-off-by: Peter Maydell <peter.maydell at linaro.org>
    Reviewed-by: Andreas Färber <afaerber at suse.de>
    Signed-off-by: Stefan Hajnoczi <stefanha at linux.vnet.ibm.com>

diff --git a/cpu-common.h b/cpu-common.h
index 1fe3280..321037f 100644
--- a/cpu-common.h
+++ b/cpu-common.h
@@ -3,9 +3,7 @@
 
 /* CPU interfaces that are target independent.  */
 
-#ifdef TARGET_PHYS_ADDR_BITS
 #include "targphys.h"
-#endif
 
 #ifndef NEED_CPU_H
 #include "poison.h"
commit 7430d0f5a79e3008d7c9f12d12776eedb317ac06
Author: Hannes Reinecke <hare at suse.de>
Date:   Tue May 29 13:51:16 2012 +0200

    megasas: Add header file
    
    This patch adds the header file for megasas.
    
    Signed-off-by: Hannes Reinecke <hare at suse.de>
    Signed-off-by: Paolo Bonzini <pbonzini at redhat.com>

diff --git a/hw/mfi.h b/hw/mfi.h
new file mode 100644
index 0000000..8a82162
--- /dev/null
+++ b/hw/mfi.h
@@ -0,0 +1,1248 @@
+/*
+ * NetBSD header file, copied from
+ * http://gitorious.org/freebsd/freebsd/blobs/HEAD/sys/dev/mfi/mfireg.h
+ */
+/*-
+ * Copyright (c) 2006 IronPort Systems
+ * Copyright (c) 2007 LSI Corp.
+ * Copyright (c) 2007 Rajesh Prabhakaran.
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ * 1. Redistributions of source code must retain the above copyright
+ *    notice, this list of conditions and the following disclaimer.
+ * 2. Redistributions in binary form must reproduce the above copyright
+ *    notice, this list of conditions and the following disclaimer in the
+ *    documentation and/or other materials provided with the distribution.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED.  IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
+ */
+
+#ifndef MFI_REG_H
+#define MFI_REG_H
+
+/*
+ * MegaRAID SAS MFI firmware definitions
+ */
+
+/*
+ * Start with the register set.  All registers are 32 bits wide.
+ * The usual Intel IOP style setup.
+ */
+#define MFI_IMSG0 0x10    /* Inbound message 0 */
+#define MFI_IMSG1 0x14    /* Inbound message 1 */
+#define MFI_OMSG0 0x18    /* Outbound message 0 */
+#define MFI_OMSG1 0x1c    /* Outbound message 1 */
+#define MFI_IDB   0x20    /* Inbound doorbell */
+#define MFI_ISTS  0x24    /* Inbound interrupt status */
+#define MFI_IMSK  0x28    /* Inbound interrupt mask */
+#define MFI_ODB   0x2c    /* Outbound doorbell */
+#define MFI_OSTS  0x30    /* Outbound interrupt status */
+#define MFI_OMSK  0x34    /* Outbound interrupt mask */
+#define MFI_IQP   0x40    /* Inbound queue port */
+#define MFI_OQP   0x44    /* Outbound queue port */
+
+/*
+ * 1078 specific related register
+ */
+#define MFI_ODR0        0x9c            /* outbound doorbell register0 */
+#define MFI_ODCR0       0xa0            /* outbound doorbell clear register0  */
+#define MFI_OSP0        0xb0            /* outbound scratch pad0  */
+#define MFI_IQPL        0xc0            /* Inbound queue port (low bytes)  */
+#define MFI_IQPH        0xc4            /* Inbound queue port (high bytes)  */
+#define MFI_DIAG        0xf8            /* Host diag */
+#define MFI_SEQ         0xfc            /* Sequencer offset */
+#define MFI_1078_EIM    0x80000004      /* 1078 enable intrrupt mask  */
+#define MFI_RMI         0x2             /* reply message interrupt  */
+#define MFI_1078_RM     0x80000000      /* reply 1078 message interrupt  */
+#define MFI_ODC         0x4             /* outbound doorbell change interrupt */
+
+/*
+ * gen2 specific changes
+ */
+#define MFI_GEN2_EIM    0x00000005      /* gen2 enable interrupt mask */
+#define MFI_GEN2_RM     0x00000001      /* reply gen2 message interrupt */
+
+/*
+ * skinny specific changes
+ */
+#define MFI_SKINNY_IDB  0x00    /* Inbound doorbell is at 0x00 for skinny */
+#define MFI_SKINNY_RM   0x00000001      /* reply skinny message interrupt */
+
+/* Bits for MFI_OSTS */
+#define MFI_OSTS_INTR_VALID     0x00000002
+
+/*
+ * Firmware state values.  Found in OMSG0 during initialization.
+ */
+#define MFI_FWSTATE_MASK                0xf0000000
+#define MFI_FWSTATE_UNDEFINED           0x00000000
+#define MFI_FWSTATE_BB_INIT             0x10000000
+#define MFI_FWSTATE_FW_INIT             0x40000000
+#define MFI_FWSTATE_WAIT_HANDSHAKE      0x60000000
+#define MFI_FWSTATE_FW_INIT_2           0x70000000
+#define MFI_FWSTATE_DEVICE_SCAN         0x80000000
+#define MFI_FWSTATE_BOOT_MSG_PENDING    0x90000000
+#define MFI_FWSTATE_FLUSH_CACHE         0xa0000000
+#define MFI_FWSTATE_READY               0xb0000000
+#define MFI_FWSTATE_OPERATIONAL         0xc0000000
+#define MFI_FWSTATE_FAULT               0xf0000000
+#define MFI_FWSTATE_MAXSGL_MASK         0x00ff0000
+#define MFI_FWSTATE_MAXCMD_MASK         0x0000ffff
+#define MFI_FWSTATE_MSIX_SUPPORTED      0x04000000
+#define MFI_FWSTATE_HOSTMEMREQD_MASK    0x08000000
+
+/*
+ * Control bits to drive the card to ready state.  These go into the IDB
+ * register.
+ */
+#define MFI_FWINIT_ABORT        0x00000001 /* Abort all pending commands */
+#define MFI_FWINIT_READY        0x00000002 /* Move from operational to ready */
+#define MFI_FWINIT_MFIMODE      0x00000004 /* unknown */
+#define MFI_FWINIT_CLEAR_HANDSHAKE 0x00000008 /* Respond to WAIT_HANDSHAKE */
+#define MFI_FWINIT_HOTPLUG      0x00000010
+#define MFI_FWINIT_STOP_ADP     0x00000020 /* Move to operational, stop */
+#define MFI_FWINIT_ADP_RESET    0x00000040 /* Reset ADP */
+
+/* MFI Commands */
+typedef enum {
+    MFI_CMD_INIT = 0x00,
+    MFI_CMD_LD_READ,
+    MFI_CMD_LD_WRITE,
+    MFI_CMD_LD_SCSI_IO,
+    MFI_CMD_PD_SCSI_IO,
+    MFI_CMD_DCMD,
+    MFI_CMD_ABORT,
+    MFI_CMD_SMP,
+    MFI_CMD_STP
+} mfi_cmd_t;
+
+/* Direct commands */
+typedef enum {
+    MFI_DCMD_CTRL_MFI_HOST_MEM_ALLOC =  0x0100e100,
+    MFI_DCMD_CTRL_GET_INFO =            0x01010000,
+    MFI_DCMD_CTRL_GET_PROPERTIES =      0x01020100,
+    MFI_DCMD_CTRL_SET_PROPERTIES =      0x01020200,
+    MFI_DCMD_CTRL_ALARM =               0x01030000,
+    MFI_DCMD_CTRL_ALARM_GET =           0x01030100,
+    MFI_DCMD_CTRL_ALARM_ENABLE =        0x01030200,
+    MFI_DCMD_CTRL_ALARM_DISABLE =       0x01030300,
+    MFI_DCMD_CTRL_ALARM_SILENCE =       0x01030400,
+    MFI_DCMD_CTRL_ALARM_TEST =          0x01030500,
+    MFI_DCMD_CTRL_EVENT_GETINFO =       0x01040100,
+    MFI_DCMD_CTRL_EVENT_CLEAR =         0x01040200,
+    MFI_DCMD_CTRL_EVENT_GET =           0x01040300,
+    MFI_DCMD_CTRL_EVENT_COUNT =         0x01040400,
+    MFI_DCMD_CTRL_EVENT_WAIT =          0x01040500,
+    MFI_DCMD_CTRL_SHUTDOWN =            0x01050000,
+    MFI_DCMD_HIBERNATE_STANDBY =        0x01060000,
+    MFI_DCMD_CTRL_GET_TIME =            0x01080101,
+    MFI_DCMD_CTRL_SET_TIME =            0x01080102,
+    MFI_DCMD_CTRL_BIOS_DATA_GET =       0x010c0100,
+    MFI_DCMD_CTRL_BIOS_DATA_SET =       0x010c0200,
+    MFI_DCMD_CTRL_FACTORY_DEFAULTS =    0x010d0000,
+    MFI_DCMD_CTRL_MFC_DEFAULTS_GET =    0x010e0201,
+    MFI_DCMD_CTRL_MFC_DEFAULTS_SET =    0x010e0202,
+    MFI_DCMD_CTRL_CACHE_FLUSH =         0x01101000,
+    MFI_DCMD_PD_GET_LIST =              0x02010000,
+    MFI_DCMD_PD_LIST_QUERY =            0x02010100,
+    MFI_DCMD_PD_GET_INFO =              0x02020000,
+    MFI_DCMD_PD_STATE_SET =             0x02030100,
+    MFI_DCMD_PD_REBUILD =               0x02040100,
+    MFI_DCMD_PD_BLINK =                 0x02070100,
+    MFI_DCMD_PD_UNBLINK =               0x02070200,
+    MFI_DCMD_LD_GET_LIST =              0x03010000,
+    MFI_DCMD_LD_GET_INFO =              0x03020000,
+    MFI_DCMD_LD_GET_PROP =              0x03030000,
+    MFI_DCMD_LD_SET_PROP =              0x03040000,
+    MFI_DCMD_LD_DELETE =                0x03090000,
+    MFI_DCMD_CFG_READ =                 0x04010000,
+    MFI_DCMD_CFG_ADD =                  0x04020000,
+    MFI_DCMD_CFG_CLEAR =                0x04030000,
+    MFI_DCMD_CFG_FOREIGN_READ =         0x04060100,
+    MFI_DCMD_CFG_FOREIGN_IMPORT =       0x04060400,
+    MFI_DCMD_BBU_STATUS =               0x05010000,
+    MFI_DCMD_BBU_CAPACITY_INFO =        0x05020000,
+    MFI_DCMD_BBU_DESIGN_INFO =          0x05030000,
+    MFI_DCMD_BBU_PROP_GET =             0x05050100,
+    MFI_DCMD_CLUSTER =                  0x08000000,
+    MFI_DCMD_CLUSTER_RESET_ALL =        0x08010100,
+    MFI_DCMD_CLUSTER_RESET_LD =         0x08010200
+} mfi_dcmd_t;
+
+/* Modifiers for MFI_DCMD_CTRL_FLUSHCACHE */
+#define MFI_FLUSHCACHE_CTRL     0x01
+#define MFI_FLUSHCACHE_DISK     0x02
+
+/* Modifiers for MFI_DCMD_CTRL_SHUTDOWN */
+#define MFI_SHUTDOWN_SPINDOWN   0x01
+
+/*
+ * MFI Frame flags
+ */
+typedef enum {
+    MFI_FRAME_DONT_POST_IN_REPLY_QUEUE =        0x0001,
+    MFI_FRAME_SGL64 =                           0x0002,
+    MFI_FRAME_SENSE64 =                         0x0004,
+    MFI_FRAME_DIR_WRITE =                       0x0008,
+    MFI_FRAME_DIR_READ =                        0x0010,
+    MFI_FRAME_IEEE_SGL =                        0x0020,
+} mfi_frame_flags;
+
+/* MFI Status codes */
+typedef enum {
+    MFI_STAT_OK =                       0x00,
+    MFI_STAT_INVALID_CMD,
+    MFI_STAT_INVALID_DCMD,
+    MFI_STAT_INVALID_PARAMETER,
+    MFI_STAT_INVALID_SEQUENCE_NUMBER,
+    MFI_STAT_ABORT_NOT_POSSIBLE,
+    MFI_STAT_APP_HOST_CODE_NOT_FOUND,
+    MFI_STAT_APP_IN_USE,
+    MFI_STAT_APP_NOT_INITIALIZED,
+    MFI_STAT_ARRAY_INDEX_INVALID,
+    MFI_STAT_ARRAY_ROW_NOT_EMPTY,
+    MFI_STAT_CONFIG_RESOURCE_CONFLICT,
+    MFI_STAT_DEVICE_NOT_FOUND,
+    MFI_STAT_DRIVE_TOO_SMALL,
+    MFI_STAT_FLASH_ALLOC_FAIL,
+    MFI_STAT_FLASH_BUSY,
+    MFI_STAT_FLASH_ERROR =              0x10,
+    MFI_STAT_FLASH_IMAGE_BAD,
+    MFI_STAT_FLASH_IMAGE_INCOMPLETE,
+    MFI_STAT_FLASH_NOT_OPEN,
+    MFI_STAT_FLASH_NOT_STARTED,
+    MFI_STAT_FLUSH_FAILED,
+    MFI_STAT_HOST_CODE_NOT_FOUNT,
+    MFI_STAT_LD_CC_IN_PROGRESS,
+    MFI_STAT_LD_INIT_IN_PROGRESS,
+    MFI_STAT_LD_LBA_OUT_OF_RANGE,
+    MFI_STAT_LD_MAX_CONFIGURED,
+    MFI_STAT_LD_NOT_OPTIMAL,
+    MFI_STAT_LD_RBLD_IN_PROGRESS,
+    MFI_STAT_LD_RECON_IN_PROGRESS,
+    MFI_STAT_LD_WRONG_RAID_LEVEL,
+    MFI_STAT_MAX_SPARES_EXCEEDED,
+    MFI_STAT_MEMORY_NOT_AVAILABLE =     0x20,
+    MFI_STAT_MFC_HW_ERROR,
+    MFI_STAT_NO_HW_PRESENT,
+    MFI_STAT_NOT_FOUND,
+    MFI_STAT_NOT_IN_ENCL,
+    MFI_STAT_PD_CLEAR_IN_PROGRESS,
+    MFI_STAT_PD_TYPE_WRONG,
+    MFI_STAT_PR_DISABLED,
+    MFI_STAT_ROW_INDEX_INVALID,
+    MFI_STAT_SAS_CONFIG_INVALID_ACTION,
+    MFI_STAT_SAS_CONFIG_INVALID_DATA,
+    MFI_STAT_SAS_CONFIG_INVALID_PAGE,
+    MFI_STAT_SAS_CONFIG_INVALID_TYPE,
+    MFI_STAT_SCSI_DONE_WITH_ERROR,
+    MFI_STAT_SCSI_IO_FAILED,
+    MFI_STAT_SCSI_RESERVATION_CONFLICT,
+    MFI_STAT_SHUTDOWN_FAILED =          0x30,
+    MFI_STAT_TIME_NOT_SET,
+    MFI_STAT_WRONG_STATE,
+    MFI_STAT_LD_OFFLINE,
+    MFI_STAT_PEER_NOTIFICATION_REJECTED,
+    MFI_STAT_PEER_NOTIFICATION_FAILED,
+    MFI_STAT_RESERVATION_IN_PROGRESS,
+    MFI_STAT_I2C_ERRORS_DETECTED,
+    MFI_STAT_PCI_ERRORS_DETECTED,
+    MFI_STAT_DIAG_FAILED,
+    MFI_STAT_BOOT_MSG_PENDING,
+    MFI_STAT_FOREIGN_CONFIG_INCOMPLETE,
+    MFI_STAT_INVALID_SGL,
+    MFI_STAT_UNSUPPORTED_HW,
+    MFI_STAT_CC_SCHEDULE_DISABLED,
+    MFI_STAT_PD_COPYBACK_IN_PROGRESS,
+    MFI_STAT_MULTIPLE_PDS_IN_ARRAY =    0x40,
+    MFI_STAT_FW_DOWNLOAD_ERROR,
+    MFI_STAT_FEATURE_SECURITY_NOT_ENABLED,
+    MFI_STAT_LOCK_KEY_ALREADY_EXISTS,
+    MFI_STAT_LOCK_KEY_BACKUP_NOT_ALLOWED,
+    MFI_STAT_LOCK_KEY_VERIFY_NOT_ALLOWED,
+    MFI_STAT_LOCK_KEY_VERIFY_FAILED,
+    MFI_STAT_LOCK_KEY_REKEY_NOT_ALLOWED,
+    MFI_STAT_LOCK_KEY_INVALID,
+    MFI_STAT_LOCK_KEY_ESCROW_INVALID,
+    MFI_STAT_LOCK_KEY_BACKUP_REQUIRED,
+    MFI_STAT_SECURE_LD_EXISTS,
+    MFI_STAT_LD_SECURE_NOT_ALLOWED,
+    MFI_STAT_REPROVISION_NOT_ALLOWED,
+    MFI_STAT_PD_SECURITY_TYPE_WRONG,
+    MFI_STAT_LD_ENCRYPTION_TYPE_INVALID,
+    MFI_STAT_CONFIG_FDE_NON_FDE_MIX_NOT_ALLOWED = 0x50,
+    MFI_STAT_CONFIG_LD_ENCRYPTION_TYPE_MIX_NOT_ALLOWED,
+    MFI_STAT_SECRET_KEY_NOT_ALLOWED,
+    MFI_STAT_PD_HW_ERRORS_DETECTED,
+    MFI_STAT_LD_CACHE_PINNED,
+    MFI_STAT_POWER_STATE_SET_IN_PROGRESS,
+    MFI_STAT_POWER_STATE_SET_BUSY,
+    MFI_STAT_POWER_STATE_WRONG,
+    MFI_STAT_PR_NO_AVAILABLE_PD_FOUND,
+    MFI_STAT_CTRL_RESET_REQUIRED,
+    MFI_STAT_LOCK_KEY_EKM_NO_BOOT_AGENT,
+    MFI_STAT_SNAP_NO_SPACE,
+    MFI_STAT_SNAP_PARTIAL_FAILURE,
+    MFI_STAT_UPGRADE_KEY_INCOMPATIBLE,
+    MFI_STAT_PFK_INCOMPATIBLE,
+    MFI_STAT_PD_MAX_UNCONFIGURED,
+    MFI_STAT_IO_METRICS_DISABLED =      0x60,
+    MFI_STAT_AEC_NOT_STOPPED,
+    MFI_STAT_PI_TYPE_WRONG,
+    MFI_STAT_LD_PD_PI_INCOMPATIBLE,
+    MFI_STAT_PI_NOT_ENABLED,
+    MFI_STAT_LD_BLOCK_SIZE_MISMATCH,
+    MFI_STAT_INVALID_STATUS =           0xFF
+} mfi_status_t;
+
+/* Event classes */
+typedef enum {
+    MFI_EVT_CLASS_DEBUG =      -2,
+    MFI_EVT_CLASS_PROGRESS =   -1,
+    MFI_EVT_CLASS_INFO =        0,
+    MFI_EVT_CLASS_WARNING =     1,
+    MFI_EVT_CLASS_CRITICAL =    2,
+    MFI_EVT_CLASS_FATAL =       3,
+    MFI_EVT_CLASS_DEAD =        4
+} mfi_evt_class_t;
+
+/* Event locales */
+typedef enum {
+    MFI_EVT_LOCALE_LD =         0x0001,
+    MFI_EVT_LOCALE_PD =         0x0002,
+    MFI_EVT_LOCALE_ENCL =       0x0004,
+    MFI_EVT_LOCALE_BBU =        0x0008,
+    MFI_EVT_LOCALE_SAS =        0x0010,
+    MFI_EVT_LOCALE_CTRL =       0x0020,
+    MFI_EVT_LOCALE_CONFIG =     0x0040,
+    MFI_EVT_LOCALE_CLUSTER =    0x0080,
+    MFI_EVT_LOCALE_ALL =        0xffff
+} mfi_evt_locale_t;
+
+/* Event args */
+typedef enum {
+    MR_EVT_ARGS_NONE =          0x00,
+    MR_EVT_ARGS_CDB_SENSE,
+    MR_EVT_ARGS_LD,
+    MR_EVT_ARGS_LD_COUNT,
+    MR_EVT_ARGS_LD_LBA,
+    MR_EVT_ARGS_LD_OWNER,
+    MR_EVT_ARGS_LD_LBA_PD_LBA,
+    MR_EVT_ARGS_LD_PROG,
+    MR_EVT_ARGS_LD_STATE,
+    MR_EVT_ARGS_LD_STRIP,
+    MR_EVT_ARGS_PD,
+    MR_EVT_ARGS_PD_ERR,
+    MR_EVT_ARGS_PD_LBA,
+    MR_EVT_ARGS_PD_LBA_LD,
+    MR_EVT_ARGS_PD_PROG,
+    MR_EVT_ARGS_PD_STATE,
+    MR_EVT_ARGS_PCI,
+    MR_EVT_ARGS_RATE,
+    MR_EVT_ARGS_STR,
+    MR_EVT_ARGS_TIME,
+    MR_EVT_ARGS_ECC,
+    MR_EVT_ARGS_LD_PROP,
+    MR_EVT_ARGS_PD_SPARE,
+    MR_EVT_ARGS_PD_INDEX,
+    MR_EVT_ARGS_DIAG_PASS,
+    MR_EVT_ARGS_DIAG_FAIL,
+    MR_EVT_ARGS_PD_LBA_LBA,
+    MR_EVT_ARGS_PORT_PHY,
+    MR_EVT_ARGS_PD_MISSING,
+    MR_EVT_ARGS_PD_ADDRESS,
+    MR_EVT_ARGS_BITMAP,
+    MR_EVT_ARGS_CONNECTOR,
+    MR_EVT_ARGS_PD_PD,
+    MR_EVT_ARGS_PD_FRU,
+    MR_EVT_ARGS_PD_PATHINFO,
+    MR_EVT_ARGS_PD_POWER_STATE,
+    MR_EVT_ARGS_GENERIC,
+} mfi_evt_args;
+
+/* Event codes */
+#define MR_EVT_CFG_CLEARED                          0x0004
+#define MR_EVT_CTRL_SHUTDOWN                        0x002a
+#define MR_EVT_LD_STATE_CHANGE                      0x0051
+#define MR_EVT_PD_INSERTED                          0x005b
+#define MR_EVT_PD_REMOVED                           0x0070
+#define MR_EVT_PD_STATE_CHANGED                     0x0072
+#define MR_EVT_LD_CREATED                           0x008a
+#define MR_EVT_LD_DELETED                           0x008b
+#define MR_EVT_FOREIGN_CFG_IMPORTED                 0x00db
+#define MR_EVT_LD_OFFLINE                           0x00fc
+#define MR_EVT_CTRL_HOST_BUS_SCAN_REQUESTED         0x0152
+
+typedef enum {
+    MR_LD_CACHE_WRITE_BACK =            0x01,
+    MR_LD_CACHE_WRITE_ADAPTIVE =        0x02,
+    MR_LD_CACHE_READ_AHEAD =            0x04,
+    MR_LD_CACHE_READ_ADAPTIVE =         0x08,
+    MR_LD_CACHE_WRITE_CACHE_BAD_BBU =   0x10,
+    MR_LD_CACHE_ALLOW_WRITE_CACHE =     0x20,
+    MR_LD_CACHE_ALLOW_READ_CACHE =      0x40
+} mfi_ld_cache;
+
+typedef enum {
+    MR_PD_CACHE_UNCHANGED  =    0,
+    MR_PD_CACHE_ENABLE =        1,
+    MR_PD_CACHE_DISABLE =       2
+} mfi_pd_cache;
+
+typedef enum {
+    MR_PD_QUERY_TYPE_ALL =              0,
+    MR_PD_QUERY_TYPE_STATE =            1,
+    MR_PD_QUERY_TYPE_POWER_STATE =      2,
+    MR_PD_QUERY_TYPE_MEDIA_TYPE =       3,
+    MR_PD_QUERY_TYPE_SPEED =            4,
+    MR_PD_QUERY_TYPE_EXPOSED_TO_HOST =  5, /*query for system drives */
+} mfi_pd_query_type;
+
+/*
+ * Other propertities and definitions
+ */
+#define MFI_MAX_PD_CHANNELS     2
+#define MFI_MAX_LD_CHANNELS     2
+#define MFI_MAX_CHANNELS        (MFI_MAX_PD_CHANNELS + MFI_MAX_LD_CHANNELS)
+#define MFI_MAX_CHANNEL_DEVS  128
+#define MFI_DEFAULT_ID         -1
+#define MFI_MAX_LUN             8
+#define MFI_MAX_LD             64
+
+#define MFI_FRAME_SIZE         64
+#define MFI_MBOX_SIZE          12
+
+/* Firmware flashing can take 40s */
+#define MFI_POLL_TIMEOUT_SECS  50
+
+/* Allow for speedier math calculations */
+#define MFI_SECTOR_LEN        512
+
+/* Scatter Gather elements */
+struct mfi_sg32 {
+    uint32_t addr;
+    uint32_t len;
+} __attribute__ ((packed));
+
+struct mfi_sg64 {
+    uint64_t addr;
+    uint32_t len;
+} __attribute__ ((packed));
+
+struct mfi_sg_skinny {
+    uint64_t addr;
+    uint32_t len;
+    uint32_t flag;
+} __attribute__ ((packed));
+
+union mfi_sgl {
+    struct mfi_sg32 sg32[1];
+    struct mfi_sg64 sg64[1];
+    struct mfi_sg_skinny sg_skinny[1];
+} __attribute__ ((packed));
+
+/* Message frames.  All messages have a common header */
+struct mfi_frame_header {
+    uint8_t frame_cmd;
+    uint8_t sense_len;
+    uint8_t cmd_status;
+    uint8_t scsi_status;
+    uint8_t target_id;
+    uint8_t lun_id;
+    uint8_t cdb_len;
+    uint8_t sge_count;
+    uint64_t context;
+    uint16_t flags;
+    uint16_t timeout;
+    uint32_t data_len;
+} __attribute__ ((packed));
+
+struct mfi_init_frame {
+    struct mfi_frame_header header;
+    uint32_t qinfo_new_addr_lo;
+    uint32_t qinfo_new_addr_hi;
+    uint32_t qinfo_old_addr_lo;
+    uint32_t qinfo_old_addr_hi;
+    uint32_t reserved[6];
+};
+
+#define MFI_IO_FRAME_SIZE 40
+struct mfi_io_frame {
+    struct mfi_frame_header header;
+    uint32_t sense_addr_lo;
+    uint32_t sense_addr_hi;
+    uint32_t lba_lo;
+    uint32_t lba_hi;
+    union mfi_sgl sgl;
+} __attribute__ ((packed));
+
+#define MFI_PASS_FRAME_SIZE 48
+struct mfi_pass_frame {
+    struct mfi_frame_header header;
+    uint32_t sense_addr_lo;
+    uint32_t sense_addr_hi;
+    uint8_t cdb[16];
+    union mfi_sgl sgl;
+} __attribute__ ((packed));
+
+#define MFI_DCMD_FRAME_SIZE 40
+struct mfi_dcmd_frame {
+    struct mfi_frame_header header;
+    uint32_t opcode;
+    uint8_t mbox[MFI_MBOX_SIZE];
+    union mfi_sgl sgl;
+} __attribute__ ((packed));
+
+struct mfi_abort_frame {
+    struct mfi_frame_header header;
+    uint64_t abort_context;
+    uint32_t abort_mfi_addr_lo;
+    uint32_t abort_mfi_addr_hi;
+    uint32_t reserved1[6];
+} __attribute__ ((packed));
+
+struct mfi_smp_frame {
+    struct mfi_frame_header header;
+    uint64_t sas_addr;
+    union {
+        struct mfi_sg32 sg32[2];
+        struct mfi_sg64 sg64[2];
+    } sgl;
+} __attribute__ ((packed));
+
+struct mfi_stp_frame {
+    struct mfi_frame_header header;
+    uint16_t fis[10];
+    uint32_t stp_flags;
+    union {
+        struct mfi_sg32 sg32[2];
+        struct mfi_sg64 sg64[2];
+    } sgl;
+} __attribute__ ((packed));
+
+union mfi_frame {
+    struct mfi_frame_header header;
+    struct mfi_init_frame init;
+    struct mfi_io_frame io;
+    struct mfi_pass_frame pass;
+    struct mfi_dcmd_frame dcmd;
+    struct mfi_abort_frame abort;
+    struct mfi_smp_frame smp;
+    struct mfi_stp_frame stp;
+    uint64_t raw[8];
+    uint8_t bytes[MFI_FRAME_SIZE];
+};
+
+#define MFI_SENSE_LEN 128
+struct mfi_sense {
+    uint8_t     data[MFI_SENSE_LEN];
+};
+
+#define MFI_QUEUE_FLAG_CONTEXT64 0x00000002
+
+/* The queue init structure that is passed with the init message */
+struct mfi_init_qinfo {
+    uint32_t flags;
+    uint32_t rq_entries;
+    uint32_t rq_addr_lo;
+    uint32_t rq_addr_hi;
+    uint32_t pi_addr_lo;
+    uint32_t pi_addr_hi;
+    uint32_t ci_addr_lo;
+    uint32_t ci_addr_hi;
+} __attribute__ ((packed));
+
+/* Controller properties */
+struct mfi_ctrl_props {
+    uint16_t seq_num;
+    uint16_t pred_fail_poll_interval;
+    uint16_t intr_throttle_cnt;
+    uint16_t intr_throttle_timeout;
+    uint8_t rebuild_rate;
+    uint8_t patrol_read_rate;
+    uint8_t bgi_rate;
+    uint8_t cc_rate;
+    uint8_t recon_rate;
+    uint8_t cache_flush_interval;
+    uint8_t spinup_drv_cnt;
+    uint8_t spinup_delay;
+    uint8_t cluster_enable;
+    uint8_t coercion_mode;
+    uint8_t alarm_enable;
+    uint8_t disable_auto_rebuild;
+    uint8_t disable_battery_warn;
+    uint8_t ecc_bucket_size;
+    uint16_t ecc_bucket_leak_rate;
+    uint8_t restore_hotspare_on_insertion;
+    uint8_t expose_encl_devices;
+    uint8_t maintainPdFailHistory;
+    uint8_t disallowHostRequestReordering;
+    uint8_t abortCCOnError;
+    uint8_t loadBalanceMode;
+    uint8_t disableAutoDetectBackplane;
+    uint8_t snapVDSpace;
+    uint32_t OnOffProperties;
+/* set TRUE to disable copyBack (0=copyback enabled) */
+#define MFI_CTRL_PROP_CopyBackDisabled           (1 << 0)
+#define MFI_CTRL_PROP_SMARTerEnabled             (1 << 1)
+#define MFI_CTRL_PROP_PRCorrectUnconfiguredAreas (1 << 2)
+#define MFI_CTRL_PROP_UseFdeOnly                 (1 << 3)
+#define MFI_CTRL_PROP_DisableNCQ                 (1 << 4)
+#define MFI_CTRL_PROP_SSDSMARTerEnabled          (1 << 5)
+#define MFI_CTRL_PROP_SSDPatrolReadEnabled       (1 << 6)
+#define MFI_CTRL_PROP_EnableSpinDownUnconfigured (1 << 7)
+#define MFI_CTRL_PROP_AutoEnhancedImport         (1 << 8)
+#define MFI_CTRL_PROP_EnableSecretKeyControl     (1 << 9)
+#define MFI_CTRL_PROP_DisableOnlineCtrlReset     (1 << 10)
+#define MFI_CTRL_PROP_AllowBootWithPinnedCache   (1 << 11)
+#define MFI_CTRL_PROP_DisableSpinDownHS          (1 << 12)
+#define MFI_CTRL_PROP_EnableJBOD                 (1 << 13)
+
+    uint8_t autoSnapVDSpace; /* % of source LD to be
+                              * reserved for auto snapshot
+                              * in snapshot repository, for
+                              * metadata and user data
+                              * 1=5%, 2=10%, 3=15% and so on
+                              */
+    uint8_t viewSpace;       /* snapshot writeable VIEWs
+                              * capacity as a % of source LD
+                              * capacity. 0=READ only
+                              * 1=5%, 2=10%, 3=15% and so on
+                              */
+    uint16_t spinDownTime;    /* # of idle minutes before device
+                               * is spun down (0=use FW defaults)
+                               */
+    uint8_t reserved[24];
+} __attribute__ ((packed));
+
+/* PCI information about the card. */
+struct mfi_info_pci {
+    uint16_t vendor;
+    uint16_t device;
+    uint16_t subvendor;
+    uint16_t subdevice;
+    uint8_t reserved[24];
+} __attribute__ ((packed));
+
+/* Host (front end) interface information */
+struct mfi_info_host {
+    uint8_t type;
+#define MFI_INFO_HOST_PCIX      0x01
+#define MFI_INFO_HOST_PCIE      0x02
+#define MFI_INFO_HOST_ISCSI     0x04
+#define MFI_INFO_HOST_SAS3G     0x08
+    uint8_t reserved[6];
+    uint8_t port_count;
+    uint64_t port_addr[8];
+} __attribute__ ((packed));
+
+/* Device (back end) interface information */
+struct mfi_info_device {
+    uint8_t type;
+#define MFI_INFO_DEV_SPI        0x01
+#define MFI_INFO_DEV_SAS3G      0x02
+#define MFI_INFO_DEV_SATA1      0x04
+#define MFI_INFO_DEV_SATA3G     0x08
+    uint8_t reserved[6];
+    uint8_t port_count;
+    uint64_t port_addr[8];
+} __attribute__ ((packed));
+
+/* Firmware component information */
+struct mfi_info_component {
+    char name[8];
+    char version[32];
+    char build_date[16];
+    char build_time[16];
+} __attribute__ ((packed));
+
+/* Controller default settings */
+struct mfi_defaults {
+    uint64_t sas_addr;
+    uint8_t phy_polarity;
+    uint8_t background_rate;
+    uint8_t stripe_size;
+    uint8_t flush_time;
+    uint8_t write_back;
+    uint8_t read_ahead;
+    uint8_t cache_when_bbu_bad;
+    uint8_t cached_io;
+    uint8_t smart_mode;
+    uint8_t alarm_disable;
+    uint8_t coercion;
+    uint8_t zrc_config;
+    uint8_t dirty_led_shows_drive_activity;
+    uint8_t bios_continue_on_error;
+    uint8_t spindown_mode;
+    uint8_t allowed_device_types;
+    uint8_t allow_mix_in_enclosure;
+    uint8_t allow_mix_in_ld;
+    uint8_t allow_sata_in_cluster;
+    uint8_t max_chained_enclosures;
+    uint8_t disable_ctrl_r;
+    uint8_t enable_web_bios;
+    uint8_t phy_polarity_split;
+    uint8_t direct_pd_mapping;
+    uint8_t bios_enumerate_lds;
+    uint8_t restored_hot_spare_on_insertion;
+    uint8_t expose_enclosure_devices;
+    uint8_t maintain_pd_fail_history;
+    uint8_t disable_puncture;
+    uint8_t zero_based_enumeration;
+    uint8_t disable_preboot_cli;
+    uint8_t show_drive_led_on_activity;
+    uint8_t cluster_disable;
+    uint8_t sas_disable;
+    uint8_t auto_detect_backplane;
+    uint8_t fde_only;
+    uint8_t delay_during_post;
+    uint8_t resv[19];
+} __attribute__ ((packed));
+
+/* Controller default settings */
+struct mfi_bios_data {
+    uint16_t boot_target_id;
+    uint8_t do_not_int_13;
+    uint8_t continue_on_error;
+    uint8_t verbose;
+    uint8_t geometry;
+    uint8_t expose_all_drives;
+    uint8_t reserved[56];
+    uint8_t check_sum;
+} __attribute__ ((packed));
+
+/* SAS (?) controller info, returned from MFI_DCMD_CTRL_GETINFO. */
+struct mfi_ctrl_info {
+    struct mfi_info_pci pci;
+    struct mfi_info_host host;
+    struct mfi_info_device device;
+
+    /* Firmware components that are present and active. */
+    uint32_t image_check_word;
+    uint32_t image_component_count;
+    struct mfi_info_component image_component[8];
+
+    /* Firmware components that have been flashed but are inactive */
+    uint32_t pending_image_component_count;
+    struct mfi_info_component pending_image_component[8];
+
+    uint8_t max_arms;
+    uint8_t max_spans;
+    uint8_t max_arrays;
+    uint8_t max_lds;
+    char product_name[80];
+    char serial_number[32];
+    uint32_t hw_present;
+#define MFI_INFO_HW_BBU         0x01
+#define MFI_INFO_HW_ALARM       0x02
+#define MFI_INFO_HW_NVRAM       0x04
+#define MFI_INFO_HW_UART        0x08
+#define MFI_INFO_HW_MEM         0x10
+#define MFI_INFO_HW_FLASH       0x20
+    uint32_t current_fw_time;
+    uint16_t max_cmds;
+    uint16_t max_sg_elements;
+    uint32_t max_request_size;
+    uint16_t lds_present;
+    uint16_t lds_degraded;
+    uint16_t lds_offline;
+    uint16_t pd_present;
+    uint16_t pd_disks_present;
+    uint16_t pd_disks_pred_failure;
+    uint16_t pd_disks_failed;
+    uint16_t nvram_size;
+    uint16_t memory_size;
+    uint16_t flash_size;
+    uint16_t ram_correctable_errors;
+    uint16_t ram_uncorrectable_errors;
+    uint8_t cluster_allowed;
+    uint8_t cluster_active;
+    uint16_t max_strips_per_io;
+
+    uint32_t raid_levels;
+#define MFI_INFO_RAID_0         0x01
+#define MFI_INFO_RAID_1         0x02
+#define MFI_INFO_RAID_5         0x04
+#define MFI_INFO_RAID_1E        0x08
+#define MFI_INFO_RAID_6         0x10
+
+    uint32_t adapter_ops;
+#define MFI_INFO_AOPS_RBLD_RATE         0x0001
+#define MFI_INFO_AOPS_CC_RATE           0x0002
+#define MFI_INFO_AOPS_BGI_RATE          0x0004
+#define MFI_INFO_AOPS_RECON_RATE        0x0008
+#define MFI_INFO_AOPS_PATROL_RATE       0x0010
+#define MFI_INFO_AOPS_ALARM_CONTROL     0x0020
+#define MFI_INFO_AOPS_CLUSTER_SUPPORTED 0x0040
+#define MFI_INFO_AOPS_BBU               0x0080
+#define MFI_INFO_AOPS_SPANNING_ALLOWED  0x0100
+#define MFI_INFO_AOPS_DEDICATED_SPARES  0x0200
+#define MFI_INFO_AOPS_REVERTIBLE_SPARES 0x0400
+#define MFI_INFO_AOPS_FOREIGN_IMPORT    0x0800
+#define MFI_INFO_AOPS_SELF_DIAGNOSTIC   0x1000
+#define MFI_INFO_AOPS_MIXED_ARRAY       0x2000
+#define MFI_INFO_AOPS_GLOBAL_SPARES     0x4000
+
+    uint32_t ld_ops;
+#define MFI_INFO_LDOPS_READ_POLICY      0x01
+#define MFI_INFO_LDOPS_WRITE_POLICY     0x02
+#define MFI_INFO_LDOPS_IO_POLICY        0x04
+#define MFI_INFO_LDOPS_ACCESS_POLICY    0x08
+#define MFI_INFO_LDOPS_DISK_CACHE_POLICY 0x10
+
+    struct {
+        uint8_t min;
+        uint8_t max;
+        uint8_t reserved[2];
+    } __attribute__ ((packed)) stripe_sz_ops;
+
+    uint32_t pd_ops;
+#define MFI_INFO_PDOPS_FORCE_ONLINE     0x01
+#define MFI_INFO_PDOPS_FORCE_OFFLINE    0x02
+#define MFI_INFO_PDOPS_FORCE_REBUILD    0x04
+
+    uint32_t pd_mix_support;
+#define MFI_INFO_PDMIX_SAS              0x01
+#define MFI_INFO_PDMIX_SATA             0x02
+#define MFI_INFO_PDMIX_ENCL             0x04
+#define MFI_INFO_PDMIX_LD               0x08
+#define MFI_INFO_PDMIX_SATA_CLUSTER     0x10
+
+    uint8_t ecc_bucket_count;
+    uint8_t reserved2[11];
+    struct mfi_ctrl_props properties;
+    char package_version[0x60];
+    uint8_t pad[0x800 - 0x6a0];
+} __attribute__ ((packed));
+
+/* keep track of an event. */
+union mfi_evt {
+    struct {
+        uint16_t locale;
+        uint8_t reserved;
+        int8_t class;
+    } members;
+    uint32_t word;
+} __attribute__ ((packed));
+
+/* event log state. */
+struct mfi_evt_log_state {
+    uint32_t newest_seq_num;
+    uint32_t oldest_seq_num;
+    uint32_t clear_seq_num;
+    uint32_t shutdown_seq_num;
+    uint32_t boot_seq_num;
+} __attribute__ ((packed));
+
+struct mfi_progress {
+    uint16_t progress;
+    uint16_t elapsed_seconds;
+} __attribute__ ((packed));
+
+struct mfi_evt_ld {
+    uint16_t target_id;
+    uint8_t ld_index;
+    uint8_t reserved;
+} __attribute__ ((packed));
+
+struct mfi_evt_pd {
+    uint16_t device_id;
+    uint8_t enclosure_index;
+    uint8_t slot_number;
+} __attribute__ ((packed));
+
+/* event detail, returned from MFI_DCMD_CTRL_EVENT_WAIT. */
+struct mfi_evt_detail {
+    uint32_t seq;
+    uint32_t time;
+    uint32_t code;
+    union mfi_evt class;
+    uint8_t arg_type;
+    uint8_t reserved1[15];
+
+    union {
+        struct {
+            struct mfi_evt_pd pd;
+            uint8_t cdb_len;
+            uint8_t sense_len;
+            uint8_t reserved[2];
+            uint8_t cdb[16];
+            uint8_t sense[64];
+        } cdb_sense;
+
+        struct mfi_evt_ld ld;
+
+        struct {
+            struct mfi_evt_ld ld;
+            uint64_t count;
+        } ld_count;
+
+        struct {
+            uint64_t lba;
+            struct mfi_evt_ld ld;
+        } ld_lba;
+
+        struct {
+            struct mfi_evt_ld ld;
+            uint32_t pre_owner;
+            uint32_t new_owner;
+        } ld_owner;
+
+        struct {
+            uint64_t ld_lba;
+            uint64_t pd_lba;
+            struct mfi_evt_ld ld;
+            struct mfi_evt_pd pd;
+        } ld_lba_pd_lba;
+
+        struct {
+            struct mfi_evt_ld ld;
+            struct mfi_progress prog;
+        } ld_prog;
+
+        struct {
+            struct mfi_evt_ld ld;
+            uint32_t prev_state;
+            uint32_t new_state;
+        } ld_state;
+
+        struct {
+            uint64_t strip;
+            struct mfi_evt_ld ld;
+        } ld_strip;
+
+        struct mfi_evt_pd pd;
+
+        struct {
+            struct mfi_evt_pd pd;
+            uint32_t err;
+        } pd_err;
+
+        struct {
+            uint64_t lba;
+            struct mfi_evt_pd pd;
+        } pd_lba;
+
+        struct {
+            uint64_t lba;
+            struct mfi_evt_pd pd;
+            struct mfi_evt_ld ld;
+        } pd_lba_ld;
+
+        struct {
+            struct mfi_evt_pd pd;
+            struct mfi_progress prog;
+        } pd_prog;
+
+        struct {
+            struct mfi_evt_pd ld;
+            uint32_t prev_state;
+            uint32_t new_state;
+        } pd_state;
+
+        struct {
+            uint16_t venderId;
+            uint16_t deviceId;
+            uint16_t subVenderId;
+            uint16_t subDeviceId;
+        } pci;
+
+        uint32_t rate;
+
+        char str[96];
+
+        struct {
+            uint32_t rtc;
+            uint16_t elapsedSeconds;
+        } time;
+
+        struct {
+            uint32_t ecar;
+            uint32_t elog;
+            char str[64];
+        } ecc;
+
+        uint8_t b[96];
+        uint16_t s[48];
+        uint32_t w[24];
+        uint64_t d[12];
+    } args;
+
+    char description[128];
+} __attribute__ ((packed));
+
+struct mfi_evt_list {
+    uint32_t count;
+    uint32_t reserved;
+    struct mfi_evt_detail event[1];
+} __attribute__ ((packed));
+
+union mfi_pd_ref {
+    struct {
+        uint16_t device_id;
+        uint16_t seq_num;
+    } v;
+    uint32_t ref;
+} __attribute__ ((packed));
+
+union mfi_pd_ddf_type {
+    struct {
+        uint16_t pd_type;
+#define MFI_PD_DDF_TYPE_FORCED_PD_GUID (1 << 0)
+#define MFI_PD_DDF_TYPE_IN_VD          (1 << 1)
+#define MFI_PD_DDF_TYPE_IS_GLOBAL_SPARE (1 << 2)
+#define MFI_PD_DDF_TYPE_IS_SPARE        (1 << 3)
+#define MFI_PD_DDF_TYPE_IS_FOREIGN      (1 << 4)
+#define MFI_PD_DDF_TYPE_INTF_SPI        (1 << 12)
+#define MFI_PD_DDF_TYPE_INTF_SAS        (1 << 13)
+#define MFI_PD_DDF_TYPE_INTF_SATA1      (1 << 14)
+#define MFI_PD_DDF_TYPE_INTF_SATA3G     (1 << 15)
+        uint16_t reserved;
+    } ddf;
+    struct {
+        uint32_t reserved;
+    } non_disk;
+    uint32_t type;
+} __attribute__ ((packed));
+
+struct mfi_pd_progress {
+    uint32_t active;
+#define PD_PROGRESS_ACTIVE_REBUILD (1 << 0)
+#define PD_PROGRESS_ACTIVE_PATROL  (1 << 1)
+#define PD_PROGRESS_ACTIVE_CLEAR   (1 << 2)
+    struct mfi_progress rbld;
+    struct mfi_progress patrol;
+    struct mfi_progress clear;
+    struct mfi_progress reserved[4];
+} __attribute__ ((packed));
+
+struct mfi_pd_info {
+    union mfi_pd_ref ref;
+    uint8_t inquiry_data[96];
+    uint8_t vpd_page83[64];
+    uint8_t not_supported;
+    uint8_t scsi_dev_type;
+    uint8_t connected_port_bitmap;
+    uint8_t device_speed;
+    uint32_t media_err_count;
+    uint32_t other_err_count;
+    uint32_t pred_fail_count;
+    uint32_t last_pred_fail_event_seq_num;
+    uint16_t fw_state;
+    uint8_t disable_for_removal;
+    uint8_t link_speed;
+    union mfi_pd_ddf_type state;
+    struct {
+        uint8_t count;
+        uint8_t is_path_broken;
+        uint8_t reserved[6];
+        uint64_t sas_addr[4];
+    } path_info;
+    uint64_t raw_size;
+    uint64_t non_coerced_size;
+    uint64_t coerced_size;
+    uint16_t encl_device_id;
+    uint8_t encl_index;
+    uint8_t slot_number;
+    struct mfi_pd_progress prog_info;
+    uint8_t bad_block_table_full;
+    uint8_t unusable_in_current_config;
+    uint8_t vpd_page83_ext[64];
+    uint8_t reserved[512-358];
+} __attribute__ ((packed));
+
+struct mfi_pd_address {
+    uint16_t device_id;
+    uint16_t encl_device_id;
+    uint8_t encl_index;
+    uint8_t slot_number;
+    uint8_t scsi_dev_type;
+    uint8_t connect_port_bitmap;
+    uint64_t sas_addr[2];
+} __attribute__ ((packed));
+
+#define MFI_MAX_SYS_PDS 240
+struct mfi_pd_list {
+    uint32_t size;
+    uint32_t count;
+    struct mfi_pd_address addr[MFI_MAX_SYS_PDS];
+} __attribute__ ((packed));
+
+union mfi_ld_ref {
+    struct {
+        uint8_t target_id;
+        uint8_t reserved;
+        uint16_t seq;
+    } v;
+    uint32_t ref;
+} __attribute__ ((packed));
+
+struct mfi_ld_list {
+    uint32_t ld_count;
+    uint32_t reserved1;
+    struct {
+        union mfi_ld_ref ld;
+        uint8_t state;
+        uint8_t reserved2[3];
+        uint64_t size;
+    } ld_list[MFI_MAX_LD];
+} __attribute__ ((packed));
+
+enum mfi_ld_access {
+    MFI_LD_ACCESS_RW =          0,
+    MFI_LD_ACCSSS_RO =          2,
+    MFI_LD_ACCESS_BLOCKED =     3,
+};
+#define MFI_LD_ACCESS_MASK      3
+
+enum mfi_ld_state {
+    MFI_LD_STATE_OFFLINE =              0,
+    MFI_LD_STATE_PARTIALLY_DEGRADED =   1,
+    MFI_LD_STATE_DEGRADED =             2,
+    MFI_LD_STATE_OPTIMAL =              3
+};
+
+enum mfi_syspd_state {
+    MFI_PD_STATE_UNCONFIGURED_GOOD =    0x00,
+    MFI_PD_STATE_UNCONFIGURED_BAD =     0x01,
+    MFI_PD_STATE_HOT_SPARE =            0x02,
+    MFI_PD_STATE_OFFLINE =              0x10,
+    MFI_PD_STATE_FAILED =               0x11,
+    MFI_PD_STATE_REBUILD =              0x14,
+    MFI_PD_STATE_ONLINE =               0x18,
+    MFI_PD_STATE_COPYBACK =             0x20,
+    MFI_PD_STATE_SYSTEM =               0x40
+};
+
+struct mfi_ld_props {
+    union mfi_ld_ref ld;
+    char name[16];
+    uint8_t default_cache_policy;
+    uint8_t access_policy;
+    uint8_t disk_cache_policy;
+    uint8_t current_cache_policy;
+    uint8_t no_bgi;
+    uint8_t reserved[7];
+} __attribute__ ((packed));
+
+struct mfi_ld_params {
+    uint8_t primary_raid_level;
+    uint8_t raid_level_qualifier;
+    uint8_t secondary_raid_level;
+    uint8_t stripe_size;
+    uint8_t num_drives;
+    uint8_t span_depth;
+    uint8_t state;
+    uint8_t init_state;
+    uint8_t is_consistent;
+    uint8_t reserved[23];
+} __attribute__ ((packed));
+
+struct mfi_ld_progress {
+    uint32_t            active;
+#define MFI_LD_PROGRESS_CC      (1<<0)
+#define MFI_LD_PROGRESS_BGI     (1<<1)
+#define MFI_LD_PROGRESS_FGI     (1<<2)
+#define MFI_LD_PORGRESS_RECON   (1<<3)
+    struct mfi_progress cc;
+    struct mfi_progress bgi;
+    struct mfi_progress fgi;
+    struct mfi_progress recon;
+    struct mfi_progress reserved[4];
+} __attribute__ ((packed));
+
+struct mfi_span {
+    uint64_t start_block;
+    uint64_t num_blocks;
+    uint16_t array_ref;
+    uint8_t reserved[6];
+} __attribute__ ((packed));
+
+#define MFI_MAX_SPAN_DEPTH      8
+struct mfi_ld_config {
+    struct mfi_ld_props properties;
+    struct mfi_ld_params params;
+    struct mfi_span span[MFI_MAX_SPAN_DEPTH];
+} __attribute__ ((packed));
+
+struct mfi_ld_info {
+    struct mfi_ld_config ld_config;
+    uint64_t size;
+    struct mfi_ld_progress progress;
+    uint16_t cluster_owner;
+    uint8_t reconstruct_active;
+    uint8_t reserved1[1];
+    uint8_t vpd_page83[64];
+    uint8_t reserved2[16];
+} __attribute__ ((packed));
+
+union mfi_spare_type {
+    uint8_t flags;
+#define MFI_SPARE_IS_DEDICATED (1 << 0)
+#define MFI_SPARE_IS_REVERTABLE (1 << 1)
+#define MFI_SPARE_IS_ENCL_AFFINITY (1 << 2)
+    uint8_t type;
+} __attribute__ ((packed));
+
+#define MFI_MAX_ARRAYS 16
+struct mfi_spare {
+    union mfi_pd_ref ref;
+    union mfi_spare_type spare_type;
+    uint8_t reserved[2];
+    uint8_t array_count;
+    uint16_t array_refd[MFI_MAX_ARRAYS];
+} __attribute__ ((packed));
+
+#define MFI_MAX_ROW_SIZE 32
+struct mfi_array {
+    uint64_t size;
+    uint8_t num_drives;
+    uint8_t reserved;
+    uint16_t array_ref;
+    uint8_t pad[20];
+    struct {
+        union mfi_pd_ref ref;
+        uint16_t fw_state; /* enum mfi_syspd_state */
+        struct {
+            uint8_t pd;
+            uint8_t slot;
+        } encl;
+    } pd[MFI_MAX_ROW_SIZE];
+} __attribute__ ((packed));
+
+struct mfi_config_data {
+    uint32_t size;
+    uint16_t array_count;
+    uint16_t array_size;
+    uint16_t log_drv_count;
+    uint16_t log_drv_size;
+    uint16_t spares_count;
+    uint16_t spares_size;
+    uint8_t reserved[16];
+    /*
+      struct mfi_array  array[];
+      struct mfi_ld_config ld[];
+      struct mfi_spare  spare[];
+    */
+} __attribute__ ((packed));
+
+#define MFI_SCSI_MAX_TARGETS  128
+#define MFI_SCSI_MAX_LUNS       8
+#define MFI_SCSI_INITIATOR_ID 255
+#define MFI_SCSI_MAX_CMDS       8
+#define MFI_SCSI_MAX_CDB_LEN   16
+
+#endif /* MFI_REG_H */
commit 622695a4585a786fdcd53852c7af87ed0af1af80
Author: Ronnie Sahlberg <ronniesahlberg at gmail.com>
Date:   Sat May 26 14:56:41 2012 +1000

    ISCSI: force use of sg for SMC and SSC devices
    
    If the device we open is a SMC or SSC device, then force the use of sg. We
    dont have any medium changer or tape emulation so only passthrough via
    real sg or scsi-generic via iscsi would work anyway.
    
    Forcing sg also makes qemu skip trying to read from the device to guess
    the image format by reading from the device (find_image_format()).
    SMC devices do not implement READ6/10/12/16 so it is not possible to
    read from them (SSC have different CDBs).
    
    With this patch I can successfully manage a SMC device wiht iscsi in
    passthrough mode.
    
    Signed-off-by: Ronnie Sahlberg <ronniesahlberg at gmail.com>
    [Added TYPE_TAPE handling - Paolo]
    Signed-off-by: Paolo Bonzini <pbonzini at redhat.com>

diff --git a/block/iscsi.c b/block/iscsi.c
index 029739e..ac65277 100644
--- a/block/iscsi.c
+++ b/block/iscsi.c
@@ -1022,6 +1022,16 @@ static int iscsi_open(BlockDriverState *bs, const char *filename, int flags)
     if (iscsi_url != NULL) {
         iscsi_destroy_url(iscsi_url);
     }
+
+    /* Medium changer or tape. We dont have any emulation for this so this must
+     * be sg ioctl compatible. We force it to be sg, otherwise qemu will try
+     * to read from the device to guess the image format.
+     */
+    if (iscsilun->type == TYPE_MEDIUM_CHANGER ||
+        iscsilun->type == TYPE_TAPE) {
+        bs->sg = 1;
+    }
+
     return 0;
 
 failed:
commit 983924532f61091fd90d1f2fafa4aa938c414dbb
Author: Ronnie Sahlberg <ronniesahlberg at gmail.com>
Date:   Fri May 25 21:59:01 2012 +1000

    ISCSI: Add SCSI passthrough via scsi-generic to libiscsi
    
    Update iscsi to allow passthrough of SG_IO scsi commands when the iscsi
    device is forced to be scsi-generic.
    
    Implement both bdrv_ioctl() and bdrv_aio_ioctl() in the iscsi backend,
    emulate the SG_IO ioctl and pass the SCSI commands across to the
    iscsi target.
    
    This allows end-to-end passthrough of SCSI all the way from the guest,
    to qemu, via scsi-generic, then libiscsi all the way to the iscsi target.
    
    To activate this you need to specify that the iscsi lun should be treated
    as a scsi-generic device.
    
    Example:
        -device lsi -device scsi-generic,drive=MyISCSI \
        -drive file=iscsi://10.1.1.125/iqn.ronnie.test/1,if=none,id=MyISCSI
    
    Note, you can currently not boot a qemu guest from a scsi device.
    
    Note,
    This only works when the host is linux, since the emulation relies on
    definitions of SG_IO from the scsi-generic implementation in the
    linux kernel.
    It should be fairly easy to re-implement some structures similar enough
    for non-linux hosts to do the same style of passthrough via a fake
    scsi generic layer and libiscsi if need be.
    
    Signed-off-by: Ronnie Sahlberg <ronniesahlberg at gmail.com>
    Signed-off-by: Paolo Bonzini <pbonzini at redhat.com>

diff --git a/block/iscsi.c b/block/iscsi.c
index 22888a0..029739e 100644
--- a/block/iscsi.c
+++ b/block/iscsi.c
@@ -35,6 +35,10 @@
 #include <iscsi/iscsi.h>
 #include <iscsi/scsi-lowlevel.h>
 
+#ifdef __linux__
+#include <scsi/sg.h>
+#include <hw/scsi-defs.h>
+#endif
 
 typedef struct IscsiLun {
     struct iscsi_context *iscsi;
@@ -56,6 +60,9 @@ typedef struct IscsiAIOCB {
     int canceled;
     size_t read_size;
     size_t read_offset;
+#ifdef __linux__
+    sg_io_hdr_t *ioh;
+#endif
 } IscsiAIOCB;
 
 struct IscsiTask {
@@ -515,6 +522,136 @@ iscsi_aio_discard(BlockDriverState *bs,
     return &acb->common;
 }
 
+#ifdef __linux__
+static void
+iscsi_aio_ioctl_cb(struct iscsi_context *iscsi, int status,
+                     void *command_data, void *opaque)
+{
+    IscsiAIOCB *acb = opaque;
+
+    if (acb->canceled != 0) {
+        qemu_aio_release(acb);
+        scsi_free_scsi_task(acb->task);
+        acb->task = NULL;
+        return;
+    }
+
+    acb->status = 0;
+    if (status < 0) {
+        error_report("Failed to ioctl(SG_IO) to iSCSI lun. %s",
+                     iscsi_get_error(iscsi));
+        acb->status = -EIO;
+    }
+
+    acb->ioh->driver_status = 0;
+    acb->ioh->host_status   = 0;
+    acb->ioh->resid         = 0;
+
+#define SG_ERR_DRIVER_SENSE    0x08
+
+    if (status == SCSI_STATUS_CHECK_CONDITION && acb->task->datain.size >= 2) {
+        int ss;
+
+        acb->ioh->driver_status |= SG_ERR_DRIVER_SENSE;
+
+        acb->ioh->sb_len_wr = acb->task->datain.size - 2;
+        ss = (acb->ioh->mx_sb_len >= acb->ioh->sb_len_wr) ?
+             acb->ioh->mx_sb_len : acb->ioh->sb_len_wr;
+        memcpy(acb->ioh->sbp, &acb->task->datain.data[2], ss);
+    }
+
+    iscsi_schedule_bh(iscsi_readv_writev_bh_cb, acb);
+    scsi_free_scsi_task(acb->task);
+    acb->task = NULL;
+}
+
+static BlockDriverAIOCB *iscsi_aio_ioctl(BlockDriverState *bs,
+        unsigned long int req, void *buf,
+        BlockDriverCompletionFunc *cb, void *opaque)
+{
+    IscsiLun *iscsilun = bs->opaque;
+    struct iscsi_context *iscsi = iscsilun->iscsi;
+    struct iscsi_data data;
+    IscsiAIOCB *acb;
+
+    assert(req == SG_IO);
+
+    acb = qemu_aio_get(&iscsi_aio_pool, bs, cb, opaque);
+
+    acb->iscsilun = iscsilun;
+    acb->canceled    = 0;
+    acb->buf         = NULL;
+    acb->ioh         = buf;
+
+    acb->task = malloc(sizeof(struct scsi_task));
+    if (acb->task == NULL) {
+        error_report("iSCSI: Failed to allocate task for scsi command. %s",
+                     iscsi_get_error(iscsi));
+        qemu_aio_release(acb);
+        return NULL;
+    }
+    memset(acb->task, 0, sizeof(struct scsi_task));
+
+    switch (acb->ioh->dxfer_direction) {
+    case SG_DXFER_TO_DEV:
+        acb->task->xfer_dir = SCSI_XFER_WRITE;
+        break;
+    case SG_DXFER_FROM_DEV:
+        acb->task->xfer_dir = SCSI_XFER_READ;
+        break;
+    default:
+        acb->task->xfer_dir = SCSI_XFER_NONE;
+        break;
+    }
+
+    acb->task->cdb_size = acb->ioh->cmd_len;
+    memcpy(&acb->task->cdb[0], acb->ioh->cmdp, acb->ioh->cmd_len);
+    acb->task->expxferlen = acb->ioh->dxfer_len;
+
+    if (acb->task->xfer_dir == SCSI_XFER_WRITE) {
+        data.data = acb->ioh->dxferp;
+        data.size = acb->ioh->dxfer_len;
+    }
+    if (iscsi_scsi_command_async(iscsi, iscsilun->lun, acb->task,
+                                 iscsi_aio_ioctl_cb,
+                                 (acb->task->xfer_dir == SCSI_XFER_WRITE) ?
+                                     &data : NULL,
+                                 acb) != 0) {
+        scsi_free_scsi_task(acb->task);
+        qemu_aio_release(acb);
+        return NULL;
+    }
+
+    /* tell libiscsi to read straight into the buffer we got from ioctl */
+    if (acb->task->xfer_dir == SCSI_XFER_READ) {
+        scsi_task_add_data_in_buffer(acb->task,
+                                     acb->ioh->dxfer_len,
+                                     acb->ioh->dxferp);
+    }
+
+    iscsi_set_events(iscsilun);
+
+    return &acb->common;
+}
+
+static int iscsi_ioctl(BlockDriverState *bs, unsigned long int req, void *buf)
+{
+    IscsiLun *iscsilun = bs->opaque;
+
+    switch (req) {
+    case SG_GET_VERSION_NUM:
+        *(int *)buf = 30000;
+        break;
+    case SG_GET_SCSI_ID:
+        ((struct sg_scsi_id *)buf)->scsi_type = iscsilun->type;
+        break;
+    default:
+        return -1;
+    }
+    return 0;
+}
+#endif
+
 static int64_t
 iscsi_getlength(BlockDriverState *bs)
 {
@@ -926,6 +1063,11 @@ static BlockDriver bdrv_iscsi = {
     .bdrv_aio_flush  = iscsi_aio_flush,
 
     .bdrv_aio_discard = iscsi_aio_discard,
+
+#ifdef __linux__
+    .bdrv_ioctl       = iscsi_ioctl,
+    .bdrv_aio_ioctl   = iscsi_aio_ioctl,
+#endif
 };
 
 static void iscsi_block_init(void)
diff --git a/hw/scsi-generic.c b/hw/scsi-generic.c
index d856d23..8d51060 100644
--- a/hw/scsi-generic.c
+++ b/hw/scsi-generic.c
@@ -400,12 +400,6 @@ static int scsi_generic_initfn(SCSIDevice *s)
         return -1;
     }
 
-    /* check we are really using a /dev/sg* file */
-    if (!bdrv_is_sg(s->conf.bs)) {
-        error_report("not /dev/sg*");
-        return -1;
-    }
-
     if (bdrv_get_on_error(s->conf.bs, 0) != BLOCK_ERR_STOP_ENOSPC) {
         error_report("Device doesn't support drive option werror");
         return -1;
@@ -416,8 +410,11 @@ static int scsi_generic_initfn(SCSIDevice *s)
     }
 
     /* check we are using a driver managing SG_IO (version 3 and after */
-    if (bdrv_ioctl(s->conf.bs, SG_GET_VERSION_NUM, &sg_version) < 0 ||
-        sg_version < 30000) {
+    if (bdrv_ioctl(s->conf.bs, SG_GET_VERSION_NUM, &sg_version) < 0) {
+        error_report("scsi generic interface not supported");
+        return -1;
+    }
+    if (sg_version < 30000) {
         error_report("scsi generic interface too old");
         return -1;
     }
commit 1a4f0c3a0621e6644f3cfc0121478641337ac9ca
Author: Paolo Bonzini <pbonzini at redhat.com>
Date:   Fri May 25 12:59:55 2012 +0200

    scsi-disk: implement READ DISC INFORMATION
    
    This command is not necessary for CD-ROM and DVD-ROM, but some versions of
    udev trip on its absence.
    
    Cc: Kevin Wolf <kwolf at redhat.com>
    Cc: Markus Armbruster <armbru at redhat.com>
    Signed-off-by: Paolo Bonzini <pbonzini at redhat.com>

diff --git a/hw/scsi-defs.h b/hw/scsi-defs.h
index 219c84d..3c9f1b5 100644
--- a/hw/scsi-defs.h
+++ b/hw/scsi-defs.h
@@ -82,6 +82,7 @@
 #define GET_EVENT_STATUS_NOTIFICATION 0x4a
 #define LOG_SELECT            0x4c
 #define LOG_SENSE             0x4d
+#define READ_DISC_INFORMATION 0x51
 #define RESERVE_TRACK         0x53
 #define MODE_SELECT_10        0x55
 #define RESERVE_10            0x56
diff --git a/hw/scsi-disk.c b/hw/scsi-disk.c
index e87e57c..34336b1 100644
--- a/hw/scsi-disk.c
+++ b/hw/scsi-disk.c
@@ -724,6 +724,39 @@ static inline bool media_is_cd(SCSIDiskState *s)
     return nb_sectors <= CD_MAX_SECTORS;
 }
 
+static int scsi_read_disc_information(SCSIDiskState *s, SCSIDiskReq *r,
+                                      uint8_t *outbuf)
+{
+    uint8_t type = r->req.cmd.buf[1] & 7;
+
+    if (s->qdev.type != TYPE_ROM) {
+        return -1;
+    }
+
+    /* Types 1/2 are only defined for Blu-Ray.  */
+    if (type != 0) {
+        scsi_check_condition(r, SENSE_CODE(INVALID_FIELD));
+        return -1;
+    }
+
+    memset(outbuf, 0, 34);
+    outbuf[1] = 32;
+    outbuf[2] = 0xe; /* last session complete, disc finalized */
+    outbuf[3] = 1;   /* first track on disc */
+    outbuf[4] = 1;   /* # of sessions */
+    outbuf[5] = 1;   /* first track of last session */
+    outbuf[6] = 1;   /* last track of last session */
+    outbuf[7] = 0x20; /* unrestricted use */
+    outbuf[8] = 0x00; /* CD-ROM or DVD-ROM */
+    /* 9-10-11: most significant byte corresponding bytes 4-5-6 */
+    /* 12-23: not meaningful for CD-ROM or DVD-ROM */
+    /* 24-31: disc bar code */
+    /* 32: disc application code */
+    /* 33: number of OPC tables */
+
+    return 34;
+}
+
 static int scsi_read_dvd_structure(SCSIDiskState *s, SCSIDiskReq *r,
                                    uint8_t *outbuf)
 {
@@ -1363,6 +1396,12 @@ static int scsi_disk_emulate_command(SCSIDiskReq *r)
             goto illegal_request;
         }
         break;
+    case READ_DISC_INFORMATION:
+        buflen = scsi_read_disc_information(s, r, outbuf);
+        if (buflen < 0) {
+            goto illegal_request;
+        }
+        break;
     case READ_DVD_STRUCTURE:
         buflen = scsi_read_dvd_structure(s, r, outbuf);
         if (buflen < 0) {
@@ -1490,6 +1529,7 @@ static int32_t scsi_send_command(SCSIRequest *req, uint8_t *buf)
     case ALLOW_MEDIUM_REMOVAL:
     case READ_CAPACITY_10:
     case READ_TOC:
+    case READ_DISC_INFORMATION:
     case READ_DVD_STRUCTURE:
     case GET_CONFIGURATION:
     case GET_EVENT_STATUS_NOTIFICATION:
commit 55042b955b56e633120027ad0cdc6c059ab9954d
Author: Paolo Bonzini <pbonzini at redhat.com>
Date:   Fri May 25 12:59:31 2012 +0200

    atapi: implement READ DISC INFORMATION
    
    This command is not necessary for CD-ROM and DVD-ROM, but some versions of
    udev trip on its absence.
    
    Cc: Kevin Wolf <kwolf at redhat.com>
    Cc: Markus Armbruster <armbru at redhat.com>
    Signed-off-by: Paolo Bonzini <pbonzini at redhat.com>

diff --git a/hw/ide/atapi.c b/hw/ide/atapi.c
index 5919cf5..f7f714c 100644
--- a/hw/ide/atapi.c
+++ b/hw/ide/atapi.c
@@ -956,6 +956,36 @@ static void cmd_read_cdvd_capacity(IDEState *s, uint8_t* buf)
     ide_atapi_cmd_reply(s, 8, 8);
 }
 
+static void cmd_read_disc_information(IDEState *s, uint8_t* buf)
+{
+    uint8_t type = buf[1] & 7;
+    uint32_t max_len = ube16_to_cpu(buf + 7);
+
+    /* Types 1/2 are only defined for Blu-Ray.  */
+    if (type != 0) {
+        ide_atapi_cmd_error(s, ILLEGAL_REQUEST,
+                            ASC_INV_FIELD_IN_CMD_PACKET);
+        return;
+    }
+
+    memset(buf, 0, 34);
+    buf[1] = 32;
+    buf[2] = 0xe; /* last session complete, disc finalized */
+    buf[3] = 1;   /* first track on disc */
+    buf[4] = 1;   /* # of sessions */
+    buf[5] = 1;   /* first track of last session */
+    buf[6] = 1;   /* last track of last session */
+    buf[7] = 0x20; /* unrestricted use */
+    buf[8] = 0x00; /* CD-ROM or DVD-ROM */
+    /* 9-10-11: most significant byte corresponding bytes 4-5-6 */
+    /* 12-23: not meaningful for CD-ROM or DVD-ROM */
+    /* 24-31: disc bar code */
+    /* 32: disc application code */
+    /* 33: number of OPC tables */
+
+    ide_atapi_cmd_reply(s, 34, max_len);
+}
+
 static void cmd_read_dvd_structure(IDEState *s, uint8_t* buf)
 {
     int max_len;
@@ -1045,6 +1075,7 @@ static const struct {
     [ 0x43 ] = { cmd_read_toc_pma_atip,             CHECK_READY },
     [ 0x46 ] = { cmd_get_configuration,             ALLOW_UA },
     [ 0x4a ] = { cmd_get_event_status_notification, ALLOW_UA },
+    [ 0x51 ] = { cmd_read_disc_information,         CHECK_READY },
     [ 0x5a ] = { cmd_mode_sense, /* (10) */         0 },
     [ 0xa8 ] = { cmd_read, /* (12) */               CHECK_READY },
     [ 0xad ] = { cmd_read_dvd_structure,            CHECK_READY },
commit 27395add759ff4caeb04a97c1bb0e8bdd7db12fb
Author: Paolo Bonzini <pbonzini at redhat.com>
Date:   Tue May 15 12:46:09 2012 +0200

    scsi: add a qdev property for the disk's WWN
    
    Signed-off-by: Paolo Bonzini <pbonzini at redhat.com>

diff --git a/hw/scsi-disk.c b/hw/scsi-disk.c
index 747e756..e87e57c 100644
--- a/hw/scsi-disk.c
+++ b/hw/scsi-disk.c
@@ -67,6 +67,7 @@ struct SCSIDiskState
     bool media_changed;
     bool media_event;
     bool eject_request;
+    uint64_t wwn;
     QEMUBH *bh;
     char *version;
     char *serial;
@@ -587,9 +588,17 @@ static int scsi_disk_emulate_inquiry(SCSIRequest *req, uint8_t *outbuf)
             outbuf[buflen++] = 0;   // not officially assigned
             outbuf[buflen++] = 0;   // reserved
             outbuf[buflen++] = id_len; // length of data following
-
             memcpy(outbuf+buflen, str, id_len);
             buflen += id_len;
+
+            if (s->wwn) {
+                outbuf[buflen++] = 0x1; // Binary
+                outbuf[buflen++] = 0x3; // NAA
+                outbuf[buflen++] = 0;   // reserved
+                outbuf[buflen++] = 8;
+                stq_be_p(&outbuf[buflen], s->wwn);
+                buflen += 8;
+            }
             break;
         }
         case 0xb0: /* block limits */
@@ -1924,6 +1933,7 @@ static Property scsi_hd_properties[] = {
                     SCSI_DISK_F_REMOVABLE, false),
     DEFINE_PROP_BIT("dpofua", SCSIDiskState, features,
                     SCSI_DISK_F_DPOFUA, false),
+    DEFINE_PROP_HEX64("wwn", SCSIDiskState, wwn, 0),
     DEFINE_PROP_END_OF_LIST(),
 };
 
@@ -1968,6 +1978,7 @@ static TypeInfo scsi_hd_info = {
 
 static Property scsi_cd_properties[] = {
     DEFINE_SCSI_DISK_PROPERTIES(),
+    DEFINE_PROP_HEX64("wwn", SCSIDiskState, wwn, 0),
     DEFINE_PROP_END_OF_LIST(),
 };
 
@@ -2029,6 +2040,7 @@ static Property scsi_disk_properties[] = {
                     SCSI_DISK_F_REMOVABLE, false),
     DEFINE_PROP_BIT("dpofua", SCSIDiskState, features,
                     SCSI_DISK_F_DPOFUA, false),
+    DEFINE_PROP_HEX64("wwn", SCSIDiskState, wwn, 0),
     DEFINE_PROP_END_OF_LIST(),
 };
 
commit 8257939002727748cc73b02eacb663b2d5b7fd25
Author: Paolo Bonzini <pbonzini at redhat.com>
Date:   Tue May 15 12:45:20 2012 +0200

    scsi: simplify handling of the VPD page length field
    
    The last four bytes of the thin provisioning page were cut out.
    
    Signed-off-by: Paolo Bonzini <pbonzini at redhat.com>

diff --git a/hw/scsi-disk.c b/hw/scsi-disk.c
index ae25194..747e756 100644
--- a/hw/scsi-disk.c
+++ b/hw/scsi-disk.c
@@ -522,6 +522,7 @@ static int scsi_disk_emulate_inquiry(SCSIRequest *req, uint8_t *outbuf)
 {
     SCSIDiskState *s = DO_UPCAST(SCSIDiskState, qdev, req->dev);
     int buflen = 0;
+    int start;
 
     if (req->cmd.buf[1] & 0x1) {
         /* Vital product data */
@@ -530,14 +531,14 @@ static int scsi_disk_emulate_inquiry(SCSIRequest *req, uint8_t *outbuf)
         outbuf[buflen++] = s->qdev.type & 0x1f;
         outbuf[buflen++] = page_code ; // this page
         outbuf[buflen++] = 0x00;
+        outbuf[buflen++] = 0x00;
+        start = buflen;
 
         switch (page_code) {
         case 0x00: /* Supported page codes, mandatory */
         {
-            int pages;
             DPRINTF("Inquiry EVPD[Supported pages] "
                     "buffer size %zd\n", req->cmd.xfer);
-            pages = buflen++;
             outbuf[buflen++] = 0x00; // list of supported pages (this page)
             if (s->serial) {
                 outbuf[buflen++] = 0x80; // unit serial number
@@ -547,7 +548,6 @@ static int scsi_disk_emulate_inquiry(SCSIRequest *req, uint8_t *outbuf)
                 outbuf[buflen++] = 0xb0; // block limits
                 outbuf[buflen++] = 0xb2; // thin provisioning
             }
-            outbuf[pages] = buflen - pages - 1; // number of pages
             break;
         }
         case 0x80: /* Device serial number, optional */
@@ -566,7 +566,6 @@ static int scsi_disk_emulate_inquiry(SCSIRequest *req, uint8_t *outbuf)
 
             DPRINTF("Inquiry EVPD[Serial number] "
                     "buffer size %zd\n", req->cmd.xfer);
-            outbuf[buflen++] = l;
             memcpy(outbuf+buflen, s->serial, l);
             buflen += l;
             break;
@@ -584,7 +583,6 @@ static int scsi_disk_emulate_inquiry(SCSIRequest *req, uint8_t *outbuf)
             DPRINTF("Inquiry EVPD[Device identification] "
                     "buffer size %zd\n", req->cmd.xfer);
 
-            outbuf[buflen++] = 4 + id_len;
             outbuf[buflen++] = 0x2; // ASCII
             outbuf[buflen++] = 0;   // not officially assigned
             outbuf[buflen++] = 0;   // reserved
@@ -609,8 +607,7 @@ static int scsi_disk_emulate_inquiry(SCSIRequest *req, uint8_t *outbuf)
                 return -1;
             }
             /* required VPD size with unmap support */
-            outbuf[3] = buflen = 0x3c;
-
+            buflen = 0x40;
             memset(outbuf + 4, 0, buflen - 4);
 
             /* optimal transfer length granularity */
@@ -632,7 +629,7 @@ static int scsi_disk_emulate_inquiry(SCSIRequest *req, uint8_t *outbuf)
         }
         case 0xb2: /* thin provisioning */
         {
-            outbuf[3] = buflen = 8;
+            buflen = 8;
             outbuf[4] = 0;
             outbuf[5] = 0x60; /* write_same 10/16 supported */
             outbuf[6] = s->qdev.conf.discard_granularity ? 2 : 1;
@@ -643,6 +640,8 @@ static int scsi_disk_emulate_inquiry(SCSIRequest *req, uint8_t *outbuf)
             return -1;
         }
         /* done with EVPD */
+        assert(buflen - start <= 255);
+        outbuf[start - 1] = buflen - start;
         return buflen;
     }
 
commit df410675e5fad55e056fb505cba3a62cac13c411
Author: Alex Williamson <alex.williamson at redhat.com>
Date:   Mon Jun 25 09:40:39 2012 -0600

    kvm: Don't abort on kvm_irqchip_add_msi_route()
    
    Anyone using these functions has to be prepared that irqchip
    support may not be present.  It shouldn't be up to the core
    code to determine whether this is a fatal error.  Currently
    code written as:
    
    virq = kvm_irqchip_add_msi_route(...)
    if (virq < 0) {
        <slow path>
    } else {
        <fast path>
    }
    
    works on x86 with and without kvm irqchip enabled, works
    without kvm support compiled in, but aborts() on !x86 with
    kvm support.
    
    Signed-off-by: Alex Williamson <alex.williamson at redhat.com>
    Acked-by: Jan Kiszka <jan.kiszka at siemens.com>
    Signed-off-by: Marcelo Tosatti <mtosatti at redhat.com>

diff --git a/kvm-all.c b/kvm-all.c
index f8e4328..a0c33b3 100644
--- a/kvm-all.c
+++ b/kvm-all.c
@@ -1142,7 +1142,7 @@ int kvm_irqchip_send_msi(KVMState *s, MSIMessage msg)
 
 int kvm_irqchip_add_msi_route(KVMState *s, MSIMessage msg)
 {
-    abort();
+    return -ENOSYS;
 }
 
 static int kvm_irqchip_assign_irqfd(KVMState *s, int fd, int virq, bool assign)
commit 45f33f01f359d6028ec4b4018a2bf2ff53806e11
Author: Juan Quintela <quintela at redhat.com>
Date:   Fri Jun 22 15:21:07 2012 +0200

    Maintain the number of dirty pages
    
    Calculate the number of dirty pages takes a lot on hosts with lots
    of memory.  Just maintain how many pages are dirty.
    
    Signed-off-by: Juan Quintela <quintela at redhat.com>

diff --git a/arch_init.c b/arch_init.c
index 64b85fd..5b0f562 100644
--- a/arch_init.c
+++ b/arch_init.c
@@ -238,20 +238,7 @@ static uint64_t bytes_transferred;
 
 static ram_addr_t ram_save_remaining(void)
 {
-    RAMBlock *block;
-    ram_addr_t count = 0;
-
-    QLIST_FOREACH(block, &ram_list.blocks, next) {
-        ram_addr_t addr;
-        for (addr = 0; addr < block->length; addr += TARGET_PAGE_SIZE) {
-            if (memory_region_get_dirty(block->mr, addr, TARGET_PAGE_SIZE,
-                                        DIRTY_MEMORY_MIGRATION)) {
-                count++;
-            }
-        }
-    }
-
-    return count;
+    return ram_list.dirty_pages;
 }
 
 uint64_t ram_bytes_remaining(void)
diff --git a/cpu-all.h b/cpu-all.h
index 9dc249a..82ba1d7 100644
--- a/cpu-all.h
+++ b/cpu-all.h
@@ -486,6 +486,7 @@ typedef struct RAMBlock {
 typedef struct RAMList {
     uint8_t *phys_dirty;
     QLIST_HEAD(, RAMBlock) blocks;
+    uint64_t dirty_pages;
 } RAMList;
 extern RAMList ram_list;
 
diff --git a/exec-obsolete.h b/exec-obsolete.h
index f8ffce6..c099256 100644
--- a/exec-obsolete.h
+++ b/exec-obsolete.h
@@ -74,6 +74,11 @@ static inline int cpu_physical_memory_get_dirty(ram_addr_t start,
 static inline int cpu_physical_memory_set_dirty_flags(ram_addr_t addr,
                                                       int dirty_flags)
 {
+    if ((dirty_flags & MIGRATION_DIRTY_FLAG) &&
+        !cpu_physical_memory_get_dirty(addr, TARGET_PAGE_SIZE,
+                                       MIGRATION_DIRTY_FLAG)) {
+        ram_list.dirty_pages++;
+    }
     return ram_list.phys_dirty[addr >> TARGET_PAGE_BITS] |= dirty_flags;
 }
 
@@ -87,6 +92,11 @@ static inline int cpu_physical_memory_clear_dirty_flags(ram_addr_t addr,
 {
     int mask = ~dirty_flags;
 
+    if ((dirty_flags & MIGRATION_DIRTY_FLAG) &&
+        cpu_physical_memory_get_dirty(addr, TARGET_PAGE_SIZE,
+                                      MIGRATION_DIRTY_FLAG)) {
+        ram_list.dirty_pages--;
+    }
     return ram_list.phys_dirty[addr >> TARGET_PAGE_BITS] &= mask;
 }
 
commit 1720aeee72888f80b974c33b6eb39922a0bea992
Author: Juan Quintela <quintela at redhat.com>
Date:   Fri Jun 22 13:14:17 2012 +0200

    dirty bitmap: abstract its use
    
    Always use accessors to read/set the dirty bitmap.
    
    Signed-off-by: Juan Quintela <quintela at redhat.com>

diff --git a/exec-obsolete.h b/exec-obsolete.h
index 792c831..f8ffce6 100644
--- a/exec-obsolete.h
+++ b/exec-obsolete.h
@@ -45,15 +45,15 @@ int cpu_physical_memory_set_dirty_tracking(int enable);
 #define CODE_DIRTY_FLAG      0x02
 #define MIGRATION_DIRTY_FLAG 0x08
 
-/* read dirty bit (return 0 or 1) */
-static inline int cpu_physical_memory_is_dirty(ram_addr_t addr)
+static inline int cpu_physical_memory_get_dirty_flags(ram_addr_t addr)
 {
-    return ram_list.phys_dirty[addr >> TARGET_PAGE_BITS] == 0xff;
+    return ram_list.phys_dirty[addr >> TARGET_PAGE_BITS];
 }
 
-static inline int cpu_physical_memory_get_dirty_flags(ram_addr_t addr)
+/* read dirty bit (return 0 or 1) */
+static inline int cpu_physical_memory_is_dirty(ram_addr_t addr)
 {
-    return ram_list.phys_dirty[addr >> TARGET_PAGE_BITS];
+    return cpu_physical_memory_get_dirty_flags(addr) == 0xff;
 }
 
 static inline int cpu_physical_memory_get_dirty(ram_addr_t start,
@@ -61,41 +61,45 @@ static inline int cpu_physical_memory_get_dirty(ram_addr_t start,
                                                 int dirty_flags)
 {
     int ret = 0;
-    uint8_t *p;
     ram_addr_t addr, end;
 
     end = TARGET_PAGE_ALIGN(start + length);
     start &= TARGET_PAGE_MASK;
-    p = ram_list.phys_dirty + (start >> TARGET_PAGE_BITS);
     for (addr = start; addr < end; addr += TARGET_PAGE_SIZE) {
-        ret |= *p++ & dirty_flags;
+        ret |= cpu_physical_memory_get_dirty_flags(addr) & dirty_flags;
     }
     return ret;
 }
 
+static inline int cpu_physical_memory_set_dirty_flags(ram_addr_t addr,
+                                                      int dirty_flags)
+{
+    return ram_list.phys_dirty[addr >> TARGET_PAGE_BITS] |= dirty_flags;
+}
+
 static inline void cpu_physical_memory_set_dirty(ram_addr_t addr)
 {
-    ram_list.phys_dirty[addr >> TARGET_PAGE_BITS] = 0xff;
+    cpu_physical_memory_set_dirty_flags(addr, 0xff);
 }
 
-static inline int cpu_physical_memory_set_dirty_flags(ram_addr_t addr,
-                                                      int dirty_flags)
+static inline int cpu_physical_memory_clear_dirty_flags(ram_addr_t addr,
+                                                        int dirty_flags)
 {
-    return ram_list.phys_dirty[addr >> TARGET_PAGE_BITS] |= dirty_flags;
+    int mask = ~dirty_flags;
+
+    return ram_list.phys_dirty[addr >> TARGET_PAGE_BITS] &= mask;
 }
 
 static inline void cpu_physical_memory_set_dirty_range(ram_addr_t start,
                                                        ram_addr_t length,
                                                        int dirty_flags)
 {
-    uint8_t *p;
     ram_addr_t addr, end;
 
     end = TARGET_PAGE_ALIGN(start + length);
     start &= TARGET_PAGE_MASK;
-    p = ram_list.phys_dirty + (start >> TARGET_PAGE_BITS);
     for (addr = start; addr < end; addr += TARGET_PAGE_SIZE) {
-        *p++ |= dirty_flags;
+        cpu_physical_memory_set_dirty_flags(addr, dirty_flags);
     }
 }
 
@@ -103,16 +107,12 @@ static inline void cpu_physical_memory_mask_dirty_range(ram_addr_t start,
                                                         ram_addr_t length,
                                                         int dirty_flags)
 {
-    int mask;
-    uint8_t *p;
     ram_addr_t addr, end;
 
     end = TARGET_PAGE_ALIGN(start + length);
     start &= TARGET_PAGE_MASK;
-    mask = ~dirty_flags;
-    p = ram_list.phys_dirty + (start >> TARGET_PAGE_BITS);
     for (addr = start; addr < end; addr += TARGET_PAGE_SIZE) {
-        *p++ &= mask;
+        cpu_physical_memory_clear_dirty_flags(addr, dirty_flags);
     }
 }
 
diff --git a/exec.c b/exec.c
index a68b65c..dd4833d 100644
--- a/exec.c
+++ b/exec.c
@@ -2565,8 +2565,7 @@ ram_addr_t qemu_ram_alloc_from_ptr(ram_addr_t size, void *host,
 
     ram_list.phys_dirty = g_realloc(ram_list.phys_dirty,
                                        last_ram_offset() >> TARGET_PAGE_BITS);
-    memset(ram_list.phys_dirty + (new_block->offset >> TARGET_PAGE_BITS),
-           0xff, size >> TARGET_PAGE_BITS);
+    cpu_physical_memory_set_dirty_range(new_block->offset, size, 0xff);
 
     if (kvm_enabled())
         kvm_setup_guest_memory(new_block->host, size);
commit 4508bd9ed8053cef0a1a849bf2f1896a5dd86580
Author: Juan Quintela <quintela at redhat.com>
Date:   Tue May 22 16:27:59 2012 +0200

    Exit loop if we have been there too long
    
    Checking each 64 pages is a random magic number as good as any other.
    We don't want to test too many times, but on the other hand,
    qemu_get_clock_ns() is not so expensive either.  We want to be sure
    that we spent less than 50ms (half of buffered_file timer), if we
    spent more than 100ms, all the accounting got wrong.
    
    Signed-off-by: Juan Quintela <quintela at redhat.com>

diff --git a/arch_init.c b/arch_init.c
index 3633f4c..64b85fd 100644
--- a/arch_init.c
+++ b/arch_init.c
@@ -309,12 +309,15 @@ static void migration_end(void)
     memory_global_dirty_log_stop();
 }
 
+#define MAX_WAIT 50 /* ms, half buffered_file limit */
+
 int ram_save_live(QEMUFile *f, int stage, void *opaque)
 {
     ram_addr_t addr;
     uint64_t bytes_transferred_last;
     double bwidth = 0;
     int ret;
+    int i;
 
     if (stage < 0) {
         migration_end();
@@ -354,6 +357,7 @@ int ram_save_live(QEMUFile *f, int stage, void *opaque)
     bytes_transferred_last = bytes_transferred;
     bwidth = qemu_get_clock_ns(rt_clock);
 
+    i = 0;
     while ((ret = qemu_file_rate_limit(f)) == 0) {
         int bytes_sent;
 
@@ -362,6 +366,20 @@ int ram_save_live(QEMUFile *f, int stage, void *opaque)
         if (bytes_sent == 0) { /* no more blocks */
             break;
         }
+        /* we want to check in the 1st loop, just in case it was the 1st time
+           and we had to sync the dirty bitmap.
+           qemu_get_clock_ns() is a bit expensive, so we only check each some
+           iterations
+        */
+        if ((i & 63) == 0) {
+            uint64_t t1 = (qemu_get_clock_ns(rt_clock) - bwidth) / 1000000;
+            if (t1 > MAX_WAIT) {
+                DPRINTF("big wait: " PRIu64 " milliseconds, %d iterations\n",
+                        t1, i);
+                break;
+            }
+        }
+        i++;
     }
 
     if (ret < 0) {
commit 5b3c96388741a99988497d734edec19c4f995cd7
Author: Juan Quintela <quintela at redhat.com>
Date:   Tue May 22 00:44:24 2012 +0200

    Only calculate expected_time for stage 2
    
    ram_save_remaining() is an expensive operation when there is a lot of memory.
    So we only call the function when we need it.
    
    Signed-off-by: Juan Quintela <quintela at redhat.com>

diff --git a/arch_init.c b/arch_init.c
index f106928..3633f4c 100644
--- a/arch_init.c
+++ b/arch_init.c
@@ -314,7 +314,6 @@ int ram_save_live(QEMUFile *f, int stage, void *opaque)
     ram_addr_t addr;
     uint64_t bytes_transferred_last;
     double bwidth = 0;
-    uint64_t expected_time = 0;
     int ret;
 
     if (stage < 0) {
@@ -391,12 +390,16 @@ int ram_save_live(QEMUFile *f, int stage, void *opaque)
 
     qemu_put_be64(f, RAM_SAVE_FLAG_EOS);
 
-    expected_time = ram_save_remaining() * TARGET_PAGE_SIZE / bwidth;
+    if (stage == 2) {
+        uint64_t expected_time;
+        expected_time = ram_save_remaining() * TARGET_PAGE_SIZE / bwidth;
 
-    DPRINTF("ram_save_live: expected(" PRIu64 ") <= max(" PRIu64 ")?\n",
-            expected_time, migrate_max_downtime());
+        DPRINTF("ram_save_live: expected(" PRIu64 ") <= max(" PRIu64 ")?\n",
+                expected_time, migrate_max_downtime());
 
-    return (stage == 2) && (expected_time <= migrate_max_downtime());
+        return expected_time <= migrate_max_downtime();
+    }
+    return 0;
 }
 
 static inline void *host_from_stream_offset(QEMUFile *f,
commit d24981d37e793b0a8fcde1879db19eb11fe0f975
Author: Juan Quintela <quintela at redhat.com>
Date:   Tue May 22 00:42:40 2012 +0200

    Only TCG needs TLB handling
    
    Refactor the code that is only needed for tcg to an static function.
    Call that only when tcg is enabled.  We can't refactor to a dummy
    function in the kvm case, as qemu can be compiled at the same time
    with tcg and kvm.
    
    Signed-off-by: Juan Quintela <quintela at redhat.com>

diff --git a/exec.c b/exec.c
index 8244d54..a68b65c 100644
--- a/exec.c
+++ b/exec.c
@@ -1824,11 +1824,29 @@ void tb_flush_jmp_cache(CPUArchState *env, target_ulong addr)
             TB_JMP_PAGE_SIZE * sizeof(TranslationBlock *));
 }
 
+static void tlb_reset_dirty_range_all(ram_addr_t start, ram_addr_t end,
+                                      uintptr_t length)
+{
+    uintptr_t start1;
+
+    /* we modify the TLB cache so that the dirty bit will be set again
+       when accessing the range */
+    start1 = (uintptr_t)qemu_safe_ram_ptr(start);
+    /* Check that we don't span multiple blocks - this breaks the
+       address comparisons below.  */
+    if ((uintptr_t)qemu_safe_ram_ptr(end - 1) - start1
+            != (end - 1) - start) {
+        abort();
+    }
+    cpu_tlb_reset_dirty_all(start1, length);
+
+}
+
 /* Note: start and end must be within the same ram block.  */
 void cpu_physical_memory_reset_dirty(ram_addr_t start, ram_addr_t end,
                                      int dirty_flags)
 {
-    uintptr_t length, start1;
+    uintptr_t length;
 
     start &= TARGET_PAGE_MASK;
     end = TARGET_PAGE_ALIGN(end);
@@ -1838,16 +1856,9 @@ void cpu_physical_memory_reset_dirty(ram_addr_t start, ram_addr_t end,
         return;
     cpu_physical_memory_mask_dirty_range(start, length, dirty_flags);
 
-    /* we modify the TLB cache so that the dirty bit will be set again
-       when accessing the range */
-    start1 = (uintptr_t)qemu_safe_ram_ptr(start);
-    /* Check that we don't span multiple blocks - this breaks the
-       address comparisons below.  */
-    if ((uintptr_t)qemu_safe_ram_ptr(end - 1) - start1
-            != (end - 1) - start) {
-        abort();
+    if (tcg_enabled()) {
+        tlb_reset_dirty_range_all(start, end, length);
     }
-    cpu_tlb_reset_dirty_all(start1, length);
 }
 
 int cpu_physical_memory_set_dirty_tracking(int enable)
commit aac844ed97c39b8c0fb16d7bf9851fdedf325be3
Author: Juan Quintela <quintela at redhat.com>
Date:   Tue May 22 00:38:26 2012 +0200

    No need to iterate if we already are over the limit
    
    If buffers are full, don't iterate, just exit.
    
    Signed-off-by: Juan Quintela <quintela at redhat.com>

diff --git a/savevm.c b/savevm.c
index 987c6c0..a15c163 100644
--- a/savevm.c
+++ b/savevm.c
@@ -1626,6 +1626,9 @@ int qemu_savevm_state_iterate(QEMUFile *f)
         if (se->save_live_state == NULL)
             continue;
 
+        if (qemu_file_rate_limit(f)) {
+            return 0;
+        }
         trace_savevm_section_start();
         /* Section type */
         qemu_put_byte(f, QEMU_VM_SECTION_PART);
commit 517a13c91a975987b4c2850c08078bd3cef4dce7
Author: Juan Quintela <quintela at redhat.com>
Date:   Mon May 21 23:46:44 2012 +0200

    Add tracepoints for savevm section start/end
    
    This allows to know how long each section takes to save.
    
    An awk script like this tells us sections that takes more that 10ms
    
    $1 ~ /savevm_state_iterate_end/ {
    	/* Print savevm_section_end line when > 10ms duration */
    	if ($2 > 10000) {
    		printf("%s times_missing=%u\n", $0, times_missing++);
    	}
    }
    
    Signed-off-by: Juan Quintela <quintela at redhat.com>
    
    fix ws tracepoints
    
    Signed-off-by: Juan Quintela <quintela at redhat.com>

diff --git a/savevm.c b/savevm.c
index d1d9020..987c6c0 100644
--- a/savevm.c
+++ b/savevm.c
@@ -85,6 +85,7 @@
 #include "cpus.h"
 #include "memory.h"
 #include "qmp-commands.h"
+#include "trace.h"
 
 #define SELF_ANNOUNCE_ROUNDS 5
 
@@ -1625,11 +1626,14 @@ int qemu_savevm_state_iterate(QEMUFile *f)
         if (se->save_live_state == NULL)
             continue;
 
+        trace_savevm_section_start();
         /* Section type */
         qemu_put_byte(f, QEMU_VM_SECTION_PART);
         qemu_put_be32(f, se->section_id);
 
         ret = se->save_live_state(f, QEMU_VM_SECTION_PART, se->opaque);
+        trace_savevm_section_end(se->section_id);
+
         if (ret <= 0) {
             /* Do not proceed to the next vmstate before this one reported
                completion of the current stage. This serializes the migration
@@ -1659,11 +1663,13 @@ int qemu_savevm_state_complete(QEMUFile *f)
         if (se->save_live_state == NULL)
             continue;
 
+        trace_savevm_section_start();
         /* Section type */
         qemu_put_byte(f, QEMU_VM_SECTION_END);
         qemu_put_be32(f, se->section_id);
 
         ret = se->save_live_state(f, QEMU_VM_SECTION_END, se->opaque);
+        trace_savevm_section_end(se->section_id);
         if (ret < 0) {
             return ret;
         }
@@ -1675,6 +1681,7 @@ int qemu_savevm_state_complete(QEMUFile *f)
 	if (se->save_state == NULL && se->vmsd == NULL)
 	    continue;
 
+        trace_savevm_section_start();
         /* Section type */
         qemu_put_byte(f, QEMU_VM_SECTION_FULL);
         qemu_put_be32(f, se->section_id);
@@ -1688,6 +1695,7 @@ int qemu_savevm_state_complete(QEMUFile *f)
         qemu_put_be32(f, se->version_id);
 
         vmstate_save(f, se);
+        trace_savevm_section_end(se->section_id);
     }
 
     qemu_put_byte(f, QEMU_VM_EOF);
diff --git a/trace-events b/trace-events
index c935ba2..d671118 100644
--- a/trace-events
+++ b/trace-events
@@ -783,6 +783,11 @@ displaysurface_resize(void *display_state, void *display_surface, int width, int
 # vga.c
 ppm_save(const char *filename, void *display_surface) "%s surface=%p"
 
+# savevm.c
+
+savevm_section_start(void) ""
+savevm_section_end(unsigned int section_id) "section_id %u"
+
 # hw/qxl.c
 disable qxl_interface_set_mm_time(int qid, uint32_t mm_time) "%d %d"
 disable qxl_io_write_vga(int qid, const char *mode, uint32_t addr, uint32_t val) "%d %s addr=%u val=%u"
commit d5f8a5701d3690b5ec0c34b6a5c0b5a24d274540
Author: Juan Quintela <quintela at redhat.com>
Date:   Mon May 21 22:01:07 2012 +0200

    Add spent time for migration
    
    We add time spent for migration to the output of "info migrate"
    command.  'total_time' means time since the start fo migration if
    migration is 'active', and total time of migration if migration is
    completed.  As we are also interested in transferred ram when
    migration completes, adding all ram statistics
    
    Signed-off-by: Juan Quintela <quintela at redhat.com>

diff --git a/hmp.c b/hmp.c
index b9cec1d..4c6d4ae 100644
--- a/hmp.c
+++ b/hmp.c
@@ -145,6 +145,8 @@ void hmp_info_migrate(Monitor *mon)
                        info->ram->remaining >> 10);
         monitor_printf(mon, "total ram: %" PRIu64 " kbytes\n",
                        info->ram->total >> 10);
+        monitor_printf(mon, "total time: %" PRIu64 " milliseconds\n",
+                       info->ram->total_time);
     }
 
     if (info->has_disk) {
diff --git a/migration.c b/migration.c
index 810727f..8db1b43 100644
--- a/migration.c
+++ b/migration.c
@@ -131,6 +131,8 @@ MigrationInfo *qmp_query_migrate(Error **errp)
         info->ram->transferred = ram_bytes_transferred();
         info->ram->remaining = ram_bytes_remaining();
         info->ram->total = ram_bytes_total();
+        info->ram->total_time = qemu_get_clock_ms(rt_clock)
+            - s->total_time;
 
         if (blk_mig_active()) {
             info->has_disk = true;
@@ -143,6 +145,13 @@ MigrationInfo *qmp_query_migrate(Error **errp)
     case MIG_STATE_COMPLETED:
         info->has_status = true;
         info->status = g_strdup("completed");
+
+        info->has_ram = true;
+        info->ram = g_malloc0(sizeof(*info->ram));
+        info->ram->transferred = ram_bytes_transferred();
+        info->ram->remaining = 0;
+        info->ram->total = ram_bytes_total();
+        info->ram->total_time = s->total_time;
         break;
     case MIG_STATE_ERROR:
         info->has_status = true;
@@ -260,6 +269,7 @@ static void migrate_fd_put_ready(void *opaque)
         } else {
             migrate_fd_completed(s);
         }
+        s->total_time = qemu_get_clock_ms(rt_clock) - s->total_time;
         if (s->state != MIG_STATE_COMPLETED) {
             if (old_vm_running) {
                 vm_start();
@@ -372,6 +382,7 @@ static MigrationState *migrate_init(const MigrationParams *params)
 
     s->bandwidth_limit = bandwidth_limit;
     s->state = MIG_STATE_SETUP;
+    s->total_time = qemu_get_clock_ms(rt_clock);
 
     return s;
 }
diff --git a/migration.h b/migration.h
index 35207bd..de13004 100644
--- a/migration.h
+++ b/migration.h
@@ -37,6 +37,7 @@ struct MigrationState
     int (*write)(MigrationState *s, const void *buff, size_t size);
     void *opaque;
     MigrationParams params;
+    int64_t total_time;
 };
 
 void process_incoming_migration(QEMUFile *f);
diff --git a/qapi-schema.json b/qapi-schema.json
index 3b6e346..1ab5dbd 100644
--- a/qapi-schema.json
+++ b/qapi-schema.json
@@ -260,10 +260,15 @@
 #
 # @total: total amount of bytes involved in the migration process
 #
+# @total_time: tota0l amount of ms since migration started.  If
+#        migration has ended, it returns the total migration
+#        time. (since 1.2)
+#
 # Since: 0.14.0.
 ##
 { 'type': 'MigrationStats',
-  'data': {'transferred': 'int', 'remaining': 'int', 'total': 'int' } }
+  'data': {'transferred': 'int', 'remaining': 'int', 'total': 'int' ,
+           'total_time': 'int' } }
 
 ##
 # @MigrationInfo
@@ -275,8 +280,9 @@
 #          'cancelled'. If this field is not returned, no migration process
 #          has been initiated
 #
-# @ram: #optional @MigrationStats containing detailed migration status,
-#       only returned if status is 'active'
+# @ram: #optional @MigrationStats containing detailed migration
+#       status, only returned if status is 'active' or
+#       'completed'. 'comppleted' (since 1.2)
 #
 # @disk: #optional @MigrationStats containing detailed disk migration
 #        status, only returned if status is 'active' and it is a block
commit 8e21cd32005f6be7475349eaeadde8d4ec8cf2e4
Author: Orit Wasserman <owasserm at redhat.com>
Date:   Tue Jun 19 18:43:17 2012 +0300

    Add migration_end function
    
    Signed-off-by: Orit Wasserman <owasserm at redhat.com>

diff --git a/arch_init.c b/arch_init.c
index 78b3c0c..f106928 100644
--- a/arch_init.c
+++ b/arch_init.c
@@ -304,6 +304,11 @@ static void sort_ram_list(void)
     g_free(blocks);
 }
 
+static void migration_end(void)
+{
+    memory_global_dirty_log_stop();
+}
+
 int ram_save_live(QEMUFile *f, int stage, void *opaque)
 {
     ram_addr_t addr;
@@ -313,7 +318,7 @@ int ram_save_live(QEMUFile *f, int stage, void *opaque)
     int ret;
 
     if (stage < 0) {
-        memory_global_dirty_log_stop();
+        migration_end();
         return 0;
     }
 
commit 3a697f697b611923d04598105859103d8b27a933
Author: Orit Wasserman <owasserm at redhat.com>
Date:   Tue Jun 19 18:43:15 2012 +0300

    Add debugging infrastructure
    
    Signed-off-by: Orit Wasserman <owasserm at redhat.com>

diff --git a/arch_init.c b/arch_init.c
index cfa1af2..78b3c0c 100644
--- a/arch_init.c
+++ b/arch_init.c
@@ -44,6 +44,14 @@
 #include "exec-memory.h"
 #include "hw/pcspk.h"
 
+#ifdef DEBUG_ARCH_INIT
+#define DPRINTF(fmt, ...) \
+    do { fprintf(stdout, "arch_init: " fmt, ## __VA_ARGS__); } while (0)
+#else
+#define DPRINTF(fmt, ...) \
+    do { } while (0)
+#endif
+
 #ifdef TARGET_SPARC
 int graphic_width = 1024;
 int graphic_height = 768;
@@ -380,6 +388,9 @@ int ram_save_live(QEMUFile *f, int stage, void *opaque)
 
     expected_time = ram_save_remaining() * TARGET_PAGE_SIZE / bwidth;
 
+    DPRINTF("ram_save_live: expected(" PRIu64 ") <= max(" PRIu64 ")?\n",
+            expected_time, migrate_max_downtime());
+
     return (stage == 2) && (expected_time <= migrate_max_downtime());
 }
 
@@ -416,8 +427,11 @@ static inline void *host_from_stream_offset(QEMUFile *f,
 int ram_load(QEMUFile *f, void *opaque, int version_id)
 {
     ram_addr_t addr;
-    int flags;
+    int flags, ret = 0;
     int error;
+    static uint64_t seq_iter;
+
+    seq_iter++;
 
     if (version_id < 4 || version_id > 4) {
         return -EINVAL;
@@ -447,8 +461,10 @@ int ram_load(QEMUFile *f, void *opaque, int version_id)
 
                     QLIST_FOREACH(block, &ram_list.blocks, next) {
                         if (!strncmp(id, block->idstr, sizeof(id))) {
-                            if (block->length != length)
-                                return -EINVAL;
+                            if (block->length != length) {
+                                ret =  -EINVAL;
+                                goto done;
+                            }
                             break;
                         }
                     }
@@ -456,7 +472,8 @@ int ram_load(QEMUFile *f, void *opaque, int version_id)
                     if (!block) {
                         fprintf(stderr, "Unknown ramblock \"%s\", cannot "
                                 "accept migration\n", id);
-                        return -EINVAL;
+                        ret = -EINVAL;
+                        goto done;
                     }
 
                     total_ram_bytes -= length;
@@ -493,11 +510,15 @@ int ram_load(QEMUFile *f, void *opaque, int version_id)
         }
         error = qemu_file_get_error(f);
         if (error) {
-            return error;
+            ret = error;
+            goto done;
         }
     } while (!(flags & RAM_SAVE_FLAG_EOS));
 
-    return 0;
+done:
+    DPRINTF("Completed load of VM with exit code %d seq iteration " PRIu64 "\n",
+            ret, seq_iter);
+    return ret;
 }
 
 #ifdef HAS_AUDIO
commit 0c51f43d7a82fedca550f9dc149edff2952b8fe1
Author: Orit Wasserman <owasserm at redhat.com>
Date:   Tue Jun 19 18:43:14 2012 +0300

    Add save_block_hdr function
    
    Signed-off-by: Benoit Hudzia <benoit.hudzia at sap.com>
    Signed-off-by: Petter Svard <petters at cs.umu.se>
    Signed-off-by: Aidan Shribman <aidan.shribman at sap.com>
    Signed-off-by: Orit Wasserman <owasserm at redhat.com>

diff --git a/arch_init.c b/arch_init.c
index 81c2e54..cfa1af2 100644
--- a/arch_init.c
+++ b/arch_init.c
@@ -161,6 +161,18 @@ static int is_dup_page(uint8_t *page)
     return 1;
 }
 
+static void save_block_hdr(QEMUFile *f, RAMBlock *block, ram_addr_t offset,
+        int cont, int flag)
+{
+        qemu_put_be64(f, offset | cont | flag);
+        if (!cont) {
+                qemu_put_byte(f, strlen(block->idstr));
+                qemu_put_buffer(f, (uint8_t *)block->idstr,
+                                strlen(block->idstr));
+        }
+
+}
+
 static RAMBlock *last_block;
 static ram_addr_t last_offset;
 
@@ -187,21 +199,11 @@ static int ram_save_block(QEMUFile *f)
             p = memory_region_get_ram_ptr(mr) + offset;
 
             if (is_dup_page(p)) {
-                qemu_put_be64(f, offset | cont | RAM_SAVE_FLAG_COMPRESS);
-                if (!cont) {
-                    qemu_put_byte(f, strlen(block->idstr));
-                    qemu_put_buffer(f, (uint8_t *)block->idstr,
-                                    strlen(block->idstr));
-                }
+                save_block_hdr(f, block, offset, cont, RAM_SAVE_FLAG_COMPRESS);
                 qemu_put_byte(f, *p);
                 bytes_sent = 1;
             } else {
-                qemu_put_be64(f, offset | cont | RAM_SAVE_FLAG_PAGE);
-                if (!cont) {
-                    qemu_put_byte(f, strlen(block->idstr));
-                    qemu_put_buffer(f, (uint8_t *)block->idstr,
-                                    strlen(block->idstr));
-                }
+                save_block_hdr(f, block, offset, cont, RAM_SAVE_FLAG_PAGE);
                 qemu_put_buffer(f, p, TARGET_PAGE_SIZE);
                 bytes_sent = TARGET_PAGE_SIZE;
             }
commit 6607ae235bbc8c8c23159c21f545e7622489a236
Author: Isaku Yamahata <yamahata at valinux.co.jp>
Date:   Tue Jun 19 18:43:09 2012 +0300

    Add MigrationParams structure
    
    Signed-off-by: Isaku Yamahata <yamahata at valinux.co.jp>

diff --git a/block-migration.c b/block-migration.c
index fd2ffff..b95b4e1 100644
--- a/block-migration.c
+++ b/block-migration.c
@@ -700,13 +700,13 @@ static int block_load(QEMUFile *f, void *opaque, int version_id)
     return 0;
 }
 
-static void block_set_params(int blk_enable, int shared_base, void *opaque)
+static void block_set_params(const MigrationParams *params, void *opaque)
 {
-    block_mig_state.blk_enable = blk_enable;
-    block_mig_state.shared_base = shared_base;
+    block_mig_state.blk_enable = params->blk;
+    block_mig_state.shared_base = params->shared;
 
     /* shared base means that blk_enable = 1 */
-    block_mig_state.blk_enable |= shared_base;
+    block_mig_state.blk_enable |= params->shared;
 }
 
 void blk_mig_init(void)
diff --git a/migration.c b/migration.c
index 3f485d3..810727f 100644
--- a/migration.c
+++ b/migration.c
@@ -352,7 +352,7 @@ void migrate_fd_connect(MigrationState *s)
                                       migrate_fd_close);
 
     DPRINTF("beginning savevm\n");
-    ret = qemu_savevm_state_begin(s->file, s->blk, s->shared);
+    ret = qemu_savevm_state_begin(s->file, &s->params);
     if (ret < 0) {
         DPRINTF("failed, %d\n", ret);
         migrate_fd_error(s);
@@ -361,15 +361,14 @@ void migrate_fd_connect(MigrationState *s)
     migrate_fd_put_ready(s);
 }
 
-static MigrationState *migrate_init(int blk, int inc)
+static MigrationState *migrate_init(const MigrationParams *params)
 {
     MigrationState *s = migrate_get_current();
     int64_t bandwidth_limit = s->bandwidth_limit;
 
     memset(s, 0, sizeof(*s));
     s->bandwidth_limit = bandwidth_limit;
-    s->blk = blk;
-    s->shared = inc;
+    s->params = *params;
 
     s->bandwidth_limit = bandwidth_limit;
     s->state = MIG_STATE_SETUP;
@@ -394,9 +393,13 @@ void qmp_migrate(const char *uri, bool has_blk, bool blk,
                  Error **errp)
 {
     MigrationState *s = migrate_get_current();
+    MigrationParams params;
     const char *p;
     int ret;
 
+    params.blk = blk;
+    params.shared = inc;
+
     if (s->state == MIG_STATE_ACTIVE) {
         error_set(errp, QERR_MIGRATION_ACTIVE);
         return;
@@ -411,7 +414,7 @@ void qmp_migrate(const char *uri, bool has_blk, bool blk,
         return;
     }
 
-    s = migrate_init(blk, inc);
+    s = migrate_init(&params);
 
     if (strstart(uri, "tcp:", &p)) {
         ret = tcp_start_outgoing_migration(s, p, errp);
diff --git a/migration.h b/migration.h
index 2e9ca2e..35207bd 100644
--- a/migration.h
+++ b/migration.h
@@ -19,6 +19,11 @@
 #include "notify.h"
 #include "error.h"
 
+struct MigrationParams {
+    bool blk;
+    bool shared;
+};
+
 typedef struct MigrationState MigrationState;
 
 struct MigrationState
@@ -31,8 +36,7 @@ struct MigrationState
     int (*close)(MigrationState *s);
     int (*write)(MigrationState *s, const void *buff, size_t size);
     void *opaque;
-    int blk;
-    int shared;
+    MigrationParams params;
 };
 
 void process_incoming_migration(QEMUFile *f);
diff --git a/qemu-common.h b/qemu-common.h
index 9d9e603..c8c6b2a 100644
--- a/qemu-common.h
+++ b/qemu-common.h
@@ -17,6 +17,7 @@ typedef struct DeviceState DeviceState;
 
 struct Monitor;
 typedef struct Monitor Monitor;
+typedef struct MigrationParams MigrationParams;
 
 /* we put basic includes here to avoid repeating them in device drivers */
 #include <stdlib.h>
diff --git a/savevm.c b/savevm.c
index faa8145..d1d9020 100644
--- a/savevm.c
+++ b/savevm.c
@@ -1561,7 +1561,8 @@ bool qemu_savevm_state_blocked(Error **errp)
     return false;
 }
 
-int qemu_savevm_state_begin(QEMUFile *f, int blk_enable, int shared)
+int qemu_savevm_state_begin(QEMUFile *f,
+                            const MigrationParams *params)
 {
     SaveStateEntry *se;
     int ret;
@@ -1569,8 +1570,8 @@ int qemu_savevm_state_begin(QEMUFile *f, int blk_enable, int shared)
     QTAILQ_FOREACH(se, &savevm_handlers, entry) {
         if(se->set_params == NULL) {
             continue;
-	}
-	se->set_params(blk_enable, shared, se->opaque);
+        }
+        se->set_params(params, se->opaque);
     }
     
     qemu_put_be32(f, QEMU_VM_FILE_MAGIC);
@@ -1708,13 +1709,17 @@ void qemu_savevm_state_cancel(QEMUFile *f)
 static int qemu_savevm_state(QEMUFile *f)
 {
     int ret;
+    MigrationParams params = {
+        .blk = 0,
+        .shared = 0
+    };
 
     if (qemu_savevm_state_blocked(NULL)) {
         ret = -EINVAL;
         goto out;
     }
 
-    ret = qemu_savevm_state_begin(f, 0, 0);
+    ret = qemu_savevm_state_begin(f, &params);
     if (ret < 0)
         goto out;
 
diff --git a/sysemu.h b/sysemu.h
index bc2c788..6540c79 100644
--- a/sysemu.h
+++ b/sysemu.h
@@ -77,7 +77,8 @@ void do_info_snapshots(Monitor *mon);
 void qemu_announce_self(void);
 
 bool qemu_savevm_state_blocked(Error **errp);
-int qemu_savevm_state_begin(QEMUFile *f, int blk_enable, int shared);
+int qemu_savevm_state_begin(QEMUFile *f,
+                            const MigrationParams *params);
 int qemu_savevm_state_iterate(QEMUFile *f);
 int qemu_savevm_state_complete(QEMUFile *f);
 void qemu_savevm_state_cancel(QEMUFile *f);
diff --git a/vmstate.h b/vmstate.h
index 82d97ae..5af45e0 100644
--- a/vmstate.h
+++ b/vmstate.h
@@ -26,7 +26,7 @@
 #ifndef QEMU_VMSTATE_H
 #define QEMU_VMSTATE_H 1
 
-typedef void SaveSetParamsHandler(int blk_enable, int shared, void * opaque);
+typedef void SaveSetParamsHandler(const MigrationParams *params, void * opaque);
 typedef void SaveStateHandler(QEMUFile *f, void *opaque);
 typedef int SaveLiveStateHandler(QEMUFile *f, int stage, void *opaque);
 typedef int LoadStateHandler(QEMUFile *f, void *opaque, int version_id);
commit 0ff1f9f585712684dc46cb6cb6a46a8cc160b2ae
Author: Orit Wasserman <owasserm at redhat.com>
Date:   Tue Jun 19 11:51:37 2012 +0300

    Add missing check for host_from_stream_offset return value for RAM_SAVE_FLAG_PAGE
    
    Signed-off-by: Orit Wasserman <owasserm at redhat.com>

diff --git a/arch_init.c b/arch_init.c
index a9e8b74..81c2e54 100644
--- a/arch_init.c
+++ b/arch_init.c
@@ -483,6 +483,9 @@ int ram_load(QEMUFile *f, void *opaque, int version_id)
             void *host;
 
             host = host_from_stream_offset(f, addr, flags);
+            if (!host) {
+                return -EINVAL;
+            }
 
             qemu_get_buffer(f, host, TARGET_PAGE_SIZE);
         }
commit 71ea2e016131a9fcde6f1ffd3e0e34a64c21f593
Author: Blue Swirl <blauwirbel at gmail.com>
Date:   Sun Jun 24 20:15:05 2012 +0000

    bsd-user: fix build
    
    Link in oslib objects also for BSD user, but avoid using the version of
    qemu_vmalloc() defined in oslib-posix.c.
    
    Signed-off-by: Blue Swirl <blauwirbel at gmail.com>

diff --git a/Makefile.target b/Makefile.target
index 127d573..74f7a4a 100644
--- a/Makefile.target
+++ b/Makefile.target
@@ -108,7 +108,7 @@ ifdef CONFIG_BSD_USER
 QEMU_CFLAGS+=-I$(SRC_PATH)/bsd-user -I$(SRC_PATH)/bsd-user/$(TARGET_ARCH)
 
 obj-y += bsd-user/
-obj-y += gdbstub.o user-exec.o
+obj-y += gdbstub.o user-exec.o $(oslib-obj-y)
 
 endif #CONFIG_BSD_USER
 
diff --git a/oslib-posix.c b/oslib-posix.c
index b6a3c7f..6b7ba64 100644
--- a/oslib-posix.c
+++ b/oslib-posix.c
@@ -105,6 +105,8 @@ void *qemu_memalign(size_t alignment, size_t size)
     return ptr;
 }
 
+/* conflicts with qemu_vmalloc in bsd-user/mmap.c */
+#if !defined(CONFIG_BSD_USER)
 /* alloc shared memory pages */
 void *qemu_vmalloc(size_t size)
 {
@@ -127,6 +129,7 @@ void *qemu_vmalloc(size_t size)
     trace_qemu_vmalloc(size, ptr);
     return ptr;
 }
+#endif
 
 void qemu_vfree(void *ptr)
 {
commit 9cc85c281bb034bb9343b6d6803e3d01d0861514
Author: Blue Swirl <blauwirbel at gmail.com>
Date:   Thu Jun 21 19:19:15 2012 +0000

    x86: rename op_helper.c to seg_helper.c
    
    Rename what is remaining of op_helper.c to seg_helper.c.
    
    Signed-off-by: Blue Swirl <blauwirbel at gmail.com>

diff --git a/target-i386/Makefile.objs b/target-i386/Makefile.objs
index 9a921c4..683fd59 100644
--- a/target-i386/Makefile.objs
+++ b/target-i386/Makefile.objs
@@ -1,12 +1,11 @@
-obj-y += translate.o op_helper.o helper.o cpu.o
+obj-y += translate.o helper.o cpu.o
 obj-y += excp_helper.o fpu_helper.o cc_helper.o int_helper.o svm_helper.o
-obj-y += smm_helper.o misc_helper.o mem_helper.o
+obj-y += smm_helper.o misc_helper.o mem_helper.o seg_helper.o
 obj-$(CONFIG_SOFTMMU) += machine.o arch_memory_mapping.o arch_dump.o
 obj-$(CONFIG_KVM) += kvm.o hyperv.o
 obj-$(CONFIG_LINUX_USER) += ioport-user.o
 obj-$(CONFIG_BSD_USER) += ioport-user.o
 
-$(obj)/op_helper.o: QEMU_CFLAGS += $(HELPER_CFLAGS)
 $(obj)/fpu_helper.o: QEMU_CFLAGS += $(HELPER_CFLAGS)
 $(obj)/cc_helper.o: QEMU_CFLAGS += $(HELPER_CFLAGS)
 $(obj)/int_helper.o: QEMU_CFLAGS += $(HELPER_CFLAGS)
@@ -14,3 +13,4 @@ $(obj)/svm_helper.o: QEMU_CFLAGS += $(HELPER_CFLAGS)
 $(obj)/smm_helper.o: QEMU_CFLAGS += $(HELPER_CFLAGS)
 $(obj)/misc_helper.o: QEMU_CFLAGS += $(HELPER_CFLAGS)
 $(obj)/mem_helper.o: QEMU_CFLAGS += $(HELPER_CFLAGS)
+$(obj)/seg_helper.o: QEMU_CFLAGS += $(HELPER_CFLAGS)
diff --git a/target-i386/op_helper.c b/target-i386/op_helper.c
deleted file mode 100644
index a4b8b64..0000000
--- a/target-i386/op_helper.c
+++ /dev/null
@@ -1,2475 +0,0 @@
-/*
- *  x86 segmentation related helpers:
- *  TSS, interrupts, system calls, jumps and call/task gates, descriptors
- *
- *  Copyright (c) 2003 Fabrice Bellard
- *
- * This library is free software; you can redistribute it and/or
- * modify it under the terms of the GNU Lesser General Public
- * License as published by the Free Software Foundation; either
- * version 2 of the License, or (at your option) any later version.
- *
- * This library is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
- * Lesser General Public License for more details.
- *
- * You should have received a copy of the GNU Lesser General Public
- * License along with this library; if not, see <http://www.gnu.org/licenses/>.
- */
-
-#include "cpu.h"
-#include "dyngen-exec.h"
-#include "qemu-log.h"
-#include "helper.h"
-
-#if !defined(CONFIG_USER_ONLY)
-#include "softmmu_exec.h"
-#endif /* !defined(CONFIG_USER_ONLY) */
-
-//#define DEBUG_PCALL
-
-#ifdef DEBUG_PCALL
-# define LOG_PCALL(...) qemu_log_mask(CPU_LOG_PCALL, ## __VA_ARGS__)
-# define LOG_PCALL_STATE(env)                                  \
-    log_cpu_state_mask(CPU_LOG_PCALL, (env), X86_DUMP_CCOP)
-#else
-# define LOG_PCALL(...) do { } while (0)
-# define LOG_PCALL_STATE(env) do { } while (0)
-#endif
-
-/* return non zero if error */
-static inline int load_segment(uint32_t *e1_ptr, uint32_t *e2_ptr,
-                               int selector)
-{
-    SegmentCache *dt;
-    int index;
-    target_ulong ptr;
-
-    if (selector & 0x4) {
-        dt = &env->ldt;
-    } else {
-        dt = &env->gdt;
-    }
-    index = selector & ~7;
-    if ((index + 7) > dt->limit) {
-        return -1;
-    }
-    ptr = dt->base + index;
-    *e1_ptr = ldl_kernel(ptr);
-    *e2_ptr = ldl_kernel(ptr + 4);
-    return 0;
-}
-
-static inline unsigned int get_seg_limit(uint32_t e1, uint32_t e2)
-{
-    unsigned int limit;
-
-    limit = (e1 & 0xffff) | (e2 & 0x000f0000);
-    if (e2 & DESC_G_MASK) {
-        limit = (limit << 12) | 0xfff;
-    }
-    return limit;
-}
-
-static inline uint32_t get_seg_base(uint32_t e1, uint32_t e2)
-{
-    return (e1 >> 16) | ((e2 & 0xff) << 16) | (e2 & 0xff000000);
-}
-
-static inline void load_seg_cache_raw_dt(SegmentCache *sc, uint32_t e1,
-                                         uint32_t e2)
-{
-    sc->base = get_seg_base(e1, e2);
-    sc->limit = get_seg_limit(e1, e2);
-    sc->flags = e2;
-}
-
-/* init the segment cache in vm86 mode. */
-static inline void load_seg_vm(int seg, int selector)
-{
-    selector &= 0xffff;
-    cpu_x86_load_seg_cache(env, seg, selector,
-                           (selector << 4), 0xffff, 0);
-}
-
-static inline void get_ss_esp_from_tss(uint32_t *ss_ptr,
-                                       uint32_t *esp_ptr, int dpl)
-{
-    int type, index, shift;
-
-#if 0
-    {
-        int i;
-        printf("TR: base=%p limit=%x\n", env->tr.base, env->tr.limit);
-        for (i = 0; i < env->tr.limit; i++) {
-            printf("%02x ", env->tr.base[i]);
-            if ((i & 7) == 7) {
-                printf("\n");
-            }
-        }
-        printf("\n");
-    }
-#endif
-
-    if (!(env->tr.flags & DESC_P_MASK)) {
-        cpu_abort(env, "invalid tss");
-    }
-    type = (env->tr.flags >> DESC_TYPE_SHIFT) & 0xf;
-    if ((type & 7) != 1) {
-        cpu_abort(env, "invalid tss type");
-    }
-    shift = type >> 3;
-    index = (dpl * 4 + 2) << shift;
-    if (index + (4 << shift) - 1 > env->tr.limit) {
-        raise_exception_err(env, EXCP0A_TSS, env->tr.selector & 0xfffc);
-    }
-    if (shift == 0) {
-        *esp_ptr = lduw_kernel(env->tr.base + index);
-        *ss_ptr = lduw_kernel(env->tr.base + index + 2);
-    } else {
-        *esp_ptr = ldl_kernel(env->tr.base + index);
-        *ss_ptr = lduw_kernel(env->tr.base + index + 4);
-    }
-}
-
-/* XXX: merge with load_seg() */
-static void tss_load_seg(int seg_reg, int selector)
-{
-    uint32_t e1, e2;
-    int rpl, dpl, cpl;
-
-    if ((selector & 0xfffc) != 0) {
-        if (load_segment(&e1, &e2, selector) != 0) {
-            raise_exception_err(env, EXCP0A_TSS, selector & 0xfffc);
-        }
-        if (!(e2 & DESC_S_MASK)) {
-            raise_exception_err(env, EXCP0A_TSS, selector & 0xfffc);
-        }
-        rpl = selector & 3;
-        dpl = (e2 >> DESC_DPL_SHIFT) & 3;
-        cpl = env->hflags & HF_CPL_MASK;
-        if (seg_reg == R_CS) {
-            if (!(e2 & DESC_CS_MASK)) {
-                raise_exception_err(env, EXCP0A_TSS, selector & 0xfffc);
-            }
-            /* XXX: is it correct? */
-            if (dpl != rpl) {
-                raise_exception_err(env, EXCP0A_TSS, selector & 0xfffc);
-            }
-            if ((e2 & DESC_C_MASK) && dpl > rpl) {
-                raise_exception_err(env, EXCP0A_TSS, selector & 0xfffc);
-            }
-        } else if (seg_reg == R_SS) {
-            /* SS must be writable data */
-            if ((e2 & DESC_CS_MASK) || !(e2 & DESC_W_MASK)) {
-                raise_exception_err(env, EXCP0A_TSS, selector & 0xfffc);
-            }
-            if (dpl != cpl || dpl != rpl) {
-                raise_exception_err(env, EXCP0A_TSS, selector & 0xfffc);
-            }
-        } else {
-            /* not readable code */
-            if ((e2 & DESC_CS_MASK) && !(e2 & DESC_R_MASK)) {
-                raise_exception_err(env, EXCP0A_TSS, selector & 0xfffc);
-            }
-            /* if data or non conforming code, checks the rights */
-            if (((e2 >> DESC_TYPE_SHIFT) & 0xf) < 12) {
-                if (dpl < cpl || dpl < rpl) {
-                    raise_exception_err(env, EXCP0A_TSS, selector & 0xfffc);
-                }
-            }
-        }
-        if (!(e2 & DESC_P_MASK)) {
-            raise_exception_err(env, EXCP0B_NOSEG, selector & 0xfffc);
-        }
-        cpu_x86_load_seg_cache(env, seg_reg, selector,
-                               get_seg_base(e1, e2),
-                               get_seg_limit(e1, e2),
-                               e2);
-    } else {
-        if (seg_reg == R_SS || seg_reg == R_CS) {
-            raise_exception_err(env, EXCP0A_TSS, selector & 0xfffc);
-        }
-    }
-}
-
-#define SWITCH_TSS_JMP  0
-#define SWITCH_TSS_IRET 1
-#define SWITCH_TSS_CALL 2
-
-/* XXX: restore CPU state in registers (PowerPC case) */
-static void switch_tss(int tss_selector,
-                       uint32_t e1, uint32_t e2, int source,
-                       uint32_t next_eip)
-{
-    int tss_limit, tss_limit_max, type, old_tss_limit_max, old_type, v1, v2, i;
-    target_ulong tss_base;
-    uint32_t new_regs[8], new_segs[6];
-    uint32_t new_eflags, new_eip, new_cr3, new_ldt, new_trap;
-    uint32_t old_eflags, eflags_mask;
-    SegmentCache *dt;
-    int index;
-    target_ulong ptr;
-
-    type = (e2 >> DESC_TYPE_SHIFT) & 0xf;
-    LOG_PCALL("switch_tss: sel=0x%04x type=%d src=%d\n", tss_selector, type,
-              source);
-
-    /* if task gate, we read the TSS segment and we load it */
-    if (type == 5) {
-        if (!(e2 & DESC_P_MASK)) {
-            raise_exception_err(env, EXCP0B_NOSEG, tss_selector & 0xfffc);
-        }
-        tss_selector = e1 >> 16;
-        if (tss_selector & 4) {
-            raise_exception_err(env, EXCP0A_TSS, tss_selector & 0xfffc);
-        }
-        if (load_segment(&e1, &e2, tss_selector) != 0) {
-            raise_exception_err(env, EXCP0D_GPF, tss_selector & 0xfffc);
-        }
-        if (e2 & DESC_S_MASK) {
-            raise_exception_err(env, EXCP0D_GPF, tss_selector & 0xfffc);
-        }
-        type = (e2 >> DESC_TYPE_SHIFT) & 0xf;
-        if ((type & 7) != 1) {
-            raise_exception_err(env, EXCP0D_GPF, tss_selector & 0xfffc);
-        }
-    }
-
-    if (!(e2 & DESC_P_MASK)) {
-        raise_exception_err(env, EXCP0B_NOSEG, tss_selector & 0xfffc);
-    }
-
-    if (type & 8) {
-        tss_limit_max = 103;
-    } else {
-        tss_limit_max = 43;
-    }
-    tss_limit = get_seg_limit(e1, e2);
-    tss_base = get_seg_base(e1, e2);
-    if ((tss_selector & 4) != 0 ||
-        tss_limit < tss_limit_max) {
-        raise_exception_err(env, EXCP0A_TSS, tss_selector & 0xfffc);
-    }
-    old_type = (env->tr.flags >> DESC_TYPE_SHIFT) & 0xf;
-    if (old_type & 8) {
-        old_tss_limit_max = 103;
-    } else {
-        old_tss_limit_max = 43;
-    }
-
-    /* read all the registers from the new TSS */
-    if (type & 8) {
-        /* 32 bit */
-        new_cr3 = ldl_kernel(tss_base + 0x1c);
-        new_eip = ldl_kernel(tss_base + 0x20);
-        new_eflags = ldl_kernel(tss_base + 0x24);
-        for (i = 0; i < 8; i++) {
-            new_regs[i] = ldl_kernel(tss_base + (0x28 + i * 4));
-        }
-        for (i = 0; i < 6; i++) {
-            new_segs[i] = lduw_kernel(tss_base + (0x48 + i * 4));
-        }
-        new_ldt = lduw_kernel(tss_base + 0x60);
-        new_trap = ldl_kernel(tss_base + 0x64);
-    } else {
-        /* 16 bit */
-        new_cr3 = 0;
-        new_eip = lduw_kernel(tss_base + 0x0e);
-        new_eflags = lduw_kernel(tss_base + 0x10);
-        for (i = 0; i < 8; i++) {
-            new_regs[i] = lduw_kernel(tss_base + (0x12 + i * 2)) | 0xffff0000;
-        }
-        for (i = 0; i < 4; i++) {
-            new_segs[i] = lduw_kernel(tss_base + (0x22 + i * 4));
-        }
-        new_ldt = lduw_kernel(tss_base + 0x2a);
-        new_segs[R_FS] = 0;
-        new_segs[R_GS] = 0;
-        new_trap = 0;
-    }
-    /* XXX: avoid a compiler warning, see
-     http://support.amd.com/us/Processor_TechDocs/24593.pdf
-     chapters 12.2.5 and 13.2.4 on how to implement TSS Trap bit */
-    (void)new_trap;
-
-    /* NOTE: we must avoid memory exceptions during the task switch,
-       so we make dummy accesses before */
-    /* XXX: it can still fail in some cases, so a bigger hack is
-       necessary to valid the TLB after having done the accesses */
-
-    v1 = ldub_kernel(env->tr.base);
-    v2 = ldub_kernel(env->tr.base + old_tss_limit_max);
-    stb_kernel(env->tr.base, v1);
-    stb_kernel(env->tr.base + old_tss_limit_max, v2);
-
-    /* clear busy bit (it is restartable) */
-    if (source == SWITCH_TSS_JMP || source == SWITCH_TSS_IRET) {
-        target_ulong ptr;
-        uint32_t e2;
-
-        ptr = env->gdt.base + (env->tr.selector & ~7);
-        e2 = ldl_kernel(ptr + 4);
-        e2 &= ~DESC_TSS_BUSY_MASK;
-        stl_kernel(ptr + 4, e2);
-    }
-    old_eflags = cpu_compute_eflags(env);
-    if (source == SWITCH_TSS_IRET) {
-        old_eflags &= ~NT_MASK;
-    }
-
-    /* save the current state in the old TSS */
-    if (type & 8) {
-        /* 32 bit */
-        stl_kernel(env->tr.base + 0x20, next_eip);
-        stl_kernel(env->tr.base + 0x24, old_eflags);
-        stl_kernel(env->tr.base + (0x28 + 0 * 4), EAX);
-        stl_kernel(env->tr.base + (0x28 + 1 * 4), ECX);
-        stl_kernel(env->tr.base + (0x28 + 2 * 4), EDX);
-        stl_kernel(env->tr.base + (0x28 + 3 * 4), EBX);
-        stl_kernel(env->tr.base + (0x28 + 4 * 4), ESP);
-        stl_kernel(env->tr.base + (0x28 + 5 * 4), EBP);
-        stl_kernel(env->tr.base + (0x28 + 6 * 4), ESI);
-        stl_kernel(env->tr.base + (0x28 + 7 * 4), EDI);
-        for (i = 0; i < 6; i++) {
-            stw_kernel(env->tr.base + (0x48 + i * 4), env->segs[i].selector);
-        }
-    } else {
-        /* 16 bit */
-        stw_kernel(env->tr.base + 0x0e, next_eip);
-        stw_kernel(env->tr.base + 0x10, old_eflags);
-        stw_kernel(env->tr.base + (0x12 + 0 * 2), EAX);
-        stw_kernel(env->tr.base + (0x12 + 1 * 2), ECX);
-        stw_kernel(env->tr.base + (0x12 + 2 * 2), EDX);
-        stw_kernel(env->tr.base + (0x12 + 3 * 2), EBX);
-        stw_kernel(env->tr.base + (0x12 + 4 * 2), ESP);
-        stw_kernel(env->tr.base + (0x12 + 5 * 2), EBP);
-        stw_kernel(env->tr.base + (0x12 + 6 * 2), ESI);
-        stw_kernel(env->tr.base + (0x12 + 7 * 2), EDI);
-        for (i = 0; i < 4; i++) {
-            stw_kernel(env->tr.base + (0x22 + i * 4), env->segs[i].selector);
-        }
-    }
-
-    /* now if an exception occurs, it will occurs in the next task
-       context */
-
-    if (source == SWITCH_TSS_CALL) {
-        stw_kernel(tss_base, env->tr.selector);
-        new_eflags |= NT_MASK;
-    }
-
-    /* set busy bit */
-    if (source == SWITCH_TSS_JMP || source == SWITCH_TSS_CALL) {
-        target_ulong ptr;
-        uint32_t e2;
-
-        ptr = env->gdt.base + (tss_selector & ~7);
-        e2 = ldl_kernel(ptr + 4);
-        e2 |= DESC_TSS_BUSY_MASK;
-        stl_kernel(ptr + 4, e2);
-    }
-
-    /* set the new CPU state */
-    /* from this point, any exception which occurs can give problems */
-    env->cr[0] |= CR0_TS_MASK;
-    env->hflags |= HF_TS_MASK;
-    env->tr.selector = tss_selector;
-    env->tr.base = tss_base;
-    env->tr.limit = tss_limit;
-    env->tr.flags = e2 & ~DESC_TSS_BUSY_MASK;
-
-    if ((type & 8) && (env->cr[0] & CR0_PG_MASK)) {
-        cpu_x86_update_cr3(env, new_cr3);
-    }
-
-    /* load all registers without an exception, then reload them with
-       possible exception */
-    env->eip = new_eip;
-    eflags_mask = TF_MASK | AC_MASK | ID_MASK |
-        IF_MASK | IOPL_MASK | VM_MASK | RF_MASK | NT_MASK;
-    if (!(type & 8)) {
-        eflags_mask &= 0xffff;
-    }
-    cpu_load_eflags(env, new_eflags, eflags_mask);
-    /* XXX: what to do in 16 bit case? */
-    EAX = new_regs[0];
-    ECX = new_regs[1];
-    EDX = new_regs[2];
-    EBX = new_regs[3];
-    ESP = new_regs[4];
-    EBP = new_regs[5];
-    ESI = new_regs[6];
-    EDI = new_regs[7];
-    if (new_eflags & VM_MASK) {
-        for (i = 0; i < 6; i++) {
-            load_seg_vm(i, new_segs[i]);
-        }
-        /* in vm86, CPL is always 3 */
-        cpu_x86_set_cpl(env, 3);
-    } else {
-        /* CPL is set the RPL of CS */
-        cpu_x86_set_cpl(env, new_segs[R_CS] & 3);
-        /* first just selectors as the rest may trigger exceptions */
-        for (i = 0; i < 6; i++) {
-            cpu_x86_load_seg_cache(env, i, new_segs[i], 0, 0, 0);
-        }
-    }
-
-    env->ldt.selector = new_ldt & ~4;
-    env->ldt.base = 0;
-    env->ldt.limit = 0;
-    env->ldt.flags = 0;
-
-    /* load the LDT */
-    if (new_ldt & 4) {
-        raise_exception_err(env, EXCP0A_TSS, new_ldt & 0xfffc);
-    }
-
-    if ((new_ldt & 0xfffc) != 0) {
-        dt = &env->gdt;
-        index = new_ldt & ~7;
-        if ((index + 7) > dt->limit) {
-            raise_exception_err(env, EXCP0A_TSS, new_ldt & 0xfffc);
-        }
-        ptr = dt->base + index;
-        e1 = ldl_kernel(ptr);
-        e2 = ldl_kernel(ptr + 4);
-        if ((e2 & DESC_S_MASK) || ((e2 >> DESC_TYPE_SHIFT) & 0xf) != 2) {
-            raise_exception_err(env, EXCP0A_TSS, new_ldt & 0xfffc);
-        }
-        if (!(e2 & DESC_P_MASK)) {
-            raise_exception_err(env, EXCP0A_TSS, new_ldt & 0xfffc);
-        }
-        load_seg_cache_raw_dt(&env->ldt, e1, e2);
-    }
-
-    /* load the segments */
-    if (!(new_eflags & VM_MASK)) {
-        tss_load_seg(R_CS, new_segs[R_CS]);
-        tss_load_seg(R_SS, new_segs[R_SS]);
-        tss_load_seg(R_ES, new_segs[R_ES]);
-        tss_load_seg(R_DS, new_segs[R_DS]);
-        tss_load_seg(R_FS, new_segs[R_FS]);
-        tss_load_seg(R_GS, new_segs[R_GS]);
-    }
-
-    /* check that EIP is in the CS segment limits */
-    if (new_eip > env->segs[R_CS].limit) {
-        /* XXX: different exception if CALL? */
-        raise_exception_err(env, EXCP0D_GPF, 0);
-    }
-
-#ifndef CONFIG_USER_ONLY
-    /* reset local breakpoints */
-    if (env->dr[7] & 0x55) {
-        for (i = 0; i < 4; i++) {
-            if (hw_breakpoint_enabled(env->dr[7], i) == 0x1) {
-                hw_breakpoint_remove(env, i);
-            }
-        }
-        env->dr[7] &= ~0x55;
-    }
-#endif
-}
-
-static inline unsigned int get_sp_mask(unsigned int e2)
-{
-    if (e2 & DESC_B_MASK) {
-        return 0xffffffff;
-    } else {
-        return 0xffff;
-    }
-}
-
-static int exception_has_error_code(int intno)
-{
-    switch (intno) {
-    case 8:
-    case 10:
-    case 11:
-    case 12:
-    case 13:
-    case 14:
-    case 17:
-        return 1;
-    }
-    return 0;
-}
-
-#ifdef TARGET_X86_64
-#define SET_ESP(val, sp_mask)                           \
-    do {                                                \
-        if ((sp_mask) == 0xffff) {                      \
-            ESP = (ESP & ~0xffff) | ((val) & 0xffff);   \
-        } else if ((sp_mask) == 0xffffffffLL) {         \
-            ESP = (uint32_t)(val);                      \
-        } else {                                        \
-            ESP = (val);                                \
-        }                                               \
-    } while (0)
-#else
-#define SET_ESP(val, sp_mask)                           \
-    do {                                                \
-        ESP = (ESP & ~(sp_mask)) | ((val) & (sp_mask)); \
-    } while (0)
-#endif
-
-/* in 64-bit machines, this can overflow. So this segment addition macro
- * can be used to trim the value to 32-bit whenever needed */
-#define SEG_ADDL(ssp, sp, sp_mask) ((uint32_t)((ssp) + (sp & (sp_mask))))
-
-/* XXX: add a is_user flag to have proper security support */
-#define PUSHW(ssp, sp, sp_mask, val)                    \
-    {                                                   \
-        sp -= 2;                                        \
-        stw_kernel((ssp) + (sp & (sp_mask)), (val));    \
-    }
-
-#define PUSHL(ssp, sp, sp_mask, val)                                    \
-    {                                                                   \
-        sp -= 4;                                                        \
-        stl_kernel(SEG_ADDL(ssp, sp, sp_mask), (uint32_t)(val));        \
-    }
-
-#define POPW(ssp, sp, sp_mask, val)                     \
-    {                                                   \
-        val = lduw_kernel((ssp) + (sp & (sp_mask)));    \
-        sp += 2;                                        \
-    }
-
-#define POPL(ssp, sp, sp_mask, val)                             \
-    {                                                           \
-        val = (uint32_t)ldl_kernel(SEG_ADDL(ssp, sp, sp_mask)); \
-        sp += 4;                                                \
-    }
-
-/* protected mode interrupt */
-static void do_interrupt_protected(int intno, int is_int, int error_code,
-                                   unsigned int next_eip, int is_hw)
-{
-    SegmentCache *dt;
-    target_ulong ptr, ssp;
-    int type, dpl, selector, ss_dpl, cpl;
-    int has_error_code, new_stack, shift;
-    uint32_t e1, e2, offset, ss = 0, esp, ss_e1 = 0, ss_e2 = 0;
-    uint32_t old_eip, sp_mask;
-
-    has_error_code = 0;
-    if (!is_int && !is_hw) {
-        has_error_code = exception_has_error_code(intno);
-    }
-    if (is_int) {
-        old_eip = next_eip;
-    } else {
-        old_eip = env->eip;
-    }
-
-    dt = &env->idt;
-    if (intno * 8 + 7 > dt->limit) {
-        raise_exception_err(env, EXCP0D_GPF, intno * 8 + 2);
-    }
-    ptr = dt->base + intno * 8;
-    e1 = ldl_kernel(ptr);
-    e2 = ldl_kernel(ptr + 4);
-    /* check gate type */
-    type = (e2 >> DESC_TYPE_SHIFT) & 0x1f;
-    switch (type) {
-    case 5: /* task gate */
-        /* must do that check here to return the correct error code */
-        if (!(e2 & DESC_P_MASK)) {
-            raise_exception_err(env, EXCP0B_NOSEG, intno * 8 + 2);
-        }
-        switch_tss(intno * 8, e1, e2, SWITCH_TSS_CALL, old_eip);
-        if (has_error_code) {
-            int type;
-            uint32_t mask;
-
-            /* push the error code */
-            type = (env->tr.flags >> DESC_TYPE_SHIFT) & 0xf;
-            shift = type >> 3;
-            if (env->segs[R_SS].flags & DESC_B_MASK) {
-                mask = 0xffffffff;
-            } else {
-                mask = 0xffff;
-            }
-            esp = (ESP - (2 << shift)) & mask;
-            ssp = env->segs[R_SS].base + esp;
-            if (shift) {
-                stl_kernel(ssp, error_code);
-            } else {
-                stw_kernel(ssp, error_code);
-            }
-            SET_ESP(esp, mask);
-        }
-        return;
-    case 6: /* 286 interrupt gate */
-    case 7: /* 286 trap gate */
-    case 14: /* 386 interrupt gate */
-    case 15: /* 386 trap gate */
-        break;
-    default:
-        raise_exception_err(env, EXCP0D_GPF, intno * 8 + 2);
-        break;
-    }
-    dpl = (e2 >> DESC_DPL_SHIFT) & 3;
-    cpl = env->hflags & HF_CPL_MASK;
-    /* check privilege if software int */
-    if (is_int && dpl < cpl) {
-        raise_exception_err(env, EXCP0D_GPF, intno * 8 + 2);
-    }
-    /* check valid bit */
-    if (!(e2 & DESC_P_MASK)) {
-        raise_exception_err(env, EXCP0B_NOSEG, intno * 8 + 2);
-    }
-    selector = e1 >> 16;
-    offset = (e2 & 0xffff0000) | (e1 & 0x0000ffff);
-    if ((selector & 0xfffc) == 0) {
-        raise_exception_err(env, EXCP0D_GPF, 0);
-    }
-    if (load_segment(&e1, &e2, selector) != 0) {
-        raise_exception_err(env, EXCP0D_GPF, selector & 0xfffc);
-    }
-    if (!(e2 & DESC_S_MASK) || !(e2 & (DESC_CS_MASK))) {
-        raise_exception_err(env, EXCP0D_GPF, selector & 0xfffc);
-    }
-    dpl = (e2 >> DESC_DPL_SHIFT) & 3;
-    if (dpl > cpl) {
-        raise_exception_err(env, EXCP0D_GPF, selector & 0xfffc);
-    }
-    if (!(e2 & DESC_P_MASK)) {
-        raise_exception_err(env, EXCP0B_NOSEG, selector & 0xfffc);
-    }
-    if (!(e2 & DESC_C_MASK) && dpl < cpl) {
-        /* to inner privilege */
-        get_ss_esp_from_tss(&ss, &esp, dpl);
-        if ((ss & 0xfffc) == 0) {
-            raise_exception_err(env, EXCP0A_TSS, ss & 0xfffc);
-        }
-        if ((ss & 3) != dpl) {
-            raise_exception_err(env, EXCP0A_TSS, ss & 0xfffc);
-        }
-        if (load_segment(&ss_e1, &ss_e2, ss) != 0) {
-            raise_exception_err(env, EXCP0A_TSS, ss & 0xfffc);
-        }
-        ss_dpl = (ss_e2 >> DESC_DPL_SHIFT) & 3;
-        if (ss_dpl != dpl) {
-            raise_exception_err(env, EXCP0A_TSS, ss & 0xfffc);
-        }
-        if (!(ss_e2 & DESC_S_MASK) ||
-            (ss_e2 & DESC_CS_MASK) ||
-            !(ss_e2 & DESC_W_MASK)) {
-            raise_exception_err(env, EXCP0A_TSS, ss & 0xfffc);
-        }
-        if (!(ss_e2 & DESC_P_MASK)) {
-            raise_exception_err(env, EXCP0A_TSS, ss & 0xfffc);
-        }
-        new_stack = 1;
-        sp_mask = get_sp_mask(ss_e2);
-        ssp = get_seg_base(ss_e1, ss_e2);
-    } else if ((e2 & DESC_C_MASK) || dpl == cpl) {
-        /* to same privilege */
-        if (env->eflags & VM_MASK) {
-            raise_exception_err(env, EXCP0D_GPF, selector & 0xfffc);
-        }
-        new_stack = 0;
-        sp_mask = get_sp_mask(env->segs[R_SS].flags);
-        ssp = env->segs[R_SS].base;
-        esp = ESP;
-        dpl = cpl;
-    } else {
-        raise_exception_err(env, EXCP0D_GPF, selector & 0xfffc);
-        new_stack = 0; /* avoid warning */
-        sp_mask = 0; /* avoid warning */
-        ssp = 0; /* avoid warning */
-        esp = 0; /* avoid warning */
-    }
-
-    shift = type >> 3;
-
-#if 0
-    /* XXX: check that enough room is available */
-    push_size = 6 + (new_stack << 2) + (has_error_code << 1);
-    if (env->eflags & VM_MASK) {
-        push_size += 8;
-    }
-    push_size <<= shift;
-#endif
-    if (shift == 1) {
-        if (new_stack) {
-            if (env->eflags & VM_MASK) {
-                PUSHL(ssp, esp, sp_mask, env->segs[R_GS].selector);
-                PUSHL(ssp, esp, sp_mask, env->segs[R_FS].selector);
-                PUSHL(ssp, esp, sp_mask, env->segs[R_DS].selector);
-                PUSHL(ssp, esp, sp_mask, env->segs[R_ES].selector);
-            }
-            PUSHL(ssp, esp, sp_mask, env->segs[R_SS].selector);
-            PUSHL(ssp, esp, sp_mask, ESP);
-        }
-        PUSHL(ssp, esp, sp_mask, cpu_compute_eflags(env));
-        PUSHL(ssp, esp, sp_mask, env->segs[R_CS].selector);
-        PUSHL(ssp, esp, sp_mask, old_eip);
-        if (has_error_code) {
-            PUSHL(ssp, esp, sp_mask, error_code);
-        }
-    } else {
-        if (new_stack) {
-            if (env->eflags & VM_MASK) {
-                PUSHW(ssp, esp, sp_mask, env->segs[R_GS].selector);
-                PUSHW(ssp, esp, sp_mask, env->segs[R_FS].selector);
-                PUSHW(ssp, esp, sp_mask, env->segs[R_DS].selector);
-                PUSHW(ssp, esp, sp_mask, env->segs[R_ES].selector);
-            }
-            PUSHW(ssp, esp, sp_mask, env->segs[R_SS].selector);
-            PUSHW(ssp, esp, sp_mask, ESP);
-        }
-        PUSHW(ssp, esp, sp_mask, cpu_compute_eflags(env));
-        PUSHW(ssp, esp, sp_mask, env->segs[R_CS].selector);
-        PUSHW(ssp, esp, sp_mask, old_eip);
-        if (has_error_code) {
-            PUSHW(ssp, esp, sp_mask, error_code);
-        }
-    }
-
-    if (new_stack) {
-        if (env->eflags & VM_MASK) {
-            cpu_x86_load_seg_cache(env, R_ES, 0, 0, 0, 0);
-            cpu_x86_load_seg_cache(env, R_DS, 0, 0, 0, 0);
-            cpu_x86_load_seg_cache(env, R_FS, 0, 0, 0, 0);
-            cpu_x86_load_seg_cache(env, R_GS, 0, 0, 0, 0);
-        }
-        ss = (ss & ~3) | dpl;
-        cpu_x86_load_seg_cache(env, R_SS, ss,
-                               ssp, get_seg_limit(ss_e1, ss_e2), ss_e2);
-    }
-    SET_ESP(esp, sp_mask);
-
-    selector = (selector & ~3) | dpl;
-    cpu_x86_load_seg_cache(env, R_CS, selector,
-                   get_seg_base(e1, e2),
-                   get_seg_limit(e1, e2),
-                   e2);
-    cpu_x86_set_cpl(env, dpl);
-    env->eip = offset;
-
-    /* interrupt gate clear IF mask */
-    if ((type & 1) == 0) {
-        env->eflags &= ~IF_MASK;
-    }
-    env->eflags &= ~(TF_MASK | VM_MASK | RF_MASK | NT_MASK);
-}
-
-#ifdef TARGET_X86_64
-
-#define PUSHQ(sp, val)                          \
-    {                                           \
-        sp -= 8;                                \
-        stq_kernel(sp, (val));                  \
-    }
-
-#define POPQ(sp, val)                           \
-    {                                           \
-        val = ldq_kernel(sp);                   \
-        sp += 8;                                \
-    }
-
-static inline target_ulong get_rsp_from_tss(int level)
-{
-    int index;
-
-#if 0
-    printf("TR: base=" TARGET_FMT_lx " limit=%x\n",
-           env->tr.base, env->tr.limit);
-#endif
-
-    if (!(env->tr.flags & DESC_P_MASK)) {
-        cpu_abort(env, "invalid tss");
-    }
-    index = 8 * level + 4;
-    if ((index + 7) > env->tr.limit) {
-        raise_exception_err(env, EXCP0A_TSS, env->tr.selector & 0xfffc);
-    }
-    return ldq_kernel(env->tr.base + index);
-}
-
-/* 64 bit interrupt */
-static void do_interrupt64(int intno, int is_int, int error_code,
-                           target_ulong next_eip, int is_hw)
-{
-    SegmentCache *dt;
-    target_ulong ptr;
-    int type, dpl, selector, cpl, ist;
-    int has_error_code, new_stack;
-    uint32_t e1, e2, e3, ss;
-    target_ulong old_eip, esp, offset;
-
-    has_error_code = 0;
-    if (!is_int && !is_hw) {
-        has_error_code = exception_has_error_code(intno);
-    }
-    if (is_int) {
-        old_eip = next_eip;
-    } else {
-        old_eip = env->eip;
-    }
-
-    dt = &env->idt;
-    if (intno * 16 + 15 > dt->limit) {
-        raise_exception_err(env, EXCP0D_GPF, intno * 16 + 2);
-    }
-    ptr = dt->base + intno * 16;
-    e1 = ldl_kernel(ptr);
-    e2 = ldl_kernel(ptr + 4);
-    e3 = ldl_kernel(ptr + 8);
-    /* check gate type */
-    type = (e2 >> DESC_TYPE_SHIFT) & 0x1f;
-    switch (type) {
-    case 14: /* 386 interrupt gate */
-    case 15: /* 386 trap gate */
-        break;
-    default:
-        raise_exception_err(env, EXCP0D_GPF, intno * 16 + 2);
-        break;
-    }
-    dpl = (e2 >> DESC_DPL_SHIFT) & 3;
-    cpl = env->hflags & HF_CPL_MASK;
-    /* check privilege if software int */
-    if (is_int && dpl < cpl) {
-        raise_exception_err(env, EXCP0D_GPF, intno * 16 + 2);
-    }
-    /* check valid bit */
-    if (!(e2 & DESC_P_MASK)) {
-        raise_exception_err(env, EXCP0B_NOSEG, intno * 16 + 2);
-    }
-    selector = e1 >> 16;
-    offset = ((target_ulong)e3 << 32) | (e2 & 0xffff0000) | (e1 & 0x0000ffff);
-    ist = e2 & 7;
-    if ((selector & 0xfffc) == 0) {
-        raise_exception_err(env, EXCP0D_GPF, 0);
-    }
-
-    if (load_segment(&e1, &e2, selector) != 0) {
-        raise_exception_err(env, EXCP0D_GPF, selector & 0xfffc);
-    }
-    if (!(e2 & DESC_S_MASK) || !(e2 & (DESC_CS_MASK))) {
-        raise_exception_err(env, EXCP0D_GPF, selector & 0xfffc);
-    }
-    dpl = (e2 >> DESC_DPL_SHIFT) & 3;
-    if (dpl > cpl) {
-        raise_exception_err(env, EXCP0D_GPF, selector & 0xfffc);
-    }
-    if (!(e2 & DESC_P_MASK)) {
-        raise_exception_err(env, EXCP0B_NOSEG, selector & 0xfffc);
-    }
-    if (!(e2 & DESC_L_MASK) || (e2 & DESC_B_MASK)) {
-        raise_exception_err(env, EXCP0D_GPF, selector & 0xfffc);
-    }
-    if ((!(e2 & DESC_C_MASK) && dpl < cpl) || ist != 0) {
-        /* to inner privilege */
-        if (ist != 0) {
-            esp = get_rsp_from_tss(ist + 3);
-        } else {
-            esp = get_rsp_from_tss(dpl);
-        }
-        esp &= ~0xfLL; /* align stack */
-        ss = 0;
-        new_stack = 1;
-    } else if ((e2 & DESC_C_MASK) || dpl == cpl) {
-        /* to same privilege */
-        if (env->eflags & VM_MASK) {
-            raise_exception_err(env, EXCP0D_GPF, selector & 0xfffc);
-        }
-        new_stack = 0;
-        if (ist != 0) {
-            esp = get_rsp_from_tss(ist + 3);
-        } else {
-            esp = ESP;
-        }
-        esp &= ~0xfLL; /* align stack */
-        dpl = cpl;
-    } else {
-        raise_exception_err(env, EXCP0D_GPF, selector & 0xfffc);
-        new_stack = 0; /* avoid warning */
-        esp = 0; /* avoid warning */
-    }
-
-    PUSHQ(esp, env->segs[R_SS].selector);
-    PUSHQ(esp, ESP);
-    PUSHQ(esp, cpu_compute_eflags(env));
-    PUSHQ(esp, env->segs[R_CS].selector);
-    PUSHQ(esp, old_eip);
-    if (has_error_code) {
-        PUSHQ(esp, error_code);
-    }
-
-    if (new_stack) {
-        ss = 0 | dpl;
-        cpu_x86_load_seg_cache(env, R_SS, ss, 0, 0, 0);
-    }
-    ESP = esp;
-
-    selector = (selector & ~3) | dpl;
-    cpu_x86_load_seg_cache(env, R_CS, selector,
-                   get_seg_base(e1, e2),
-                   get_seg_limit(e1, e2),
-                   e2);
-    cpu_x86_set_cpl(env, dpl);
-    env->eip = offset;
-
-    /* interrupt gate clear IF mask */
-    if ((type & 1) == 0) {
-        env->eflags &= ~IF_MASK;
-    }
-    env->eflags &= ~(TF_MASK | VM_MASK | RF_MASK | NT_MASK);
-}
-#endif
-
-#ifdef TARGET_X86_64
-#if defined(CONFIG_USER_ONLY)
-void helper_syscall(int next_eip_addend)
-{
-    env->exception_index = EXCP_SYSCALL;
-    env->exception_next_eip = env->eip + next_eip_addend;
-    cpu_loop_exit(env);
-}
-#else
-void helper_syscall(int next_eip_addend)
-{
-    int selector;
-
-    if (!(env->efer & MSR_EFER_SCE)) {
-        raise_exception_err(env, EXCP06_ILLOP, 0);
-    }
-    selector = (env->star >> 32) & 0xffff;
-    if (env->hflags & HF_LMA_MASK) {
-        int code64;
-
-        ECX = env->eip + next_eip_addend;
-        env->regs[11] = cpu_compute_eflags(env);
-
-        code64 = env->hflags & HF_CS64_MASK;
-
-        cpu_x86_set_cpl(env, 0);
-        cpu_x86_load_seg_cache(env, R_CS, selector & 0xfffc,
-                           0, 0xffffffff,
-                               DESC_G_MASK | DESC_P_MASK |
-                               DESC_S_MASK |
-                               DESC_CS_MASK | DESC_R_MASK | DESC_A_MASK |
-                               DESC_L_MASK);
-        cpu_x86_load_seg_cache(env, R_SS, (selector + 8) & 0xfffc,
-                               0, 0xffffffff,
-                               DESC_G_MASK | DESC_B_MASK | DESC_P_MASK |
-                               DESC_S_MASK |
-                               DESC_W_MASK | DESC_A_MASK);
-        env->eflags &= ~env->fmask;
-        cpu_load_eflags(env, env->eflags, 0);
-        if (code64) {
-            env->eip = env->lstar;
-        } else {
-            env->eip = env->cstar;
-        }
-    } else {
-        ECX = (uint32_t)(env->eip + next_eip_addend);
-
-        cpu_x86_set_cpl(env, 0);
-        cpu_x86_load_seg_cache(env, R_CS, selector & 0xfffc,
-                           0, 0xffffffff,
-                               DESC_G_MASK | DESC_B_MASK | DESC_P_MASK |
-                               DESC_S_MASK |
-                               DESC_CS_MASK | DESC_R_MASK | DESC_A_MASK);
-        cpu_x86_load_seg_cache(env, R_SS, (selector + 8) & 0xfffc,
-                               0, 0xffffffff,
-                               DESC_G_MASK | DESC_B_MASK | DESC_P_MASK |
-                               DESC_S_MASK |
-                               DESC_W_MASK | DESC_A_MASK);
-        env->eflags &= ~(IF_MASK | RF_MASK | VM_MASK);
-        env->eip = (uint32_t)env->star;
-    }
-}
-#endif
-#endif
-
-#ifdef TARGET_X86_64
-void helper_sysret(int dflag)
-{
-    int cpl, selector;
-
-    if (!(env->efer & MSR_EFER_SCE)) {
-        raise_exception_err(env, EXCP06_ILLOP, 0);
-    }
-    cpl = env->hflags & HF_CPL_MASK;
-    if (!(env->cr[0] & CR0_PE_MASK) || cpl != 0) {
-        raise_exception_err(env, EXCP0D_GPF, 0);
-    }
-    selector = (env->star >> 48) & 0xffff;
-    if (env->hflags & HF_LMA_MASK) {
-        if (dflag == 2) {
-            cpu_x86_load_seg_cache(env, R_CS, (selector + 16) | 3,
-                                   0, 0xffffffff,
-                                   DESC_G_MASK | DESC_P_MASK |
-                                   DESC_S_MASK | (3 << DESC_DPL_SHIFT) |
-                                   DESC_CS_MASK | DESC_R_MASK | DESC_A_MASK |
-                                   DESC_L_MASK);
-            env->eip = ECX;
-        } else {
-            cpu_x86_load_seg_cache(env, R_CS, selector | 3,
-                                   0, 0xffffffff,
-                                   DESC_G_MASK | DESC_B_MASK | DESC_P_MASK |
-                                   DESC_S_MASK | (3 << DESC_DPL_SHIFT) |
-                                   DESC_CS_MASK | DESC_R_MASK | DESC_A_MASK);
-            env->eip = (uint32_t)ECX;
-        }
-        cpu_x86_load_seg_cache(env, R_SS, selector + 8,
-                               0, 0xffffffff,
-                               DESC_G_MASK | DESC_B_MASK | DESC_P_MASK |
-                               DESC_S_MASK | (3 << DESC_DPL_SHIFT) |
-                               DESC_W_MASK | DESC_A_MASK);
-        cpu_load_eflags(env, (uint32_t)(env->regs[11]), TF_MASK | AC_MASK
-                        | ID_MASK | IF_MASK | IOPL_MASK | VM_MASK | RF_MASK |
-                        NT_MASK);
-        cpu_x86_set_cpl(env, 3);
-    } else {
-        cpu_x86_load_seg_cache(env, R_CS, selector | 3,
-                               0, 0xffffffff,
-                               DESC_G_MASK | DESC_B_MASK | DESC_P_MASK |
-                               DESC_S_MASK | (3 << DESC_DPL_SHIFT) |
-                               DESC_CS_MASK | DESC_R_MASK | DESC_A_MASK);
-        env->eip = (uint32_t)ECX;
-        cpu_x86_load_seg_cache(env, R_SS, selector + 8,
-                               0, 0xffffffff,
-                               DESC_G_MASK | DESC_B_MASK | DESC_P_MASK |
-                               DESC_S_MASK | (3 << DESC_DPL_SHIFT) |
-                               DESC_W_MASK | DESC_A_MASK);
-        env->eflags |= IF_MASK;
-        cpu_x86_set_cpl(env, 3);
-    }
-}
-#endif
-
-/* real mode interrupt */
-static void do_interrupt_real(int intno, int is_int, int error_code,
-                              unsigned int next_eip)
-{
-    SegmentCache *dt;
-    target_ulong ptr, ssp;
-    int selector;
-    uint32_t offset, esp;
-    uint32_t old_cs, old_eip;
-
-    /* real mode (simpler!) */
-    dt = &env->idt;
-    if (intno * 4 + 3 > dt->limit) {
-        raise_exception_err(env, EXCP0D_GPF, intno * 8 + 2);
-    }
-    ptr = dt->base + intno * 4;
-    offset = lduw_kernel(ptr);
-    selector = lduw_kernel(ptr + 2);
-    esp = ESP;
-    ssp = env->segs[R_SS].base;
-    if (is_int) {
-        old_eip = next_eip;
-    } else {
-        old_eip = env->eip;
-    }
-    old_cs = env->segs[R_CS].selector;
-    /* XXX: use SS segment size? */
-    PUSHW(ssp, esp, 0xffff, cpu_compute_eflags(env));
-    PUSHW(ssp, esp, 0xffff, old_cs);
-    PUSHW(ssp, esp, 0xffff, old_eip);
-
-    /* update processor state */
-    ESP = (ESP & ~0xffff) | (esp & 0xffff);
-    env->eip = offset;
-    env->segs[R_CS].selector = selector;
-    env->segs[R_CS].base = (selector << 4);
-    env->eflags &= ~(IF_MASK | TF_MASK | AC_MASK | RF_MASK);
-}
-
-#if defined(CONFIG_USER_ONLY)
-/* fake user mode interrupt */
-static void do_interrupt_user(int intno, int is_int, int error_code,
-                              target_ulong next_eip)
-{
-    SegmentCache *dt;
-    target_ulong ptr;
-    int dpl, cpl, shift;
-    uint32_t e2;
-
-    dt = &env->idt;
-    if (env->hflags & HF_LMA_MASK) {
-        shift = 4;
-    } else {
-        shift = 3;
-    }
-    ptr = dt->base + (intno << shift);
-    e2 = ldl_kernel(ptr + 4);
-
-    dpl = (e2 >> DESC_DPL_SHIFT) & 3;
-    cpl = env->hflags & HF_CPL_MASK;
-    /* check privilege if software int */
-    if (is_int && dpl < cpl) {
-        raise_exception_err(env, EXCP0D_GPF, (intno << shift) + 2);
-    }
-
-    /* Since we emulate only user space, we cannot do more than
-       exiting the emulation with the suitable exception and error
-       code */
-    if (is_int) {
-        EIP = next_eip;
-    }
-}
-
-#else
-
-static void handle_even_inj(int intno, int is_int, int error_code,
-                            int is_hw, int rm)
-{
-    uint32_t event_inj = ldl_phys(env->vm_vmcb + offsetof(struct vmcb,
-                                                          control.event_inj));
-
-    if (!(event_inj & SVM_EVTINJ_VALID)) {
-        int type;
-
-        if (is_int) {
-            type = SVM_EVTINJ_TYPE_SOFT;
-        } else {
-            type = SVM_EVTINJ_TYPE_EXEPT;
-        }
-        event_inj = intno | type | SVM_EVTINJ_VALID;
-        if (!rm && exception_has_error_code(intno)) {
-            event_inj |= SVM_EVTINJ_VALID_ERR;
-            stl_phys(env->vm_vmcb + offsetof(struct vmcb,
-                                             control.event_inj_err),
-                     error_code);
-        }
-        stl_phys(env->vm_vmcb + offsetof(struct vmcb, control.event_inj),
-                 event_inj);
-    }
-}
-#endif
-
-/*
- * Begin execution of an interruption. is_int is TRUE if coming from
- * the int instruction. next_eip is the EIP value AFTER the interrupt
- * instruction. It is only relevant if is_int is TRUE.
- */
-static void do_interrupt_all(int intno, int is_int, int error_code,
-                             target_ulong next_eip, int is_hw)
-{
-    if (qemu_loglevel_mask(CPU_LOG_INT)) {
-        if ((env->cr[0] & CR0_PE_MASK)) {
-            static int count;
-
-            qemu_log("%6d: v=%02x e=%04x i=%d cpl=%d IP=%04x:" TARGET_FMT_lx
-                     " pc=" TARGET_FMT_lx " SP=%04x:" TARGET_FMT_lx,
-                     count, intno, error_code, is_int,
-                     env->hflags & HF_CPL_MASK,
-                     env->segs[R_CS].selector, EIP,
-                     (int)env->segs[R_CS].base + EIP,
-                     env->segs[R_SS].selector, ESP);
-            if (intno == 0x0e) {
-                qemu_log(" CR2=" TARGET_FMT_lx, env->cr[2]);
-            } else {
-                qemu_log(" EAX=" TARGET_FMT_lx, EAX);
-            }
-            qemu_log("\n");
-            log_cpu_state(env, X86_DUMP_CCOP);
-#if 0
-            {
-                int i;
-                target_ulong ptr;
-
-                qemu_log("       code=");
-                ptr = env->segs[R_CS].base + env->eip;
-                for (i = 0; i < 16; i++) {
-                    qemu_log(" %02x", ldub(ptr + i));
-                }
-                qemu_log("\n");
-            }
-#endif
-            count++;
-        }
-    }
-    if (env->cr[0] & CR0_PE_MASK) {
-#if !defined(CONFIG_USER_ONLY)
-        if (env->hflags & HF_SVMI_MASK) {
-            handle_even_inj(intno, is_int, error_code, is_hw, 0);
-        }
-#endif
-#ifdef TARGET_X86_64
-        if (env->hflags & HF_LMA_MASK) {
-            do_interrupt64(intno, is_int, error_code, next_eip, is_hw);
-        } else
-#endif
-        {
-            do_interrupt_protected(intno, is_int, error_code, next_eip, is_hw);
-        }
-    } else {
-#if !defined(CONFIG_USER_ONLY)
-        if (env->hflags & HF_SVMI_MASK) {
-            handle_even_inj(intno, is_int, error_code, is_hw, 1);
-        }
-#endif
-        do_interrupt_real(intno, is_int, error_code, next_eip);
-    }
-
-#if !defined(CONFIG_USER_ONLY)
-    if (env->hflags & HF_SVMI_MASK) {
-        uint32_t event_inj = ldl_phys(env->vm_vmcb +
-                                      offsetof(struct vmcb,
-                                               control.event_inj));
-
-        stl_phys(env->vm_vmcb + offsetof(struct vmcb, control.event_inj),
-                 event_inj & ~SVM_EVTINJ_VALID);
-    }
-#endif
-}
-
-void do_interrupt(CPUX86State *env1)
-{
-    CPUX86State *saved_env;
-
-    saved_env = env;
-    env = env1;
-#if defined(CONFIG_USER_ONLY)
-    /* if user mode only, we simulate a fake exception
-       which will be handled outside the cpu execution
-       loop */
-    do_interrupt_user(env->exception_index,
-                      env->exception_is_int,
-                      env->error_code,
-                      env->exception_next_eip);
-    /* successfully delivered */
-    env->old_exception = -1;
-#else
-    /* simulate a real cpu exception. On i386, it can
-       trigger new exceptions, but we do not handle
-       double or triple faults yet. */
-    do_interrupt_all(env->exception_index,
-                     env->exception_is_int,
-                     env->error_code,
-                     env->exception_next_eip, 0);
-    /* successfully delivered */
-    env->old_exception = -1;
-#endif
-    env = saved_env;
-}
-
-void do_interrupt_x86_hardirq(CPUX86State *env1, int intno, int is_hw)
-{
-    CPUX86State *saved_env;
-
-    saved_env = env;
-    env = env1;
-    do_interrupt_all(intno, 0, 0, 0, is_hw);
-    env = saved_env;
-}
-
-void helper_enter_level(int level, int data32, target_ulong t1)
-{
-    target_ulong ssp;
-    uint32_t esp_mask, esp, ebp;
-
-    esp_mask = get_sp_mask(env->segs[R_SS].flags);
-    ssp = env->segs[R_SS].base;
-    ebp = EBP;
-    esp = ESP;
-    if (data32) {
-        /* 32 bit */
-        esp -= 4;
-        while (--level) {
-            esp -= 4;
-            ebp -= 4;
-            stl(ssp + (esp & esp_mask), ldl(ssp + (ebp & esp_mask)));
-        }
-        esp -= 4;
-        stl(ssp + (esp & esp_mask), t1);
-    } else {
-        /* 16 bit */
-        esp -= 2;
-        while (--level) {
-            esp -= 2;
-            ebp -= 2;
-            stw(ssp + (esp & esp_mask), lduw(ssp + (ebp & esp_mask)));
-        }
-        esp -= 2;
-        stw(ssp + (esp & esp_mask), t1);
-    }
-}
-
-#ifdef TARGET_X86_64
-void helper_enter64_level(int level, int data64, target_ulong t1)
-{
-    target_ulong esp, ebp;
-
-    ebp = EBP;
-    esp = ESP;
-
-    if (data64) {
-        /* 64 bit */
-        esp -= 8;
-        while (--level) {
-            esp -= 8;
-            ebp -= 8;
-            stq(esp, ldq(ebp));
-        }
-        esp -= 8;
-        stq(esp, t1);
-    } else {
-        /* 16 bit */
-        esp -= 2;
-        while (--level) {
-            esp -= 2;
-            ebp -= 2;
-            stw(esp, lduw(ebp));
-        }
-        esp -= 2;
-        stw(esp, t1);
-    }
-}
-#endif
-
-void helper_lldt(int selector)
-{
-    SegmentCache *dt;
-    uint32_t e1, e2;
-    int index, entry_limit;
-    target_ulong ptr;
-
-    selector &= 0xffff;
-    if ((selector & 0xfffc) == 0) {
-        /* XXX: NULL selector case: invalid LDT */
-        env->ldt.base = 0;
-        env->ldt.limit = 0;
-    } else {
-        if (selector & 0x4) {
-            raise_exception_err(env, EXCP0D_GPF, selector & 0xfffc);
-        }
-        dt = &env->gdt;
-        index = selector & ~7;
-#ifdef TARGET_X86_64
-        if (env->hflags & HF_LMA_MASK) {
-            entry_limit = 15;
-        } else
-#endif
-        {
-            entry_limit = 7;
-        }
-        if ((index + entry_limit) > dt->limit) {
-            raise_exception_err(env, EXCP0D_GPF, selector & 0xfffc);
-        }
-        ptr = dt->base + index;
-        e1 = ldl_kernel(ptr);
-        e2 = ldl_kernel(ptr + 4);
-        if ((e2 & DESC_S_MASK) || ((e2 >> DESC_TYPE_SHIFT) & 0xf) != 2) {
-            raise_exception_err(env, EXCP0D_GPF, selector & 0xfffc);
-        }
-        if (!(e2 & DESC_P_MASK)) {
-            raise_exception_err(env, EXCP0B_NOSEG, selector & 0xfffc);
-        }
-#ifdef TARGET_X86_64
-        if (env->hflags & HF_LMA_MASK) {
-            uint32_t e3;
-
-            e3 = ldl_kernel(ptr + 8);
-            load_seg_cache_raw_dt(&env->ldt, e1, e2);
-            env->ldt.base |= (target_ulong)e3 << 32;
-        } else
-#endif
-        {
-            load_seg_cache_raw_dt(&env->ldt, e1, e2);
-        }
-    }
-    env->ldt.selector = selector;
-}
-
-void helper_ltr(int selector)
-{
-    SegmentCache *dt;
-    uint32_t e1, e2;
-    int index, type, entry_limit;
-    target_ulong ptr;
-
-    selector &= 0xffff;
-    if ((selector & 0xfffc) == 0) {
-        /* NULL selector case: invalid TR */
-        env->tr.base = 0;
-        env->tr.limit = 0;
-        env->tr.flags = 0;
-    } else {
-        if (selector & 0x4) {
-            raise_exception_err(env, EXCP0D_GPF, selector & 0xfffc);
-        }
-        dt = &env->gdt;
-        index = selector & ~7;
-#ifdef TARGET_X86_64
-        if (env->hflags & HF_LMA_MASK) {
-            entry_limit = 15;
-        } else
-#endif
-        {
-            entry_limit = 7;
-        }
-        if ((index + entry_limit) > dt->limit) {
-            raise_exception_err(env, EXCP0D_GPF, selector & 0xfffc);
-        }
-        ptr = dt->base + index;
-        e1 = ldl_kernel(ptr);
-        e2 = ldl_kernel(ptr + 4);
-        type = (e2 >> DESC_TYPE_SHIFT) & 0xf;
-        if ((e2 & DESC_S_MASK) ||
-            (type != 1 && type != 9)) {
-            raise_exception_err(env, EXCP0D_GPF, selector & 0xfffc);
-        }
-        if (!(e2 & DESC_P_MASK)) {
-            raise_exception_err(env, EXCP0B_NOSEG, selector & 0xfffc);
-        }
-#ifdef TARGET_X86_64
-        if (env->hflags & HF_LMA_MASK) {
-            uint32_t e3, e4;
-
-            e3 = ldl_kernel(ptr + 8);
-            e4 = ldl_kernel(ptr + 12);
-            if ((e4 >> DESC_TYPE_SHIFT) & 0xf) {
-                raise_exception_err(env, EXCP0D_GPF, selector & 0xfffc);
-            }
-            load_seg_cache_raw_dt(&env->tr, e1, e2);
-            env->tr.base |= (target_ulong)e3 << 32;
-        } else
-#endif
-        {
-            load_seg_cache_raw_dt(&env->tr, e1, e2);
-        }
-        e2 |= DESC_TSS_BUSY_MASK;
-        stl_kernel(ptr + 4, e2);
-    }
-    env->tr.selector = selector;
-}
-
-/* only works if protected mode and not VM86. seg_reg must be != R_CS */
-void helper_load_seg(int seg_reg, int selector)
-{
-    uint32_t e1, e2;
-    int cpl, dpl, rpl;
-    SegmentCache *dt;
-    int index;
-    target_ulong ptr;
-
-    selector &= 0xffff;
-    cpl = env->hflags & HF_CPL_MASK;
-    if ((selector & 0xfffc) == 0) {
-        /* null selector case */
-        if (seg_reg == R_SS
-#ifdef TARGET_X86_64
-            && (!(env->hflags & HF_CS64_MASK) || cpl == 3)
-#endif
-            ) {
-            raise_exception_err(env, EXCP0D_GPF, 0);
-        }
-        cpu_x86_load_seg_cache(env, seg_reg, selector, 0, 0, 0);
-    } else {
-
-        if (selector & 0x4) {
-            dt = &env->ldt;
-        } else {
-            dt = &env->gdt;
-        }
-        index = selector & ~7;
-        if ((index + 7) > dt->limit) {
-            raise_exception_err(env, EXCP0D_GPF, selector & 0xfffc);
-        }
-        ptr = dt->base + index;
-        e1 = ldl_kernel(ptr);
-        e2 = ldl_kernel(ptr + 4);
-
-        if (!(e2 & DESC_S_MASK)) {
-            raise_exception_err(env, EXCP0D_GPF, selector & 0xfffc);
-        }
-        rpl = selector & 3;
-        dpl = (e2 >> DESC_DPL_SHIFT) & 3;
-        if (seg_reg == R_SS) {
-            /* must be writable segment */
-            if ((e2 & DESC_CS_MASK) || !(e2 & DESC_W_MASK)) {
-                raise_exception_err(env, EXCP0D_GPF, selector & 0xfffc);
-            }
-            if (rpl != cpl || dpl != cpl) {
-                raise_exception_err(env, EXCP0D_GPF, selector & 0xfffc);
-            }
-        } else {
-            /* must be readable segment */
-            if ((e2 & (DESC_CS_MASK | DESC_R_MASK)) == DESC_CS_MASK) {
-                raise_exception_err(env, EXCP0D_GPF, selector & 0xfffc);
-            }
-
-            if (!(e2 & DESC_CS_MASK) || !(e2 & DESC_C_MASK)) {
-                /* if not conforming code, test rights */
-                if (dpl < cpl || dpl < rpl) {
-                    raise_exception_err(env, EXCP0D_GPF, selector & 0xfffc);
-                }
-            }
-        }
-
-        if (!(e2 & DESC_P_MASK)) {
-            if (seg_reg == R_SS) {
-                raise_exception_err(env, EXCP0C_STACK, selector & 0xfffc);
-            } else {
-                raise_exception_err(env, EXCP0B_NOSEG, selector & 0xfffc);
-            }
-        }
-
-        /* set the access bit if not already set */
-        if (!(e2 & DESC_A_MASK)) {
-            e2 |= DESC_A_MASK;
-            stl_kernel(ptr + 4, e2);
-        }
-
-        cpu_x86_load_seg_cache(env, seg_reg, selector,
-                       get_seg_base(e1, e2),
-                       get_seg_limit(e1, e2),
-                       e2);
-#if 0
-        qemu_log("load_seg: sel=0x%04x base=0x%08lx limit=0x%08lx flags=%08x\n",
-                selector, (unsigned long)sc->base, sc->limit, sc->flags);
-#endif
-    }
-}
-
-/* protected mode jump */
-void helper_ljmp_protected(int new_cs, target_ulong new_eip,
-                           int next_eip_addend)
-{
-    int gate_cs, type;
-    uint32_t e1, e2, cpl, dpl, rpl, limit;
-    target_ulong next_eip;
-
-    if ((new_cs & 0xfffc) == 0) {
-        raise_exception_err(env, EXCP0D_GPF, 0);
-    }
-    if (load_segment(&e1, &e2, new_cs) != 0) {
-        raise_exception_err(env, EXCP0D_GPF, new_cs & 0xfffc);
-    }
-    cpl = env->hflags & HF_CPL_MASK;
-    if (e2 & DESC_S_MASK) {
-        if (!(e2 & DESC_CS_MASK)) {
-            raise_exception_err(env, EXCP0D_GPF, new_cs & 0xfffc);
-        }
-        dpl = (e2 >> DESC_DPL_SHIFT) & 3;
-        if (e2 & DESC_C_MASK) {
-            /* conforming code segment */
-            if (dpl > cpl) {
-                raise_exception_err(env, EXCP0D_GPF, new_cs & 0xfffc);
-            }
-        } else {
-            /* non conforming code segment */
-            rpl = new_cs & 3;
-            if (rpl > cpl) {
-                raise_exception_err(env, EXCP0D_GPF, new_cs & 0xfffc);
-            }
-            if (dpl != cpl) {
-                raise_exception_err(env, EXCP0D_GPF, new_cs & 0xfffc);
-            }
-        }
-        if (!(e2 & DESC_P_MASK)) {
-            raise_exception_err(env, EXCP0B_NOSEG, new_cs & 0xfffc);
-        }
-        limit = get_seg_limit(e1, e2);
-        if (new_eip > limit &&
-            !(env->hflags & HF_LMA_MASK) && !(e2 & DESC_L_MASK)) {
-            raise_exception_err(env, EXCP0D_GPF, new_cs & 0xfffc);
-        }
-        cpu_x86_load_seg_cache(env, R_CS, (new_cs & 0xfffc) | cpl,
-                       get_seg_base(e1, e2), limit, e2);
-        EIP = new_eip;
-    } else {
-        /* jump to call or task gate */
-        dpl = (e2 >> DESC_DPL_SHIFT) & 3;
-        rpl = new_cs & 3;
-        cpl = env->hflags & HF_CPL_MASK;
-        type = (e2 >> DESC_TYPE_SHIFT) & 0xf;
-        switch (type) {
-        case 1: /* 286 TSS */
-        case 9: /* 386 TSS */
-        case 5: /* task gate */
-            if (dpl < cpl || dpl < rpl) {
-                raise_exception_err(env, EXCP0D_GPF, new_cs & 0xfffc);
-            }
-            next_eip = env->eip + next_eip_addend;
-            switch_tss(new_cs, e1, e2, SWITCH_TSS_JMP, next_eip);
-            CC_OP = CC_OP_EFLAGS;
-            break;
-        case 4: /* 286 call gate */
-        case 12: /* 386 call gate */
-            if ((dpl < cpl) || (dpl < rpl)) {
-                raise_exception_err(env, EXCP0D_GPF, new_cs & 0xfffc);
-            }
-            if (!(e2 & DESC_P_MASK)) {
-                raise_exception_err(env, EXCP0B_NOSEG, new_cs & 0xfffc);
-            }
-            gate_cs = e1 >> 16;
-            new_eip = (e1 & 0xffff);
-            if (type == 12) {
-                new_eip |= (e2 & 0xffff0000);
-            }
-            if (load_segment(&e1, &e2, gate_cs) != 0) {
-                raise_exception_err(env, EXCP0D_GPF, gate_cs & 0xfffc);
-            }
-            dpl = (e2 >> DESC_DPL_SHIFT) & 3;
-            /* must be code segment */
-            if (((e2 & (DESC_S_MASK | DESC_CS_MASK)) !=
-                 (DESC_S_MASK | DESC_CS_MASK))) {
-                raise_exception_err(env, EXCP0D_GPF, gate_cs & 0xfffc);
-            }
-            if (((e2 & DESC_C_MASK) && (dpl > cpl)) ||
-                (!(e2 & DESC_C_MASK) && (dpl != cpl))) {
-                raise_exception_err(env, EXCP0D_GPF, gate_cs & 0xfffc);
-            }
-            if (!(e2 & DESC_P_MASK)) {
-                raise_exception_err(env, EXCP0D_GPF, gate_cs & 0xfffc);
-            }
-            limit = get_seg_limit(e1, e2);
-            if (new_eip > limit) {
-                raise_exception_err(env, EXCP0D_GPF, 0);
-            }
-            cpu_x86_load_seg_cache(env, R_CS, (gate_cs & 0xfffc) | cpl,
-                                   get_seg_base(e1, e2), limit, e2);
-            EIP = new_eip;
-            break;
-        default:
-            raise_exception_err(env, EXCP0D_GPF, new_cs & 0xfffc);
-            break;
-        }
-    }
-}
-
-/* real mode call */
-void helper_lcall_real(int new_cs, target_ulong new_eip1,
-                       int shift, int next_eip)
-{
-    int new_eip;
-    uint32_t esp, esp_mask;
-    target_ulong ssp;
-
-    new_eip = new_eip1;
-    esp = ESP;
-    esp_mask = get_sp_mask(env->segs[R_SS].flags);
-    ssp = env->segs[R_SS].base;
-    if (shift) {
-        PUSHL(ssp, esp, esp_mask, env->segs[R_CS].selector);
-        PUSHL(ssp, esp, esp_mask, next_eip);
-    } else {
-        PUSHW(ssp, esp, esp_mask, env->segs[R_CS].selector);
-        PUSHW(ssp, esp, esp_mask, next_eip);
-    }
-
-    SET_ESP(esp, esp_mask);
-    env->eip = new_eip;
-    env->segs[R_CS].selector = new_cs;
-    env->segs[R_CS].base = (new_cs << 4);
-}
-
-/* protected mode call */
-void helper_lcall_protected(int new_cs, target_ulong new_eip,
-                            int shift, int next_eip_addend)
-{
-    int new_stack, i;
-    uint32_t e1, e2, cpl, dpl, rpl, selector, offset, param_count;
-    uint32_t ss = 0, ss_e1 = 0, ss_e2 = 0, sp, type, ss_dpl, sp_mask;
-    uint32_t val, limit, old_sp_mask;
-    target_ulong ssp, old_ssp, next_eip;
-
-    next_eip = env->eip + next_eip_addend;
-    LOG_PCALL("lcall %04x:%08x s=%d\n", new_cs, (uint32_t)new_eip, shift);
-    LOG_PCALL_STATE(env);
-    if ((new_cs & 0xfffc) == 0) {
-        raise_exception_err(env, EXCP0D_GPF, 0);
-    }
-    if (load_segment(&e1, &e2, new_cs) != 0) {
-        raise_exception_err(env, EXCP0D_GPF, new_cs & 0xfffc);
-    }
-    cpl = env->hflags & HF_CPL_MASK;
-    LOG_PCALL("desc=%08x:%08x\n", e1, e2);
-    if (e2 & DESC_S_MASK) {
-        if (!(e2 & DESC_CS_MASK)) {
-            raise_exception_err(env, EXCP0D_GPF, new_cs & 0xfffc);
-        }
-        dpl = (e2 >> DESC_DPL_SHIFT) & 3;
-        if (e2 & DESC_C_MASK) {
-            /* conforming code segment */
-            if (dpl > cpl) {
-                raise_exception_err(env, EXCP0D_GPF, new_cs & 0xfffc);
-            }
-        } else {
-            /* non conforming code segment */
-            rpl = new_cs & 3;
-            if (rpl > cpl) {
-                raise_exception_err(env, EXCP0D_GPF, new_cs & 0xfffc);
-            }
-            if (dpl != cpl) {
-                raise_exception_err(env, EXCP0D_GPF, new_cs & 0xfffc);
-            }
-        }
-        if (!(e2 & DESC_P_MASK)) {
-            raise_exception_err(env, EXCP0B_NOSEG, new_cs & 0xfffc);
-        }
-
-#ifdef TARGET_X86_64
-        /* XXX: check 16/32 bit cases in long mode */
-        if (shift == 2) {
-            target_ulong rsp;
-
-            /* 64 bit case */
-            rsp = ESP;
-            PUSHQ(rsp, env->segs[R_CS].selector);
-            PUSHQ(rsp, next_eip);
-            /* from this point, not restartable */
-            ESP = rsp;
-            cpu_x86_load_seg_cache(env, R_CS, (new_cs & 0xfffc) | cpl,
-                                   get_seg_base(e1, e2),
-                                   get_seg_limit(e1, e2), e2);
-            EIP = new_eip;
-        } else
-#endif
-        {
-            sp = ESP;
-            sp_mask = get_sp_mask(env->segs[R_SS].flags);
-            ssp = env->segs[R_SS].base;
-            if (shift) {
-                PUSHL(ssp, sp, sp_mask, env->segs[R_CS].selector);
-                PUSHL(ssp, sp, sp_mask, next_eip);
-            } else {
-                PUSHW(ssp, sp, sp_mask, env->segs[R_CS].selector);
-                PUSHW(ssp, sp, sp_mask, next_eip);
-            }
-
-            limit = get_seg_limit(e1, e2);
-            if (new_eip > limit) {
-                raise_exception_err(env, EXCP0D_GPF, new_cs & 0xfffc);
-            }
-            /* from this point, not restartable */
-            SET_ESP(sp, sp_mask);
-            cpu_x86_load_seg_cache(env, R_CS, (new_cs & 0xfffc) | cpl,
-                                   get_seg_base(e1, e2), limit, e2);
-            EIP = new_eip;
-        }
-    } else {
-        /* check gate type */
-        type = (e2 >> DESC_TYPE_SHIFT) & 0x1f;
-        dpl = (e2 >> DESC_DPL_SHIFT) & 3;
-        rpl = new_cs & 3;
-        switch (type) {
-        case 1: /* available 286 TSS */
-        case 9: /* available 386 TSS */
-        case 5: /* task gate */
-            if (dpl < cpl || dpl < rpl) {
-                raise_exception_err(env, EXCP0D_GPF, new_cs & 0xfffc);
-            }
-            switch_tss(new_cs, e1, e2, SWITCH_TSS_CALL, next_eip);
-            CC_OP = CC_OP_EFLAGS;
-            return;
-        case 4: /* 286 call gate */
-        case 12: /* 386 call gate */
-            break;
-        default:
-            raise_exception_err(env, EXCP0D_GPF, new_cs & 0xfffc);
-            break;
-        }
-        shift = type >> 3;
-
-        if (dpl < cpl || dpl < rpl) {
-            raise_exception_err(env, EXCP0D_GPF, new_cs & 0xfffc);
-        }
-        /* check valid bit */
-        if (!(e2 & DESC_P_MASK)) {
-            raise_exception_err(env, EXCP0B_NOSEG,  new_cs & 0xfffc);
-        }
-        selector = e1 >> 16;
-        offset = (e2 & 0xffff0000) | (e1 & 0x0000ffff);
-        param_count = e2 & 0x1f;
-        if ((selector & 0xfffc) == 0) {
-            raise_exception_err(env, EXCP0D_GPF, 0);
-        }
-
-        if (load_segment(&e1, &e2, selector) != 0) {
-            raise_exception_err(env, EXCP0D_GPF, selector & 0xfffc);
-        }
-        if (!(e2 & DESC_S_MASK) || !(e2 & (DESC_CS_MASK))) {
-            raise_exception_err(env, EXCP0D_GPF, selector & 0xfffc);
-        }
-        dpl = (e2 >> DESC_DPL_SHIFT) & 3;
-        if (dpl > cpl) {
-            raise_exception_err(env, EXCP0D_GPF, selector & 0xfffc);
-        }
-        if (!(e2 & DESC_P_MASK)) {
-            raise_exception_err(env, EXCP0B_NOSEG, selector & 0xfffc);
-        }
-
-        if (!(e2 & DESC_C_MASK) && dpl < cpl) {
-            /* to inner privilege */
-            get_ss_esp_from_tss(&ss, &sp, dpl);
-            LOG_PCALL("new ss:esp=%04x:%08x param_count=%d ESP=" TARGET_FMT_lx
-                      "\n",
-                      ss, sp, param_count, ESP);
-            if ((ss & 0xfffc) == 0) {
-                raise_exception_err(env, EXCP0A_TSS, ss & 0xfffc);
-            }
-            if ((ss & 3) != dpl) {
-                raise_exception_err(env, EXCP0A_TSS, ss & 0xfffc);
-            }
-            if (load_segment(&ss_e1, &ss_e2, ss) != 0) {
-                raise_exception_err(env, EXCP0A_TSS, ss & 0xfffc);
-            }
-            ss_dpl = (ss_e2 >> DESC_DPL_SHIFT) & 3;
-            if (ss_dpl != dpl) {
-                raise_exception_err(env, EXCP0A_TSS, ss & 0xfffc);
-            }
-            if (!(ss_e2 & DESC_S_MASK) ||
-                (ss_e2 & DESC_CS_MASK) ||
-                !(ss_e2 & DESC_W_MASK)) {
-                raise_exception_err(env, EXCP0A_TSS, ss & 0xfffc);
-            }
-            if (!(ss_e2 & DESC_P_MASK)) {
-                raise_exception_err(env, EXCP0A_TSS, ss & 0xfffc);
-            }
-
-            /* push_size = ((param_count * 2) + 8) << shift; */
-
-            old_sp_mask = get_sp_mask(env->segs[R_SS].flags);
-            old_ssp = env->segs[R_SS].base;
-
-            sp_mask = get_sp_mask(ss_e2);
-            ssp = get_seg_base(ss_e1, ss_e2);
-            if (shift) {
-                PUSHL(ssp, sp, sp_mask, env->segs[R_SS].selector);
-                PUSHL(ssp, sp, sp_mask, ESP);
-                for (i = param_count - 1; i >= 0; i--) {
-                    val = ldl_kernel(old_ssp + ((ESP + i * 4) & old_sp_mask));
-                    PUSHL(ssp, sp, sp_mask, val);
-                }
-            } else {
-                PUSHW(ssp, sp, sp_mask, env->segs[R_SS].selector);
-                PUSHW(ssp, sp, sp_mask, ESP);
-                for (i = param_count - 1; i >= 0; i--) {
-                    val = lduw_kernel(old_ssp + ((ESP + i * 2) & old_sp_mask));
-                    PUSHW(ssp, sp, sp_mask, val);
-                }
-            }
-            new_stack = 1;
-        } else {
-            /* to same privilege */
-            sp = ESP;
-            sp_mask = get_sp_mask(env->segs[R_SS].flags);
-            ssp = env->segs[R_SS].base;
-            /* push_size = (4 << shift); */
-            new_stack = 0;
-        }
-
-        if (shift) {
-            PUSHL(ssp, sp, sp_mask, env->segs[R_CS].selector);
-            PUSHL(ssp, sp, sp_mask, next_eip);
-        } else {
-            PUSHW(ssp, sp, sp_mask, env->segs[R_CS].selector);
-            PUSHW(ssp, sp, sp_mask, next_eip);
-        }
-
-        /* from this point, not restartable */
-
-        if (new_stack) {
-            ss = (ss & ~3) | dpl;
-            cpu_x86_load_seg_cache(env, R_SS, ss,
-                                   ssp,
-                                   get_seg_limit(ss_e1, ss_e2),
-                                   ss_e2);
-        }
-
-        selector = (selector & ~3) | dpl;
-        cpu_x86_load_seg_cache(env, R_CS, selector,
-                       get_seg_base(e1, e2),
-                       get_seg_limit(e1, e2),
-                       e2);
-        cpu_x86_set_cpl(env, dpl);
-        SET_ESP(sp, sp_mask);
-        EIP = offset;
-    }
-}
-
-/* real and vm86 mode iret */
-void helper_iret_real(int shift)
-{
-    uint32_t sp, new_cs, new_eip, new_eflags, sp_mask;
-    target_ulong ssp;
-    int eflags_mask;
-
-    sp_mask = 0xffff; /* XXXX: use SS segment size? */
-    sp = ESP;
-    ssp = env->segs[R_SS].base;
-    if (shift == 1) {
-        /* 32 bits */
-        POPL(ssp, sp, sp_mask, new_eip);
-        POPL(ssp, sp, sp_mask, new_cs);
-        new_cs &= 0xffff;
-        POPL(ssp, sp, sp_mask, new_eflags);
-    } else {
-        /* 16 bits */
-        POPW(ssp, sp, sp_mask, new_eip);
-        POPW(ssp, sp, sp_mask, new_cs);
-        POPW(ssp, sp, sp_mask, new_eflags);
-    }
-    ESP = (ESP & ~sp_mask) | (sp & sp_mask);
-    env->segs[R_CS].selector = new_cs;
-    env->segs[R_CS].base = (new_cs << 4);
-    env->eip = new_eip;
-    if (env->eflags & VM_MASK) {
-        eflags_mask = TF_MASK | AC_MASK | ID_MASK | IF_MASK | RF_MASK |
-            NT_MASK;
-    } else {
-        eflags_mask = TF_MASK | AC_MASK | ID_MASK | IF_MASK | IOPL_MASK |
-            RF_MASK | NT_MASK;
-    }
-    if (shift == 0) {
-        eflags_mask &= 0xffff;
-    }
-    cpu_load_eflags(env, new_eflags, eflags_mask);
-    env->hflags2 &= ~HF2_NMI_MASK;
-}
-
-static inline void validate_seg(int seg_reg, int cpl)
-{
-    int dpl;
-    uint32_t e2;
-
-    /* XXX: on x86_64, we do not want to nullify FS and GS because
-       they may still contain a valid base. I would be interested to
-       know how a real x86_64 CPU behaves */
-    if ((seg_reg == R_FS || seg_reg == R_GS) &&
-        (env->segs[seg_reg].selector & 0xfffc) == 0) {
-        return;
-    }
-
-    e2 = env->segs[seg_reg].flags;
-    dpl = (e2 >> DESC_DPL_SHIFT) & 3;
-    if (!(e2 & DESC_CS_MASK) || !(e2 & DESC_C_MASK)) {
-        /* data or non conforming code segment */
-        if (dpl < cpl) {
-            cpu_x86_load_seg_cache(env, seg_reg, 0, 0, 0, 0);
-        }
-    }
-}
-
-/* protected mode iret */
-static inline void helper_ret_protected(int shift, int is_iret, int addend)
-{
-    uint32_t new_cs, new_eflags, new_ss;
-    uint32_t new_es, new_ds, new_fs, new_gs;
-    uint32_t e1, e2, ss_e1, ss_e2;
-    int cpl, dpl, rpl, eflags_mask, iopl;
-    target_ulong ssp, sp, new_eip, new_esp, sp_mask;
-
-#ifdef TARGET_X86_64
-    if (shift == 2) {
-        sp_mask = -1;
-    } else
-#endif
-    {
-        sp_mask = get_sp_mask(env->segs[R_SS].flags);
-    }
-    sp = ESP;
-    ssp = env->segs[R_SS].base;
-    new_eflags = 0; /* avoid warning */
-#ifdef TARGET_X86_64
-    if (shift == 2) {
-        POPQ(sp, new_eip);
-        POPQ(sp, new_cs);
-        new_cs &= 0xffff;
-        if (is_iret) {
-            POPQ(sp, new_eflags);
-        }
-    } else
-#endif
-    {
-        if (shift == 1) {
-            /* 32 bits */
-            POPL(ssp, sp, sp_mask, new_eip);
-            POPL(ssp, sp, sp_mask, new_cs);
-            new_cs &= 0xffff;
-            if (is_iret) {
-                POPL(ssp, sp, sp_mask, new_eflags);
-                if (new_eflags & VM_MASK) {
-                    goto return_to_vm86;
-                }
-            }
-        } else {
-            /* 16 bits */
-            POPW(ssp, sp, sp_mask, new_eip);
-            POPW(ssp, sp, sp_mask, new_cs);
-            if (is_iret) {
-                POPW(ssp, sp, sp_mask, new_eflags);
-            }
-        }
-    }
-    LOG_PCALL("lret new %04x:" TARGET_FMT_lx " s=%d addend=0x%x\n",
-              new_cs, new_eip, shift, addend);
-    LOG_PCALL_STATE(env);
-    if ((new_cs & 0xfffc) == 0) {
-        raise_exception_err(env, EXCP0D_GPF, new_cs & 0xfffc);
-    }
-    if (load_segment(&e1, &e2, new_cs) != 0) {
-        raise_exception_err(env, EXCP0D_GPF, new_cs & 0xfffc);
-    }
-    if (!(e2 & DESC_S_MASK) ||
-        !(e2 & DESC_CS_MASK)) {
-        raise_exception_err(env, EXCP0D_GPF, new_cs & 0xfffc);
-    }
-    cpl = env->hflags & HF_CPL_MASK;
-    rpl = new_cs & 3;
-    if (rpl < cpl) {
-        raise_exception_err(env, EXCP0D_GPF, new_cs & 0xfffc);
-    }
-    dpl = (e2 >> DESC_DPL_SHIFT) & 3;
-    if (e2 & DESC_C_MASK) {
-        if (dpl > rpl) {
-            raise_exception_err(env, EXCP0D_GPF, new_cs & 0xfffc);
-        }
-    } else {
-        if (dpl != rpl) {
-            raise_exception_err(env, EXCP0D_GPF, new_cs & 0xfffc);
-        }
-    }
-    if (!(e2 & DESC_P_MASK)) {
-        raise_exception_err(env, EXCP0B_NOSEG, new_cs & 0xfffc);
-    }
-
-    sp += addend;
-    if (rpl == cpl && (!(env->hflags & HF_CS64_MASK) ||
-                       ((env->hflags & HF_CS64_MASK) && !is_iret))) {
-        /* return to same privilege level */
-        cpu_x86_load_seg_cache(env, R_CS, new_cs,
-                       get_seg_base(e1, e2),
-                       get_seg_limit(e1, e2),
-                       e2);
-    } else {
-        /* return to different privilege level */
-#ifdef TARGET_X86_64
-        if (shift == 2) {
-            POPQ(sp, new_esp);
-            POPQ(sp, new_ss);
-            new_ss &= 0xffff;
-        } else
-#endif
-        {
-            if (shift == 1) {
-                /* 32 bits */
-                POPL(ssp, sp, sp_mask, new_esp);
-                POPL(ssp, sp, sp_mask, new_ss);
-                new_ss &= 0xffff;
-            } else {
-                /* 16 bits */
-                POPW(ssp, sp, sp_mask, new_esp);
-                POPW(ssp, sp, sp_mask, new_ss);
-            }
-        }
-        LOG_PCALL("new ss:esp=%04x:" TARGET_FMT_lx "\n",
-                  new_ss, new_esp);
-        if ((new_ss & 0xfffc) == 0) {
-#ifdef TARGET_X86_64
-            /* NULL ss is allowed in long mode if cpl != 3 */
-            /* XXX: test CS64? */
-            if ((env->hflags & HF_LMA_MASK) && rpl != 3) {
-                cpu_x86_load_seg_cache(env, R_SS, new_ss,
-                                       0, 0xffffffff,
-                                       DESC_G_MASK | DESC_B_MASK | DESC_P_MASK |
-                                       DESC_S_MASK | (rpl << DESC_DPL_SHIFT) |
-                                       DESC_W_MASK | DESC_A_MASK);
-                ss_e2 = DESC_B_MASK; /* XXX: should not be needed? */
-            } else
-#endif
-            {
-                raise_exception_err(env, EXCP0D_GPF, 0);
-            }
-        } else {
-            if ((new_ss & 3) != rpl) {
-                raise_exception_err(env, EXCP0D_GPF, new_ss & 0xfffc);
-            }
-            if (load_segment(&ss_e1, &ss_e2, new_ss) != 0) {
-                raise_exception_err(env, EXCP0D_GPF, new_ss & 0xfffc);
-            }
-            if (!(ss_e2 & DESC_S_MASK) ||
-                (ss_e2 & DESC_CS_MASK) ||
-                !(ss_e2 & DESC_W_MASK)) {
-                raise_exception_err(env, EXCP0D_GPF, new_ss & 0xfffc);
-            }
-            dpl = (ss_e2 >> DESC_DPL_SHIFT) & 3;
-            if (dpl != rpl) {
-                raise_exception_err(env, EXCP0D_GPF, new_ss & 0xfffc);
-            }
-            if (!(ss_e2 & DESC_P_MASK)) {
-                raise_exception_err(env, EXCP0B_NOSEG, new_ss & 0xfffc);
-            }
-            cpu_x86_load_seg_cache(env, R_SS, new_ss,
-                                   get_seg_base(ss_e1, ss_e2),
-                                   get_seg_limit(ss_e1, ss_e2),
-                                   ss_e2);
-        }
-
-        cpu_x86_load_seg_cache(env, R_CS, new_cs,
-                       get_seg_base(e1, e2),
-                       get_seg_limit(e1, e2),
-                       e2);
-        cpu_x86_set_cpl(env, rpl);
-        sp = new_esp;
-#ifdef TARGET_X86_64
-        if (env->hflags & HF_CS64_MASK) {
-            sp_mask = -1;
-        } else
-#endif
-        {
-            sp_mask = get_sp_mask(ss_e2);
-        }
-
-        /* validate data segments */
-        validate_seg(R_ES, rpl);
-        validate_seg(R_DS, rpl);
-        validate_seg(R_FS, rpl);
-        validate_seg(R_GS, rpl);
-
-        sp += addend;
-    }
-    SET_ESP(sp, sp_mask);
-    env->eip = new_eip;
-    if (is_iret) {
-        /* NOTE: 'cpl' is the _old_ CPL */
-        eflags_mask = TF_MASK | AC_MASK | ID_MASK | RF_MASK | NT_MASK;
-        if (cpl == 0) {
-            eflags_mask |= IOPL_MASK;
-        }
-        iopl = (env->eflags >> IOPL_SHIFT) & 3;
-        if (cpl <= iopl) {
-            eflags_mask |= IF_MASK;
-        }
-        if (shift == 0) {
-            eflags_mask &= 0xffff;
-        }
-        cpu_load_eflags(env, new_eflags, eflags_mask);
-    }
-    return;
-
- return_to_vm86:
-    POPL(ssp, sp, sp_mask, new_esp);
-    POPL(ssp, sp, sp_mask, new_ss);
-    POPL(ssp, sp, sp_mask, new_es);
-    POPL(ssp, sp, sp_mask, new_ds);
-    POPL(ssp, sp, sp_mask, new_fs);
-    POPL(ssp, sp, sp_mask, new_gs);
-
-    /* modify processor state */
-    cpu_load_eflags(env, new_eflags, TF_MASK | AC_MASK | ID_MASK |
-                    IF_MASK | IOPL_MASK | VM_MASK | NT_MASK | VIF_MASK |
-                    VIP_MASK);
-    load_seg_vm(R_CS, new_cs & 0xffff);
-    cpu_x86_set_cpl(env, 3);
-    load_seg_vm(R_SS, new_ss & 0xffff);
-    load_seg_vm(R_ES, new_es & 0xffff);
-    load_seg_vm(R_DS, new_ds & 0xffff);
-    load_seg_vm(R_FS, new_fs & 0xffff);
-    load_seg_vm(R_GS, new_gs & 0xffff);
-
-    env->eip = new_eip & 0xffff;
-    ESP = new_esp;
-}
-
-void helper_iret_protected(int shift, int next_eip)
-{
-    int tss_selector, type;
-    uint32_t e1, e2;
-
-    /* specific case for TSS */
-    if (env->eflags & NT_MASK) {
-#ifdef TARGET_X86_64
-        if (env->hflags & HF_LMA_MASK) {
-            raise_exception_err(env, EXCP0D_GPF, 0);
-        }
-#endif
-        tss_selector = lduw_kernel(env->tr.base + 0);
-        if (tss_selector & 4) {
-            raise_exception_err(env, EXCP0A_TSS, tss_selector & 0xfffc);
-        }
-        if (load_segment(&e1, &e2, tss_selector) != 0) {
-            raise_exception_err(env, EXCP0A_TSS, tss_selector & 0xfffc);
-        }
-        type = (e2 >> DESC_TYPE_SHIFT) & 0x17;
-        /* NOTE: we check both segment and busy TSS */
-        if (type != 3) {
-            raise_exception_err(env, EXCP0A_TSS, tss_selector & 0xfffc);
-        }
-        switch_tss(tss_selector, e1, e2, SWITCH_TSS_IRET, next_eip);
-    } else {
-        helper_ret_protected(shift, 1, 0);
-    }
-    env->hflags2 &= ~HF2_NMI_MASK;
-}
-
-void helper_lret_protected(int shift, int addend)
-{
-    helper_ret_protected(shift, 0, addend);
-}
-
-void helper_sysenter(void)
-{
-    if (env->sysenter_cs == 0) {
-        raise_exception_err(env, EXCP0D_GPF, 0);
-    }
-    env->eflags &= ~(VM_MASK | IF_MASK | RF_MASK);
-    cpu_x86_set_cpl(env, 0);
-
-#ifdef TARGET_X86_64
-    if (env->hflags & HF_LMA_MASK) {
-        cpu_x86_load_seg_cache(env, R_CS, env->sysenter_cs & 0xfffc,
-                               0, 0xffffffff,
-                               DESC_G_MASK | DESC_B_MASK | DESC_P_MASK |
-                               DESC_S_MASK |
-                               DESC_CS_MASK | DESC_R_MASK | DESC_A_MASK |
-                               DESC_L_MASK);
-    } else
-#endif
-    {
-        cpu_x86_load_seg_cache(env, R_CS, env->sysenter_cs & 0xfffc,
-                               0, 0xffffffff,
-                               DESC_G_MASK | DESC_B_MASK | DESC_P_MASK |
-                               DESC_S_MASK |
-                               DESC_CS_MASK | DESC_R_MASK | DESC_A_MASK);
-    }
-    cpu_x86_load_seg_cache(env, R_SS, (env->sysenter_cs + 8) & 0xfffc,
-                           0, 0xffffffff,
-                           DESC_G_MASK | DESC_B_MASK | DESC_P_MASK |
-                           DESC_S_MASK |
-                           DESC_W_MASK | DESC_A_MASK);
-    ESP = env->sysenter_esp;
-    EIP = env->sysenter_eip;
-}
-
-void helper_sysexit(int dflag)
-{
-    int cpl;
-
-    cpl = env->hflags & HF_CPL_MASK;
-    if (env->sysenter_cs == 0 || cpl != 0) {
-        raise_exception_err(env, EXCP0D_GPF, 0);
-    }
-    cpu_x86_set_cpl(env, 3);
-#ifdef TARGET_X86_64
-    if (dflag == 2) {
-        cpu_x86_load_seg_cache(env, R_CS, ((env->sysenter_cs + 32) & 0xfffc) |
-                               3, 0, 0xffffffff,
-                               DESC_G_MASK | DESC_B_MASK | DESC_P_MASK |
-                               DESC_S_MASK | (3 << DESC_DPL_SHIFT) |
-                               DESC_CS_MASK | DESC_R_MASK | DESC_A_MASK |
-                               DESC_L_MASK);
-        cpu_x86_load_seg_cache(env, R_SS, ((env->sysenter_cs + 40) & 0xfffc) |
-                               3, 0, 0xffffffff,
-                               DESC_G_MASK | DESC_B_MASK | DESC_P_MASK |
-                               DESC_S_MASK | (3 << DESC_DPL_SHIFT) |
-                               DESC_W_MASK | DESC_A_MASK);
-    } else
-#endif
-    {
-        cpu_x86_load_seg_cache(env, R_CS, ((env->sysenter_cs + 16) & 0xfffc) |
-                               3, 0, 0xffffffff,
-                               DESC_G_MASK | DESC_B_MASK | DESC_P_MASK |
-                               DESC_S_MASK | (3 << DESC_DPL_SHIFT) |
-                               DESC_CS_MASK | DESC_R_MASK | DESC_A_MASK);
-        cpu_x86_load_seg_cache(env, R_SS, ((env->sysenter_cs + 24) & 0xfffc) |
-                               3, 0, 0xffffffff,
-                               DESC_G_MASK | DESC_B_MASK | DESC_P_MASK |
-                               DESC_S_MASK | (3 << DESC_DPL_SHIFT) |
-                               DESC_W_MASK | DESC_A_MASK);
-    }
-    ESP = ECX;
-    EIP = EDX;
-}
-
-target_ulong helper_lsl(target_ulong selector1)
-{
-    unsigned int limit;
-    uint32_t e1, e2, eflags, selector;
-    int rpl, dpl, cpl, type;
-
-    selector = selector1 & 0xffff;
-    eflags = helper_cc_compute_all(CC_OP);
-    if ((selector & 0xfffc) == 0) {
-        goto fail;
-    }
-    if (load_segment(&e1, &e2, selector) != 0) {
-        goto fail;
-    }
-    rpl = selector & 3;
-    dpl = (e2 >> DESC_DPL_SHIFT) & 3;
-    cpl = env->hflags & HF_CPL_MASK;
-    if (e2 & DESC_S_MASK) {
-        if ((e2 & DESC_CS_MASK) && (e2 & DESC_C_MASK)) {
-            /* conforming */
-        } else {
-            if (dpl < cpl || dpl < rpl) {
-                goto fail;
-            }
-        }
-    } else {
-        type = (e2 >> DESC_TYPE_SHIFT) & 0xf;
-        switch (type) {
-        case 1:
-        case 2:
-        case 3:
-        case 9:
-        case 11:
-            break;
-        default:
-            goto fail;
-        }
-        if (dpl < cpl || dpl < rpl) {
-        fail:
-            CC_SRC = eflags & ~CC_Z;
-            return 0;
-        }
-    }
-    limit = get_seg_limit(e1, e2);
-    CC_SRC = eflags | CC_Z;
-    return limit;
-}
-
-target_ulong helper_lar(target_ulong selector1)
-{
-    uint32_t e1, e2, eflags, selector;
-    int rpl, dpl, cpl, type;
-
-    selector = selector1 & 0xffff;
-    eflags = helper_cc_compute_all(CC_OP);
-    if ((selector & 0xfffc) == 0) {
-        goto fail;
-    }
-    if (load_segment(&e1, &e2, selector) != 0) {
-        goto fail;
-    }
-    rpl = selector & 3;
-    dpl = (e2 >> DESC_DPL_SHIFT) & 3;
-    cpl = env->hflags & HF_CPL_MASK;
-    if (e2 & DESC_S_MASK) {
-        if ((e2 & DESC_CS_MASK) && (e2 & DESC_C_MASK)) {
-            /* conforming */
-        } else {
-            if (dpl < cpl || dpl < rpl) {
-                goto fail;
-            }
-        }
-    } else {
-        type = (e2 >> DESC_TYPE_SHIFT) & 0xf;
-        switch (type) {
-        case 1:
-        case 2:
-        case 3:
-        case 4:
-        case 5:
-        case 9:
-        case 11:
-        case 12:
-            break;
-        default:
-            goto fail;
-        }
-        if (dpl < cpl || dpl < rpl) {
-        fail:
-            CC_SRC = eflags & ~CC_Z;
-            return 0;
-        }
-    }
-    CC_SRC = eflags | CC_Z;
-    return e2 & 0x00f0ff00;
-}
-
-void helper_verr(target_ulong selector1)
-{
-    uint32_t e1, e2, eflags, selector;
-    int rpl, dpl, cpl;
-
-    selector = selector1 & 0xffff;
-    eflags = helper_cc_compute_all(CC_OP);
-    if ((selector & 0xfffc) == 0) {
-        goto fail;
-    }
-    if (load_segment(&e1, &e2, selector) != 0) {
-        goto fail;
-    }
-    if (!(e2 & DESC_S_MASK)) {
-        goto fail;
-    }
-    rpl = selector & 3;
-    dpl = (e2 >> DESC_DPL_SHIFT) & 3;
-    cpl = env->hflags & HF_CPL_MASK;
-    if (e2 & DESC_CS_MASK) {
-        if (!(e2 & DESC_R_MASK)) {
-            goto fail;
-        }
-        if (!(e2 & DESC_C_MASK)) {
-            if (dpl < cpl || dpl < rpl) {
-                goto fail;
-            }
-        }
-    } else {
-        if (dpl < cpl || dpl < rpl) {
-        fail:
-            CC_SRC = eflags & ~CC_Z;
-            return;
-        }
-    }
-    CC_SRC = eflags | CC_Z;
-}
-
-void helper_verw(target_ulong selector1)
-{
-    uint32_t e1, e2, eflags, selector;
-    int rpl, dpl, cpl;
-
-    selector = selector1 & 0xffff;
-    eflags = helper_cc_compute_all(CC_OP);
-    if ((selector & 0xfffc) == 0) {
-        goto fail;
-    }
-    if (load_segment(&e1, &e2, selector) != 0) {
-        goto fail;
-    }
-    if (!(e2 & DESC_S_MASK)) {
-        goto fail;
-    }
-    rpl = selector & 3;
-    dpl = (e2 >> DESC_DPL_SHIFT) & 3;
-    cpl = env->hflags & HF_CPL_MASK;
-    if (e2 & DESC_CS_MASK) {
-        goto fail;
-    } else {
-        if (dpl < cpl || dpl < rpl) {
-            goto fail;
-        }
-        if (!(e2 & DESC_W_MASK)) {
-        fail:
-            CC_SRC = eflags & ~CC_Z;
-            return;
-        }
-    }
-    CC_SRC = eflags | CC_Z;
-}
-
-#if defined(CONFIG_USER_ONLY)
-void cpu_x86_load_seg(CPUX86State *s, int seg_reg, int selector)
-{
-    CPUX86State *saved_env;
-
-    saved_env = env;
-    env = s;
-    if (!(env->cr[0] & CR0_PE_MASK) || (env->eflags & VM_MASK)) {
-        selector &= 0xffff;
-        cpu_x86_load_seg_cache(env, seg_reg, selector,
-                               (selector << 4), 0xffff, 0);
-    } else {
-        helper_load_seg(seg_reg, selector);
-    }
-    env = saved_env;
-}
-#endif
diff --git a/target-i386/seg_helper.c b/target-i386/seg_helper.c
new file mode 100644
index 0000000..a4b8b64
--- /dev/null
+++ b/target-i386/seg_helper.c
@@ -0,0 +1,2475 @@
+/*
+ *  x86 segmentation related helpers:
+ *  TSS, interrupts, system calls, jumps and call/task gates, descriptors
+ *
+ *  Copyright (c) 2003 Fabrice Bellard
+ *
+ * This library is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Lesser General Public
+ * License as published by the Free Software Foundation; either
+ * version 2 of the License, or (at your option) any later version.
+ *
+ * This library is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
+ * Lesser General Public License for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public
+ * License along with this library; if not, see <http://www.gnu.org/licenses/>.
+ */
+
+#include "cpu.h"
+#include "dyngen-exec.h"
+#include "qemu-log.h"
+#include "helper.h"
+
+#if !defined(CONFIG_USER_ONLY)
+#include "softmmu_exec.h"
+#endif /* !defined(CONFIG_USER_ONLY) */
+
+//#define DEBUG_PCALL
+
+#ifdef DEBUG_PCALL
+# define LOG_PCALL(...) qemu_log_mask(CPU_LOG_PCALL, ## __VA_ARGS__)
+# define LOG_PCALL_STATE(env)                                  \
+    log_cpu_state_mask(CPU_LOG_PCALL, (env), X86_DUMP_CCOP)
+#else
+# define LOG_PCALL(...) do { } while (0)
+# define LOG_PCALL_STATE(env) do { } while (0)
+#endif
+
+/* return non zero if error */
+static inline int load_segment(uint32_t *e1_ptr, uint32_t *e2_ptr,
+                               int selector)
+{
+    SegmentCache *dt;
+    int index;
+    target_ulong ptr;
+
+    if (selector & 0x4) {
+        dt = &env->ldt;
+    } else {
+        dt = &env->gdt;
+    }
+    index = selector & ~7;
+    if ((index + 7) > dt->limit) {
+        return -1;
+    }
+    ptr = dt->base + index;
+    *e1_ptr = ldl_kernel(ptr);
+    *e2_ptr = ldl_kernel(ptr + 4);
+    return 0;
+}
+
+static inline unsigned int get_seg_limit(uint32_t e1, uint32_t e2)
+{
+    unsigned int limit;
+
+    limit = (e1 & 0xffff) | (e2 & 0x000f0000);
+    if (e2 & DESC_G_MASK) {
+        limit = (limit << 12) | 0xfff;
+    }
+    return limit;
+}
+
+static inline uint32_t get_seg_base(uint32_t e1, uint32_t e2)
+{
+    return (e1 >> 16) | ((e2 & 0xff) << 16) | (e2 & 0xff000000);
+}
+
+static inline void load_seg_cache_raw_dt(SegmentCache *sc, uint32_t e1,
+                                         uint32_t e2)
+{
+    sc->base = get_seg_base(e1, e2);
+    sc->limit = get_seg_limit(e1, e2);
+    sc->flags = e2;
+}
+
+/* init the segment cache in vm86 mode. */
+static inline void load_seg_vm(int seg, int selector)
+{
+    selector &= 0xffff;
+    cpu_x86_load_seg_cache(env, seg, selector,
+                           (selector << 4), 0xffff, 0);
+}
+
+static inline void get_ss_esp_from_tss(uint32_t *ss_ptr,
+                                       uint32_t *esp_ptr, int dpl)
+{
+    int type, index, shift;
+
+#if 0
+    {
+        int i;
+        printf("TR: base=%p limit=%x\n", env->tr.base, env->tr.limit);
+        for (i = 0; i < env->tr.limit; i++) {
+            printf("%02x ", env->tr.base[i]);
+            if ((i & 7) == 7) {
+                printf("\n");
+            }
+        }
+        printf("\n");
+    }
+#endif
+
+    if (!(env->tr.flags & DESC_P_MASK)) {
+        cpu_abort(env, "invalid tss");
+    }
+    type = (env->tr.flags >> DESC_TYPE_SHIFT) & 0xf;
+    if ((type & 7) != 1) {
+        cpu_abort(env, "invalid tss type");
+    }
+    shift = type >> 3;
+    index = (dpl * 4 + 2) << shift;
+    if (index + (4 << shift) - 1 > env->tr.limit) {
+        raise_exception_err(env, EXCP0A_TSS, env->tr.selector & 0xfffc);
+    }
+    if (shift == 0) {
+        *esp_ptr = lduw_kernel(env->tr.base + index);
+        *ss_ptr = lduw_kernel(env->tr.base + index + 2);
+    } else {
+        *esp_ptr = ldl_kernel(env->tr.base + index);
+        *ss_ptr = lduw_kernel(env->tr.base + index + 4);
+    }
+}
+
+/* XXX: merge with load_seg() */
+static void tss_load_seg(int seg_reg, int selector)
+{
+    uint32_t e1, e2;
+    int rpl, dpl, cpl;
+
+    if ((selector & 0xfffc) != 0) {
+        if (load_segment(&e1, &e2, selector) != 0) {
+            raise_exception_err(env, EXCP0A_TSS, selector & 0xfffc);
+        }
+        if (!(e2 & DESC_S_MASK)) {
+            raise_exception_err(env, EXCP0A_TSS, selector & 0xfffc);
+        }
+        rpl = selector & 3;
+        dpl = (e2 >> DESC_DPL_SHIFT) & 3;
+        cpl = env->hflags & HF_CPL_MASK;
+        if (seg_reg == R_CS) {
+            if (!(e2 & DESC_CS_MASK)) {
+                raise_exception_err(env, EXCP0A_TSS, selector & 0xfffc);
+            }
+            /* XXX: is it correct? */
+            if (dpl != rpl) {
+                raise_exception_err(env, EXCP0A_TSS, selector & 0xfffc);
+            }
+            if ((e2 & DESC_C_MASK) && dpl > rpl) {
+                raise_exception_err(env, EXCP0A_TSS, selector & 0xfffc);
+            }
+        } else if (seg_reg == R_SS) {
+            /* SS must be writable data */
+            if ((e2 & DESC_CS_MASK) || !(e2 & DESC_W_MASK)) {
+                raise_exception_err(env, EXCP0A_TSS, selector & 0xfffc);
+            }
+            if (dpl != cpl || dpl != rpl) {
+                raise_exception_err(env, EXCP0A_TSS, selector & 0xfffc);
+            }
+        } else {
+            /* not readable code */
+            if ((e2 & DESC_CS_MASK) && !(e2 & DESC_R_MASK)) {
+                raise_exception_err(env, EXCP0A_TSS, selector & 0xfffc);
+            }
+            /* if data or non conforming code, checks the rights */
+            if (((e2 >> DESC_TYPE_SHIFT) & 0xf) < 12) {
+                if (dpl < cpl || dpl < rpl) {
+                    raise_exception_err(env, EXCP0A_TSS, selector & 0xfffc);
+                }
+            }
+        }
+        if (!(e2 & DESC_P_MASK)) {
+            raise_exception_err(env, EXCP0B_NOSEG, selector & 0xfffc);
+        }
+        cpu_x86_load_seg_cache(env, seg_reg, selector,
+                               get_seg_base(e1, e2),
+                               get_seg_limit(e1, e2),
+                               e2);
+    } else {
+        if (seg_reg == R_SS || seg_reg == R_CS) {
+            raise_exception_err(env, EXCP0A_TSS, selector & 0xfffc);
+        }
+    }
+}
+
+#define SWITCH_TSS_JMP  0
+#define SWITCH_TSS_IRET 1
+#define SWITCH_TSS_CALL 2
+
+/* XXX: restore CPU state in registers (PowerPC case) */
+static void switch_tss(int tss_selector,
+                       uint32_t e1, uint32_t e2, int source,
+                       uint32_t next_eip)
+{
+    int tss_limit, tss_limit_max, type, old_tss_limit_max, old_type, v1, v2, i;
+    target_ulong tss_base;
+    uint32_t new_regs[8], new_segs[6];
+    uint32_t new_eflags, new_eip, new_cr3, new_ldt, new_trap;
+    uint32_t old_eflags, eflags_mask;
+    SegmentCache *dt;
+    int index;
+    target_ulong ptr;
+
+    type = (e2 >> DESC_TYPE_SHIFT) & 0xf;
+    LOG_PCALL("switch_tss: sel=0x%04x type=%d src=%d\n", tss_selector, type,
+              source);
+
+    /* if task gate, we read the TSS segment and we load it */
+    if (type == 5) {
+        if (!(e2 & DESC_P_MASK)) {
+            raise_exception_err(env, EXCP0B_NOSEG, tss_selector & 0xfffc);
+        }
+        tss_selector = e1 >> 16;
+        if (tss_selector & 4) {
+            raise_exception_err(env, EXCP0A_TSS, tss_selector & 0xfffc);
+        }
+        if (load_segment(&e1, &e2, tss_selector) != 0) {
+            raise_exception_err(env, EXCP0D_GPF, tss_selector & 0xfffc);
+        }
+        if (e2 & DESC_S_MASK) {
+            raise_exception_err(env, EXCP0D_GPF, tss_selector & 0xfffc);
+        }
+        type = (e2 >> DESC_TYPE_SHIFT) & 0xf;
+        if ((type & 7) != 1) {
+            raise_exception_err(env, EXCP0D_GPF, tss_selector & 0xfffc);
+        }
+    }
+
+    if (!(e2 & DESC_P_MASK)) {
+        raise_exception_err(env, EXCP0B_NOSEG, tss_selector & 0xfffc);
+    }
+
+    if (type & 8) {
+        tss_limit_max = 103;
+    } else {
+        tss_limit_max = 43;
+    }
+    tss_limit = get_seg_limit(e1, e2);
+    tss_base = get_seg_base(e1, e2);
+    if ((tss_selector & 4) != 0 ||
+        tss_limit < tss_limit_max) {
+        raise_exception_err(env, EXCP0A_TSS, tss_selector & 0xfffc);
+    }
+    old_type = (env->tr.flags >> DESC_TYPE_SHIFT) & 0xf;
+    if (old_type & 8) {
+        old_tss_limit_max = 103;
+    } else {
+        old_tss_limit_max = 43;
+    }
+
+    /* read all the registers from the new TSS */
+    if (type & 8) {
+        /* 32 bit */
+        new_cr3 = ldl_kernel(tss_base + 0x1c);
+        new_eip = ldl_kernel(tss_base + 0x20);
+        new_eflags = ldl_kernel(tss_base + 0x24);
+        for (i = 0; i < 8; i++) {
+            new_regs[i] = ldl_kernel(tss_base + (0x28 + i * 4));
+        }
+        for (i = 0; i < 6; i++) {
+            new_segs[i] = lduw_kernel(tss_base + (0x48 + i * 4));
+        }
+        new_ldt = lduw_kernel(tss_base + 0x60);
+        new_trap = ldl_kernel(tss_base + 0x64);
+    } else {
+        /* 16 bit */
+        new_cr3 = 0;
+        new_eip = lduw_kernel(tss_base + 0x0e);
+        new_eflags = lduw_kernel(tss_base + 0x10);
+        for (i = 0; i < 8; i++) {
+            new_regs[i] = lduw_kernel(tss_base + (0x12 + i * 2)) | 0xffff0000;
+        }
+        for (i = 0; i < 4; i++) {
+            new_segs[i] = lduw_kernel(tss_base + (0x22 + i * 4));
+        }
+        new_ldt = lduw_kernel(tss_base + 0x2a);
+        new_segs[R_FS] = 0;
+        new_segs[R_GS] = 0;
+        new_trap = 0;
+    }
+    /* XXX: avoid a compiler warning, see
+     http://support.amd.com/us/Processor_TechDocs/24593.pdf
+     chapters 12.2.5 and 13.2.4 on how to implement TSS Trap bit */
+    (void)new_trap;
+
+    /* NOTE: we must avoid memory exceptions during the task switch,
+       so we make dummy accesses before */
+    /* XXX: it can still fail in some cases, so a bigger hack is
+       necessary to valid the TLB after having done the accesses */
+
+    v1 = ldub_kernel(env->tr.base);
+    v2 = ldub_kernel(env->tr.base + old_tss_limit_max);
+    stb_kernel(env->tr.base, v1);
+    stb_kernel(env->tr.base + old_tss_limit_max, v2);
+
+    /* clear busy bit (it is restartable) */
+    if (source == SWITCH_TSS_JMP || source == SWITCH_TSS_IRET) {
+        target_ulong ptr;
+        uint32_t e2;
+
+        ptr = env->gdt.base + (env->tr.selector & ~7);
+        e2 = ldl_kernel(ptr + 4);
+        e2 &= ~DESC_TSS_BUSY_MASK;
+        stl_kernel(ptr + 4, e2);
+    }
+    old_eflags = cpu_compute_eflags(env);
+    if (source == SWITCH_TSS_IRET) {
+        old_eflags &= ~NT_MASK;
+    }
+
+    /* save the current state in the old TSS */
+    if (type & 8) {
+        /* 32 bit */
+        stl_kernel(env->tr.base + 0x20, next_eip);
+        stl_kernel(env->tr.base + 0x24, old_eflags);
+        stl_kernel(env->tr.base + (0x28 + 0 * 4), EAX);
+        stl_kernel(env->tr.base + (0x28 + 1 * 4), ECX);
+        stl_kernel(env->tr.base + (0x28 + 2 * 4), EDX);
+        stl_kernel(env->tr.base + (0x28 + 3 * 4), EBX);
+        stl_kernel(env->tr.base + (0x28 + 4 * 4), ESP);
+        stl_kernel(env->tr.base + (0x28 + 5 * 4), EBP);
+        stl_kernel(env->tr.base + (0x28 + 6 * 4), ESI);
+        stl_kernel(env->tr.base + (0x28 + 7 * 4), EDI);
+        for (i = 0; i < 6; i++) {
+            stw_kernel(env->tr.base + (0x48 + i * 4), env->segs[i].selector);
+        }
+    } else {
+        /* 16 bit */
+        stw_kernel(env->tr.base + 0x0e, next_eip);
+        stw_kernel(env->tr.base + 0x10, old_eflags);
+        stw_kernel(env->tr.base + (0x12 + 0 * 2), EAX);
+        stw_kernel(env->tr.base + (0x12 + 1 * 2), ECX);
+        stw_kernel(env->tr.base + (0x12 + 2 * 2), EDX);
+        stw_kernel(env->tr.base + (0x12 + 3 * 2), EBX);
+        stw_kernel(env->tr.base + (0x12 + 4 * 2), ESP);
+        stw_kernel(env->tr.base + (0x12 + 5 * 2), EBP);
+        stw_kernel(env->tr.base + (0x12 + 6 * 2), ESI);
+        stw_kernel(env->tr.base + (0x12 + 7 * 2), EDI);
+        for (i = 0; i < 4; i++) {
+            stw_kernel(env->tr.base + (0x22 + i * 4), env->segs[i].selector);
+        }
+    }
+
+    /* now if an exception occurs, it will occurs in the next task
+       context */
+
+    if (source == SWITCH_TSS_CALL) {
+        stw_kernel(tss_base, env->tr.selector);
+        new_eflags |= NT_MASK;
+    }
+
+    /* set busy bit */
+    if (source == SWITCH_TSS_JMP || source == SWITCH_TSS_CALL) {
+        target_ulong ptr;
+        uint32_t e2;
+
+        ptr = env->gdt.base + (tss_selector & ~7);
+        e2 = ldl_kernel(ptr + 4);
+        e2 |= DESC_TSS_BUSY_MASK;
+        stl_kernel(ptr + 4, e2);
+    }
+
+    /* set the new CPU state */
+    /* from this point, any exception which occurs can give problems */
+    env->cr[0] |= CR0_TS_MASK;
+    env->hflags |= HF_TS_MASK;
+    env->tr.selector = tss_selector;
+    env->tr.base = tss_base;
+    env->tr.limit = tss_limit;
+    env->tr.flags = e2 & ~DESC_TSS_BUSY_MASK;
+
+    if ((type & 8) && (env->cr[0] & CR0_PG_MASK)) {
+        cpu_x86_update_cr3(env, new_cr3);
+    }
+
+    /* load all registers without an exception, then reload them with
+       possible exception */
+    env->eip = new_eip;
+    eflags_mask = TF_MASK | AC_MASK | ID_MASK |
+        IF_MASK | IOPL_MASK | VM_MASK | RF_MASK | NT_MASK;
+    if (!(type & 8)) {
+        eflags_mask &= 0xffff;
+    }
+    cpu_load_eflags(env, new_eflags, eflags_mask);
+    /* XXX: what to do in 16 bit case? */
+    EAX = new_regs[0];
+    ECX = new_regs[1];
+    EDX = new_regs[2];
+    EBX = new_regs[3];
+    ESP = new_regs[4];
+    EBP = new_regs[5];
+    ESI = new_regs[6];
+    EDI = new_regs[7];
+    if (new_eflags & VM_MASK) {
+        for (i = 0; i < 6; i++) {
+            load_seg_vm(i, new_segs[i]);
+        }
+        /* in vm86, CPL is always 3 */
+        cpu_x86_set_cpl(env, 3);
+    } else {
+        /* CPL is set the RPL of CS */
+        cpu_x86_set_cpl(env, new_segs[R_CS] & 3);
+        /* first just selectors as the rest may trigger exceptions */
+        for (i = 0; i < 6; i++) {
+            cpu_x86_load_seg_cache(env, i, new_segs[i], 0, 0, 0);
+        }
+    }
+
+    env->ldt.selector = new_ldt & ~4;
+    env->ldt.base = 0;
+    env->ldt.limit = 0;
+    env->ldt.flags = 0;
+
+    /* load the LDT */
+    if (new_ldt & 4) {
+        raise_exception_err(env, EXCP0A_TSS, new_ldt & 0xfffc);
+    }
+
+    if ((new_ldt & 0xfffc) != 0) {
+        dt = &env->gdt;
+        index = new_ldt & ~7;
+        if ((index + 7) > dt->limit) {
+            raise_exception_err(env, EXCP0A_TSS, new_ldt & 0xfffc);
+        }
+        ptr = dt->base + index;
+        e1 = ldl_kernel(ptr);
+        e2 = ldl_kernel(ptr + 4);
+        if ((e2 & DESC_S_MASK) || ((e2 >> DESC_TYPE_SHIFT) & 0xf) != 2) {
+            raise_exception_err(env, EXCP0A_TSS, new_ldt & 0xfffc);
+        }
+        if (!(e2 & DESC_P_MASK)) {
+            raise_exception_err(env, EXCP0A_TSS, new_ldt & 0xfffc);
+        }
+        load_seg_cache_raw_dt(&env->ldt, e1, e2);
+    }
+
+    /* load the segments */
+    if (!(new_eflags & VM_MASK)) {
+        tss_load_seg(R_CS, new_segs[R_CS]);
+        tss_load_seg(R_SS, new_segs[R_SS]);
+        tss_load_seg(R_ES, new_segs[R_ES]);
+        tss_load_seg(R_DS, new_segs[R_DS]);
+        tss_load_seg(R_FS, new_segs[R_FS]);
+        tss_load_seg(R_GS, new_segs[R_GS]);
+    }
+
+    /* check that EIP is in the CS segment limits */
+    if (new_eip > env->segs[R_CS].limit) {
+        /* XXX: different exception if CALL? */
+        raise_exception_err(env, EXCP0D_GPF, 0);
+    }
+
+#ifndef CONFIG_USER_ONLY
+    /* reset local breakpoints */
+    if (env->dr[7] & 0x55) {
+        for (i = 0; i < 4; i++) {
+            if (hw_breakpoint_enabled(env->dr[7], i) == 0x1) {
+                hw_breakpoint_remove(env, i);
+            }
+        }
+        env->dr[7] &= ~0x55;
+    }
+#endif
+}
+
+static inline unsigned int get_sp_mask(unsigned int e2)
+{
+    if (e2 & DESC_B_MASK) {
+        return 0xffffffff;
+    } else {
+        return 0xffff;
+    }
+}
+
+static int exception_has_error_code(int intno)
+{
+    switch (intno) {
+    case 8:
+    case 10:
+    case 11:
+    case 12:
+    case 13:
+    case 14:
+    case 17:
+        return 1;
+    }
+    return 0;
+}
+
+#ifdef TARGET_X86_64
+#define SET_ESP(val, sp_mask)                           \
+    do {                                                \
+        if ((sp_mask) == 0xffff) {                      \
+            ESP = (ESP & ~0xffff) | ((val) & 0xffff);   \
+        } else if ((sp_mask) == 0xffffffffLL) {         \
+            ESP = (uint32_t)(val);                      \
+        } else {                                        \
+            ESP = (val);                                \
+        }                                               \
+    } while (0)
+#else
+#define SET_ESP(val, sp_mask)                           \
+    do {                                                \
+        ESP = (ESP & ~(sp_mask)) | ((val) & (sp_mask)); \
+    } while (0)
+#endif
+
+/* in 64-bit machines, this can overflow. So this segment addition macro
+ * can be used to trim the value to 32-bit whenever needed */
+#define SEG_ADDL(ssp, sp, sp_mask) ((uint32_t)((ssp) + (sp & (sp_mask))))
+
+/* XXX: add a is_user flag to have proper security support */
+#define PUSHW(ssp, sp, sp_mask, val)                    \
+    {                                                   \
+        sp -= 2;                                        \
+        stw_kernel((ssp) + (sp & (sp_mask)), (val));    \
+    }
+
+#define PUSHL(ssp, sp, sp_mask, val)                                    \
+    {                                                                   \
+        sp -= 4;                                                        \
+        stl_kernel(SEG_ADDL(ssp, sp, sp_mask), (uint32_t)(val));        \
+    }
+
+#define POPW(ssp, sp, sp_mask, val)                     \
+    {                                                   \
+        val = lduw_kernel((ssp) + (sp & (sp_mask)));    \
+        sp += 2;                                        \
+    }
+
+#define POPL(ssp, sp, sp_mask, val)                             \
+    {                                                           \
+        val = (uint32_t)ldl_kernel(SEG_ADDL(ssp, sp, sp_mask)); \
+        sp += 4;                                                \
+    }
+
+/* protected mode interrupt */
+static void do_interrupt_protected(int intno, int is_int, int error_code,
+                                   unsigned int next_eip, int is_hw)
+{
+    SegmentCache *dt;
+    target_ulong ptr, ssp;
+    int type, dpl, selector, ss_dpl, cpl;
+    int has_error_code, new_stack, shift;
+    uint32_t e1, e2, offset, ss = 0, esp, ss_e1 = 0, ss_e2 = 0;
+    uint32_t old_eip, sp_mask;
+
+    has_error_code = 0;
+    if (!is_int && !is_hw) {
+        has_error_code = exception_has_error_code(intno);
+    }
+    if (is_int) {
+        old_eip = next_eip;
+    } else {
+        old_eip = env->eip;
+    }
+
+    dt = &env->idt;
+    if (intno * 8 + 7 > dt->limit) {
+        raise_exception_err(env, EXCP0D_GPF, intno * 8 + 2);
+    }
+    ptr = dt->base + intno * 8;
+    e1 = ldl_kernel(ptr);
+    e2 = ldl_kernel(ptr + 4);
+    /* check gate type */
+    type = (e2 >> DESC_TYPE_SHIFT) & 0x1f;
+    switch (type) {
+    case 5: /* task gate */
+        /* must do that check here to return the correct error code */
+        if (!(e2 & DESC_P_MASK)) {
+            raise_exception_err(env, EXCP0B_NOSEG, intno * 8 + 2);
+        }
+        switch_tss(intno * 8, e1, e2, SWITCH_TSS_CALL, old_eip);
+        if (has_error_code) {
+            int type;
+            uint32_t mask;
+
+            /* push the error code */
+            type = (env->tr.flags >> DESC_TYPE_SHIFT) & 0xf;
+            shift = type >> 3;
+            if (env->segs[R_SS].flags & DESC_B_MASK) {
+                mask = 0xffffffff;
+            } else {
+                mask = 0xffff;
+            }
+            esp = (ESP - (2 << shift)) & mask;
+            ssp = env->segs[R_SS].base + esp;
+            if (shift) {
+                stl_kernel(ssp, error_code);
+            } else {
+                stw_kernel(ssp, error_code);
+            }
+            SET_ESP(esp, mask);
+        }
+        return;
+    case 6: /* 286 interrupt gate */
+    case 7: /* 286 trap gate */
+    case 14: /* 386 interrupt gate */
+    case 15: /* 386 trap gate */
+        break;
+    default:
+        raise_exception_err(env, EXCP0D_GPF, intno * 8 + 2);
+        break;
+    }
+    dpl = (e2 >> DESC_DPL_SHIFT) & 3;
+    cpl = env->hflags & HF_CPL_MASK;
+    /* check privilege if software int */
+    if (is_int && dpl < cpl) {
+        raise_exception_err(env, EXCP0D_GPF, intno * 8 + 2);
+    }
+    /* check valid bit */
+    if (!(e2 & DESC_P_MASK)) {
+        raise_exception_err(env, EXCP0B_NOSEG, intno * 8 + 2);
+    }
+    selector = e1 >> 16;
+    offset = (e2 & 0xffff0000) | (e1 & 0x0000ffff);
+    if ((selector & 0xfffc) == 0) {
+        raise_exception_err(env, EXCP0D_GPF, 0);
+    }
+    if (load_segment(&e1, &e2, selector) != 0) {
+        raise_exception_err(env, EXCP0D_GPF, selector & 0xfffc);
+    }
+    if (!(e2 & DESC_S_MASK) || !(e2 & (DESC_CS_MASK))) {
+        raise_exception_err(env, EXCP0D_GPF, selector & 0xfffc);
+    }
+    dpl = (e2 >> DESC_DPL_SHIFT) & 3;
+    if (dpl > cpl) {
+        raise_exception_err(env, EXCP0D_GPF, selector & 0xfffc);
+    }
+    if (!(e2 & DESC_P_MASK)) {
+        raise_exception_err(env, EXCP0B_NOSEG, selector & 0xfffc);
+    }
+    if (!(e2 & DESC_C_MASK) && dpl < cpl) {
+        /* to inner privilege */
+        get_ss_esp_from_tss(&ss, &esp, dpl);
+        if ((ss & 0xfffc) == 0) {
+            raise_exception_err(env, EXCP0A_TSS, ss & 0xfffc);
+        }
+        if ((ss & 3) != dpl) {
+            raise_exception_err(env, EXCP0A_TSS, ss & 0xfffc);
+        }
+        if (load_segment(&ss_e1, &ss_e2, ss) != 0) {
+            raise_exception_err(env, EXCP0A_TSS, ss & 0xfffc);
+        }
+        ss_dpl = (ss_e2 >> DESC_DPL_SHIFT) & 3;
+        if (ss_dpl != dpl) {
+            raise_exception_err(env, EXCP0A_TSS, ss & 0xfffc);
+        }
+        if (!(ss_e2 & DESC_S_MASK) ||
+            (ss_e2 & DESC_CS_MASK) ||
+            !(ss_e2 & DESC_W_MASK)) {
+            raise_exception_err(env, EXCP0A_TSS, ss & 0xfffc);
+        }
+        if (!(ss_e2 & DESC_P_MASK)) {
+            raise_exception_err(env, EXCP0A_TSS, ss & 0xfffc);
+        }
+        new_stack = 1;
+        sp_mask = get_sp_mask(ss_e2);
+        ssp = get_seg_base(ss_e1, ss_e2);
+    } else if ((e2 & DESC_C_MASK) || dpl == cpl) {
+        /* to same privilege */
+        if (env->eflags & VM_MASK) {
+            raise_exception_err(env, EXCP0D_GPF, selector & 0xfffc);
+        }
+        new_stack = 0;
+        sp_mask = get_sp_mask(env->segs[R_SS].flags);
+        ssp = env->segs[R_SS].base;
+        esp = ESP;
+        dpl = cpl;
+    } else {
+        raise_exception_err(env, EXCP0D_GPF, selector & 0xfffc);
+        new_stack = 0; /* avoid warning */
+        sp_mask = 0; /* avoid warning */
+        ssp = 0; /* avoid warning */
+        esp = 0; /* avoid warning */
+    }
+
+    shift = type >> 3;
+
+#if 0
+    /* XXX: check that enough room is available */
+    push_size = 6 + (new_stack << 2) + (has_error_code << 1);
+    if (env->eflags & VM_MASK) {
+        push_size += 8;
+    }
+    push_size <<= shift;
+#endif
+    if (shift == 1) {
+        if (new_stack) {
+            if (env->eflags & VM_MASK) {
+                PUSHL(ssp, esp, sp_mask, env->segs[R_GS].selector);
+                PUSHL(ssp, esp, sp_mask, env->segs[R_FS].selector);
+                PUSHL(ssp, esp, sp_mask, env->segs[R_DS].selector);
+                PUSHL(ssp, esp, sp_mask, env->segs[R_ES].selector);
+            }
+            PUSHL(ssp, esp, sp_mask, env->segs[R_SS].selector);
+            PUSHL(ssp, esp, sp_mask, ESP);
+        }
+        PUSHL(ssp, esp, sp_mask, cpu_compute_eflags(env));
+        PUSHL(ssp, esp, sp_mask, env->segs[R_CS].selector);
+        PUSHL(ssp, esp, sp_mask, old_eip);
+        if (has_error_code) {
+            PUSHL(ssp, esp, sp_mask, error_code);
+        }
+    } else {
+        if (new_stack) {
+            if (env->eflags & VM_MASK) {
+                PUSHW(ssp, esp, sp_mask, env->segs[R_GS].selector);
+                PUSHW(ssp, esp, sp_mask, env->segs[R_FS].selector);
+                PUSHW(ssp, esp, sp_mask, env->segs[R_DS].selector);
+                PUSHW(ssp, esp, sp_mask, env->segs[R_ES].selector);
+            }
+            PUSHW(ssp, esp, sp_mask, env->segs[R_SS].selector);
+            PUSHW(ssp, esp, sp_mask, ESP);
+        }
+        PUSHW(ssp, esp, sp_mask, cpu_compute_eflags(env));
+        PUSHW(ssp, esp, sp_mask, env->segs[R_CS].selector);
+        PUSHW(ssp, esp, sp_mask, old_eip);
+        if (has_error_code) {
+            PUSHW(ssp, esp, sp_mask, error_code);
+        }
+    }
+
+    if (new_stack) {
+        if (env->eflags & VM_MASK) {
+            cpu_x86_load_seg_cache(env, R_ES, 0, 0, 0, 0);
+            cpu_x86_load_seg_cache(env, R_DS, 0, 0, 0, 0);
+            cpu_x86_load_seg_cache(env, R_FS, 0, 0, 0, 0);
+            cpu_x86_load_seg_cache(env, R_GS, 0, 0, 0, 0);
+        }
+        ss = (ss & ~3) | dpl;
+        cpu_x86_load_seg_cache(env, R_SS, ss,
+                               ssp, get_seg_limit(ss_e1, ss_e2), ss_e2);
+    }
+    SET_ESP(esp, sp_mask);
+
+    selector = (selector & ~3) | dpl;
+    cpu_x86_load_seg_cache(env, R_CS, selector,
+                   get_seg_base(e1, e2),
+                   get_seg_limit(e1, e2),
+                   e2);
+    cpu_x86_set_cpl(env, dpl);
+    env->eip = offset;
+
+    /* interrupt gate clear IF mask */
+    if ((type & 1) == 0) {
+        env->eflags &= ~IF_MASK;
+    }
+    env->eflags &= ~(TF_MASK | VM_MASK | RF_MASK | NT_MASK);
+}
+
+#ifdef TARGET_X86_64
+
+#define PUSHQ(sp, val)                          \
+    {                                           \
+        sp -= 8;                                \
+        stq_kernel(sp, (val));                  \
+    }
+
+#define POPQ(sp, val)                           \
+    {                                           \
+        val = ldq_kernel(sp);                   \
+        sp += 8;                                \
+    }
+
+static inline target_ulong get_rsp_from_tss(int level)
+{
+    int index;
+
+#if 0
+    printf("TR: base=" TARGET_FMT_lx " limit=%x\n",
+           env->tr.base, env->tr.limit);
+#endif
+
+    if (!(env->tr.flags & DESC_P_MASK)) {
+        cpu_abort(env, "invalid tss");
+    }
+    index = 8 * level + 4;
+    if ((index + 7) > env->tr.limit) {
+        raise_exception_err(env, EXCP0A_TSS, env->tr.selector & 0xfffc);
+    }
+    return ldq_kernel(env->tr.base + index);
+}
+
+/* 64 bit interrupt */
+static void do_interrupt64(int intno, int is_int, int error_code,
+                           target_ulong next_eip, int is_hw)
+{
+    SegmentCache *dt;
+    target_ulong ptr;
+    int type, dpl, selector, cpl, ist;
+    int has_error_code, new_stack;
+    uint32_t e1, e2, e3, ss;
+    target_ulong old_eip, esp, offset;
+
+    has_error_code = 0;
+    if (!is_int && !is_hw) {
+        has_error_code = exception_has_error_code(intno);
+    }
+    if (is_int) {
+        old_eip = next_eip;
+    } else {
+        old_eip = env->eip;
+    }
+
+    dt = &env->idt;
+    if (intno * 16 + 15 > dt->limit) {
+        raise_exception_err(env, EXCP0D_GPF, intno * 16 + 2);
+    }
+    ptr = dt->base + intno * 16;
+    e1 = ldl_kernel(ptr);
+    e2 = ldl_kernel(ptr + 4);
+    e3 = ldl_kernel(ptr + 8);
+    /* check gate type */
+    type = (e2 >> DESC_TYPE_SHIFT) & 0x1f;
+    switch (type) {
+    case 14: /* 386 interrupt gate */
+    case 15: /* 386 trap gate */
+        break;
+    default:
+        raise_exception_err(env, EXCP0D_GPF, intno * 16 + 2);
+        break;
+    }
+    dpl = (e2 >> DESC_DPL_SHIFT) & 3;
+    cpl = env->hflags & HF_CPL_MASK;
+    /* check privilege if software int */
+    if (is_int && dpl < cpl) {
+        raise_exception_err(env, EXCP0D_GPF, intno * 16 + 2);
+    }
+    /* check valid bit */
+    if (!(e2 & DESC_P_MASK)) {
+        raise_exception_err(env, EXCP0B_NOSEG, intno * 16 + 2);
+    }
+    selector = e1 >> 16;
+    offset = ((target_ulong)e3 << 32) | (e2 & 0xffff0000) | (e1 & 0x0000ffff);
+    ist = e2 & 7;
+    if ((selector & 0xfffc) == 0) {
+        raise_exception_err(env, EXCP0D_GPF, 0);
+    }
+
+    if (load_segment(&e1, &e2, selector) != 0) {
+        raise_exception_err(env, EXCP0D_GPF, selector & 0xfffc);
+    }
+    if (!(e2 & DESC_S_MASK) || !(e2 & (DESC_CS_MASK))) {
+        raise_exception_err(env, EXCP0D_GPF, selector & 0xfffc);
+    }
+    dpl = (e2 >> DESC_DPL_SHIFT) & 3;
+    if (dpl > cpl) {
+        raise_exception_err(env, EXCP0D_GPF, selector & 0xfffc);
+    }
+    if (!(e2 & DESC_P_MASK)) {
+        raise_exception_err(env, EXCP0B_NOSEG, selector & 0xfffc);
+    }
+    if (!(e2 & DESC_L_MASK) || (e2 & DESC_B_MASK)) {
+        raise_exception_err(env, EXCP0D_GPF, selector & 0xfffc);
+    }
+    if ((!(e2 & DESC_C_MASK) && dpl < cpl) || ist != 0) {
+        /* to inner privilege */
+        if (ist != 0) {
+            esp = get_rsp_from_tss(ist + 3);
+        } else {
+            esp = get_rsp_from_tss(dpl);
+        }
+        esp &= ~0xfLL; /* align stack */
+        ss = 0;
+        new_stack = 1;
+    } else if ((e2 & DESC_C_MASK) || dpl == cpl) {
+        /* to same privilege */
+        if (env->eflags & VM_MASK) {
+            raise_exception_err(env, EXCP0D_GPF, selector & 0xfffc);
+        }
+        new_stack = 0;
+        if (ist != 0) {
+            esp = get_rsp_from_tss(ist + 3);
+        } else {
+            esp = ESP;
+        }
+        esp &= ~0xfLL; /* align stack */
+        dpl = cpl;
+    } else {
+        raise_exception_err(env, EXCP0D_GPF, selector & 0xfffc);
+        new_stack = 0; /* avoid warning */
+        esp = 0; /* avoid warning */
+    }
+
+    PUSHQ(esp, env->segs[R_SS].selector);
+    PUSHQ(esp, ESP);
+    PUSHQ(esp, cpu_compute_eflags(env));
+    PUSHQ(esp, env->segs[R_CS].selector);
+    PUSHQ(esp, old_eip);
+    if (has_error_code) {
+        PUSHQ(esp, error_code);
+    }
+
+    if (new_stack) {
+        ss = 0 | dpl;
+        cpu_x86_load_seg_cache(env, R_SS, ss, 0, 0, 0);
+    }
+    ESP = esp;
+
+    selector = (selector & ~3) | dpl;
+    cpu_x86_load_seg_cache(env, R_CS, selector,
+                   get_seg_base(e1, e2),
+                   get_seg_limit(e1, e2),
+                   e2);
+    cpu_x86_set_cpl(env, dpl);
+    env->eip = offset;
+
+    /* interrupt gate clear IF mask */
+    if ((type & 1) == 0) {
+        env->eflags &= ~IF_MASK;
+    }
+    env->eflags &= ~(TF_MASK | VM_MASK | RF_MASK | NT_MASK);
+}
+#endif
+
+#ifdef TARGET_X86_64
+#if defined(CONFIG_USER_ONLY)
+void helper_syscall(int next_eip_addend)
+{
+    env->exception_index = EXCP_SYSCALL;
+    env->exception_next_eip = env->eip + next_eip_addend;
+    cpu_loop_exit(env);
+}
+#else
+void helper_syscall(int next_eip_addend)
+{
+    int selector;
+
+    if (!(env->efer & MSR_EFER_SCE)) {
+        raise_exception_err(env, EXCP06_ILLOP, 0);
+    }
+    selector = (env->star >> 32) & 0xffff;
+    if (env->hflags & HF_LMA_MASK) {
+        int code64;
+
+        ECX = env->eip + next_eip_addend;
+        env->regs[11] = cpu_compute_eflags(env);
+
+        code64 = env->hflags & HF_CS64_MASK;
+
+        cpu_x86_set_cpl(env, 0);
+        cpu_x86_load_seg_cache(env, R_CS, selector & 0xfffc,
+                           0, 0xffffffff,
+                               DESC_G_MASK | DESC_P_MASK |
+                               DESC_S_MASK |
+                               DESC_CS_MASK | DESC_R_MASK | DESC_A_MASK |
+                               DESC_L_MASK);
+        cpu_x86_load_seg_cache(env, R_SS, (selector + 8) & 0xfffc,
+                               0, 0xffffffff,
+                               DESC_G_MASK | DESC_B_MASK | DESC_P_MASK |
+                               DESC_S_MASK |
+                               DESC_W_MASK | DESC_A_MASK);
+        env->eflags &= ~env->fmask;
+        cpu_load_eflags(env, env->eflags, 0);
+        if (code64) {
+            env->eip = env->lstar;
+        } else {
+            env->eip = env->cstar;
+        }
+    } else {
+        ECX = (uint32_t)(env->eip + next_eip_addend);
+
+        cpu_x86_set_cpl(env, 0);
+        cpu_x86_load_seg_cache(env, R_CS, selector & 0xfffc,
+                           0, 0xffffffff,
+                               DESC_G_MASK | DESC_B_MASK | DESC_P_MASK |
+                               DESC_S_MASK |
+                               DESC_CS_MASK | DESC_R_MASK | DESC_A_MASK);
+        cpu_x86_load_seg_cache(env, R_SS, (selector + 8) & 0xfffc,
+                               0, 0xffffffff,
+                               DESC_G_MASK | DESC_B_MASK | DESC_P_MASK |
+                               DESC_S_MASK |
+                               DESC_W_MASK | DESC_A_MASK);
+        env->eflags &= ~(IF_MASK | RF_MASK | VM_MASK);
+        env->eip = (uint32_t)env->star;
+    }
+}
+#endif
+#endif
+
+#ifdef TARGET_X86_64
+void helper_sysret(int dflag)
+{
+    int cpl, selector;
+
+    if (!(env->efer & MSR_EFER_SCE)) {
+        raise_exception_err(env, EXCP06_ILLOP, 0);
+    }
+    cpl = env->hflags & HF_CPL_MASK;
+    if (!(env->cr[0] & CR0_PE_MASK) || cpl != 0) {
+        raise_exception_err(env, EXCP0D_GPF, 0);
+    }
+    selector = (env->star >> 48) & 0xffff;
+    if (env->hflags & HF_LMA_MASK) {
+        if (dflag == 2) {
+            cpu_x86_load_seg_cache(env, R_CS, (selector + 16) | 3,
+                                   0, 0xffffffff,
+                                   DESC_G_MASK | DESC_P_MASK |
+                                   DESC_S_MASK | (3 << DESC_DPL_SHIFT) |
+                                   DESC_CS_MASK | DESC_R_MASK | DESC_A_MASK |
+                                   DESC_L_MASK);
+            env->eip = ECX;
+        } else {
+            cpu_x86_load_seg_cache(env, R_CS, selector | 3,
+                                   0, 0xffffffff,
+                                   DESC_G_MASK | DESC_B_MASK | DESC_P_MASK |
+                                   DESC_S_MASK | (3 << DESC_DPL_SHIFT) |
+                                   DESC_CS_MASK | DESC_R_MASK | DESC_A_MASK);
+            env->eip = (uint32_t)ECX;
+        }
+        cpu_x86_load_seg_cache(env, R_SS, selector + 8,
+                               0, 0xffffffff,
+                               DESC_G_MASK | DESC_B_MASK | DESC_P_MASK |
+                               DESC_S_MASK | (3 << DESC_DPL_SHIFT) |
+                               DESC_W_MASK | DESC_A_MASK);
+        cpu_load_eflags(env, (uint32_t)(env->regs[11]), TF_MASK | AC_MASK
+                        | ID_MASK | IF_MASK | IOPL_MASK | VM_MASK | RF_MASK |
+                        NT_MASK);
+        cpu_x86_set_cpl(env, 3);
+    } else {
+        cpu_x86_load_seg_cache(env, R_CS, selector | 3,
+                               0, 0xffffffff,
+                               DESC_G_MASK | DESC_B_MASK | DESC_P_MASK |
+                               DESC_S_MASK | (3 << DESC_DPL_SHIFT) |
+                               DESC_CS_MASK | DESC_R_MASK | DESC_A_MASK);
+        env->eip = (uint32_t)ECX;
+        cpu_x86_load_seg_cache(env, R_SS, selector + 8,
+                               0, 0xffffffff,
+                               DESC_G_MASK | DESC_B_MASK | DESC_P_MASK |
+                               DESC_S_MASK | (3 << DESC_DPL_SHIFT) |
+                               DESC_W_MASK | DESC_A_MASK);
+        env->eflags |= IF_MASK;
+        cpu_x86_set_cpl(env, 3);
+    }
+}
+#endif
+
+/* real mode interrupt */
+static void do_interrupt_real(int intno, int is_int, int error_code,
+                              unsigned int next_eip)
+{
+    SegmentCache *dt;
+    target_ulong ptr, ssp;
+    int selector;
+    uint32_t offset, esp;
+    uint32_t old_cs, old_eip;
+
+    /* real mode (simpler!) */
+    dt = &env->idt;
+    if (intno * 4 + 3 > dt->limit) {
+        raise_exception_err(env, EXCP0D_GPF, intno * 8 + 2);
+    }
+    ptr = dt->base + intno * 4;
+    offset = lduw_kernel(ptr);
+    selector = lduw_kernel(ptr + 2);
+    esp = ESP;
+    ssp = env->segs[R_SS].base;
+    if (is_int) {
+        old_eip = next_eip;
+    } else {
+        old_eip = env->eip;
+    }
+    old_cs = env->segs[R_CS].selector;
+    /* XXX: use SS segment size? */
+    PUSHW(ssp, esp, 0xffff, cpu_compute_eflags(env));
+    PUSHW(ssp, esp, 0xffff, old_cs);
+    PUSHW(ssp, esp, 0xffff, old_eip);
+
+    /* update processor state */
+    ESP = (ESP & ~0xffff) | (esp & 0xffff);
+    env->eip = offset;
+    env->segs[R_CS].selector = selector;
+    env->segs[R_CS].base = (selector << 4);
+    env->eflags &= ~(IF_MASK | TF_MASK | AC_MASK | RF_MASK);
+}
+
+#if defined(CONFIG_USER_ONLY)
+/* fake user mode interrupt */
+static void do_interrupt_user(int intno, int is_int, int error_code,
+                              target_ulong next_eip)
+{
+    SegmentCache *dt;
+    target_ulong ptr;
+    int dpl, cpl, shift;
+    uint32_t e2;
+
+    dt = &env->idt;
+    if (env->hflags & HF_LMA_MASK) {
+        shift = 4;
+    } else {
+        shift = 3;
+    }
+    ptr = dt->base + (intno << shift);
+    e2 = ldl_kernel(ptr + 4);
+
+    dpl = (e2 >> DESC_DPL_SHIFT) & 3;
+    cpl = env->hflags & HF_CPL_MASK;
+    /* check privilege if software int */
+    if (is_int && dpl < cpl) {
+        raise_exception_err(env, EXCP0D_GPF, (intno << shift) + 2);
+    }
+
+    /* Since we emulate only user space, we cannot do more than
+       exiting the emulation with the suitable exception and error
+       code */
+    if (is_int) {
+        EIP = next_eip;
+    }
+}
+
+#else
+
+static void handle_even_inj(int intno, int is_int, int error_code,
+                            int is_hw, int rm)
+{
+    uint32_t event_inj = ldl_phys(env->vm_vmcb + offsetof(struct vmcb,
+                                                          control.event_inj));
+
+    if (!(event_inj & SVM_EVTINJ_VALID)) {
+        int type;
+
+        if (is_int) {
+            type = SVM_EVTINJ_TYPE_SOFT;
+        } else {
+            type = SVM_EVTINJ_TYPE_EXEPT;
+        }
+        event_inj = intno | type | SVM_EVTINJ_VALID;
+        if (!rm && exception_has_error_code(intno)) {
+            event_inj |= SVM_EVTINJ_VALID_ERR;
+            stl_phys(env->vm_vmcb + offsetof(struct vmcb,
+                                             control.event_inj_err),
+                     error_code);
+        }
+        stl_phys(env->vm_vmcb + offsetof(struct vmcb, control.event_inj),
+                 event_inj);
+    }
+}
+#endif
+
+/*
+ * Begin execution of an interruption. is_int is TRUE if coming from
+ * the int instruction. next_eip is the EIP value AFTER the interrupt
+ * instruction. It is only relevant if is_int is TRUE.
+ */
+static void do_interrupt_all(int intno, int is_int, int error_code,
+                             target_ulong next_eip, int is_hw)
+{
+    if (qemu_loglevel_mask(CPU_LOG_INT)) {
+        if ((env->cr[0] & CR0_PE_MASK)) {
+            static int count;
+
+            qemu_log("%6d: v=%02x e=%04x i=%d cpl=%d IP=%04x:" TARGET_FMT_lx
+                     " pc=" TARGET_FMT_lx " SP=%04x:" TARGET_FMT_lx,
+                     count, intno, error_code, is_int,
+                     env->hflags & HF_CPL_MASK,
+                     env->segs[R_CS].selector, EIP,
+                     (int)env->segs[R_CS].base + EIP,
+                     env->segs[R_SS].selector, ESP);
+            if (intno == 0x0e) {
+                qemu_log(" CR2=" TARGET_FMT_lx, env->cr[2]);
+            } else {
+                qemu_log(" EAX=" TARGET_FMT_lx, EAX);
+            }
+            qemu_log("\n");
+            log_cpu_state(env, X86_DUMP_CCOP);
+#if 0
+            {
+                int i;
+                target_ulong ptr;
+
+                qemu_log("       code=");
+                ptr = env->segs[R_CS].base + env->eip;
+                for (i = 0; i < 16; i++) {
+                    qemu_log(" %02x", ldub(ptr + i));
+                }
+                qemu_log("\n");
+            }
+#endif
+            count++;
+        }
+    }
+    if (env->cr[0] & CR0_PE_MASK) {
+#if !defined(CONFIG_USER_ONLY)
+        if (env->hflags & HF_SVMI_MASK) {
+            handle_even_inj(intno, is_int, error_code, is_hw, 0);
+        }
+#endif
+#ifdef TARGET_X86_64
+        if (env->hflags & HF_LMA_MASK) {
+            do_interrupt64(intno, is_int, error_code, next_eip, is_hw);
+        } else
+#endif
+        {
+            do_interrupt_protected(intno, is_int, error_code, next_eip, is_hw);
+        }
+    } else {
+#if !defined(CONFIG_USER_ONLY)
+        if (env->hflags & HF_SVMI_MASK) {
+            handle_even_inj(intno, is_int, error_code, is_hw, 1);
+        }
+#endif
+        do_interrupt_real(intno, is_int, error_code, next_eip);
+    }
+
+#if !defined(CONFIG_USER_ONLY)
+    if (env->hflags & HF_SVMI_MASK) {
+        uint32_t event_inj = ldl_phys(env->vm_vmcb +
+                                      offsetof(struct vmcb,
+                                               control.event_inj));
+
+        stl_phys(env->vm_vmcb + offsetof(struct vmcb, control.event_inj),
+                 event_inj & ~SVM_EVTINJ_VALID);
+    }
+#endif
+}
+
+void do_interrupt(CPUX86State *env1)
+{
+    CPUX86State *saved_env;
+
+    saved_env = env;
+    env = env1;
+#if defined(CONFIG_USER_ONLY)
+    /* if user mode only, we simulate a fake exception
+       which will be handled outside the cpu execution
+       loop */
+    do_interrupt_user(env->exception_index,
+                      env->exception_is_int,
+                      env->error_code,
+                      env->exception_next_eip);
+    /* successfully delivered */
+    env->old_exception = -1;
+#else
+    /* simulate a real cpu exception. On i386, it can
+       trigger new exceptions, but we do not handle
+       double or triple faults yet. */
+    do_interrupt_all(env->exception_index,
+                     env->exception_is_int,
+                     env->error_code,
+                     env->exception_next_eip, 0);
+    /* successfully delivered */
+    env->old_exception = -1;
+#endif
+    env = saved_env;
+}
+
+void do_interrupt_x86_hardirq(CPUX86State *env1, int intno, int is_hw)
+{
+    CPUX86State *saved_env;
+
+    saved_env = env;
+    env = env1;
+    do_interrupt_all(intno, 0, 0, 0, is_hw);
+    env = saved_env;
+}
+
+void helper_enter_level(int level, int data32, target_ulong t1)
+{
+    target_ulong ssp;
+    uint32_t esp_mask, esp, ebp;
+
+    esp_mask = get_sp_mask(env->segs[R_SS].flags);
+    ssp = env->segs[R_SS].base;
+    ebp = EBP;
+    esp = ESP;
+    if (data32) {
+        /* 32 bit */
+        esp -= 4;
+        while (--level) {
+            esp -= 4;
+            ebp -= 4;
+            stl(ssp + (esp & esp_mask), ldl(ssp + (ebp & esp_mask)));
+        }
+        esp -= 4;
+        stl(ssp + (esp & esp_mask), t1);
+    } else {
+        /* 16 bit */
+        esp -= 2;
+        while (--level) {
+            esp -= 2;
+            ebp -= 2;
+            stw(ssp + (esp & esp_mask), lduw(ssp + (ebp & esp_mask)));
+        }
+        esp -= 2;
+        stw(ssp + (esp & esp_mask), t1);
+    }
+}
+
+#ifdef TARGET_X86_64
+void helper_enter64_level(int level, int data64, target_ulong t1)
+{
+    target_ulong esp, ebp;
+
+    ebp = EBP;
+    esp = ESP;
+
+    if (data64) {
+        /* 64 bit */
+        esp -= 8;
+        while (--level) {
+            esp -= 8;
+            ebp -= 8;
+            stq(esp, ldq(ebp));
+        }
+        esp -= 8;
+        stq(esp, t1);
+    } else {
+        /* 16 bit */
+        esp -= 2;
+        while (--level) {
+            esp -= 2;
+            ebp -= 2;
+            stw(esp, lduw(ebp));
+        }
+        esp -= 2;
+        stw(esp, t1);
+    }
+}
+#endif
+
+void helper_lldt(int selector)
+{
+    SegmentCache *dt;
+    uint32_t e1, e2;
+    int index, entry_limit;
+    target_ulong ptr;
+
+    selector &= 0xffff;
+    if ((selector & 0xfffc) == 0) {
+        /* XXX: NULL selector case: invalid LDT */
+        env->ldt.base = 0;
+        env->ldt.limit = 0;
+    } else {
+        if (selector & 0x4) {
+            raise_exception_err(env, EXCP0D_GPF, selector & 0xfffc);
+        }
+        dt = &env->gdt;
+        index = selector & ~7;
+#ifdef TARGET_X86_64
+        if (env->hflags & HF_LMA_MASK) {
+            entry_limit = 15;
+        } else
+#endif
+        {
+            entry_limit = 7;
+        }
+        if ((index + entry_limit) > dt->limit) {
+            raise_exception_err(env, EXCP0D_GPF, selector & 0xfffc);
+        }
+        ptr = dt->base + index;
+        e1 = ldl_kernel(ptr);
+        e2 = ldl_kernel(ptr + 4);
+        if ((e2 & DESC_S_MASK) || ((e2 >> DESC_TYPE_SHIFT) & 0xf) != 2) {
+            raise_exception_err(env, EXCP0D_GPF, selector & 0xfffc);
+        }
+        if (!(e2 & DESC_P_MASK)) {
+            raise_exception_err(env, EXCP0B_NOSEG, selector & 0xfffc);
+        }
+#ifdef TARGET_X86_64
+        if (env->hflags & HF_LMA_MASK) {
+            uint32_t e3;
+
+            e3 = ldl_kernel(ptr + 8);
+            load_seg_cache_raw_dt(&env->ldt, e1, e2);
+            env->ldt.base |= (target_ulong)e3 << 32;
+        } else
+#endif
+        {
+            load_seg_cache_raw_dt(&env->ldt, e1, e2);
+        }
+    }
+    env->ldt.selector = selector;
+}
+
+void helper_ltr(int selector)
+{
+    SegmentCache *dt;
+    uint32_t e1, e2;
+    int index, type, entry_limit;
+    target_ulong ptr;
+
+    selector &= 0xffff;
+    if ((selector & 0xfffc) == 0) {
+        /* NULL selector case: invalid TR */
+        env->tr.base = 0;
+        env->tr.limit = 0;
+        env->tr.flags = 0;
+    } else {
+        if (selector & 0x4) {
+            raise_exception_err(env, EXCP0D_GPF, selector & 0xfffc);
+        }
+        dt = &env->gdt;
+        index = selector & ~7;
+#ifdef TARGET_X86_64
+        if (env->hflags & HF_LMA_MASK) {
+            entry_limit = 15;
+        } else
+#endif
+        {
+            entry_limit = 7;
+        }
+        if ((index + entry_limit) > dt->limit) {
+            raise_exception_err(env, EXCP0D_GPF, selector & 0xfffc);
+        }
+        ptr = dt->base + index;
+        e1 = ldl_kernel(ptr);
+        e2 = ldl_kernel(ptr + 4);
+        type = (e2 >> DESC_TYPE_SHIFT) & 0xf;
+        if ((e2 & DESC_S_MASK) ||
+            (type != 1 && type != 9)) {
+            raise_exception_err(env, EXCP0D_GPF, selector & 0xfffc);
+        }
+        if (!(e2 & DESC_P_MASK)) {
+            raise_exception_err(env, EXCP0B_NOSEG, selector & 0xfffc);
+        }
+#ifdef TARGET_X86_64
+        if (env->hflags & HF_LMA_MASK) {
+            uint32_t e3, e4;
+
+            e3 = ldl_kernel(ptr + 8);
+            e4 = ldl_kernel(ptr + 12);
+            if ((e4 >> DESC_TYPE_SHIFT) & 0xf) {
+                raise_exception_err(env, EXCP0D_GPF, selector & 0xfffc);
+            }
+            load_seg_cache_raw_dt(&env->tr, e1, e2);
+            env->tr.base |= (target_ulong)e3 << 32;
+        } else
+#endif
+        {
+            load_seg_cache_raw_dt(&env->tr, e1, e2);
+        }
+        e2 |= DESC_TSS_BUSY_MASK;
+        stl_kernel(ptr + 4, e2);
+    }
+    env->tr.selector = selector;
+}
+
+/* only works if protected mode and not VM86. seg_reg must be != R_CS */
+void helper_load_seg(int seg_reg, int selector)
+{
+    uint32_t e1, e2;
+    int cpl, dpl, rpl;
+    SegmentCache *dt;
+    int index;
+    target_ulong ptr;
+
+    selector &= 0xffff;
+    cpl = env->hflags & HF_CPL_MASK;
+    if ((selector & 0xfffc) == 0) {
+        /* null selector case */
+        if (seg_reg == R_SS
+#ifdef TARGET_X86_64
+            && (!(env->hflags & HF_CS64_MASK) || cpl == 3)
+#endif
+            ) {
+            raise_exception_err(env, EXCP0D_GPF, 0);
+        }
+        cpu_x86_load_seg_cache(env, seg_reg, selector, 0, 0, 0);
+    } else {
+
+        if (selector & 0x4) {
+            dt = &env->ldt;
+        } else {
+            dt = &env->gdt;
+        }
+        index = selector & ~7;
+        if ((index + 7) > dt->limit) {
+            raise_exception_err(env, EXCP0D_GPF, selector & 0xfffc);
+        }
+        ptr = dt->base + index;
+        e1 = ldl_kernel(ptr);
+        e2 = ldl_kernel(ptr + 4);
+
+        if (!(e2 & DESC_S_MASK)) {
+            raise_exception_err(env, EXCP0D_GPF, selector & 0xfffc);
+        }
+        rpl = selector & 3;
+        dpl = (e2 >> DESC_DPL_SHIFT) & 3;
+        if (seg_reg == R_SS) {
+            /* must be writable segment */
+            if ((e2 & DESC_CS_MASK) || !(e2 & DESC_W_MASK)) {
+                raise_exception_err(env, EXCP0D_GPF, selector & 0xfffc);
+            }
+            if (rpl != cpl || dpl != cpl) {
+                raise_exception_err(env, EXCP0D_GPF, selector & 0xfffc);
+            }
+        } else {
+            /* must be readable segment */
+            if ((e2 & (DESC_CS_MASK | DESC_R_MASK)) == DESC_CS_MASK) {
+                raise_exception_err(env, EXCP0D_GPF, selector & 0xfffc);
+            }
+
+            if (!(e2 & DESC_CS_MASK) || !(e2 & DESC_C_MASK)) {
+                /* if not conforming code, test rights */
+                if (dpl < cpl || dpl < rpl) {
+                    raise_exception_err(env, EXCP0D_GPF, selector & 0xfffc);
+                }
+            }
+        }
+
+        if (!(e2 & DESC_P_MASK)) {
+            if (seg_reg == R_SS) {
+                raise_exception_err(env, EXCP0C_STACK, selector & 0xfffc);
+            } else {
+                raise_exception_err(env, EXCP0B_NOSEG, selector & 0xfffc);
+            }
+        }
+
+        /* set the access bit if not already set */
+        if (!(e2 & DESC_A_MASK)) {
+            e2 |= DESC_A_MASK;
+            stl_kernel(ptr + 4, e2);
+        }
+
+        cpu_x86_load_seg_cache(env, seg_reg, selector,
+                       get_seg_base(e1, e2),
+                       get_seg_limit(e1, e2),
+                       e2);
+#if 0
+        qemu_log("load_seg: sel=0x%04x base=0x%08lx limit=0x%08lx flags=%08x\n",
+                selector, (unsigned long)sc->base, sc->limit, sc->flags);
+#endif
+    }
+}
+
+/* protected mode jump */
+void helper_ljmp_protected(int new_cs, target_ulong new_eip,
+                           int next_eip_addend)
+{
+    int gate_cs, type;
+    uint32_t e1, e2, cpl, dpl, rpl, limit;
+    target_ulong next_eip;
+
+    if ((new_cs & 0xfffc) == 0) {
+        raise_exception_err(env, EXCP0D_GPF, 0);
+    }
+    if (load_segment(&e1, &e2, new_cs) != 0) {
+        raise_exception_err(env, EXCP0D_GPF, new_cs & 0xfffc);
+    }
+    cpl = env->hflags & HF_CPL_MASK;
+    if (e2 & DESC_S_MASK) {
+        if (!(e2 & DESC_CS_MASK)) {
+            raise_exception_err(env, EXCP0D_GPF, new_cs & 0xfffc);
+        }
+        dpl = (e2 >> DESC_DPL_SHIFT) & 3;
+        if (e2 & DESC_C_MASK) {
+            /* conforming code segment */
+            if (dpl > cpl) {
+                raise_exception_err(env, EXCP0D_GPF, new_cs & 0xfffc);
+            }
+        } else {
+            /* non conforming code segment */
+            rpl = new_cs & 3;
+            if (rpl > cpl) {
+                raise_exception_err(env, EXCP0D_GPF, new_cs & 0xfffc);
+            }
+            if (dpl != cpl) {
+                raise_exception_err(env, EXCP0D_GPF, new_cs & 0xfffc);
+            }
+        }
+        if (!(e2 & DESC_P_MASK)) {
+            raise_exception_err(env, EXCP0B_NOSEG, new_cs & 0xfffc);
+        }
+        limit = get_seg_limit(e1, e2);
+        if (new_eip > limit &&
+            !(env->hflags & HF_LMA_MASK) && !(e2 & DESC_L_MASK)) {
+            raise_exception_err(env, EXCP0D_GPF, new_cs & 0xfffc);
+        }
+        cpu_x86_load_seg_cache(env, R_CS, (new_cs & 0xfffc) | cpl,
+                       get_seg_base(e1, e2), limit, e2);
+        EIP = new_eip;
+    } else {
+        /* jump to call or task gate */
+        dpl = (e2 >> DESC_DPL_SHIFT) & 3;
+        rpl = new_cs & 3;
+        cpl = env->hflags & HF_CPL_MASK;
+        type = (e2 >> DESC_TYPE_SHIFT) & 0xf;
+        switch (type) {
+        case 1: /* 286 TSS */
+        case 9: /* 386 TSS */
+        case 5: /* task gate */
+            if (dpl < cpl || dpl < rpl) {
+                raise_exception_err(env, EXCP0D_GPF, new_cs & 0xfffc);
+            }
+            next_eip = env->eip + next_eip_addend;
+            switch_tss(new_cs, e1, e2, SWITCH_TSS_JMP, next_eip);
+            CC_OP = CC_OP_EFLAGS;
+            break;
+        case 4: /* 286 call gate */
+        case 12: /* 386 call gate */
+            if ((dpl < cpl) || (dpl < rpl)) {
+                raise_exception_err(env, EXCP0D_GPF, new_cs & 0xfffc);
+            }
+            if (!(e2 & DESC_P_MASK)) {
+                raise_exception_err(env, EXCP0B_NOSEG, new_cs & 0xfffc);
+            }
+            gate_cs = e1 >> 16;
+            new_eip = (e1 & 0xffff);
+            if (type == 12) {
+                new_eip |= (e2 & 0xffff0000);
+            }
+            if (load_segment(&e1, &e2, gate_cs) != 0) {
+                raise_exception_err(env, EXCP0D_GPF, gate_cs & 0xfffc);
+            }
+            dpl = (e2 >> DESC_DPL_SHIFT) & 3;
+            /* must be code segment */
+            if (((e2 & (DESC_S_MASK | DESC_CS_MASK)) !=
+                 (DESC_S_MASK | DESC_CS_MASK))) {
+                raise_exception_err(env, EXCP0D_GPF, gate_cs & 0xfffc);
+            }
+            if (((e2 & DESC_C_MASK) && (dpl > cpl)) ||
+                (!(e2 & DESC_C_MASK) && (dpl != cpl))) {
+                raise_exception_err(env, EXCP0D_GPF, gate_cs & 0xfffc);
+            }
+            if (!(e2 & DESC_P_MASK)) {
+                raise_exception_err(env, EXCP0D_GPF, gate_cs & 0xfffc);
+            }
+            limit = get_seg_limit(e1, e2);
+            if (new_eip > limit) {
+                raise_exception_err(env, EXCP0D_GPF, 0);
+            }
+            cpu_x86_load_seg_cache(env, R_CS, (gate_cs & 0xfffc) | cpl,
+                                   get_seg_base(e1, e2), limit, e2);
+            EIP = new_eip;
+            break;
+        default:
+            raise_exception_err(env, EXCP0D_GPF, new_cs & 0xfffc);
+            break;
+        }
+    }
+}
+
+/* real mode call */
+void helper_lcall_real(int new_cs, target_ulong new_eip1,
+                       int shift, int next_eip)
+{
+    int new_eip;
+    uint32_t esp, esp_mask;
+    target_ulong ssp;
+
+    new_eip = new_eip1;
+    esp = ESP;
+    esp_mask = get_sp_mask(env->segs[R_SS].flags);
+    ssp = env->segs[R_SS].base;
+    if (shift) {
+        PUSHL(ssp, esp, esp_mask, env->segs[R_CS].selector);
+        PUSHL(ssp, esp, esp_mask, next_eip);
+    } else {
+        PUSHW(ssp, esp, esp_mask, env->segs[R_CS].selector);
+        PUSHW(ssp, esp, esp_mask, next_eip);
+    }
+
+    SET_ESP(esp, esp_mask);
+    env->eip = new_eip;
+    env->segs[R_CS].selector = new_cs;
+    env->segs[R_CS].base = (new_cs << 4);
+}
+
+/* protected mode call */
+void helper_lcall_protected(int new_cs, target_ulong new_eip,
+                            int shift, int next_eip_addend)
+{
+    int new_stack, i;
+    uint32_t e1, e2, cpl, dpl, rpl, selector, offset, param_count;
+    uint32_t ss = 0, ss_e1 = 0, ss_e2 = 0, sp, type, ss_dpl, sp_mask;
+    uint32_t val, limit, old_sp_mask;
+    target_ulong ssp, old_ssp, next_eip;
+
+    next_eip = env->eip + next_eip_addend;
+    LOG_PCALL("lcall %04x:%08x s=%d\n", new_cs, (uint32_t)new_eip, shift);
+    LOG_PCALL_STATE(env);
+    if ((new_cs & 0xfffc) == 0) {
+        raise_exception_err(env, EXCP0D_GPF, 0);
+    }
+    if (load_segment(&e1, &e2, new_cs) != 0) {
+        raise_exception_err(env, EXCP0D_GPF, new_cs & 0xfffc);
+    }
+    cpl = env->hflags & HF_CPL_MASK;
+    LOG_PCALL("desc=%08x:%08x\n", e1, e2);
+    if (e2 & DESC_S_MASK) {
+        if (!(e2 & DESC_CS_MASK)) {
+            raise_exception_err(env, EXCP0D_GPF, new_cs & 0xfffc);
+        }
+        dpl = (e2 >> DESC_DPL_SHIFT) & 3;
+        if (e2 & DESC_C_MASK) {
+            /* conforming code segment */
+            if (dpl > cpl) {
+                raise_exception_err(env, EXCP0D_GPF, new_cs & 0xfffc);
+            }
+        } else {
+            /* non conforming code segment */
+            rpl = new_cs & 3;
+            if (rpl > cpl) {
+                raise_exception_err(env, EXCP0D_GPF, new_cs & 0xfffc);
+            }
+            if (dpl != cpl) {
+                raise_exception_err(env, EXCP0D_GPF, new_cs & 0xfffc);
+            }
+        }
+        if (!(e2 & DESC_P_MASK)) {
+            raise_exception_err(env, EXCP0B_NOSEG, new_cs & 0xfffc);
+        }
+
+#ifdef TARGET_X86_64
+        /* XXX: check 16/32 bit cases in long mode */
+        if (shift == 2) {
+            target_ulong rsp;
+
+            /* 64 bit case */
+            rsp = ESP;
+            PUSHQ(rsp, env->segs[R_CS].selector);
+            PUSHQ(rsp, next_eip);
+            /* from this point, not restartable */
+            ESP = rsp;
+            cpu_x86_load_seg_cache(env, R_CS, (new_cs & 0xfffc) | cpl,
+                                   get_seg_base(e1, e2),
+                                   get_seg_limit(e1, e2), e2);
+            EIP = new_eip;
+        } else
+#endif
+        {
+            sp = ESP;
+            sp_mask = get_sp_mask(env->segs[R_SS].flags);
+            ssp = env->segs[R_SS].base;
+            if (shift) {
+                PUSHL(ssp, sp, sp_mask, env->segs[R_CS].selector);
+                PUSHL(ssp, sp, sp_mask, next_eip);
+            } else {
+                PUSHW(ssp, sp, sp_mask, env->segs[R_CS].selector);
+                PUSHW(ssp, sp, sp_mask, next_eip);
+            }
+
+            limit = get_seg_limit(e1, e2);
+            if (new_eip > limit) {
+                raise_exception_err(env, EXCP0D_GPF, new_cs & 0xfffc);
+            }
+            /* from this point, not restartable */
+            SET_ESP(sp, sp_mask);
+            cpu_x86_load_seg_cache(env, R_CS, (new_cs & 0xfffc) | cpl,
+                                   get_seg_base(e1, e2), limit, e2);
+            EIP = new_eip;
+        }
+    } else {
+        /* check gate type */
+        type = (e2 >> DESC_TYPE_SHIFT) & 0x1f;
+        dpl = (e2 >> DESC_DPL_SHIFT) & 3;
+        rpl = new_cs & 3;
+        switch (type) {
+        case 1: /* available 286 TSS */
+        case 9: /* available 386 TSS */
+        case 5: /* task gate */
+            if (dpl < cpl || dpl < rpl) {
+                raise_exception_err(env, EXCP0D_GPF, new_cs & 0xfffc);
+            }
+            switch_tss(new_cs, e1, e2, SWITCH_TSS_CALL, next_eip);
+            CC_OP = CC_OP_EFLAGS;
+            return;
+        case 4: /* 286 call gate */
+        case 12: /* 386 call gate */
+            break;
+        default:
+            raise_exception_err(env, EXCP0D_GPF, new_cs & 0xfffc);
+            break;
+        }
+        shift = type >> 3;
+
+        if (dpl < cpl || dpl < rpl) {
+            raise_exception_err(env, EXCP0D_GPF, new_cs & 0xfffc);
+        }
+        /* check valid bit */
+        if (!(e2 & DESC_P_MASK)) {
+            raise_exception_err(env, EXCP0B_NOSEG,  new_cs & 0xfffc);
+        }
+        selector = e1 >> 16;
+        offset = (e2 & 0xffff0000) | (e1 & 0x0000ffff);
+        param_count = e2 & 0x1f;
+        if ((selector & 0xfffc) == 0) {
+            raise_exception_err(env, EXCP0D_GPF, 0);
+        }
+
+        if (load_segment(&e1, &e2, selector) != 0) {
+            raise_exception_err(env, EXCP0D_GPF, selector & 0xfffc);
+        }
+        if (!(e2 & DESC_S_MASK) || !(e2 & (DESC_CS_MASK))) {
+            raise_exception_err(env, EXCP0D_GPF, selector & 0xfffc);
+        }
+        dpl = (e2 >> DESC_DPL_SHIFT) & 3;
+        if (dpl > cpl) {
+            raise_exception_err(env, EXCP0D_GPF, selector & 0xfffc);
+        }
+        if (!(e2 & DESC_P_MASK)) {
+            raise_exception_err(env, EXCP0B_NOSEG, selector & 0xfffc);
+        }
+
+        if (!(e2 & DESC_C_MASK) && dpl < cpl) {
+            /* to inner privilege */
+            get_ss_esp_from_tss(&ss, &sp, dpl);
+            LOG_PCALL("new ss:esp=%04x:%08x param_count=%d ESP=" TARGET_FMT_lx
+                      "\n",
+                      ss, sp, param_count, ESP);
+            if ((ss & 0xfffc) == 0) {
+                raise_exception_err(env, EXCP0A_TSS, ss & 0xfffc);
+            }
+            if ((ss & 3) != dpl) {
+                raise_exception_err(env, EXCP0A_TSS, ss & 0xfffc);
+            }
+            if (load_segment(&ss_e1, &ss_e2, ss) != 0) {
+                raise_exception_err(env, EXCP0A_TSS, ss & 0xfffc);
+            }
+            ss_dpl = (ss_e2 >> DESC_DPL_SHIFT) & 3;
+            if (ss_dpl != dpl) {
+                raise_exception_err(env, EXCP0A_TSS, ss & 0xfffc);
+            }
+            if (!(ss_e2 & DESC_S_MASK) ||
+                (ss_e2 & DESC_CS_MASK) ||
+                !(ss_e2 & DESC_W_MASK)) {
+                raise_exception_err(env, EXCP0A_TSS, ss & 0xfffc);
+            }
+            if (!(ss_e2 & DESC_P_MASK)) {
+                raise_exception_err(env, EXCP0A_TSS, ss & 0xfffc);
+            }
+
+            /* push_size = ((param_count * 2) + 8) << shift; */
+
+            old_sp_mask = get_sp_mask(env->segs[R_SS].flags);
+            old_ssp = env->segs[R_SS].base;
+
+            sp_mask = get_sp_mask(ss_e2);
+            ssp = get_seg_base(ss_e1, ss_e2);
+            if (shift) {
+                PUSHL(ssp, sp, sp_mask, env->segs[R_SS].selector);
+                PUSHL(ssp, sp, sp_mask, ESP);
+                for (i = param_count - 1; i >= 0; i--) {
+                    val = ldl_kernel(old_ssp + ((ESP + i * 4) & old_sp_mask));
+                    PUSHL(ssp, sp, sp_mask, val);
+                }
+            } else {
+                PUSHW(ssp, sp, sp_mask, env->segs[R_SS].selector);
+                PUSHW(ssp, sp, sp_mask, ESP);
+                for (i = param_count - 1; i >= 0; i--) {
+                    val = lduw_kernel(old_ssp + ((ESP + i * 2) & old_sp_mask));
+                    PUSHW(ssp, sp, sp_mask, val);
+                }
+            }
+            new_stack = 1;
+        } else {
+            /* to same privilege */
+            sp = ESP;
+            sp_mask = get_sp_mask(env->segs[R_SS].flags);
+            ssp = env->segs[R_SS].base;
+            /* push_size = (4 << shift); */
+            new_stack = 0;
+        }
+
+        if (shift) {
+            PUSHL(ssp, sp, sp_mask, env->segs[R_CS].selector);
+            PUSHL(ssp, sp, sp_mask, next_eip);
+        } else {
+            PUSHW(ssp, sp, sp_mask, env->segs[R_CS].selector);
+            PUSHW(ssp, sp, sp_mask, next_eip);
+        }
+
+        /* from this point, not restartable */
+
+        if (new_stack) {
+            ss = (ss & ~3) | dpl;
+            cpu_x86_load_seg_cache(env, R_SS, ss,
+                                   ssp,
+                                   get_seg_limit(ss_e1, ss_e2),
+                                   ss_e2);
+        }
+
+        selector = (selector & ~3) | dpl;
+        cpu_x86_load_seg_cache(env, R_CS, selector,
+                       get_seg_base(e1, e2),
+                       get_seg_limit(e1, e2),
+                       e2);
+        cpu_x86_set_cpl(env, dpl);
+        SET_ESP(sp, sp_mask);
+        EIP = offset;
+    }
+}
+
+/* real and vm86 mode iret */
+void helper_iret_real(int shift)
+{
+    uint32_t sp, new_cs, new_eip, new_eflags, sp_mask;
+    target_ulong ssp;
+    int eflags_mask;
+
+    sp_mask = 0xffff; /* XXXX: use SS segment size? */
+    sp = ESP;
+    ssp = env->segs[R_SS].base;
+    if (shift == 1) {
+        /* 32 bits */
+        POPL(ssp, sp, sp_mask, new_eip);
+        POPL(ssp, sp, sp_mask, new_cs);
+        new_cs &= 0xffff;
+        POPL(ssp, sp, sp_mask, new_eflags);
+    } else {
+        /* 16 bits */
+        POPW(ssp, sp, sp_mask, new_eip);
+        POPW(ssp, sp, sp_mask, new_cs);
+        POPW(ssp, sp, sp_mask, new_eflags);
+    }
+    ESP = (ESP & ~sp_mask) | (sp & sp_mask);
+    env->segs[R_CS].selector = new_cs;
+    env->segs[R_CS].base = (new_cs << 4);
+    env->eip = new_eip;
+    if (env->eflags & VM_MASK) {
+        eflags_mask = TF_MASK | AC_MASK | ID_MASK | IF_MASK | RF_MASK |
+            NT_MASK;
+    } else {
+        eflags_mask = TF_MASK | AC_MASK | ID_MASK | IF_MASK | IOPL_MASK |
+            RF_MASK | NT_MASK;
+    }
+    if (shift == 0) {
+        eflags_mask &= 0xffff;
+    }
+    cpu_load_eflags(env, new_eflags, eflags_mask);
+    env->hflags2 &= ~HF2_NMI_MASK;
+}
+
+static inline void validate_seg(int seg_reg, int cpl)
+{
+    int dpl;
+    uint32_t e2;
+
+    /* XXX: on x86_64, we do not want to nullify FS and GS because
+       they may still contain a valid base. I would be interested to
+       know how a real x86_64 CPU behaves */
+    if ((seg_reg == R_FS || seg_reg == R_GS) &&
+        (env->segs[seg_reg].selector & 0xfffc) == 0) {
+        return;
+    }
+
+    e2 = env->segs[seg_reg].flags;
+    dpl = (e2 >> DESC_DPL_SHIFT) & 3;
+    if (!(e2 & DESC_CS_MASK) || !(e2 & DESC_C_MASK)) {
+        /* data or non conforming code segment */
+        if (dpl < cpl) {
+            cpu_x86_load_seg_cache(env, seg_reg, 0, 0, 0, 0);
+        }
+    }
+}
+
+/* protected mode iret */
+static inline void helper_ret_protected(int shift, int is_iret, int addend)
+{
+    uint32_t new_cs, new_eflags, new_ss;
+    uint32_t new_es, new_ds, new_fs, new_gs;
+    uint32_t e1, e2, ss_e1, ss_e2;
+    int cpl, dpl, rpl, eflags_mask, iopl;
+    target_ulong ssp, sp, new_eip, new_esp, sp_mask;
+
+#ifdef TARGET_X86_64
+    if (shift == 2) {
+        sp_mask = -1;
+    } else
+#endif
+    {
+        sp_mask = get_sp_mask(env->segs[R_SS].flags);
+    }
+    sp = ESP;
+    ssp = env->segs[R_SS].base;
+    new_eflags = 0; /* avoid warning */
+#ifdef TARGET_X86_64
+    if (shift == 2) {
+        POPQ(sp, new_eip);
+        POPQ(sp, new_cs);
+        new_cs &= 0xffff;
+        if (is_iret) {
+            POPQ(sp, new_eflags);
+        }
+    } else
+#endif
+    {
+        if (shift == 1) {
+            /* 32 bits */
+            POPL(ssp, sp, sp_mask, new_eip);
+            POPL(ssp, sp, sp_mask, new_cs);
+            new_cs &= 0xffff;
+            if (is_iret) {
+                POPL(ssp, sp, sp_mask, new_eflags);
+                if (new_eflags & VM_MASK) {
+                    goto return_to_vm86;
+                }
+            }
+        } else {
+            /* 16 bits */
+            POPW(ssp, sp, sp_mask, new_eip);
+            POPW(ssp, sp, sp_mask, new_cs);
+            if (is_iret) {
+                POPW(ssp, sp, sp_mask, new_eflags);
+            }
+        }
+    }
+    LOG_PCALL("lret new %04x:" TARGET_FMT_lx " s=%d addend=0x%x\n",
+              new_cs, new_eip, shift, addend);
+    LOG_PCALL_STATE(env);
+    if ((new_cs & 0xfffc) == 0) {
+        raise_exception_err(env, EXCP0D_GPF, new_cs & 0xfffc);
+    }
+    if (load_segment(&e1, &e2, new_cs) != 0) {
+        raise_exception_err(env, EXCP0D_GPF, new_cs & 0xfffc);
+    }
+    if (!(e2 & DESC_S_MASK) ||
+        !(e2 & DESC_CS_MASK)) {
+        raise_exception_err(env, EXCP0D_GPF, new_cs & 0xfffc);
+    }
+    cpl = env->hflags & HF_CPL_MASK;
+    rpl = new_cs & 3;
+    if (rpl < cpl) {
+        raise_exception_err(env, EXCP0D_GPF, new_cs & 0xfffc);
+    }
+    dpl = (e2 >> DESC_DPL_SHIFT) & 3;
+    if (e2 & DESC_C_MASK) {
+        if (dpl > rpl) {
+            raise_exception_err(env, EXCP0D_GPF, new_cs & 0xfffc);
+        }
+    } else {
+        if (dpl != rpl) {
+            raise_exception_err(env, EXCP0D_GPF, new_cs & 0xfffc);
+        }
+    }
+    if (!(e2 & DESC_P_MASK)) {
+        raise_exception_err(env, EXCP0B_NOSEG, new_cs & 0xfffc);
+    }
+
+    sp += addend;
+    if (rpl == cpl && (!(env->hflags & HF_CS64_MASK) ||
+                       ((env->hflags & HF_CS64_MASK) && !is_iret))) {
+        /* return to same privilege level */
+        cpu_x86_load_seg_cache(env, R_CS, new_cs,
+                       get_seg_base(e1, e2),
+                       get_seg_limit(e1, e2),
+                       e2);
+    } else {
+        /* return to different privilege level */
+#ifdef TARGET_X86_64
+        if (shift == 2) {
+            POPQ(sp, new_esp);
+            POPQ(sp, new_ss);
+            new_ss &= 0xffff;
+        } else
+#endif
+        {
+            if (shift == 1) {
+                /* 32 bits */
+                POPL(ssp, sp, sp_mask, new_esp);
+                POPL(ssp, sp, sp_mask, new_ss);
+                new_ss &= 0xffff;
+            } else {
+                /* 16 bits */
+                POPW(ssp, sp, sp_mask, new_esp);
+                POPW(ssp, sp, sp_mask, new_ss);
+            }
+        }
+        LOG_PCALL("new ss:esp=%04x:" TARGET_FMT_lx "\n",
+                  new_ss, new_esp);
+        if ((new_ss & 0xfffc) == 0) {
+#ifdef TARGET_X86_64
+            /* NULL ss is allowed in long mode if cpl != 3 */
+            /* XXX: test CS64? */
+            if ((env->hflags & HF_LMA_MASK) && rpl != 3) {
+                cpu_x86_load_seg_cache(env, R_SS, new_ss,
+                                       0, 0xffffffff,
+                                       DESC_G_MASK | DESC_B_MASK | DESC_P_MASK |
+                                       DESC_S_MASK | (rpl << DESC_DPL_SHIFT) |
+                                       DESC_W_MASK | DESC_A_MASK);
+                ss_e2 = DESC_B_MASK; /* XXX: should not be needed? */
+            } else
+#endif
+            {
+                raise_exception_err(env, EXCP0D_GPF, 0);
+            }
+        } else {
+            if ((new_ss & 3) != rpl) {
+                raise_exception_err(env, EXCP0D_GPF, new_ss & 0xfffc);
+            }
+            if (load_segment(&ss_e1, &ss_e2, new_ss) != 0) {
+                raise_exception_err(env, EXCP0D_GPF, new_ss & 0xfffc);
+            }
+            if (!(ss_e2 & DESC_S_MASK) ||
+                (ss_e2 & DESC_CS_MASK) ||
+                !(ss_e2 & DESC_W_MASK)) {
+                raise_exception_err(env, EXCP0D_GPF, new_ss & 0xfffc);
+            }
+            dpl = (ss_e2 >> DESC_DPL_SHIFT) & 3;
+            if (dpl != rpl) {
+                raise_exception_err(env, EXCP0D_GPF, new_ss & 0xfffc);
+            }
+            if (!(ss_e2 & DESC_P_MASK)) {
+                raise_exception_err(env, EXCP0B_NOSEG, new_ss & 0xfffc);
+            }
+            cpu_x86_load_seg_cache(env, R_SS, new_ss,
+                                   get_seg_base(ss_e1, ss_e2),
+                                   get_seg_limit(ss_e1, ss_e2),
+                                   ss_e2);
+        }
+
+        cpu_x86_load_seg_cache(env, R_CS, new_cs,
+                       get_seg_base(e1, e2),
+                       get_seg_limit(e1, e2),
+                       e2);
+        cpu_x86_set_cpl(env, rpl);
+        sp = new_esp;
+#ifdef TARGET_X86_64
+        if (env->hflags & HF_CS64_MASK) {
+            sp_mask = -1;
+        } else
+#endif
+        {
+            sp_mask = get_sp_mask(ss_e2);
+        }
+
+        /* validate data segments */
+        validate_seg(R_ES, rpl);
+        validate_seg(R_DS, rpl);
+        validate_seg(R_FS, rpl);
+        validate_seg(R_GS, rpl);
+
+        sp += addend;
+    }
+    SET_ESP(sp, sp_mask);
+    env->eip = new_eip;
+    if (is_iret) {
+        /* NOTE: 'cpl' is the _old_ CPL */
+        eflags_mask = TF_MASK | AC_MASK | ID_MASK | RF_MASK | NT_MASK;
+        if (cpl == 0) {
+            eflags_mask |= IOPL_MASK;
+        }
+        iopl = (env->eflags >> IOPL_SHIFT) & 3;
+        if (cpl <= iopl) {
+            eflags_mask |= IF_MASK;
+        }
+        if (shift == 0) {
+            eflags_mask &= 0xffff;
+        }
+        cpu_load_eflags(env, new_eflags, eflags_mask);
+    }
+    return;
+
+ return_to_vm86:
+    POPL(ssp, sp, sp_mask, new_esp);
+    POPL(ssp, sp, sp_mask, new_ss);
+    POPL(ssp, sp, sp_mask, new_es);
+    POPL(ssp, sp, sp_mask, new_ds);
+    POPL(ssp, sp, sp_mask, new_fs);
+    POPL(ssp, sp, sp_mask, new_gs);
+
+    /* modify processor state */
+    cpu_load_eflags(env, new_eflags, TF_MASK | AC_MASK | ID_MASK |
+                    IF_MASK | IOPL_MASK | VM_MASK | NT_MASK | VIF_MASK |
+                    VIP_MASK);
+    load_seg_vm(R_CS, new_cs & 0xffff);
+    cpu_x86_set_cpl(env, 3);
+    load_seg_vm(R_SS, new_ss & 0xffff);
+    load_seg_vm(R_ES, new_es & 0xffff);
+    load_seg_vm(R_DS, new_ds & 0xffff);
+    load_seg_vm(R_FS, new_fs & 0xffff);
+    load_seg_vm(R_GS, new_gs & 0xffff);
+
+    env->eip = new_eip & 0xffff;
+    ESP = new_esp;
+}
+
+void helper_iret_protected(int shift, int next_eip)
+{
+    int tss_selector, type;
+    uint32_t e1, e2;
+
+    /* specific case for TSS */
+    if (env->eflags & NT_MASK) {
+#ifdef TARGET_X86_64
+        if (env->hflags & HF_LMA_MASK) {
+            raise_exception_err(env, EXCP0D_GPF, 0);
+        }
+#endif
+        tss_selector = lduw_kernel(env->tr.base + 0);
+        if (tss_selector & 4) {
+            raise_exception_err(env, EXCP0A_TSS, tss_selector & 0xfffc);
+        }
+        if (load_segment(&e1, &e2, tss_selector) != 0) {
+            raise_exception_err(env, EXCP0A_TSS, tss_selector & 0xfffc);
+        }
+        type = (e2 >> DESC_TYPE_SHIFT) & 0x17;
+        /* NOTE: we check both segment and busy TSS */
+        if (type != 3) {
+            raise_exception_err(env, EXCP0A_TSS, tss_selector & 0xfffc);
+        }
+        switch_tss(tss_selector, e1, e2, SWITCH_TSS_IRET, next_eip);
+    } else {
+        helper_ret_protected(shift, 1, 0);
+    }
+    env->hflags2 &= ~HF2_NMI_MASK;
+}
+
+void helper_lret_protected(int shift, int addend)
+{
+    helper_ret_protected(shift, 0, addend);
+}
+
+void helper_sysenter(void)
+{
+    if (env->sysenter_cs == 0) {
+        raise_exception_err(env, EXCP0D_GPF, 0);
+    }
+    env->eflags &= ~(VM_MASK | IF_MASK | RF_MASK);
+    cpu_x86_set_cpl(env, 0);
+
+#ifdef TARGET_X86_64
+    if (env->hflags & HF_LMA_MASK) {
+        cpu_x86_load_seg_cache(env, R_CS, env->sysenter_cs & 0xfffc,
+                               0, 0xffffffff,
+                               DESC_G_MASK | DESC_B_MASK | DESC_P_MASK |
+                               DESC_S_MASK |
+                               DESC_CS_MASK | DESC_R_MASK | DESC_A_MASK |
+                               DESC_L_MASK);
+    } else
+#endif
+    {
+        cpu_x86_load_seg_cache(env, R_CS, env->sysenter_cs & 0xfffc,
+                               0, 0xffffffff,
+                               DESC_G_MASK | DESC_B_MASK | DESC_P_MASK |
+                               DESC_S_MASK |
+                               DESC_CS_MASK | DESC_R_MASK | DESC_A_MASK);
+    }
+    cpu_x86_load_seg_cache(env, R_SS, (env->sysenter_cs + 8) & 0xfffc,
+                           0, 0xffffffff,
+                           DESC_G_MASK | DESC_B_MASK | DESC_P_MASK |
+                           DESC_S_MASK |
+                           DESC_W_MASK | DESC_A_MASK);
+    ESP = env->sysenter_esp;
+    EIP = env->sysenter_eip;
+}
+
+void helper_sysexit(int dflag)
+{
+    int cpl;
+
+    cpl = env->hflags & HF_CPL_MASK;
+    if (env->sysenter_cs == 0 || cpl != 0) {
+        raise_exception_err(env, EXCP0D_GPF, 0);
+    }
+    cpu_x86_set_cpl(env, 3);
+#ifdef TARGET_X86_64
+    if (dflag == 2) {
+        cpu_x86_load_seg_cache(env, R_CS, ((env->sysenter_cs + 32) & 0xfffc) |
+                               3, 0, 0xffffffff,
+                               DESC_G_MASK | DESC_B_MASK | DESC_P_MASK |
+                               DESC_S_MASK | (3 << DESC_DPL_SHIFT) |
+                               DESC_CS_MASK | DESC_R_MASK | DESC_A_MASK |
+                               DESC_L_MASK);
+        cpu_x86_load_seg_cache(env, R_SS, ((env->sysenter_cs + 40) & 0xfffc) |
+                               3, 0, 0xffffffff,
+                               DESC_G_MASK | DESC_B_MASK | DESC_P_MASK |
+                               DESC_S_MASK | (3 << DESC_DPL_SHIFT) |
+                               DESC_W_MASK | DESC_A_MASK);
+    } else
+#endif
+    {
+        cpu_x86_load_seg_cache(env, R_CS, ((env->sysenter_cs + 16) & 0xfffc) |
+                               3, 0, 0xffffffff,
+                               DESC_G_MASK | DESC_B_MASK | DESC_P_MASK |
+                               DESC_S_MASK | (3 << DESC_DPL_SHIFT) |
+                               DESC_CS_MASK | DESC_R_MASK | DESC_A_MASK);
+        cpu_x86_load_seg_cache(env, R_SS, ((env->sysenter_cs + 24) & 0xfffc) |
+                               3, 0, 0xffffffff,
+                               DESC_G_MASK | DESC_B_MASK | DESC_P_MASK |
+                               DESC_S_MASK | (3 << DESC_DPL_SHIFT) |
+                               DESC_W_MASK | DESC_A_MASK);
+    }
+    ESP = ECX;
+    EIP = EDX;
+}
+
+target_ulong helper_lsl(target_ulong selector1)
+{
+    unsigned int limit;
+    uint32_t e1, e2, eflags, selector;
+    int rpl, dpl, cpl, type;
+
+    selector = selector1 & 0xffff;
+    eflags = helper_cc_compute_all(CC_OP);
+    if ((selector & 0xfffc) == 0) {
+        goto fail;
+    }
+    if (load_segment(&e1, &e2, selector) != 0) {
+        goto fail;
+    }
+    rpl = selector & 3;
+    dpl = (e2 >> DESC_DPL_SHIFT) & 3;
+    cpl = env->hflags & HF_CPL_MASK;
+    if (e2 & DESC_S_MASK) {
+        if ((e2 & DESC_CS_MASK) && (e2 & DESC_C_MASK)) {
+            /* conforming */
+        } else {
+            if (dpl < cpl || dpl < rpl) {
+                goto fail;
+            }
+        }
+    } else {
+        type = (e2 >> DESC_TYPE_SHIFT) & 0xf;
+        switch (type) {
+        case 1:
+        case 2:
+        case 3:
+        case 9:
+        case 11:
+            break;
+        default:
+            goto fail;
+        }
+        if (dpl < cpl || dpl < rpl) {
+        fail:
+            CC_SRC = eflags & ~CC_Z;
+            return 0;
+        }
+    }
+    limit = get_seg_limit(e1, e2);
+    CC_SRC = eflags | CC_Z;
+    return limit;
+}
+
+target_ulong helper_lar(target_ulong selector1)
+{
+    uint32_t e1, e2, eflags, selector;
+    int rpl, dpl, cpl, type;
+
+    selector = selector1 & 0xffff;
+    eflags = helper_cc_compute_all(CC_OP);
+    if ((selector & 0xfffc) == 0) {
+        goto fail;
+    }
+    if (load_segment(&e1, &e2, selector) != 0) {
+        goto fail;
+    }
+    rpl = selector & 3;
+    dpl = (e2 >> DESC_DPL_SHIFT) & 3;
+    cpl = env->hflags & HF_CPL_MASK;
+    if (e2 & DESC_S_MASK) {
+        if ((e2 & DESC_CS_MASK) && (e2 & DESC_C_MASK)) {
+            /* conforming */
+        } else {
+            if (dpl < cpl || dpl < rpl) {
+                goto fail;
+            }
+        }
+    } else {
+        type = (e2 >> DESC_TYPE_SHIFT) & 0xf;
+        switch (type) {
+        case 1:
+        case 2:
+        case 3:
+        case 4:
+        case 5:
+        case 9:
+        case 11:
+        case 12:
+            break;
+        default:
+            goto fail;
+        }
+        if (dpl < cpl || dpl < rpl) {
+        fail:
+            CC_SRC = eflags & ~CC_Z;
+            return 0;
+        }
+    }
+    CC_SRC = eflags | CC_Z;
+    return e2 & 0x00f0ff00;
+}
+
+void helper_verr(target_ulong selector1)
+{
+    uint32_t e1, e2, eflags, selector;
+    int rpl, dpl, cpl;
+
+    selector = selector1 & 0xffff;
+    eflags = helper_cc_compute_all(CC_OP);
+    if ((selector & 0xfffc) == 0) {
+        goto fail;
+    }
+    if (load_segment(&e1, &e2, selector) != 0) {
+        goto fail;
+    }
+    if (!(e2 & DESC_S_MASK)) {
+        goto fail;
+    }
+    rpl = selector & 3;
+    dpl = (e2 >> DESC_DPL_SHIFT) & 3;
+    cpl = env->hflags & HF_CPL_MASK;
+    if (e2 & DESC_CS_MASK) {
+        if (!(e2 & DESC_R_MASK)) {
+            goto fail;
+        }
+        if (!(e2 & DESC_C_MASK)) {
+            if (dpl < cpl || dpl < rpl) {
+                goto fail;
+            }
+        }
+    } else {
+        if (dpl < cpl || dpl < rpl) {
+        fail:
+            CC_SRC = eflags & ~CC_Z;
+            return;
+        }
+    }
+    CC_SRC = eflags | CC_Z;
+}
+
+void helper_verw(target_ulong selector1)
+{
+    uint32_t e1, e2, eflags, selector;
+    int rpl, dpl, cpl;
+
+    selector = selector1 & 0xffff;
+    eflags = helper_cc_compute_all(CC_OP);
+    if ((selector & 0xfffc) == 0) {
+        goto fail;
+    }
+    if (load_segment(&e1, &e2, selector) != 0) {
+        goto fail;
+    }
+    if (!(e2 & DESC_S_MASK)) {
+        goto fail;
+    }
+    rpl = selector & 3;
+    dpl = (e2 >> DESC_DPL_SHIFT) & 3;
+    cpl = env->hflags & HF_CPL_MASK;
+    if (e2 & DESC_CS_MASK) {
+        goto fail;
+    } else {
+        if (dpl < cpl || dpl < rpl) {
+            goto fail;
+        }
+        if (!(e2 & DESC_W_MASK)) {
+        fail:
+            CC_SRC = eflags & ~CC_Z;
+            return;
+        }
+    }
+    CC_SRC = eflags | CC_Z;
+}
+
+#if defined(CONFIG_USER_ONLY)
+void cpu_x86_load_seg(CPUX86State *s, int seg_reg, int selector)
+{
+    CPUX86State *saved_env;
+
+    saved_env = env;
+    env = s;
+    if (!(env->cr[0] & CR0_PE_MASK) || (env->eflags & VM_MASK)) {
+        selector &= 0xffff;
+        cpu_x86_load_seg_cache(env, seg_reg, selector,
+                               (selector << 4), 0xffff, 0);
+    } else {
+        helper_load_seg(seg_reg, selector);
+    }
+    env = saved_env;
+}
+#endif
commit 10774999ca6336cf82327fc91001e444003e9d04
Author: Blue Swirl <blauwirbel at gmail.com>
Date:   Sun Apr 29 16:39:13 2012 +0000

    x86: split off memory access helpers
    
    Move memory access helpers to mem_helper.c.
    
    Signed-off-by: Blue Swirl <blauwirbel at gmail.com>

diff --git a/target-i386/Makefile.objs b/target-i386/Makefile.objs
index 72bd423..9a921c4 100644
--- a/target-i386/Makefile.objs
+++ b/target-i386/Makefile.objs
@@ -1,6 +1,6 @@
 obj-y += translate.o op_helper.o helper.o cpu.o
 obj-y += excp_helper.o fpu_helper.o cc_helper.o int_helper.o svm_helper.o
-obj-y += smm_helper.o misc_helper.o
+obj-y += smm_helper.o misc_helper.o mem_helper.o
 obj-$(CONFIG_SOFTMMU) += machine.o arch_memory_mapping.o arch_dump.o
 obj-$(CONFIG_KVM) += kvm.o hyperv.o
 obj-$(CONFIG_LINUX_USER) += ioport-user.o
@@ -13,3 +13,4 @@ $(obj)/int_helper.o: QEMU_CFLAGS += $(HELPER_CFLAGS)
 $(obj)/svm_helper.o: QEMU_CFLAGS += $(HELPER_CFLAGS)
 $(obj)/smm_helper.o: QEMU_CFLAGS += $(HELPER_CFLAGS)
 $(obj)/misc_helper.o: QEMU_CFLAGS += $(HELPER_CFLAGS)
+$(obj)/mem_helper.o: QEMU_CFLAGS += $(HELPER_CFLAGS)
diff --git a/target-i386/mem_helper.c b/target-i386/mem_helper.c
new file mode 100644
index 0000000..91353c0
--- /dev/null
+++ b/target-i386/mem_helper.c
@@ -0,0 +1,161 @@
+/*
+ *  x86 memory access helpers
+ *
+ *  Copyright (c) 2003 Fabrice Bellard
+ *
+ * This library is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Lesser General Public
+ * License as published by the Free Software Foundation; either
+ * version 2 of the License, or (at your option) any later version.
+ *
+ * This library is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
+ * Lesser General Public License for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public
+ * License along with this library; if not, see <http://www.gnu.org/licenses/>.
+ */
+
+#include "cpu.h"
+#include "dyngen-exec.h"
+#include "helper.h"
+
+#if !defined(CONFIG_USER_ONLY)
+#include "softmmu_exec.h"
+#endif /* !defined(CONFIG_USER_ONLY) */
+
+/* broken thread support */
+
+static spinlock_t global_cpu_lock = SPIN_LOCK_UNLOCKED;
+
+void helper_lock(void)
+{
+    spin_lock(&global_cpu_lock);
+}
+
+void helper_unlock(void)
+{
+    spin_unlock(&global_cpu_lock);
+}
+
+void helper_cmpxchg8b(target_ulong a0)
+{
+    uint64_t d;
+    int eflags;
+
+    eflags = helper_cc_compute_all(CC_OP);
+    d = ldq(a0);
+    if (d == (((uint64_t)EDX << 32) | (uint32_t)EAX)) {
+        stq(a0, ((uint64_t)ECX << 32) | (uint32_t)EBX);
+        eflags |= CC_Z;
+    } else {
+        /* always do the store */
+        stq(a0, d);
+        EDX = (uint32_t)(d >> 32);
+        EAX = (uint32_t)d;
+        eflags &= ~CC_Z;
+    }
+    CC_SRC = eflags;
+}
+
+#ifdef TARGET_X86_64
+void helper_cmpxchg16b(target_ulong a0)
+{
+    uint64_t d0, d1;
+    int eflags;
+
+    if ((a0 & 0xf) != 0) {
+        raise_exception(env, EXCP0D_GPF);
+    }
+    eflags = helper_cc_compute_all(CC_OP);
+    d0 = ldq(a0);
+    d1 = ldq(a0 + 8);
+    if (d0 == EAX && d1 == EDX) {
+        stq(a0, EBX);
+        stq(a0 + 8, ECX);
+        eflags |= CC_Z;
+    } else {
+        /* always do the store */
+        stq(a0, d0);
+        stq(a0 + 8, d1);
+        EDX = d1;
+        EAX = d0;
+        eflags &= ~CC_Z;
+    }
+    CC_SRC = eflags;
+}
+#endif
+
+void helper_boundw(target_ulong a0, int v)
+{
+    int low, high;
+
+    low = ldsw(a0);
+    high = ldsw(a0 + 2);
+    v = (int16_t)v;
+    if (v < low || v > high) {
+        raise_exception(env, EXCP05_BOUND);
+    }
+}
+
+void helper_boundl(target_ulong a0, int v)
+{
+    int low, high;
+
+    low = ldl(a0);
+    high = ldl(a0 + 4);
+    if (v < low || v > high) {
+        raise_exception(env, EXCP05_BOUND);
+    }
+}
+
+#if !defined(CONFIG_USER_ONLY)
+
+#define MMUSUFFIX _mmu
+
+#define SHIFT 0
+#include "softmmu_template.h"
+
+#define SHIFT 1
+#include "softmmu_template.h"
+
+#define SHIFT 2
+#include "softmmu_template.h"
+
+#define SHIFT 3
+#include "softmmu_template.h"
+
+#endif
+
+#if !defined(CONFIG_USER_ONLY)
+/* try to fill the TLB and return an exception if error. If retaddr is
+   NULL, it means that the function was called in C code (i.e. not
+   from generated code or from helper.c) */
+/* XXX: fix it to restore all registers */
+void tlb_fill(CPUX86State *env1, target_ulong addr, int is_write, int mmu_idx,
+              uintptr_t retaddr)
+{
+    TranslationBlock *tb;
+    int ret;
+    CPUX86State *saved_env;
+
+    saved_env = env;
+    env = env1;
+
+    ret = cpu_x86_handle_mmu_fault(env, addr, is_write, mmu_idx);
+    if (ret) {
+        if (retaddr) {
+            /* now we have a real cpu fault */
+            tb = tb_find_pc(retaddr);
+            if (tb) {
+                /* the PC is inside the translated code. It means that we have
+                   a virtual CPU fault */
+                cpu_restore_state(tb, env, retaddr);
+            }
+        }
+        raise_exception_err(env, env->exception_index, env->error_code);
+    }
+    env = saved_env;
+}
+#endif
diff --git a/target-i386/op_helper.c b/target-i386/op_helper.c
index 441c0ae..a4b8b64 100644
--- a/target-i386/op_helper.c
+++ b/target-i386/op_helper.c
@@ -1,5 +1,6 @@
 /*
- *  i386 helpers
+ *  x86 segmentation related helpers:
+ *  TSS, interrupts, system calls, jumps and call/task gates, descriptors
  *
  *  Copyright (c) 2003 Fabrice Bellard
  *
@@ -37,20 +38,6 @@
 # define LOG_PCALL_STATE(env) do { } while (0)
 #endif
 
-/* broken thread support */
-
-static spinlock_t global_cpu_lock = SPIN_LOCK_UNLOCKED;
-
-void helper_lock(void)
-{
-    spin_lock(&global_cpu_lock);
-}
-
-void helper_unlock(void)
-{
-    spin_unlock(&global_cpu_lock);
-}
-
 /* return non zero if error */
 static inline int load_segment(uint32_t *e1_ptr, uint32_t *e2_ptr,
                                int selector)
@@ -1279,54 +1266,6 @@ void do_interrupt_x86_hardirq(CPUX86State *env1, int intno, int is_hw)
     env = saved_env;
 }
 
-void helper_cmpxchg8b(target_ulong a0)
-{
-    uint64_t d;
-    int eflags;
-
-    eflags = helper_cc_compute_all(CC_OP);
-    d = ldq(a0);
-    if (d == (((uint64_t)EDX << 32) | (uint32_t)EAX)) {
-        stq(a0, ((uint64_t)ECX << 32) | (uint32_t)EBX);
-        eflags |= CC_Z;
-    } else {
-        /* always do the store */
-        stq(a0, d);
-        EDX = (uint32_t)(d >> 32);
-        EAX = (uint32_t)d;
-        eflags &= ~CC_Z;
-    }
-    CC_SRC = eflags;
-}
-
-#ifdef TARGET_X86_64
-void helper_cmpxchg16b(target_ulong a0)
-{
-    uint64_t d0, d1;
-    int eflags;
-
-    if ((a0 & 0xf) != 0) {
-        raise_exception(env, EXCP0D_GPF);
-    }
-    eflags = helper_cc_compute_all(CC_OP);
-    d0 = ldq(a0);
-    d1 = ldq(a0 + 8);
-    if (d0 == EAX && d1 == EDX) {
-        stq(a0, EBX);
-        stq(a0 + 8, ECX);
-        eflags |= CC_Z;
-    } else {
-        /* always do the store */
-        stq(a0, d0);
-        stq(a0 + 8, d1);
-        EDX = d1;
-        EAX = d0;
-        eflags &= ~CC_Z;
-    }
-    CC_SRC = eflags;
-}
-#endif
-
 void helper_enter_level(int level, int data32, target_ulong t1)
 {
     target_ulong ssp;
@@ -2534,76 +2473,3 @@ void cpu_x86_load_seg(CPUX86State *s, int seg_reg, int selector)
     env = saved_env;
 }
 #endif
-
-void helper_boundw(target_ulong a0, int v)
-{
-    int low, high;
-
-    low = ldsw(a0);
-    high = ldsw(a0 + 2);
-    v = (int16_t)v;
-    if (v < low || v > high) {
-        raise_exception(env, EXCP05_BOUND);
-    }
-}
-
-void helper_boundl(target_ulong a0, int v)
-{
-    int low, high;
-
-    low = ldl(a0);
-    high = ldl(a0 + 4);
-    if (v < low || v > high) {
-        raise_exception(env, EXCP05_BOUND);
-    }
-}
-
-#if !defined(CONFIG_USER_ONLY)
-
-#define MMUSUFFIX _mmu
-
-#define SHIFT 0
-#include "softmmu_template.h"
-
-#define SHIFT 1
-#include "softmmu_template.h"
-
-#define SHIFT 2
-#include "softmmu_template.h"
-
-#define SHIFT 3
-#include "softmmu_template.h"
-
-#endif
-
-#if !defined(CONFIG_USER_ONLY)
-/* try to fill the TLB and return an exception if error. If retaddr is
-   NULL, it means that the function was called in C code (i.e. not
-   from generated code or from helper.c) */
-/* XXX: fix it to restore all registers */
-void tlb_fill(CPUX86State *env1, target_ulong addr, int is_write, int mmu_idx,
-              uintptr_t retaddr)
-{
-    TranslationBlock *tb;
-    int ret;
-    CPUX86State *saved_env;
-
-    saved_env = env;
-    env = env1;
-
-    ret = cpu_x86_handle_mmu_fault(env, addr, is_write, mmu_idx);
-    if (ret) {
-        if (retaddr) {
-            /* now we have a real cpu fault */
-            tb = tb_find_pc(retaddr);
-            if (tb) {
-                /* the PC is inside the translated code. It means that we have
-                   a virtual CPU fault */
-                cpu_restore_state(tb, env, retaddr);
-            }
-        }
-        raise_exception_err(env, env->exception_index, env->error_code);
-    }
-    env = saved_env;
-}
-#endif
commit f7b2429f5233d2ed8e4667edcbf97f2cae1cb40c
Author: Blue Swirl <blauwirbel at gmail.com>
Date:   Sun Apr 29 18:20:34 2012 +0000

    x86: split off misc helpers
    
    Move various functions to misc_helper.c.
    
    Signed-off-by: Blue Swirl <blauwirbel at gmail.com>

diff --git a/target-i386/Makefile.objs b/target-i386/Makefile.objs
index a2ba717..72bd423 100644
--- a/target-i386/Makefile.objs
+++ b/target-i386/Makefile.objs
@@ -1,6 +1,6 @@
 obj-y += translate.o op_helper.o helper.o cpu.o
 obj-y += excp_helper.o fpu_helper.o cc_helper.o int_helper.o svm_helper.o
-obj-y += smm_helper.o
+obj-y += smm_helper.o misc_helper.o
 obj-$(CONFIG_SOFTMMU) += machine.o arch_memory_mapping.o arch_dump.o
 obj-$(CONFIG_KVM) += kvm.o hyperv.o
 obj-$(CONFIG_LINUX_USER) += ioport-user.o
@@ -12,3 +12,4 @@ $(obj)/cc_helper.o: QEMU_CFLAGS += $(HELPER_CFLAGS)
 $(obj)/int_helper.o: QEMU_CFLAGS += $(HELPER_CFLAGS)
 $(obj)/svm_helper.o: QEMU_CFLAGS += $(HELPER_CFLAGS)
 $(obj)/smm_helper.o: QEMU_CFLAGS += $(HELPER_CFLAGS)
+$(obj)/misc_helper.o: QEMU_CFLAGS += $(HELPER_CFLAGS)
diff --git a/target-i386/misc_helper.c b/target-i386/misc_helper.c
new file mode 100644
index 0000000..ce675b7
--- /dev/null
+++ b/target-i386/misc_helper.c
@@ -0,0 +1,603 @@
+/*
+ *  x86 misc helpers
+ *
+ *  Copyright (c) 2003 Fabrice Bellard
+ *
+ * This library is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Lesser General Public
+ * License as published by the Free Software Foundation; either
+ * version 2 of the License, or (at your option) any later version.
+ *
+ * This library is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
+ * Lesser General Public License for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public
+ * License along with this library; if not, see <http://www.gnu.org/licenses/>.
+ */
+
+#include "cpu.h"
+#include "dyngen-exec.h"
+#include "ioport.h"
+#include "helper.h"
+
+#if !defined(CONFIG_USER_ONLY)
+#include "softmmu_exec.h"
+#endif /* !defined(CONFIG_USER_ONLY) */
+
+/* check if Port I/O is allowed in TSS */
+static inline void check_io(int addr, int size)
+{
+    int io_offset, val, mask;
+
+    /* TSS must be a valid 32 bit one */
+    if (!(env->tr.flags & DESC_P_MASK) ||
+        ((env->tr.flags >> DESC_TYPE_SHIFT) & 0xf) != 9 ||
+        env->tr.limit < 103) {
+        goto fail;
+    }
+    io_offset = lduw_kernel(env->tr.base + 0x66);
+    io_offset += (addr >> 3);
+    /* Note: the check needs two bytes */
+    if ((io_offset + 1) > env->tr.limit) {
+        goto fail;
+    }
+    val = lduw_kernel(env->tr.base + io_offset);
+    val >>= (addr & 7);
+    mask = (1 << size) - 1;
+    /* all bits must be zero to allow the I/O */
+    if ((val & mask) != 0) {
+    fail:
+        raise_exception_err(env, EXCP0D_GPF, 0);
+    }
+}
+
+void helper_check_iob(uint32_t t0)
+{
+    check_io(t0, 1);
+}
+
+void helper_check_iow(uint32_t t0)
+{
+    check_io(t0, 2);
+}
+
+void helper_check_iol(uint32_t t0)
+{
+    check_io(t0, 4);
+}
+
+void helper_outb(uint32_t port, uint32_t data)
+{
+    cpu_outb(port, data & 0xff);
+}
+
+target_ulong helper_inb(uint32_t port)
+{
+    return cpu_inb(port);
+}
+
+void helper_outw(uint32_t port, uint32_t data)
+{
+    cpu_outw(port, data & 0xffff);
+}
+
+target_ulong helper_inw(uint32_t port)
+{
+    return cpu_inw(port);
+}
+
+void helper_outl(uint32_t port, uint32_t data)
+{
+    cpu_outl(port, data);
+}
+
+target_ulong helper_inl(uint32_t port)
+{
+    return cpu_inl(port);
+}
+
+void helper_into(int next_eip_addend)
+{
+    int eflags;
+
+    eflags = helper_cc_compute_all(CC_OP);
+    if (eflags & CC_O) {
+        raise_interrupt(env, EXCP04_INTO, 1, 0, next_eip_addend);
+    }
+}
+
+void helper_single_step(void)
+{
+#ifndef CONFIG_USER_ONLY
+    check_hw_breakpoints(env, 1);
+    env->dr[6] |= DR6_BS;
+#endif
+    raise_exception(env, EXCP01_DB);
+}
+
+void helper_cpuid(void)
+{
+    uint32_t eax, ebx, ecx, edx;
+
+    cpu_svm_check_intercept_param(env, SVM_EXIT_CPUID, 0);
+
+    cpu_x86_cpuid(env, (uint32_t)EAX, (uint32_t)ECX, &eax, &ebx, &ecx, &edx);
+    EAX = eax;
+    EBX = ebx;
+    ECX = ecx;
+    EDX = edx;
+}
+
+#if defined(CONFIG_USER_ONLY)
+target_ulong helper_read_crN(int reg)
+{
+    return 0;
+}
+
+void helper_write_crN(int reg, target_ulong t0)
+{
+}
+
+void helper_movl_drN_T0(int reg, target_ulong t0)
+{
+}
+#else
+target_ulong helper_read_crN(int reg)
+{
+    target_ulong val;
+
+    cpu_svm_check_intercept_param(env, SVM_EXIT_READ_CR0 + reg, 0);
+    switch (reg) {
+    default:
+        val = env->cr[reg];
+        break;
+    case 8:
+        if (!(env->hflags2 & HF2_VINTR_MASK)) {
+            val = cpu_get_apic_tpr(env->apic_state);
+        } else {
+            val = env->v_tpr;
+        }
+        break;
+    }
+    return val;
+}
+
+void helper_write_crN(int reg, target_ulong t0)
+{
+    cpu_svm_check_intercept_param(env, SVM_EXIT_WRITE_CR0 + reg, 0);
+    switch (reg) {
+    case 0:
+        cpu_x86_update_cr0(env, t0);
+        break;
+    case 3:
+        cpu_x86_update_cr3(env, t0);
+        break;
+    case 4:
+        cpu_x86_update_cr4(env, t0);
+        break;
+    case 8:
+        if (!(env->hflags2 & HF2_VINTR_MASK)) {
+            cpu_set_apic_tpr(env->apic_state, t0);
+        }
+        env->v_tpr = t0 & 0x0f;
+        break;
+    default:
+        env->cr[reg] = t0;
+        break;
+    }
+}
+
+void helper_movl_drN_T0(int reg, target_ulong t0)
+{
+    int i;
+
+    if (reg < 4) {
+        hw_breakpoint_remove(env, reg);
+        env->dr[reg] = t0;
+        hw_breakpoint_insert(env, reg);
+    } else if (reg == 7) {
+        for (i = 0; i < 4; i++) {
+            hw_breakpoint_remove(env, i);
+        }
+        env->dr[7] = t0;
+        for (i = 0; i < 4; i++) {
+            hw_breakpoint_insert(env, i);
+        }
+    } else {
+        env->dr[reg] = t0;
+    }
+}
+#endif
+
+void helper_lmsw(target_ulong t0)
+{
+    /* only 4 lower bits of CR0 are modified. PE cannot be set to zero
+       if already set to one. */
+    t0 = (env->cr[0] & ~0xe) | (t0 & 0xf);
+    helper_write_crN(0, t0);
+}
+
+void helper_invlpg(target_ulong addr)
+{
+    cpu_svm_check_intercept_param(env, SVM_EXIT_INVLPG, 0);
+    tlb_flush_page(env, addr);
+}
+
+void helper_rdtsc(void)
+{
+    uint64_t val;
+
+    if ((env->cr[4] & CR4_TSD_MASK) && ((env->hflags & HF_CPL_MASK) != 0)) {
+        raise_exception(env, EXCP0D_GPF);
+    }
+    cpu_svm_check_intercept_param(env, SVM_EXIT_RDTSC, 0);
+
+    val = cpu_get_tsc(env) + env->tsc_offset;
+    EAX = (uint32_t)(val);
+    EDX = (uint32_t)(val >> 32);
+}
+
+void helper_rdtscp(void)
+{
+    helper_rdtsc();
+    ECX = (uint32_t)(env->tsc_aux);
+}
+
+void helper_rdpmc(void)
+{
+    if ((env->cr[4] & CR4_PCE_MASK) && ((env->hflags & HF_CPL_MASK) != 0)) {
+        raise_exception(env, EXCP0D_GPF);
+    }
+    cpu_svm_check_intercept_param(env, SVM_EXIT_RDPMC, 0);
+
+    /* currently unimplemented */
+    qemu_log_mask(LOG_UNIMP, "x86: unimplemented rdpmc\n");
+    raise_exception_err(env, EXCP06_ILLOP, 0);
+}
+
+#if defined(CONFIG_USER_ONLY)
+void helper_wrmsr(void)
+{
+}
+
+void helper_rdmsr(void)
+{
+}
+#else
+void helper_wrmsr(void)
+{
+    uint64_t val;
+
+    cpu_svm_check_intercept_param(env, SVM_EXIT_MSR, 1);
+
+    val = ((uint32_t)EAX) | ((uint64_t)((uint32_t)EDX) << 32);
+
+    switch ((uint32_t)ECX) {
+    case MSR_IA32_SYSENTER_CS:
+        env->sysenter_cs = val & 0xffff;
+        break;
+    case MSR_IA32_SYSENTER_ESP:
+        env->sysenter_esp = val;
+        break;
+    case MSR_IA32_SYSENTER_EIP:
+        env->sysenter_eip = val;
+        break;
+    case MSR_IA32_APICBASE:
+        cpu_set_apic_base(env->apic_state, val);
+        break;
+    case MSR_EFER:
+        {
+            uint64_t update_mask;
+
+            update_mask = 0;
+            if (env->cpuid_ext2_features & CPUID_EXT2_SYSCALL) {
+                update_mask |= MSR_EFER_SCE;
+            }
+            if (env->cpuid_ext2_features & CPUID_EXT2_LM) {
+                update_mask |= MSR_EFER_LME;
+            }
+            if (env->cpuid_ext2_features & CPUID_EXT2_FFXSR) {
+                update_mask |= MSR_EFER_FFXSR;
+            }
+            if (env->cpuid_ext2_features & CPUID_EXT2_NX) {
+                update_mask |= MSR_EFER_NXE;
+            }
+            if (env->cpuid_ext3_features & CPUID_EXT3_SVM) {
+                update_mask |= MSR_EFER_SVME;
+            }
+            if (env->cpuid_ext2_features & CPUID_EXT2_FFXSR) {
+                update_mask |= MSR_EFER_FFXSR;
+            }
+            cpu_load_efer(env, (env->efer & ~update_mask) |
+                          (val & update_mask));
+        }
+        break;
+    case MSR_STAR:
+        env->star = val;
+        break;
+    case MSR_PAT:
+        env->pat = val;
+        break;
+    case MSR_VM_HSAVE_PA:
+        env->vm_hsave = val;
+        break;
+#ifdef TARGET_X86_64
+    case MSR_LSTAR:
+        env->lstar = val;
+        break;
+    case MSR_CSTAR:
+        env->cstar = val;
+        break;
+    case MSR_FMASK:
+        env->fmask = val;
+        break;
+    case MSR_FSBASE:
+        env->segs[R_FS].base = val;
+        break;
+    case MSR_GSBASE:
+        env->segs[R_GS].base = val;
+        break;
+    case MSR_KERNELGSBASE:
+        env->kernelgsbase = val;
+        break;
+#endif
+    case MSR_MTRRphysBase(0):
+    case MSR_MTRRphysBase(1):
+    case MSR_MTRRphysBase(2):
+    case MSR_MTRRphysBase(3):
+    case MSR_MTRRphysBase(4):
+    case MSR_MTRRphysBase(5):
+    case MSR_MTRRphysBase(6):
+    case MSR_MTRRphysBase(7):
+        env->mtrr_var[((uint32_t)ECX - MSR_MTRRphysBase(0)) / 2].base = val;
+        break;
+    case MSR_MTRRphysMask(0):
+    case MSR_MTRRphysMask(1):
+    case MSR_MTRRphysMask(2):
+    case MSR_MTRRphysMask(3):
+    case MSR_MTRRphysMask(4):
+    case MSR_MTRRphysMask(5):
+    case MSR_MTRRphysMask(6):
+    case MSR_MTRRphysMask(7):
+        env->mtrr_var[((uint32_t)ECX - MSR_MTRRphysMask(0)) / 2].mask = val;
+        break;
+    case MSR_MTRRfix64K_00000:
+        env->mtrr_fixed[(uint32_t)ECX - MSR_MTRRfix64K_00000] = val;
+        break;
+    case MSR_MTRRfix16K_80000:
+    case MSR_MTRRfix16K_A0000:
+        env->mtrr_fixed[(uint32_t)ECX - MSR_MTRRfix16K_80000 + 1] = val;
+        break;
+    case MSR_MTRRfix4K_C0000:
+    case MSR_MTRRfix4K_C8000:
+    case MSR_MTRRfix4K_D0000:
+    case MSR_MTRRfix4K_D8000:
+    case MSR_MTRRfix4K_E0000:
+    case MSR_MTRRfix4K_E8000:
+    case MSR_MTRRfix4K_F0000:
+    case MSR_MTRRfix4K_F8000:
+        env->mtrr_fixed[(uint32_t)ECX - MSR_MTRRfix4K_C0000 + 3] = val;
+        break;
+    case MSR_MTRRdefType:
+        env->mtrr_deftype = val;
+        break;
+    case MSR_MCG_STATUS:
+        env->mcg_status = val;
+        break;
+    case MSR_MCG_CTL:
+        if ((env->mcg_cap & MCG_CTL_P)
+            && (val == 0 || val == ~(uint64_t)0)) {
+            env->mcg_ctl = val;
+        }
+        break;
+    case MSR_TSC_AUX:
+        env->tsc_aux = val;
+        break;
+    case MSR_IA32_MISC_ENABLE:
+        env->msr_ia32_misc_enable = val;
+        break;
+    default:
+        if ((uint32_t)ECX >= MSR_MC0_CTL
+            && (uint32_t)ECX < MSR_MC0_CTL + (4 * env->mcg_cap & 0xff)) {
+            uint32_t offset = (uint32_t)ECX - MSR_MC0_CTL;
+            if ((offset & 0x3) != 0
+                || (val == 0 || val == ~(uint64_t)0)) {
+                env->mce_banks[offset] = val;
+            }
+            break;
+        }
+        /* XXX: exception? */
+        break;
+    }
+}
+
+void helper_rdmsr(void)
+{
+    uint64_t val;
+
+    cpu_svm_check_intercept_param(env, SVM_EXIT_MSR, 0);
+
+    switch ((uint32_t)ECX) {
+    case MSR_IA32_SYSENTER_CS:
+        val = env->sysenter_cs;
+        break;
+    case MSR_IA32_SYSENTER_ESP:
+        val = env->sysenter_esp;
+        break;
+    case MSR_IA32_SYSENTER_EIP:
+        val = env->sysenter_eip;
+        break;
+    case MSR_IA32_APICBASE:
+        val = cpu_get_apic_base(env->apic_state);
+        break;
+    case MSR_EFER:
+        val = env->efer;
+        break;
+    case MSR_STAR:
+        val = env->star;
+        break;
+    case MSR_PAT:
+        val = env->pat;
+        break;
+    case MSR_VM_HSAVE_PA:
+        val = env->vm_hsave;
+        break;
+    case MSR_IA32_PERF_STATUS:
+        /* tsc_increment_by_tick */
+        val = 1000ULL;
+        /* CPU multiplier */
+        val |= (((uint64_t)4ULL) << 40);
+        break;
+#ifdef TARGET_X86_64
+    case MSR_LSTAR:
+        val = env->lstar;
+        break;
+    case MSR_CSTAR:
+        val = env->cstar;
+        break;
+    case MSR_FMASK:
+        val = env->fmask;
+        break;
+    case MSR_FSBASE:
+        val = env->segs[R_FS].base;
+        break;
+    case MSR_GSBASE:
+        val = env->segs[R_GS].base;
+        break;
+    case MSR_KERNELGSBASE:
+        val = env->kernelgsbase;
+        break;
+    case MSR_TSC_AUX:
+        val = env->tsc_aux;
+        break;
+#endif
+    case MSR_MTRRphysBase(0):
+    case MSR_MTRRphysBase(1):
+    case MSR_MTRRphysBase(2):
+    case MSR_MTRRphysBase(3):
+    case MSR_MTRRphysBase(4):
+    case MSR_MTRRphysBase(5):
+    case MSR_MTRRphysBase(6):
+    case MSR_MTRRphysBase(7):
+        val = env->mtrr_var[((uint32_t)ECX - MSR_MTRRphysBase(0)) / 2].base;
+        break;
+    case MSR_MTRRphysMask(0):
+    case MSR_MTRRphysMask(1):
+    case MSR_MTRRphysMask(2):
+    case MSR_MTRRphysMask(3):
+    case MSR_MTRRphysMask(4):
+    case MSR_MTRRphysMask(5):
+    case MSR_MTRRphysMask(6):
+    case MSR_MTRRphysMask(7):
+        val = env->mtrr_var[((uint32_t)ECX - MSR_MTRRphysMask(0)) / 2].mask;
+        break;
+    case MSR_MTRRfix64K_00000:
+        val = env->mtrr_fixed[0];
+        break;
+    case MSR_MTRRfix16K_80000:
+    case MSR_MTRRfix16K_A0000:
+        val = env->mtrr_fixed[(uint32_t)ECX - MSR_MTRRfix16K_80000 + 1];
+        break;
+    case MSR_MTRRfix4K_C0000:
+    case MSR_MTRRfix4K_C8000:
+    case MSR_MTRRfix4K_D0000:
+    case MSR_MTRRfix4K_D8000:
+    case MSR_MTRRfix4K_E0000:
+    case MSR_MTRRfix4K_E8000:
+    case MSR_MTRRfix4K_F0000:
+    case MSR_MTRRfix4K_F8000:
+        val = env->mtrr_fixed[(uint32_t)ECX - MSR_MTRRfix4K_C0000 + 3];
+        break;
+    case MSR_MTRRdefType:
+        val = env->mtrr_deftype;
+        break;
+    case MSR_MTRRcap:
+        if (env->cpuid_features & CPUID_MTRR) {
+            val = MSR_MTRRcap_VCNT | MSR_MTRRcap_FIXRANGE_SUPPORT |
+                MSR_MTRRcap_WC_SUPPORTED;
+        } else {
+            /* XXX: exception? */
+            val = 0;
+        }
+        break;
+    case MSR_MCG_CAP:
+        val = env->mcg_cap;
+        break;
+    case MSR_MCG_CTL:
+        if (env->mcg_cap & MCG_CTL_P) {
+            val = env->mcg_ctl;
+        } else {
+            val = 0;
+        }
+        break;
+    case MSR_MCG_STATUS:
+        val = env->mcg_status;
+        break;
+    case MSR_IA32_MISC_ENABLE:
+        val = env->msr_ia32_misc_enable;
+        break;
+    default:
+        if ((uint32_t)ECX >= MSR_MC0_CTL
+            && (uint32_t)ECX < MSR_MC0_CTL + (4 * env->mcg_cap & 0xff)) {
+            uint32_t offset = (uint32_t)ECX - MSR_MC0_CTL;
+            val = env->mce_banks[offset];
+            break;
+        }
+        /* XXX: exception? */
+        val = 0;
+        break;
+    }
+    EAX = (uint32_t)(val);
+    EDX = (uint32_t)(val >> 32);
+}
+#endif
+
+static void do_hlt(void)
+{
+    env->hflags &= ~HF_INHIBIT_IRQ_MASK; /* needed if sti is just before */
+    env->halted = 1;
+    env->exception_index = EXCP_HLT;
+    cpu_loop_exit(env);
+}
+
+void helper_hlt(int next_eip_addend)
+{
+    cpu_svm_check_intercept_param(env, SVM_EXIT_HLT, 0);
+    EIP += next_eip_addend;
+
+    do_hlt();
+}
+
+void helper_monitor(target_ulong ptr)
+{
+    if ((uint32_t)ECX != 0) {
+        raise_exception(env, EXCP0D_GPF);
+    }
+    /* XXX: store address? */
+    cpu_svm_check_intercept_param(env, SVM_EXIT_MONITOR, 0);
+}
+
+void helper_mwait(int next_eip_addend)
+{
+    if ((uint32_t)ECX != 0) {
+        raise_exception(env, EXCP0D_GPF);
+    }
+    cpu_svm_check_intercept_param(env, SVM_EXIT_MWAIT, 0);
+    EIP += next_eip_addend;
+
+    /* XXX: not complete but not completely erroneous */
+    if (env->cpu_index != 0 || env->next_cpu != NULL) {
+        /* more than one CPU: do not sleep because another CPU may
+           wake this one */
+    } else {
+        do_hlt();
+    }
+}
+
+void helper_debug(void)
+{
+    env->exception_index = EXCP_DEBUG;
+    cpu_loop_exit(env);
+}
diff --git a/target-i386/op_helper.c b/target-i386/op_helper.c
index 0d31afa..441c0ae 100644
--- a/target-i386/op_helper.c
+++ b/target-i386/op_helper.c
@@ -19,9 +19,7 @@
 
 #include "cpu.h"
 #include "dyngen-exec.h"
-#include "ioport.h"
 #include "qemu-log.h"
-#include "cpu-defs.h"
 #include "helper.h"
 
 #if !defined(CONFIG_USER_ONLY)
@@ -489,78 +487,6 @@ static void switch_tss(int tss_selector,
 #endif
 }
 
-/* check if Port I/O is allowed in TSS */
-static inline void check_io(int addr, int size)
-{
-    int io_offset, val, mask;
-
-    /* TSS must be a valid 32 bit one */
-    if (!(env->tr.flags & DESC_P_MASK) ||
-        ((env->tr.flags >> DESC_TYPE_SHIFT) & 0xf) != 9 ||
-        env->tr.limit < 103) {
-        goto fail;
-    }
-    io_offset = lduw_kernel(env->tr.base + 0x66);
-    io_offset += (addr >> 3);
-    /* Note: the check needs two bytes */
-    if ((io_offset + 1) > env->tr.limit) {
-        goto fail;
-    }
-    val = lduw_kernel(env->tr.base + io_offset);
-    val >>= (addr & 7);
-    mask = (1 << size) - 1;
-    /* all bits must be zero to allow the I/O */
-    if ((val & mask) != 0) {
-    fail:
-        raise_exception_err(env, EXCP0D_GPF, 0);
-    }
-}
-
-void helper_check_iob(uint32_t t0)
-{
-    check_io(t0, 1);
-}
-
-void helper_check_iow(uint32_t t0)
-{
-    check_io(t0, 2);
-}
-
-void helper_check_iol(uint32_t t0)
-{
-    check_io(t0, 4);
-}
-
-void helper_outb(uint32_t port, uint32_t data)
-{
-    cpu_outb(port, data & 0xff);
-}
-
-target_ulong helper_inb(uint32_t port)
-{
-    return cpu_inb(port);
-}
-
-void helper_outw(uint32_t port, uint32_t data)
-{
-    cpu_outw(port, data & 0xffff);
-}
-
-target_ulong helper_inw(uint32_t port)
-{
-    return cpu_inw(port);
-}
-
-void helper_outl(uint32_t port, uint32_t data)
-{
-    cpu_outl(port, data);
-}
-
-target_ulong helper_inl(uint32_t port)
-{
-    return cpu_inl(port);
-}
-
 static inline unsigned int get_sp_mask(unsigned int e2)
 {
     if (e2 & DESC_B_MASK) {
@@ -1353,16 +1279,6 @@ void do_interrupt_x86_hardirq(CPUX86State *env1, int intno, int is_hw)
     env = saved_env;
 }
 
-void helper_into(int next_eip_addend)
-{
-    int eflags;
-
-    eflags = helper_cc_compute_all(CC_OP);
-    if (eflags & CC_O) {
-        raise_interrupt(env, EXCP04_INTO, 1, 0, next_eip_addend);
-    }
-}
-
 void helper_cmpxchg8b(target_ulong a0)
 {
     uint64_t d;
@@ -1411,28 +1327,6 @@ void helper_cmpxchg16b(target_ulong a0)
 }
 #endif
 
-void helper_single_step(void)
-{
-#ifndef CONFIG_USER_ONLY
-    check_hw_breakpoints(env, 1);
-    env->dr[6] |= DR6_BS;
-#endif
-    raise_exception(env, EXCP01_DB);
-}
-
-void helper_cpuid(void)
-{
-    uint32_t eax, ebx, ecx, edx;
-
-    cpu_svm_check_intercept_param(env, SVM_EXIT_CPUID, 0);
-
-    cpu_x86_cpuid(env, (uint32_t)EAX, (uint32_t)ECX, &eax, &ebx, &ecx, &edx);
-    EAX = eax;
-    EBX = ebx;
-    ECX = ecx;
-    EDX = edx;
-}
-
 void helper_enter_level(int level, int data32, target_ulong t1)
 {
     target_ulong ssp;
@@ -2454,430 +2348,6 @@ void helper_sysexit(int dflag)
     EIP = EDX;
 }
 
-#if defined(CONFIG_USER_ONLY)
-target_ulong helper_read_crN(int reg)
-{
-    return 0;
-}
-
-void helper_write_crN(int reg, target_ulong t0)
-{
-}
-
-void helper_movl_drN_T0(int reg, target_ulong t0)
-{
-}
-#else
-target_ulong helper_read_crN(int reg)
-{
-    target_ulong val;
-
-    cpu_svm_check_intercept_param(env, SVM_EXIT_READ_CR0 + reg, 0);
-    switch (reg) {
-    default:
-        val = env->cr[reg];
-        break;
-    case 8:
-        if (!(env->hflags2 & HF2_VINTR_MASK)) {
-            val = cpu_get_apic_tpr(env->apic_state);
-        } else {
-            val = env->v_tpr;
-        }
-        break;
-    }
-    return val;
-}
-
-void helper_write_crN(int reg, target_ulong t0)
-{
-    cpu_svm_check_intercept_param(env, SVM_EXIT_WRITE_CR0 + reg, 0);
-    switch (reg) {
-    case 0:
-        cpu_x86_update_cr0(env, t0);
-        break;
-    case 3:
-        cpu_x86_update_cr3(env, t0);
-        break;
-    case 4:
-        cpu_x86_update_cr4(env, t0);
-        break;
-    case 8:
-        if (!(env->hflags2 & HF2_VINTR_MASK)) {
-            cpu_set_apic_tpr(env->apic_state, t0);
-        }
-        env->v_tpr = t0 & 0x0f;
-        break;
-    default:
-        env->cr[reg] = t0;
-        break;
-    }
-}
-
-void helper_movl_drN_T0(int reg, target_ulong t0)
-{
-    int i;
-
-    if (reg < 4) {
-        hw_breakpoint_remove(env, reg);
-        env->dr[reg] = t0;
-        hw_breakpoint_insert(env, reg);
-    } else if (reg == 7) {
-        for (i = 0; i < 4; i++) {
-            hw_breakpoint_remove(env, i);
-        }
-        env->dr[7] = t0;
-        for (i = 0; i < 4; i++) {
-            hw_breakpoint_insert(env, i);
-        }
-    } else {
-        env->dr[reg] = t0;
-    }
-}
-#endif
-
-void helper_lmsw(target_ulong t0)
-{
-    /* only 4 lower bits of CR0 are modified. PE cannot be set to zero
-       if already set to one. */
-    t0 = (env->cr[0] & ~0xe) | (t0 & 0xf);
-    helper_write_crN(0, t0);
-}
-
-void helper_invlpg(target_ulong addr)
-{
-    cpu_svm_check_intercept_param(env, SVM_EXIT_INVLPG, 0);
-    tlb_flush_page(env, addr);
-}
-
-void helper_rdtsc(void)
-{
-    uint64_t val;
-
-    if ((env->cr[4] & CR4_TSD_MASK) && ((env->hflags & HF_CPL_MASK) != 0)) {
-        raise_exception(env, EXCP0D_GPF);
-    }
-    cpu_svm_check_intercept_param(env, SVM_EXIT_RDTSC, 0);
-
-    val = cpu_get_tsc(env) + env->tsc_offset;
-    EAX = (uint32_t)(val);
-    EDX = (uint32_t)(val >> 32);
-}
-
-void helper_rdtscp(void)
-{
-    helper_rdtsc();
-    ECX = (uint32_t)(env->tsc_aux);
-}
-
-void helper_rdpmc(void)
-{
-    if ((env->cr[4] & CR4_PCE_MASK) && ((env->hflags & HF_CPL_MASK) != 0)) {
-        raise_exception(env, EXCP0D_GPF);
-    }
-    cpu_svm_check_intercept_param(env, SVM_EXIT_RDPMC, 0);
-
-    /* currently unimplemented */
-    qemu_log_mask(LOG_UNIMP, "x86: unimplemented rdpmc\n");
-    raise_exception_err(env, EXCP06_ILLOP, 0);
-}
-
-#if defined(CONFIG_USER_ONLY)
-void helper_wrmsr(void)
-{
-}
-
-void helper_rdmsr(void)
-{
-}
-#else
-void helper_wrmsr(void)
-{
-    uint64_t val;
-
-    cpu_svm_check_intercept_param(env, SVM_EXIT_MSR, 1);
-
-    val = ((uint32_t)EAX) | ((uint64_t)((uint32_t)EDX) << 32);
-
-    switch ((uint32_t)ECX) {
-    case MSR_IA32_SYSENTER_CS:
-        env->sysenter_cs = val & 0xffff;
-        break;
-    case MSR_IA32_SYSENTER_ESP:
-        env->sysenter_esp = val;
-        break;
-    case MSR_IA32_SYSENTER_EIP:
-        env->sysenter_eip = val;
-        break;
-    case MSR_IA32_APICBASE:
-        cpu_set_apic_base(env->apic_state, val);
-        break;
-    case MSR_EFER:
-        {
-            uint64_t update_mask;
-
-            update_mask = 0;
-            if (env->cpuid_ext2_features & CPUID_EXT2_SYSCALL) {
-                update_mask |= MSR_EFER_SCE;
-            }
-            if (env->cpuid_ext2_features & CPUID_EXT2_LM) {
-                update_mask |= MSR_EFER_LME;
-            }
-            if (env->cpuid_ext2_features & CPUID_EXT2_FFXSR) {
-                update_mask |= MSR_EFER_FFXSR;
-            }
-            if (env->cpuid_ext2_features & CPUID_EXT2_NX) {
-                update_mask |= MSR_EFER_NXE;
-            }
-            if (env->cpuid_ext3_features & CPUID_EXT3_SVM) {
-                update_mask |= MSR_EFER_SVME;
-            }
-            if (env->cpuid_ext2_features & CPUID_EXT2_FFXSR) {
-                update_mask |= MSR_EFER_FFXSR;
-            }
-            cpu_load_efer(env, (env->efer & ~update_mask) |
-                          (val & update_mask));
-        }
-        break;
-    case MSR_STAR:
-        env->star = val;
-        break;
-    case MSR_PAT:
-        env->pat = val;
-        break;
-    case MSR_VM_HSAVE_PA:
-        env->vm_hsave = val;
-        break;
-#ifdef TARGET_X86_64
-    case MSR_LSTAR:
-        env->lstar = val;
-        break;
-    case MSR_CSTAR:
-        env->cstar = val;
-        break;
-    case MSR_FMASK:
-        env->fmask = val;
-        break;
-    case MSR_FSBASE:
-        env->segs[R_FS].base = val;
-        break;
-    case MSR_GSBASE:
-        env->segs[R_GS].base = val;
-        break;
-    case MSR_KERNELGSBASE:
-        env->kernelgsbase = val;
-        break;
-#endif
-    case MSR_MTRRphysBase(0):
-    case MSR_MTRRphysBase(1):
-    case MSR_MTRRphysBase(2):
-    case MSR_MTRRphysBase(3):
-    case MSR_MTRRphysBase(4):
-    case MSR_MTRRphysBase(5):
-    case MSR_MTRRphysBase(6):
-    case MSR_MTRRphysBase(7):
-        env->mtrr_var[((uint32_t)ECX - MSR_MTRRphysBase(0)) / 2].base = val;
-        break;
-    case MSR_MTRRphysMask(0):
-    case MSR_MTRRphysMask(1):
-    case MSR_MTRRphysMask(2):
-    case MSR_MTRRphysMask(3):
-    case MSR_MTRRphysMask(4):
-    case MSR_MTRRphysMask(5):
-    case MSR_MTRRphysMask(6):
-    case MSR_MTRRphysMask(7):
-        env->mtrr_var[((uint32_t)ECX - MSR_MTRRphysMask(0)) / 2].mask = val;
-        break;
-    case MSR_MTRRfix64K_00000:
-        env->mtrr_fixed[(uint32_t)ECX - MSR_MTRRfix64K_00000] = val;
-        break;
-    case MSR_MTRRfix16K_80000:
-    case MSR_MTRRfix16K_A0000:
-        env->mtrr_fixed[(uint32_t)ECX - MSR_MTRRfix16K_80000 + 1] = val;
-        break;
-    case MSR_MTRRfix4K_C0000:
-    case MSR_MTRRfix4K_C8000:
-    case MSR_MTRRfix4K_D0000:
-    case MSR_MTRRfix4K_D8000:
-    case MSR_MTRRfix4K_E0000:
-    case MSR_MTRRfix4K_E8000:
-    case MSR_MTRRfix4K_F0000:
-    case MSR_MTRRfix4K_F8000:
-        env->mtrr_fixed[(uint32_t)ECX - MSR_MTRRfix4K_C0000 + 3] = val;
-        break;
-    case MSR_MTRRdefType:
-        env->mtrr_deftype = val;
-        break;
-    case MSR_MCG_STATUS:
-        env->mcg_status = val;
-        break;
-    case MSR_MCG_CTL:
-        if ((env->mcg_cap & MCG_CTL_P)
-            && (val == 0 || val == ~(uint64_t)0)) {
-            env->mcg_ctl = val;
-        }
-        break;
-    case MSR_TSC_AUX:
-        env->tsc_aux = val;
-        break;
-    case MSR_IA32_MISC_ENABLE:
-        env->msr_ia32_misc_enable = val;
-        break;
-    default:
-        if ((uint32_t)ECX >= MSR_MC0_CTL
-            && (uint32_t)ECX < MSR_MC0_CTL + (4 * env->mcg_cap & 0xff)) {
-            uint32_t offset = (uint32_t)ECX - MSR_MC0_CTL;
-            if ((offset & 0x3) != 0
-                || (val == 0 || val == ~(uint64_t)0)) {
-                env->mce_banks[offset] = val;
-            }
-            break;
-        }
-        /* XXX: exception? */
-        break;
-    }
-}
-
-void helper_rdmsr(void)
-{
-    uint64_t val;
-
-    cpu_svm_check_intercept_param(env, SVM_EXIT_MSR, 0);
-
-    switch ((uint32_t)ECX) {
-    case MSR_IA32_SYSENTER_CS:
-        val = env->sysenter_cs;
-        break;
-    case MSR_IA32_SYSENTER_ESP:
-        val = env->sysenter_esp;
-        break;
-    case MSR_IA32_SYSENTER_EIP:
-        val = env->sysenter_eip;
-        break;
-    case MSR_IA32_APICBASE:
-        val = cpu_get_apic_base(env->apic_state);
-        break;
-    case MSR_EFER:
-        val = env->efer;
-        break;
-    case MSR_STAR:
-        val = env->star;
-        break;
-    case MSR_PAT:
-        val = env->pat;
-        break;
-    case MSR_VM_HSAVE_PA:
-        val = env->vm_hsave;
-        break;
-    case MSR_IA32_PERF_STATUS:
-        /* tsc_increment_by_tick */
-        val = 1000ULL;
-        /* CPU multiplier */
-        val |= (((uint64_t)4ULL) << 40);
-        break;
-#ifdef TARGET_X86_64
-    case MSR_LSTAR:
-        val = env->lstar;
-        break;
-    case MSR_CSTAR:
-        val = env->cstar;
-        break;
-    case MSR_FMASK:
-        val = env->fmask;
-        break;
-    case MSR_FSBASE:
-        val = env->segs[R_FS].base;
-        break;
-    case MSR_GSBASE:
-        val = env->segs[R_GS].base;
-        break;
-    case MSR_KERNELGSBASE:
-        val = env->kernelgsbase;
-        break;
-    case MSR_TSC_AUX:
-        val = env->tsc_aux;
-        break;
-#endif
-    case MSR_MTRRphysBase(0):
-    case MSR_MTRRphysBase(1):
-    case MSR_MTRRphysBase(2):
-    case MSR_MTRRphysBase(3):
-    case MSR_MTRRphysBase(4):
-    case MSR_MTRRphysBase(5):
-    case MSR_MTRRphysBase(6):
-    case MSR_MTRRphysBase(7):
-        val = env->mtrr_var[((uint32_t)ECX - MSR_MTRRphysBase(0)) / 2].base;
-        break;
-    case MSR_MTRRphysMask(0):
-    case MSR_MTRRphysMask(1):
-    case MSR_MTRRphysMask(2):
-    case MSR_MTRRphysMask(3):
-    case MSR_MTRRphysMask(4):
-    case MSR_MTRRphysMask(5):
-    case MSR_MTRRphysMask(6):
-    case MSR_MTRRphysMask(7):
-        val = env->mtrr_var[((uint32_t)ECX - MSR_MTRRphysMask(0)) / 2].mask;
-        break;
-    case MSR_MTRRfix64K_00000:
-        val = env->mtrr_fixed[0];
-        break;
-    case MSR_MTRRfix16K_80000:
-    case MSR_MTRRfix16K_A0000:
-        val = env->mtrr_fixed[(uint32_t)ECX - MSR_MTRRfix16K_80000 + 1];
-        break;
-    case MSR_MTRRfix4K_C0000:
-    case MSR_MTRRfix4K_C8000:
-    case MSR_MTRRfix4K_D0000:
-    case MSR_MTRRfix4K_D8000:
-    case MSR_MTRRfix4K_E0000:
-    case MSR_MTRRfix4K_E8000:
-    case MSR_MTRRfix4K_F0000:
-    case MSR_MTRRfix4K_F8000:
-        val = env->mtrr_fixed[(uint32_t)ECX - MSR_MTRRfix4K_C0000 + 3];
-        break;
-    case MSR_MTRRdefType:
-        val = env->mtrr_deftype;
-        break;
-    case MSR_MTRRcap:
-        if (env->cpuid_features & CPUID_MTRR) {
-            val = MSR_MTRRcap_VCNT | MSR_MTRRcap_FIXRANGE_SUPPORT |
-                MSR_MTRRcap_WC_SUPPORTED;
-        } else {
-            /* XXX: exception? */
-            val = 0;
-        }
-        break;
-    case MSR_MCG_CAP:
-        val = env->mcg_cap;
-        break;
-    case MSR_MCG_CTL:
-        if (env->mcg_cap & MCG_CTL_P) {
-            val = env->mcg_ctl;
-        } else {
-            val = 0;
-        }
-        break;
-    case MSR_MCG_STATUS:
-        val = env->mcg_status;
-        break;
-    case MSR_IA32_MISC_ENABLE:
-        val = env->msr_ia32_misc_enable;
-        break;
-    default:
-        if ((uint32_t)ECX >= MSR_MC0_CTL
-            && (uint32_t)ECX < MSR_MC0_CTL + (4 * env->mcg_cap & 0xff)) {
-            uint32_t offset = (uint32_t)ECX - MSR_MC0_CTL;
-            val = env->mce_banks[offset];
-            break;
-        }
-        /* XXX: exception? */
-        val = 0;
-        break;
-    }
-    EAX = (uint32_t)(val);
-    EDX = (uint32_t)(val >> 32);
-}
-#endif
-
 target_ulong helper_lsl(target_ulong selector1)
 {
     unsigned int limit;
@@ -3065,54 +2535,6 @@ void cpu_x86_load_seg(CPUX86State *s, int seg_reg, int selector)
 }
 #endif
 
-static void do_hlt(void)
-{
-    env->hflags &= ~HF_INHIBIT_IRQ_MASK; /* needed if sti is just before */
-    env->halted = 1;
-    env->exception_index = EXCP_HLT;
-    cpu_loop_exit(env);
-}
-
-void helper_hlt(int next_eip_addend)
-{
-    cpu_svm_check_intercept_param(env, SVM_EXIT_HLT, 0);
-    EIP += next_eip_addend;
-
-    do_hlt();
-}
-
-void helper_monitor(target_ulong ptr)
-{
-    if ((uint32_t)ECX != 0) {
-        raise_exception(env, EXCP0D_GPF);
-    }
-    /* XXX: store address? */
-    cpu_svm_check_intercept_param(env, SVM_EXIT_MONITOR, 0);
-}
-
-void helper_mwait(int next_eip_addend)
-{
-    if ((uint32_t)ECX != 0) {
-        raise_exception(env, EXCP0D_GPF);
-    }
-    cpu_svm_check_intercept_param(env, SVM_EXIT_MWAIT, 0);
-    EIP += next_eip_addend;
-
-    /* XXX: not complete but not completely erroneous */
-    if (env->cpu_index != 0 || env->next_cpu != NULL) {
-        /* more than one CPU: do not sleep because another CPU may
-           wake this one */
-    } else {
-        do_hlt();
-    }
-}
-
-void helper_debug(void)
-{
-    env->exception_index = EXCP_DEBUG;
-    cpu_loop_exit(env);
-}
-
 void helper_boundw(target_ulong a0, int v)
 {
     int low, high;
commit ab109e5947a7c09b87152863b33a4eea0b714706
Author: Blue Swirl <blauwirbel at gmail.com>
Date:   Sun Apr 29 17:48:05 2012 +0000

    x86: split off SMM helpers
    
    Move SMM helpers to smm_helper.c.
    
    Signed-off-by: Blue Swirl <blauwirbel at gmail.com>

diff --git a/target-i386/Makefile.objs b/target-i386/Makefile.objs
index 25bea43..a2ba717 100644
--- a/target-i386/Makefile.objs
+++ b/target-i386/Makefile.objs
@@ -1,5 +1,6 @@
 obj-y += translate.o op_helper.o helper.o cpu.o
 obj-y += excp_helper.o fpu_helper.o cc_helper.o int_helper.o svm_helper.o
+obj-y += smm_helper.o
 obj-$(CONFIG_SOFTMMU) += machine.o arch_memory_mapping.o arch_dump.o
 obj-$(CONFIG_KVM) += kvm.o hyperv.o
 obj-$(CONFIG_LINUX_USER) += ioport-user.o
@@ -10,3 +11,4 @@ $(obj)/fpu_helper.o: QEMU_CFLAGS += $(HELPER_CFLAGS)
 $(obj)/cc_helper.o: QEMU_CFLAGS += $(HELPER_CFLAGS)
 $(obj)/int_helper.o: QEMU_CFLAGS += $(HELPER_CFLAGS)
 $(obj)/svm_helper.o: QEMU_CFLAGS += $(HELPER_CFLAGS)
+$(obj)/smm_helper.o: QEMU_CFLAGS += $(HELPER_CFLAGS)
diff --git a/target-i386/op_helper.c b/target-i386/op_helper.c
index 4c4974e..0d31afa 100644
--- a/target-i386/op_helper.c
+++ b/target-i386/op_helper.c
@@ -1353,291 +1353,6 @@ void do_interrupt_x86_hardirq(CPUX86State *env1, int intno, int is_hw)
     env = saved_env;
 }
 
-/* SMM support */
-
-#if defined(CONFIG_USER_ONLY)
-
-void do_smm_enter(CPUX86State *env1)
-{
-}
-
-void helper_rsm(void)
-{
-}
-
-#else
-
-#ifdef TARGET_X86_64
-#define SMM_REVISION_ID 0x00020064
-#else
-#define SMM_REVISION_ID 0x00020000
-#endif
-
-void do_smm_enter(CPUX86State *env1)
-{
-    target_ulong sm_state;
-    SegmentCache *dt;
-    int i, offset;
-    CPUX86State *saved_env;
-
-    saved_env = env;
-    env = env1;
-
-    qemu_log_mask(CPU_LOG_INT, "SMM: enter\n");
-    log_cpu_state_mask(CPU_LOG_INT, env, X86_DUMP_CCOP);
-
-    env->hflags |= HF_SMM_MASK;
-    cpu_smm_update(env);
-
-    sm_state = env->smbase + 0x8000;
-
-#ifdef TARGET_X86_64
-    for (i = 0; i < 6; i++) {
-        dt = &env->segs[i];
-        offset = 0x7e00 + i * 16;
-        stw_phys(sm_state + offset, dt->selector);
-        stw_phys(sm_state + offset + 2, (dt->flags >> 8) & 0xf0ff);
-        stl_phys(sm_state + offset + 4, dt->limit);
-        stq_phys(sm_state + offset + 8, dt->base);
-    }
-
-    stq_phys(sm_state + 0x7e68, env->gdt.base);
-    stl_phys(sm_state + 0x7e64, env->gdt.limit);
-
-    stw_phys(sm_state + 0x7e70, env->ldt.selector);
-    stq_phys(sm_state + 0x7e78, env->ldt.base);
-    stl_phys(sm_state + 0x7e74, env->ldt.limit);
-    stw_phys(sm_state + 0x7e72, (env->ldt.flags >> 8) & 0xf0ff);
-
-    stq_phys(sm_state + 0x7e88, env->idt.base);
-    stl_phys(sm_state + 0x7e84, env->idt.limit);
-
-    stw_phys(sm_state + 0x7e90, env->tr.selector);
-    stq_phys(sm_state + 0x7e98, env->tr.base);
-    stl_phys(sm_state + 0x7e94, env->tr.limit);
-    stw_phys(sm_state + 0x7e92, (env->tr.flags >> 8) & 0xf0ff);
-
-    stq_phys(sm_state + 0x7ed0, env->efer);
-
-    stq_phys(sm_state + 0x7ff8, EAX);
-    stq_phys(sm_state + 0x7ff0, ECX);
-    stq_phys(sm_state + 0x7fe8, EDX);
-    stq_phys(sm_state + 0x7fe0, EBX);
-    stq_phys(sm_state + 0x7fd8, ESP);
-    stq_phys(sm_state + 0x7fd0, EBP);
-    stq_phys(sm_state + 0x7fc8, ESI);
-    stq_phys(sm_state + 0x7fc0, EDI);
-    for (i = 8; i < 16; i++) {
-        stq_phys(sm_state + 0x7ff8 - i * 8, env->regs[i]);
-    }
-    stq_phys(sm_state + 0x7f78, env->eip);
-    stl_phys(sm_state + 0x7f70, cpu_compute_eflags(env));
-    stl_phys(sm_state + 0x7f68, env->dr[6]);
-    stl_phys(sm_state + 0x7f60, env->dr[7]);
-
-    stl_phys(sm_state + 0x7f48, env->cr[4]);
-    stl_phys(sm_state + 0x7f50, env->cr[3]);
-    stl_phys(sm_state + 0x7f58, env->cr[0]);
-
-    stl_phys(sm_state + 0x7efc, SMM_REVISION_ID);
-    stl_phys(sm_state + 0x7f00, env->smbase);
-#else
-    stl_phys(sm_state + 0x7ffc, env->cr[0]);
-    stl_phys(sm_state + 0x7ff8, env->cr[3]);
-    stl_phys(sm_state + 0x7ff4, cpu_compute_eflags(env));
-    stl_phys(sm_state + 0x7ff0, env->eip);
-    stl_phys(sm_state + 0x7fec, EDI);
-    stl_phys(sm_state + 0x7fe8, ESI);
-    stl_phys(sm_state + 0x7fe4, EBP);
-    stl_phys(sm_state + 0x7fe0, ESP);
-    stl_phys(sm_state + 0x7fdc, EBX);
-    stl_phys(sm_state + 0x7fd8, EDX);
-    stl_phys(sm_state + 0x7fd4, ECX);
-    stl_phys(sm_state + 0x7fd0, EAX);
-    stl_phys(sm_state + 0x7fcc, env->dr[6]);
-    stl_phys(sm_state + 0x7fc8, env->dr[7]);
-
-    stl_phys(sm_state + 0x7fc4, env->tr.selector);
-    stl_phys(sm_state + 0x7f64, env->tr.base);
-    stl_phys(sm_state + 0x7f60, env->tr.limit);
-    stl_phys(sm_state + 0x7f5c, (env->tr.flags >> 8) & 0xf0ff);
-
-    stl_phys(sm_state + 0x7fc0, env->ldt.selector);
-    stl_phys(sm_state + 0x7f80, env->ldt.base);
-    stl_phys(sm_state + 0x7f7c, env->ldt.limit);
-    stl_phys(sm_state + 0x7f78, (env->ldt.flags >> 8) & 0xf0ff);
-
-    stl_phys(sm_state + 0x7f74, env->gdt.base);
-    stl_phys(sm_state + 0x7f70, env->gdt.limit);
-
-    stl_phys(sm_state + 0x7f58, env->idt.base);
-    stl_phys(sm_state + 0x7f54, env->idt.limit);
-
-    for (i = 0; i < 6; i++) {
-        dt = &env->segs[i];
-        if (i < 3) {
-            offset = 0x7f84 + i * 12;
-        } else {
-            offset = 0x7f2c + (i - 3) * 12;
-        }
-        stl_phys(sm_state + 0x7fa8 + i * 4, dt->selector);
-        stl_phys(sm_state + offset + 8, dt->base);
-        stl_phys(sm_state + offset + 4, dt->limit);
-        stl_phys(sm_state + offset, (dt->flags >> 8) & 0xf0ff);
-    }
-    stl_phys(sm_state + 0x7f14, env->cr[4]);
-
-    stl_phys(sm_state + 0x7efc, SMM_REVISION_ID);
-    stl_phys(sm_state + 0x7ef8, env->smbase);
-#endif
-    /* init SMM cpu state */
-
-#ifdef TARGET_X86_64
-    cpu_load_efer(env, 0);
-#endif
-    cpu_load_eflags(env, 0, ~(CC_O | CC_S | CC_Z | CC_A | CC_P | CC_C |
-                              DF_MASK));
-    env->eip = 0x00008000;
-    cpu_x86_load_seg_cache(env, R_CS, (env->smbase >> 4) & 0xffff, env->smbase,
-                           0xffffffff, 0);
-    cpu_x86_load_seg_cache(env, R_DS, 0, 0, 0xffffffff, 0);
-    cpu_x86_load_seg_cache(env, R_ES, 0, 0, 0xffffffff, 0);
-    cpu_x86_load_seg_cache(env, R_SS, 0, 0, 0xffffffff, 0);
-    cpu_x86_load_seg_cache(env, R_FS, 0, 0, 0xffffffff, 0);
-    cpu_x86_load_seg_cache(env, R_GS, 0, 0, 0xffffffff, 0);
-
-    cpu_x86_update_cr0(env,
-                       env->cr[0] & ~(CR0_PE_MASK | CR0_EM_MASK | CR0_TS_MASK |
-                                      CR0_PG_MASK));
-    cpu_x86_update_cr4(env, 0);
-    env->dr[7] = 0x00000400;
-    CC_OP = CC_OP_EFLAGS;
-    env = saved_env;
-}
-
-void helper_rsm(void)
-{
-    target_ulong sm_state;
-    int i, offset;
-    uint32_t val;
-
-    sm_state = env->smbase + 0x8000;
-#ifdef TARGET_X86_64
-    cpu_load_efer(env, ldq_phys(sm_state + 0x7ed0));
-
-    for (i = 0; i < 6; i++) {
-        offset = 0x7e00 + i * 16;
-        cpu_x86_load_seg_cache(env, i,
-                               lduw_phys(sm_state + offset),
-                               ldq_phys(sm_state + offset + 8),
-                               ldl_phys(sm_state + offset + 4),
-                               (lduw_phys(sm_state + offset + 2) &
-                                0xf0ff) << 8);
-    }
-
-    env->gdt.base = ldq_phys(sm_state + 0x7e68);
-    env->gdt.limit = ldl_phys(sm_state + 0x7e64);
-
-    env->ldt.selector = lduw_phys(sm_state + 0x7e70);
-    env->ldt.base = ldq_phys(sm_state + 0x7e78);
-    env->ldt.limit = ldl_phys(sm_state + 0x7e74);
-    env->ldt.flags = (lduw_phys(sm_state + 0x7e72) & 0xf0ff) << 8;
-
-    env->idt.base = ldq_phys(sm_state + 0x7e88);
-    env->idt.limit = ldl_phys(sm_state + 0x7e84);
-
-    env->tr.selector = lduw_phys(sm_state + 0x7e90);
-    env->tr.base = ldq_phys(sm_state + 0x7e98);
-    env->tr.limit = ldl_phys(sm_state + 0x7e94);
-    env->tr.flags = (lduw_phys(sm_state + 0x7e92) & 0xf0ff) << 8;
-
-    EAX = ldq_phys(sm_state + 0x7ff8);
-    ECX = ldq_phys(sm_state + 0x7ff0);
-    EDX = ldq_phys(sm_state + 0x7fe8);
-    EBX = ldq_phys(sm_state + 0x7fe0);
-    ESP = ldq_phys(sm_state + 0x7fd8);
-    EBP = ldq_phys(sm_state + 0x7fd0);
-    ESI = ldq_phys(sm_state + 0x7fc8);
-    EDI = ldq_phys(sm_state + 0x7fc0);
-    for (i = 8; i < 16; i++) {
-        env->regs[i] = ldq_phys(sm_state + 0x7ff8 - i * 8);
-    }
-    env->eip = ldq_phys(sm_state + 0x7f78);
-    cpu_load_eflags(env, ldl_phys(sm_state + 0x7f70),
-                    ~(CC_O | CC_S | CC_Z | CC_A | CC_P | CC_C | DF_MASK));
-    env->dr[6] = ldl_phys(sm_state + 0x7f68);
-    env->dr[7] = ldl_phys(sm_state + 0x7f60);
-
-    cpu_x86_update_cr4(env, ldl_phys(sm_state + 0x7f48));
-    cpu_x86_update_cr3(env, ldl_phys(sm_state + 0x7f50));
-    cpu_x86_update_cr0(env, ldl_phys(sm_state + 0x7f58));
-
-    val = ldl_phys(sm_state + 0x7efc); /* revision ID */
-    if (val & 0x20000) {
-        env->smbase = ldl_phys(sm_state + 0x7f00) & ~0x7fff;
-    }
-#else
-    cpu_x86_update_cr0(env, ldl_phys(sm_state + 0x7ffc));
-    cpu_x86_update_cr3(env, ldl_phys(sm_state + 0x7ff8));
-    cpu_load_eflags(env, ldl_phys(sm_state + 0x7ff4),
-                    ~(CC_O | CC_S | CC_Z | CC_A | CC_P | CC_C | DF_MASK));
-    env->eip = ldl_phys(sm_state + 0x7ff0);
-    EDI = ldl_phys(sm_state + 0x7fec);
-    ESI = ldl_phys(sm_state + 0x7fe8);
-    EBP = ldl_phys(sm_state + 0x7fe4);
-    ESP = ldl_phys(sm_state + 0x7fe0);
-    EBX = ldl_phys(sm_state + 0x7fdc);
-    EDX = ldl_phys(sm_state + 0x7fd8);
-    ECX = ldl_phys(sm_state + 0x7fd4);
-    EAX = ldl_phys(sm_state + 0x7fd0);
-    env->dr[6] = ldl_phys(sm_state + 0x7fcc);
-    env->dr[7] = ldl_phys(sm_state + 0x7fc8);
-
-    env->tr.selector = ldl_phys(sm_state + 0x7fc4) & 0xffff;
-    env->tr.base = ldl_phys(sm_state + 0x7f64);
-    env->tr.limit = ldl_phys(sm_state + 0x7f60);
-    env->tr.flags = (ldl_phys(sm_state + 0x7f5c) & 0xf0ff) << 8;
-
-    env->ldt.selector = ldl_phys(sm_state + 0x7fc0) & 0xffff;
-    env->ldt.base = ldl_phys(sm_state + 0x7f80);
-    env->ldt.limit = ldl_phys(sm_state + 0x7f7c);
-    env->ldt.flags = (ldl_phys(sm_state + 0x7f78) & 0xf0ff) << 8;
-
-    env->gdt.base = ldl_phys(sm_state + 0x7f74);
-    env->gdt.limit = ldl_phys(sm_state + 0x7f70);
-
-    env->idt.base = ldl_phys(sm_state + 0x7f58);
-    env->idt.limit = ldl_phys(sm_state + 0x7f54);
-
-    for (i = 0; i < 6; i++) {
-        if (i < 3) {
-            offset = 0x7f84 + i * 12;
-        } else {
-            offset = 0x7f2c + (i - 3) * 12;
-        }
-        cpu_x86_load_seg_cache(env, i,
-                               ldl_phys(sm_state + 0x7fa8 + i * 4) & 0xffff,
-                               ldl_phys(sm_state + offset + 8),
-                               ldl_phys(sm_state + offset + 4),
-                               (ldl_phys(sm_state + offset) & 0xf0ff) << 8);
-    }
-    cpu_x86_update_cr4(env, ldl_phys(sm_state + 0x7f14));
-
-    val = ldl_phys(sm_state + 0x7efc); /* revision ID */
-    if (val & 0x20000) {
-        env->smbase = ldl_phys(sm_state + 0x7ef8) & ~0x7fff;
-    }
-#endif
-    CC_OP = CC_OP_EFLAGS;
-    env->hflags &= ~HF_SMM_MASK;
-    cpu_smm_update(env);
-
-    qemu_log_mask(CPU_LOG_INT, "SMM: after RSM\n");
-    log_cpu_state_mask(CPU_LOG_INT, env, X86_DUMP_CCOP);
-}
-
-#endif /* !CONFIG_USER_ONLY */
-
 void helper_into(int next_eip_addend)
 {
     int eflags;
diff --git a/target-i386/smm_helper.c b/target-i386/smm_helper.c
new file mode 100644
index 0000000..bc1bfa2
--- /dev/null
+++ b/target-i386/smm_helper.c
@@ -0,0 +1,307 @@
+/*
+ *  x86 SMM helpers
+ *
+ *  Copyright (c) 2003 Fabrice Bellard
+ *
+ * This library is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Lesser General Public
+ * License as published by the Free Software Foundation; either
+ * version 2 of the License, or (at your option) any later version.
+ *
+ * This library is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
+ * Lesser General Public License for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public
+ * License along with this library; if not, see <http://www.gnu.org/licenses/>.
+ */
+
+#include "cpu.h"
+#include "dyngen-exec.h"
+#include "helper.h"
+
+/* SMM support */
+
+#if defined(CONFIG_USER_ONLY)
+
+void do_smm_enter(CPUX86State *env1)
+{
+}
+
+void helper_rsm(void)
+{
+}
+
+#else
+
+#ifdef TARGET_X86_64
+#define SMM_REVISION_ID 0x00020064
+#else
+#define SMM_REVISION_ID 0x00020000
+#endif
+
+void do_smm_enter(CPUX86State *env1)
+{
+    target_ulong sm_state;
+    SegmentCache *dt;
+    int i, offset;
+    CPUX86State *saved_env;
+
+    saved_env = env;
+    env = env1;
+
+    qemu_log_mask(CPU_LOG_INT, "SMM: enter\n");
+    log_cpu_state_mask(CPU_LOG_INT, env, X86_DUMP_CCOP);
+
+    env->hflags |= HF_SMM_MASK;
+    cpu_smm_update(env);
+
+    sm_state = env->smbase + 0x8000;
+
+#ifdef TARGET_X86_64
+    for (i = 0; i < 6; i++) {
+        dt = &env->segs[i];
+        offset = 0x7e00 + i * 16;
+        stw_phys(sm_state + offset, dt->selector);
+        stw_phys(sm_state + offset + 2, (dt->flags >> 8) & 0xf0ff);
+        stl_phys(sm_state + offset + 4, dt->limit);
+        stq_phys(sm_state + offset + 8, dt->base);
+    }
+
+    stq_phys(sm_state + 0x7e68, env->gdt.base);
+    stl_phys(sm_state + 0x7e64, env->gdt.limit);
+
+    stw_phys(sm_state + 0x7e70, env->ldt.selector);
+    stq_phys(sm_state + 0x7e78, env->ldt.base);
+    stl_phys(sm_state + 0x7e74, env->ldt.limit);
+    stw_phys(sm_state + 0x7e72, (env->ldt.flags >> 8) & 0xf0ff);
+
+    stq_phys(sm_state + 0x7e88, env->idt.base);
+    stl_phys(sm_state + 0x7e84, env->idt.limit);
+
+    stw_phys(sm_state + 0x7e90, env->tr.selector);
+    stq_phys(sm_state + 0x7e98, env->tr.base);
+    stl_phys(sm_state + 0x7e94, env->tr.limit);
+    stw_phys(sm_state + 0x7e92, (env->tr.flags >> 8) & 0xf0ff);
+
+    stq_phys(sm_state + 0x7ed0, env->efer);
+
+    stq_phys(sm_state + 0x7ff8, EAX);
+    stq_phys(sm_state + 0x7ff0, ECX);
+    stq_phys(sm_state + 0x7fe8, EDX);
+    stq_phys(sm_state + 0x7fe0, EBX);
+    stq_phys(sm_state + 0x7fd8, ESP);
+    stq_phys(sm_state + 0x7fd0, EBP);
+    stq_phys(sm_state + 0x7fc8, ESI);
+    stq_phys(sm_state + 0x7fc0, EDI);
+    for (i = 8; i < 16; i++) {
+        stq_phys(sm_state + 0x7ff8 - i * 8, env->regs[i]);
+    }
+    stq_phys(sm_state + 0x7f78, env->eip);
+    stl_phys(sm_state + 0x7f70, cpu_compute_eflags(env));
+    stl_phys(sm_state + 0x7f68, env->dr[6]);
+    stl_phys(sm_state + 0x7f60, env->dr[7]);
+
+    stl_phys(sm_state + 0x7f48, env->cr[4]);
+    stl_phys(sm_state + 0x7f50, env->cr[3]);
+    stl_phys(sm_state + 0x7f58, env->cr[0]);
+
+    stl_phys(sm_state + 0x7efc, SMM_REVISION_ID);
+    stl_phys(sm_state + 0x7f00, env->smbase);
+#else
+    stl_phys(sm_state + 0x7ffc, env->cr[0]);
+    stl_phys(sm_state + 0x7ff8, env->cr[3]);
+    stl_phys(sm_state + 0x7ff4, cpu_compute_eflags(env));
+    stl_phys(sm_state + 0x7ff0, env->eip);
+    stl_phys(sm_state + 0x7fec, EDI);
+    stl_phys(sm_state + 0x7fe8, ESI);
+    stl_phys(sm_state + 0x7fe4, EBP);
+    stl_phys(sm_state + 0x7fe0, ESP);
+    stl_phys(sm_state + 0x7fdc, EBX);
+    stl_phys(sm_state + 0x7fd8, EDX);
+    stl_phys(sm_state + 0x7fd4, ECX);
+    stl_phys(sm_state + 0x7fd0, EAX);
+    stl_phys(sm_state + 0x7fcc, env->dr[6]);
+    stl_phys(sm_state + 0x7fc8, env->dr[7]);
+
+    stl_phys(sm_state + 0x7fc4, env->tr.selector);
+    stl_phys(sm_state + 0x7f64, env->tr.base);
+    stl_phys(sm_state + 0x7f60, env->tr.limit);
+    stl_phys(sm_state + 0x7f5c, (env->tr.flags >> 8) & 0xf0ff);
+
+    stl_phys(sm_state + 0x7fc0, env->ldt.selector);
+    stl_phys(sm_state + 0x7f80, env->ldt.base);
+    stl_phys(sm_state + 0x7f7c, env->ldt.limit);
+    stl_phys(sm_state + 0x7f78, (env->ldt.flags >> 8) & 0xf0ff);
+
+    stl_phys(sm_state + 0x7f74, env->gdt.base);
+    stl_phys(sm_state + 0x7f70, env->gdt.limit);
+
+    stl_phys(sm_state + 0x7f58, env->idt.base);
+    stl_phys(sm_state + 0x7f54, env->idt.limit);
+
+    for (i = 0; i < 6; i++) {
+        dt = &env->segs[i];
+        if (i < 3) {
+            offset = 0x7f84 + i * 12;
+        } else {
+            offset = 0x7f2c + (i - 3) * 12;
+        }
+        stl_phys(sm_state + 0x7fa8 + i * 4, dt->selector);
+        stl_phys(sm_state + offset + 8, dt->base);
+        stl_phys(sm_state + offset + 4, dt->limit);
+        stl_phys(sm_state + offset, (dt->flags >> 8) & 0xf0ff);
+    }
+    stl_phys(sm_state + 0x7f14, env->cr[4]);
+
+    stl_phys(sm_state + 0x7efc, SMM_REVISION_ID);
+    stl_phys(sm_state + 0x7ef8, env->smbase);
+#endif
+    /* init SMM cpu state */
+
+#ifdef TARGET_X86_64
+    cpu_load_efer(env, 0);
+#endif
+    cpu_load_eflags(env, 0, ~(CC_O | CC_S | CC_Z | CC_A | CC_P | CC_C |
+                              DF_MASK));
+    env->eip = 0x00008000;
+    cpu_x86_load_seg_cache(env, R_CS, (env->smbase >> 4) & 0xffff, env->smbase,
+                           0xffffffff, 0);
+    cpu_x86_load_seg_cache(env, R_DS, 0, 0, 0xffffffff, 0);
+    cpu_x86_load_seg_cache(env, R_ES, 0, 0, 0xffffffff, 0);
+    cpu_x86_load_seg_cache(env, R_SS, 0, 0, 0xffffffff, 0);
+    cpu_x86_load_seg_cache(env, R_FS, 0, 0, 0xffffffff, 0);
+    cpu_x86_load_seg_cache(env, R_GS, 0, 0, 0xffffffff, 0);
+
+    cpu_x86_update_cr0(env,
+                       env->cr[0] & ~(CR0_PE_MASK | CR0_EM_MASK | CR0_TS_MASK |
+                                      CR0_PG_MASK));
+    cpu_x86_update_cr4(env, 0);
+    env->dr[7] = 0x00000400;
+    CC_OP = CC_OP_EFLAGS;
+    env = saved_env;
+}
+
+void helper_rsm(void)
+{
+    target_ulong sm_state;
+    int i, offset;
+    uint32_t val;
+
+    sm_state = env->smbase + 0x8000;
+#ifdef TARGET_X86_64
+    cpu_load_efer(env, ldq_phys(sm_state + 0x7ed0));
+
+    for (i = 0; i < 6; i++) {
+        offset = 0x7e00 + i * 16;
+        cpu_x86_load_seg_cache(env, i,
+                               lduw_phys(sm_state + offset),
+                               ldq_phys(sm_state + offset + 8),
+                               ldl_phys(sm_state + offset + 4),
+                               (lduw_phys(sm_state + offset + 2) &
+                                0xf0ff) << 8);
+    }
+
+    env->gdt.base = ldq_phys(sm_state + 0x7e68);
+    env->gdt.limit = ldl_phys(sm_state + 0x7e64);
+
+    env->ldt.selector = lduw_phys(sm_state + 0x7e70);
+    env->ldt.base = ldq_phys(sm_state + 0x7e78);
+    env->ldt.limit = ldl_phys(sm_state + 0x7e74);
+    env->ldt.flags = (lduw_phys(sm_state + 0x7e72) & 0xf0ff) << 8;
+
+    env->idt.base = ldq_phys(sm_state + 0x7e88);
+    env->idt.limit = ldl_phys(sm_state + 0x7e84);
+
+    env->tr.selector = lduw_phys(sm_state + 0x7e90);
+    env->tr.base = ldq_phys(sm_state + 0x7e98);
+    env->tr.limit = ldl_phys(sm_state + 0x7e94);
+    env->tr.flags = (lduw_phys(sm_state + 0x7e92) & 0xf0ff) << 8;
+
+    EAX = ldq_phys(sm_state + 0x7ff8);
+    ECX = ldq_phys(sm_state + 0x7ff0);
+    EDX = ldq_phys(sm_state + 0x7fe8);
+    EBX = ldq_phys(sm_state + 0x7fe0);
+    ESP = ldq_phys(sm_state + 0x7fd8);
+    EBP = ldq_phys(sm_state + 0x7fd0);
+    ESI = ldq_phys(sm_state + 0x7fc8);
+    EDI = ldq_phys(sm_state + 0x7fc0);
+    for (i = 8; i < 16; i++) {
+        env->regs[i] = ldq_phys(sm_state + 0x7ff8 - i * 8);
+    }
+    env->eip = ldq_phys(sm_state + 0x7f78);
+    cpu_load_eflags(env, ldl_phys(sm_state + 0x7f70),
+                    ~(CC_O | CC_S | CC_Z | CC_A | CC_P | CC_C | DF_MASK));
+    env->dr[6] = ldl_phys(sm_state + 0x7f68);
+    env->dr[7] = ldl_phys(sm_state + 0x7f60);
+
+    cpu_x86_update_cr4(env, ldl_phys(sm_state + 0x7f48));
+    cpu_x86_update_cr3(env, ldl_phys(sm_state + 0x7f50));
+    cpu_x86_update_cr0(env, ldl_phys(sm_state + 0x7f58));
+
+    val = ldl_phys(sm_state + 0x7efc); /* revision ID */
+    if (val & 0x20000) {
+        env->smbase = ldl_phys(sm_state + 0x7f00) & ~0x7fff;
+    }
+#else
+    cpu_x86_update_cr0(env, ldl_phys(sm_state + 0x7ffc));
+    cpu_x86_update_cr3(env, ldl_phys(sm_state + 0x7ff8));
+    cpu_load_eflags(env, ldl_phys(sm_state + 0x7ff4),
+                    ~(CC_O | CC_S | CC_Z | CC_A | CC_P | CC_C | DF_MASK));
+    env->eip = ldl_phys(sm_state + 0x7ff0);
+    EDI = ldl_phys(sm_state + 0x7fec);
+    ESI = ldl_phys(sm_state + 0x7fe8);
+    EBP = ldl_phys(sm_state + 0x7fe4);
+    ESP = ldl_phys(sm_state + 0x7fe0);
+    EBX = ldl_phys(sm_state + 0x7fdc);
+    EDX = ldl_phys(sm_state + 0x7fd8);
+    ECX = ldl_phys(sm_state + 0x7fd4);
+    EAX = ldl_phys(sm_state + 0x7fd0);
+    env->dr[6] = ldl_phys(sm_state + 0x7fcc);
+    env->dr[7] = ldl_phys(sm_state + 0x7fc8);
+
+    env->tr.selector = ldl_phys(sm_state + 0x7fc4) & 0xffff;
+    env->tr.base = ldl_phys(sm_state + 0x7f64);
+    env->tr.limit = ldl_phys(sm_state + 0x7f60);
+    env->tr.flags = (ldl_phys(sm_state + 0x7f5c) & 0xf0ff) << 8;
+
+    env->ldt.selector = ldl_phys(sm_state + 0x7fc0) & 0xffff;
+    env->ldt.base = ldl_phys(sm_state + 0x7f80);
+    env->ldt.limit = ldl_phys(sm_state + 0x7f7c);
+    env->ldt.flags = (ldl_phys(sm_state + 0x7f78) & 0xf0ff) << 8;
+
+    env->gdt.base = ldl_phys(sm_state + 0x7f74);
+    env->gdt.limit = ldl_phys(sm_state + 0x7f70);
+
+    env->idt.base = ldl_phys(sm_state + 0x7f58);
+    env->idt.limit = ldl_phys(sm_state + 0x7f54);
+
+    for (i = 0; i < 6; i++) {
+        if (i < 3) {
+            offset = 0x7f84 + i * 12;
+        } else {
+            offset = 0x7f2c + (i - 3) * 12;
+        }
+        cpu_x86_load_seg_cache(env, i,
+                               ldl_phys(sm_state + 0x7fa8 + i * 4) & 0xffff,
+                               ldl_phys(sm_state + offset + 8),
+                               ldl_phys(sm_state + offset + 4),
+                               (ldl_phys(sm_state + offset) & 0xf0ff) << 8);
+    }
+    cpu_x86_update_cr4(env, ldl_phys(sm_state + 0x7f14));
+
+    val = ldl_phys(sm_state + 0x7efc); /* revision ID */
+    if (val & 0x20000) {
+        env->smbase = ldl_phys(sm_state + 0x7ef8) & ~0x7fff;
+    }
+#endif
+    CC_OP = CC_OP_EFLAGS;
+    env->hflags &= ~HF_SMM_MASK;
+    cpu_smm_update(env);
+
+    qemu_log_mask(CPU_LOG_INT, "SMM: after RSM\n");
+    log_cpu_state_mask(CPU_LOG_INT, env, X86_DUMP_CCOP);
+}
+
+#endif /* !CONFIG_USER_ONLY */
commit 6bada5e80ee5941a3b7ab118b738a4097dd76e37
Author: Blue Swirl <blauwirbel at gmail.com>
Date:   Sun Apr 29 14:42:35 2012 +0000

    x86: split off SVM helpers
    
    Move SVM helpers to svm_helper.c.
    
    Signed-off-by: Blue Swirl <blauwirbel at gmail.com>

diff --git a/target-i386/Makefile.objs b/target-i386/Makefile.objs
index d4cbcd7..25bea43 100644
--- a/target-i386/Makefile.objs
+++ b/target-i386/Makefile.objs
@@ -1,5 +1,5 @@
 obj-y += translate.o op_helper.o helper.o cpu.o
-obj-y += excp_helper.o fpu_helper.o cc_helper.o int_helper.o
+obj-y += excp_helper.o fpu_helper.o cc_helper.o int_helper.o svm_helper.o
 obj-$(CONFIG_SOFTMMU) += machine.o arch_memory_mapping.o arch_dump.o
 obj-$(CONFIG_KVM) += kvm.o hyperv.o
 obj-$(CONFIG_LINUX_USER) += ioport-user.o
@@ -9,3 +9,4 @@ $(obj)/op_helper.o: QEMU_CFLAGS += $(HELPER_CFLAGS)
 $(obj)/fpu_helper.o: QEMU_CFLAGS += $(HELPER_CFLAGS)
 $(obj)/cc_helper.o: QEMU_CFLAGS += $(HELPER_CFLAGS)
 $(obj)/int_helper.o: QEMU_CFLAGS += $(HELPER_CFLAGS)
+$(obj)/svm_helper.o: QEMU_CFLAGS += $(HELPER_CFLAGS)
diff --git a/target-i386/cpu.h b/target-i386/cpu.h
index 7d7ad33..f257c97 100644
--- a/target-i386/cpu.h
+++ b/target-i386/cpu.h
@@ -1121,16 +1121,17 @@ static inline void cpu_load_efer(CPUX86State *env, uint64_t val)
     }
 }
 
+/* svm_helper.c */
+void cpu_svm_check_intercept_param(CPUX86State *env1, uint32_t type,
+                                   uint64_t param);
+void cpu_vmexit(CPUX86State *nenv, uint32_t exit_code, uint64_t exit_info_1);
+
 /* op_helper.c */
 void do_interrupt(CPUX86State *env);
 void do_interrupt_x86_hardirq(CPUX86State *env, int intno, int is_hw);
 
 void do_smm_enter(CPUX86State *env1);
 
-void cpu_svm_check_intercept_param(CPUX86State *env1, uint32_t type,
-                                   uint64_t param);
-void cpu_vmexit(CPUX86State *nenv, uint32_t exit_code, uint64_t exit_info_1);
-
 void cpu_report_tpr_access(CPUX86State *env, TPRAccess access);
 
 #endif /* CPU_I386_H */
diff --git a/target-i386/op_helper.c b/target-i386/op_helper.c
index af8ff64..4c4974e 100644
--- a/target-i386/op_helper.c
+++ b/target-i386/op_helper.c
@@ -1709,7 +1709,7 @@ void helper_cpuid(void)
 {
     uint32_t eax, ebx, ecx, edx;
 
-    helper_svm_check_intercept_param(SVM_EXIT_CPUID, 0);
+    cpu_svm_check_intercept_param(env, SVM_EXIT_CPUID, 0);
 
     cpu_x86_cpuid(env, (uint32_t)EAX, (uint32_t)ECX, &eax, &ebx, &ecx, &edx);
     EAX = eax;
@@ -2757,7 +2757,7 @@ target_ulong helper_read_crN(int reg)
 {
     target_ulong val;
 
-    helper_svm_check_intercept_param(SVM_EXIT_READ_CR0 + reg, 0);
+    cpu_svm_check_intercept_param(env, SVM_EXIT_READ_CR0 + reg, 0);
     switch (reg) {
     default:
         val = env->cr[reg];
@@ -2775,7 +2775,7 @@ target_ulong helper_read_crN(int reg)
 
 void helper_write_crN(int reg, target_ulong t0)
 {
-    helper_svm_check_intercept_param(SVM_EXIT_WRITE_CR0 + reg, 0);
+    cpu_svm_check_intercept_param(env, SVM_EXIT_WRITE_CR0 + reg, 0);
     switch (reg) {
     case 0:
         cpu_x86_update_cr0(env, t0);
@@ -2830,7 +2830,7 @@ void helper_lmsw(target_ulong t0)
 
 void helper_invlpg(target_ulong addr)
 {
-    helper_svm_check_intercept_param(SVM_EXIT_INVLPG, 0);
+    cpu_svm_check_intercept_param(env, SVM_EXIT_INVLPG, 0);
     tlb_flush_page(env, addr);
 }
 
@@ -2841,7 +2841,7 @@ void helper_rdtsc(void)
     if ((env->cr[4] & CR4_TSD_MASK) && ((env->hflags & HF_CPL_MASK) != 0)) {
         raise_exception(env, EXCP0D_GPF);
     }
-    helper_svm_check_intercept_param(SVM_EXIT_RDTSC, 0);
+    cpu_svm_check_intercept_param(env, SVM_EXIT_RDTSC, 0);
 
     val = cpu_get_tsc(env) + env->tsc_offset;
     EAX = (uint32_t)(val);
@@ -2859,7 +2859,7 @@ void helper_rdpmc(void)
     if ((env->cr[4] & CR4_PCE_MASK) && ((env->hflags & HF_CPL_MASK) != 0)) {
         raise_exception(env, EXCP0D_GPF);
     }
-    helper_svm_check_intercept_param(SVM_EXIT_RDPMC, 0);
+    cpu_svm_check_intercept_param(env, SVM_EXIT_RDPMC, 0);
 
     /* currently unimplemented */
     qemu_log_mask(LOG_UNIMP, "x86: unimplemented rdpmc\n");
@@ -2879,7 +2879,7 @@ void helper_wrmsr(void)
 {
     uint64_t val;
 
-    helper_svm_check_intercept_param(SVM_EXIT_MSR, 1);
+    cpu_svm_check_intercept_param(env, SVM_EXIT_MSR, 1);
 
     val = ((uint32_t)EAX) | ((uint64_t)((uint32_t)EDX) << 32);
 
@@ -3026,7 +3026,7 @@ void helper_rdmsr(void)
 {
     uint64_t val;
 
-    helper_svm_check_intercept_param(SVM_EXIT_MSR, 0);
+    cpu_svm_check_intercept_param(env, SVM_EXIT_MSR, 0);
 
     switch ((uint32_t)ECX) {
     case MSR_IA32_SYSENTER_CS:
@@ -3360,7 +3360,7 @@ static void do_hlt(void)
 
 void helper_hlt(int next_eip_addend)
 {
-    helper_svm_check_intercept_param(SVM_EXIT_HLT, 0);
+    cpu_svm_check_intercept_param(env, SVM_EXIT_HLT, 0);
     EIP += next_eip_addend;
 
     do_hlt();
@@ -3372,7 +3372,7 @@ void helper_monitor(target_ulong ptr)
         raise_exception(env, EXCP0D_GPF);
     }
     /* XXX: store address? */
-    helper_svm_check_intercept_param(SVM_EXIT_MONITOR, 0);
+    cpu_svm_check_intercept_param(env, SVM_EXIT_MONITOR, 0);
 }
 
 void helper_mwait(int next_eip_addend)
@@ -3380,7 +3380,7 @@ void helper_mwait(int next_eip_addend)
     if ((uint32_t)ECX != 0) {
         raise_exception(env, EXCP0D_GPF);
     }
-    helper_svm_check_intercept_param(SVM_EXIT_MWAIT, 0);
+    cpu_svm_check_intercept_param(env, SVM_EXIT_MWAIT, 0);
     EIP += next_eip_addend;
 
     /* XXX: not complete but not completely erroneous */
@@ -3470,697 +3470,3 @@ void tlb_fill(CPUX86State *env1, target_ulong addr, int is_write, int mmu_idx,
     env = saved_env;
 }
 #endif
-
-/* Secure Virtual Machine helpers */
-
-#if defined(CONFIG_USER_ONLY)
-
-void helper_vmrun(int aflag, int next_eip_addend)
-{
-}
-
-void helper_vmmcall(void)
-{
-}
-
-void helper_vmload(int aflag)
-{
-}
-
-void helper_vmsave(int aflag)
-{
-}
-
-void helper_stgi(void)
-{
-}
-
-void helper_clgi(void)
-{
-}
-
-void helper_skinit(void)
-{
-}
-
-void helper_invlpga(int aflag)
-{
-}
-
-void helper_vmexit(uint32_t exit_code, uint64_t exit_info_1)
-{
-}
-
-void cpu_vmexit(CPUX86State *nenv, uint32_t exit_code, uint64_t exit_info_1)
-{
-}
-
-void helper_svm_check_intercept_param(uint32_t type, uint64_t param)
-{
-}
-
-void cpu_svm_check_intercept_param(CPUX86State *env, uint32_t type,
-                                   uint64_t param)
-{
-}
-
-void helper_svm_check_io(uint32_t port, uint32_t param,
-                         uint32_t next_eip_addend)
-{
-}
-#else
-
-static inline void svm_save_seg(target_phys_addr_t addr,
-                                const SegmentCache *sc)
-{
-    stw_phys(addr + offsetof(struct vmcb_seg, selector),
-             sc->selector);
-    stq_phys(addr + offsetof(struct vmcb_seg, base),
-             sc->base);
-    stl_phys(addr + offsetof(struct vmcb_seg, limit),
-             sc->limit);
-    stw_phys(addr + offsetof(struct vmcb_seg, attrib),
-             ((sc->flags >> 8) & 0xff) | ((sc->flags >> 12) & 0x0f00));
-}
-
-static inline void svm_load_seg(target_phys_addr_t addr, SegmentCache *sc)
-{
-    unsigned int flags;
-
-    sc->selector = lduw_phys(addr + offsetof(struct vmcb_seg, selector));
-    sc->base = ldq_phys(addr + offsetof(struct vmcb_seg, base));
-    sc->limit = ldl_phys(addr + offsetof(struct vmcb_seg, limit));
-    flags = lduw_phys(addr + offsetof(struct vmcb_seg, attrib));
-    sc->flags = ((flags & 0xff) << 8) | ((flags & 0x0f00) << 12);
-}
-
-static inline void svm_load_seg_cache(target_phys_addr_t addr,
-                                      CPUX86State *env, int seg_reg)
-{
-    SegmentCache sc1, *sc = &sc1;
-
-    svm_load_seg(addr, sc);
-    cpu_x86_load_seg_cache(env, seg_reg, sc->selector,
-                           sc->base, sc->limit, sc->flags);
-}
-
-void helper_vmrun(int aflag, int next_eip_addend)
-{
-    target_ulong addr;
-    uint32_t event_inj;
-    uint32_t int_ctl;
-
-    helper_svm_check_intercept_param(SVM_EXIT_VMRUN, 0);
-
-    if (aflag == 2) {
-        addr = EAX;
-    } else {
-        addr = (uint32_t)EAX;
-    }
-
-    qemu_log_mask(CPU_LOG_TB_IN_ASM, "vmrun! " TARGET_FMT_lx "\n", addr);
-
-    env->vm_vmcb = addr;
-
-    /* save the current CPU state in the hsave page */
-    stq_phys(env->vm_hsave + offsetof(struct vmcb, save.gdtr.base),
-             env->gdt.base);
-    stl_phys(env->vm_hsave + offsetof(struct vmcb, save.gdtr.limit),
-             env->gdt.limit);
-
-    stq_phys(env->vm_hsave + offsetof(struct vmcb, save.idtr.base),
-             env->idt.base);
-    stl_phys(env->vm_hsave + offsetof(struct vmcb, save.idtr.limit),
-             env->idt.limit);
-
-    stq_phys(env->vm_hsave + offsetof(struct vmcb, save.cr0), env->cr[0]);
-    stq_phys(env->vm_hsave + offsetof(struct vmcb, save.cr2), env->cr[2]);
-    stq_phys(env->vm_hsave + offsetof(struct vmcb, save.cr3), env->cr[3]);
-    stq_phys(env->vm_hsave + offsetof(struct vmcb, save.cr4), env->cr[4]);
-    stq_phys(env->vm_hsave + offsetof(struct vmcb, save.dr6), env->dr[6]);
-    stq_phys(env->vm_hsave + offsetof(struct vmcb, save.dr7), env->dr[7]);
-
-    stq_phys(env->vm_hsave + offsetof(struct vmcb, save.efer), env->efer);
-    stq_phys(env->vm_hsave + offsetof(struct vmcb, save.rflags),
-             cpu_compute_eflags(env));
-
-    svm_save_seg(env->vm_hsave + offsetof(struct vmcb, save.es),
-                 &env->segs[R_ES]);
-    svm_save_seg(env->vm_hsave + offsetof(struct vmcb, save.cs),
-                 &env->segs[R_CS]);
-    svm_save_seg(env->vm_hsave + offsetof(struct vmcb, save.ss),
-                 &env->segs[R_SS]);
-    svm_save_seg(env->vm_hsave + offsetof(struct vmcb, save.ds),
-                 &env->segs[R_DS]);
-
-    stq_phys(env->vm_hsave + offsetof(struct vmcb, save.rip),
-             EIP + next_eip_addend);
-    stq_phys(env->vm_hsave + offsetof(struct vmcb, save.rsp), ESP);
-    stq_phys(env->vm_hsave + offsetof(struct vmcb, save.rax), EAX);
-
-    /* load the interception bitmaps so we do not need to access the
-       vmcb in svm mode */
-    env->intercept = ldq_phys(env->vm_vmcb + offsetof(struct vmcb,
-                                                      control.intercept));
-    env->intercept_cr_read = lduw_phys(env->vm_vmcb +
-                                       offsetof(struct vmcb,
-                                                control.intercept_cr_read));
-    env->intercept_cr_write = lduw_phys(env->vm_vmcb +
-                                        offsetof(struct vmcb,
-                                                 control.intercept_cr_write));
-    env->intercept_dr_read = lduw_phys(env->vm_vmcb +
-                                       offsetof(struct vmcb,
-                                                control.intercept_dr_read));
-    env->intercept_dr_write = lduw_phys(env->vm_vmcb +
-                                        offsetof(struct vmcb,
-                                                 control.intercept_dr_write));
-    env->intercept_exceptions = ldl_phys(env->vm_vmcb +
-                                         offsetof(struct vmcb,
-                                                  control.intercept_exceptions
-                                                  ));
-
-    /* enable intercepts */
-    env->hflags |= HF_SVMI_MASK;
-
-    env->tsc_offset = ldq_phys(env->vm_vmcb +
-                               offsetof(struct vmcb, control.tsc_offset));
-
-    env->gdt.base  = ldq_phys(env->vm_vmcb + offsetof(struct vmcb,
-                                                      save.gdtr.base));
-    env->gdt.limit = ldl_phys(env->vm_vmcb + offsetof(struct vmcb,
-                                                      save.gdtr.limit));
-
-    env->idt.base  = ldq_phys(env->vm_vmcb + offsetof(struct vmcb,
-                                                      save.idtr.base));
-    env->idt.limit = ldl_phys(env->vm_vmcb + offsetof(struct vmcb,
-                                                      save.idtr.limit));
-
-    /* clear exit_info_2 so we behave like the real hardware */
-    stq_phys(env->vm_vmcb + offsetof(struct vmcb, control.exit_info_2), 0);
-
-    cpu_x86_update_cr0(env, ldq_phys(env->vm_vmcb + offsetof(struct vmcb,
-                                                             save.cr0)));
-    cpu_x86_update_cr4(env, ldq_phys(env->vm_vmcb + offsetof(struct vmcb,
-                                                             save.cr4)));
-    cpu_x86_update_cr3(env, ldq_phys(env->vm_vmcb + offsetof(struct vmcb,
-                                                             save.cr3)));
-    env->cr[2] = ldq_phys(env->vm_vmcb + offsetof(struct vmcb, save.cr2));
-    int_ctl = ldl_phys(env->vm_vmcb + offsetof(struct vmcb, control.int_ctl));
-    env->hflags2 &= ~(HF2_HIF_MASK | HF2_VINTR_MASK);
-    if (int_ctl & V_INTR_MASKING_MASK) {
-        env->v_tpr = int_ctl & V_TPR_MASK;
-        env->hflags2 |= HF2_VINTR_MASK;
-        if (env->eflags & IF_MASK) {
-            env->hflags2 |= HF2_HIF_MASK;
-        }
-    }
-
-    cpu_load_efer(env,
-                  ldq_phys(env->vm_vmcb + offsetof(struct vmcb, save.efer)));
-    env->eflags = 0;
-    cpu_load_eflags(env, ldq_phys(env->vm_vmcb + offsetof(struct vmcb,
-                                                          save.rflags)),
-                    ~(CC_O | CC_S | CC_Z | CC_A | CC_P | CC_C | DF_MASK));
-    CC_OP = CC_OP_EFLAGS;
-
-    svm_load_seg_cache(env->vm_vmcb + offsetof(struct vmcb, save.es),
-                       env, R_ES);
-    svm_load_seg_cache(env->vm_vmcb + offsetof(struct vmcb, save.cs),
-                       env, R_CS);
-    svm_load_seg_cache(env->vm_vmcb + offsetof(struct vmcb, save.ss),
-                       env, R_SS);
-    svm_load_seg_cache(env->vm_vmcb + offsetof(struct vmcb, save.ds),
-                       env, R_DS);
-
-    EIP = ldq_phys(env->vm_vmcb + offsetof(struct vmcb, save.rip));
-    env->eip = EIP;
-    ESP = ldq_phys(env->vm_vmcb + offsetof(struct vmcb, save.rsp));
-    EAX = ldq_phys(env->vm_vmcb + offsetof(struct vmcb, save.rax));
-    env->dr[7] = ldq_phys(env->vm_vmcb + offsetof(struct vmcb, save.dr7));
-    env->dr[6] = ldq_phys(env->vm_vmcb + offsetof(struct vmcb, save.dr6));
-    cpu_x86_set_cpl(env, ldub_phys(env->vm_vmcb + offsetof(struct vmcb,
-                                                           save.cpl)));
-
-    /* FIXME: guest state consistency checks */
-
-    switch (ldub_phys(env->vm_vmcb + offsetof(struct vmcb, control.tlb_ctl))) {
-    case TLB_CONTROL_DO_NOTHING:
-        break;
-    case TLB_CONTROL_FLUSH_ALL_ASID:
-        /* FIXME: this is not 100% correct but should work for now */
-        tlb_flush(env, 1);
-        break;
-    }
-
-    env->hflags2 |= HF2_GIF_MASK;
-
-    if (int_ctl & V_IRQ_MASK) {
-        env->interrupt_request |= CPU_INTERRUPT_VIRQ;
-    }
-
-    /* maybe we need to inject an event */
-    event_inj = ldl_phys(env->vm_vmcb + offsetof(struct vmcb,
-                                                 control.event_inj));
-    if (event_inj & SVM_EVTINJ_VALID) {
-        uint8_t vector = event_inj & SVM_EVTINJ_VEC_MASK;
-        uint16_t valid_err = event_inj & SVM_EVTINJ_VALID_ERR;
-        uint32_t event_inj_err = ldl_phys(env->vm_vmcb +
-                                          offsetof(struct vmcb,
-                                                   control.event_inj_err));
-
-        qemu_log_mask(CPU_LOG_TB_IN_ASM, "Injecting(%#hx): ", valid_err);
-        /* FIXME: need to implement valid_err */
-        switch (event_inj & SVM_EVTINJ_TYPE_MASK) {
-        case SVM_EVTINJ_TYPE_INTR:
-            env->exception_index = vector;
-            env->error_code = event_inj_err;
-            env->exception_is_int = 0;
-            env->exception_next_eip = -1;
-            qemu_log_mask(CPU_LOG_TB_IN_ASM, "INTR");
-            /* XXX: is it always correct? */
-            do_interrupt_x86_hardirq(env, vector, 1);
-            break;
-        case SVM_EVTINJ_TYPE_NMI:
-            env->exception_index = EXCP02_NMI;
-            env->error_code = event_inj_err;
-            env->exception_is_int = 0;
-            env->exception_next_eip = EIP;
-            qemu_log_mask(CPU_LOG_TB_IN_ASM, "NMI");
-            cpu_loop_exit(env);
-            break;
-        case SVM_EVTINJ_TYPE_EXEPT:
-            env->exception_index = vector;
-            env->error_code = event_inj_err;
-            env->exception_is_int = 0;
-            env->exception_next_eip = -1;
-            qemu_log_mask(CPU_LOG_TB_IN_ASM, "EXEPT");
-            cpu_loop_exit(env);
-            break;
-        case SVM_EVTINJ_TYPE_SOFT:
-            env->exception_index = vector;
-            env->error_code = event_inj_err;
-            env->exception_is_int = 1;
-            env->exception_next_eip = EIP;
-            qemu_log_mask(CPU_LOG_TB_IN_ASM, "SOFT");
-            cpu_loop_exit(env);
-            break;
-        }
-        qemu_log_mask(CPU_LOG_TB_IN_ASM, " %#x %#x\n", env->exception_index,
-                      env->error_code);
-    }
-}
-
-void helper_vmmcall(void)
-{
-    helper_svm_check_intercept_param(SVM_EXIT_VMMCALL, 0);
-    raise_exception(env, EXCP06_ILLOP);
-}
-
-void helper_vmload(int aflag)
-{
-    target_ulong addr;
-
-    helper_svm_check_intercept_param(SVM_EXIT_VMLOAD, 0);
-
-    if (aflag == 2) {
-        addr = EAX;
-    } else {
-        addr = (uint32_t)EAX;
-    }
-
-    qemu_log_mask(CPU_LOG_TB_IN_ASM, "vmload! " TARGET_FMT_lx
-                  "\nFS: %016" PRIx64 " | " TARGET_FMT_lx "\n",
-                  addr, ldq_phys(addr + offsetof(struct vmcb, save.fs.base)),
-                  env->segs[R_FS].base);
-
-    svm_load_seg_cache(addr + offsetof(struct vmcb, save.fs),
-                       env, R_FS);
-    svm_load_seg_cache(addr + offsetof(struct vmcb, save.gs),
-                       env, R_GS);
-    svm_load_seg(addr + offsetof(struct vmcb, save.tr),
-                 &env->tr);
-    svm_load_seg(addr + offsetof(struct vmcb, save.ldtr),
-                 &env->ldt);
-
-#ifdef TARGET_X86_64
-    env->kernelgsbase = ldq_phys(addr + offsetof(struct vmcb,
-                                                 save.kernel_gs_base));
-    env->lstar = ldq_phys(addr + offsetof(struct vmcb, save.lstar));
-    env->cstar = ldq_phys(addr + offsetof(struct vmcb, save.cstar));
-    env->fmask = ldq_phys(addr + offsetof(struct vmcb, save.sfmask));
-#endif
-    env->star = ldq_phys(addr + offsetof(struct vmcb, save.star));
-    env->sysenter_cs = ldq_phys(addr + offsetof(struct vmcb, save.sysenter_cs));
-    env->sysenter_esp = ldq_phys(addr + offsetof(struct vmcb,
-                                                 save.sysenter_esp));
-    env->sysenter_eip = ldq_phys(addr + offsetof(struct vmcb,
-                                                 save.sysenter_eip));
-}
-
-void helper_vmsave(int aflag)
-{
-    target_ulong addr;
-
-    helper_svm_check_intercept_param(SVM_EXIT_VMSAVE, 0);
-
-    if (aflag == 2) {
-        addr = EAX;
-    } else {
-        addr = (uint32_t)EAX;
-    }
-
-    qemu_log_mask(CPU_LOG_TB_IN_ASM, "vmsave! " TARGET_FMT_lx
-                  "\nFS: %016" PRIx64 " | " TARGET_FMT_lx "\n",
-                  addr, ldq_phys(addr + offsetof(struct vmcb, save.fs.base)),
-                  env->segs[R_FS].base);
-
-    svm_save_seg(addr + offsetof(struct vmcb, save.fs),
-                 &env->segs[R_FS]);
-    svm_save_seg(addr + offsetof(struct vmcb, save.gs),
-                 &env->segs[R_GS]);
-    svm_save_seg(addr + offsetof(struct vmcb, save.tr),
-                 &env->tr);
-    svm_save_seg(addr + offsetof(struct vmcb, save.ldtr),
-                 &env->ldt);
-
-#ifdef TARGET_X86_64
-    stq_phys(addr + offsetof(struct vmcb, save.kernel_gs_base),
-             env->kernelgsbase);
-    stq_phys(addr + offsetof(struct vmcb, save.lstar), env->lstar);
-    stq_phys(addr + offsetof(struct vmcb, save.cstar), env->cstar);
-    stq_phys(addr + offsetof(struct vmcb, save.sfmask), env->fmask);
-#endif
-    stq_phys(addr + offsetof(struct vmcb, save.star), env->star);
-    stq_phys(addr + offsetof(struct vmcb, save.sysenter_cs), env->sysenter_cs);
-    stq_phys(addr + offsetof(struct vmcb, save.sysenter_esp),
-             env->sysenter_esp);
-    stq_phys(addr + offsetof(struct vmcb, save.sysenter_eip),
-             env->sysenter_eip);
-}
-
-void helper_stgi(void)
-{
-    helper_svm_check_intercept_param(SVM_EXIT_STGI, 0);
-    env->hflags2 |= HF2_GIF_MASK;
-}
-
-void helper_clgi(void)
-{
-    helper_svm_check_intercept_param(SVM_EXIT_CLGI, 0);
-    env->hflags2 &= ~HF2_GIF_MASK;
-}
-
-void helper_skinit(void)
-{
-    helper_svm_check_intercept_param(SVM_EXIT_SKINIT, 0);
-    /* XXX: not implemented */
-    raise_exception(env, EXCP06_ILLOP);
-}
-
-void helper_invlpga(int aflag)
-{
-    target_ulong addr;
-
-    helper_svm_check_intercept_param(SVM_EXIT_INVLPGA, 0);
-
-    if (aflag == 2) {
-        addr = EAX;
-    } else {
-        addr = (uint32_t)EAX;
-    }
-
-    /* XXX: could use the ASID to see if it is needed to do the
-       flush */
-    tlb_flush_page(env, addr);
-}
-
-void helper_svm_check_intercept_param(uint32_t type, uint64_t param)
-{
-    if (likely(!(env->hflags & HF_SVMI_MASK))) {
-        return;
-    }
-    switch (type) {
-    case SVM_EXIT_READ_CR0 ... SVM_EXIT_READ_CR0 + 8:
-        if (env->intercept_cr_read & (1 << (type - SVM_EXIT_READ_CR0))) {
-            helper_vmexit(type, param);
-        }
-        break;
-    case SVM_EXIT_WRITE_CR0 ... SVM_EXIT_WRITE_CR0 + 8:
-        if (env->intercept_cr_write & (1 << (type - SVM_EXIT_WRITE_CR0))) {
-            helper_vmexit(type, param);
-        }
-        break;
-    case SVM_EXIT_READ_DR0 ... SVM_EXIT_READ_DR0 + 7:
-        if (env->intercept_dr_read & (1 << (type - SVM_EXIT_READ_DR0))) {
-            helper_vmexit(type, param);
-        }
-        break;
-    case SVM_EXIT_WRITE_DR0 ... SVM_EXIT_WRITE_DR0 + 7:
-        if (env->intercept_dr_write & (1 << (type - SVM_EXIT_WRITE_DR0))) {
-            helper_vmexit(type, param);
-        }
-        break;
-    case SVM_EXIT_EXCP_BASE ... SVM_EXIT_EXCP_BASE + 31:
-        if (env->intercept_exceptions & (1 << (type - SVM_EXIT_EXCP_BASE))) {
-            helper_vmexit(type, param);
-        }
-        break;
-    case SVM_EXIT_MSR:
-        if (env->intercept & (1ULL << (SVM_EXIT_MSR - SVM_EXIT_INTR))) {
-            /* FIXME: this should be read in at vmrun (faster this way?) */
-            uint64_t addr = ldq_phys(env->vm_vmcb +
-                                     offsetof(struct vmcb,
-                                              control.msrpm_base_pa));
-            uint32_t t0, t1;
-
-            switch ((uint32_t)ECX) {
-            case 0 ... 0x1fff:
-                t0 = (ECX * 2) % 8;
-                t1 = (ECX * 2) / 8;
-                break;
-            case 0xc0000000 ... 0xc0001fff:
-                t0 = (8192 + ECX - 0xc0000000) * 2;
-                t1 = (t0 / 8);
-                t0 %= 8;
-                break;
-            case 0xc0010000 ... 0xc0011fff:
-                t0 = (16384 + ECX - 0xc0010000) * 2;
-                t1 = (t0 / 8);
-                t0 %= 8;
-                break;
-            default:
-                helper_vmexit(type, param);
-                t0 = 0;
-                t1 = 0;
-                break;
-            }
-            if (ldub_phys(addr + t1) & ((1 << param) << t0)) {
-                helper_vmexit(type, param);
-            }
-        }
-        break;
-    default:
-        if (env->intercept & (1ULL << (type - SVM_EXIT_INTR))) {
-            helper_vmexit(type, param);
-        }
-        break;
-    }
-}
-
-void cpu_svm_check_intercept_param(CPUX86State *env1, uint32_t type,
-                                   uint64_t param)
-{
-    CPUX86State *saved_env;
-
-    saved_env = env;
-    env = env1;
-    helper_svm_check_intercept_param(type, param);
-    env = saved_env;
-}
-
-void helper_svm_check_io(uint32_t port, uint32_t param,
-                         uint32_t next_eip_addend)
-{
-    if (env->intercept & (1ULL << (SVM_EXIT_IOIO - SVM_EXIT_INTR))) {
-        /* FIXME: this should be read in at vmrun (faster this way?) */
-        uint64_t addr = ldq_phys(env->vm_vmcb +
-                                 offsetof(struct vmcb, control.iopm_base_pa));
-        uint16_t mask = (1 << ((param >> 4) & 7)) - 1;
-
-        if (lduw_phys(addr + port / 8) & (mask << (port & 7))) {
-            /* next EIP */
-            stq_phys(env->vm_vmcb + offsetof(struct vmcb, control.exit_info_2),
-                     env->eip + next_eip_addend);
-            helper_vmexit(SVM_EXIT_IOIO, param | (port << 16));
-        }
-    }
-}
-
-/* Note: currently only 32 bits of exit_code are used */
-void helper_vmexit(uint32_t exit_code, uint64_t exit_info_1)
-{
-    uint32_t int_ctl;
-
-    qemu_log_mask(CPU_LOG_TB_IN_ASM, "vmexit(%08x, %016" PRIx64 ", %016"
-                  PRIx64 ", " TARGET_FMT_lx ")!\n",
-                  exit_code, exit_info_1,
-                  ldq_phys(env->vm_vmcb + offsetof(struct vmcb,
-                                                   control.exit_info_2)),
-                  EIP);
-
-    if (env->hflags & HF_INHIBIT_IRQ_MASK) {
-        stl_phys(env->vm_vmcb + offsetof(struct vmcb, control.int_state),
-                 SVM_INTERRUPT_SHADOW_MASK);
-        env->hflags &= ~HF_INHIBIT_IRQ_MASK;
-    } else {
-        stl_phys(env->vm_vmcb + offsetof(struct vmcb, control.int_state), 0);
-    }
-
-    /* Save the VM state in the vmcb */
-    svm_save_seg(env->vm_vmcb + offsetof(struct vmcb, save.es),
-                 &env->segs[R_ES]);
-    svm_save_seg(env->vm_vmcb + offsetof(struct vmcb, save.cs),
-                 &env->segs[R_CS]);
-    svm_save_seg(env->vm_vmcb + offsetof(struct vmcb, save.ss),
-                 &env->segs[R_SS]);
-    svm_save_seg(env->vm_vmcb + offsetof(struct vmcb, save.ds),
-                 &env->segs[R_DS]);
-
-    stq_phys(env->vm_vmcb + offsetof(struct vmcb, save.gdtr.base),
-             env->gdt.base);
-    stl_phys(env->vm_vmcb + offsetof(struct vmcb, save.gdtr.limit),
-             env->gdt.limit);
-
-    stq_phys(env->vm_vmcb + offsetof(struct vmcb, save.idtr.base),
-             env->idt.base);
-    stl_phys(env->vm_vmcb + offsetof(struct vmcb, save.idtr.limit),
-             env->idt.limit);
-
-    stq_phys(env->vm_vmcb + offsetof(struct vmcb, save.efer), env->efer);
-    stq_phys(env->vm_vmcb + offsetof(struct vmcb, save.cr0), env->cr[0]);
-    stq_phys(env->vm_vmcb + offsetof(struct vmcb, save.cr2), env->cr[2]);
-    stq_phys(env->vm_vmcb + offsetof(struct vmcb, save.cr3), env->cr[3]);
-    stq_phys(env->vm_vmcb + offsetof(struct vmcb, save.cr4), env->cr[4]);
-
-    int_ctl = ldl_phys(env->vm_vmcb + offsetof(struct vmcb, control.int_ctl));
-    int_ctl &= ~(V_TPR_MASK | V_IRQ_MASK);
-    int_ctl |= env->v_tpr & V_TPR_MASK;
-    if (env->interrupt_request & CPU_INTERRUPT_VIRQ) {
-        int_ctl |= V_IRQ_MASK;
-    }
-    stl_phys(env->vm_vmcb + offsetof(struct vmcb, control.int_ctl), int_ctl);
-
-    stq_phys(env->vm_vmcb + offsetof(struct vmcb, save.rflags),
-             cpu_compute_eflags(env));
-    stq_phys(env->vm_vmcb + offsetof(struct vmcb, save.rip), env->eip);
-    stq_phys(env->vm_vmcb + offsetof(struct vmcb, save.rsp), ESP);
-    stq_phys(env->vm_vmcb + offsetof(struct vmcb, save.rax), EAX);
-    stq_phys(env->vm_vmcb + offsetof(struct vmcb, save.dr7), env->dr[7]);
-    stq_phys(env->vm_vmcb + offsetof(struct vmcb, save.dr6), env->dr[6]);
-    stb_phys(env->vm_vmcb + offsetof(struct vmcb, save.cpl),
-             env->hflags & HF_CPL_MASK);
-
-    /* Reload the host state from vm_hsave */
-    env->hflags2 &= ~(HF2_HIF_MASK | HF2_VINTR_MASK);
-    env->hflags &= ~HF_SVMI_MASK;
-    env->intercept = 0;
-    env->intercept_exceptions = 0;
-    env->interrupt_request &= ~CPU_INTERRUPT_VIRQ;
-    env->tsc_offset = 0;
-
-    env->gdt.base  = ldq_phys(env->vm_hsave + offsetof(struct vmcb,
-                                                       save.gdtr.base));
-    env->gdt.limit = ldl_phys(env->vm_hsave + offsetof(struct vmcb,
-                                                       save.gdtr.limit));
-
-    env->idt.base  = ldq_phys(env->vm_hsave + offsetof(struct vmcb,
-                                                       save.idtr.base));
-    env->idt.limit = ldl_phys(env->vm_hsave + offsetof(struct vmcb,
-                                                       save.idtr.limit));
-
-    cpu_x86_update_cr0(env, ldq_phys(env->vm_hsave + offsetof(struct vmcb,
-                                                              save.cr0)) |
-                       CR0_PE_MASK);
-    cpu_x86_update_cr4(env, ldq_phys(env->vm_hsave + offsetof(struct vmcb,
-                                                              save.cr4)));
-    cpu_x86_update_cr3(env, ldq_phys(env->vm_hsave + offsetof(struct vmcb,
-                                                              save.cr3)));
-    /* we need to set the efer after the crs so the hidden flags get
-       set properly */
-    cpu_load_efer(env, ldq_phys(env->vm_hsave + offsetof(struct vmcb,
-                                                         save.efer)));
-    env->eflags = 0;
-    cpu_load_eflags(env, ldq_phys(env->vm_hsave + offsetof(struct vmcb,
-                                                           save.rflags)),
-                    ~(CC_O | CC_S | CC_Z | CC_A | CC_P | CC_C | DF_MASK));
-    CC_OP = CC_OP_EFLAGS;
-
-    svm_load_seg_cache(env->vm_hsave + offsetof(struct vmcb, save.es),
-                       env, R_ES);
-    svm_load_seg_cache(env->vm_hsave + offsetof(struct vmcb, save.cs),
-                       env, R_CS);
-    svm_load_seg_cache(env->vm_hsave + offsetof(struct vmcb, save.ss),
-                       env, R_SS);
-    svm_load_seg_cache(env->vm_hsave + offsetof(struct vmcb, save.ds),
-                       env, R_DS);
-
-    EIP = ldq_phys(env->vm_hsave + offsetof(struct vmcb, save.rip));
-    ESP = ldq_phys(env->vm_hsave + offsetof(struct vmcb, save.rsp));
-    EAX = ldq_phys(env->vm_hsave + offsetof(struct vmcb, save.rax));
-
-    env->dr[6] = ldq_phys(env->vm_hsave + offsetof(struct vmcb, save.dr6));
-    env->dr[7] = ldq_phys(env->vm_hsave + offsetof(struct vmcb, save.dr7));
-
-    /* other setups */
-    cpu_x86_set_cpl(env, 0);
-    stq_phys(env->vm_vmcb + offsetof(struct vmcb, control.exit_code),
-             exit_code);
-    stq_phys(env->vm_vmcb + offsetof(struct vmcb, control.exit_info_1),
-             exit_info_1);
-
-    stl_phys(env->vm_vmcb + offsetof(struct vmcb, control.exit_int_info),
-             ldl_phys(env->vm_vmcb + offsetof(struct vmcb,
-                                              control.event_inj)));
-    stl_phys(env->vm_vmcb + offsetof(struct vmcb, control.exit_int_info_err),
-             ldl_phys(env->vm_vmcb + offsetof(struct vmcb,
-                                              control.event_inj_err)));
-    stl_phys(env->vm_vmcb + offsetof(struct vmcb, control.event_inj), 0);
-
-    env->hflags2 &= ~HF2_GIF_MASK;
-    /* FIXME: Resets the current ASID register to zero (host ASID). */
-
-    /* Clears the V_IRQ and V_INTR_MASKING bits inside the processor. */
-
-    /* Clears the TSC_OFFSET inside the processor. */
-
-    /* If the host is in PAE mode, the processor reloads the host's PDPEs
-       from the page table indicated the host's CR3. If the PDPEs contain
-       illegal state, the processor causes a shutdown. */
-
-    /* Forces CR0.PE = 1, RFLAGS.VM = 0. */
-    env->cr[0] |= CR0_PE_MASK;
-    env->eflags &= ~VM_MASK;
-
-    /* Disables all breakpoints in the host DR7 register. */
-
-    /* Checks the reloaded host state for consistency. */
-
-    /* If the host's rIP reloaded by #VMEXIT is outside the limit of the
-       host's code segment or non-canonical (in the case of long mode), a
-       #GP fault is delivered inside the host. */
-
-    /* remove any pending exception */
-    env->exception_index = -1;
-    env->error_code = 0;
-    env->old_exception = -1;
-
-    cpu_loop_exit(env);
-}
-
-void cpu_vmexit(CPUX86State *nenv, uint32_t exit_code, uint64_t exit_info_1)
-{
-    env = nenv;
-    helper_vmexit(exit_code, exit_info_1);
-}
-
-#endif
diff --git a/target-i386/svm_helper.c b/target-i386/svm_helper.c
new file mode 100644
index 0000000..64d842c
--- /dev/null
+++ b/target-i386/svm_helper.c
@@ -0,0 +1,716 @@
+/*
+ *  x86 SVM helpers
+ *
+ *  Copyright (c) 2003 Fabrice Bellard
+ *
+ * This library is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Lesser General Public
+ * License as published by the Free Software Foundation; either
+ * version 2 of the License, or (at your option) any later version.
+ *
+ * This library is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
+ * Lesser General Public License for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public
+ * License along with this library; if not, see <http://www.gnu.org/licenses/>.
+ */
+
+#include "cpu.h"
+#include "dyngen-exec.h"
+#include "helper.h"
+
+/* Secure Virtual Machine helpers */
+
+#if defined(CONFIG_USER_ONLY)
+
+void helper_vmrun(int aflag, int next_eip_addend)
+{
+}
+
+void helper_vmmcall(void)
+{
+}
+
+void helper_vmload(int aflag)
+{
+}
+
+void helper_vmsave(int aflag)
+{
+}
+
+void helper_stgi(void)
+{
+}
+
+void helper_clgi(void)
+{
+}
+
+void helper_skinit(void)
+{
+}
+
+void helper_invlpga(int aflag)
+{
+}
+
+void helper_vmexit(uint32_t exit_code, uint64_t exit_info_1)
+{
+}
+
+void cpu_vmexit(CPUX86State *nenv, uint32_t exit_code, uint64_t exit_info_1)
+{
+}
+
+void helper_svm_check_intercept_param(uint32_t type, uint64_t param)
+{
+}
+
+void cpu_svm_check_intercept_param(CPUX86State *env, uint32_t type,
+                                   uint64_t param)
+{
+}
+
+void helper_svm_check_io(uint32_t port, uint32_t param,
+                         uint32_t next_eip_addend)
+{
+}
+#else
+
+static inline void svm_save_seg(target_phys_addr_t addr,
+                                const SegmentCache *sc)
+{
+    stw_phys(addr + offsetof(struct vmcb_seg, selector),
+             sc->selector);
+    stq_phys(addr + offsetof(struct vmcb_seg, base),
+             sc->base);
+    stl_phys(addr + offsetof(struct vmcb_seg, limit),
+             sc->limit);
+    stw_phys(addr + offsetof(struct vmcb_seg, attrib),
+             ((sc->flags >> 8) & 0xff) | ((sc->flags >> 12) & 0x0f00));
+}
+
+static inline void svm_load_seg(target_phys_addr_t addr, SegmentCache *sc)
+{
+    unsigned int flags;
+
+    sc->selector = lduw_phys(addr + offsetof(struct vmcb_seg, selector));
+    sc->base = ldq_phys(addr + offsetof(struct vmcb_seg, base));
+    sc->limit = ldl_phys(addr + offsetof(struct vmcb_seg, limit));
+    flags = lduw_phys(addr + offsetof(struct vmcb_seg, attrib));
+    sc->flags = ((flags & 0xff) << 8) | ((flags & 0x0f00) << 12);
+}
+
+static inline void svm_load_seg_cache(target_phys_addr_t addr,
+                                      CPUX86State *env, int seg_reg)
+{
+    SegmentCache sc1, *sc = &sc1;
+
+    svm_load_seg(addr, sc);
+    cpu_x86_load_seg_cache(env, seg_reg, sc->selector,
+                           sc->base, sc->limit, sc->flags);
+}
+
+void helper_vmrun(int aflag, int next_eip_addend)
+{
+    target_ulong addr;
+    uint32_t event_inj;
+    uint32_t int_ctl;
+
+    helper_svm_check_intercept_param(SVM_EXIT_VMRUN, 0);
+
+    if (aflag == 2) {
+        addr = EAX;
+    } else {
+        addr = (uint32_t)EAX;
+    }
+
+    qemu_log_mask(CPU_LOG_TB_IN_ASM, "vmrun! " TARGET_FMT_lx "\n", addr);
+
+    env->vm_vmcb = addr;
+
+    /* save the current CPU state in the hsave page */
+    stq_phys(env->vm_hsave + offsetof(struct vmcb, save.gdtr.base),
+             env->gdt.base);
+    stl_phys(env->vm_hsave + offsetof(struct vmcb, save.gdtr.limit),
+             env->gdt.limit);
+
+    stq_phys(env->vm_hsave + offsetof(struct vmcb, save.idtr.base),
+             env->idt.base);
+    stl_phys(env->vm_hsave + offsetof(struct vmcb, save.idtr.limit),
+             env->idt.limit);
+
+    stq_phys(env->vm_hsave + offsetof(struct vmcb, save.cr0), env->cr[0]);
+    stq_phys(env->vm_hsave + offsetof(struct vmcb, save.cr2), env->cr[2]);
+    stq_phys(env->vm_hsave + offsetof(struct vmcb, save.cr3), env->cr[3]);
+    stq_phys(env->vm_hsave + offsetof(struct vmcb, save.cr4), env->cr[4]);
+    stq_phys(env->vm_hsave + offsetof(struct vmcb, save.dr6), env->dr[6]);
+    stq_phys(env->vm_hsave + offsetof(struct vmcb, save.dr7), env->dr[7]);
+
+    stq_phys(env->vm_hsave + offsetof(struct vmcb, save.efer), env->efer);
+    stq_phys(env->vm_hsave + offsetof(struct vmcb, save.rflags),
+             cpu_compute_eflags(env));
+
+    svm_save_seg(env->vm_hsave + offsetof(struct vmcb, save.es),
+                 &env->segs[R_ES]);
+    svm_save_seg(env->vm_hsave + offsetof(struct vmcb, save.cs),
+                 &env->segs[R_CS]);
+    svm_save_seg(env->vm_hsave + offsetof(struct vmcb, save.ss),
+                 &env->segs[R_SS]);
+    svm_save_seg(env->vm_hsave + offsetof(struct vmcb, save.ds),
+                 &env->segs[R_DS]);
+
+    stq_phys(env->vm_hsave + offsetof(struct vmcb, save.rip),
+             EIP + next_eip_addend);
+    stq_phys(env->vm_hsave + offsetof(struct vmcb, save.rsp), ESP);
+    stq_phys(env->vm_hsave + offsetof(struct vmcb, save.rax), EAX);
+
+    /* load the interception bitmaps so we do not need to access the
+       vmcb in svm mode */
+    env->intercept = ldq_phys(env->vm_vmcb + offsetof(struct vmcb,
+                                                      control.intercept));
+    env->intercept_cr_read = lduw_phys(env->vm_vmcb +
+                                       offsetof(struct vmcb,
+                                                control.intercept_cr_read));
+    env->intercept_cr_write = lduw_phys(env->vm_vmcb +
+                                        offsetof(struct vmcb,
+                                                 control.intercept_cr_write));
+    env->intercept_dr_read = lduw_phys(env->vm_vmcb +
+                                       offsetof(struct vmcb,
+                                                control.intercept_dr_read));
+    env->intercept_dr_write = lduw_phys(env->vm_vmcb +
+                                        offsetof(struct vmcb,
+                                                 control.intercept_dr_write));
+    env->intercept_exceptions = ldl_phys(env->vm_vmcb +
+                                         offsetof(struct vmcb,
+                                                  control.intercept_exceptions
+                                                  ));
+
+    /* enable intercepts */
+    env->hflags |= HF_SVMI_MASK;
+
+    env->tsc_offset = ldq_phys(env->vm_vmcb +
+                               offsetof(struct vmcb, control.tsc_offset));
+
+    env->gdt.base  = ldq_phys(env->vm_vmcb + offsetof(struct vmcb,
+                                                      save.gdtr.base));
+    env->gdt.limit = ldl_phys(env->vm_vmcb + offsetof(struct vmcb,
+                                                      save.gdtr.limit));
+
+    env->idt.base  = ldq_phys(env->vm_vmcb + offsetof(struct vmcb,
+                                                      save.idtr.base));
+    env->idt.limit = ldl_phys(env->vm_vmcb + offsetof(struct vmcb,
+                                                      save.idtr.limit));
+
+    /* clear exit_info_2 so we behave like the real hardware */
+    stq_phys(env->vm_vmcb + offsetof(struct vmcb, control.exit_info_2), 0);
+
+    cpu_x86_update_cr0(env, ldq_phys(env->vm_vmcb + offsetof(struct vmcb,
+                                                             save.cr0)));
+    cpu_x86_update_cr4(env, ldq_phys(env->vm_vmcb + offsetof(struct vmcb,
+                                                             save.cr4)));
+    cpu_x86_update_cr3(env, ldq_phys(env->vm_vmcb + offsetof(struct vmcb,
+                                                             save.cr3)));
+    env->cr[2] = ldq_phys(env->vm_vmcb + offsetof(struct vmcb, save.cr2));
+    int_ctl = ldl_phys(env->vm_vmcb + offsetof(struct vmcb, control.int_ctl));
+    env->hflags2 &= ~(HF2_HIF_MASK | HF2_VINTR_MASK);
+    if (int_ctl & V_INTR_MASKING_MASK) {
+        env->v_tpr = int_ctl & V_TPR_MASK;
+        env->hflags2 |= HF2_VINTR_MASK;
+        if (env->eflags & IF_MASK) {
+            env->hflags2 |= HF2_HIF_MASK;
+        }
+    }
+
+    cpu_load_efer(env,
+                  ldq_phys(env->vm_vmcb + offsetof(struct vmcb, save.efer)));
+    env->eflags = 0;
+    cpu_load_eflags(env, ldq_phys(env->vm_vmcb + offsetof(struct vmcb,
+                                                          save.rflags)),
+                    ~(CC_O | CC_S | CC_Z | CC_A | CC_P | CC_C | DF_MASK));
+    CC_OP = CC_OP_EFLAGS;
+
+    svm_load_seg_cache(env->vm_vmcb + offsetof(struct vmcb, save.es),
+                       env, R_ES);
+    svm_load_seg_cache(env->vm_vmcb + offsetof(struct vmcb, save.cs),
+                       env, R_CS);
+    svm_load_seg_cache(env->vm_vmcb + offsetof(struct vmcb, save.ss),
+                       env, R_SS);
+    svm_load_seg_cache(env->vm_vmcb + offsetof(struct vmcb, save.ds),
+                       env, R_DS);
+
+    EIP = ldq_phys(env->vm_vmcb + offsetof(struct vmcb, save.rip));
+    env->eip = EIP;
+    ESP = ldq_phys(env->vm_vmcb + offsetof(struct vmcb, save.rsp));
+    EAX = ldq_phys(env->vm_vmcb + offsetof(struct vmcb, save.rax));
+    env->dr[7] = ldq_phys(env->vm_vmcb + offsetof(struct vmcb, save.dr7));
+    env->dr[6] = ldq_phys(env->vm_vmcb + offsetof(struct vmcb, save.dr6));
+    cpu_x86_set_cpl(env, ldub_phys(env->vm_vmcb + offsetof(struct vmcb,
+                                                           save.cpl)));
+
+    /* FIXME: guest state consistency checks */
+
+    switch (ldub_phys(env->vm_vmcb + offsetof(struct vmcb, control.tlb_ctl))) {
+    case TLB_CONTROL_DO_NOTHING:
+        break;
+    case TLB_CONTROL_FLUSH_ALL_ASID:
+        /* FIXME: this is not 100% correct but should work for now */
+        tlb_flush(env, 1);
+        break;
+    }
+
+    env->hflags2 |= HF2_GIF_MASK;
+
+    if (int_ctl & V_IRQ_MASK) {
+        env->interrupt_request |= CPU_INTERRUPT_VIRQ;
+    }
+
+    /* maybe we need to inject an event */
+    event_inj = ldl_phys(env->vm_vmcb + offsetof(struct vmcb,
+                                                 control.event_inj));
+    if (event_inj & SVM_EVTINJ_VALID) {
+        uint8_t vector = event_inj & SVM_EVTINJ_VEC_MASK;
+        uint16_t valid_err = event_inj & SVM_EVTINJ_VALID_ERR;
+        uint32_t event_inj_err = ldl_phys(env->vm_vmcb +
+                                          offsetof(struct vmcb,
+                                                   control.event_inj_err));
+
+        qemu_log_mask(CPU_LOG_TB_IN_ASM, "Injecting(%#hx): ", valid_err);
+        /* FIXME: need to implement valid_err */
+        switch (event_inj & SVM_EVTINJ_TYPE_MASK) {
+        case SVM_EVTINJ_TYPE_INTR:
+            env->exception_index = vector;
+            env->error_code = event_inj_err;
+            env->exception_is_int = 0;
+            env->exception_next_eip = -1;
+            qemu_log_mask(CPU_LOG_TB_IN_ASM, "INTR");
+            /* XXX: is it always correct? */
+            do_interrupt_x86_hardirq(env, vector, 1);
+            break;
+        case SVM_EVTINJ_TYPE_NMI:
+            env->exception_index = EXCP02_NMI;
+            env->error_code = event_inj_err;
+            env->exception_is_int = 0;
+            env->exception_next_eip = EIP;
+            qemu_log_mask(CPU_LOG_TB_IN_ASM, "NMI");
+            cpu_loop_exit(env);
+            break;
+        case SVM_EVTINJ_TYPE_EXEPT:
+            env->exception_index = vector;
+            env->error_code = event_inj_err;
+            env->exception_is_int = 0;
+            env->exception_next_eip = -1;
+            qemu_log_mask(CPU_LOG_TB_IN_ASM, "EXEPT");
+            cpu_loop_exit(env);
+            break;
+        case SVM_EVTINJ_TYPE_SOFT:
+            env->exception_index = vector;
+            env->error_code = event_inj_err;
+            env->exception_is_int = 1;
+            env->exception_next_eip = EIP;
+            qemu_log_mask(CPU_LOG_TB_IN_ASM, "SOFT");
+            cpu_loop_exit(env);
+            break;
+        }
+        qemu_log_mask(CPU_LOG_TB_IN_ASM, " %#x %#x\n", env->exception_index,
+                      env->error_code);
+    }
+}
+
+void helper_vmmcall(void)
+{
+    helper_svm_check_intercept_param(SVM_EXIT_VMMCALL, 0);
+    raise_exception(env, EXCP06_ILLOP);
+}
+
+void helper_vmload(int aflag)
+{
+    target_ulong addr;
+
+    helper_svm_check_intercept_param(SVM_EXIT_VMLOAD, 0);
+
+    if (aflag == 2) {
+        addr = EAX;
+    } else {
+        addr = (uint32_t)EAX;
+    }
+
+    qemu_log_mask(CPU_LOG_TB_IN_ASM, "vmload! " TARGET_FMT_lx
+                  "\nFS: %016" PRIx64 " | " TARGET_FMT_lx "\n",
+                  addr, ldq_phys(addr + offsetof(struct vmcb, save.fs.base)),
+                  env->segs[R_FS].base);
+
+    svm_load_seg_cache(addr + offsetof(struct vmcb, save.fs),
+                       env, R_FS);
+    svm_load_seg_cache(addr + offsetof(struct vmcb, save.gs),
+                       env, R_GS);
+    svm_load_seg(addr + offsetof(struct vmcb, save.tr),
+                 &env->tr);
+    svm_load_seg(addr + offsetof(struct vmcb, save.ldtr),
+                 &env->ldt);
+
+#ifdef TARGET_X86_64
+    env->kernelgsbase = ldq_phys(addr + offsetof(struct vmcb,
+                                                 save.kernel_gs_base));
+    env->lstar = ldq_phys(addr + offsetof(struct vmcb, save.lstar));
+    env->cstar = ldq_phys(addr + offsetof(struct vmcb, save.cstar));
+    env->fmask = ldq_phys(addr + offsetof(struct vmcb, save.sfmask));
+#endif
+    env->star = ldq_phys(addr + offsetof(struct vmcb, save.star));
+    env->sysenter_cs = ldq_phys(addr + offsetof(struct vmcb, save.sysenter_cs));
+    env->sysenter_esp = ldq_phys(addr + offsetof(struct vmcb,
+                                                 save.sysenter_esp));
+    env->sysenter_eip = ldq_phys(addr + offsetof(struct vmcb,
+                                                 save.sysenter_eip));
+}
+
+void helper_vmsave(int aflag)
+{
+    target_ulong addr;
+
+    helper_svm_check_intercept_param(SVM_EXIT_VMSAVE, 0);
+
+    if (aflag == 2) {
+        addr = EAX;
+    } else {
+        addr = (uint32_t)EAX;
+    }
+
+    qemu_log_mask(CPU_LOG_TB_IN_ASM, "vmsave! " TARGET_FMT_lx
+                  "\nFS: %016" PRIx64 " | " TARGET_FMT_lx "\n",
+                  addr, ldq_phys(addr + offsetof(struct vmcb, save.fs.base)),
+                  env->segs[R_FS].base);
+
+    svm_save_seg(addr + offsetof(struct vmcb, save.fs),
+                 &env->segs[R_FS]);
+    svm_save_seg(addr + offsetof(struct vmcb, save.gs),
+                 &env->segs[R_GS]);
+    svm_save_seg(addr + offsetof(struct vmcb, save.tr),
+                 &env->tr);
+    svm_save_seg(addr + offsetof(struct vmcb, save.ldtr),
+                 &env->ldt);
+
+#ifdef TARGET_X86_64
+    stq_phys(addr + offsetof(struct vmcb, save.kernel_gs_base),
+             env->kernelgsbase);
+    stq_phys(addr + offsetof(struct vmcb, save.lstar), env->lstar);
+    stq_phys(addr + offsetof(struct vmcb, save.cstar), env->cstar);
+    stq_phys(addr + offsetof(struct vmcb, save.sfmask), env->fmask);
+#endif
+    stq_phys(addr + offsetof(struct vmcb, save.star), env->star);
+    stq_phys(addr + offsetof(struct vmcb, save.sysenter_cs), env->sysenter_cs);
+    stq_phys(addr + offsetof(struct vmcb, save.sysenter_esp),
+             env->sysenter_esp);
+    stq_phys(addr + offsetof(struct vmcb, save.sysenter_eip),
+             env->sysenter_eip);
+}
+
+void helper_stgi(void)
+{
+    helper_svm_check_intercept_param(SVM_EXIT_STGI, 0);
+    env->hflags2 |= HF2_GIF_MASK;
+}
+
+void helper_clgi(void)
+{
+    helper_svm_check_intercept_param(SVM_EXIT_CLGI, 0);
+    env->hflags2 &= ~HF2_GIF_MASK;
+}
+
+void helper_skinit(void)
+{
+    helper_svm_check_intercept_param(SVM_EXIT_SKINIT, 0);
+    /* XXX: not implemented */
+    raise_exception(env, EXCP06_ILLOP);
+}
+
+void helper_invlpga(int aflag)
+{
+    target_ulong addr;
+
+    helper_svm_check_intercept_param(SVM_EXIT_INVLPGA, 0);
+
+    if (aflag == 2) {
+        addr = EAX;
+    } else {
+        addr = (uint32_t)EAX;
+    }
+
+    /* XXX: could use the ASID to see if it is needed to do the
+       flush */
+    tlb_flush_page(env, addr);
+}
+
+void helper_svm_check_intercept_param(uint32_t type, uint64_t param)
+{
+    if (likely(!(env->hflags & HF_SVMI_MASK))) {
+        return;
+    }
+    switch (type) {
+    case SVM_EXIT_READ_CR0 ... SVM_EXIT_READ_CR0 + 8:
+        if (env->intercept_cr_read & (1 << (type - SVM_EXIT_READ_CR0))) {
+            helper_vmexit(type, param);
+        }
+        break;
+    case SVM_EXIT_WRITE_CR0 ... SVM_EXIT_WRITE_CR0 + 8:
+        if (env->intercept_cr_write & (1 << (type - SVM_EXIT_WRITE_CR0))) {
+            helper_vmexit(type, param);
+        }
+        break;
+    case SVM_EXIT_READ_DR0 ... SVM_EXIT_READ_DR0 + 7:
+        if (env->intercept_dr_read & (1 << (type - SVM_EXIT_READ_DR0))) {
+            helper_vmexit(type, param);
+        }
+        break;
+    case SVM_EXIT_WRITE_DR0 ... SVM_EXIT_WRITE_DR0 + 7:
+        if (env->intercept_dr_write & (1 << (type - SVM_EXIT_WRITE_DR0))) {
+            helper_vmexit(type, param);
+        }
+        break;
+    case SVM_EXIT_EXCP_BASE ... SVM_EXIT_EXCP_BASE + 31:
+        if (env->intercept_exceptions & (1 << (type - SVM_EXIT_EXCP_BASE))) {
+            helper_vmexit(type, param);
+        }
+        break;
+    case SVM_EXIT_MSR:
+        if (env->intercept & (1ULL << (SVM_EXIT_MSR - SVM_EXIT_INTR))) {
+            /* FIXME: this should be read in at vmrun (faster this way?) */
+            uint64_t addr = ldq_phys(env->vm_vmcb +
+                                     offsetof(struct vmcb,
+                                              control.msrpm_base_pa));
+            uint32_t t0, t1;
+
+            switch ((uint32_t)ECX) {
+            case 0 ... 0x1fff:
+                t0 = (ECX * 2) % 8;
+                t1 = (ECX * 2) / 8;
+                break;
+            case 0xc0000000 ... 0xc0001fff:
+                t0 = (8192 + ECX - 0xc0000000) * 2;
+                t1 = (t0 / 8);
+                t0 %= 8;
+                break;
+            case 0xc0010000 ... 0xc0011fff:
+                t0 = (16384 + ECX - 0xc0010000) * 2;
+                t1 = (t0 / 8);
+                t0 %= 8;
+                break;
+            default:
+                helper_vmexit(type, param);
+                t0 = 0;
+                t1 = 0;
+                break;
+            }
+            if (ldub_phys(addr + t1) & ((1 << param) << t0)) {
+                helper_vmexit(type, param);
+            }
+        }
+        break;
+    default:
+        if (env->intercept & (1ULL << (type - SVM_EXIT_INTR))) {
+            helper_vmexit(type, param);
+        }
+        break;
+    }
+}
+
+void cpu_svm_check_intercept_param(CPUX86State *env1, uint32_t type,
+                                   uint64_t param)
+{
+    CPUX86State *saved_env;
+
+    saved_env = env;
+    env = env1;
+    helper_svm_check_intercept_param(type, param);
+    env = saved_env;
+}
+
+void helper_svm_check_io(uint32_t port, uint32_t param,
+                         uint32_t next_eip_addend)
+{
+    if (env->intercept & (1ULL << (SVM_EXIT_IOIO - SVM_EXIT_INTR))) {
+        /* FIXME: this should be read in at vmrun (faster this way?) */
+        uint64_t addr = ldq_phys(env->vm_vmcb +
+                                 offsetof(struct vmcb, control.iopm_base_pa));
+        uint16_t mask = (1 << ((param >> 4) & 7)) - 1;
+
+        if (lduw_phys(addr + port / 8) & (mask << (port & 7))) {
+            /* next EIP */
+            stq_phys(env->vm_vmcb + offsetof(struct vmcb, control.exit_info_2),
+                     env->eip + next_eip_addend);
+            helper_vmexit(SVM_EXIT_IOIO, param | (port << 16));
+        }
+    }
+}
+
+/* Note: currently only 32 bits of exit_code are used */
+void helper_vmexit(uint32_t exit_code, uint64_t exit_info_1)
+{
+    uint32_t int_ctl;
+
+    qemu_log_mask(CPU_LOG_TB_IN_ASM, "vmexit(%08x, %016" PRIx64 ", %016"
+                  PRIx64 ", " TARGET_FMT_lx ")!\n",
+                  exit_code, exit_info_1,
+                  ldq_phys(env->vm_vmcb + offsetof(struct vmcb,
+                                                   control.exit_info_2)),
+                  EIP);
+
+    if (env->hflags & HF_INHIBIT_IRQ_MASK) {
+        stl_phys(env->vm_vmcb + offsetof(struct vmcb, control.int_state),
+                 SVM_INTERRUPT_SHADOW_MASK);
+        env->hflags &= ~HF_INHIBIT_IRQ_MASK;
+    } else {
+        stl_phys(env->vm_vmcb + offsetof(struct vmcb, control.int_state), 0);
+    }
+
+    /* Save the VM state in the vmcb */
+    svm_save_seg(env->vm_vmcb + offsetof(struct vmcb, save.es),
+                 &env->segs[R_ES]);
+    svm_save_seg(env->vm_vmcb + offsetof(struct vmcb, save.cs),
+                 &env->segs[R_CS]);
+    svm_save_seg(env->vm_vmcb + offsetof(struct vmcb, save.ss),
+                 &env->segs[R_SS]);
+    svm_save_seg(env->vm_vmcb + offsetof(struct vmcb, save.ds),
+                 &env->segs[R_DS]);
+
+    stq_phys(env->vm_vmcb + offsetof(struct vmcb, save.gdtr.base),
+             env->gdt.base);
+    stl_phys(env->vm_vmcb + offsetof(struct vmcb, save.gdtr.limit),
+             env->gdt.limit);
+
+    stq_phys(env->vm_vmcb + offsetof(struct vmcb, save.idtr.base),
+             env->idt.base);
+    stl_phys(env->vm_vmcb + offsetof(struct vmcb, save.idtr.limit),
+             env->idt.limit);
+
+    stq_phys(env->vm_vmcb + offsetof(struct vmcb, save.efer), env->efer);
+    stq_phys(env->vm_vmcb + offsetof(struct vmcb, save.cr0), env->cr[0]);
+    stq_phys(env->vm_vmcb + offsetof(struct vmcb, save.cr2), env->cr[2]);
+    stq_phys(env->vm_vmcb + offsetof(struct vmcb, save.cr3), env->cr[3]);
+    stq_phys(env->vm_vmcb + offsetof(struct vmcb, save.cr4), env->cr[4]);
+
+    int_ctl = ldl_phys(env->vm_vmcb + offsetof(struct vmcb, control.int_ctl));
+    int_ctl &= ~(V_TPR_MASK | V_IRQ_MASK);
+    int_ctl |= env->v_tpr & V_TPR_MASK;
+    if (env->interrupt_request & CPU_INTERRUPT_VIRQ) {
+        int_ctl |= V_IRQ_MASK;
+    }
+    stl_phys(env->vm_vmcb + offsetof(struct vmcb, control.int_ctl), int_ctl);
+
+    stq_phys(env->vm_vmcb + offsetof(struct vmcb, save.rflags),
+             cpu_compute_eflags(env));
+    stq_phys(env->vm_vmcb + offsetof(struct vmcb, save.rip), env->eip);
+    stq_phys(env->vm_vmcb + offsetof(struct vmcb, save.rsp), ESP);
+    stq_phys(env->vm_vmcb + offsetof(struct vmcb, save.rax), EAX);
+    stq_phys(env->vm_vmcb + offsetof(struct vmcb, save.dr7), env->dr[7]);
+    stq_phys(env->vm_vmcb + offsetof(struct vmcb, save.dr6), env->dr[6]);
+    stb_phys(env->vm_vmcb + offsetof(struct vmcb, save.cpl),
+             env->hflags & HF_CPL_MASK);
+
+    /* Reload the host state from vm_hsave */
+    env->hflags2 &= ~(HF2_HIF_MASK | HF2_VINTR_MASK);
+    env->hflags &= ~HF_SVMI_MASK;
+    env->intercept = 0;
+    env->intercept_exceptions = 0;
+    env->interrupt_request &= ~CPU_INTERRUPT_VIRQ;
+    env->tsc_offset = 0;
+
+    env->gdt.base  = ldq_phys(env->vm_hsave + offsetof(struct vmcb,
+                                                       save.gdtr.base));
+    env->gdt.limit = ldl_phys(env->vm_hsave + offsetof(struct vmcb,
+                                                       save.gdtr.limit));
+
+    env->idt.base  = ldq_phys(env->vm_hsave + offsetof(struct vmcb,
+                                                       save.idtr.base));
+    env->idt.limit = ldl_phys(env->vm_hsave + offsetof(struct vmcb,
+                                                       save.idtr.limit));
+
+    cpu_x86_update_cr0(env, ldq_phys(env->vm_hsave + offsetof(struct vmcb,
+                                                              save.cr0)) |
+                       CR0_PE_MASK);
+    cpu_x86_update_cr4(env, ldq_phys(env->vm_hsave + offsetof(struct vmcb,
+                                                              save.cr4)));
+    cpu_x86_update_cr3(env, ldq_phys(env->vm_hsave + offsetof(struct vmcb,
+                                                              save.cr3)));
+    /* we need to set the efer after the crs so the hidden flags get
+       set properly */
+    cpu_load_efer(env, ldq_phys(env->vm_hsave + offsetof(struct vmcb,
+                                                         save.efer)));
+    env->eflags = 0;
+    cpu_load_eflags(env, ldq_phys(env->vm_hsave + offsetof(struct vmcb,
+                                                           save.rflags)),
+                    ~(CC_O | CC_S | CC_Z | CC_A | CC_P | CC_C | DF_MASK));
+    CC_OP = CC_OP_EFLAGS;
+
+    svm_load_seg_cache(env->vm_hsave + offsetof(struct vmcb, save.es),
+                       env, R_ES);
+    svm_load_seg_cache(env->vm_hsave + offsetof(struct vmcb, save.cs),
+                       env, R_CS);
+    svm_load_seg_cache(env->vm_hsave + offsetof(struct vmcb, save.ss),
+                       env, R_SS);
+    svm_load_seg_cache(env->vm_hsave + offsetof(struct vmcb, save.ds),
+                       env, R_DS);
+
+    EIP = ldq_phys(env->vm_hsave + offsetof(struct vmcb, save.rip));
+    ESP = ldq_phys(env->vm_hsave + offsetof(struct vmcb, save.rsp));
+    EAX = ldq_phys(env->vm_hsave + offsetof(struct vmcb, save.rax));
+
+    env->dr[6] = ldq_phys(env->vm_hsave + offsetof(struct vmcb, save.dr6));
+    env->dr[7] = ldq_phys(env->vm_hsave + offsetof(struct vmcb, save.dr7));
+
+    /* other setups */
+    cpu_x86_set_cpl(env, 0);
+    stq_phys(env->vm_vmcb + offsetof(struct vmcb, control.exit_code),
+             exit_code);
+    stq_phys(env->vm_vmcb + offsetof(struct vmcb, control.exit_info_1),
+             exit_info_1);
+
+    stl_phys(env->vm_vmcb + offsetof(struct vmcb, control.exit_int_info),
+             ldl_phys(env->vm_vmcb + offsetof(struct vmcb,
+                                              control.event_inj)));
+    stl_phys(env->vm_vmcb + offsetof(struct vmcb, control.exit_int_info_err),
+             ldl_phys(env->vm_vmcb + offsetof(struct vmcb,
+                                              control.event_inj_err)));
+    stl_phys(env->vm_vmcb + offsetof(struct vmcb, control.event_inj), 0);
+
+    env->hflags2 &= ~HF2_GIF_MASK;
+    /* FIXME: Resets the current ASID register to zero (host ASID). */
+
+    /* Clears the V_IRQ and V_INTR_MASKING bits inside the processor. */
+
+    /* Clears the TSC_OFFSET inside the processor. */
+
+    /* If the host is in PAE mode, the processor reloads the host's PDPEs
+       from the page table indicated the host's CR3. If the PDPEs contain
+       illegal state, the processor causes a shutdown. */
+
+    /* Forces CR0.PE = 1, RFLAGS.VM = 0. */
+    env->cr[0] |= CR0_PE_MASK;
+    env->eflags &= ~VM_MASK;
+
+    /* Disables all breakpoints in the host DR7 register. */
+
+    /* Checks the reloaded host state for consistency. */
+
+    /* If the host's rIP reloaded by #VMEXIT is outside the limit of the
+       host's code segment or non-canonical (in the case of long mode), a
+       #GP fault is delivered inside the host. */
+
+    /* remove any pending exception */
+    env->exception_index = -1;
+    env->error_code = 0;
+    env->old_exception = -1;
+
+    cpu_loop_exit(env);
+}
+
+void cpu_vmexit(CPUX86State *nenv, uint32_t exit_code, uint64_t exit_info_1)
+{
+    env = nenv;
+    helper_vmexit(exit_code, exit_info_1);
+}
+
+#endif
commit d7582078017c5c7c4a8ca0d794db1c896e86a105
Author: Blue Swirl <blauwirbel at gmail.com>
Date:   Sun Apr 29 13:12:26 2012 +0000

    x86: split off integer helpers
    
    Move integer and bit field helpers to int_helper.c.
    
    Signed-off-by: Blue Swirl <blauwirbel at gmail.com>

diff --git a/target-i386/Makefile.objs b/target-i386/Makefile.objs
index 96a2266..d4cbcd7 100644
--- a/target-i386/Makefile.objs
+++ b/target-i386/Makefile.objs
@@ -1,5 +1,5 @@
 obj-y += translate.o op_helper.o helper.o cpu.o
-obj-y += excp_helper.o fpu_helper.o cc_helper.o
+obj-y += excp_helper.o fpu_helper.o cc_helper.o int_helper.o
 obj-$(CONFIG_SOFTMMU) += machine.o arch_memory_mapping.o arch_dump.o
 obj-$(CONFIG_KVM) += kvm.o hyperv.o
 obj-$(CONFIG_LINUX_USER) += ioport-user.o
@@ -8,3 +8,4 @@ obj-$(CONFIG_BSD_USER) += ioport-user.o
 $(obj)/op_helper.o: QEMU_CFLAGS += $(HELPER_CFLAGS)
 $(obj)/fpu_helper.o: QEMU_CFLAGS += $(HELPER_CFLAGS)
 $(obj)/cc_helper.o: QEMU_CFLAGS += $(HELPER_CFLAGS)
+$(obj)/int_helper.o: QEMU_CFLAGS += $(HELPER_CFLAGS)
diff --git a/target-i386/int_helper.c b/target-i386/int_helper.c
new file mode 100644
index 0000000..e1f66f5
--- /dev/null
+++ b/target-i386/int_helper.c
@@ -0,0 +1,500 @@
+/*
+ *  x86 integer helpers
+ *
+ *  Copyright (c) 2003 Fabrice Bellard
+ *
+ * This library is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Lesser General Public
+ * License as published by the Free Software Foundation; either
+ * version 2 of the License, or (at your option) any later version.
+ *
+ * This library is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
+ * Lesser General Public License for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public
+ * License along with this library; if not, see <http://www.gnu.org/licenses/>.
+ */
+
+#include "cpu.h"
+#include "dyngen-exec.h"
+#include "host-utils.h"
+#include "helper.h"
+
+//#define DEBUG_MULDIV
+
+/* modulo 9 table */
+static const uint8_t rclb_table[32] = {
+    0, 1, 2, 3, 4, 5, 6, 7,
+    8, 0, 1, 2, 3, 4, 5, 6,
+    7, 8, 0, 1, 2, 3, 4, 5,
+    6, 7, 8, 0, 1, 2, 3, 4,
+};
+
+/* modulo 17 table */
+static const uint8_t rclw_table[32] = {
+    0, 1, 2, 3, 4, 5, 6, 7,
+    8, 9, 10, 11, 12, 13, 14, 15,
+    16, 0, 1, 2, 3, 4, 5, 6,
+    7, 8, 9, 10, 11, 12, 13, 14,
+};
+
+/* division, flags are undefined */
+
+void helper_divb_AL(target_ulong t0)
+{
+    unsigned int num, den, q, r;
+
+    num = (EAX & 0xffff);
+    den = (t0 & 0xff);
+    if (den == 0) {
+        raise_exception(env, EXCP00_DIVZ);
+    }
+    q = (num / den);
+    if (q > 0xff) {
+        raise_exception(env, EXCP00_DIVZ);
+    }
+    q &= 0xff;
+    r = (num % den) & 0xff;
+    EAX = (EAX & ~0xffff) | (r << 8) | q;
+}
+
+void helper_idivb_AL(target_ulong t0)
+{
+    int num, den, q, r;
+
+    num = (int16_t)EAX;
+    den = (int8_t)t0;
+    if (den == 0) {
+        raise_exception(env, EXCP00_DIVZ);
+    }
+    q = (num / den);
+    if (q != (int8_t)q) {
+        raise_exception(env, EXCP00_DIVZ);
+    }
+    q &= 0xff;
+    r = (num % den) & 0xff;
+    EAX = (EAX & ~0xffff) | (r << 8) | q;
+}
+
+void helper_divw_AX(target_ulong t0)
+{
+    unsigned int num, den, q, r;
+
+    num = (EAX & 0xffff) | ((EDX & 0xffff) << 16);
+    den = (t0 & 0xffff);
+    if (den == 0) {
+        raise_exception(env, EXCP00_DIVZ);
+    }
+    q = (num / den);
+    if (q > 0xffff) {
+        raise_exception(env, EXCP00_DIVZ);
+    }
+    q &= 0xffff;
+    r = (num % den) & 0xffff;
+    EAX = (EAX & ~0xffff) | q;
+    EDX = (EDX & ~0xffff) | r;
+}
+
+void helper_idivw_AX(target_ulong t0)
+{
+    int num, den, q, r;
+
+    num = (EAX & 0xffff) | ((EDX & 0xffff) << 16);
+    den = (int16_t)t0;
+    if (den == 0) {
+        raise_exception(env, EXCP00_DIVZ);
+    }
+    q = (num / den);
+    if (q != (int16_t)q) {
+        raise_exception(env, EXCP00_DIVZ);
+    }
+    q &= 0xffff;
+    r = (num % den) & 0xffff;
+    EAX = (EAX & ~0xffff) | q;
+    EDX = (EDX & ~0xffff) | r;
+}
+
+void helper_divl_EAX(target_ulong t0)
+{
+    unsigned int den, r;
+    uint64_t num, q;
+
+    num = ((uint32_t)EAX) | ((uint64_t)((uint32_t)EDX) << 32);
+    den = t0;
+    if (den == 0) {
+        raise_exception(env, EXCP00_DIVZ);
+    }
+    q = (num / den);
+    r = (num % den);
+    if (q > 0xffffffff) {
+        raise_exception(env, EXCP00_DIVZ);
+    }
+    EAX = (uint32_t)q;
+    EDX = (uint32_t)r;
+}
+
+void helper_idivl_EAX(target_ulong t0)
+{
+    int den, r;
+    int64_t num, q;
+
+    num = ((uint32_t)EAX) | ((uint64_t)((uint32_t)EDX) << 32);
+    den = t0;
+    if (den == 0) {
+        raise_exception(env, EXCP00_DIVZ);
+    }
+    q = (num / den);
+    r = (num % den);
+    if (q != (int32_t)q) {
+        raise_exception(env, EXCP00_DIVZ);
+    }
+    EAX = (uint32_t)q;
+    EDX = (uint32_t)r;
+}
+
+/* bcd */
+
+/* XXX: exception */
+void helper_aam(int base)
+{
+    int al, ah;
+
+    al = EAX & 0xff;
+    ah = al / base;
+    al = al % base;
+    EAX = (EAX & ~0xffff) | al | (ah << 8);
+    CC_DST = al;
+}
+
+void helper_aad(int base)
+{
+    int al, ah;
+
+    al = EAX & 0xff;
+    ah = (EAX >> 8) & 0xff;
+    al = ((ah * base) + al) & 0xff;
+    EAX = (EAX & ~0xffff) | al;
+    CC_DST = al;
+}
+
+void helper_aaa(void)
+{
+    int icarry;
+    int al, ah, af;
+    int eflags;
+
+    eflags = helper_cc_compute_all(CC_OP);
+    af = eflags & CC_A;
+    al = EAX & 0xff;
+    ah = (EAX >> 8) & 0xff;
+
+    icarry = (al > 0xf9);
+    if (((al & 0x0f) > 9) || af) {
+        al = (al + 6) & 0x0f;
+        ah = (ah + 1 + icarry) & 0xff;
+        eflags |= CC_C | CC_A;
+    } else {
+        eflags &= ~(CC_C | CC_A);
+        al &= 0x0f;
+    }
+    EAX = (EAX & ~0xffff) | al | (ah << 8);
+    CC_SRC = eflags;
+}
+
+void helper_aas(void)
+{
+    int icarry;
+    int al, ah, af;
+    int eflags;
+
+    eflags = helper_cc_compute_all(CC_OP);
+    af = eflags & CC_A;
+    al = EAX & 0xff;
+    ah = (EAX >> 8) & 0xff;
+
+    icarry = (al < 6);
+    if (((al & 0x0f) > 9) || af) {
+        al = (al - 6) & 0x0f;
+        ah = (ah - 1 - icarry) & 0xff;
+        eflags |= CC_C | CC_A;
+    } else {
+        eflags &= ~(CC_C | CC_A);
+        al &= 0x0f;
+    }
+    EAX = (EAX & ~0xffff) | al | (ah << 8);
+    CC_SRC = eflags;
+}
+
+void helper_daa(void)
+{
+    int old_al, al, af, cf;
+    int eflags;
+
+    eflags = helper_cc_compute_all(CC_OP);
+    cf = eflags & CC_C;
+    af = eflags & CC_A;
+    old_al = al = EAX & 0xff;
+
+    eflags = 0;
+    if (((al & 0x0f) > 9) || af) {
+        al = (al + 6) & 0xff;
+        eflags |= CC_A;
+    }
+    if ((old_al > 0x99) || cf) {
+        al = (al + 0x60) & 0xff;
+        eflags |= CC_C;
+    }
+    EAX = (EAX & ~0xff) | al;
+    /* well, speed is not an issue here, so we compute the flags by hand */
+    eflags |= (al == 0) << 6; /* zf */
+    eflags |= parity_table[al]; /* pf */
+    eflags |= (al & 0x80); /* sf */
+    CC_SRC = eflags;
+}
+
+void helper_das(void)
+{
+    int al, al1, af, cf;
+    int eflags;
+
+    eflags = helper_cc_compute_all(CC_OP);
+    cf = eflags & CC_C;
+    af = eflags & CC_A;
+    al = EAX & 0xff;
+
+    eflags = 0;
+    al1 = al;
+    if (((al & 0x0f) > 9) || af) {
+        eflags |= CC_A;
+        if (al < 6 || cf) {
+            eflags |= CC_C;
+        }
+        al = (al - 6) & 0xff;
+    }
+    if ((al1 > 0x99) || cf) {
+        al = (al - 0x60) & 0xff;
+        eflags |= CC_C;
+    }
+    EAX = (EAX & ~0xff) | al;
+    /* well, speed is not an issue here, so we compute the flags by hand */
+    eflags |= (al == 0) << 6; /* zf */
+    eflags |= parity_table[al]; /* pf */
+    eflags |= (al & 0x80); /* sf */
+    CC_SRC = eflags;
+}
+
+#ifdef TARGET_X86_64
+static void add128(uint64_t *plow, uint64_t *phigh, uint64_t a, uint64_t b)
+{
+    *plow += a;
+    /* carry test */
+    if (*plow < a) {
+        (*phigh)++;
+    }
+    *phigh += b;
+}
+
+static void neg128(uint64_t *plow, uint64_t *phigh)
+{
+    *plow = ~*plow;
+    *phigh = ~*phigh;
+    add128(plow, phigh, 1, 0);
+}
+
+/* return TRUE if overflow */
+static int div64(uint64_t *plow, uint64_t *phigh, uint64_t b)
+{
+    uint64_t q, r, a1, a0;
+    int i, qb, ab;
+
+    a0 = *plow;
+    a1 = *phigh;
+    if (a1 == 0) {
+        q = a0 / b;
+        r = a0 % b;
+        *plow = q;
+        *phigh = r;
+    } else {
+        if (a1 >= b) {
+            return 1;
+        }
+        /* XXX: use a better algorithm */
+        for (i = 0; i < 64; i++) {
+            ab = a1 >> 63;
+            a1 = (a1 << 1) | (a0 >> 63);
+            if (ab || a1 >= b) {
+                a1 -= b;
+                qb = 1;
+            } else {
+                qb = 0;
+            }
+            a0 = (a0 << 1) | qb;
+        }
+#if defined(DEBUG_MULDIV)
+        printf("div: 0x%016" PRIx64 "%016" PRIx64 " / 0x%016" PRIx64
+               ": q=0x%016" PRIx64 " r=0x%016" PRIx64 "\n",
+               *phigh, *plow, b, a0, a1);
+#endif
+        *plow = a0;
+        *phigh = a1;
+    }
+    return 0;
+}
+
+/* return TRUE if overflow */
+static int idiv64(uint64_t *plow, uint64_t *phigh, int64_t b)
+{
+    int sa, sb;
+
+    sa = ((int64_t)*phigh < 0);
+    if (sa) {
+        neg128(plow, phigh);
+    }
+    sb = (b < 0);
+    if (sb) {
+        b = -b;
+    }
+    if (div64(plow, phigh, b) != 0) {
+        return 1;
+    }
+    if (sa ^ sb) {
+        if (*plow > (1ULL << 63)) {
+            return 1;
+        }
+        *plow = -*plow;
+    } else {
+        if (*plow >= (1ULL << 63)) {
+            return 1;
+        }
+    }
+    if (sa) {
+        *phigh = -*phigh;
+    }
+    return 0;
+}
+
+void helper_mulq_EAX_T0(target_ulong t0)
+{
+    uint64_t r0, r1;
+
+    mulu64(&r0, &r1, EAX, t0);
+    EAX = r0;
+    EDX = r1;
+    CC_DST = r0;
+    CC_SRC = r1;
+}
+
+void helper_imulq_EAX_T0(target_ulong t0)
+{
+    uint64_t r0, r1;
+
+    muls64(&r0, &r1, EAX, t0);
+    EAX = r0;
+    EDX = r1;
+    CC_DST = r0;
+    CC_SRC = ((int64_t)r1 != ((int64_t)r0 >> 63));
+}
+
+target_ulong helper_imulq_T0_T1(target_ulong t0, target_ulong t1)
+{
+    uint64_t r0, r1;
+
+    muls64(&r0, &r1, t0, t1);
+    CC_DST = r0;
+    CC_SRC = ((int64_t)r1 != ((int64_t)r0 >> 63));
+    return r0;
+}
+
+void helper_divq_EAX(target_ulong t0)
+{
+    uint64_t r0, r1;
+
+    if (t0 == 0) {
+        raise_exception(env, EXCP00_DIVZ);
+    }
+    r0 = EAX;
+    r1 = EDX;
+    if (div64(&r0, &r1, t0)) {
+        raise_exception(env, EXCP00_DIVZ);
+    }
+    EAX = r0;
+    EDX = r1;
+}
+
+void helper_idivq_EAX(target_ulong t0)
+{
+    uint64_t r0, r1;
+
+    if (t0 == 0) {
+        raise_exception(env, EXCP00_DIVZ);
+    }
+    r0 = EAX;
+    r1 = EDX;
+    if (idiv64(&r0, &r1, t0)) {
+        raise_exception(env, EXCP00_DIVZ);
+    }
+    EAX = r0;
+    EDX = r1;
+}
+#endif
+
+/* bit operations */
+target_ulong helper_bsf(target_ulong t0)
+{
+    int count;
+    target_ulong res;
+
+    res = t0;
+    count = 0;
+    while ((res & 1) == 0) {
+        count++;
+        res >>= 1;
+    }
+    return count;
+}
+
+target_ulong helper_lzcnt(target_ulong t0, int wordsize)
+{
+    int count;
+    target_ulong res, mask;
+
+    if (wordsize > 0 && t0 == 0) {
+        return wordsize;
+    }
+    res = t0;
+    count = TARGET_LONG_BITS - 1;
+    mask = (target_ulong)1 << (TARGET_LONG_BITS - 1);
+    while ((res & mask) == 0) {
+        count--;
+        res <<= 1;
+    }
+    if (wordsize > 0) {
+        return wordsize - 1 - count;
+    }
+    return count;
+}
+
+target_ulong helper_bsr(target_ulong t0)
+{
+    return helper_lzcnt(t0, 0);
+}
+
+#define SHIFT 0
+#include "shift_helper_template.h"
+#undef SHIFT
+
+#define SHIFT 1
+#include "shift_helper_template.h"
+#undef SHIFT
+
+#define SHIFT 2
+#include "shift_helper_template.h"
+#undef SHIFT
+
+#ifdef TARGET_X86_64
+#define SHIFT 3
+#include "shift_helper_template.h"
+#undef SHIFT
+#endif
diff --git a/target-i386/op_helper.c b/target-i386/op_helper.c
index 44b5467..af8ff64 100644
--- a/target-i386/op_helper.c
+++ b/target-i386/op_helper.c
@@ -19,7 +19,6 @@
 
 #include "cpu.h"
 #include "dyngen-exec.h"
-#include "host-utils.h"
 #include "ioport.h"
 #include "qemu-log.h"
 #include "cpu-defs.h"
@@ -30,7 +29,6 @@
 #endif /* !defined(CONFIG_USER_ONLY) */
 
 //#define DEBUG_PCALL
-//#define DEBUG_MULDIV
 
 #ifdef DEBUG_PCALL
 # define LOG_PCALL(...) qemu_log_mask(CPU_LOG_PCALL, ## __VA_ARGS__)
@@ -41,22 +39,6 @@
 # define LOG_PCALL_STATE(env) do { } while (0)
 #endif
 
-/* modulo 17 table */
-static const uint8_t rclw_table[32] = {
-    0, 1, 2, 3, 4, 5, 6, 7,
-    8, 9, 10, 11, 12, 13, 14, 15,
-    16, 0, 1, 2, 3, 4, 5, 6,
-    7, 8, 9, 10, 11, 12, 13, 14,
-};
-
-/* modulo 9 table */
-static const uint8_t rclb_table[32] = {
-    0, 1, 2, 3, 4, 5, 6, 7,
-    8, 0, 1, 2, 3, 4, 5, 6,
-    7, 8, 0, 1, 2, 3, 4, 5,
-    6, 7, 8, 0, 1, 2, 3, 4,
-};
-
 /* broken thread support */
 
 static spinlock_t global_cpu_lock = SPIN_LOCK_UNLOCKED;
@@ -1656,252 +1638,6 @@ void helper_rsm(void)
 
 #endif /* !CONFIG_USER_ONLY */
 
-
-/* division, flags are undefined */
-
-void helper_divb_AL(target_ulong t0)
-{
-    unsigned int num, den, q, r;
-
-    num = (EAX & 0xffff);
-    den = (t0 & 0xff);
-    if (den == 0) {
-        raise_exception(env, EXCP00_DIVZ);
-    }
-    q = (num / den);
-    if (q > 0xff) {
-        raise_exception(env, EXCP00_DIVZ);
-    }
-    q &= 0xff;
-    r = (num % den) & 0xff;
-    EAX = (EAX & ~0xffff) | (r << 8) | q;
-}
-
-void helper_idivb_AL(target_ulong t0)
-{
-    int num, den, q, r;
-
-    num = (int16_t)EAX;
-    den = (int8_t)t0;
-    if (den == 0) {
-        raise_exception(env, EXCP00_DIVZ);
-    }
-    q = (num / den);
-    if (q != (int8_t)q) {
-        raise_exception(env, EXCP00_DIVZ);
-    }
-    q &= 0xff;
-    r = (num % den) & 0xff;
-    EAX = (EAX & ~0xffff) | (r << 8) | q;
-}
-
-void helper_divw_AX(target_ulong t0)
-{
-    unsigned int num, den, q, r;
-
-    num = (EAX & 0xffff) | ((EDX & 0xffff) << 16);
-    den = (t0 & 0xffff);
-    if (den == 0) {
-        raise_exception(env, EXCP00_DIVZ);
-    }
-    q = (num / den);
-    if (q > 0xffff) {
-        raise_exception(env, EXCP00_DIVZ);
-    }
-    q &= 0xffff;
-    r = (num % den) & 0xffff;
-    EAX = (EAX & ~0xffff) | q;
-    EDX = (EDX & ~0xffff) | r;
-}
-
-void helper_idivw_AX(target_ulong t0)
-{
-    int num, den, q, r;
-
-    num = (EAX & 0xffff) | ((EDX & 0xffff) << 16);
-    den = (int16_t)t0;
-    if (den == 0) {
-        raise_exception(env, EXCP00_DIVZ);
-    }
-    q = (num / den);
-    if (q != (int16_t)q) {
-        raise_exception(env, EXCP00_DIVZ);
-    }
-    q &= 0xffff;
-    r = (num % den) & 0xffff;
-    EAX = (EAX & ~0xffff) | q;
-    EDX = (EDX & ~0xffff) | r;
-}
-
-void helper_divl_EAX(target_ulong t0)
-{
-    unsigned int den, r;
-    uint64_t num, q;
-
-    num = ((uint32_t)EAX) | ((uint64_t)((uint32_t)EDX) << 32);
-    den = t0;
-    if (den == 0) {
-        raise_exception(env, EXCP00_DIVZ);
-    }
-    q = (num / den);
-    r = (num % den);
-    if (q > 0xffffffff) {
-        raise_exception(env, EXCP00_DIVZ);
-    }
-    EAX = (uint32_t)q;
-    EDX = (uint32_t)r;
-}
-
-void helper_idivl_EAX(target_ulong t0)
-{
-    int den, r;
-    int64_t num, q;
-
-    num = ((uint32_t)EAX) | ((uint64_t)((uint32_t)EDX) << 32);
-    den = t0;
-    if (den == 0) {
-        raise_exception(env, EXCP00_DIVZ);
-    }
-    q = (num / den);
-    r = (num % den);
-    if (q != (int32_t)q) {
-        raise_exception(env, EXCP00_DIVZ);
-    }
-    EAX = (uint32_t)q;
-    EDX = (uint32_t)r;
-}
-
-/* bcd */
-
-/* XXX: exception */
-void helper_aam(int base)
-{
-    int al, ah;
-
-    al = EAX & 0xff;
-    ah = al / base;
-    al = al % base;
-    EAX = (EAX & ~0xffff) | al | (ah << 8);
-    CC_DST = al;
-}
-
-void helper_aad(int base)
-{
-    int al, ah;
-
-    al = EAX & 0xff;
-    ah = (EAX >> 8) & 0xff;
-    al = ((ah * base) + al) & 0xff;
-    EAX = (EAX & ~0xffff) | al;
-    CC_DST = al;
-}
-
-void helper_aaa(void)
-{
-    int icarry;
-    int al, ah, af;
-    int eflags;
-
-    eflags = helper_cc_compute_all(CC_OP);
-    af = eflags & CC_A;
-    al = EAX & 0xff;
-    ah = (EAX >> 8) & 0xff;
-
-    icarry = (al > 0xf9);
-    if (((al & 0x0f) > 9) || af) {
-        al = (al + 6) & 0x0f;
-        ah = (ah + 1 + icarry) & 0xff;
-        eflags |= CC_C | CC_A;
-    } else {
-        eflags &= ~(CC_C | CC_A);
-        al &= 0x0f;
-    }
-    EAX = (EAX & ~0xffff) | al | (ah << 8);
-    CC_SRC = eflags;
-}
-
-void helper_aas(void)
-{
-    int icarry;
-    int al, ah, af;
-    int eflags;
-
-    eflags = helper_cc_compute_all(CC_OP);
-    af = eflags & CC_A;
-    al = EAX & 0xff;
-    ah = (EAX >> 8) & 0xff;
-
-    icarry = (al < 6);
-    if (((al & 0x0f) > 9) || af) {
-        al = (al - 6) & 0x0f;
-        ah = (ah - 1 - icarry) & 0xff;
-        eflags |= CC_C | CC_A;
-    } else {
-        eflags &= ~(CC_C | CC_A);
-        al &= 0x0f;
-    }
-    EAX = (EAX & ~0xffff) | al | (ah << 8);
-    CC_SRC = eflags;
-}
-
-void helper_daa(void)
-{
-    int old_al, al, af, cf;
-    int eflags;
-
-    eflags = helper_cc_compute_all(CC_OP);
-    cf = eflags & CC_C;
-    af = eflags & CC_A;
-    old_al = al = EAX & 0xff;
-
-    eflags = 0;
-    if (((al & 0x0f) > 9) || af) {
-        al = (al + 6) & 0xff;
-        eflags |= CC_A;
-    }
-    if ((old_al > 0x99) || cf) {
-        al = (al + 0x60) & 0xff;
-        eflags |= CC_C;
-    }
-    EAX = (EAX & ~0xff) | al;
-    /* well, speed is not an issue here, so we compute the flags by hand */
-    eflags |= (al == 0) << 6; /* zf */
-    eflags |= parity_table[al]; /* pf */
-    eflags |= (al & 0x80); /* sf */
-    CC_SRC = eflags;
-}
-
-void helper_das(void)
-{
-    int al, al1, af, cf;
-    int eflags;
-
-    eflags = helper_cc_compute_all(CC_OP);
-    cf = eflags & CC_C;
-    af = eflags & CC_A;
-    al = EAX & 0xff;
-
-    eflags = 0;
-    al1 = al;
-    if (((al & 0x0f) > 9) || af) {
-        eflags |= CC_A;
-        if (al < 6 || cf) {
-            eflags |= CC_C;
-        }
-        al = (al - 6) & 0xff;
-    }
-    if ((al1 > 0x99) || cf) {
-        al = (al - 0x60) & 0xff;
-        eflags |= CC_C;
-    }
-    EAX = (EAX & ~0xff) | al;
-    /* well, speed is not an issue here, so we compute the flags by hand */
-    eflags |= (al == 0) << 6; /* zf */
-    eflags |= parity_table[al]; /* pf */
-    eflags |= (al & 0x80); /* sf */
-    CC_SRC = eflags;
-}
-
 void helper_into(int next_eip_addend)
 {
     int eflags;
@@ -3614,161 +3350,6 @@ void cpu_x86_load_seg(CPUX86State *s, int seg_reg, int selector)
 }
 #endif
 
-#ifdef TARGET_X86_64
-static void add128(uint64_t *plow, uint64_t *phigh, uint64_t a, uint64_t b)
-{
-    *plow += a;
-    /* carry test */
-    if (*plow < a) {
-        (*phigh)++;
-    }
-    *phigh += b;
-}
-
-static void neg128(uint64_t *plow, uint64_t *phigh)
-{
-    *plow = ~*plow;
-    *phigh = ~*phigh;
-    add128(plow, phigh, 1, 0);
-}
-
-/* return TRUE if overflow */
-static int div64(uint64_t *plow, uint64_t *phigh, uint64_t b)
-{
-    uint64_t q, r, a1, a0;
-    int i, qb, ab;
-
-    a0 = *plow;
-    a1 = *phigh;
-    if (a1 == 0) {
-        q = a0 / b;
-        r = a0 % b;
-        *plow = q;
-        *phigh = r;
-    } else {
-        if (a1 >= b) {
-            return 1;
-        }
-        /* XXX: use a better algorithm */
-        for (i = 0; i < 64; i++) {
-            ab = a1 >> 63;
-            a1 = (a1 << 1) | (a0 >> 63);
-            if (ab || a1 >= b) {
-                a1 -= b;
-                qb = 1;
-            } else {
-                qb = 0;
-            }
-            a0 = (a0 << 1) | qb;
-        }
-#if defined(DEBUG_MULDIV)
-        printf("div: 0x%016" PRIx64 "%016" PRIx64 " / 0x%016" PRIx64
-               ": q=0x%016" PRIx64 " r=0x%016" PRIx64 "\n",
-               *phigh, *plow, b, a0, a1);
-#endif
-        *plow = a0;
-        *phigh = a1;
-    }
-    return 0;
-}
-
-/* return TRUE if overflow */
-static int idiv64(uint64_t *plow, uint64_t *phigh, int64_t b)
-{
-    int sa, sb;
-
-    sa = ((int64_t)*phigh < 0);
-    if (sa) {
-        neg128(plow, phigh);
-    }
-    sb = (b < 0);
-    if (sb) {
-        b = -b;
-    }
-    if (div64(plow, phigh, b) != 0) {
-        return 1;
-    }
-    if (sa ^ sb) {
-        if (*plow > (1ULL << 63)) {
-            return 1;
-        }
-        *plow = -*plow;
-    } else {
-        if (*plow >= (1ULL << 63)) {
-            return 1;
-        }
-    }
-    if (sa) {
-        *phigh = -*phigh;
-    }
-    return 0;
-}
-
-void helper_mulq_EAX_T0(target_ulong t0)
-{
-    uint64_t r0, r1;
-
-    mulu64(&r0, &r1, EAX, t0);
-    EAX = r0;
-    EDX = r1;
-    CC_DST = r0;
-    CC_SRC = r1;
-}
-
-void helper_imulq_EAX_T0(target_ulong t0)
-{
-    uint64_t r0, r1;
-
-    muls64(&r0, &r1, EAX, t0);
-    EAX = r0;
-    EDX = r1;
-    CC_DST = r0;
-    CC_SRC = ((int64_t)r1 != ((int64_t)r0 >> 63));
-}
-
-target_ulong helper_imulq_T0_T1(target_ulong t0, target_ulong t1)
-{
-    uint64_t r0, r1;
-
-    muls64(&r0, &r1, t0, t1);
-    CC_DST = r0;
-    CC_SRC = ((int64_t)r1 != ((int64_t)r0 >> 63));
-    return r0;
-}
-
-void helper_divq_EAX(target_ulong t0)
-{
-    uint64_t r0, r1;
-
-    if (t0 == 0) {
-        raise_exception(env, EXCP00_DIVZ);
-    }
-    r0 = EAX;
-    r1 = EDX;
-    if (div64(&r0, &r1, t0)) {
-        raise_exception(env, EXCP00_DIVZ);
-    }
-    EAX = r0;
-    EDX = r1;
-}
-
-void helper_idivq_EAX(target_ulong t0)
-{
-    uint64_t r0, r1;
-
-    if (t0 == 0) {
-        raise_exception(env, EXCP00_DIVZ);
-    }
-    r0 = EAX;
-    r1 = EDX;
-    if (idiv64(&r0, &r1, t0)) {
-        raise_exception(env, EXCP00_DIVZ);
-    }
-    EAX = r0;
-    EDX = r1;
-}
-#endif
-
 static void do_hlt(void)
 {
     env->hflags &= ~HF_INHIBIT_IRQ_MASK; /* needed if sti is just before */
@@ -4583,62 +4164,3 @@ void cpu_vmexit(CPUX86State *nenv, uint32_t exit_code, uint64_t exit_info_1)
 }
 
 #endif
-
-#define SHIFT 0
-#include "shift_helper_template.h"
-#undef SHIFT
-
-#define SHIFT 1
-#include "shift_helper_template.h"
-#undef SHIFT
-
-#define SHIFT 2
-#include "shift_helper_template.h"
-#undef SHIFT
-
-#ifdef TARGET_X86_64
-#define SHIFT 3
-#include "shift_helper_template.h"
-#undef SHIFT
-#endif
-
-/* bit operations */
-target_ulong helper_bsf(target_ulong t0)
-{
-    int count;
-    target_ulong res;
-
-    res = t0;
-    count = 0;
-    while ((res & 1) == 0) {
-        count++;
-        res >>= 1;
-    }
-    return count;
-}
-
-target_ulong helper_lzcnt(target_ulong t0, int wordsize)
-{
-    int count;
-    target_ulong res, mask;
-
-    if (wordsize > 0 && t0 == 0) {
-        return wordsize;
-    }
-    res = t0;
-    count = TARGET_LONG_BITS - 1;
-    mask = (target_ulong)1 << (TARGET_LONG_BITS - 1);
-    while ((res & mask) == 0) {
-        count--;
-        res <<= 1;
-    }
-    if (wordsize > 0) {
-        return wordsize - 1 - count;
-    }
-    return count;
-}
-
-target_ulong helper_bsr(target_ulong t0)
-{
-    return helper_lzcnt(t0, 0);
-}
commit 5918fffb1d5060bf8a480c5201a17f09baa26514
Author: Blue Swirl <blauwirbel at gmail.com>
Date:   Sun Apr 29 12:21:21 2012 +0000

    x86: split off condition code helpers
    
    Move condition code helpers to cc_helper.c.
    
    Move the shared inline functions lshift(), cpu_load_eflags() and
    cpu_cc_compute_all() to cpu.h.
    
    Signed-off-by: Blue Swirl <blauwirbel at gmail.com>

diff --git a/target-i386/Makefile.objs b/target-i386/Makefile.objs
index 7c15de4..96a2266 100644
--- a/target-i386/Makefile.objs
+++ b/target-i386/Makefile.objs
@@ -1,5 +1,5 @@
 obj-y += translate.o op_helper.o helper.o cpu.o
-obj-y += excp_helper.o fpu_helper.o
+obj-y += excp_helper.o fpu_helper.o cc_helper.o
 obj-$(CONFIG_SOFTMMU) += machine.o arch_memory_mapping.o arch_dump.o
 obj-$(CONFIG_KVM) += kvm.o hyperv.o
 obj-$(CONFIG_LINUX_USER) += ioport-user.o
@@ -7,3 +7,4 @@ obj-$(CONFIG_BSD_USER) += ioport-user.o
 
 $(obj)/op_helper.o: QEMU_CFLAGS += $(HELPER_CFLAGS)
 $(obj)/fpu_helper.o: QEMU_CFLAGS += $(HELPER_CFLAGS)
+$(obj)/cc_helper.o: QEMU_CFLAGS += $(HELPER_CFLAGS)
diff --git a/target-i386/cc_helper.c b/target-i386/cc_helper.c
new file mode 100644
index 0000000..ff654bc
--- /dev/null
+++ b/target-i386/cc_helper.c
@@ -0,0 +1,387 @@
+/*
+ *  x86 condition code helpers
+ *
+ *  Copyright (c) 2003 Fabrice Bellard
+ *
+ * This library is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Lesser General Public
+ * License as published by the Free Software Foundation; either
+ * version 2 of the License, or (at your option) any later version.
+ *
+ * This library is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
+ * Lesser General Public License for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public
+ * License along with this library; if not, see <http://www.gnu.org/licenses/>.
+ */
+
+#include "cpu.h"
+#include "dyngen-exec.h"
+#include "helper.h"
+
+const uint8_t parity_table[256] = {
+    CC_P, 0, 0, CC_P, 0, CC_P, CC_P, 0,
+    0, CC_P, CC_P, 0, CC_P, 0, 0, CC_P,
+    0, CC_P, CC_P, 0, CC_P, 0, 0, CC_P,
+    CC_P, 0, 0, CC_P, 0, CC_P, CC_P, 0,
+    0, CC_P, CC_P, 0, CC_P, 0, 0, CC_P,
+    CC_P, 0, 0, CC_P, 0, CC_P, CC_P, 0,
+    CC_P, 0, 0, CC_P, 0, CC_P, CC_P, 0,
+    0, CC_P, CC_P, 0, CC_P, 0, 0, CC_P,
+    0, CC_P, CC_P, 0, CC_P, 0, 0, CC_P,
+    CC_P, 0, 0, CC_P, 0, CC_P, CC_P, 0,
+    CC_P, 0, 0, CC_P, 0, CC_P, CC_P, 0,
+    0, CC_P, CC_P, 0, CC_P, 0, 0, CC_P,
+    CC_P, 0, 0, CC_P, 0, CC_P, CC_P, 0,
+    0, CC_P, CC_P, 0, CC_P, 0, 0, CC_P,
+    0, CC_P, CC_P, 0, CC_P, 0, 0, CC_P,
+    CC_P, 0, 0, CC_P, 0, CC_P, CC_P, 0,
+    0, CC_P, CC_P, 0, CC_P, 0, 0, CC_P,
+    CC_P, 0, 0, CC_P, 0, CC_P, CC_P, 0,
+    CC_P, 0, 0, CC_P, 0, CC_P, CC_P, 0,
+    0, CC_P, CC_P, 0, CC_P, 0, 0, CC_P,
+    CC_P, 0, 0, CC_P, 0, CC_P, CC_P, 0,
+    0, CC_P, CC_P, 0, CC_P, 0, 0, CC_P,
+    0, CC_P, CC_P, 0, CC_P, 0, 0, CC_P,
+    CC_P, 0, 0, CC_P, 0, CC_P, CC_P, 0,
+    CC_P, 0, 0, CC_P, 0, CC_P, CC_P, 0,
+    0, CC_P, CC_P, 0, CC_P, 0, 0, CC_P,
+    0, CC_P, CC_P, 0, CC_P, 0, 0, CC_P,
+    CC_P, 0, 0, CC_P, 0, CC_P, CC_P, 0,
+    0, CC_P, CC_P, 0, CC_P, 0, 0, CC_P,
+    CC_P, 0, 0, CC_P, 0, CC_P, CC_P, 0,
+    CC_P, 0, 0, CC_P, 0, CC_P, CC_P, 0,
+    0, CC_P, CC_P, 0, CC_P, 0, 0, CC_P,
+};
+
+#define SHIFT 0
+#include "cc_helper_template.h"
+#undef SHIFT
+
+#define SHIFT 1
+#include "cc_helper_template.h"
+#undef SHIFT
+
+#define SHIFT 2
+#include "cc_helper_template.h"
+#undef SHIFT
+
+#ifdef TARGET_X86_64
+
+#define SHIFT 3
+#include "cc_helper_template.h"
+#undef SHIFT
+
+#endif
+
+static int compute_all_eflags(void)
+{
+    return CC_SRC;
+}
+
+static int compute_c_eflags(void)
+{
+    return CC_SRC & CC_C;
+}
+
+uint32_t helper_cc_compute_all(int op)
+{
+    switch (op) {
+    default: /* should never happen */
+        return 0;
+
+    case CC_OP_EFLAGS:
+        return compute_all_eflags();
+
+    case CC_OP_MULB:
+        return compute_all_mulb();
+    case CC_OP_MULW:
+        return compute_all_mulw();
+    case CC_OP_MULL:
+        return compute_all_mull();
+
+    case CC_OP_ADDB:
+        return compute_all_addb();
+    case CC_OP_ADDW:
+        return compute_all_addw();
+    case CC_OP_ADDL:
+        return compute_all_addl();
+
+    case CC_OP_ADCB:
+        return compute_all_adcb();
+    case CC_OP_ADCW:
+        return compute_all_adcw();
+    case CC_OP_ADCL:
+        return compute_all_adcl();
+
+    case CC_OP_SUBB:
+        return compute_all_subb();
+    case CC_OP_SUBW:
+        return compute_all_subw();
+    case CC_OP_SUBL:
+        return compute_all_subl();
+
+    case CC_OP_SBBB:
+        return compute_all_sbbb();
+    case CC_OP_SBBW:
+        return compute_all_sbbw();
+    case CC_OP_SBBL:
+        return compute_all_sbbl();
+
+    case CC_OP_LOGICB:
+        return compute_all_logicb();
+    case CC_OP_LOGICW:
+        return compute_all_logicw();
+    case CC_OP_LOGICL:
+        return compute_all_logicl();
+
+    case CC_OP_INCB:
+        return compute_all_incb();
+    case CC_OP_INCW:
+        return compute_all_incw();
+    case CC_OP_INCL:
+        return compute_all_incl();
+
+    case CC_OP_DECB:
+        return compute_all_decb();
+    case CC_OP_DECW:
+        return compute_all_decw();
+    case CC_OP_DECL:
+        return compute_all_decl();
+
+    case CC_OP_SHLB:
+        return compute_all_shlb();
+    case CC_OP_SHLW:
+        return compute_all_shlw();
+    case CC_OP_SHLL:
+        return compute_all_shll();
+
+    case CC_OP_SARB:
+        return compute_all_sarb();
+    case CC_OP_SARW:
+        return compute_all_sarw();
+    case CC_OP_SARL:
+        return compute_all_sarl();
+
+#ifdef TARGET_X86_64
+    case CC_OP_MULQ:
+        return compute_all_mulq();
+
+    case CC_OP_ADDQ:
+        return compute_all_addq();
+
+    case CC_OP_ADCQ:
+        return compute_all_adcq();
+
+    case CC_OP_SUBQ:
+        return compute_all_subq();
+
+    case CC_OP_SBBQ:
+        return compute_all_sbbq();
+
+    case CC_OP_LOGICQ:
+        return compute_all_logicq();
+
+    case CC_OP_INCQ:
+        return compute_all_incq();
+
+    case CC_OP_DECQ:
+        return compute_all_decq();
+
+    case CC_OP_SHLQ:
+        return compute_all_shlq();
+
+    case CC_OP_SARQ:
+        return compute_all_sarq();
+#endif
+    }
+}
+
+uint32_t cpu_cc_compute_all(CPUX86State *env1, int op)
+{
+    CPUX86State *saved_env;
+    uint32_t ret;
+
+    saved_env = env;
+    env = env1;
+    ret = helper_cc_compute_all(op);
+    env = saved_env;
+    return ret;
+}
+
+uint32_t helper_cc_compute_c(int op)
+{
+    switch (op) {
+    default: /* should never happen */
+        return 0;
+
+    case CC_OP_EFLAGS:
+        return compute_c_eflags();
+
+    case CC_OP_MULB:
+        return compute_c_mull();
+    case CC_OP_MULW:
+        return compute_c_mull();
+    case CC_OP_MULL:
+        return compute_c_mull();
+
+    case CC_OP_ADDB:
+        return compute_c_addb();
+    case CC_OP_ADDW:
+        return compute_c_addw();
+    case CC_OP_ADDL:
+        return compute_c_addl();
+
+    case CC_OP_ADCB:
+        return compute_c_adcb();
+    case CC_OP_ADCW:
+        return compute_c_adcw();
+    case CC_OP_ADCL:
+        return compute_c_adcl();
+
+    case CC_OP_SUBB:
+        return compute_c_subb();
+    case CC_OP_SUBW:
+        return compute_c_subw();
+    case CC_OP_SUBL:
+        return compute_c_subl();
+
+    case CC_OP_SBBB:
+        return compute_c_sbbb();
+    case CC_OP_SBBW:
+        return compute_c_sbbw();
+    case CC_OP_SBBL:
+        return compute_c_sbbl();
+
+    case CC_OP_LOGICB:
+        return compute_c_logicb();
+    case CC_OP_LOGICW:
+        return compute_c_logicw();
+    case CC_OP_LOGICL:
+        return compute_c_logicl();
+
+    case CC_OP_INCB:
+        return compute_c_incl();
+    case CC_OP_INCW:
+        return compute_c_incl();
+    case CC_OP_INCL:
+        return compute_c_incl();
+
+    case CC_OP_DECB:
+        return compute_c_incl();
+    case CC_OP_DECW:
+        return compute_c_incl();
+    case CC_OP_DECL:
+        return compute_c_incl();
+
+    case CC_OP_SHLB:
+        return compute_c_shlb();
+    case CC_OP_SHLW:
+        return compute_c_shlw();
+    case CC_OP_SHLL:
+        return compute_c_shll();
+
+    case CC_OP_SARB:
+        return compute_c_sarl();
+    case CC_OP_SARW:
+        return compute_c_sarl();
+    case CC_OP_SARL:
+        return compute_c_sarl();
+
+#ifdef TARGET_X86_64
+    case CC_OP_MULQ:
+        return compute_c_mull();
+
+    case CC_OP_ADDQ:
+        return compute_c_addq();
+
+    case CC_OP_ADCQ:
+        return compute_c_adcq();
+
+    case CC_OP_SUBQ:
+        return compute_c_subq();
+
+    case CC_OP_SBBQ:
+        return compute_c_sbbq();
+
+    case CC_OP_LOGICQ:
+        return compute_c_logicq();
+
+    case CC_OP_INCQ:
+        return compute_c_incl();
+
+    case CC_OP_DECQ:
+        return compute_c_incl();
+
+    case CC_OP_SHLQ:
+        return compute_c_shlq();
+
+    case CC_OP_SARQ:
+        return compute_c_sarl();
+#endif
+    }
+}
+
+void helper_write_eflags(target_ulong t0, uint32_t update_mask)
+{
+    cpu_load_eflags(env, t0, update_mask);
+}
+
+target_ulong helper_read_eflags(void)
+{
+    uint32_t eflags;
+
+    eflags = helper_cc_compute_all(CC_OP);
+    eflags |= (DF & DF_MASK);
+    eflags |= env->eflags & ~(VM_MASK | RF_MASK);
+    return eflags;
+}
+
+void helper_clts(void)
+{
+    env->cr[0] &= ~CR0_TS_MASK;
+    env->hflags &= ~HF_TS_MASK;
+}
+
+void helper_reset_rf(void)
+{
+    env->eflags &= ~RF_MASK;
+}
+
+void helper_cli(void)
+{
+    env->eflags &= ~IF_MASK;
+}
+
+void helper_sti(void)
+{
+    env->eflags |= IF_MASK;
+}
+
+#if 0
+/* vm86plus instructions */
+void helper_cli_vm(void)
+{
+    env->eflags &= ~VIF_MASK;
+}
+
+void helper_sti_vm(void)
+{
+    env->eflags |= VIF_MASK;
+    if (env->eflags & VIP_MASK) {
+        raise_exception(env, EXCP0D_GPF);
+    }
+}
+#endif
+
+void helper_set_inhibit_irq(void)
+{
+    env->hflags |= HF_INHIBIT_IRQ_MASK;
+}
+
+void helper_reset_inhibit_irq(void)
+{
+    env->hflags &= ~HF_INHIBIT_IRQ_MASK;
+}
diff --git a/target-i386/cpu.h b/target-i386/cpu.h
index cea8ecc..7d7ad33 100644
--- a/target-i386/cpu.h
+++ b/target-i386/cpu.h
@@ -1010,6 +1010,16 @@ static inline int cpu_mmu_index (CPUX86State *env)
 #define CC_DST (env->cc_dst)
 #define CC_OP  (env->cc_op)
 
+/* n must be a constant to be efficient */
+static inline target_long lshift(target_long x, int n)
+{
+    if (n >= 0) {
+        return x << n;
+    } else {
+        return x >> (-n);
+    }
+}
+
 /* float macros */
 #define FT0    (env->ft0)
 #define ST0    (env->fpregs[env->fpstt].d)
@@ -1078,6 +1088,39 @@ void QEMU_NORETURN raise_exception_err(CPUX86State *env, int exception_index,
 void QEMU_NORETURN raise_interrupt(CPUX86State *nenv, int intno, int is_int,
                                    int error_code, int next_eip_addend);
 
+/* cc_helper.c */
+extern const uint8_t parity_table[256];
+uint32_t cpu_cc_compute_all(CPUX86State *env1, int op);
+
+static inline uint32_t cpu_compute_eflags(CPUX86State *env)
+{
+    return env->eflags | cpu_cc_compute_all(env, CC_OP) | (DF & DF_MASK);
+}
+
+/* NOTE: CC_OP must be modified manually to CC_OP_EFLAGS */
+static inline void cpu_load_eflags(CPUX86State *env, int eflags,
+                                   int update_mask)
+{
+    CC_SRC = eflags & (CC_O | CC_S | CC_Z | CC_A | CC_P | CC_C);
+    DF = 1 - (2 * ((eflags >> 10) & 1));
+    env->eflags = (env->eflags & ~update_mask) |
+        (eflags & update_mask) | 0x2;
+}
+
+/* load efer and update the corresponding hflags. XXX: do consistency
+   checks with cpuid bits? */
+static inline void cpu_load_efer(CPUX86State *env, uint64_t val)
+{
+    env->efer = val;
+    env->hflags &= ~(HF_LMA_MASK | HF_SVME_MASK);
+    if (env->efer & MSR_EFER_LMA) {
+        env->hflags |= HF_LMA_MASK;
+    }
+    if (env->efer & MSR_EFER_SVME) {
+        env->hflags |= HF_SVME_MASK;
+    }
+}
+
 /* op_helper.c */
 void do_interrupt(CPUX86State *env);
 void do_interrupt_x86_hardirq(CPUX86State *env, int intno, int is_hw);
@@ -1088,8 +1131,6 @@ void cpu_svm_check_intercept_param(CPUX86State *env1, uint32_t type,
                                    uint64_t param);
 void cpu_vmexit(CPUX86State *nenv, uint32_t exit_code, uint64_t exit_info_1);
 
-uint32_t cpu_cc_compute_all(CPUX86State *env1, int op);
-
 void cpu_report_tpr_access(CPUX86State *env, TPRAccess access);
 
 #endif /* CPU_I386_H */
diff --git a/target-i386/op_helper.c b/target-i386/op_helper.c
index a65b6a2..44b5467 100644
--- a/target-i386/op_helper.c
+++ b/target-i386/op_helper.c
@@ -41,80 +41,6 @@
 # define LOG_PCALL_STATE(env) do { } while (0)
 #endif
 
-/* n must be a constant to be efficient */
-static inline target_long lshift(target_long x, int n)
-{
-    if (n >= 0) {
-        return x << n;
-    } else {
-        return x >> (-n);
-    }
-}
-
-static inline uint32_t cpu_compute_eflags(CPUX86State *env)
-{
-    return env->eflags | cpu_cc_compute_all(env, CC_OP) | (DF & DF_MASK);
-}
-
-/* NOTE: CC_OP must be modified manually to CC_OP_EFLAGS */
-static inline void cpu_load_eflags(CPUX86State *env, int eflags,
-                                   int update_mask)
-{
-    CC_SRC = eflags & (CC_O | CC_S | CC_Z | CC_A | CC_P | CC_C);
-    DF = 1 - (2 * ((eflags >> 10) & 1));
-    env->eflags = (env->eflags & ~update_mask) |
-        (eflags & update_mask) | 0x2;
-}
-
-/* load efer and update the corresponding hflags. XXX: do consistency
-   checks with cpuid bits? */
-static inline void cpu_load_efer(CPUX86State *env, uint64_t val)
-{
-    env->efer = val;
-    env->hflags &= ~(HF_LMA_MASK | HF_SVME_MASK);
-    if (env->efer & MSR_EFER_LMA) {
-        env->hflags |= HF_LMA_MASK;
-    }
-    if (env->efer & MSR_EFER_SVME) {
-        env->hflags |= HF_SVME_MASK;
-    }
-}
-
-static const uint8_t parity_table[256] = {
-    CC_P, 0, 0, CC_P, 0, CC_P, CC_P, 0,
-    0, CC_P, CC_P, 0, CC_P, 0, 0, CC_P,
-    0, CC_P, CC_P, 0, CC_P, 0, 0, CC_P,
-    CC_P, 0, 0, CC_P, 0, CC_P, CC_P, 0,
-    0, CC_P, CC_P, 0, CC_P, 0, 0, CC_P,
-    CC_P, 0, 0, CC_P, 0, CC_P, CC_P, 0,
-    CC_P, 0, 0, CC_P, 0, CC_P, CC_P, 0,
-    0, CC_P, CC_P, 0, CC_P, 0, 0, CC_P,
-    0, CC_P, CC_P, 0, CC_P, 0, 0, CC_P,
-    CC_P, 0, 0, CC_P, 0, CC_P, CC_P, 0,
-    CC_P, 0, 0, CC_P, 0, CC_P, CC_P, 0,
-    0, CC_P, CC_P, 0, CC_P, 0, 0, CC_P,
-    CC_P, 0, 0, CC_P, 0, CC_P, CC_P, 0,
-    0, CC_P, CC_P, 0, CC_P, 0, 0, CC_P,
-    0, CC_P, CC_P, 0, CC_P, 0, 0, CC_P,
-    CC_P, 0, 0, CC_P, 0, CC_P, CC_P, 0,
-    0, CC_P, CC_P, 0, CC_P, 0, 0, CC_P,
-    CC_P, 0, 0, CC_P, 0, CC_P, CC_P, 0,
-    CC_P, 0, 0, CC_P, 0, CC_P, CC_P, 0,
-    0, CC_P, CC_P, 0, CC_P, 0, 0, CC_P,
-    CC_P, 0, 0, CC_P, 0, CC_P, CC_P, 0,
-    0, CC_P, CC_P, 0, CC_P, 0, 0, CC_P,
-    0, CC_P, CC_P, 0, CC_P, 0, 0, CC_P,
-    CC_P, 0, 0, CC_P, 0, CC_P, CC_P, 0,
-    CC_P, 0, 0, CC_P, 0, CC_P, CC_P, 0,
-    0, CC_P, CC_P, 0, CC_P, 0, 0, CC_P,
-    0, CC_P, CC_P, 0, CC_P, 0, 0, CC_P,
-    CC_P, 0, 0, CC_P, 0, CC_P, CC_P, 0,
-    0, CC_P, CC_P, 0, CC_P, 0, 0, CC_P,
-    CC_P, 0, 0, CC_P, 0, CC_P, CC_P, 0,
-    CC_P, 0, 0, CC_P, 0, CC_P, CC_P, 0,
-    0, CC_P, CC_P, 0, CC_P, 0, 0, CC_P,
-};
-
 /* modulo 17 table */
 static const uint8_t rclw_table[32] = {
     0, 1, 2, 3, 4, 5, 6, 7,
@@ -145,21 +71,6 @@ void helper_unlock(void)
     spin_unlock(&global_cpu_lock);
 }
 
-void helper_write_eflags(target_ulong t0, uint32_t update_mask)
-{
-    cpu_load_eflags(env, t0, update_mask);
-}
-
-target_ulong helper_read_eflags(void)
-{
-    uint32_t eflags;
-
-    eflags = helper_cc_compute_all(CC_OP);
-    eflags |= (DF & DF_MASK);
-    eflags |= env->eflags & ~(VM_MASK | RF_MASK);
-    return eflags;
-}
-
 /* return non zero if error */
 static inline int load_segment(uint32_t *e1_ptr, uint32_t *e2_ptr,
                                int selector)
@@ -3181,12 +3092,6 @@ void helper_lmsw(target_ulong t0)
     helper_write_crN(0, t0);
 }
 
-void helper_clts(void)
-{
-    env->cr[0] &= ~CR0_TS_MASK;
-    env->hflags &= ~HF_TS_MASK;
-}
-
 void helper_invlpg(target_ulong addr)
 {
     helper_svm_check_intercept_param(SVM_EXIT_INVLPG, 0);
@@ -3912,47 +3817,6 @@ void helper_debug(void)
     cpu_loop_exit(env);
 }
 
-void helper_reset_rf(void)
-{
-    env->eflags &= ~RF_MASK;
-}
-
-void helper_cli(void)
-{
-    env->eflags &= ~IF_MASK;
-}
-
-void helper_sti(void)
-{
-    env->eflags |= IF_MASK;
-}
-
-#if 0
-/* vm86plus instructions */
-void helper_cli_vm(void)
-{
-    env->eflags &= ~VIF_MASK;
-}
-
-void helper_sti_vm(void)
-{
-    env->eflags |= VIF_MASK;
-    if (env->eflags & VIP_MASK) {
-        raise_exception(env, EXCP0D_GPF);
-    }
-}
-#endif
-
-void helper_set_inhibit_irq(void)
-{
-    env->hflags |= HF_INHIBIT_IRQ_MASK;
-}
-
-void helper_reset_inhibit_irq(void)
-{
-    env->hflags &= ~HF_INHIBIT_IRQ_MASK;
-}
-
 void helper_boundw(target_ulong a0, int v)
 {
     int low, high;
@@ -4721,26 +4585,6 @@ void cpu_vmexit(CPUX86State *nenv, uint32_t exit_code, uint64_t exit_info_1)
 #endif
 
 #define SHIFT 0
-#include "cc_helper_template.h"
-#undef SHIFT
-
-#define SHIFT 1
-#include "cc_helper_template.h"
-#undef SHIFT
-
-#define SHIFT 2
-#include "cc_helper_template.h"
-#undef SHIFT
-
-#ifdef TARGET_X86_64
-
-#define SHIFT 3
-#include "cc_helper_template.h"
-#undef SHIFT
-
-#endif
-
-#define SHIFT 0
 #include "shift_helper_template.h"
 #undef SHIFT
 
@@ -4798,251 +4642,3 @@ target_ulong helper_bsr(target_ulong t0)
 {
     return helper_lzcnt(t0, 0);
 }
-
-static int compute_all_eflags(void)
-{
-    return CC_SRC;
-}
-
-static int compute_c_eflags(void)
-{
-    return CC_SRC & CC_C;
-}
-
-uint32_t helper_cc_compute_all(int op)
-{
-    switch (op) {
-    default: /* should never happen */
-        return 0;
-
-    case CC_OP_EFLAGS:
-        return compute_all_eflags();
-
-    case CC_OP_MULB:
-        return compute_all_mulb();
-    case CC_OP_MULW:
-        return compute_all_mulw();
-    case CC_OP_MULL:
-        return compute_all_mull();
-
-    case CC_OP_ADDB:
-        return compute_all_addb();
-    case CC_OP_ADDW:
-        return compute_all_addw();
-    case CC_OP_ADDL:
-        return compute_all_addl();
-
-    case CC_OP_ADCB:
-        return compute_all_adcb();
-    case CC_OP_ADCW:
-        return compute_all_adcw();
-    case CC_OP_ADCL:
-        return compute_all_adcl();
-
-    case CC_OP_SUBB:
-        return compute_all_subb();
-    case CC_OP_SUBW:
-        return compute_all_subw();
-    case CC_OP_SUBL:
-        return compute_all_subl();
-
-    case CC_OP_SBBB:
-        return compute_all_sbbb();
-    case CC_OP_SBBW:
-        return compute_all_sbbw();
-    case CC_OP_SBBL:
-        return compute_all_sbbl();
-
-    case CC_OP_LOGICB:
-        return compute_all_logicb();
-    case CC_OP_LOGICW:
-        return compute_all_logicw();
-    case CC_OP_LOGICL:
-        return compute_all_logicl();
-
-    case CC_OP_INCB:
-        return compute_all_incb();
-    case CC_OP_INCW:
-        return compute_all_incw();
-    case CC_OP_INCL:
-        return compute_all_incl();
-
-    case CC_OP_DECB:
-        return compute_all_decb();
-    case CC_OP_DECW:
-        return compute_all_decw();
-    case CC_OP_DECL:
-        return compute_all_decl();
-
-    case CC_OP_SHLB:
-        return compute_all_shlb();
-    case CC_OP_SHLW:
-        return compute_all_shlw();
-    case CC_OP_SHLL:
-        return compute_all_shll();
-
-    case CC_OP_SARB:
-        return compute_all_sarb();
-    case CC_OP_SARW:
-        return compute_all_sarw();
-    case CC_OP_SARL:
-        return compute_all_sarl();
-
-#ifdef TARGET_X86_64
-    case CC_OP_MULQ:
-        return compute_all_mulq();
-
-    case CC_OP_ADDQ:
-        return compute_all_addq();
-
-    case CC_OP_ADCQ:
-        return compute_all_adcq();
-
-    case CC_OP_SUBQ:
-        return compute_all_subq();
-
-    case CC_OP_SBBQ:
-        return compute_all_sbbq();
-
-    case CC_OP_LOGICQ:
-        return compute_all_logicq();
-
-    case CC_OP_INCQ:
-        return compute_all_incq();
-
-    case CC_OP_DECQ:
-        return compute_all_decq();
-
-    case CC_OP_SHLQ:
-        return compute_all_shlq();
-
-    case CC_OP_SARQ:
-        return compute_all_sarq();
-#endif
-    }
-}
-
-uint32_t cpu_cc_compute_all(CPUX86State *env1, int op)
-{
-    CPUX86State *saved_env;
-    uint32_t ret;
-
-    saved_env = env;
-    env = env1;
-    ret = helper_cc_compute_all(op);
-    env = saved_env;
-    return ret;
-}
-
-uint32_t helper_cc_compute_c(int op)
-{
-    switch (op) {
-    default: /* should never happen */
-        return 0;
-
-    case CC_OP_EFLAGS:
-        return compute_c_eflags();
-
-    case CC_OP_MULB:
-        return compute_c_mull();
-    case CC_OP_MULW:
-        return compute_c_mull();
-    case CC_OP_MULL:
-        return compute_c_mull();
-
-    case CC_OP_ADDB:
-        return compute_c_addb();
-    case CC_OP_ADDW:
-        return compute_c_addw();
-    case CC_OP_ADDL:
-        return compute_c_addl();
-
-    case CC_OP_ADCB:
-        return compute_c_adcb();
-    case CC_OP_ADCW:
-        return compute_c_adcw();
-    case CC_OP_ADCL:
-        return compute_c_adcl();
-
-    case CC_OP_SUBB:
-        return compute_c_subb();
-    case CC_OP_SUBW:
-        return compute_c_subw();
-    case CC_OP_SUBL:
-        return compute_c_subl();
-
-    case CC_OP_SBBB:
-        return compute_c_sbbb();
-    case CC_OP_SBBW:
-        return compute_c_sbbw();
-    case CC_OP_SBBL:
-        return compute_c_sbbl();
-
-    case CC_OP_LOGICB:
-        return compute_c_logicb();
-    case CC_OP_LOGICW:
-        return compute_c_logicw();
-    case CC_OP_LOGICL:
-        return compute_c_logicl();
-
-    case CC_OP_INCB:
-        return compute_c_incl();
-    case CC_OP_INCW:
-        return compute_c_incl();
-    case CC_OP_INCL:
-        return compute_c_incl();
-
-    case CC_OP_DECB:
-        return compute_c_incl();
-    case CC_OP_DECW:
-        return compute_c_incl();
-    case CC_OP_DECL:
-        return compute_c_incl();
-
-    case CC_OP_SHLB:
-        return compute_c_shlb();
-    case CC_OP_SHLW:
-        return compute_c_shlw();
-    case CC_OP_SHLL:
-        return compute_c_shll();
-
-    case CC_OP_SARB:
-        return compute_c_sarl();
-    case CC_OP_SARW:
-        return compute_c_sarl();
-    case CC_OP_SARL:
-        return compute_c_sarl();
-
-#ifdef TARGET_X86_64
-    case CC_OP_MULQ:
-        return compute_c_mull();
-
-    case CC_OP_ADDQ:
-        return compute_c_addq();
-
-    case CC_OP_ADCQ:
-        return compute_c_adcq();
-
-    case CC_OP_SUBQ:
-        return compute_c_subq();
-
-    case CC_OP_SBBQ:
-        return compute_c_sbbq();
-
-    case CC_OP_LOGICQ:
-        return compute_c_logicq();
-
-    case CC_OP_INCQ:
-        return compute_c_incl();
-
-    case CC_OP_DECQ:
-        return compute_c_incl();
-
-    case CC_OP_SHLQ:
-        return compute_c_shlq();
-
-    case CC_OP_SARQ:
-        return compute_c_sarl();
-#endif
-    }
-}
commit 997ff0d9a964b2268c2041ccf1db786140aec257
Author: Blue Swirl <blauwirbel at gmail.com>
Date:   Sun Apr 29 15:01:21 2012 +0000

    x86: prepare eflags helpers for general use
    
    Adjust function names and add an explicit CPUX86State
    parameter instead of relying on AREG0.
    
    Signed-off-by: Blue Swirl <blauwirbel at gmail.com>

diff --git a/target-i386/op_helper.c b/target-i386/op_helper.c
index d791e38..a65b6a2 100644
--- a/target-i386/op_helper.c
+++ b/target-i386/op_helper.c
@@ -51,13 +51,14 @@ static inline target_long lshift(target_long x, int n)
     }
 }
 
-static inline uint32_t compute_eflags(void)
+static inline uint32_t cpu_compute_eflags(CPUX86State *env)
 {
-    return env->eflags | helper_cc_compute_all(CC_OP) | (DF & DF_MASK);
+    return env->eflags | cpu_cc_compute_all(env, CC_OP) | (DF & DF_MASK);
 }
 
 /* NOTE: CC_OP must be modified manually to CC_OP_EFLAGS */
-static inline void load_eflags(int eflags, int update_mask)
+static inline void cpu_load_eflags(CPUX86State *env, int eflags,
+                                   int update_mask)
 {
     CC_SRC = eflags & (CC_O | CC_S | CC_Z | CC_A | CC_P | CC_C);
     DF = 1 - (2 * ((eflags >> 10) & 1));
@@ -146,7 +147,7 @@ void helper_unlock(void)
 
 void helper_write_eflags(target_ulong t0, uint32_t update_mask)
 {
-    load_eflags(t0, update_mask);
+    cpu_load_eflags(env, t0, update_mask);
 }
 
 target_ulong helper_read_eflags(void)
@@ -435,7 +436,7 @@ static void switch_tss(int tss_selector,
         e2 &= ~DESC_TSS_BUSY_MASK;
         stl_kernel(ptr + 4, e2);
     }
-    old_eflags = compute_eflags();
+    old_eflags = cpu_compute_eflags(env);
     if (source == SWITCH_TSS_IRET) {
         old_eflags &= ~NT_MASK;
     }
@@ -513,7 +514,7 @@ static void switch_tss(int tss_selector,
     if (!(type & 8)) {
         eflags_mask &= 0xffff;
     }
-    load_eflags(new_eflags, eflags_mask);
+    cpu_load_eflags(env, new_eflags, eflags_mask);
     /* XXX: what to do in 16 bit case? */
     EAX = new_regs[0];
     ECX = new_regs[1];
@@ -900,7 +901,7 @@ static void do_interrupt_protected(int intno, int is_int, int error_code,
             PUSHL(ssp, esp, sp_mask, env->segs[R_SS].selector);
             PUSHL(ssp, esp, sp_mask, ESP);
         }
-        PUSHL(ssp, esp, sp_mask, compute_eflags());
+        PUSHL(ssp, esp, sp_mask, cpu_compute_eflags(env));
         PUSHL(ssp, esp, sp_mask, env->segs[R_CS].selector);
         PUSHL(ssp, esp, sp_mask, old_eip);
         if (has_error_code) {
@@ -917,7 +918,7 @@ static void do_interrupt_protected(int intno, int is_int, int error_code,
             PUSHW(ssp, esp, sp_mask, env->segs[R_SS].selector);
             PUSHW(ssp, esp, sp_mask, ESP);
         }
-        PUSHW(ssp, esp, sp_mask, compute_eflags());
+        PUSHW(ssp, esp, sp_mask, cpu_compute_eflags(env));
         PUSHW(ssp, esp, sp_mask, env->segs[R_CS].selector);
         PUSHW(ssp, esp, sp_mask, old_eip);
         if (has_error_code) {
@@ -1089,7 +1090,7 @@ static void do_interrupt64(int intno, int is_int, int error_code,
 
     PUSHQ(esp, env->segs[R_SS].selector);
     PUSHQ(esp, ESP);
-    PUSHQ(esp, compute_eflags());
+    PUSHQ(esp, cpu_compute_eflags(env));
     PUSHQ(esp, env->segs[R_CS].selector);
     PUSHQ(esp, old_eip);
     if (has_error_code) {
@@ -1139,7 +1140,7 @@ void helper_syscall(int next_eip_addend)
         int code64;
 
         ECX = env->eip + next_eip_addend;
-        env->regs[11] = compute_eflags();
+        env->regs[11] = cpu_compute_eflags(env);
 
         code64 = env->hflags & HF_CS64_MASK;
 
@@ -1156,7 +1157,7 @@ void helper_syscall(int next_eip_addend)
                                DESC_S_MASK |
                                DESC_W_MASK | DESC_A_MASK);
         env->eflags &= ~env->fmask;
-        load_eflags(env->eflags, 0);
+        cpu_load_eflags(env, env->eflags, 0);
         if (code64) {
             env->eip = env->lstar;
         } else {
@@ -1218,8 +1219,9 @@ void helper_sysret(int dflag)
                                DESC_G_MASK | DESC_B_MASK | DESC_P_MASK |
                                DESC_S_MASK | (3 << DESC_DPL_SHIFT) |
                                DESC_W_MASK | DESC_A_MASK);
-        load_eflags((uint32_t)(env->regs[11]), TF_MASK | AC_MASK | ID_MASK |
-                    IF_MASK | IOPL_MASK | VM_MASK | RF_MASK | NT_MASK);
+        cpu_load_eflags(env, (uint32_t)(env->regs[11]), TF_MASK | AC_MASK
+                        | ID_MASK | IF_MASK | IOPL_MASK | VM_MASK | RF_MASK |
+                        NT_MASK);
         cpu_x86_set_cpl(env, 3);
     } else {
         cpu_x86_load_seg_cache(env, R_CS, selector | 3,
@@ -1266,7 +1268,7 @@ static void do_interrupt_real(int intno, int is_int, int error_code,
     }
     old_cs = env->segs[R_CS].selector;
     /* XXX: use SS segment size? */
-    PUSHW(ssp, esp, 0xffff, compute_eflags());
+    PUSHW(ssp, esp, 0xffff, cpu_compute_eflags(env));
     PUSHW(ssp, esp, 0xffff, old_cs);
     PUSHW(ssp, esp, 0xffff, old_eip);
 
@@ -1536,7 +1538,7 @@ void do_smm_enter(CPUX86State *env1)
         stq_phys(sm_state + 0x7ff8 - i * 8, env->regs[i]);
     }
     stq_phys(sm_state + 0x7f78, env->eip);
-    stl_phys(sm_state + 0x7f70, compute_eflags());
+    stl_phys(sm_state + 0x7f70, cpu_compute_eflags(env));
     stl_phys(sm_state + 0x7f68, env->dr[6]);
     stl_phys(sm_state + 0x7f60, env->dr[7]);
 
@@ -1549,7 +1551,7 @@ void do_smm_enter(CPUX86State *env1)
 #else
     stl_phys(sm_state + 0x7ffc, env->cr[0]);
     stl_phys(sm_state + 0x7ff8, env->cr[3]);
-    stl_phys(sm_state + 0x7ff4, compute_eflags());
+    stl_phys(sm_state + 0x7ff4, cpu_compute_eflags(env));
     stl_phys(sm_state + 0x7ff0, env->eip);
     stl_phys(sm_state + 0x7fec, EDI);
     stl_phys(sm_state + 0x7fe8, ESI);
@@ -1600,7 +1602,8 @@ void do_smm_enter(CPUX86State *env1)
 #ifdef TARGET_X86_64
     cpu_load_efer(env, 0);
 #endif
-    load_eflags(0, ~(CC_O | CC_S | CC_Z | CC_A | CC_P | CC_C | DF_MASK));
+    cpu_load_eflags(env, 0, ~(CC_O | CC_S | CC_Z | CC_A | CC_P | CC_C |
+                              DF_MASK));
     env->eip = 0x00008000;
     cpu_x86_load_seg_cache(env, R_CS, (env->smbase >> 4) & 0xffff, env->smbase,
                            0xffffffff, 0);
@@ -1667,8 +1670,8 @@ void helper_rsm(void)
         env->regs[i] = ldq_phys(sm_state + 0x7ff8 - i * 8);
     }
     env->eip = ldq_phys(sm_state + 0x7f78);
-    load_eflags(ldl_phys(sm_state + 0x7f70),
-                ~(CC_O | CC_S | CC_Z | CC_A | CC_P | CC_C | DF_MASK));
+    cpu_load_eflags(env, ldl_phys(sm_state + 0x7f70),
+                    ~(CC_O | CC_S | CC_Z | CC_A | CC_P | CC_C | DF_MASK));
     env->dr[6] = ldl_phys(sm_state + 0x7f68);
     env->dr[7] = ldl_phys(sm_state + 0x7f60);
 
@@ -1683,8 +1686,8 @@ void helper_rsm(void)
 #else
     cpu_x86_update_cr0(env, ldl_phys(sm_state + 0x7ffc));
     cpu_x86_update_cr3(env, ldl_phys(sm_state + 0x7ff8));
-    load_eflags(ldl_phys(sm_state + 0x7ff4),
-                ~(CC_O | CC_S | CC_Z | CC_A | CC_P | CC_C | DF_MASK));
+    cpu_load_eflags(env, ldl_phys(sm_state + 0x7ff4),
+                    ~(CC_O | CC_S | CC_Z | CC_A | CC_P | CC_C | DF_MASK));
     env->eip = ldl_phys(sm_state + 0x7ff0);
     EDI = ldl_phys(sm_state + 0x7fec);
     ESI = ldl_phys(sm_state + 0x7fe8);
@@ -2731,7 +2734,7 @@ void helper_iret_real(int shift)
     if (shift == 0) {
         eflags_mask &= 0xffff;
     }
-    load_eflags(new_eflags, eflags_mask);
+    cpu_load_eflags(env, new_eflags, eflags_mask);
     env->hflags2 &= ~HF2_NMI_MASK;
 }
 
@@ -2951,7 +2954,7 @@ static inline void helper_ret_protected(int shift, int is_iret, int addend)
         if (shift == 0) {
             eflags_mask &= 0xffff;
         }
-        load_eflags(new_eflags, eflags_mask);
+        cpu_load_eflags(env, new_eflags, eflags_mask);
     }
     return;
 
@@ -2964,8 +2967,9 @@ static inline void helper_ret_protected(int shift, int is_iret, int addend)
     POPL(ssp, sp, sp_mask, new_gs);
 
     /* modify processor state */
-    load_eflags(new_eflags, TF_MASK | AC_MASK | ID_MASK |
-                IF_MASK | IOPL_MASK | VM_MASK | NT_MASK | VIF_MASK | VIP_MASK);
+    cpu_load_eflags(env, new_eflags, TF_MASK | AC_MASK | ID_MASK |
+                    IF_MASK | IOPL_MASK | VM_MASK | NT_MASK | VIF_MASK |
+                    VIP_MASK);
     load_seg_vm(R_CS, new_cs & 0xffff);
     cpu_x86_set_cpl(env, 3);
     load_seg_vm(R_SS, new_ss & 0xffff);
@@ -4153,7 +4157,7 @@ void helper_vmrun(int aflag, int next_eip_addend)
 
     stq_phys(env->vm_hsave + offsetof(struct vmcb, save.efer), env->efer);
     stq_phys(env->vm_hsave + offsetof(struct vmcb, save.rflags),
-             compute_eflags());
+             cpu_compute_eflags(env));
 
     svm_save_seg(env->vm_hsave + offsetof(struct vmcb, save.es),
                  &env->segs[R_ES]);
@@ -4229,8 +4233,9 @@ void helper_vmrun(int aflag, int next_eip_addend)
     cpu_load_efer(env,
                   ldq_phys(env->vm_vmcb + offsetof(struct vmcb, save.efer)));
     env->eflags = 0;
-    load_eflags(ldq_phys(env->vm_vmcb + offsetof(struct vmcb, save.rflags)),
-                ~(CC_O | CC_S | CC_Z | CC_A | CC_P | CC_C | DF_MASK));
+    cpu_load_eflags(env, ldq_phys(env->vm_vmcb + offsetof(struct vmcb,
+                                                          save.rflags)),
+                    ~(CC_O | CC_S | CC_Z | CC_A | CC_P | CC_C | DF_MASK));
     CC_OP = CC_OP_EFLAGS;
 
     svm_load_seg_cache(env->vm_vmcb + offsetof(struct vmcb, save.es),
@@ -4601,7 +4606,7 @@ void helper_vmexit(uint32_t exit_code, uint64_t exit_info_1)
     stl_phys(env->vm_vmcb + offsetof(struct vmcb, control.int_ctl), int_ctl);
 
     stq_phys(env->vm_vmcb + offsetof(struct vmcb, save.rflags),
-             compute_eflags());
+             cpu_compute_eflags(env));
     stq_phys(env->vm_vmcb + offsetof(struct vmcb, save.rip), env->eip);
     stq_phys(env->vm_vmcb + offsetof(struct vmcb, save.rsp), ESP);
     stq_phys(env->vm_vmcb + offsetof(struct vmcb, save.rax), EAX);
@@ -4640,8 +4645,9 @@ void helper_vmexit(uint32_t exit_code, uint64_t exit_info_1)
     cpu_load_efer(env, ldq_phys(env->vm_hsave + offsetof(struct vmcb,
                                                          save.efer)));
     env->eflags = 0;
-    load_eflags(ldq_phys(env->vm_hsave + offsetof(struct vmcb, save.rflags)),
-                ~(CC_O | CC_S | CC_Z | CC_A | CC_P | CC_C | DF_MASK));
+    cpu_load_eflags(env, ldq_phys(env->vm_hsave + offsetof(struct vmcb,
+                                                           save.rflags)),
+                    ~(CC_O | CC_S | CC_Z | CC_A | CC_P | CC_C | DF_MASK));
     CC_OP = CC_OP_EFLAGS;
 
     svm_load_seg_cache(env->vm_hsave + offsetof(struct vmcb, save.es),
commit 38de4c46f2560c08a113c65bd6186ac31f1869dd
Author: Blue Swirl <blauwirbel at gmail.com>
Date:   Sat May 12 20:39:26 2012 +0000

    x86: split condition code and shift templates
    
    Move shift templates from helper_template.h to
    shift_helper_template.h and the condition code helpers
    to cc_helper_template.h.
    
    Signed-off-by: Blue Swirl <blauwirbel at gmail.com>

diff --git a/target-i386/cc_helper_template.h b/target-i386/cc_helper_template.h
new file mode 100644
index 0000000..ff22830
--- /dev/null
+++ b/target-i386/cc_helper_template.h
@@ -0,0 +1,277 @@
+/*
+ *  x86 condition code helpers
+ *
+ *  Copyright (c) 2008 Fabrice Bellard
+ *
+ * This library is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Lesser General Public
+ * License as published by the Free Software Foundation; either
+ * version 2 of the License, or (at your option) any later version.
+ *
+ * This library is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
+ * Lesser General Public License for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public
+ * License along with this library; if not, see <http://www.gnu.org/licenses/>.
+ */
+
+#define DATA_BITS (1 << (3 + SHIFT))
+#define SIGN_MASK (((target_ulong)1) << (DATA_BITS - 1))
+
+#if DATA_BITS == 8
+#define SUFFIX b
+#define DATA_TYPE uint8_t
+#define DATA_MASK 0xff
+#elif DATA_BITS == 16
+#define SUFFIX w
+#define DATA_TYPE uint16_t
+#define DATA_MASK 0xffff
+#elif DATA_BITS == 32
+#define SUFFIX l
+#define DATA_TYPE uint32_t
+#define DATA_MASK 0xffffffff
+#elif DATA_BITS == 64
+#define SUFFIX q
+#define DATA_TYPE uint64_t
+#define DATA_MASK 0xffffffffffffffffULL
+#else
+#error unhandled operand size
+#endif
+
+/* dynamic flags computation */
+
+static int glue(compute_all_add, SUFFIX)(void)
+{
+    int cf, pf, af, zf, sf, of;
+    target_long src1, src2;
+
+    src1 = CC_SRC;
+    src2 = CC_DST - CC_SRC;
+    cf = (DATA_TYPE)CC_DST < (DATA_TYPE)src1;
+    pf = parity_table[(uint8_t)CC_DST];
+    af = (CC_DST ^ src1 ^ src2) & 0x10;
+    zf = ((DATA_TYPE)CC_DST == 0) << 6;
+    sf = lshift(CC_DST, 8 - DATA_BITS) & 0x80;
+    of = lshift((src1 ^ src2 ^ -1) & (src1 ^ CC_DST), 12 - DATA_BITS) & CC_O;
+    return cf | pf | af | zf | sf | of;
+}
+
+static int glue(compute_c_add, SUFFIX)(void)
+{
+    int cf;
+    target_long src1;
+
+    src1 = CC_SRC;
+    cf = (DATA_TYPE)CC_DST < (DATA_TYPE)src1;
+    return cf;
+}
+
+static int glue(compute_all_adc, SUFFIX)(void)
+{
+    int cf, pf, af, zf, sf, of;
+    target_long src1, src2;
+
+    src1 = CC_SRC;
+    src2 = CC_DST - CC_SRC - 1;
+    cf = (DATA_TYPE)CC_DST <= (DATA_TYPE)src1;
+    pf = parity_table[(uint8_t)CC_DST];
+    af = (CC_DST ^ src1 ^ src2) & 0x10;
+    zf = ((DATA_TYPE)CC_DST == 0) << 6;
+    sf = lshift(CC_DST, 8 - DATA_BITS) & 0x80;
+    of = lshift((src1 ^ src2 ^ -1) & (src1 ^ CC_DST), 12 - DATA_BITS) & CC_O;
+    return cf | pf | af | zf | sf | of;
+}
+
+static int glue(compute_c_adc, SUFFIX)(void)
+{
+    int cf;
+    target_long src1;
+
+    src1 = CC_SRC;
+    cf = (DATA_TYPE)CC_DST <= (DATA_TYPE)src1;
+    return cf;
+}
+
+static int glue(compute_all_sub, SUFFIX)(void)
+{
+    int cf, pf, af, zf, sf, of;
+    target_long src1, src2;
+
+    src1 = CC_DST + CC_SRC;
+    src2 = CC_SRC;
+    cf = (DATA_TYPE)src1 < (DATA_TYPE)src2;
+    pf = parity_table[(uint8_t)CC_DST];
+    af = (CC_DST ^ src1 ^ src2) & 0x10;
+    zf = ((DATA_TYPE)CC_DST == 0) << 6;
+    sf = lshift(CC_DST, 8 - DATA_BITS) & 0x80;
+    of = lshift((src1 ^ src2) & (src1 ^ CC_DST), 12 - DATA_BITS) & CC_O;
+    return cf | pf | af | zf | sf | of;
+}
+
+static int glue(compute_c_sub, SUFFIX)(void)
+{
+    int cf;
+    target_long src1, src2;
+
+    src1 = CC_DST + CC_SRC;
+    src2 = CC_SRC;
+    cf = (DATA_TYPE)src1 < (DATA_TYPE)src2;
+    return cf;
+}
+
+static int glue(compute_all_sbb, SUFFIX)(void)
+{
+    int cf, pf, af, zf, sf, of;
+    target_long src1, src2;
+
+    src1 = CC_DST + CC_SRC + 1;
+    src2 = CC_SRC;
+    cf = (DATA_TYPE)src1 <= (DATA_TYPE)src2;
+    pf = parity_table[(uint8_t)CC_DST];
+    af = (CC_DST ^ src1 ^ src2) & 0x10;
+    zf = ((DATA_TYPE)CC_DST == 0) << 6;
+    sf = lshift(CC_DST, 8 - DATA_BITS) & 0x80;
+    of = lshift((src1 ^ src2) & (src1 ^ CC_DST), 12 - DATA_BITS) & CC_O;
+    return cf | pf | af | zf | sf | of;
+}
+
+static int glue(compute_c_sbb, SUFFIX)(void)
+{
+    int cf;
+    target_long src1, src2;
+
+    src1 = CC_DST + CC_SRC + 1;
+    src2 = CC_SRC;
+    cf = (DATA_TYPE)src1 <= (DATA_TYPE)src2;
+    return cf;
+}
+
+static int glue(compute_all_logic, SUFFIX)(void)
+{
+    int cf, pf, af, zf, sf, of;
+
+    cf = 0;
+    pf = parity_table[(uint8_t)CC_DST];
+    af = 0;
+    zf = ((DATA_TYPE)CC_DST == 0) << 6;
+    sf = lshift(CC_DST, 8 - DATA_BITS) & 0x80;
+    of = 0;
+    return cf | pf | af | zf | sf | of;
+}
+
+static int glue(compute_c_logic, SUFFIX)(void)
+{
+    return 0;
+}
+
+static int glue(compute_all_inc, SUFFIX)(void)
+{
+    int cf, pf, af, zf, sf, of;
+    target_long src1, src2;
+
+    src1 = CC_DST - 1;
+    src2 = 1;
+    cf = CC_SRC;
+    pf = parity_table[(uint8_t)CC_DST];
+    af = (CC_DST ^ src1 ^ src2) & 0x10;
+    zf = ((DATA_TYPE)CC_DST == 0) << 6;
+    sf = lshift(CC_DST, 8 - DATA_BITS) & 0x80;
+    of = ((CC_DST & DATA_MASK) == SIGN_MASK) << 11;
+    return cf | pf | af | zf | sf | of;
+}
+
+#if DATA_BITS == 32
+static int glue(compute_c_inc, SUFFIX)(void)
+{
+    return CC_SRC;
+}
+#endif
+
+static int glue(compute_all_dec, SUFFIX)(void)
+{
+    int cf, pf, af, zf, sf, of;
+    target_long src1, src2;
+
+    src1 = CC_DST + 1;
+    src2 = 1;
+    cf = CC_SRC;
+    pf = parity_table[(uint8_t)CC_DST];
+    af = (CC_DST ^ src1 ^ src2) & 0x10;
+    zf = ((DATA_TYPE)CC_DST == 0) << 6;
+    sf = lshift(CC_DST, 8 - DATA_BITS) & 0x80;
+    of = ((CC_DST & DATA_MASK) == ((target_ulong)SIGN_MASK - 1)) << 11;
+    return cf | pf | af | zf | sf | of;
+}
+
+static int glue(compute_all_shl, SUFFIX)(void)
+{
+    int cf, pf, af, zf, sf, of;
+
+    cf = (CC_SRC >> (DATA_BITS - 1)) & CC_C;
+    pf = parity_table[(uint8_t)CC_DST];
+    af = 0; /* undefined */
+    zf = ((DATA_TYPE)CC_DST == 0) << 6;
+    sf = lshift(CC_DST, 8 - DATA_BITS) & 0x80;
+    /* of is defined if shift count == 1 */
+    of = lshift(CC_SRC ^ CC_DST, 12 - DATA_BITS) & CC_O;
+    return cf | pf | af | zf | sf | of;
+}
+
+static int glue(compute_c_shl, SUFFIX)(void)
+{
+    return (CC_SRC >> (DATA_BITS - 1)) & CC_C;
+}
+
+#if DATA_BITS == 32
+static int glue(compute_c_sar, SUFFIX)(void)
+{
+    return CC_SRC & 1;
+}
+#endif
+
+static int glue(compute_all_sar, SUFFIX)(void)
+{
+    int cf, pf, af, zf, sf, of;
+
+    cf = CC_SRC & 1;
+    pf = parity_table[(uint8_t)CC_DST];
+    af = 0; /* undefined */
+    zf = ((DATA_TYPE)CC_DST == 0) << 6;
+    sf = lshift(CC_DST, 8 - DATA_BITS) & 0x80;
+    /* of is defined if shift count == 1 */
+    of = lshift(CC_SRC ^ CC_DST, 12 - DATA_BITS) & CC_O;
+    return cf | pf | af | zf | sf | of;
+}
+
+#if DATA_BITS == 32
+static int glue(compute_c_mul, SUFFIX)(void)
+{
+    int cf;
+
+    cf = (CC_SRC != 0);
+    return cf;
+}
+#endif
+
+/* NOTE: we compute the flags like the P4. On olders CPUs, only OF and
+   CF are modified and it is slower to do that. */
+static int glue(compute_all_mul, SUFFIX)(void)
+{
+    int cf, pf, af, zf, sf, of;
+
+    cf = (CC_SRC != 0);
+    pf = parity_table[(uint8_t)CC_DST];
+    af = 0; /* undefined */
+    zf = ((DATA_TYPE)CC_DST == 0) << 6;
+    sf = lshift(CC_DST, 8 - DATA_BITS) & 0x80;
+    of = cf << 11;
+    return cf | pf | af | zf | sf | of;
+}
+
+#undef DATA_BITS
+#undef SIGN_MASK
+#undef DATA_TYPE
+#undef DATA_MASK
+#undef SUFFIX
diff --git a/target-i386/helper_template.h b/target-i386/helper_template.h
deleted file mode 100644
index 8b2d4f0..0000000
--- a/target-i386/helper_template.h
+++ /dev/null
@@ -1,353 +0,0 @@
-/*
- *  i386 helpers
- *
- *  Copyright (c) 2008 Fabrice Bellard
- *
- * This library is free software; you can redistribute it and/or
- * modify it under the terms of the GNU Lesser General Public
- * License as published by the Free Software Foundation; either
- * version 2 of the License, or (at your option) any later version.
- *
- * This library is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
- * Lesser General Public License for more details.
- *
- * You should have received a copy of the GNU Lesser General Public
- * License along with this library; if not, see <http://www.gnu.org/licenses/>.
- */
-
-#define DATA_BITS (1 << (3 + SHIFT))
-#define SHIFT_MASK (DATA_BITS - 1)
-#define SIGN_MASK (((target_ulong)1) << (DATA_BITS - 1))
-#if DATA_BITS <= 32
-#define SHIFT1_MASK 0x1f
-#else
-#define SHIFT1_MASK 0x3f
-#endif
-
-#if DATA_BITS == 8
-#define SUFFIX b
-#define DATA_TYPE uint8_t
-#define DATA_STYPE int8_t
-#define DATA_MASK 0xff
-#elif DATA_BITS == 16
-#define SUFFIX w
-#define DATA_TYPE uint16_t
-#define DATA_STYPE int16_t
-#define DATA_MASK 0xffff
-#elif DATA_BITS == 32
-#define SUFFIX l
-#define DATA_TYPE uint32_t
-#define DATA_STYPE int32_t
-#define DATA_MASK 0xffffffff
-#elif DATA_BITS == 64
-#define SUFFIX q
-#define DATA_TYPE uint64_t
-#define DATA_STYPE int64_t
-#define DATA_MASK 0xffffffffffffffffULL
-#else
-#error unhandled operand size
-#endif
-
-/* dynamic flags computation */
-
-static int glue(compute_all_add, SUFFIX)(void)
-{
-    int cf, pf, af, zf, sf, of;
-    target_long src1, src2;
-
-    src1 = CC_SRC;
-    src2 = CC_DST - CC_SRC;
-    cf = (DATA_TYPE)CC_DST < (DATA_TYPE)src1;
-    pf = parity_table[(uint8_t)CC_DST];
-    af = (CC_DST ^ src1 ^ src2) & 0x10;
-    zf = ((DATA_TYPE)CC_DST == 0) << 6;
-    sf = lshift(CC_DST, 8 - DATA_BITS) & 0x80;
-    of = lshift((src1 ^ src2 ^ -1) & (src1 ^ CC_DST), 12 - DATA_BITS) & CC_O;
-    return cf | pf | af | zf | sf | of;
-}
-
-static int glue(compute_c_add, SUFFIX)(void)
-{
-    int cf;
-    target_long src1;
-
-    src1 = CC_SRC;
-    cf = (DATA_TYPE)CC_DST < (DATA_TYPE)src1;
-    return cf;
-}
-
-static int glue(compute_all_adc, SUFFIX)(void)
-{
-    int cf, pf, af, zf, sf, of;
-    target_long src1, src2;
-
-    src1 = CC_SRC;
-    src2 = CC_DST - CC_SRC - 1;
-    cf = (DATA_TYPE)CC_DST <= (DATA_TYPE)src1;
-    pf = parity_table[(uint8_t)CC_DST];
-    af = (CC_DST ^ src1 ^ src2) & 0x10;
-    zf = ((DATA_TYPE)CC_DST == 0) << 6;
-    sf = lshift(CC_DST, 8 - DATA_BITS) & 0x80;
-    of = lshift((src1 ^ src2 ^ -1) & (src1 ^ CC_DST), 12 - DATA_BITS) & CC_O;
-    return cf | pf | af | zf | sf | of;
-}
-
-static int glue(compute_c_adc, SUFFIX)(void)
-{
-    int cf;
-    target_long src1;
-
-    src1 = CC_SRC;
-    cf = (DATA_TYPE)CC_DST <= (DATA_TYPE)src1;
-    return cf;
-}
-
-static int glue(compute_all_sub, SUFFIX)(void)
-{
-    int cf, pf, af, zf, sf, of;
-    target_long src1, src2;
-
-    src1 = CC_DST + CC_SRC;
-    src2 = CC_SRC;
-    cf = (DATA_TYPE)src1 < (DATA_TYPE)src2;
-    pf = parity_table[(uint8_t)CC_DST];
-    af = (CC_DST ^ src1 ^ src2) & 0x10;
-    zf = ((DATA_TYPE)CC_DST == 0) << 6;
-    sf = lshift(CC_DST, 8 - DATA_BITS) & 0x80;
-    of = lshift((src1 ^ src2) & (src1 ^ CC_DST), 12 - DATA_BITS) & CC_O;
-    return cf | pf | af | zf | sf | of;
-}
-
-static int glue(compute_c_sub, SUFFIX)(void)
-{
-    int cf;
-    target_long src1, src2;
-
-    src1 = CC_DST + CC_SRC;
-    src2 = CC_SRC;
-    cf = (DATA_TYPE)src1 < (DATA_TYPE)src2;
-    return cf;
-}
-
-static int glue(compute_all_sbb, SUFFIX)(void)
-{
-    int cf, pf, af, zf, sf, of;
-    target_long src1, src2;
-
-    src1 = CC_DST + CC_SRC + 1;
-    src2 = CC_SRC;
-    cf = (DATA_TYPE)src1 <= (DATA_TYPE)src2;
-    pf = parity_table[(uint8_t)CC_DST];
-    af = (CC_DST ^ src1 ^ src2) & 0x10;
-    zf = ((DATA_TYPE)CC_DST == 0) << 6;
-    sf = lshift(CC_DST, 8 - DATA_BITS) & 0x80;
-    of = lshift((src1 ^ src2) & (src1 ^ CC_DST), 12 - DATA_BITS) & CC_O;
-    return cf | pf | af | zf | sf | of;
-}
-
-static int glue(compute_c_sbb, SUFFIX)(void)
-{
-    int cf;
-    target_long src1, src2;
-
-    src1 = CC_DST + CC_SRC + 1;
-    src2 = CC_SRC;
-    cf = (DATA_TYPE)src1 <= (DATA_TYPE)src2;
-    return cf;
-}
-
-static int glue(compute_all_logic, SUFFIX)(void)
-{
-    int cf, pf, af, zf, sf, of;
-
-    cf = 0;
-    pf = parity_table[(uint8_t)CC_DST];
-    af = 0;
-    zf = ((DATA_TYPE)CC_DST == 0) << 6;
-    sf = lshift(CC_DST, 8 - DATA_BITS) & 0x80;
-    of = 0;
-    return cf | pf | af | zf | sf | of;
-}
-
-static int glue(compute_c_logic, SUFFIX)(void)
-{
-    return 0;
-}
-
-static int glue(compute_all_inc, SUFFIX)(void)
-{
-    int cf, pf, af, zf, sf, of;
-    target_long src1, src2;
-
-    src1 = CC_DST - 1;
-    src2 = 1;
-    cf = CC_SRC;
-    pf = parity_table[(uint8_t)CC_DST];
-    af = (CC_DST ^ src1 ^ src2) & 0x10;
-    zf = ((DATA_TYPE)CC_DST == 0) << 6;
-    sf = lshift(CC_DST, 8 - DATA_BITS) & 0x80;
-    of = ((CC_DST & DATA_MASK) == SIGN_MASK) << 11;
-    return cf | pf | af | zf | sf | of;
-}
-
-#if DATA_BITS == 32
-static int glue(compute_c_inc, SUFFIX)(void)
-{
-    return CC_SRC;
-}
-#endif
-
-static int glue(compute_all_dec, SUFFIX)(void)
-{
-    int cf, pf, af, zf, sf, of;
-    target_long src1, src2;
-
-    src1 = CC_DST + 1;
-    src2 = 1;
-    cf = CC_SRC;
-    pf = parity_table[(uint8_t)CC_DST];
-    af = (CC_DST ^ src1 ^ src2) & 0x10;
-    zf = ((DATA_TYPE)CC_DST == 0) << 6;
-    sf = lshift(CC_DST, 8 - DATA_BITS) & 0x80;
-    of = ((CC_DST & DATA_MASK) == ((target_ulong)SIGN_MASK - 1)) << 11;
-    return cf | pf | af | zf | sf | of;
-}
-
-static int glue(compute_all_shl, SUFFIX)(void)
-{
-    int cf, pf, af, zf, sf, of;
-
-    cf = (CC_SRC >> (DATA_BITS - 1)) & CC_C;
-    pf = parity_table[(uint8_t)CC_DST];
-    af = 0; /* undefined */
-    zf = ((DATA_TYPE)CC_DST == 0) << 6;
-    sf = lshift(CC_DST, 8 - DATA_BITS) & 0x80;
-    /* of is defined if shift count == 1 */
-    of = lshift(CC_SRC ^ CC_DST, 12 - DATA_BITS) & CC_O;
-    return cf | pf | af | zf | sf | of;
-}
-
-static int glue(compute_c_shl, SUFFIX)(void)
-{
-    return (CC_SRC >> (DATA_BITS - 1)) & CC_C;
-}
-
-#if DATA_BITS == 32
-static int glue(compute_c_sar, SUFFIX)(void)
-{
-    return CC_SRC & 1;
-}
-#endif
-
-static int glue(compute_all_sar, SUFFIX)(void)
-{
-    int cf, pf, af, zf, sf, of;
-
-    cf = CC_SRC & 1;
-    pf = parity_table[(uint8_t)CC_DST];
-    af = 0; /* undefined */
-    zf = ((DATA_TYPE)CC_DST == 0) << 6;
-    sf = lshift(CC_DST, 8 - DATA_BITS) & 0x80;
-    /* of is defined if shift count == 1 */
-    of = lshift(CC_SRC ^ CC_DST, 12 - DATA_BITS) & CC_O;
-    return cf | pf | af | zf | sf | of;
-}
-
-#if DATA_BITS == 32
-static int glue(compute_c_mul, SUFFIX)(void)
-{
-    int cf;
-
-    cf = (CC_SRC != 0);
-    return cf;
-}
-#endif
-
-/* NOTE: we compute the flags like the P4. On olders CPUs, only OF and
-   CF are modified and it is slower to do that. */
-static int glue(compute_all_mul, SUFFIX)(void)
-{
-    int cf, pf, af, zf, sf, of;
-
-    cf = (CC_SRC != 0);
-    pf = parity_table[(uint8_t)CC_DST];
-    af = 0; /* undefined */
-    zf = ((DATA_TYPE)CC_DST == 0) << 6;
-    sf = lshift(CC_DST, 8 - DATA_BITS) & 0x80;
-    of = cf << 11;
-    return cf | pf | af | zf | sf | of;
-}
-
-/* shifts */
-
-target_ulong glue(helper_rcl, SUFFIX)(target_ulong t0, target_ulong t1)
-{
-    int count, eflags;
-    target_ulong src;
-    target_long res;
-
-    count = t1 & SHIFT1_MASK;
-#if DATA_BITS == 16
-    count = rclw_table[count];
-#elif DATA_BITS == 8
-    count = rclb_table[count];
-#endif
-    if (count) {
-        eflags = helper_cc_compute_all(CC_OP);
-        t0 &= DATA_MASK;
-        src = t0;
-        res = (t0 << count) | ((target_ulong)(eflags & CC_C) << (count - 1));
-        if (count > 1) {
-            res |= t0 >> (DATA_BITS + 1 - count);
-        }
-        t0 = res;
-        env->cc_tmp = (eflags & ~(CC_C | CC_O)) |
-            (lshift(src ^ t0, 11 - (DATA_BITS - 1)) & CC_O) |
-            ((src >> (DATA_BITS - count)) & CC_C);
-    } else {
-        env->cc_tmp = -1;
-    }
-    return t0;
-}
-
-target_ulong glue(helper_rcr, SUFFIX)(target_ulong t0, target_ulong t1)
-{
-    int count, eflags;
-    target_ulong src;
-    target_long res;
-
-    count = t1 & SHIFT1_MASK;
-#if DATA_BITS == 16
-    count = rclw_table[count];
-#elif DATA_BITS == 8
-    count = rclb_table[count];
-#endif
-    if (count) {
-        eflags = helper_cc_compute_all(CC_OP);
-        t0 &= DATA_MASK;
-        src = t0;
-        res = (t0 >> count) |
-            ((target_ulong)(eflags & CC_C) << (DATA_BITS - count));
-        if (count > 1) {
-            res |= t0 << (DATA_BITS + 1 - count);
-        }
-        t0 = res;
-        env->cc_tmp = (eflags & ~(CC_C | CC_O)) |
-            (lshift(src ^ t0, 11 - (DATA_BITS - 1)) & CC_O) |
-            ((src >> (count - 1)) & CC_C);
-    } else {
-        env->cc_tmp = -1;
-    }
-    return t0;
-}
-
-#undef DATA_BITS
-#undef SHIFT_MASK
-#undef SHIFT1_MASK
-#undef SIGN_MASK
-#undef DATA_TYPE
-#undef DATA_STYPE
-#undef DATA_MASK
-#undef SUFFIX
diff --git a/target-i386/op_helper.c b/target-i386/op_helper.c
index 3b77972..d791e38 100644
--- a/target-i386/op_helper.c
+++ b/target-i386/op_helper.c
@@ -4715,25 +4715,43 @@ void cpu_vmexit(CPUX86State *nenv, uint32_t exit_code, uint64_t exit_info_1)
 #endif
 
 #define SHIFT 0
-#include "helper_template.h"
+#include "cc_helper_template.h"
 #undef SHIFT
 
 #define SHIFT 1
-#include "helper_template.h"
+#include "cc_helper_template.h"
 #undef SHIFT
 
 #define SHIFT 2
-#include "helper_template.h"
+#include "cc_helper_template.h"
 #undef SHIFT
 
 #ifdef TARGET_X86_64
 
 #define SHIFT 3
-#include "helper_template.h"
+#include "cc_helper_template.h"
 #undef SHIFT
 
 #endif
 
+#define SHIFT 0
+#include "shift_helper_template.h"
+#undef SHIFT
+
+#define SHIFT 1
+#include "shift_helper_template.h"
+#undef SHIFT
+
+#define SHIFT 2
+#include "shift_helper_template.h"
+#undef SHIFT
+
+#ifdef TARGET_X86_64
+#define SHIFT 3
+#include "shift_helper_template.h"
+#undef SHIFT
+#endif
+
 /* bit operations */
 target_ulong helper_bsf(target_ulong t0)
 {
diff --git a/target-i386/shift_helper_template.h b/target-i386/shift_helper_template.h
new file mode 100644
index 0000000..239ee09
--- /dev/null
+++ b/target-i386/shift_helper_template.h
@@ -0,0 +1,110 @@
+/*
+ *  x86 shift helpers
+ *
+ *  Copyright (c) 2008 Fabrice Bellard
+ *
+ * This library is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Lesser General Public
+ * License as published by the Free Software Foundation; either
+ * version 2 of the License, or (at your option) any later version.
+ *
+ * This library is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
+ * Lesser General Public License for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public
+ * License along with this library; if not, see <http://www.gnu.org/licenses/>.
+ */
+
+#define DATA_BITS (1 << (3 + SHIFT))
+#define SHIFT_MASK (DATA_BITS - 1)
+#if DATA_BITS <= 32
+#define SHIFT1_MASK 0x1f
+#else
+#define SHIFT1_MASK 0x3f
+#endif
+
+#if DATA_BITS == 8
+#define SUFFIX b
+#define DATA_MASK 0xff
+#elif DATA_BITS == 16
+#define SUFFIX w
+#define DATA_MASK 0xffff
+#elif DATA_BITS == 32
+#define SUFFIX l
+#define DATA_MASK 0xffffffff
+#elif DATA_BITS == 64
+#define SUFFIX q
+#define DATA_MASK 0xffffffffffffffffULL
+#else
+#error unhandled operand size
+#endif
+
+target_ulong glue(helper_rcl, SUFFIX)(target_ulong t0, target_ulong t1)
+{
+    int count, eflags;
+    target_ulong src;
+    target_long res;
+
+    count = t1 & SHIFT1_MASK;
+#if DATA_BITS == 16
+    count = rclw_table[count];
+#elif DATA_BITS == 8
+    count = rclb_table[count];
+#endif
+    if (count) {
+        eflags = helper_cc_compute_all(CC_OP);
+        t0 &= DATA_MASK;
+        src = t0;
+        res = (t0 << count) | ((target_ulong)(eflags & CC_C) << (count - 1));
+        if (count > 1) {
+            res |= t0 >> (DATA_BITS + 1 - count);
+        }
+        t0 = res;
+        env->cc_tmp = (eflags & ~(CC_C | CC_O)) |
+            (lshift(src ^ t0, 11 - (DATA_BITS - 1)) & CC_O) |
+            ((src >> (DATA_BITS - count)) & CC_C);
+    } else {
+        env->cc_tmp = -1;
+    }
+    return t0;
+}
+
+target_ulong glue(helper_rcr, SUFFIX)(target_ulong t0, target_ulong t1)
+{
+    int count, eflags;
+    target_ulong src;
+    target_long res;
+
+    count = t1 & SHIFT1_MASK;
+#if DATA_BITS == 16
+    count = rclw_table[count];
+#elif DATA_BITS == 8
+    count = rclb_table[count];
+#endif
+    if (count) {
+        eflags = helper_cc_compute_all(CC_OP);
+        t0 &= DATA_MASK;
+        src = t0;
+        res = (t0 >> count) |
+            ((target_ulong)(eflags & CC_C) << (DATA_BITS - count));
+        if (count > 1) {
+            res |= t0 << (DATA_BITS + 1 - count);
+        }
+        t0 = res;
+        env->cc_tmp = (eflags & ~(CC_C | CC_O)) |
+            (lshift(src ^ t0, 11 - (DATA_BITS - 1)) & CC_O) |
+            ((src >> (count - 1)) & CC_C);
+    } else {
+        env->cc_tmp = -1;
+    }
+    return t0;
+}
+
+#undef DATA_BITS
+#undef SHIFT_MASK
+#undef SHIFT1_MASK
+#undef DATA_TYPE
+#undef DATA_MASK
+#undef SUFFIX
commit a04759f6ae5a4fd496917dabbdff0d552bda730a
Author: Blue Swirl <blauwirbel at gmail.com>
Date:   Sun Apr 29 12:27:33 2012 +0000

    x86: fix coding style in helper_template.h
    
    Fix coding style in helper_template.h before next commit.
    
    Signed-off-by: Blue Swirl <blauwirbel at gmail.com>

diff --git a/target-i386/helper_template.h b/target-i386/helper_template.h
index afc41fb..8b2d4f0 100644
--- a/target-i386/helper_template.h
+++ b/target-i386/helper_template.h
@@ -16,6 +16,7 @@
  * You should have received a copy of the GNU Lesser General Public
  * License along with this library; if not, see <http://www.gnu.org/licenses/>.
  */
+
 #define DATA_BITS (1 << (3 + SHIFT))
 #define SHIFT_MASK (DATA_BITS - 1)
 #define SIGN_MASK (((target_ulong)1) << (DATA_BITS - 1))
@@ -55,6 +56,7 @@ static int glue(compute_all_add, SUFFIX)(void)
 {
     int cf, pf, af, zf, sf, of;
     target_long src1, src2;
+
     src1 = CC_SRC;
     src2 = CC_DST - CC_SRC;
     cf = (DATA_TYPE)CC_DST < (DATA_TYPE)src1;
@@ -70,6 +72,7 @@ static int glue(compute_c_add, SUFFIX)(void)
 {
     int cf;
     target_long src1;
+
     src1 = CC_SRC;
     cf = (DATA_TYPE)CC_DST < (DATA_TYPE)src1;
     return cf;
@@ -79,6 +82,7 @@ static int glue(compute_all_adc, SUFFIX)(void)
 {
     int cf, pf, af, zf, sf, of;
     target_long src1, src2;
+
     src1 = CC_SRC;
     src2 = CC_DST - CC_SRC - 1;
     cf = (DATA_TYPE)CC_DST <= (DATA_TYPE)src1;
@@ -94,6 +98,7 @@ static int glue(compute_c_adc, SUFFIX)(void)
 {
     int cf;
     target_long src1;
+
     src1 = CC_SRC;
     cf = (DATA_TYPE)CC_DST <= (DATA_TYPE)src1;
     return cf;
@@ -103,6 +108,7 @@ static int glue(compute_all_sub, SUFFIX)(void)
 {
     int cf, pf, af, zf, sf, of;
     target_long src1, src2;
+
     src1 = CC_DST + CC_SRC;
     src2 = CC_SRC;
     cf = (DATA_TYPE)src1 < (DATA_TYPE)src2;
@@ -118,6 +124,7 @@ static int glue(compute_c_sub, SUFFIX)(void)
 {
     int cf;
     target_long src1, src2;
+
     src1 = CC_DST + CC_SRC;
     src2 = CC_SRC;
     cf = (DATA_TYPE)src1 < (DATA_TYPE)src2;
@@ -128,6 +135,7 @@ static int glue(compute_all_sbb, SUFFIX)(void)
 {
     int cf, pf, af, zf, sf, of;
     target_long src1, src2;
+
     src1 = CC_DST + CC_SRC + 1;
     src2 = CC_SRC;
     cf = (DATA_TYPE)src1 <= (DATA_TYPE)src2;
@@ -143,6 +151,7 @@ static int glue(compute_c_sbb, SUFFIX)(void)
 {
     int cf;
     target_long src1, src2;
+
     src1 = CC_DST + CC_SRC + 1;
     src2 = CC_SRC;
     cf = (DATA_TYPE)src1 <= (DATA_TYPE)src2;
@@ -152,6 +161,7 @@ static int glue(compute_c_sbb, SUFFIX)(void)
 static int glue(compute_all_logic, SUFFIX)(void)
 {
     int cf, pf, af, zf, sf, of;
+
     cf = 0;
     pf = parity_table[(uint8_t)CC_DST];
     af = 0;
@@ -170,6 +180,7 @@ static int glue(compute_all_inc, SUFFIX)(void)
 {
     int cf, pf, af, zf, sf, of;
     target_long src1, src2;
+
     src1 = CC_DST - 1;
     src2 = 1;
     cf = CC_SRC;
@@ -192,6 +203,7 @@ static int glue(compute_all_dec, SUFFIX)(void)
 {
     int cf, pf, af, zf, sf, of;
     target_long src1, src2;
+
     src1 = CC_DST + 1;
     src2 = 1;
     cf = CC_SRC;
@@ -206,6 +218,7 @@ static int glue(compute_all_dec, SUFFIX)(void)
 static int glue(compute_all_shl, SUFFIX)(void)
 {
     int cf, pf, af, zf, sf, of;
+
     cf = (CC_SRC >> (DATA_BITS - 1)) & CC_C;
     pf = parity_table[(uint8_t)CC_DST];
     af = 0; /* undefined */
@@ -231,6 +244,7 @@ static int glue(compute_c_sar, SUFFIX)(void)
 static int glue(compute_all_sar, SUFFIX)(void)
 {
     int cf, pf, af, zf, sf, of;
+
     cf = CC_SRC & 1;
     pf = parity_table[(uint8_t)CC_DST];
     af = 0; /* undefined */
@@ -245,6 +259,7 @@ static int glue(compute_all_sar, SUFFIX)(void)
 static int glue(compute_c_mul, SUFFIX)(void)
 {
     int cf;
+
     cf = (CC_SRC != 0);
     return cf;
 }
@@ -255,6 +270,7 @@ static int glue(compute_c_mul, SUFFIX)(void)
 static int glue(compute_all_mul, SUFFIX)(void)
 {
     int cf, pf, af, zf, sf, of;
+
     cf = (CC_SRC != 0);
     pf = parity_table[(uint8_t)CC_DST];
     af = 0; /* undefined */
@@ -283,8 +299,9 @@ target_ulong glue(helper_rcl, SUFFIX)(target_ulong t0, target_ulong t1)
         t0 &= DATA_MASK;
         src = t0;
         res = (t0 << count) | ((target_ulong)(eflags & CC_C) << (count - 1));
-        if (count > 1)
+        if (count > 1) {
             res |= t0 >> (DATA_BITS + 1 - count);
+        }
         t0 = res;
         env->cc_tmp = (eflags & ~(CC_C | CC_O)) |
             (lshift(src ^ t0, 11 - (DATA_BITS - 1)) & CC_O) |
@@ -311,9 +328,11 @@ target_ulong glue(helper_rcr, SUFFIX)(target_ulong t0, target_ulong t1)
         eflags = helper_cc_compute_all(CC_OP);
         t0 &= DATA_MASK;
         src = t0;
-        res = (t0 >> count) | ((target_ulong)(eflags & CC_C) << (DATA_BITS - count));
-        if (count > 1)
+        res = (t0 >> count) |
+            ((target_ulong)(eflags & CC_C) << (DATA_BITS - count));
+        if (count > 1) {
             res |= t0 << (DATA_BITS + 1 - count);
+        }
         t0 = res;
         env->cc_tmp = (eflags & ~(CC_C | CC_O)) |
             (lshift(src ^ t0, 11 - (DATA_BITS - 1)) & CC_O) |
commit c4baa0503d9623f1ce891f525ccd140c598bc29a
Author: Blue Swirl <blauwirbel at gmail.com>
Date:   Sun May 13 18:53:07 2012 +0000

    x86: improve SSE table type safety
    
    SSE function tables could easily be corrupted because of use
    of void pointers.
    
    Introduce function pointer types and helper variables in order
    to improve type safety.
    
    Split sse_op_table3 according to types used.
    
    Signed-off-by: Blue Swirl <blauwirbel at gmail.com>

diff --git a/target-i386/translate.c b/target-i386/translate.c
index 8ac6132..a902f4a 100644
--- a/target-i386/translate.c
+++ b/target-i386/translate.c
@@ -2786,6 +2786,14 @@ static inline void gen_op_movq_env_0(int d_offset)
     tcg_gen_st_i64(cpu_tmp1_i64, cpu_env, d_offset);
 }
 
+typedef void (*SSEFunc_i_p)(TCGv_i32 val, TCGv_ptr reg);
+typedef void (*SSEFunc_l_p)(TCGv_i64 val, TCGv_ptr reg);
+typedef void (*SSEFunc_0_pi)(TCGv_ptr reg, TCGv_i32 val);
+typedef void (*SSEFunc_0_pl)(TCGv_ptr reg, TCGv_i64 val);
+typedef void (*SSEFunc_0_pp)(TCGv_ptr reg_a, TCGv_ptr reg_b);
+typedef void (*SSEFunc_0_ppi)(TCGv_ptr reg_a, TCGv_ptr reg_b, TCGv_i32 val);
+typedef void (*SSEFunc_0_ppt)(TCGv_ptr reg_a, TCGv_ptr reg_b, TCGv val);
+
 #define SSE_SPECIAL ((void *)1)
 #define SSE_DUMMY ((void *)2)
 
@@ -2793,7 +2801,7 @@ static inline void gen_op_movq_env_0(int d_offset)
 #define SSE_FOP(x) { gen_helper_ ## x ## ps, gen_helper_ ## x ## pd, \
                      gen_helper_ ## x ## ss, gen_helper_ ## x ## sd, }
 
-static void *sse_op_table1[256][4] = {
+static const SSEFunc_0_pp sse_op_table1[256][4] = {
     /* 3DNow! extensions */
     [0x0e] = { SSE_DUMMY }, /* femms */
     [0x0f] = { SSE_DUMMY }, /* pf... */
@@ -2834,7 +2842,8 @@ static void *sse_op_table1[256][4] = {
     [0x5f] = SSE_FOP(max),
 
     [0xc2] = SSE_FOP(cmpeq),
-    [0xc6] = { gen_helper_shufps, gen_helper_shufpd },
+    [0xc6] = { (SSEFunc_0_pp)gen_helper_shufps,
+               (SSEFunc_0_pp)gen_helper_shufpd }, /* XXX: casts */
 
     [0x38] = { SSE_SPECIAL, SSE_SPECIAL, NULL, SSE_SPECIAL }, /* SSSE3/SSE4 */
     [0x3a] = { SSE_SPECIAL, SSE_SPECIAL }, /* SSSE3/SSE4 */
@@ -2856,10 +2865,10 @@ static void *sse_op_table1[256][4] = {
     [0x6d] = { NULL, gen_helper_punpckhqdq_xmm },
     [0x6e] = { SSE_SPECIAL, SSE_SPECIAL }, /* movd mm, ea */
     [0x6f] = { SSE_SPECIAL, SSE_SPECIAL, SSE_SPECIAL }, /* movq, movdqa, , movqdu */
-    [0x70] = { gen_helper_pshufw_mmx,
-               gen_helper_pshufd_xmm,
-               gen_helper_pshufhw_xmm,
-               gen_helper_pshuflw_xmm },
+    [0x70] = { (SSEFunc_0_pp)gen_helper_pshufw_mmx,
+               (SSEFunc_0_pp)gen_helper_pshufd_xmm,
+               (SSEFunc_0_pp)gen_helper_pshufhw_xmm,
+               (SSEFunc_0_pp)gen_helper_pshuflw_xmm }, /* XXX: casts */
     [0x71] = { SSE_SPECIAL, SSE_SPECIAL }, /* shiftw */
     [0x72] = { SSE_SPECIAL, SSE_SPECIAL }, /* shiftd */
     [0x73] = { SSE_SPECIAL, SSE_SPECIAL }, /* shiftq */
@@ -2914,7 +2923,8 @@ static void *sse_op_table1[256][4] = {
     [0xf4] = MMX_OP2(pmuludq),
     [0xf5] = MMX_OP2(pmaddwd),
     [0xf6] = MMX_OP2(psadbw),
-    [0xf7] = MMX_OP2(maskmov),
+    [0xf7] = { (SSEFunc_0_pp)gen_helper_maskmov_mmx,
+               (SSEFunc_0_pp)gen_helper_maskmov_xmm }, /* XXX: casts */
     [0xf8] = MMX_OP2(psubb),
     [0xf9] = MMX_OP2(psubw),
     [0xfa] = MMX_OP2(psubl),
@@ -2924,7 +2934,7 @@ static void *sse_op_table1[256][4] = {
     [0xfe] = MMX_OP2(paddl),
 };
 
-static void *sse_op_table2[3 * 8][2] = {
+static const SSEFunc_0_pp sse_op_table2[3 * 8][2] = {
     [0 + 2] = MMX_OP2(psrlw),
     [0 + 4] = MMX_OP2(psraw),
     [0 + 6] = MMX_OP2(psllw),
@@ -2937,12 +2947,14 @@ static void *sse_op_table2[3 * 8][2] = {
     [16 + 7] = { NULL, gen_helper_pslldq_xmm },
 };
 
-static void *sse_op_table3[4 * 3] = {
+static const SSEFunc_0_pi sse_op_table3a[4] = {
     gen_helper_cvtsi2ss,
     gen_helper_cvtsi2sd,
     X86_64_ONLY(gen_helper_cvtsq2ss),
     X86_64_ONLY(gen_helper_cvtsq2sd),
+};
 
+static const SSEFunc_i_p sse_op_table3b[4 * 2] = {
     gen_helper_cvttss2si,
     gen_helper_cvttsd2si,
     X86_64_ONLY(gen_helper_cvttss2sq),
@@ -2954,7 +2966,7 @@ static void *sse_op_table3[4 * 3] = {
     X86_64_ONLY(gen_helper_cvtsd2sq),
 };
 
-static void *sse_op_table4[8][4] = {
+static const SSEFunc_0_pp sse_op_table4[8][4] = {
     SSE_FOP(cmpeq),
     SSE_FOP(cmplt),
     SSE_FOP(cmple),
@@ -2965,7 +2977,7 @@ static void *sse_op_table4[8][4] = {
     SSE_FOP(cmpord),
 };
 
-static void *sse_op_table5[256] = {
+static const SSEFunc_0_pp sse_op_table5[256] = {
     [0x0c] = gen_helper_pi2fw,
     [0x0d] = gen_helper_pi2fd,
     [0x1c] = gen_helper_pf2iw,
@@ -2992,14 +3004,22 @@ static void *sse_op_table5[256] = {
     [0xbf] = gen_helper_pavgb_mmx /* pavgusb */
 };
 
-struct sse_op_helper_s {
-    void *op[2]; uint32_t ext_mask;
+struct SSEOpHelper_pp {
+    SSEFunc_0_pp op[2];
+    uint32_t ext_mask;
+};
+
+struct SSEOpHelper_ppi {
+    SSEFunc_0_ppi op[2];
+    uint32_t ext_mask;
 };
+
 #define SSSE3_OP(x) { MMX_OP2(x), CPUID_EXT_SSSE3 }
 #define SSE41_OP(x) { { NULL, gen_helper_ ## x ## _xmm }, CPUID_EXT_SSE41 }
 #define SSE42_OP(x) { { NULL, gen_helper_ ## x ## _xmm }, CPUID_EXT_SSE42 }
 #define SSE41_SPECIAL { { NULL, SSE_SPECIAL }, CPUID_EXT_SSE41 }
-static struct sse_op_helper_s sse_op_table6[256] = {
+
+static const struct SSEOpHelper_pp sse_op_table6[256] = {
     [0x00] = SSSE3_OP(pshufb),
     [0x01] = SSSE3_OP(phaddw),
     [0x02] = SSSE3_OP(phaddd),
@@ -3048,7 +3068,7 @@ static struct sse_op_helper_s sse_op_table6[256] = {
     [0x41] = SSE41_OP(phminposuw),
 };
 
-static struct sse_op_helper_s sse_op_table7[256] = {
+static const struct SSEOpHelper_ppi sse_op_table7[256] = {
     [0x08] = SSE41_OP(roundps),
     [0x09] = SSE41_OP(roundpd),
     [0x0a] = SSE41_OP(roundss),
@@ -3077,7 +3097,13 @@ static void gen_sse(DisasContext *s, int b, target_ulong pc_start, int rex_r)
 {
     int b1, op1_offset, op2_offset, is_xmm, val, ot;
     int modrm, mod, rm, reg, reg_addr, offset_addr;
-    void *sse_op2;
+    SSEFunc_i_p sse_fn_i_p;
+    SSEFunc_l_p sse_fn_l_p;
+    SSEFunc_0_pi sse_fn_pi;
+    SSEFunc_0_pl sse_fn_pl;
+    SSEFunc_0_pp sse_fn_pp;
+    SSEFunc_0_ppi sse_fn_ppi;
+    SSEFunc_0_ppt sse_fn_ppt;
 
     b &= 0xff;
     if (s->prefix & PREFIX_DATA)
@@ -3088,9 +3114,10 @@ static void gen_sse(DisasContext *s, int b, target_ulong pc_start, int rex_r)
         b1 = 3;
     else
         b1 = 0;
-    sse_op2 = sse_op_table1[b][b1];
-    if (!sse_op2)
+    sse_fn_pp = sse_op_table1[b][b1];
+    if (!sse_fn_pp) {
         goto illegal_op;
+    }
     if ((b <= 0x5f && b >= 0x10) || b == 0xc6 || b == 0xc2) {
         is_xmm = 1;
     } else {
@@ -3137,7 +3164,7 @@ static void gen_sse(DisasContext *s, int b, target_ulong pc_start, int rex_r)
     if (is_xmm)
         reg |= rex_r;
     mod = (modrm >> 6) & 3;
-    if (sse_op2 == SSE_SPECIAL) {
+    if (sse_fn_pp == SSE_SPECIAL) {
         b |= (b1 << 8);
         switch(b) {
         case 0x0e7: /* movntq */
@@ -3474,9 +3501,10 @@ static void gen_sse(DisasContext *s, int b, target_ulong pc_start, int rex_r)
                 tcg_gen_st32_tl(cpu_T[0], cpu_env, offsetof(CPUX86State,mmx_t0.MMX_L(1)));
                 op1_offset = offsetof(CPUX86State,mmx_t0);
             }
-            sse_op2 = sse_op_table2[((b - 1) & 3) * 8 + (((modrm >> 3)) & 7)][b1];
-            if (!sse_op2)
+            sse_fn_pp = sse_op_table2[((b - 1) & 3) * 8 + (((modrm >> 3)) & 7)][b1];
+            if (!sse_fn_pp) {
                 goto illegal_op;
+            }
             if (is_xmm) {
                 rm = (modrm & 7) | REX_B(s);
                 op2_offset = offsetof(CPUX86State,xmm_regs[rm]);
@@ -3486,7 +3514,7 @@ static void gen_sse(DisasContext *s, int b, target_ulong pc_start, int rex_r)
             }
             tcg_gen_addi_ptr(cpu_ptr0, cpu_env, op2_offset);
             tcg_gen_addi_ptr(cpu_ptr1, cpu_env, op1_offset);
-            ((void (*)(TCGv_ptr, TCGv_ptr))sse_op2)(cpu_ptr0, cpu_ptr1);
+            sse_fn_pp(cpu_ptr0, cpu_ptr1);
             break;
         case 0x050: /* movmskps */
             rm = (modrm & 7) | REX_B(s);
@@ -3534,12 +3562,15 @@ static void gen_sse(DisasContext *s, int b, target_ulong pc_start, int rex_r)
             gen_ldst_modrm(s, modrm, ot, OR_TMP0, 0);
             op1_offset = offsetof(CPUX86State,xmm_regs[reg]);
             tcg_gen_addi_ptr(cpu_ptr0, cpu_env, op1_offset);
-            sse_op2 = sse_op_table3[(s->dflag == 2) * 2 + ((b >> 8) - 2)];
             if (ot == OT_LONG) {
+                sse_fn_pi = sse_op_table3a[(s->dflag == 2) * 2 +
+                                           ((b >> 8) - 2)];
                 tcg_gen_trunc_tl_i32(cpu_tmp2_i32, cpu_T[0]);
-                ((void (*)(TCGv_ptr, TCGv_i32))sse_op2)(cpu_ptr0, cpu_tmp2_i32);
+                sse_fn_pi(cpu_ptr0, cpu_tmp2_i32);
             } else {
-                ((void (*)(TCGv_ptr, TCGv))sse_op2)(cpu_ptr0, cpu_T[0]);
+                sse_fn_pl = sse_op_table3a[(s->dflag == 2) * 2 +
+                                           ((b >> 8) - 2)];
+                sse_fn_pl(cpu_ptr0, cpu_T[0]);
             }
             break;
         case 0x02c: /* cvttps2pi */
@@ -3591,14 +3622,18 @@ static void gen_sse(DisasContext *s, int b, target_ulong pc_start, int rex_r)
                 rm = (modrm & 7) | REX_B(s);
                 op2_offset = offsetof(CPUX86State,xmm_regs[rm]);
             }
-            sse_op2 = sse_op_table3[(s->dflag == 2) * 2 + ((b >> 8) - 2) + 4 +
-                                    (b & 1) * 4];
             tcg_gen_addi_ptr(cpu_ptr0, cpu_env, op2_offset);
             if (ot == OT_LONG) {
-                ((void (*)(TCGv_i32, TCGv_ptr))sse_op2)(cpu_tmp2_i32, cpu_ptr0);
+                sse_fn_i_p = sse_op_table3b[(s->dflag == 2) * 2 +
+                                            ((b >> 8) - 2) +
+                                            (b & 1) * 4];
+                sse_fn_i_p(cpu_tmp2_i32, cpu_ptr0);
                 tcg_gen_extu_i32_tl(cpu_T[0], cpu_tmp2_i32);
             } else {
-                ((void (*)(TCGv, TCGv_ptr))sse_op2)(cpu_T[0], cpu_ptr0);
+                sse_fn_l_p = sse_op_table3b[(s->dflag == 2) * 2 +
+                                            ((b >> 8) - 2) +
+                                            (b & 1) * 4];
+                sse_fn_l_p(cpu_T[0], cpu_ptr0);
             }
             gen_op_mov_reg_T0(ot, reg);
             break;
@@ -3691,9 +3726,10 @@ static void gen_sse(DisasContext *s, int b, target_ulong pc_start, int rex_r)
                 goto illegal_op;
             }
 
-            sse_op2 = sse_op_table6[b].op[b1];
-            if (!sse_op2)
+            sse_fn_pp = sse_op_table6[b].op[b1];
+            if (!sse_fn_pp) {
                 goto illegal_op;
+            }
             if (!(s->cpuid_ext_features & sse_op_table6[b].ext_mask))
                 goto illegal_op;
 
@@ -3742,12 +3778,13 @@ static void gen_sse(DisasContext *s, int b, target_ulong pc_start, int rex_r)
                     gen_ldq_env_A0(s->mem_index, op2_offset);
                 }
             }
-            if (sse_op2 == SSE_SPECIAL)
+            if (sse_fn_pp == SSE_SPECIAL) {
                 goto illegal_op;
+            }
 
             tcg_gen_addi_ptr(cpu_ptr0, cpu_env, op1_offset);
             tcg_gen_addi_ptr(cpu_ptr1, cpu_env, op2_offset);
-            ((void (*)(TCGv_ptr, TCGv_ptr))sse_op2)(cpu_ptr0, cpu_ptr1);
+            sse_fn_pp(cpu_ptr0, cpu_ptr1);
 
             if (b == 0x17)
                 s->cc_op = CC_OP_EFLAGS;
@@ -3793,13 +3830,14 @@ static void gen_sse(DisasContext *s, int b, target_ulong pc_start, int rex_r)
                 goto illegal_op;
             }
 
-            sse_op2 = sse_op_table7[b].op[b1];
-            if (!sse_op2)
+            sse_fn_ppi = sse_op_table7[b].op[b1];
+            if (!sse_fn_ppi) {
                 goto illegal_op;
+            }
             if (!(s->cpuid_ext_features & sse_op_table7[b].ext_mask))
                 goto illegal_op;
 
-            if (sse_op2 == SSE_SPECIAL) {
+            if (sse_fn_ppi == SSE_SPECIAL) {
                 ot = (s->dflag == 2) ? OT_QUAD : OT_LONG;
                 rm = (modrm & 7) | REX_B(s);
                 if (mod != 3)
@@ -3960,7 +3998,7 @@ static void gen_sse(DisasContext *s, int b, target_ulong pc_start, int rex_r)
 
             tcg_gen_addi_ptr(cpu_ptr0, cpu_env, op1_offset);
             tcg_gen_addi_ptr(cpu_ptr1, cpu_env, op2_offset);
-            ((void (*)(TCGv_ptr, TCGv_ptr, TCGv_i32))sse_op2)(cpu_ptr0, cpu_ptr1, tcg_const_i32(val));
+            sse_fn_ppi(cpu_ptr0, cpu_ptr1, tcg_const_i32(val));
             break;
         default:
             goto illegal_op;
@@ -4015,29 +4053,33 @@ static void gen_sse(DisasContext *s, int b, target_ulong pc_start, int rex_r)
             if (!(s->cpuid_ext2_features & CPUID_EXT2_3DNOW))
                 goto illegal_op;
             val = ldub_code(s->pc++);
-            sse_op2 = sse_op_table5[val];
-            if (!sse_op2)
+            sse_fn_pp = sse_op_table5[val];
+            if (!sse_fn_pp) {
                 goto illegal_op;
+            }
             tcg_gen_addi_ptr(cpu_ptr0, cpu_env, op1_offset);
             tcg_gen_addi_ptr(cpu_ptr1, cpu_env, op2_offset);
-            ((void (*)(TCGv_ptr, TCGv_ptr))sse_op2)(cpu_ptr0, cpu_ptr1);
+            sse_fn_pp(cpu_ptr0, cpu_ptr1);
             break;
         case 0x70: /* pshufx insn */
         case 0xc6: /* pshufx insn */
             val = ldub_code(s->pc++);
             tcg_gen_addi_ptr(cpu_ptr0, cpu_env, op1_offset);
             tcg_gen_addi_ptr(cpu_ptr1, cpu_env, op2_offset);
-            ((void (*)(TCGv_ptr, TCGv_ptr, TCGv_i32))sse_op2)(cpu_ptr0, cpu_ptr1, tcg_const_i32(val));
+            /* XXX: introduce a new table? */
+            sse_fn_ppi = (SSEFunc_0_ppi)sse_fn_pp;
+            sse_fn_ppi(cpu_ptr0, cpu_ptr1, tcg_const_i32(val));
             break;
         case 0xc2:
             /* compare insns */
             val = ldub_code(s->pc++);
             if (val >= 8)
                 goto illegal_op;
-            sse_op2 = sse_op_table4[val][b1];
+            sse_fn_pp = sse_op_table4[val][b1];
+
             tcg_gen_addi_ptr(cpu_ptr0, cpu_env, op1_offset);
             tcg_gen_addi_ptr(cpu_ptr1, cpu_env, op2_offset);
-            ((void (*)(TCGv_ptr, TCGv_ptr))sse_op2)(cpu_ptr0, cpu_ptr1);
+            sse_fn_pp(cpu_ptr0, cpu_ptr1);
             break;
         case 0xf7:
             /* maskmov : we must prepare A0 */
@@ -4057,12 +4099,14 @@ static void gen_sse(DisasContext *s, int b, target_ulong pc_start, int rex_r)
 
             tcg_gen_addi_ptr(cpu_ptr0, cpu_env, op1_offset);
             tcg_gen_addi_ptr(cpu_ptr1, cpu_env, op2_offset);
-            ((void (*)(TCGv_ptr, TCGv_ptr, TCGv))sse_op2)(cpu_ptr0, cpu_ptr1, cpu_A0);
+            /* XXX: introduce a new table? */
+            sse_fn_ppt = (SSEFunc_0_ppt)sse_fn_pp;
+            sse_fn_ppt(cpu_ptr0, cpu_ptr1, cpu_A0);
             break;
         default:
             tcg_gen_addi_ptr(cpu_ptr0, cpu_env, op1_offset);
             tcg_gen_addi_ptr(cpu_ptr1, cpu_env, op2_offset);
-            ((void (*)(TCGv_ptr, TCGv_ptr))sse_op2)(cpu_ptr0, cpu_ptr1);
+            sse_fn_pp(cpu_ptr0, cpu_ptr1);
             break;
         }
         if (b == 0x2e || b == 0x2f) {
commit f299f4374affb6b838765841bb69a6e92566a9a8
Author: Blue Swirl <blauwirbel at gmail.com>
Date:   Sat Apr 28 20:21:41 2012 +0000

    x86: split off FPU helpers
    
    Move FPU and MMX/SSE helpers to fpu_helpers.c.
    
    Signed-off-by: Blue Swirl <blauwirbel at gmail.com>

diff --git a/target-i386/Makefile.objs b/target-i386/Makefile.objs
index c0feffe..7c15de4 100644
--- a/target-i386/Makefile.objs
+++ b/target-i386/Makefile.objs
@@ -1,8 +1,9 @@
 obj-y += translate.o op_helper.o helper.o cpu.o
-obj-y += excp_helper.o
+obj-y += excp_helper.o fpu_helper.o
 obj-$(CONFIG_SOFTMMU) += machine.o arch_memory_mapping.o arch_dump.o
 obj-$(CONFIG_KVM) += kvm.o hyperv.o
 obj-$(CONFIG_LINUX_USER) += ioport-user.o
 obj-$(CONFIG_BSD_USER) += ioport-user.o
 
 $(obj)/op_helper.o: QEMU_CFLAGS += $(HELPER_CFLAGS)
+$(obj)/fpu_helper.o: QEMU_CFLAGS += $(HELPER_CFLAGS)
diff --git a/target-i386/fpu_helper.c b/target-i386/fpu_helper.c
new file mode 100644
index 0000000..6065c2e
--- /dev/null
+++ b/target-i386/fpu_helper.c
@@ -0,0 +1,1304 @@
+/*
+ *  x86 FPU, MMX/3DNow!/SSE/SSE2/SSE3/SSSE3/SSE4/PNI helpers
+ *
+ *  Copyright (c) 2003 Fabrice Bellard
+ *
+ * This library is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Lesser General Public
+ * License as published by the Free Software Foundation; either
+ * version 2 of the License, or (at your option) any later version.
+ *
+ * This library is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
+ * Lesser General Public License for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public
+ * License along with this library; if not, see <http://www.gnu.org/licenses/>.
+ */
+
+#include <math.h>
+#include "cpu.h"
+#include "dyngen-exec.h"
+#include "helper.h"
+
+#if !defined(CONFIG_USER_ONLY)
+#include "softmmu_exec.h"
+#endif /* !defined(CONFIG_USER_ONLY) */
+
+#define FPU_RC_MASK         0xc00
+#define FPU_RC_NEAR         0x000
+#define FPU_RC_DOWN         0x400
+#define FPU_RC_UP           0x800
+#define FPU_RC_CHOP         0xc00
+
+#define MAXTAN 9223372036854775808.0
+
+/* the following deal with x86 long double-precision numbers */
+#define MAXEXPD 0x7fff
+#define EXPBIAS 16383
+#define EXPD(fp)        (fp.l.upper & 0x7fff)
+#define SIGND(fp)       ((fp.l.upper) & 0x8000)
+#define MANTD(fp)       (fp.l.lower)
+#define BIASEXPONENT(fp) fp.l.upper = (fp.l.upper & ~(0x7fff)) | EXPBIAS
+
+#define FPUS_IE (1 << 0)
+#define FPUS_DE (1 << 1)
+#define FPUS_ZE (1 << 2)
+#define FPUS_OE (1 << 3)
+#define FPUS_UE (1 << 4)
+#define FPUS_PE (1 << 5)
+#define FPUS_SF (1 << 6)
+#define FPUS_SE (1 << 7)
+#define FPUS_B  (1 << 15)
+
+#define FPUC_EM 0x3f
+
+#define floatx80_lg2 make_floatx80(0x3ffd, 0x9a209a84fbcff799LL)
+#define floatx80_l2e make_floatx80(0x3fff, 0xb8aa3b295c17f0bcLL)
+#define floatx80_l2t make_floatx80(0x4000, 0xd49a784bcd1b8afeLL)
+
+static inline void fpush(void)
+{
+    env->fpstt = (env->fpstt - 1) & 7;
+    env->fptags[env->fpstt] = 0; /* validate stack entry */
+}
+
+static inline void fpop(void)
+{
+    env->fptags[env->fpstt] = 1; /* invalidate stack entry */
+    env->fpstt = (env->fpstt + 1) & 7;
+}
+
+static inline floatx80 helper_fldt(target_ulong ptr)
+{
+    CPU_LDoubleU temp;
+
+    temp.l.lower = ldq(ptr);
+    temp.l.upper = lduw(ptr + 8);
+    return temp.d;
+}
+
+static inline void helper_fstt(floatx80 f, target_ulong ptr)
+{
+    CPU_LDoubleU temp;
+
+    temp.d = f;
+    stq(ptr, temp.l.lower);
+    stw(ptr + 8, temp.l.upper);
+}
+
+/* x87 FPU helpers */
+
+static inline double floatx80_to_double(floatx80 a)
+{
+    union {
+        float64 f64;
+        double d;
+    } u;
+
+    u.f64 = floatx80_to_float64(a, &env->fp_status);
+    return u.d;
+}
+
+static inline floatx80 double_to_floatx80(double a)
+{
+    union {
+        float64 f64;
+        double d;
+    } u;
+
+    u.d = a;
+    return float64_to_floatx80(u.f64, &env->fp_status);
+}
+
+static void fpu_set_exception(int mask)
+{
+    env->fpus |= mask;
+    if (env->fpus & (~env->fpuc & FPUC_EM)) {
+        env->fpus |= FPUS_SE | FPUS_B;
+    }
+}
+
+static inline floatx80 helper_fdiv(floatx80 a, floatx80 b)
+{
+    if (floatx80_is_zero(b)) {
+        fpu_set_exception(FPUS_ZE);
+    }
+    return floatx80_div(a, b, &env->fp_status);
+}
+
+static void fpu_raise_exception(void)
+{
+    if (env->cr[0] & CR0_NE_MASK) {
+        raise_exception(env, EXCP10_COPR);
+    }
+#if !defined(CONFIG_USER_ONLY)
+    else {
+        cpu_set_ferr(env);
+    }
+#endif
+}
+
+void helper_flds_FT0(uint32_t val)
+{
+    union {
+        float32 f;
+        uint32_t i;
+    } u;
+
+    u.i = val;
+    FT0 = float32_to_floatx80(u.f, &env->fp_status);
+}
+
+void helper_fldl_FT0(uint64_t val)
+{
+    union {
+        float64 f;
+        uint64_t i;
+    } u;
+
+    u.i = val;
+    FT0 = float64_to_floatx80(u.f, &env->fp_status);
+}
+
+void helper_fildl_FT0(int32_t val)
+{
+    FT0 = int32_to_floatx80(val, &env->fp_status);
+}
+
+void helper_flds_ST0(uint32_t val)
+{
+    int new_fpstt;
+    union {
+        float32 f;
+        uint32_t i;
+    } u;
+
+    new_fpstt = (env->fpstt - 1) & 7;
+    u.i = val;
+    env->fpregs[new_fpstt].d = float32_to_floatx80(u.f, &env->fp_status);
+    env->fpstt = new_fpstt;
+    env->fptags[new_fpstt] = 0; /* validate stack entry */
+}
+
+void helper_fldl_ST0(uint64_t val)
+{
+    int new_fpstt;
+    union {
+        float64 f;
+        uint64_t i;
+    } u;
+
+    new_fpstt = (env->fpstt - 1) & 7;
+    u.i = val;
+    env->fpregs[new_fpstt].d = float64_to_floatx80(u.f, &env->fp_status);
+    env->fpstt = new_fpstt;
+    env->fptags[new_fpstt] = 0; /* validate stack entry */
+}
+
+void helper_fildl_ST0(int32_t val)
+{
+    int new_fpstt;
+
+    new_fpstt = (env->fpstt - 1) & 7;
+    env->fpregs[new_fpstt].d = int32_to_floatx80(val, &env->fp_status);
+    env->fpstt = new_fpstt;
+    env->fptags[new_fpstt] = 0; /* validate stack entry */
+}
+
+void helper_fildll_ST0(int64_t val)
+{
+    int new_fpstt;
+
+    new_fpstt = (env->fpstt - 1) & 7;
+    env->fpregs[new_fpstt].d = int64_to_floatx80(val, &env->fp_status);
+    env->fpstt = new_fpstt;
+    env->fptags[new_fpstt] = 0; /* validate stack entry */
+}
+
+uint32_t helper_fsts_ST0(void)
+{
+    union {
+        float32 f;
+        uint32_t i;
+    } u;
+
+    u.f = floatx80_to_float32(ST0, &env->fp_status);
+    return u.i;
+}
+
+uint64_t helper_fstl_ST0(void)
+{
+    union {
+        float64 f;
+        uint64_t i;
+    } u;
+
+    u.f = floatx80_to_float64(ST0, &env->fp_status);
+    return u.i;
+}
+
+int32_t helper_fist_ST0(void)
+{
+    int32_t val;
+
+    val = floatx80_to_int32(ST0, &env->fp_status);
+    if (val != (int16_t)val) {
+        val = -32768;
+    }
+    return val;
+}
+
+int32_t helper_fistl_ST0(void)
+{
+    int32_t val;
+
+    val = floatx80_to_int32(ST0, &env->fp_status);
+    return val;
+}
+
+int64_t helper_fistll_ST0(void)
+{
+    int64_t val;
+
+    val = floatx80_to_int64(ST0, &env->fp_status);
+    return val;
+}
+
+int32_t helper_fistt_ST0(void)
+{
+    int32_t val;
+
+    val = floatx80_to_int32_round_to_zero(ST0, &env->fp_status);
+    if (val != (int16_t)val) {
+        val = -32768;
+    }
+    return val;
+}
+
+int32_t helper_fisttl_ST0(void)
+{
+    int32_t val;
+
+    val = floatx80_to_int32_round_to_zero(ST0, &env->fp_status);
+    return val;
+}
+
+int64_t helper_fisttll_ST0(void)
+{
+    int64_t val;
+
+    val = floatx80_to_int64_round_to_zero(ST0, &env->fp_status);
+    return val;
+}
+
+void helper_fldt_ST0(target_ulong ptr)
+{
+    int new_fpstt;
+
+    new_fpstt = (env->fpstt - 1) & 7;
+    env->fpregs[new_fpstt].d = helper_fldt(ptr);
+    env->fpstt = new_fpstt;
+    env->fptags[new_fpstt] = 0; /* validate stack entry */
+}
+
+void helper_fstt_ST0(target_ulong ptr)
+{
+    helper_fstt(ST0, ptr);
+}
+
+void helper_fpush(void)
+{
+    fpush();
+}
+
+void helper_fpop(void)
+{
+    fpop();
+}
+
+void helper_fdecstp(void)
+{
+    env->fpstt = (env->fpstt - 1) & 7;
+    env->fpus &= ~0x4700;
+}
+
+void helper_fincstp(void)
+{
+    env->fpstt = (env->fpstt + 1) & 7;
+    env->fpus &= ~0x4700;
+}
+
+/* FPU move */
+
+void helper_ffree_STN(int st_index)
+{
+    env->fptags[(env->fpstt + st_index) & 7] = 1;
+}
+
+void helper_fmov_ST0_FT0(void)
+{
+    ST0 = FT0;
+}
+
+void helper_fmov_FT0_STN(int st_index)
+{
+    FT0 = ST(st_index);
+}
+
+void helper_fmov_ST0_STN(int st_index)
+{
+    ST0 = ST(st_index);
+}
+
+void helper_fmov_STN_ST0(int st_index)
+{
+    ST(st_index) = ST0;
+}
+
+void helper_fxchg_ST0_STN(int st_index)
+{
+    floatx80 tmp;
+
+    tmp = ST(st_index);
+    ST(st_index) = ST0;
+    ST0 = tmp;
+}
+
+/* FPU operations */
+
+static const int fcom_ccval[4] = {0x0100, 0x4000, 0x0000, 0x4500};
+
+void helper_fcom_ST0_FT0(void)
+{
+    int ret;
+
+    ret = floatx80_compare(ST0, FT0, &env->fp_status);
+    env->fpus = (env->fpus & ~0x4500) | fcom_ccval[ret + 1];
+}
+
+void helper_fucom_ST0_FT0(void)
+{
+    int ret;
+
+    ret = floatx80_compare_quiet(ST0, FT0, &env->fp_status);
+    env->fpus = (env->fpus & ~0x4500) | fcom_ccval[ret + 1];
+}
+
+static const int fcomi_ccval[4] = {CC_C, CC_Z, 0, CC_Z | CC_P | CC_C};
+
+void helper_fcomi_ST0_FT0(void)
+{
+    int eflags;
+    int ret;
+
+    ret = floatx80_compare(ST0, FT0, &env->fp_status);
+    eflags = helper_cc_compute_all(CC_OP);
+    eflags = (eflags & ~(CC_Z | CC_P | CC_C)) | fcomi_ccval[ret + 1];
+    CC_SRC = eflags;
+}
+
+void helper_fucomi_ST0_FT0(void)
+{
+    int eflags;
+    int ret;
+
+    ret = floatx80_compare_quiet(ST0, FT0, &env->fp_status);
+    eflags = helper_cc_compute_all(CC_OP);
+    eflags = (eflags & ~(CC_Z | CC_P | CC_C)) | fcomi_ccval[ret + 1];
+    CC_SRC = eflags;
+}
+
+void helper_fadd_ST0_FT0(void)
+{
+    ST0 = floatx80_add(ST0, FT0, &env->fp_status);
+}
+
+void helper_fmul_ST0_FT0(void)
+{
+    ST0 = floatx80_mul(ST0, FT0, &env->fp_status);
+}
+
+void helper_fsub_ST0_FT0(void)
+{
+    ST0 = floatx80_sub(ST0, FT0, &env->fp_status);
+}
+
+void helper_fsubr_ST0_FT0(void)
+{
+    ST0 = floatx80_sub(FT0, ST0, &env->fp_status);
+}
+
+void helper_fdiv_ST0_FT0(void)
+{
+    ST0 = helper_fdiv(ST0, FT0);
+}
+
+void helper_fdivr_ST0_FT0(void)
+{
+    ST0 = helper_fdiv(FT0, ST0);
+}
+
+/* fp operations between STN and ST0 */
+
+void helper_fadd_STN_ST0(int st_index)
+{
+    ST(st_index) = floatx80_add(ST(st_index), ST0, &env->fp_status);
+}
+
+void helper_fmul_STN_ST0(int st_index)
+{
+    ST(st_index) = floatx80_mul(ST(st_index), ST0, &env->fp_status);
+}
+
+void helper_fsub_STN_ST0(int st_index)
+{
+    ST(st_index) = floatx80_sub(ST(st_index), ST0, &env->fp_status);
+}
+
+void helper_fsubr_STN_ST0(int st_index)
+{
+    ST(st_index) = floatx80_sub(ST0, ST(st_index), &env->fp_status);
+}
+
+void helper_fdiv_STN_ST0(int st_index)
+{
+    floatx80 *p;
+
+    p = &ST(st_index);
+    *p = helper_fdiv(*p, ST0);
+}
+
+void helper_fdivr_STN_ST0(int st_index)
+{
+    floatx80 *p;
+
+    p = &ST(st_index);
+    *p = helper_fdiv(ST0, *p);
+}
+
+/* misc FPU operations */
+void helper_fchs_ST0(void)
+{
+    ST0 = floatx80_chs(ST0);
+}
+
+void helper_fabs_ST0(void)
+{
+    ST0 = floatx80_abs(ST0);
+}
+
+void helper_fld1_ST0(void)
+{
+    ST0 = floatx80_one;
+}
+
+void helper_fldl2t_ST0(void)
+{
+    ST0 = floatx80_l2t;
+}
+
+void helper_fldl2e_ST0(void)
+{
+    ST0 = floatx80_l2e;
+}
+
+void helper_fldpi_ST0(void)
+{
+    ST0 = floatx80_pi;
+}
+
+void helper_fldlg2_ST0(void)
+{
+    ST0 = floatx80_lg2;
+}
+
+void helper_fldln2_ST0(void)
+{
+    ST0 = floatx80_ln2;
+}
+
+void helper_fldz_ST0(void)
+{
+    ST0 = floatx80_zero;
+}
+
+void helper_fldz_FT0(void)
+{
+    FT0 = floatx80_zero;
+}
+
+uint32_t helper_fnstsw(void)
+{
+    return (env->fpus & ~0x3800) | (env->fpstt & 0x7) << 11;
+}
+
+uint32_t helper_fnstcw(void)
+{
+    return env->fpuc;
+}
+
+static void update_fp_status(void)
+{
+    int rnd_type;
+
+    /* set rounding mode */
+    switch (env->fpuc & FPU_RC_MASK) {
+    default:
+    case FPU_RC_NEAR:
+        rnd_type = float_round_nearest_even;
+        break;
+    case FPU_RC_DOWN:
+        rnd_type = float_round_down;
+        break;
+    case FPU_RC_UP:
+        rnd_type = float_round_up;
+        break;
+    case FPU_RC_CHOP:
+        rnd_type = float_round_to_zero;
+        break;
+    }
+    set_float_rounding_mode(rnd_type, &env->fp_status);
+    switch ((env->fpuc >> 8) & 3) {
+    case 0:
+        rnd_type = 32;
+        break;
+    case 2:
+        rnd_type = 64;
+        break;
+    case 3:
+    default:
+        rnd_type = 80;
+        break;
+    }
+    set_floatx80_rounding_precision(rnd_type, &env->fp_status);
+}
+
+void helper_fldcw(uint32_t val)
+{
+    env->fpuc = val;
+    update_fp_status();
+}
+
+void helper_fclex(void)
+{
+    env->fpus &= 0x7f00;
+}
+
+void helper_fwait(void)
+{
+    if (env->fpus & FPUS_SE) {
+        fpu_raise_exception();
+    }
+}
+
+void helper_fninit(void)
+{
+    env->fpus = 0;
+    env->fpstt = 0;
+    env->fpuc = 0x37f;
+    env->fptags[0] = 1;
+    env->fptags[1] = 1;
+    env->fptags[2] = 1;
+    env->fptags[3] = 1;
+    env->fptags[4] = 1;
+    env->fptags[5] = 1;
+    env->fptags[6] = 1;
+    env->fptags[7] = 1;
+}
+
+/* BCD ops */
+
+void helper_fbld_ST0(target_ulong ptr)
+{
+    floatx80 tmp;
+    uint64_t val;
+    unsigned int v;
+    int i;
+
+    val = 0;
+    for (i = 8; i >= 0; i--) {
+        v = ldub(ptr + i);
+        val = (val * 100) + ((v >> 4) * 10) + (v & 0xf);
+    }
+    tmp = int64_to_floatx80(val, &env->fp_status);
+    if (ldub(ptr + 9) & 0x80) {
+        floatx80_chs(tmp);
+    }
+    fpush();
+    ST0 = tmp;
+}
+
+void helper_fbst_ST0(target_ulong ptr)
+{
+    int v;
+    target_ulong mem_ref, mem_end;
+    int64_t val;
+
+    val = floatx80_to_int64(ST0, &env->fp_status);
+    mem_ref = ptr;
+    mem_end = mem_ref + 9;
+    if (val < 0) {
+        stb(mem_end, 0x80);
+        val = -val;
+    } else {
+        stb(mem_end, 0x00);
+    }
+    while (mem_ref < mem_end) {
+        if (val == 0) {
+            break;
+        }
+        v = val % 100;
+        val = val / 100;
+        v = ((v / 10) << 4) | (v % 10);
+        stb(mem_ref++, v);
+    }
+    while (mem_ref < mem_end) {
+        stb(mem_ref++, 0);
+    }
+}
+
+void helper_f2xm1(void)
+{
+    double val = floatx80_to_double(ST0);
+
+    val = pow(2.0, val) - 1.0;
+    ST0 = double_to_floatx80(val);
+}
+
+void helper_fyl2x(void)
+{
+    double fptemp = floatx80_to_double(ST0);
+
+    if (fptemp > 0.0) {
+        fptemp = log(fptemp) / log(2.0); /* log2(ST) */
+        fptemp *= floatx80_to_double(ST1);
+        ST1 = double_to_floatx80(fptemp);
+        fpop();
+    } else {
+        env->fpus &= ~0x4700;
+        env->fpus |= 0x400;
+    }
+}
+
+void helper_fptan(void)
+{
+    double fptemp = floatx80_to_double(ST0);
+
+    if ((fptemp > MAXTAN) || (fptemp < -MAXTAN)) {
+        env->fpus |= 0x400;
+    } else {
+        fptemp = tan(fptemp);
+        ST0 = double_to_floatx80(fptemp);
+        fpush();
+        ST0 = floatx80_one;
+        env->fpus &= ~0x400; /* C2 <-- 0 */
+        /* the above code is for |arg| < 2**52 only */
+    }
+}
+
+void helper_fpatan(void)
+{
+    double fptemp, fpsrcop;
+
+    fpsrcop = floatx80_to_double(ST1);
+    fptemp = floatx80_to_double(ST0);
+    ST1 = double_to_floatx80(atan2(fpsrcop, fptemp));
+    fpop();
+}
+
+void helper_fxtract(void)
+{
+    CPU_LDoubleU temp;
+
+    temp.d = ST0;
+
+    if (floatx80_is_zero(ST0)) {
+        /* Easy way to generate -inf and raising division by 0 exception */
+        ST0 = floatx80_div(floatx80_chs(floatx80_one), floatx80_zero,
+                           &env->fp_status);
+        fpush();
+        ST0 = temp.d;
+    } else {
+        int expdif;
+
+        expdif = EXPD(temp) - EXPBIAS;
+        /* DP exponent bias */
+        ST0 = int32_to_floatx80(expdif, &env->fp_status);
+        fpush();
+        BIASEXPONENT(temp);
+        ST0 = temp.d;
+    }
+}
+
+void helper_fprem1(void)
+{
+    double st0, st1, dblq, fpsrcop, fptemp;
+    CPU_LDoubleU fpsrcop1, fptemp1;
+    int expdif;
+    signed long long int q;
+
+    st0 = floatx80_to_double(ST0);
+    st1 = floatx80_to_double(ST1);
+
+    if (isinf(st0) || isnan(st0) || isnan(st1) || (st1 == 0.0)) {
+        ST0 = double_to_floatx80(0.0 / 0.0); /* NaN */
+        env->fpus &= ~0x4700; /* (C3,C2,C1,C0) <-- 0000 */
+        return;
+    }
+
+    fpsrcop = st0;
+    fptemp = st1;
+    fpsrcop1.d = ST0;
+    fptemp1.d = ST1;
+    expdif = EXPD(fpsrcop1) - EXPD(fptemp1);
+
+    if (expdif < 0) {
+        /* optimisation? taken from the AMD docs */
+        env->fpus &= ~0x4700; /* (C3,C2,C1,C0) <-- 0000 */
+        /* ST0 is unchanged */
+        return;
+    }
+
+    if (expdif < 53) {
+        dblq = fpsrcop / fptemp;
+        /* round dblq towards nearest integer */
+        dblq = rint(dblq);
+        st0 = fpsrcop - fptemp * dblq;
+
+        /* convert dblq to q by truncating towards zero */
+        if (dblq < 0.0) {
+            q = (signed long long int)(-dblq);
+        } else {
+            q = (signed long long int)dblq;
+        }
+
+        env->fpus &= ~0x4700; /* (C3,C2,C1,C0) <-- 0000 */
+        /* (C0,C3,C1) <-- (q2,q1,q0) */
+        env->fpus |= (q & 0x4) << (8 - 2);  /* (C0) <-- q2 */
+        env->fpus |= (q & 0x2) << (14 - 1); /* (C3) <-- q1 */
+        env->fpus |= (q & 0x1) << (9 - 0);  /* (C1) <-- q0 */
+    } else {
+        env->fpus |= 0x400;  /* C2 <-- 1 */
+        fptemp = pow(2.0, expdif - 50);
+        fpsrcop = (st0 / st1) / fptemp;
+        /* fpsrcop = integer obtained by chopping */
+        fpsrcop = (fpsrcop < 0.0) ?
+                  -(floor(fabs(fpsrcop))) : floor(fpsrcop);
+        st0 -= (st1 * fpsrcop * fptemp);
+    }
+    ST0 = double_to_floatx80(st0);
+}
+
+void helper_fprem(void)
+{
+    double st0, st1, dblq, fpsrcop, fptemp;
+    CPU_LDoubleU fpsrcop1, fptemp1;
+    int expdif;
+    signed long long int q;
+
+    st0 = floatx80_to_double(ST0);
+    st1 = floatx80_to_double(ST1);
+
+    if (isinf(st0) || isnan(st0) || isnan(st1) || (st1 == 0.0)) {
+        ST0 = double_to_floatx80(0.0 / 0.0); /* NaN */
+        env->fpus &= ~0x4700; /* (C3,C2,C1,C0) <-- 0000 */
+        return;
+    }
+
+    fpsrcop = st0;
+    fptemp = st1;
+    fpsrcop1.d = ST0;
+    fptemp1.d = ST1;
+    expdif = EXPD(fpsrcop1) - EXPD(fptemp1);
+
+    if (expdif < 0) {
+        /* optimisation? taken from the AMD docs */
+        env->fpus &= ~0x4700; /* (C3,C2,C1,C0) <-- 0000 */
+        /* ST0 is unchanged */
+        return;
+    }
+
+    if (expdif < 53) {
+        dblq = fpsrcop / fptemp; /* ST0 / ST1 */
+        /* round dblq towards zero */
+        dblq = (dblq < 0.0) ? ceil(dblq) : floor(dblq);
+        st0 = fpsrcop - fptemp * dblq; /* fpsrcop is ST0 */
+
+        /* convert dblq to q by truncating towards zero */
+        if (dblq < 0.0) {
+            q = (signed long long int)(-dblq);
+        } else {
+            q = (signed long long int)dblq;
+        }
+
+        env->fpus &= ~0x4700; /* (C3,C2,C1,C0) <-- 0000 */
+        /* (C0,C3,C1) <-- (q2,q1,q0) */
+        env->fpus |= (q & 0x4) << (8 - 2);  /* (C0) <-- q2 */
+        env->fpus |= (q & 0x2) << (14 - 1); /* (C3) <-- q1 */
+        env->fpus |= (q & 0x1) << (9 - 0);  /* (C1) <-- q0 */
+    } else {
+        int N = 32 + (expdif % 32); /* as per AMD docs */
+
+        env->fpus |= 0x400;  /* C2 <-- 1 */
+        fptemp = pow(2.0, (double)(expdif - N));
+        fpsrcop = (st0 / st1) / fptemp;
+        /* fpsrcop = integer obtained by chopping */
+        fpsrcop = (fpsrcop < 0.0) ?
+                  -(floor(fabs(fpsrcop))) : floor(fpsrcop);
+        st0 -= (st1 * fpsrcop * fptemp);
+    }
+    ST0 = double_to_floatx80(st0);
+}
+
+void helper_fyl2xp1(void)
+{
+    double fptemp = floatx80_to_double(ST0);
+
+    if ((fptemp + 1.0) > 0.0) {
+        fptemp = log(fptemp + 1.0) / log(2.0); /* log2(ST + 1.0) */
+        fptemp *= floatx80_to_double(ST1);
+        ST1 = double_to_floatx80(fptemp);
+        fpop();
+    } else {
+        env->fpus &= ~0x4700;
+        env->fpus |= 0x400;
+    }
+}
+
+void helper_fsqrt(void)
+{
+    if (floatx80_is_neg(ST0)) {
+        env->fpus &= ~0x4700;  /* (C3,C2,C1,C0) <-- 0000 */
+        env->fpus |= 0x400;
+    }
+    ST0 = floatx80_sqrt(ST0, &env->fp_status);
+}
+
+void helper_fsincos(void)
+{
+    double fptemp = floatx80_to_double(ST0);
+
+    if ((fptemp > MAXTAN) || (fptemp < -MAXTAN)) {
+        env->fpus |= 0x400;
+    } else {
+        ST0 = double_to_floatx80(sin(fptemp));
+        fpush();
+        ST0 = double_to_floatx80(cos(fptemp));
+        env->fpus &= ~0x400;  /* C2 <-- 0 */
+        /* the above code is for |arg| < 2**63 only */
+    }
+}
+
+void helper_frndint(void)
+{
+    ST0 = floatx80_round_to_int(ST0, &env->fp_status);
+}
+
+void helper_fscale(void)
+{
+    if (floatx80_is_any_nan(ST1)) {
+        ST0 = ST1;
+    } else {
+        int n = floatx80_to_int32_round_to_zero(ST1, &env->fp_status);
+        ST0 = floatx80_scalbn(ST0, n, &env->fp_status);
+    }
+}
+
+void helper_fsin(void)
+{
+    double fptemp = floatx80_to_double(ST0);
+
+    if ((fptemp > MAXTAN) || (fptemp < -MAXTAN)) {
+        env->fpus |= 0x400;
+    } else {
+        ST0 = double_to_floatx80(sin(fptemp));
+        env->fpus &= ~0x400;  /* C2 <-- 0 */
+        /* the above code is for |arg| < 2**53 only */
+    }
+}
+
+void helper_fcos(void)
+{
+    double fptemp = floatx80_to_double(ST0);
+
+    if ((fptemp > MAXTAN) || (fptemp < -MAXTAN)) {
+        env->fpus |= 0x400;
+    } else {
+        ST0 = double_to_floatx80(cos(fptemp));
+        env->fpus &= ~0x400;  /* C2 <-- 0 */
+        /* the above code is for |arg| < 2**63 only */
+    }
+}
+
+void helper_fxam_ST0(void)
+{
+    CPU_LDoubleU temp;
+    int expdif;
+
+    temp.d = ST0;
+
+    env->fpus &= ~0x4700; /* (C3,C2,C1,C0) <-- 0000 */
+    if (SIGND(temp)) {
+        env->fpus |= 0x200; /* C1 <-- 1 */
+    }
+
+    /* XXX: test fptags too */
+    expdif = EXPD(temp);
+    if (expdif == MAXEXPD) {
+        if (MANTD(temp) == 0x8000000000000000ULL) {
+            env->fpus |= 0x500; /* Infinity */
+        } else {
+            env->fpus |= 0x100; /* NaN */
+        }
+    } else if (expdif == 0) {
+        if (MANTD(temp) == 0) {
+            env->fpus |=  0x4000; /* Zero */
+        } else {
+            env->fpus |= 0x4400; /* Denormal */
+        }
+    } else {
+        env->fpus |= 0x400;
+    }
+}
+
+void helper_fstenv(target_ulong ptr, int data32)
+{
+    int fpus, fptag, exp, i;
+    uint64_t mant;
+    CPU_LDoubleU tmp;
+
+    fpus = (env->fpus & ~0x3800) | (env->fpstt & 0x7) << 11;
+    fptag = 0;
+    for (i = 7; i >= 0; i--) {
+        fptag <<= 2;
+        if (env->fptags[i]) {
+            fptag |= 3;
+        } else {
+            tmp.d = env->fpregs[i].d;
+            exp = EXPD(tmp);
+            mant = MANTD(tmp);
+            if (exp == 0 && mant == 0) {
+                /* zero */
+                fptag |= 1;
+            } else if (exp == 0 || exp == MAXEXPD
+                       || (mant & (1LL << 63)) == 0) {
+                /* NaNs, infinity, denormal */
+                fptag |= 2;
+            }
+        }
+    }
+    if (data32) {
+        /* 32 bit */
+        stl(ptr, env->fpuc);
+        stl(ptr + 4, fpus);
+        stl(ptr + 8, fptag);
+        stl(ptr + 12, 0); /* fpip */
+        stl(ptr + 16, 0); /* fpcs */
+        stl(ptr + 20, 0); /* fpoo */
+        stl(ptr + 24, 0); /* fpos */
+    } else {
+        /* 16 bit */
+        stw(ptr, env->fpuc);
+        stw(ptr + 2, fpus);
+        stw(ptr + 4, fptag);
+        stw(ptr + 6, 0);
+        stw(ptr + 8, 0);
+        stw(ptr + 10, 0);
+        stw(ptr + 12, 0);
+    }
+}
+
+void helper_fldenv(target_ulong ptr, int data32)
+{
+    int i, fpus, fptag;
+
+    if (data32) {
+        env->fpuc = lduw(ptr);
+        fpus = lduw(ptr + 4);
+        fptag = lduw(ptr + 8);
+    } else {
+        env->fpuc = lduw(ptr);
+        fpus = lduw(ptr + 2);
+        fptag = lduw(ptr + 4);
+    }
+    env->fpstt = (fpus >> 11) & 7;
+    env->fpus = fpus & ~0x3800;
+    for (i = 0; i < 8; i++) {
+        env->fptags[i] = ((fptag & 3) == 3);
+        fptag >>= 2;
+    }
+}
+
+void helper_fsave(target_ulong ptr, int data32)
+{
+    floatx80 tmp;
+    int i;
+
+    helper_fstenv(ptr, data32);
+
+    ptr += (14 << data32);
+    for (i = 0; i < 8; i++) {
+        tmp = ST(i);
+        helper_fstt(tmp, ptr);
+        ptr += 10;
+    }
+
+    /* fninit */
+    env->fpus = 0;
+    env->fpstt = 0;
+    env->fpuc = 0x37f;
+    env->fptags[0] = 1;
+    env->fptags[1] = 1;
+    env->fptags[2] = 1;
+    env->fptags[3] = 1;
+    env->fptags[4] = 1;
+    env->fptags[5] = 1;
+    env->fptags[6] = 1;
+    env->fptags[7] = 1;
+}
+
+void helper_frstor(target_ulong ptr, int data32)
+{
+    floatx80 tmp;
+    int i;
+
+    helper_fldenv(ptr, data32);
+    ptr += (14 << data32);
+
+    for (i = 0; i < 8; i++) {
+        tmp = helper_fldt(ptr);
+        ST(i) = tmp;
+        ptr += 10;
+    }
+}
+
+#if defined(CONFIG_USER_ONLY)
+void cpu_x86_fsave(CPUX86State *s, target_ulong ptr, int data32)
+{
+    CPUX86State *saved_env;
+
+    saved_env = env;
+    env = s;
+
+    helper_fsave(ptr, data32);
+
+    env = saved_env;
+}
+
+void cpu_x86_frstor(CPUX86State *s, target_ulong ptr, int data32)
+{
+    CPUX86State *saved_env;
+
+    saved_env = env;
+    env = s;
+
+    helper_frstor(ptr, data32);
+
+    env = saved_env;
+}
+#endif
+
+void helper_fxsave(target_ulong ptr, int data64)
+{
+    int fpus, fptag, i, nb_xmm_regs;
+    floatx80 tmp;
+    target_ulong addr;
+
+    /* The operand must be 16 byte aligned */
+    if (ptr & 0xf) {
+        raise_exception(env, EXCP0D_GPF);
+    }
+
+    fpus = (env->fpus & ~0x3800) | (env->fpstt & 0x7) << 11;
+    fptag = 0;
+    for (i = 0; i < 8; i++) {
+        fptag |= (env->fptags[i] << i);
+    }
+    stw(ptr, env->fpuc);
+    stw(ptr + 2, fpus);
+    stw(ptr + 4, fptag ^ 0xff);
+#ifdef TARGET_X86_64
+    if (data64) {
+        stq(ptr + 0x08, 0); /* rip */
+        stq(ptr + 0x10, 0); /* rdp */
+    } else
+#endif
+    {
+        stl(ptr + 0x08, 0); /* eip */
+        stl(ptr + 0x0c, 0); /* sel  */
+        stl(ptr + 0x10, 0); /* dp */
+        stl(ptr + 0x14, 0); /* sel  */
+    }
+
+    addr = ptr + 0x20;
+    for (i = 0; i < 8; i++) {
+        tmp = ST(i);
+        helper_fstt(tmp, addr);
+        addr += 16;
+    }
+
+    if (env->cr[4] & CR4_OSFXSR_MASK) {
+        /* XXX: finish it */
+        stl(ptr + 0x18, env->mxcsr); /* mxcsr */
+        stl(ptr + 0x1c, 0x0000ffff); /* mxcsr_mask */
+        if (env->hflags & HF_CS64_MASK) {
+            nb_xmm_regs = 16;
+        } else {
+            nb_xmm_regs = 8;
+        }
+        addr = ptr + 0xa0;
+        /* Fast FXSAVE leaves out the XMM registers */
+        if (!(env->efer & MSR_EFER_FFXSR)
+            || (env->hflags & HF_CPL_MASK)
+            || !(env->hflags & HF_LMA_MASK)) {
+            for (i = 0; i < nb_xmm_regs; i++) {
+                stq(addr, env->xmm_regs[i].XMM_Q(0));
+                stq(addr + 8, env->xmm_regs[i].XMM_Q(1));
+                addr += 16;
+            }
+        }
+    }
+}
+
+void helper_fxrstor(target_ulong ptr, int data64)
+{
+    int i, fpus, fptag, nb_xmm_regs;
+    floatx80 tmp;
+    target_ulong addr;
+
+    /* The operand must be 16 byte aligned */
+    if (ptr & 0xf) {
+        raise_exception(env, EXCP0D_GPF);
+    }
+
+    env->fpuc = lduw(ptr);
+    fpus = lduw(ptr + 2);
+    fptag = lduw(ptr + 4);
+    env->fpstt = (fpus >> 11) & 7;
+    env->fpus = fpus & ~0x3800;
+    fptag ^= 0xff;
+    for (i = 0; i < 8; i++) {
+        env->fptags[i] = ((fptag >> i) & 1);
+    }
+
+    addr = ptr + 0x20;
+    for (i = 0; i < 8; i++) {
+        tmp = helper_fldt(addr);
+        ST(i) = tmp;
+        addr += 16;
+    }
+
+    if (env->cr[4] & CR4_OSFXSR_MASK) {
+        /* XXX: finish it */
+        env->mxcsr = ldl(ptr + 0x18);
+        /* ldl(ptr + 0x1c); */
+        if (env->hflags & HF_CS64_MASK) {
+            nb_xmm_regs = 16;
+        } else {
+            nb_xmm_regs = 8;
+        }
+        addr = ptr + 0xa0;
+        /* Fast FXRESTORE leaves out the XMM registers */
+        if (!(env->efer & MSR_EFER_FFXSR)
+            || (env->hflags & HF_CPL_MASK)
+            || !(env->hflags & HF_LMA_MASK)) {
+            for (i = 0; i < nb_xmm_regs; i++) {
+                env->xmm_regs[i].XMM_Q(0) = ldq(addr);
+                env->xmm_regs[i].XMM_Q(1) = ldq(addr + 8);
+                addr += 16;
+            }
+        }
+    }
+}
+
+void cpu_get_fp80(uint64_t *pmant, uint16_t *pexp, floatx80 f)
+{
+    CPU_LDoubleU temp;
+
+    temp.d = f;
+    *pmant = temp.l.lower;
+    *pexp = temp.l.upper;
+}
+
+floatx80 cpu_set_fp80(uint64_t mant, uint16_t upper)
+{
+    CPU_LDoubleU temp;
+
+    temp.l.upper = upper;
+    temp.l.lower = mant;
+    return temp.d;
+}
+
+/* MMX/SSE */
+/* XXX: optimize by storing fptt and fptags in the static cpu state */
+
+#define SSE_DAZ             0x0040
+#define SSE_RC_MASK         0x6000
+#define SSE_RC_NEAR         0x0000
+#define SSE_RC_DOWN         0x2000
+#define SSE_RC_UP           0x4000
+#define SSE_RC_CHOP         0x6000
+#define SSE_FZ              0x8000
+
+static void update_sse_status(void)
+{
+    int rnd_type;
+
+    /* set rounding mode */
+    switch (env->mxcsr & SSE_RC_MASK) {
+    default:
+    case SSE_RC_NEAR:
+        rnd_type = float_round_nearest_even;
+        break;
+    case SSE_RC_DOWN:
+        rnd_type = float_round_down;
+        break;
+    case SSE_RC_UP:
+        rnd_type = float_round_up;
+        break;
+    case SSE_RC_CHOP:
+        rnd_type = float_round_to_zero;
+        break;
+    }
+    set_float_rounding_mode(rnd_type, &env->sse_status);
+
+    /* set denormals are zero */
+    set_flush_inputs_to_zero((env->mxcsr & SSE_DAZ) ? 1 : 0, &env->sse_status);
+
+    /* set flush to zero */
+    set_flush_to_zero((env->mxcsr & SSE_FZ) ? 1 : 0, &env->fp_status);
+}
+
+void helper_ldmxcsr(uint32_t val)
+{
+    env->mxcsr = val;
+    update_sse_status();
+}
+
+void helper_enter_mmx(void)
+{
+    env->fpstt = 0;
+    *(uint32_t *)(env->fptags) = 0;
+    *(uint32_t *)(env->fptags + 4) = 0;
+}
+
+void helper_emms(void)
+{
+    /* set to empty state */
+    *(uint32_t *)(env->fptags) = 0x01010101;
+    *(uint32_t *)(env->fptags + 4) = 0x01010101;
+}
+
+/* XXX: suppress */
+void helper_movq(void *d, void *s)
+{
+    *(uint64_t *)d = *(uint64_t *)s;
+}
+
+#define SHIFT 0
+#include "ops_sse.h"
+
+#define SHIFT 1
+#include "ops_sse.h"
diff --git a/target-i386/op_helper.c b/target-i386/op_helper.c
index 8625936..3b77972 100644
--- a/target-i386/op_helper.c
+++ b/target-i386/op_helper.c
@@ -17,7 +17,6 @@
  * License along with this library; if not, see <http://www.gnu.org/licenses/>.
  */
 
-#include <math.h>
 #include "cpu.h"
 #include "dyngen-exec.h"
 #include "host-utils.h"
@@ -52,64 +51,6 @@ static inline target_long lshift(target_long x, int n)
     }
 }
 
-#define FPU_RC_MASK         0xc00
-#define FPU_RC_NEAR         0x000
-#define FPU_RC_DOWN         0x400
-#define FPU_RC_UP           0x800
-#define FPU_RC_CHOP         0xc00
-
-#define MAXTAN 9223372036854775808.0
-
-/* the following deal with x86 long double-precision numbers */
-#define MAXEXPD 0x7fff
-#define EXPBIAS 16383
-#define EXPD(fp)        (fp.l.upper & 0x7fff)
-#define SIGND(fp)       ((fp.l.upper) & 0x8000)
-#define MANTD(fp)       (fp.l.lower)
-#define BIASEXPONENT(fp) fp.l.upper = (fp.l.upper & ~(0x7fff)) | EXPBIAS
-
-static inline void fpush(void)
-{
-    env->fpstt = (env->fpstt - 1) & 7;
-    env->fptags[env->fpstt] = 0; /* validate stack entry */
-}
-
-static inline void fpop(void)
-{
-    env->fptags[env->fpstt] = 1; /* invalidate stack entry */
-    env->fpstt = (env->fpstt + 1) & 7;
-}
-
-static inline floatx80 helper_fldt(target_ulong ptr)
-{
-    CPU_LDoubleU temp;
-
-    temp.l.lower = ldq(ptr);
-    temp.l.upper = lduw(ptr + 8);
-    return temp.d;
-}
-
-static inline void helper_fstt(floatx80 f, target_ulong ptr)
-{
-    CPU_LDoubleU temp;
-
-    temp.d = f;
-    stq(ptr, temp.l.lower);
-    stw(ptr + 8, temp.l.upper);
-}
-
-#define FPUS_IE (1 << 0)
-#define FPUS_DE (1 << 1)
-#define FPUS_ZE (1 << 2)
-#define FPUS_OE (1 << 3)
-#define FPUS_UE (1 << 4)
-#define FPUS_PE (1 << 5)
-#define FPUS_SF (1 << 6)
-#define FPUS_SE (1 << 7)
-#define FPUS_B  (1 << 15)
-
-#define FPUC_EM 0x3f
-
 static inline uint32_t compute_eflags(void)
 {
     return env->eflags | helper_cc_compute_all(CC_OP) | (DF & DF_MASK);
@@ -189,10 +130,6 @@ static const uint8_t rclb_table[32] = {
     6, 7, 8, 0, 1, 2, 3, 4,
 };
 
-#define floatx80_lg2 make_floatx80(0x3ffd, 0x9a209a84fbcff799LL)
-#define floatx80_l2e make_floatx80(0x3fff, 0xb8aa3b295c17f0bcLL)
-#define floatx80_l2t make_floatx80(0x4000, 0xd49a784bcd1b8afeLL)
-
 /* broken thread support */
 
 static spinlock_t global_cpu_lock = SPIN_LOCK_UNLOCKED;
@@ -3750,993 +3687,6 @@ void helper_verw(target_ulong selector1)
     CC_SRC = eflags | CC_Z;
 }
 
-/* x87 FPU helpers */
-
-static inline double floatx80_to_double(floatx80 a)
-{
-    union {
-        float64 f64;
-        double d;
-    } u;
-
-    u.f64 = floatx80_to_float64(a, &env->fp_status);
-    return u.d;
-}
-
-static inline floatx80 double_to_floatx80(double a)
-{
-    union {
-        float64 f64;
-        double d;
-    } u;
-
-    u.d = a;
-    return float64_to_floatx80(u.f64, &env->fp_status);
-}
-
-static void fpu_set_exception(int mask)
-{
-    env->fpus |= mask;
-    if (env->fpus & (~env->fpuc & FPUC_EM)) {
-        env->fpus |= FPUS_SE | FPUS_B;
-    }
-}
-
-static inline floatx80 helper_fdiv(floatx80 a, floatx80 b)
-{
-    if (floatx80_is_zero(b)) {
-        fpu_set_exception(FPUS_ZE);
-    }
-    return floatx80_div(a, b, &env->fp_status);
-}
-
-static void fpu_raise_exception(void)
-{
-    if (env->cr[0] & CR0_NE_MASK) {
-        raise_exception(env, EXCP10_COPR);
-    }
-#if !defined(CONFIG_USER_ONLY)
-    else {
-        cpu_set_ferr(env);
-    }
-#endif
-}
-
-void helper_flds_FT0(uint32_t val)
-{
-    union {
-        float32 f;
-        uint32_t i;
-    } u;
-
-    u.i = val;
-    FT0 = float32_to_floatx80(u.f, &env->fp_status);
-}
-
-void helper_fldl_FT0(uint64_t val)
-{
-    union {
-        float64 f;
-        uint64_t i;
-    } u;
-
-    u.i = val;
-    FT0 = float64_to_floatx80(u.f, &env->fp_status);
-}
-
-void helper_fildl_FT0(int32_t val)
-{
-    FT0 = int32_to_floatx80(val, &env->fp_status);
-}
-
-void helper_flds_ST0(uint32_t val)
-{
-    int new_fpstt;
-    union {
-        float32 f;
-        uint32_t i;
-    } u;
-
-    new_fpstt = (env->fpstt - 1) & 7;
-    u.i = val;
-    env->fpregs[new_fpstt].d = float32_to_floatx80(u.f, &env->fp_status);
-    env->fpstt = new_fpstt;
-    env->fptags[new_fpstt] = 0; /* validate stack entry */
-}
-
-void helper_fldl_ST0(uint64_t val)
-{
-    int new_fpstt;
-    union {
-        float64 f;
-        uint64_t i;
-    } u;
-
-    new_fpstt = (env->fpstt - 1) & 7;
-    u.i = val;
-    env->fpregs[new_fpstt].d = float64_to_floatx80(u.f, &env->fp_status);
-    env->fpstt = new_fpstt;
-    env->fptags[new_fpstt] = 0; /* validate stack entry */
-}
-
-void helper_fildl_ST0(int32_t val)
-{
-    int new_fpstt;
-
-    new_fpstt = (env->fpstt - 1) & 7;
-    env->fpregs[new_fpstt].d = int32_to_floatx80(val, &env->fp_status);
-    env->fpstt = new_fpstt;
-    env->fptags[new_fpstt] = 0; /* validate stack entry */
-}
-
-void helper_fildll_ST0(int64_t val)
-{
-    int new_fpstt;
-
-    new_fpstt = (env->fpstt - 1) & 7;
-    env->fpregs[new_fpstt].d = int64_to_floatx80(val, &env->fp_status);
-    env->fpstt = new_fpstt;
-    env->fptags[new_fpstt] = 0; /* validate stack entry */
-}
-
-uint32_t helper_fsts_ST0(void)
-{
-    union {
-        float32 f;
-        uint32_t i;
-    } u;
-
-    u.f = floatx80_to_float32(ST0, &env->fp_status);
-    return u.i;
-}
-
-uint64_t helper_fstl_ST0(void)
-{
-    union {
-        float64 f;
-        uint64_t i;
-    } u;
-
-    u.f = floatx80_to_float64(ST0, &env->fp_status);
-    return u.i;
-}
-
-int32_t helper_fist_ST0(void)
-{
-    int32_t val;
-
-    val = floatx80_to_int32(ST0, &env->fp_status);
-    if (val != (int16_t)val) {
-        val = -32768;
-    }
-    return val;
-}
-
-int32_t helper_fistl_ST0(void)
-{
-    int32_t val;
-
-    val = floatx80_to_int32(ST0, &env->fp_status);
-    return val;
-}
-
-int64_t helper_fistll_ST0(void)
-{
-    int64_t val;
-
-    val = floatx80_to_int64(ST0, &env->fp_status);
-    return val;
-}
-
-int32_t helper_fistt_ST0(void)
-{
-    int32_t val;
-
-    val = floatx80_to_int32_round_to_zero(ST0, &env->fp_status);
-    if (val != (int16_t)val) {
-        val = -32768;
-    }
-    return val;
-}
-
-int32_t helper_fisttl_ST0(void)
-{
-    int32_t val;
-
-    val = floatx80_to_int32_round_to_zero(ST0, &env->fp_status);
-    return val;
-}
-
-int64_t helper_fisttll_ST0(void)
-{
-    int64_t val;
-
-    val = floatx80_to_int64_round_to_zero(ST0, &env->fp_status);
-    return val;
-}
-
-void helper_fldt_ST0(target_ulong ptr)
-{
-    int new_fpstt;
-
-    new_fpstt = (env->fpstt - 1) & 7;
-    env->fpregs[new_fpstt].d = helper_fldt(ptr);
-    env->fpstt = new_fpstt;
-    env->fptags[new_fpstt] = 0; /* validate stack entry */
-}
-
-void helper_fstt_ST0(target_ulong ptr)
-{
-    helper_fstt(ST0, ptr);
-}
-
-void helper_fpush(void)
-{
-    fpush();
-}
-
-void helper_fpop(void)
-{
-    fpop();
-}
-
-void helper_fdecstp(void)
-{
-    env->fpstt = (env->fpstt - 1) & 7;
-    env->fpus &= ~0x4700;
-}
-
-void helper_fincstp(void)
-{
-    env->fpstt = (env->fpstt + 1) & 7;
-    env->fpus &= ~0x4700;
-}
-
-/* FPU move */
-
-void helper_ffree_STN(int st_index)
-{
-    env->fptags[(env->fpstt + st_index) & 7] = 1;
-}
-
-void helper_fmov_ST0_FT0(void)
-{
-    ST0 = FT0;
-}
-
-void helper_fmov_FT0_STN(int st_index)
-{
-    FT0 = ST(st_index);
-}
-
-void helper_fmov_ST0_STN(int st_index)
-{
-    ST0 = ST(st_index);
-}
-
-void helper_fmov_STN_ST0(int st_index)
-{
-    ST(st_index) = ST0;
-}
-
-void helper_fxchg_ST0_STN(int st_index)
-{
-    floatx80 tmp;
-
-    tmp = ST(st_index);
-    ST(st_index) = ST0;
-    ST0 = tmp;
-}
-
-/* FPU operations */
-
-static const int fcom_ccval[4] = {0x0100, 0x4000, 0x0000, 0x4500};
-
-void helper_fcom_ST0_FT0(void)
-{
-    int ret;
-
-    ret = floatx80_compare(ST0, FT0, &env->fp_status);
-    env->fpus = (env->fpus & ~0x4500) | fcom_ccval[ret + 1];
-}
-
-void helper_fucom_ST0_FT0(void)
-{
-    int ret;
-
-    ret = floatx80_compare_quiet(ST0, FT0, &env->fp_status);
-    env->fpus = (env->fpus & ~0x4500) | fcom_ccval[ret + 1];
-}
-
-static const int fcomi_ccval[4] = {CC_C, CC_Z, 0, CC_Z | CC_P | CC_C};
-
-void helper_fcomi_ST0_FT0(void)
-{
-    int eflags;
-    int ret;
-
-    ret = floatx80_compare(ST0, FT0, &env->fp_status);
-    eflags = helper_cc_compute_all(CC_OP);
-    eflags = (eflags & ~(CC_Z | CC_P | CC_C)) | fcomi_ccval[ret + 1];
-    CC_SRC = eflags;
-}
-
-void helper_fucomi_ST0_FT0(void)
-{
-    int eflags;
-    int ret;
-
-    ret = floatx80_compare_quiet(ST0, FT0, &env->fp_status);
-    eflags = helper_cc_compute_all(CC_OP);
-    eflags = (eflags & ~(CC_Z | CC_P | CC_C)) | fcomi_ccval[ret + 1];
-    CC_SRC = eflags;
-}
-
-void helper_fadd_ST0_FT0(void)
-{
-    ST0 = floatx80_add(ST0, FT0, &env->fp_status);
-}
-
-void helper_fmul_ST0_FT0(void)
-{
-    ST0 = floatx80_mul(ST0, FT0, &env->fp_status);
-}
-
-void helper_fsub_ST0_FT0(void)
-{
-    ST0 = floatx80_sub(ST0, FT0, &env->fp_status);
-}
-
-void helper_fsubr_ST0_FT0(void)
-{
-    ST0 = floatx80_sub(FT0, ST0, &env->fp_status);
-}
-
-void helper_fdiv_ST0_FT0(void)
-{
-    ST0 = helper_fdiv(ST0, FT0);
-}
-
-void helper_fdivr_ST0_FT0(void)
-{
-    ST0 = helper_fdiv(FT0, ST0);
-}
-
-/* fp operations between STN and ST0 */
-
-void helper_fadd_STN_ST0(int st_index)
-{
-    ST(st_index) = floatx80_add(ST(st_index), ST0, &env->fp_status);
-}
-
-void helper_fmul_STN_ST0(int st_index)
-{
-    ST(st_index) = floatx80_mul(ST(st_index), ST0, &env->fp_status);
-}
-
-void helper_fsub_STN_ST0(int st_index)
-{
-    ST(st_index) = floatx80_sub(ST(st_index), ST0, &env->fp_status);
-}
-
-void helper_fsubr_STN_ST0(int st_index)
-{
-    ST(st_index) = floatx80_sub(ST0, ST(st_index), &env->fp_status);
-}
-
-void helper_fdiv_STN_ST0(int st_index)
-{
-    floatx80 *p;
-
-    p = &ST(st_index);
-    *p = helper_fdiv(*p, ST0);
-}
-
-void helper_fdivr_STN_ST0(int st_index)
-{
-    floatx80 *p;
-
-    p = &ST(st_index);
-    *p = helper_fdiv(ST0, *p);
-}
-
-/* misc FPU operations */
-void helper_fchs_ST0(void)
-{
-    ST0 = floatx80_chs(ST0);
-}
-
-void helper_fabs_ST0(void)
-{
-    ST0 = floatx80_abs(ST0);
-}
-
-void helper_fld1_ST0(void)
-{
-    ST0 = floatx80_one;
-}
-
-void helper_fldl2t_ST0(void)
-{
-    ST0 = floatx80_l2t;
-}
-
-void helper_fldl2e_ST0(void)
-{
-    ST0 = floatx80_l2e;
-}
-
-void helper_fldpi_ST0(void)
-{
-    ST0 = floatx80_pi;
-}
-
-void helper_fldlg2_ST0(void)
-{
-    ST0 = floatx80_lg2;
-}
-
-void helper_fldln2_ST0(void)
-{
-    ST0 = floatx80_ln2;
-}
-
-void helper_fldz_ST0(void)
-{
-    ST0 = floatx80_zero;
-}
-
-void helper_fldz_FT0(void)
-{
-    FT0 = floatx80_zero;
-}
-
-uint32_t helper_fnstsw(void)
-{
-    return (env->fpus & ~0x3800) | (env->fpstt & 0x7) << 11;
-}
-
-uint32_t helper_fnstcw(void)
-{
-    return env->fpuc;
-}
-
-static void update_fp_status(void)
-{
-    int rnd_type;
-
-    /* set rounding mode */
-    switch (env->fpuc & FPU_RC_MASK) {
-    default:
-    case FPU_RC_NEAR:
-        rnd_type = float_round_nearest_even;
-        break;
-    case FPU_RC_DOWN:
-        rnd_type = float_round_down;
-        break;
-    case FPU_RC_UP:
-        rnd_type = float_round_up;
-        break;
-    case FPU_RC_CHOP:
-        rnd_type = float_round_to_zero;
-        break;
-    }
-    set_float_rounding_mode(rnd_type, &env->fp_status);
-    switch ((env->fpuc >> 8) & 3) {
-    case 0:
-        rnd_type = 32;
-        break;
-    case 2:
-        rnd_type = 64;
-        break;
-    case 3:
-    default:
-        rnd_type = 80;
-        break;
-    }
-    set_floatx80_rounding_precision(rnd_type, &env->fp_status);
-}
-
-void helper_fldcw(uint32_t val)
-{
-    env->fpuc = val;
-    update_fp_status();
-}
-
-void helper_fclex(void)
-{
-    env->fpus &= 0x7f00;
-}
-
-void helper_fwait(void)
-{
-    if (env->fpus & FPUS_SE) {
-        fpu_raise_exception();
-    }
-}
-
-void helper_fninit(void)
-{
-    env->fpus = 0;
-    env->fpstt = 0;
-    env->fpuc = 0x37f;
-    env->fptags[0] = 1;
-    env->fptags[1] = 1;
-    env->fptags[2] = 1;
-    env->fptags[3] = 1;
-    env->fptags[4] = 1;
-    env->fptags[5] = 1;
-    env->fptags[6] = 1;
-    env->fptags[7] = 1;
-}
-
-/* BCD ops */
-
-void helper_fbld_ST0(target_ulong ptr)
-{
-    floatx80 tmp;
-    uint64_t val;
-    unsigned int v;
-    int i;
-
-    val = 0;
-    for (i = 8; i >= 0; i--) {
-        v = ldub(ptr + i);
-        val = (val * 100) + ((v >> 4) * 10) + (v & 0xf);
-    }
-    tmp = int64_to_floatx80(val, &env->fp_status);
-    if (ldub(ptr + 9) & 0x80) {
-        floatx80_chs(tmp);
-    }
-    fpush();
-    ST0 = tmp;
-}
-
-void helper_fbst_ST0(target_ulong ptr)
-{
-    int v;
-    target_ulong mem_ref, mem_end;
-    int64_t val;
-
-    val = floatx80_to_int64(ST0, &env->fp_status);
-    mem_ref = ptr;
-    mem_end = mem_ref + 9;
-    if (val < 0) {
-        stb(mem_end, 0x80);
-        val = -val;
-    } else {
-        stb(mem_end, 0x00);
-    }
-    while (mem_ref < mem_end) {
-        if (val == 0) {
-            break;
-        }
-        v = val % 100;
-        val = val / 100;
-        v = ((v / 10) << 4) | (v % 10);
-        stb(mem_ref++, v);
-    }
-    while (mem_ref < mem_end) {
-        stb(mem_ref++, 0);
-    }
-}
-
-void helper_f2xm1(void)
-{
-    double val = floatx80_to_double(ST0);
-
-    val = pow(2.0, val) - 1.0;
-    ST0 = double_to_floatx80(val);
-}
-
-void helper_fyl2x(void)
-{
-    double fptemp = floatx80_to_double(ST0);
-
-    if (fptemp > 0.0) {
-        fptemp = log(fptemp) / log(2.0); /* log2(ST) */
-        fptemp *= floatx80_to_double(ST1);
-        ST1 = double_to_floatx80(fptemp);
-        fpop();
-    } else {
-        env->fpus &= ~0x4700;
-        env->fpus |= 0x400;
-    }
-}
-
-void helper_fptan(void)
-{
-    double fptemp = floatx80_to_double(ST0);
-
-    if ((fptemp > MAXTAN) || (fptemp < -MAXTAN)) {
-        env->fpus |= 0x400;
-    } else {
-        fptemp = tan(fptemp);
-        ST0 = double_to_floatx80(fptemp);
-        fpush();
-        ST0 = floatx80_one;
-        env->fpus &= ~0x400; /* C2 <-- 0 */
-        /* the above code is for |arg| < 2**52 only */
-    }
-}
-
-void helper_fpatan(void)
-{
-    double fptemp, fpsrcop;
-
-    fpsrcop = floatx80_to_double(ST1);
-    fptemp = floatx80_to_double(ST0);
-    ST1 = double_to_floatx80(atan2(fpsrcop, fptemp));
-    fpop();
-}
-
-void helper_fxtract(void)
-{
-    CPU_LDoubleU temp;
-
-    temp.d = ST0;
-
-    if (floatx80_is_zero(ST0)) {
-        /* Easy way to generate -inf and raising division by 0 exception */
-        ST0 = floatx80_div(floatx80_chs(floatx80_one), floatx80_zero,
-                           &env->fp_status);
-        fpush();
-        ST0 = temp.d;
-    } else {
-        int expdif;
-
-        expdif = EXPD(temp) - EXPBIAS;
-        /* DP exponent bias */
-        ST0 = int32_to_floatx80(expdif, &env->fp_status);
-        fpush();
-        BIASEXPONENT(temp);
-        ST0 = temp.d;
-    }
-}
-
-void helper_fprem1(void)
-{
-    double st0, st1, dblq, fpsrcop, fptemp;
-    CPU_LDoubleU fpsrcop1, fptemp1;
-    int expdif;
-    signed long long int q;
-
-    st0 = floatx80_to_double(ST0);
-    st1 = floatx80_to_double(ST1);
-
-    if (isinf(st0) || isnan(st0) || isnan(st1) || (st1 == 0.0)) {
-        ST0 = double_to_floatx80(0.0 / 0.0); /* NaN */
-        env->fpus &= ~0x4700; /* (C3,C2,C1,C0) <-- 0000 */
-        return;
-    }
-
-    fpsrcop = st0;
-    fptemp = st1;
-    fpsrcop1.d = ST0;
-    fptemp1.d = ST1;
-    expdif = EXPD(fpsrcop1) - EXPD(fptemp1);
-
-    if (expdif < 0) {
-        /* optimisation? taken from the AMD docs */
-        env->fpus &= ~0x4700; /* (C3,C2,C1,C0) <-- 0000 */
-        /* ST0 is unchanged */
-        return;
-    }
-
-    if (expdif < 53) {
-        dblq = fpsrcop / fptemp;
-        /* round dblq towards nearest integer */
-        dblq = rint(dblq);
-        st0 = fpsrcop - fptemp * dblq;
-
-        /* convert dblq to q by truncating towards zero */
-        if (dblq < 0.0) {
-            q = (signed long long int)(-dblq);
-        } else {
-            q = (signed long long int)dblq;
-        }
-
-        env->fpus &= ~0x4700; /* (C3,C2,C1,C0) <-- 0000 */
-        /* (C0,C3,C1) <-- (q2,q1,q0) */
-        env->fpus |= (q & 0x4) << (8 - 2);  /* (C0) <-- q2 */
-        env->fpus |= (q & 0x2) << (14 - 1); /* (C3) <-- q1 */
-        env->fpus |= (q & 0x1) << (9 - 0);  /* (C1) <-- q0 */
-    } else {
-        env->fpus |= 0x400;  /* C2 <-- 1 */
-        fptemp = pow(2.0, expdif - 50);
-        fpsrcop = (st0 / st1) / fptemp;
-        /* fpsrcop = integer obtained by chopping */
-        fpsrcop = (fpsrcop < 0.0) ?
-                  -(floor(fabs(fpsrcop))) : floor(fpsrcop);
-        st0 -= (st1 * fpsrcop * fptemp);
-    }
-    ST0 = double_to_floatx80(st0);
-}
-
-void helper_fprem(void)
-{
-    double st0, st1, dblq, fpsrcop, fptemp;
-    CPU_LDoubleU fpsrcop1, fptemp1;
-    int expdif;
-    signed long long int q;
-
-    st0 = floatx80_to_double(ST0);
-    st1 = floatx80_to_double(ST1);
-
-    if (isinf(st0) || isnan(st0) || isnan(st1) || (st1 == 0.0)) {
-        ST0 = double_to_floatx80(0.0 / 0.0); /* NaN */
-        env->fpus &= ~0x4700; /* (C3,C2,C1,C0) <-- 0000 */
-        return;
-    }
-
-    fpsrcop = st0;
-    fptemp = st1;
-    fpsrcop1.d = ST0;
-    fptemp1.d = ST1;
-    expdif = EXPD(fpsrcop1) - EXPD(fptemp1);
-
-    if (expdif < 0) {
-        /* optimisation? taken from the AMD docs */
-        env->fpus &= ~0x4700; /* (C3,C2,C1,C0) <-- 0000 */
-        /* ST0 is unchanged */
-        return;
-    }
-
-    if (expdif < 53) {
-        dblq = fpsrcop / fptemp; /* ST0 / ST1 */
-        /* round dblq towards zero */
-        dblq = (dblq < 0.0) ? ceil(dblq) : floor(dblq);
-        st0 = fpsrcop - fptemp * dblq; /* fpsrcop is ST0 */
-
-        /* convert dblq to q by truncating towards zero */
-        if (dblq < 0.0) {
-            q = (signed long long int)(-dblq);
-        } else {
-            q = (signed long long int)dblq;
-        }
-
-        env->fpus &= ~0x4700; /* (C3,C2,C1,C0) <-- 0000 */
-        /* (C0,C3,C1) <-- (q2,q1,q0) */
-        env->fpus |= (q & 0x4) << (8 - 2);  /* (C0) <-- q2 */
-        env->fpus |= (q & 0x2) << (14 - 1); /* (C3) <-- q1 */
-        env->fpus |= (q & 0x1) << (9 - 0);  /* (C1) <-- q0 */
-    } else {
-        int N = 32 + (expdif % 32); /* as per AMD docs */
-
-        env->fpus |= 0x400;  /* C2 <-- 1 */
-        fptemp = pow(2.0, (double)(expdif - N));
-        fpsrcop = (st0 / st1) / fptemp;
-        /* fpsrcop = integer obtained by chopping */
-        fpsrcop = (fpsrcop < 0.0) ?
-                  -(floor(fabs(fpsrcop))) : floor(fpsrcop);
-        st0 -= (st1 * fpsrcop * fptemp);
-    }
-    ST0 = double_to_floatx80(st0);
-}
-
-void helper_fyl2xp1(void)
-{
-    double fptemp = floatx80_to_double(ST0);
-
-    if ((fptemp + 1.0) > 0.0) {
-        fptemp = log(fptemp + 1.0) / log(2.0); /* log2(ST + 1.0) */
-        fptemp *= floatx80_to_double(ST1);
-        ST1 = double_to_floatx80(fptemp);
-        fpop();
-    } else {
-        env->fpus &= ~0x4700;
-        env->fpus |= 0x400;
-    }
-}
-
-void helper_fsqrt(void)
-{
-    if (floatx80_is_neg(ST0)) {
-        env->fpus &= ~0x4700;  /* (C3,C2,C1,C0) <-- 0000 */
-        env->fpus |= 0x400;
-    }
-    ST0 = floatx80_sqrt(ST0, &env->fp_status);
-}
-
-void helper_fsincos(void)
-{
-    double fptemp = floatx80_to_double(ST0);
-
-    if ((fptemp > MAXTAN) || (fptemp < -MAXTAN)) {
-        env->fpus |= 0x400;
-    } else {
-        ST0 = double_to_floatx80(sin(fptemp));
-        fpush();
-        ST0 = double_to_floatx80(cos(fptemp));
-        env->fpus &= ~0x400;  /* C2 <-- 0 */
-        /* the above code is for |arg| < 2**63 only */
-    }
-}
-
-void helper_frndint(void)
-{
-    ST0 = floatx80_round_to_int(ST0, &env->fp_status);
-}
-
-void helper_fscale(void)
-{
-    if (floatx80_is_any_nan(ST1)) {
-        ST0 = ST1;
-    } else {
-        int n = floatx80_to_int32_round_to_zero(ST1, &env->fp_status);
-        ST0 = floatx80_scalbn(ST0, n, &env->fp_status);
-    }
-}
-
-void helper_fsin(void)
-{
-    double fptemp = floatx80_to_double(ST0);
-
-    if ((fptemp > MAXTAN) || (fptemp < -MAXTAN)) {
-        env->fpus |= 0x400;
-    } else {
-        ST0 = double_to_floatx80(sin(fptemp));
-        env->fpus &= ~0x400;  /* C2 <-- 0 */
-        /* the above code is for |arg| < 2**53 only */
-    }
-}
-
-void helper_fcos(void)
-{
-    double fptemp = floatx80_to_double(ST0);
-
-    if ((fptemp > MAXTAN) || (fptemp < -MAXTAN)) {
-        env->fpus |= 0x400;
-    } else {
-        ST0 = double_to_floatx80(cos(fptemp));
-        env->fpus &= ~0x400;  /* C2 <-- 0 */
-        /* the above code is for |arg| < 2**63 only */
-    }
-}
-
-void helper_fxam_ST0(void)
-{
-    CPU_LDoubleU temp;
-    int expdif;
-
-    temp.d = ST0;
-
-    env->fpus &= ~0x4700; /* (C3,C2,C1,C0) <-- 0000 */
-    if (SIGND(temp)) {
-        env->fpus |= 0x200; /* C1 <-- 1 */
-    }
-
-    /* XXX: test fptags too */
-    expdif = EXPD(temp);
-    if (expdif == MAXEXPD) {
-        if (MANTD(temp) == 0x8000000000000000ULL) {
-            env->fpus |= 0x500; /* Infinity */
-        } else {
-            env->fpus |= 0x100; /* NaN */
-        }
-    } else if (expdif == 0) {
-        if (MANTD(temp) == 0) {
-            env->fpus |=  0x4000; /* Zero */
-        } else {
-            env->fpus |= 0x4400; /* Denormal */
-        }
-    } else {
-        env->fpus |= 0x400;
-    }
-}
-
-void helper_fstenv(target_ulong ptr, int data32)
-{
-    int fpus, fptag, exp, i;
-    uint64_t mant;
-    CPU_LDoubleU tmp;
-
-    fpus = (env->fpus & ~0x3800) | (env->fpstt & 0x7) << 11;
-    fptag = 0;
-    for (i = 7; i >= 0; i--) {
-        fptag <<= 2;
-        if (env->fptags[i]) {
-            fptag |= 3;
-        } else {
-            tmp.d = env->fpregs[i].d;
-            exp = EXPD(tmp);
-            mant = MANTD(tmp);
-            if (exp == 0 && mant == 0) {
-                /* zero */
-                fptag |= 1;
-            } else if (exp == 0 || exp == MAXEXPD
-                       || (mant & (1LL << 63)) == 0) {
-                /* NaNs, infinity, denormal */
-                fptag |= 2;
-            }
-        }
-    }
-    if (data32) {
-        /* 32 bit */
-        stl(ptr, env->fpuc);
-        stl(ptr + 4, fpus);
-        stl(ptr + 8, fptag);
-        stl(ptr + 12, 0); /* fpip */
-        stl(ptr + 16, 0); /* fpcs */
-        stl(ptr + 20, 0); /* fpoo */
-        stl(ptr + 24, 0); /* fpos */
-    } else {
-        /* 16 bit */
-        stw(ptr, env->fpuc);
-        stw(ptr + 2, fpus);
-        stw(ptr + 4, fptag);
-        stw(ptr + 6, 0);
-        stw(ptr + 8, 0);
-        stw(ptr + 10, 0);
-        stw(ptr + 12, 0);
-    }
-}
-
-void helper_fldenv(target_ulong ptr, int data32)
-{
-    int i, fpus, fptag;
-
-    if (data32) {
-        env->fpuc = lduw(ptr);
-        fpus = lduw(ptr + 4);
-        fptag = lduw(ptr + 8);
-    } else {
-        env->fpuc = lduw(ptr);
-        fpus = lduw(ptr + 2);
-        fptag = lduw(ptr + 4);
-    }
-    env->fpstt = (fpus >> 11) & 7;
-    env->fpus = fpus & ~0x3800;
-    for (i = 0; i < 8; i++) {
-        env->fptags[i] = ((fptag & 3) == 3);
-        fptag >>= 2;
-    }
-}
-
-void helper_fsave(target_ulong ptr, int data32)
-{
-    floatx80 tmp;
-    int i;
-
-    helper_fstenv(ptr, data32);
-
-    ptr += (14 << data32);
-    for (i = 0; i < 8; i++) {
-        tmp = ST(i);
-        helper_fstt(tmp, ptr);
-        ptr += 10;
-    }
-
-    /* fninit */
-    env->fpus = 0;
-    env->fpstt = 0;
-    env->fpuc = 0x37f;
-    env->fptags[0] = 1;
-    env->fptags[1] = 1;
-    env->fptags[2] = 1;
-    env->fptags[3] = 1;
-    env->fptags[4] = 1;
-    env->fptags[5] = 1;
-    env->fptags[6] = 1;
-    env->fptags[7] = 1;
-}
-
-void helper_frstor(target_ulong ptr, int data32)
-{
-    floatx80 tmp;
-    int i;
-
-    helper_fldenv(ptr, data32);
-    ptr += (14 << data32);
-
-    for (i = 0; i < 8; i++) {
-        tmp = helper_fldt(ptr);
-        ST(i) = tmp;
-        ptr += 10;
-    }
-}
-
-
 #if defined(CONFIG_USER_ONLY)
 void cpu_x86_load_seg(CPUX86State *s, int seg_reg, int selector)
 {
@@ -4753,162 +3703,7 @@ void cpu_x86_load_seg(CPUX86State *s, int seg_reg, int selector)
     }
     env = saved_env;
 }
-
-void cpu_x86_fsave(CPUX86State *s, target_ulong ptr, int data32)
-{
-    CPUX86State *saved_env;
-
-    saved_env = env;
-    env = s;
-
-    helper_fsave(ptr, data32);
-
-    env = saved_env;
-}
-
-void cpu_x86_frstor(CPUX86State *s, target_ulong ptr, int data32)
-{
-    CPUX86State *saved_env;
-
-    saved_env = env;
-    env = s;
-
-    helper_frstor(ptr, data32);
-
-    env = saved_env;
-}
-#endif
-
-void helper_fxsave(target_ulong ptr, int data64)
-{
-    int fpus, fptag, i, nb_xmm_regs;
-    floatx80 tmp;
-    target_ulong addr;
-
-    /* The operand must be 16 byte aligned */
-    if (ptr & 0xf) {
-        raise_exception(env, EXCP0D_GPF);
-    }
-
-    fpus = (env->fpus & ~0x3800) | (env->fpstt & 0x7) << 11;
-    fptag = 0;
-    for (i = 0; i < 8; i++) {
-        fptag |= (env->fptags[i] << i);
-    }
-    stw(ptr, env->fpuc);
-    stw(ptr + 2, fpus);
-    stw(ptr + 4, fptag ^ 0xff);
-#ifdef TARGET_X86_64
-    if (data64) {
-        stq(ptr + 0x08, 0); /* rip */
-        stq(ptr + 0x10, 0); /* rdp */
-    } else
 #endif
-    {
-        stl(ptr + 0x08, 0); /* eip */
-        stl(ptr + 0x0c, 0); /* sel  */
-        stl(ptr + 0x10, 0); /* dp */
-        stl(ptr + 0x14, 0); /* sel  */
-    }
-
-    addr = ptr + 0x20;
-    for (i = 0; i < 8; i++) {
-        tmp = ST(i);
-        helper_fstt(tmp, addr);
-        addr += 16;
-    }
-
-    if (env->cr[4] & CR4_OSFXSR_MASK) {
-        /* XXX: finish it */
-        stl(ptr + 0x18, env->mxcsr); /* mxcsr */
-        stl(ptr + 0x1c, 0x0000ffff); /* mxcsr_mask */
-        if (env->hflags & HF_CS64_MASK) {
-            nb_xmm_regs = 16;
-        } else {
-            nb_xmm_regs = 8;
-        }
-        addr = ptr + 0xa0;
-        /* Fast FXSAVE leaves out the XMM registers */
-        if (!(env->efer & MSR_EFER_FFXSR)
-            || (env->hflags & HF_CPL_MASK)
-            || !(env->hflags & HF_LMA_MASK)) {
-            for (i = 0; i < nb_xmm_regs; i++) {
-                stq(addr, env->xmm_regs[i].XMM_Q(0));
-                stq(addr + 8, env->xmm_regs[i].XMM_Q(1));
-                addr += 16;
-            }
-        }
-    }
-}
-
-void helper_fxrstor(target_ulong ptr, int data64)
-{
-    int i, fpus, fptag, nb_xmm_regs;
-    floatx80 tmp;
-    target_ulong addr;
-
-    /* The operand must be 16 byte aligned */
-    if (ptr & 0xf) {
-        raise_exception(env, EXCP0D_GPF);
-    }
-
-    env->fpuc = lduw(ptr);
-    fpus = lduw(ptr + 2);
-    fptag = lduw(ptr + 4);
-    env->fpstt = (fpus >> 11) & 7;
-    env->fpus = fpus & ~0x3800;
-    fptag ^= 0xff;
-    for (i = 0; i < 8; i++) {
-        env->fptags[i] = ((fptag >> i) & 1);
-    }
-
-    addr = ptr + 0x20;
-    for (i = 0; i < 8; i++) {
-        tmp = helper_fldt(addr);
-        ST(i) = tmp;
-        addr += 16;
-    }
-
-    if (env->cr[4] & CR4_OSFXSR_MASK) {
-        /* XXX: finish it */
-        env->mxcsr = ldl(ptr + 0x18);
-        /* ldl(ptr + 0x1c); */
-        if (env->hflags & HF_CS64_MASK) {
-            nb_xmm_regs = 16;
-        } else {
-            nb_xmm_regs = 8;
-        }
-        addr = ptr + 0xa0;
-        /* Fast FXRESTORE leaves out the XMM registers */
-        if (!(env->efer & MSR_EFER_FFXSR)
-            || (env->hflags & HF_CPL_MASK)
-            || !(env->hflags & HF_LMA_MASK)) {
-            for (i = 0; i < nb_xmm_regs; i++) {
-                env->xmm_regs[i].XMM_Q(0) = ldq(addr);
-                env->xmm_regs[i].XMM_Q(1) = ldq(addr + 8);
-                addr += 16;
-            }
-        }
-    }
-}
-
-void cpu_get_fp80(uint64_t *pmant, uint16_t *pexp, floatx80 f)
-{
-    CPU_LDoubleU temp;
-
-    temp.d = f;
-    *pmant = temp.l.lower;
-    *pexp = temp.l.upper;
-}
-
-floatx80 cpu_set_fp80(uint64_t mant, uint16_t upper)
-{
-    CPU_LDoubleU temp;
-
-    temp.l.upper = upper;
-    temp.l.lower = mant;
-    return temp.d;
-}
 
 #ifdef TARGET_X86_64
 static void add128(uint64_t *plow, uint64_t *phigh, uint64_t a, uint64_t b)
@@ -5919,78 +4714,6 @@ void cpu_vmexit(CPUX86State *nenv, uint32_t exit_code, uint64_t exit_info_1)
 
 #endif
 
-/* MMX/SSE */
-/* XXX: optimize by storing fptt and fptags in the static cpu state */
-
-#define SSE_DAZ             0x0040
-#define SSE_RC_MASK         0x6000
-#define SSE_RC_NEAR         0x0000
-#define SSE_RC_DOWN         0x2000
-#define SSE_RC_UP           0x4000
-#define SSE_RC_CHOP         0x6000
-#define SSE_FZ              0x8000
-
-static void update_sse_status(void)
-{
-    int rnd_type;
-
-    /* set rounding mode */
-    switch (env->mxcsr & SSE_RC_MASK) {
-    default:
-    case SSE_RC_NEAR:
-        rnd_type = float_round_nearest_even;
-        break;
-    case SSE_RC_DOWN:
-        rnd_type = float_round_down;
-        break;
-    case SSE_RC_UP:
-        rnd_type = float_round_up;
-        break;
-    case SSE_RC_CHOP:
-        rnd_type = float_round_to_zero;
-        break;
-    }
-    set_float_rounding_mode(rnd_type, &env->sse_status);
-
-    /* set denormals are zero */
-    set_flush_inputs_to_zero((env->mxcsr & SSE_DAZ) ? 1 : 0, &env->sse_status);
-
-    /* set flush to zero */
-    set_flush_to_zero((env->mxcsr & SSE_FZ) ? 1 : 0, &env->fp_status);
-}
-
-void helper_ldmxcsr(uint32_t val)
-{
-    env->mxcsr = val;
-    update_sse_status();
-}
-
-void helper_enter_mmx(void)
-{
-    env->fpstt = 0;
-    *(uint32_t *)(env->fptags) = 0;
-    *(uint32_t *)(env->fptags + 4) = 0;
-}
-
-void helper_emms(void)
-{
-    /* set to empty state */
-    *(uint32_t *)(env->fptags) = 0x01010101;
-    *(uint32_t *)(env->fptags + 4) = 0x01010101;
-}
-
-/* XXX: suppress */
-void helper_movq(void *d, void *s)
-{
-    *(uint64_t *)d = *(uint64_t *)s;
-}
-
-#define SHIFT 0
-#include "ops_sse.h"
-
-#define SHIFT 1
-#include "ops_sse.h"
-
 #define SHIFT 0
 #include "helper_template.h"
 #undef SHIFT
commit e01d9d31d9fd5824a1b0279a3631a2d66b5185ea
Author: Blue Swirl <blauwirbel at gmail.com>
Date:   Sun Apr 29 08:54:44 2012 +0000

    x86: fix coding style in ops_sse.h
    
    Fix coding style in ops_sse.h before next commit.
    
    Signed-off-by: Blue Swirl <blauwirbel at gmail.com>

diff --git a/target-i386/ops_sse.h b/target-i386/ops_sse.h
index 0d33ca1..d109512 100644
--- a/target-i386/ops_sse.h
+++ b/target-i386/ops_sse.h
@@ -203,12 +203,15 @@ void glue(helper_psrldq, SUFFIX)(Reg *d, Reg *s)
     int shift, i;
 
     shift = s->L(0);
-    if (shift > 16)
+    if (shift > 16) {
         shift = 16;
-    for(i = 0; i < 16 - shift; i++)
+    }
+    for (i = 0; i < 16 - shift; i++) {
         d->B(i) = d->B(i + shift);
-    for(i = 16 - shift; i < 16; i++)
+    }
+    for (i = 16 - shift; i < 16; i++) {
         d->B(i) = 0;
+    }
 }
 
 void glue(helper_pslldq, SUFFIX)(Reg *d, Reg *s)
@@ -216,112 +219,119 @@ void glue(helper_pslldq, SUFFIX)(Reg *d, Reg *s)
     int shift, i;
 
     shift = s->L(0);
-    if (shift > 16)
+    if (shift > 16) {
         shift = 16;
-    for(i = 15; i >= shift; i--)
+    }
+    for (i = 15; i >= shift; i--) {
         d->B(i) = d->B(i - shift);
-    for(i = 0; i < shift; i++)
+    }
+    for (i = 0; i < shift; i++) {
         d->B(i) = 0;
+    }
 }
 #endif
 
-#define SSE_HELPER_B(name, F)\
-void glue(name, SUFFIX) (Reg *d, Reg *s)\
-{\
-    d->B(0) = F(d->B(0), s->B(0));\
-    d->B(1) = F(d->B(1), s->B(1));\
-    d->B(2) = F(d->B(2), s->B(2));\
-    d->B(3) = F(d->B(3), s->B(3));\
-    d->B(4) = F(d->B(4), s->B(4));\
-    d->B(5) = F(d->B(5), s->B(5));\
-    d->B(6) = F(d->B(6), s->B(6));\
-    d->B(7) = F(d->B(7), s->B(7));\
-    XMM_ONLY(\
-    d->B(8) = F(d->B(8), s->B(8));\
-    d->B(9) = F(d->B(9), s->B(9));\
-    d->B(10) = F(d->B(10), s->B(10));\
-    d->B(11) = F(d->B(11), s->B(11));\
-    d->B(12) = F(d->B(12), s->B(12));\
-    d->B(13) = F(d->B(13), s->B(13));\
-    d->B(14) = F(d->B(14), s->B(14));\
-    d->B(15) = F(d->B(15), s->B(15));\
-    )\
-}
-
-#define SSE_HELPER_W(name, F)\
-void glue(name, SUFFIX) (Reg *d, Reg *s)\
-{\
-    d->W(0) = F(d->W(0), s->W(0));\
-    d->W(1) = F(d->W(1), s->W(1));\
-    d->W(2) = F(d->W(2), s->W(2));\
-    d->W(3) = F(d->W(3), s->W(3));\
-    XMM_ONLY(\
-    d->W(4) = F(d->W(4), s->W(4));\
-    d->W(5) = F(d->W(5), s->W(5));\
-    d->W(6) = F(d->W(6), s->W(6));\
-    d->W(7) = F(d->W(7), s->W(7));\
-    )\
-}
-
-#define SSE_HELPER_L(name, F)\
-void glue(name, SUFFIX) (Reg *d, Reg *s)\
-{\
-    d->L(0) = F(d->L(0), s->L(0));\
-    d->L(1) = F(d->L(1), s->L(1));\
-    XMM_ONLY(\
-    d->L(2) = F(d->L(2), s->L(2));\
-    d->L(3) = F(d->L(3), s->L(3));\
-    )\
-}
-
-#define SSE_HELPER_Q(name, F)\
-void glue(name, SUFFIX) (Reg *d, Reg *s)\
-{\
-    d->Q(0) = F(d->Q(0), s->Q(0));\
-    XMM_ONLY(\
-    d->Q(1) = F(d->Q(1), s->Q(1));\
-    )\
-}
+#define SSE_HELPER_B(name, F)                                   \
+    void glue(name, SUFFIX)(Reg *d, Reg *s)                     \
+    {                                                           \
+        d->B(0) = F(d->B(0), s->B(0));                          \
+        d->B(1) = F(d->B(1), s->B(1));                          \
+        d->B(2) = F(d->B(2), s->B(2));                          \
+        d->B(3) = F(d->B(3), s->B(3));                          \
+        d->B(4) = F(d->B(4), s->B(4));                          \
+        d->B(5) = F(d->B(5), s->B(5));                          \
+        d->B(6) = F(d->B(6), s->B(6));                          \
+        d->B(7) = F(d->B(7), s->B(7));                          \
+        XMM_ONLY(                                               \
+                 d->B(8) = F(d->B(8), s->B(8));                 \
+                 d->B(9) = F(d->B(9), s->B(9));                 \
+                 d->B(10) = F(d->B(10), s->B(10));              \
+                 d->B(11) = F(d->B(11), s->B(11));              \
+                 d->B(12) = F(d->B(12), s->B(12));              \
+                 d->B(13) = F(d->B(13), s->B(13));              \
+                 d->B(14) = F(d->B(14), s->B(14));              \
+                 d->B(15) = F(d->B(15), s->B(15));              \
+                                                        )       \
+            }
+
+#define SSE_HELPER_W(name, F)                                   \
+    void glue(name, SUFFIX)(Reg *d, Reg *s)                     \
+    {                                                           \
+        d->W(0) = F(d->W(0), s->W(0));                          \
+        d->W(1) = F(d->W(1), s->W(1));                          \
+        d->W(2) = F(d->W(2), s->W(2));                          \
+        d->W(3) = F(d->W(3), s->W(3));                          \
+        XMM_ONLY(                                               \
+                 d->W(4) = F(d->W(4), s->W(4));                 \
+                 d->W(5) = F(d->W(5), s->W(5));                 \
+                 d->W(6) = F(d->W(6), s->W(6));                 \
+                 d->W(7) = F(d->W(7), s->W(7));                 \
+                                                        )       \
+            }
+
+#define SSE_HELPER_L(name, F)                                   \
+    void glue(name, SUFFIX)(Reg *d, Reg *s)                     \
+    {                                                           \
+        d->L(0) = F(d->L(0), s->L(0));                          \
+        d->L(1) = F(d->L(1), s->L(1));                          \
+        XMM_ONLY(                                               \
+                 d->L(2) = F(d->L(2), s->L(2));                 \
+                 d->L(3) = F(d->L(3), s->L(3));                 \
+                                                        )       \
+            }
+
+#define SSE_HELPER_Q(name, F)                                   \
+    void glue(name, SUFFIX)(Reg *d, Reg *s)                     \
+    {                                                           \
+        d->Q(0) = F(d->Q(0), s->Q(0));                          \
+        XMM_ONLY(                                               \
+                 d->Q(1) = F(d->Q(1), s->Q(1));                 \
+                                                        )       \
+            }
 
 #if SHIFT == 0
 static inline int satub(int x)
 {
-    if (x < 0)
+    if (x < 0) {
         return 0;
-    else if (x > 255)
+    } else if (x > 255) {
         return 255;
-    else
+    } else {
         return x;
+    }
 }
 
 static inline int satuw(int x)
 {
-    if (x < 0)
+    if (x < 0) {
         return 0;
-    else if (x > 65535)
+    } else if (x > 65535) {
         return 65535;
-    else
+    } else {
         return x;
+    }
 }
 
 static inline int satsb(int x)
 {
-    if (x < -128)
+    if (x < -128) {
         return -128;
-    else if (x > 127)
+    } else if (x > 127) {
         return 127;
-    else
+    } else {
         return x;
+    }
 }
 
 static inline int satsw(int x)
 {
-    if (x < -32768)
+    if (x < -32768) {
         return -32768;
-    else if (x > 32767)
+    } else if (x > 32767) {
         return 32767;
-    else
+    } else {
         return x;
+    }
 }
 
 #define FADD(a, b) ((a) + (b))
@@ -340,22 +350,22 @@ static inline int satsw(int x)
 #define FMAXUB(a, b) ((a) > (b)) ? (a) : (b)
 #define FMAXSW(a, b) ((int16_t)(a) > (int16_t)(b)) ? (a) : (b)
 
-#define FAND(a, b) (a) & (b)
+#define FAND(a, b) ((a) & (b))
 #define FANDN(a, b) ((~(a)) & (b))
-#define FOR(a, b) (a) | (b)
-#define FXOR(a, b) (a) ^ (b)
+#define FOR(a, b) ((a) | (b))
+#define FXOR(a, b) ((a) ^ (b))
 
-#define FCMPGTB(a, b) (int8_t)(a) > (int8_t)(b) ? -1 : 0
-#define FCMPGTW(a, b) (int16_t)(a) > (int16_t)(b) ? -1 : 0
-#define FCMPGTL(a, b) (int32_t)(a) > (int32_t)(b) ? -1 : 0
-#define FCMPEQ(a, b) (a) == (b) ? -1 : 0
+#define FCMPGTB(a, b) ((int8_t)(a) > (int8_t)(b) ? -1 : 0)
+#define FCMPGTW(a, b) ((int16_t)(a) > (int16_t)(b) ? -1 : 0)
+#define FCMPGTL(a, b) ((int32_t)(a) > (int32_t)(b) ? -1 : 0)
+#define FCMPEQ(a, b) ((a) == (b) ? -1 : 0)
 
-#define FMULLW(a, b) (a) * (b)
-#define FMULHRW(a, b) ((int16_t)(a) * (int16_t)(b) + 0x8000) >> 16
-#define FMULHUW(a, b) (a) * (b) >> 16
-#define FMULHW(a, b) (int16_t)(a) * (int16_t)(b) >> 16
+#define FMULLW(a, b) ((a) * (b))
+#define FMULHRW(a, b) (((int16_t)(a) * (int16_t)(b) + 0x8000) >> 16)
+#define FMULHUW(a, b) ((a) * (b) >> 16)
+#define FMULHW(a, b) ((int16_t)(a) * (int16_t)(b) >> 16)
 
-#define FAVG(a, b) ((a) + (b) + 1) >> 1
+#define FAVG(a, b) (((a) + (b) + 1) >> 1)
 #endif
 
 SSE_HELPER_B(helper_paddb, FADD)
@@ -407,7 +417,7 @@ SSE_HELPER_W(helper_pmulhw, FMULHW)
 SSE_HELPER_B(helper_pavgb, FAVG)
 SSE_HELPER_W(helper_pavgw, FAVG)
 
-void glue(helper_pmuludq, SUFFIX) (Reg *d, Reg *s)
+void glue(helper_pmuludq, SUFFIX)(Reg *d, Reg *s)
 {
     d->Q(0) = (uint64_t)s->L(0) * (uint64_t)d->L(0);
 #if SHIFT == 1
@@ -415,26 +425,27 @@ void glue(helper_pmuludq, SUFFIX) (Reg *d, Reg *s)
 #endif
 }
 
-void glue(helper_pmaddwd, SUFFIX) (Reg *d, Reg *s)
+void glue(helper_pmaddwd, SUFFIX)(Reg *d, Reg *s)
 {
     int i;
 
-    for(i = 0; i < (2 << SHIFT); i++) {
-        d->L(i) = (int16_t)s->W(2*i) * (int16_t)d->W(2*i) +
-            (int16_t)s->W(2*i+1) * (int16_t)d->W(2*i+1);
+    for (i = 0; i < (2 << SHIFT); i++) {
+        d->L(i) = (int16_t)s->W(2 * i) * (int16_t)d->W(2 * i) +
+            (int16_t)s->W(2 * i + 1) * (int16_t)d->W(2 * i + 1);
     }
 }
 
 #if SHIFT == 0
 static inline int abs1(int a)
 {
-    if (a < 0)
+    if (a < 0) {
         return -a;
-    else
+    } else {
         return a;
+    }
 }
 #endif
-void glue(helper_psadbw, SUFFIX) (Reg *d, Reg *s)
+void glue(helper_psadbw, SUFFIX)(Reg *d, Reg *s)
 {
     unsigned int val;
 
@@ -462,16 +473,18 @@ void glue(helper_psadbw, SUFFIX) (Reg *d, Reg *s)
 #endif
 }
 
-void glue(helper_maskmov, SUFFIX) (Reg *d, Reg *s, target_ulong a0)
+void glue(helper_maskmov, SUFFIX)(Reg *d, Reg *s, target_ulong a0)
 {
     int i;
-    for(i = 0; i < (8 << SHIFT); i++) {
-        if (s->B(i) & 0x80)
+
+    for (i = 0; i < (8 << SHIFT); i++) {
+        if (s->B(i) & 0x80) {
             stb(a0 + i, d->B(i));
+        }
     }
 }
 
-void glue(helper_movl_mm_T0, SUFFIX) (Reg *d, uint32_t val)
+void glue(helper_movl_mm_T0, SUFFIX)(Reg *d, uint32_t val)
 {
     d->L(0) = val;
     d->L(1) = 0;
@@ -481,7 +494,7 @@ void glue(helper_movl_mm_T0, SUFFIX) (Reg *d, uint32_t val)
 }
 
 #ifdef TARGET_X86_64
-void glue(helper_movq_mm_T0, SUFFIX) (Reg *d, uint64_t val)
+void glue(helper_movq_mm_T0, SUFFIX)(Reg *d, uint64_t val)
 {
     d->Q(0) = val;
 #if SHIFT == 1
@@ -491,9 +504,10 @@ void glue(helper_movq_mm_T0, SUFFIX) (Reg *d, uint64_t val)
 #endif
 
 #if SHIFT == 0
-void glue(helper_pshufw, SUFFIX) (Reg *d, Reg *s, int order)
+void glue(helper_pshufw, SUFFIX)(Reg *d, Reg *s, int order)
 {
     Reg r;
+
     r.W(0) = s->W(order & 3);
     r.W(1) = s->W((order >> 2) & 3);
     r.W(2) = s->W((order >> 4) & 3);
@@ -504,6 +518,7 @@ void glue(helper_pshufw, SUFFIX) (Reg *d, Reg *s, int order)
 void helper_shufps(Reg *d, Reg *s, int order)
 {
     Reg r;
+
     r.L(0) = d->L(order & 3);
     r.L(1) = d->L((order >> 2) & 3);
     r.L(2) = s->L((order >> 4) & 3);
@@ -514,14 +529,16 @@ void helper_shufps(Reg *d, Reg *s, int order)
 void helper_shufpd(Reg *d, Reg *s, int order)
 {
     Reg r;
+
     r.Q(0) = d->Q(order & 1);
     r.Q(1) = s->Q((order >> 1) & 1);
     *d = r;
 }
 
-void glue(helper_pshufd, SUFFIX) (Reg *d, Reg *s, int order)
+void glue(helper_pshufd, SUFFIX)(Reg *d, Reg *s, int order)
 {
     Reg r;
+
     r.L(0) = s->L(order & 3);
     r.L(1) = s->L((order >> 2) & 3);
     r.L(2) = s->L((order >> 4) & 3);
@@ -529,9 +546,10 @@ void glue(helper_pshufd, SUFFIX) (Reg *d, Reg *s, int order)
     *d = r;
 }
 
-void glue(helper_pshuflw, SUFFIX) (Reg *d, Reg *s, int order)
+void glue(helper_pshuflw, SUFFIX)(Reg *d, Reg *s, int order)
 {
     Reg r;
+
     r.W(0) = s->W(order & 3);
     r.W(1) = s->W((order >> 2) & 3);
     r.W(2) = s->W((order >> 4) & 3);
@@ -540,9 +558,10 @@ void glue(helper_pshuflw, SUFFIX) (Reg *d, Reg *s, int order)
     *d = r;
 }
 
-void glue(helper_pshufhw, SUFFIX) (Reg *d, Reg *s, int order)
+void glue(helper_pshufhw, SUFFIX)(Reg *d, Reg *s, int order)
 {
     Reg r;
+
     r.Q(0) = s->Q(0);
     r.W(4) = s->W(4 + (order & 3));
     r.W(5) = s->W(4 + ((order >> 2) & 3));
@@ -556,29 +575,30 @@ void glue(helper_pshufhw, SUFFIX) (Reg *d, Reg *s, int order)
 /* FPU ops */
 /* XXX: not accurate */
 
-#define SSE_HELPER_S(name, F)\
-void helper_ ## name ## ps (Reg *d, Reg *s)\
-{\
-    d->XMM_S(0) = F(32, d->XMM_S(0), s->XMM_S(0));\
-    d->XMM_S(1) = F(32, d->XMM_S(1), s->XMM_S(1));\
-    d->XMM_S(2) = F(32, d->XMM_S(2), s->XMM_S(2));\
-    d->XMM_S(3) = F(32, d->XMM_S(3), s->XMM_S(3));\
-}\
-\
-void helper_ ## name ## ss (Reg *d, Reg *s)\
-{\
-    d->XMM_S(0) = F(32, d->XMM_S(0), s->XMM_S(0));\
-}\
-void helper_ ## name ## pd (Reg *d, Reg *s)\
-{\
-    d->XMM_D(0) = F(64, d->XMM_D(0), s->XMM_D(0));\
-    d->XMM_D(1) = F(64, d->XMM_D(1), s->XMM_D(1));\
-}\
-\
-void helper_ ## name ## sd (Reg *d, Reg *s)\
-{\
-    d->XMM_D(0) = F(64, d->XMM_D(0), s->XMM_D(0));\
-}
+#define SSE_HELPER_S(name, F)                           \
+    void helper_ ## name ## ps(Reg *d, Reg *s)          \
+    {                                                   \
+        d->XMM_S(0) = F(32, d->XMM_S(0), s->XMM_S(0));  \
+        d->XMM_S(1) = F(32, d->XMM_S(1), s->XMM_S(1));  \
+        d->XMM_S(2) = F(32, d->XMM_S(2), s->XMM_S(2));  \
+        d->XMM_S(3) = F(32, d->XMM_S(3), s->XMM_S(3));  \
+    }                                                   \
+                                                        \
+    void helper_ ## name ## ss(Reg *d, Reg *s)          \
+    {                                                   \
+        d->XMM_S(0) = F(32, d->XMM_S(0), s->XMM_S(0));  \
+    }                                                   \
+                                                        \
+    void helper_ ## name ## pd(Reg *d, Reg *s)          \
+    {                                                   \
+        d->XMM_D(0) = F(64, d->XMM_D(0), s->XMM_D(0));  \
+        d->XMM_D(1) = F(64, d->XMM_D(1), s->XMM_D(1));  \
+    }                                                   \
+                                                        \
+    void helper_ ## name ## sd(Reg *d, Reg *s)          \
+    {                                                   \
+        d->XMM_D(0) = F(64, d->XMM_D(0), s->XMM_D(0));  \
+    }
 
 #define FPU_ADD(size, a, b) float ## size ## _add(a, b, &env->sse_status)
 #define FPU_SUB(size, a, b) float ## size ## _sub(a, b, &env->sse_status)
@@ -590,8 +610,10 @@ void helper_ ## name ## sd (Reg *d, Reg *s)\
  * special cases right: for min and max Intel specifies that (-0,0),
  * (NaN, anything) and (anything, NaN) return the second argument.
  */
-#define FPU_MIN(size, a, b) float ## size ## _lt(a, b, &env->sse_status) ? (a) : (b)
-#define FPU_MAX(size, a, b) float ## size ## _lt(b, a, &env->sse_status) ? (a) : (b)
+#define FPU_MIN(size, a, b)                                     \
+    (float ## size ## _lt(a, b, &env->sse_status) ? (a) : (b))
+#define FPU_MAX(size, a, b)                                     \
+    (float ## size ## _lt(b, a, &env->sse_status) ? (a) : (b))
 
 SSE_HELPER_S(add, FPU_ADD)
 SSE_HELPER_S(sub, FPU_SUB)
@@ -606,6 +628,7 @@ SSE_HELPER_S(sqrt, FPU_SQRT)
 void helper_cvtps2pd(Reg *d, Reg *s)
 {
     float32 s0, s1;
+
     s0 = s->XMM_S(0);
     s1 = s->XMM_S(1);
     d->XMM_D(0) = float32_to_float64(s0, &env->sse_status);
@@ -641,6 +664,7 @@ void helper_cvtdq2ps(Reg *d, Reg *s)
 void helper_cvtdq2pd(Reg *d, Reg *s)
 {
     int32_t l0, l1;
+
     l0 = (int32_t)s->XMM_L(0);
     l1 = (int32_t)s->XMM_L(1);
     d->XMM_D(0) = int32_to_float64(l0, &env->sse_status);
@@ -864,6 +888,7 @@ void helper_insertq_i(XMMReg *d, int index, int length)
 void helper_haddps(XMMReg *d, XMMReg *s)
 {
     XMMReg r;
+
     r.XMM_S(0) = float32_add(d->XMM_S(0), d->XMM_S(1), &env->sse_status);
     r.XMM_S(1) = float32_add(d->XMM_S(2), d->XMM_S(3), &env->sse_status);
     r.XMM_S(2) = float32_add(s->XMM_S(0), s->XMM_S(1), &env->sse_status);
@@ -874,6 +899,7 @@ void helper_haddps(XMMReg *d, XMMReg *s)
 void helper_haddpd(XMMReg *d, XMMReg *s)
 {
     XMMReg r;
+
     r.XMM_D(0) = float64_add(d->XMM_D(0), d->XMM_D(1), &env->sse_status);
     r.XMM_D(1) = float64_add(s->XMM_D(0), s->XMM_D(1), &env->sse_status);
     *d = r;
@@ -882,6 +908,7 @@ void helper_haddpd(XMMReg *d, XMMReg *s)
 void helper_hsubps(XMMReg *d, XMMReg *s)
 {
     XMMReg r;
+
     r.XMM_S(0) = float32_sub(d->XMM_S(0), d->XMM_S(1), &env->sse_status);
     r.XMM_S(1) = float32_sub(d->XMM_S(2), d->XMM_S(3), &env->sse_status);
     r.XMM_S(2) = float32_sub(s->XMM_S(0), s->XMM_S(1), &env->sse_status);
@@ -892,6 +919,7 @@ void helper_hsubps(XMMReg *d, XMMReg *s)
 void helper_hsubpd(XMMReg *d, XMMReg *s)
 {
     XMMReg r;
+
     r.XMM_D(0) = float64_sub(d->XMM_D(0), d->XMM_D(1), &env->sse_status);
     r.XMM_D(1) = float64_sub(s->XMM_D(0), s->XMM_D(1), &env->sse_status);
     *d = r;
@@ -912,38 +940,47 @@ void helper_addsubpd(XMMReg *d, XMMReg *s)
 }
 
 /* XXX: unordered */
-#define SSE_HELPER_CMP(name, F)\
-void helper_ ## name ## ps (Reg *d, Reg *s)\
-{\
-    d->XMM_L(0) = F(32, d->XMM_S(0), s->XMM_S(0));\
-    d->XMM_L(1) = F(32, d->XMM_S(1), s->XMM_S(1));\
-    d->XMM_L(2) = F(32, d->XMM_S(2), s->XMM_S(2));\
-    d->XMM_L(3) = F(32, d->XMM_S(3), s->XMM_S(3));\
-}\
-\
-void helper_ ## name ## ss (Reg *d, Reg *s)\
-{\
-    d->XMM_L(0) = F(32, d->XMM_S(0), s->XMM_S(0));\
-}\
-void helper_ ## name ## pd (Reg *d, Reg *s)\
-{\
-    d->XMM_Q(0) = F(64, d->XMM_D(0), s->XMM_D(0));\
-    d->XMM_Q(1) = F(64, d->XMM_D(1), s->XMM_D(1));\
-}\
-\
-void helper_ ## name ## sd (Reg *d, Reg *s)\
-{\
-    d->XMM_Q(0) = F(64, d->XMM_D(0), s->XMM_D(0));\
-}
-
-#define FPU_CMPEQ(size, a, b) float ## size ## _eq_quiet(a, b, &env->sse_status) ? -1 : 0
-#define FPU_CMPLT(size, a, b) float ## size ## _lt(a, b, &env->sse_status) ? -1 : 0
-#define FPU_CMPLE(size, a, b) float ## size ## _le(a, b, &env->sse_status) ? -1 : 0
-#define FPU_CMPUNORD(size, a, b) float ## size ## _unordered_quiet(a, b, &env->sse_status) ? - 1 : 0
-#define FPU_CMPNEQ(size, a, b) float ## size ## _eq_quiet(a, b, &env->sse_status) ? 0 : -1
-#define FPU_CMPNLT(size, a, b) float ## size ## _lt(a, b, &env->sse_status) ? 0 : -1
-#define FPU_CMPNLE(size, a, b) float ## size ## _le(a, b, &env->sse_status) ? 0 : -1
-#define FPU_CMPORD(size, a, b) float ## size ## _unordered_quiet(a, b, &env->sse_status) ? 0 : -1
+#define SSE_HELPER_CMP(name, F)                         \
+    void helper_ ## name ## ps(Reg *d, Reg *s)          \
+    {                                                   \
+        d->XMM_L(0) = F(32, d->XMM_S(0), s->XMM_S(0));  \
+        d->XMM_L(1) = F(32, d->XMM_S(1), s->XMM_S(1));  \
+        d->XMM_L(2) = F(32, d->XMM_S(2), s->XMM_S(2));  \
+        d->XMM_L(3) = F(32, d->XMM_S(3), s->XMM_S(3));  \
+    }                                                   \
+                                                        \
+    void helper_ ## name ## ss(Reg *d, Reg *s)          \
+    {                                                   \
+        d->XMM_L(0) = F(32, d->XMM_S(0), s->XMM_S(0));  \
+    }                                                   \
+                                                        \
+    void helper_ ## name ## pd(Reg *d, Reg *s)          \
+    {                                                   \
+        d->XMM_Q(0) = F(64, d->XMM_D(0), s->XMM_D(0));  \
+        d->XMM_Q(1) = F(64, d->XMM_D(1), s->XMM_D(1));  \
+    }                                                   \
+                                                        \
+    void helper_ ## name ## sd(Reg *d, Reg *s)          \
+    {                                                   \
+        d->XMM_Q(0) = F(64, d->XMM_D(0), s->XMM_D(0));  \
+    }
+
+#define FPU_CMPEQ(size, a, b)                                           \
+    (float ## size ## _eq_quiet(a, b, &env->sse_status) ? -1 : 0)
+#define FPU_CMPLT(size, a, b)                                           \
+    (float ## size ## _lt(a, b, &env->sse_status) ? -1 : 0)
+#define FPU_CMPLE(size, a, b)                                           \
+    (float ## size ## _le(a, b, &env->sse_status) ? -1 : 0)
+#define FPU_CMPUNORD(size, a, b)                                        \
+    (float ## size ## _unordered_quiet(a, b, &env->sse_status) ? -1 : 0)
+#define FPU_CMPNEQ(size, a, b)                                          \
+    (float ## size ## _eq_quiet(a, b, &env->sse_status) ? 0 : -1)
+#define FPU_CMPNLT(size, a, b)                                          \
+    (float ## size ## _lt(a, b, &env->sse_status) ? 0 : -1)
+#define FPU_CMPNLE(size, a, b)                                          \
+    (float ## size ## _le(a, b, &env->sse_status) ? 0 : -1)
+#define FPU_CMPORD(size, a, b)                                          \
+    (float ## size ## _unordered_quiet(a, b, &env->sse_status) ? 0 : -1)
 
 SSE_HELPER_CMP(cmpeq, FPU_CMPEQ)
 SSE_HELPER_CMP(cmplt, FPU_CMPLT)
@@ -1003,6 +1040,7 @@ void helper_comisd(Reg *d, Reg *s)
 uint32_t helper_movmskps(Reg *s)
 {
     int b0, b1, b2, b3;
+
     b0 = s->XMM_L(0) >> 31;
     b1 = s->XMM_L(1) >> 31;
     b2 = s->XMM_L(2) >> 31;
@@ -1013,6 +1051,7 @@ uint32_t helper_movmskps(Reg *s)
 uint32_t helper_movmskpd(Reg *s)
 {
     int b0, b1;
+
     b0 = s->XMM_L(1) >> 31;
     b1 = s->XMM_L(3) >> 31;
     return b0 | (b1 << 1);
@@ -1023,6 +1062,7 @@ uint32_t helper_movmskpd(Reg *s)
 uint32_t glue(helper_pmovmskb, SUFFIX)(Reg *s)
 {
     uint32_t val;
+
     val = 0;
     val |= (s->B(0) >> 7);
     val |= (s->B(1) >> 6) & 0x02;
@@ -1045,7 +1085,7 @@ uint32_t glue(helper_pmovmskb, SUFFIX)(Reg *s)
     return val;
 }
 
-void glue(helper_packsswb, SUFFIX) (Reg *d, Reg *s)
+void glue(helper_packsswb, SUFFIX)(Reg *d, Reg *s)
 {
     Reg r;
 
@@ -1072,7 +1112,7 @@ void glue(helper_packsswb, SUFFIX) (Reg *d, Reg *s)
     *d = r;
 }
 
-void glue(helper_packuswb, SUFFIX) (Reg *d, Reg *s)
+void glue(helper_packuswb, SUFFIX)(Reg *d, Reg *s)
 {
     Reg r;
 
@@ -1099,7 +1139,7 @@ void glue(helper_packuswb, SUFFIX) (Reg *d, Reg *s)
     *d = r;
 }
 
-void glue(helper_packssdw, SUFFIX) (Reg *d, Reg *s)
+void glue(helper_packssdw, SUFFIX)(Reg *d, Reg *s)
 {
     Reg r;
 
@@ -1118,73 +1158,74 @@ void glue(helper_packssdw, SUFFIX) (Reg *d, Reg *s)
     *d = r;
 }
 
-#define UNPCK_OP(base_name, base)                               \
-                                                                \
-void glue(helper_punpck ## base_name ## bw, SUFFIX) (Reg *d, Reg *s)   \
-{                                                               \
-    Reg r;                                              \
-                                                                \
-    r.B(0) = d->B((base << (SHIFT + 2)) + 0);                   \
-    r.B(1) = s->B((base << (SHIFT + 2)) + 0);                   \
-    r.B(2) = d->B((base << (SHIFT + 2)) + 1);                   \
-    r.B(3) = s->B((base << (SHIFT + 2)) + 1);                   \
-    r.B(4) = d->B((base << (SHIFT + 2)) + 2);                   \
-    r.B(5) = s->B((base << (SHIFT + 2)) + 2);                   \
-    r.B(6) = d->B((base << (SHIFT + 2)) + 3);                   \
-    r.B(7) = s->B((base << (SHIFT + 2)) + 3);                   \
-XMM_ONLY(                                                       \
-    r.B(8) = d->B((base << (SHIFT + 2)) + 4);                   \
-    r.B(9) = s->B((base << (SHIFT + 2)) + 4);                   \
-    r.B(10) = d->B((base << (SHIFT + 2)) + 5);                  \
-    r.B(11) = s->B((base << (SHIFT + 2)) + 5);                  \
-    r.B(12) = d->B((base << (SHIFT + 2)) + 6);                  \
-    r.B(13) = s->B((base << (SHIFT + 2)) + 6);                  \
-    r.B(14) = d->B((base << (SHIFT + 2)) + 7);                  \
-    r.B(15) = s->B((base << (SHIFT + 2)) + 7);                  \
-)                                                               \
-    *d = r;                                                     \
-}                                                               \
-                                                                \
-void glue(helper_punpck ## base_name ## wd, SUFFIX) (Reg *d, Reg *s)   \
-{                                                               \
-    Reg r;                                              \
-                                                                \
-    r.W(0) = d->W((base << (SHIFT + 1)) + 0);                   \
-    r.W(1) = s->W((base << (SHIFT + 1)) + 0);                   \
-    r.W(2) = d->W((base << (SHIFT + 1)) + 1);                   \
-    r.W(3) = s->W((base << (SHIFT + 1)) + 1);                   \
-XMM_ONLY(                                                       \
-    r.W(4) = d->W((base << (SHIFT + 1)) + 2);                   \
-    r.W(5) = s->W((base << (SHIFT + 1)) + 2);                   \
-    r.W(6) = d->W((base << (SHIFT + 1)) + 3);                   \
-    r.W(7) = s->W((base << (SHIFT + 1)) + 3);                   \
-)                                                               \
-    *d = r;                                                     \
-}                                                               \
-                                                                \
-void glue(helper_punpck ## base_name ## dq, SUFFIX) (Reg *d, Reg *s)   \
-{                                                               \
-    Reg r;                                              \
-                                                                \
-    r.L(0) = d->L((base << SHIFT) + 0);                         \
-    r.L(1) = s->L((base << SHIFT) + 0);                         \
-XMM_ONLY(                                                       \
-    r.L(2) = d->L((base << SHIFT) + 1);                         \
-    r.L(3) = s->L((base << SHIFT) + 1);                         \
-)                                                               \
-    *d = r;                                                     \
-}                                                               \
-                                                                \
-XMM_ONLY(                                                       \
-void glue(helper_punpck ## base_name ## qdq, SUFFIX) (Reg *d, Reg *s)  \
-{                                                               \
-    Reg r;                                              \
-                                                                \
-    r.Q(0) = d->Q(base);                                        \
-    r.Q(1) = s->Q(base);                                        \
-    *d = r;                                                     \
-}                                                               \
-)
+#define UNPCK_OP(base_name, base)                                       \
+                                                                        \
+    void glue(helper_punpck ## base_name ## bw, SUFFIX)(Reg *d, Reg *s) \
+    {                                                                   \
+        Reg r;                                                          \
+                                                                        \
+        r.B(0) = d->B((base << (SHIFT + 2)) + 0);                       \
+        r.B(1) = s->B((base << (SHIFT + 2)) + 0);                       \
+        r.B(2) = d->B((base << (SHIFT + 2)) + 1);                       \
+        r.B(3) = s->B((base << (SHIFT + 2)) + 1);                       \
+        r.B(4) = d->B((base << (SHIFT + 2)) + 2);                       \
+        r.B(5) = s->B((base << (SHIFT + 2)) + 2);                       \
+        r.B(6) = d->B((base << (SHIFT + 2)) + 3);                       \
+        r.B(7) = s->B((base << (SHIFT + 2)) + 3);                       \
+        XMM_ONLY(                                                       \
+                 r.B(8) = d->B((base << (SHIFT + 2)) + 4);              \
+                 r.B(9) = s->B((base << (SHIFT + 2)) + 4);              \
+                 r.B(10) = d->B((base << (SHIFT + 2)) + 5);             \
+                 r.B(11) = s->B((base << (SHIFT + 2)) + 5);             \
+                 r.B(12) = d->B((base << (SHIFT + 2)) + 6);             \
+                 r.B(13) = s->B((base << (SHIFT + 2)) + 6);             \
+                 r.B(14) = d->B((base << (SHIFT + 2)) + 7);             \
+                 r.B(15) = s->B((base << (SHIFT + 2)) + 7);             \
+                                                                        ) \
+            *d = r;                                                     \
+    }                                                                   \
+                                                                        \
+    void glue(helper_punpck ## base_name ## wd, SUFFIX)(Reg *d, Reg *s) \
+    {                                                                   \
+        Reg r;                                                          \
+                                                                        \
+        r.W(0) = d->W((base << (SHIFT + 1)) + 0);                       \
+        r.W(1) = s->W((base << (SHIFT + 1)) + 0);                       \
+        r.W(2) = d->W((base << (SHIFT + 1)) + 1);                       \
+        r.W(3) = s->W((base << (SHIFT + 1)) + 1);                       \
+        XMM_ONLY(                                                       \
+                 r.W(4) = d->W((base << (SHIFT + 1)) + 2);              \
+                 r.W(5) = s->W((base << (SHIFT + 1)) + 2);              \
+                 r.W(6) = d->W((base << (SHIFT + 1)) + 3);              \
+                 r.W(7) = s->W((base << (SHIFT + 1)) + 3);              \
+                                                                        ) \
+            *d = r;                                                     \
+    }                                                                   \
+                                                                        \
+    void glue(helper_punpck ## base_name ## dq, SUFFIX)(Reg *d, Reg *s) \
+    {                                                                   \
+        Reg r;                                                          \
+                                                                        \
+        r.L(0) = d->L((base << SHIFT) + 0);                             \
+        r.L(1) = s->L((base << SHIFT) + 0);                             \
+        XMM_ONLY(                                                       \
+                 r.L(2) = d->L((base << SHIFT) + 1);                    \
+                 r.L(3) = s->L((base << SHIFT) + 1);                    \
+                                                                        ) \
+            *d = r;                                                     \
+    }                                                                   \
+                                                                        \
+    XMM_ONLY(                                                           \
+             void glue(helper_punpck ## base_name ## qdq, SUFFIX)(Reg *d, \
+                                                                  Reg *s) \
+             {                                                          \
+                 Reg r;                                                 \
+                                                                        \
+                 r.Q(0) = d->Q(base);                                   \
+                 r.Q(1) = s->Q(base);                                   \
+                 *d = r;                                                \
+             }                                                          \
+                                                                        )
 
 UNPCK_OP(l, 0)
 UNPCK_OP(h, 1)
@@ -1211,13 +1252,16 @@ void helper_pf2id(MMXReg *d, MMXReg *s)
 
 void helper_pf2iw(MMXReg *d, MMXReg *s)
 {
-    d->MMX_L(0) = satsw(float32_to_int32_round_to_zero(s->MMX_S(0), &env->mmx_status));
-    d->MMX_L(1) = satsw(float32_to_int32_round_to_zero(s->MMX_S(1), &env->mmx_status));
+    d->MMX_L(0) = satsw(float32_to_int32_round_to_zero(s->MMX_S(0),
+                                                       &env->mmx_status));
+    d->MMX_L(1) = satsw(float32_to_int32_round_to_zero(s->MMX_S(1),
+                                                       &env->mmx_status));
 }
 
 void helper_pfacc(MMXReg *d, MMXReg *s)
 {
     MMXReg r;
+
     r.MMX_S(0) = float32_add(d->MMX_S(0), d->MMX_S(1), &env->mmx_status);
     r.MMX_S(1) = float32_add(s->MMX_S(0), s->MMX_S(1), &env->mmx_status);
     *d = r;
@@ -1231,36 +1275,46 @@ void helper_pfadd(MMXReg *d, MMXReg *s)
 
 void helper_pfcmpeq(MMXReg *d, MMXReg *s)
 {
-    d->MMX_L(0) = float32_eq_quiet(d->MMX_S(0), s->MMX_S(0), &env->mmx_status) ? -1 : 0;
-    d->MMX_L(1) = float32_eq_quiet(d->MMX_S(1), s->MMX_S(1), &env->mmx_status) ? -1 : 0;
+    d->MMX_L(0) = float32_eq_quiet(d->MMX_S(0), s->MMX_S(0),
+                                   &env->mmx_status) ? -1 : 0;
+    d->MMX_L(1) = float32_eq_quiet(d->MMX_S(1), s->MMX_S(1),
+                                   &env->mmx_status) ? -1 : 0;
 }
 
 void helper_pfcmpge(MMXReg *d, MMXReg *s)
 {
-    d->MMX_L(0) = float32_le(s->MMX_S(0), d->MMX_S(0), &env->mmx_status) ? -1 : 0;
-    d->MMX_L(1) = float32_le(s->MMX_S(1), d->MMX_S(1), &env->mmx_status) ? -1 : 0;
+    d->MMX_L(0) = float32_le(s->MMX_S(0), d->MMX_S(0),
+                             &env->mmx_status) ? -1 : 0;
+    d->MMX_L(1) = float32_le(s->MMX_S(1), d->MMX_S(1),
+                             &env->mmx_status) ? -1 : 0;
 }
 
 void helper_pfcmpgt(MMXReg *d, MMXReg *s)
 {
-    d->MMX_L(0) = float32_lt(s->MMX_S(0), d->MMX_S(0), &env->mmx_status) ? -1 : 0;
-    d->MMX_L(1) = float32_lt(s->MMX_S(1), d->MMX_S(1), &env->mmx_status) ? -1 : 0;
+    d->MMX_L(0) = float32_lt(s->MMX_S(0), d->MMX_S(0),
+                             &env->mmx_status) ? -1 : 0;
+    d->MMX_L(1) = float32_lt(s->MMX_S(1), d->MMX_S(1),
+                             &env->mmx_status) ? -1 : 0;
 }
 
 void helper_pfmax(MMXReg *d, MMXReg *s)
 {
-    if (float32_lt(d->MMX_S(0), s->MMX_S(0), &env->mmx_status))
+    if (float32_lt(d->MMX_S(0), s->MMX_S(0), &env->mmx_status)) {
         d->MMX_S(0) = s->MMX_S(0);
-    if (float32_lt(d->MMX_S(1), s->MMX_S(1), &env->mmx_status))
+    }
+    if (float32_lt(d->MMX_S(1), s->MMX_S(1), &env->mmx_status)) {
         d->MMX_S(1) = s->MMX_S(1);
+    }
 }
 
 void helper_pfmin(MMXReg *d, MMXReg *s)
 {
-    if (float32_lt(s->MMX_S(0), d->MMX_S(0), &env->mmx_status))
+    if (float32_lt(s->MMX_S(0), d->MMX_S(0), &env->mmx_status)) {
         d->MMX_S(0) = s->MMX_S(0);
-    if (float32_lt(s->MMX_S(1), d->MMX_S(1), &env->mmx_status))
+    }
+    if (float32_lt(s->MMX_S(1), d->MMX_S(1), &env->mmx_status)) {
         d->MMX_S(1) = s->MMX_S(1);
+    }
 }
 
 void helper_pfmul(MMXReg *d, MMXReg *s)
@@ -1272,6 +1326,7 @@ void helper_pfmul(MMXReg *d, MMXReg *s)
 void helper_pfnacc(MMXReg *d, MMXReg *s)
 {
     MMXReg r;
+
     r.MMX_S(0) = float32_sub(d->MMX_S(0), d->MMX_S(1), &env->mmx_status);
     r.MMX_S(1) = float32_sub(s->MMX_S(0), s->MMX_S(1), &env->mmx_status);
     *d = r;
@@ -1280,6 +1335,7 @@ void helper_pfnacc(MMXReg *d, MMXReg *s)
 void helper_pfpnacc(MMXReg *d, MMXReg *s)
 {
     MMXReg r;
+
     r.MMX_S(0) = float32_sub(d->MMX_S(0), d->MMX_S(1), &env->mmx_status);
     r.MMX_S(1) = float32_add(s->MMX_S(0), s->MMX_S(1), &env->mmx_status);
     *d = r;
@@ -1316,6 +1372,7 @@ void helper_pfsubr(MMXReg *d, MMXReg *s)
 void helper_pswapd(MMXReg *d, MMXReg *s)
 {
     MMXReg r;
+
     r.MMX_L(0) = s->MMX_L(1);
     r.MMX_L(1) = s->MMX_L(0);
     *d = r;
@@ -1323,18 +1380,19 @@ void helper_pswapd(MMXReg *d, MMXReg *s)
 #endif
 
 /* SSSE3 op helpers */
-void glue(helper_pshufb, SUFFIX) (Reg *d, Reg *s)
+void glue(helper_pshufb, SUFFIX)(Reg *d, Reg *s)
 {
     int i;
     Reg r;
 
-    for (i = 0; i < (8 << SHIFT); i++)
+    for (i = 0; i < (8 << SHIFT); i++) {
         r.B(i) = (s->B(i) & 0x80) ? 0 : (d->B(s->B(i) & ((8 << SHIFT) - 1)));
+    }
 
     *d = r;
 }
 
-void glue(helper_phaddw, SUFFIX) (Reg *d, Reg *s)
+void glue(helper_phaddw, SUFFIX)(Reg *d, Reg *s)
 {
     d->W(0) = (int16_t)d->W(0) + (int16_t)d->W(1);
     d->W(1) = (int16_t)d->W(2) + (int16_t)d->W(3);
@@ -1346,7 +1404,7 @@ void glue(helper_phaddw, SUFFIX) (Reg *d, Reg *s)
     XMM_ONLY(d->W(7) = (int16_t)s->W(6) + (int16_t)s->W(7));
 }
 
-void glue(helper_phaddd, SUFFIX) (Reg *d, Reg *s)
+void glue(helper_phaddd, SUFFIX)(Reg *d, Reg *s)
 {
     d->L(0) = (int32_t)d->L(0) + (int32_t)d->L(1);
     XMM_ONLY(d->L(1) = (int32_t)d->L(2) + (int32_t)d->L(3));
@@ -1354,7 +1412,7 @@ void glue(helper_phaddd, SUFFIX) (Reg *d, Reg *s)
     XMM_ONLY(d->L(3) = (int32_t)s->L(2) + (int32_t)s->L(3));
 }
 
-void glue(helper_phaddsw, SUFFIX) (Reg *d, Reg *s)
+void glue(helper_phaddsw, SUFFIX)(Reg *d, Reg *s)
 {
     d->W(0) = satsw((int16_t)d->W(0) + (int16_t)d->W(1));
     d->W(1) = satsw((int16_t)d->W(2) + (int16_t)d->W(3));
@@ -1366,19 +1424,19 @@ void glue(helper_phaddsw, SUFFIX) (Reg *d, Reg *s)
     XMM_ONLY(d->W(7) = satsw((int16_t)s->W(6) + (int16_t)s->W(7)));
 }
 
-void glue(helper_pmaddubsw, SUFFIX) (Reg *d, Reg *s)
+void glue(helper_pmaddubsw, SUFFIX)(Reg *d, Reg *s)
 {
-    d->W(0) = satsw((int8_t)s->B( 0) * (uint8_t)d->B( 0) +
-                    (int8_t)s->B( 1) * (uint8_t)d->B( 1));
-    d->W(1) = satsw((int8_t)s->B( 2) * (uint8_t)d->B( 2) +
-                    (int8_t)s->B( 3) * (uint8_t)d->B( 3));
-    d->W(2) = satsw((int8_t)s->B( 4) * (uint8_t)d->B( 4) +
-                    (int8_t)s->B( 5) * (uint8_t)d->B( 5));
-    d->W(3) = satsw((int8_t)s->B( 6) * (uint8_t)d->B( 6) +
-                    (int8_t)s->B( 7) * (uint8_t)d->B( 7));
+    d->W(0) = satsw((int8_t)s->B(0) * (uint8_t)d->B(0) +
+                    (int8_t)s->B(1) * (uint8_t)d->B(1));
+    d->W(1) = satsw((int8_t)s->B(2) * (uint8_t)d->B(2) +
+                    (int8_t)s->B(3) * (uint8_t)d->B(3));
+    d->W(2) = satsw((int8_t)s->B(4) * (uint8_t)d->B(4) +
+                    (int8_t)s->B(5) * (uint8_t)d->B(5));
+    d->W(3) = satsw((int8_t)s->B(6) * (uint8_t)d->B(6) +
+                    (int8_t)s->B(7) * (uint8_t)d->B(7));
 #if SHIFT == 1
-    d->W(4) = satsw((int8_t)s->B( 8) * (uint8_t)d->B( 8) +
-                    (int8_t)s->B( 9) * (uint8_t)d->B( 9));
+    d->W(4) = satsw((int8_t)s->B(8) * (uint8_t)d->B(8) +
+                    (int8_t)s->B(9) * (uint8_t)d->B(9));
     d->W(5) = satsw((int8_t)s->B(10) * (uint8_t)d->B(10) +
                     (int8_t)s->B(11) * (uint8_t)d->B(11));
     d->W(6) = satsw((int8_t)s->B(12) * (uint8_t)d->B(12) +
@@ -1388,7 +1446,7 @@ void glue(helper_pmaddubsw, SUFFIX) (Reg *d, Reg *s)
 #endif
 }
 
-void glue(helper_phsubw, SUFFIX) (Reg *d, Reg *s)
+void glue(helper_phsubw, SUFFIX)(Reg *d, Reg *s)
 {
     d->W(0) = (int16_t)d->W(0) - (int16_t)d->W(1);
     d->W(1) = (int16_t)d->W(2) - (int16_t)d->W(3);
@@ -1400,7 +1458,7 @@ void glue(helper_phsubw, SUFFIX) (Reg *d, Reg *s)
     XMM_ONLY(d->W(7) = (int16_t)s->W(6) - (int16_t)s->W(7));
 }
 
-void glue(helper_phsubd, SUFFIX) (Reg *d, Reg *s)
+void glue(helper_phsubd, SUFFIX)(Reg *d, Reg *s)
 {
     d->L(0) = (int32_t)d->L(0) - (int32_t)d->L(1);
     XMM_ONLY(d->L(1) = (int32_t)d->L(2) - (int32_t)d->L(3));
@@ -1408,7 +1466,7 @@ void glue(helper_phsubd, SUFFIX) (Reg *d, Reg *s)
     XMM_ONLY(d->L(3) = (int32_t)s->L(2) - (int32_t)s->L(3));
 }
 
-void glue(helper_phsubsw, SUFFIX) (Reg *d, Reg *s)
+void glue(helper_phsubsw, SUFFIX)(Reg *d, Reg *s)
 {
     d->W(0) = satsw((int16_t)d->W(0) - (int16_t)d->W(1));
     d->W(1) = satsw((int16_t)d->W(2) - (int16_t)d->W(3));
@@ -1420,24 +1478,24 @@ void glue(helper_phsubsw, SUFFIX) (Reg *d, Reg *s)
     XMM_ONLY(d->W(7) = satsw((int16_t)s->W(6) - (int16_t)s->W(7)));
 }
 
-#define FABSB(_, x) x > INT8_MAX  ? -(int8_t ) x : x
-#define FABSW(_, x) x > INT16_MAX ? -(int16_t) x : x
-#define FABSL(_, x) x > INT32_MAX ? -(int32_t) x : x
+#define FABSB(_, x) (x > INT8_MAX  ? -(int8_t)x : x)
+#define FABSW(_, x) (x > INT16_MAX ? -(int16_t)x : x)
+#define FABSL(_, x) (x > INT32_MAX ? -(int32_t)x : x)
 SSE_HELPER_B(helper_pabsb, FABSB)
 SSE_HELPER_W(helper_pabsw, FABSW)
 SSE_HELPER_L(helper_pabsd, FABSL)
 
-#define FMULHRSW(d, s) ((int16_t) d * (int16_t) s + 0x4000) >> 15
+#define FMULHRSW(d, s) (((int16_t) d * (int16_t)s + 0x4000) >> 15)
 SSE_HELPER_W(helper_pmulhrsw, FMULHRSW)
 
-#define FSIGNB(d, s) s <= INT8_MAX  ? s ? d : 0 : -(int8_t ) d
-#define FSIGNW(d, s) s <= INT16_MAX ? s ? d : 0 : -(int16_t) d
-#define FSIGNL(d, s) s <= INT32_MAX ? s ? d : 0 : -(int32_t) d
+#define FSIGNB(d, s) (s <= INT8_MAX  ? s ? d : 0 : -(int8_t)d)
+#define FSIGNW(d, s) (s <= INT16_MAX ? s ? d : 0 : -(int16_t)d)
+#define FSIGNL(d, s) (s <= INT32_MAX ? s ? d : 0 : -(int32_t)d)
 SSE_HELPER_B(helper_psignb, FSIGNB)
 SSE_HELPER_W(helper_psignw, FSIGNW)
 SSE_HELPER_L(helper_psignd, FSIGNL)
 
-void glue(helper_palignr, SUFFIX) (Reg *d, Reg *s, int32_t shift)
+void glue(helper_palignr, SUFFIX)(Reg *d, Reg *s, int32_t shift)
 {
     Reg r;
 
@@ -1449,17 +1507,17 @@ void glue(helper_palignr, SUFFIX) (Reg *d, Reg *s, int32_t shift)
         shift <<= 3;
 #define SHR(v, i) (i < 64 && i > -64 ? i > 0 ? v >> (i) : (v << -(i)) : 0)
 #if SHIFT == 0
-        r.Q(0) = SHR(s->Q(0), shift -   0) |
-                 SHR(d->Q(0), shift -  64);
+        r.Q(0) = SHR(s->Q(0), shift - 0) |
+            SHR(d->Q(0), shift -  64);
 #else
-        r.Q(0) = SHR(s->Q(0), shift -   0) |
-                 SHR(s->Q(1), shift -  64) |
-                 SHR(d->Q(0), shift - 128) |
-                 SHR(d->Q(1), shift - 192);
-        r.Q(1) = SHR(s->Q(0), shift +  64) |
-                 SHR(s->Q(1), shift -   0) |
-                 SHR(d->Q(0), shift -  64) |
-                 SHR(d->Q(1), shift - 128);
+        r.Q(0) = SHR(s->Q(0), shift - 0) |
+            SHR(s->Q(1), shift -  64) |
+            SHR(d->Q(0), shift - 128) |
+            SHR(d->Q(1), shift - 192);
+        r.Q(1) = SHR(s->Q(0), shift + 64) |
+            SHR(s->Q(1), shift -   0) |
+            SHR(d->Q(0), shift -  64) |
+            SHR(d->Q(1), shift - 128);
 #endif
 #undef SHR
     }
@@ -1467,72 +1525,78 @@ void glue(helper_palignr, SUFFIX) (Reg *d, Reg *s, int32_t shift)
     *d = r;
 }
 
-#define XMM0 env->xmm_regs[0]
+#define XMM0 (env->xmm_regs[0])
 
 #if SHIFT == 1
-#define SSE_HELPER_V(name, elem, num, F)\
-void glue(name, SUFFIX) (Reg *d, Reg *s)\
-{\
-    d->elem(0) = F(d->elem(0), s->elem(0), XMM0.elem(0));\
-    d->elem(1) = F(d->elem(1), s->elem(1), XMM0.elem(1));\
-    if (num > 2) {\
-        d->elem(2) = F(d->elem(2), s->elem(2), XMM0.elem(2));\
-        d->elem(3) = F(d->elem(3), s->elem(3), XMM0.elem(3));\
-        if (num > 4) {\
-            d->elem(4) = F(d->elem(4), s->elem(4), XMM0.elem(4));\
-            d->elem(5) = F(d->elem(5), s->elem(5), XMM0.elem(5));\
-            d->elem(6) = F(d->elem(6), s->elem(6), XMM0.elem(6));\
-            d->elem(7) = F(d->elem(7), s->elem(7), XMM0.elem(7));\
-            if (num > 8) {\
-                d->elem(8) = F(d->elem(8), s->elem(8), XMM0.elem(8));\
-                d->elem(9) = F(d->elem(9), s->elem(9), XMM0.elem(9));\
-                d->elem(10) = F(d->elem(10), s->elem(10), XMM0.elem(10));\
-                d->elem(11) = F(d->elem(11), s->elem(11), XMM0.elem(11));\
-                d->elem(12) = F(d->elem(12), s->elem(12), XMM0.elem(12));\
-                d->elem(13) = F(d->elem(13), s->elem(13), XMM0.elem(13));\
-                d->elem(14) = F(d->elem(14), s->elem(14), XMM0.elem(14));\
-                d->elem(15) = F(d->elem(15), s->elem(15), XMM0.elem(15));\
-            }\
-        }\
-    }\
-}
-
-#define SSE_HELPER_I(name, elem, num, F)\
-void glue(name, SUFFIX) (Reg *d, Reg *s, uint32_t imm)\
-{\
-    d->elem(0) = F(d->elem(0), s->elem(0), ((imm >> 0) & 1));\
-    d->elem(1) = F(d->elem(1), s->elem(1), ((imm >> 1) & 1));\
-    if (num > 2) {\
-        d->elem(2) = F(d->elem(2), s->elem(2), ((imm >> 2) & 1));\
-        d->elem(3) = F(d->elem(3), s->elem(3), ((imm >> 3) & 1));\
-        if (num > 4) {\
-            d->elem(4) = F(d->elem(4), s->elem(4), ((imm >> 4) & 1));\
-            d->elem(5) = F(d->elem(5), s->elem(5), ((imm >> 5) & 1));\
-            d->elem(6) = F(d->elem(6), s->elem(6), ((imm >> 6) & 1));\
-            d->elem(7) = F(d->elem(7), s->elem(7), ((imm >> 7) & 1));\
-            if (num > 8) {\
-                d->elem(8) = F(d->elem(8), s->elem(8), ((imm >> 8) & 1));\
-                d->elem(9) = F(d->elem(9), s->elem(9), ((imm >> 9) & 1));\
-                d->elem(10) = F(d->elem(10), s->elem(10), ((imm >> 10) & 1));\
-                d->elem(11) = F(d->elem(11), s->elem(11), ((imm >> 11) & 1));\
-                d->elem(12) = F(d->elem(12), s->elem(12), ((imm >> 12) & 1));\
-                d->elem(13) = F(d->elem(13), s->elem(13), ((imm >> 13) & 1));\
-                d->elem(14) = F(d->elem(14), s->elem(14), ((imm >> 14) & 1));\
-                d->elem(15) = F(d->elem(15), s->elem(15), ((imm >> 15) & 1));\
-            }\
-        }\
-    }\
-}
+#define SSE_HELPER_V(name, elem, num, F)                                \
+    void glue(name, SUFFIX)(Reg *d, Reg *s)                             \
+    {                                                                   \
+        d->elem(0) = F(d->elem(0), s->elem(0), XMM0.elem(0));           \
+        d->elem(1) = F(d->elem(1), s->elem(1), XMM0.elem(1));           \
+        if (num > 2) {                                                  \
+            d->elem(2) = F(d->elem(2), s->elem(2), XMM0.elem(2));       \
+            d->elem(3) = F(d->elem(3), s->elem(3), XMM0.elem(3));       \
+            if (num > 4) {                                              \
+                d->elem(4) = F(d->elem(4), s->elem(4), XMM0.elem(4));   \
+                d->elem(5) = F(d->elem(5), s->elem(5), XMM0.elem(5));   \
+                d->elem(6) = F(d->elem(6), s->elem(6), XMM0.elem(6));   \
+                d->elem(7) = F(d->elem(7), s->elem(7), XMM0.elem(7));   \
+                if (num > 8) {                                          \
+                    d->elem(8) = F(d->elem(8), s->elem(8), XMM0.elem(8)); \
+                    d->elem(9) = F(d->elem(9), s->elem(9), XMM0.elem(9)); \
+                    d->elem(10) = F(d->elem(10), s->elem(10), XMM0.elem(10)); \
+                    d->elem(11) = F(d->elem(11), s->elem(11), XMM0.elem(11)); \
+                    d->elem(12) = F(d->elem(12), s->elem(12), XMM0.elem(12)); \
+                    d->elem(13) = F(d->elem(13), s->elem(13), XMM0.elem(13)); \
+                    d->elem(14) = F(d->elem(14), s->elem(14), XMM0.elem(14)); \
+                    d->elem(15) = F(d->elem(15), s->elem(15), XMM0.elem(15)); \
+                }                                                       \
+            }                                                           \
+        }                                                               \
+    }
+
+#define SSE_HELPER_I(name, elem, num, F)                                \
+    void glue(name, SUFFIX)(Reg *d, Reg *s, uint32_t imm)               \
+    {                                                                   \
+        d->elem(0) = F(d->elem(0), s->elem(0), ((imm >> 0) & 1));       \
+        d->elem(1) = F(d->elem(1), s->elem(1), ((imm >> 1) & 1));       \
+        if (num > 2) {                                                  \
+            d->elem(2) = F(d->elem(2), s->elem(2), ((imm >> 2) & 1));   \
+            d->elem(3) = F(d->elem(3), s->elem(3), ((imm >> 3) & 1));   \
+            if (num > 4) {                                              \
+                d->elem(4) = F(d->elem(4), s->elem(4), ((imm >> 4) & 1)); \
+                d->elem(5) = F(d->elem(5), s->elem(5), ((imm >> 5) & 1)); \
+                d->elem(6) = F(d->elem(6), s->elem(6), ((imm >> 6) & 1)); \
+                d->elem(7) = F(d->elem(7), s->elem(7), ((imm >> 7) & 1)); \
+                if (num > 8) {                                          \
+                    d->elem(8) = F(d->elem(8), s->elem(8), ((imm >> 8) & 1)); \
+                    d->elem(9) = F(d->elem(9), s->elem(9), ((imm >> 9) & 1)); \
+                    d->elem(10) = F(d->elem(10), s->elem(10),           \
+                                    ((imm >> 10) & 1));                 \
+                    d->elem(11) = F(d->elem(11), s->elem(11),           \
+                                    ((imm >> 11) & 1));                 \
+                    d->elem(12) = F(d->elem(12), s->elem(12),           \
+                                    ((imm >> 12) & 1));                 \
+                    d->elem(13) = F(d->elem(13), s->elem(13),           \
+                                    ((imm >> 13) & 1));                 \
+                    d->elem(14) = F(d->elem(14), s->elem(14),           \
+                                    ((imm >> 14) & 1));                 \
+                    d->elem(15) = F(d->elem(15), s->elem(15),           \
+                                    ((imm >> 15) & 1));                 \
+                }                                                       \
+            }                                                           \
+        }                                                               \
+    }
 
 /* SSE4.1 op helpers */
-#define FBLENDVB(d, s, m) (m & 0x80) ? s : d
-#define FBLENDVPS(d, s, m) (m & 0x80000000) ? s : d
-#define FBLENDVPD(d, s, m) (m & 0x8000000000000000LL) ? s : d
+#define FBLENDVB(d, s, m) ((m & 0x80) ? s : d)
+#define FBLENDVPS(d, s, m) ((m & 0x80000000) ? s : d)
+#define FBLENDVPD(d, s, m) ((m & 0x8000000000000000LL) ? s : d)
 SSE_HELPER_V(helper_pblendvb, B, 16, FBLENDVB)
 SSE_HELPER_V(helper_blendvps, L, 4, FBLENDVPS)
 SSE_HELPER_V(helper_blendvpd, Q, 2, FBLENDVPD)
 
-void glue(helper_ptest, SUFFIX) (Reg *d, Reg *s)
+void glue(helper_ptest, SUFFIX)(Reg *d, Reg *s)
 {
     uint64_t zf = (s->Q(0) &  d->Q(0)) | (s->Q(1) &  d->Q(1));
     uint64_t cf = (s->Q(0) & ~d->Q(0)) | (s->Q(1) & ~d->Q(1));
@@ -1540,22 +1604,22 @@ void glue(helper_ptest, SUFFIX) (Reg *d, Reg *s)
     CC_SRC = (zf ? 0 : CC_Z) | (cf ? 0 : CC_C);
 }
 
-#define SSE_HELPER_F(name, elem, num, F)\
-void glue(name, SUFFIX) (Reg *d, Reg *s)\
-{\
-    d->elem(0) = F(0);\
-    d->elem(1) = F(1);\
-    if (num > 2) {\
-        d->elem(2) = F(2);\
-        d->elem(3) = F(3);\
-        if (num > 4) {\
-            d->elem(4) = F(4);\
-            d->elem(5) = F(5);\
-            d->elem(6) = F(6);\
-            d->elem(7) = F(7);\
-        }\
-    }\
-}
+#define SSE_HELPER_F(name, elem, num, F)        \
+    void glue(name, SUFFIX)(Reg *d, Reg *s)     \
+    {                                           \
+        d->elem(0) = F(0);                      \
+        d->elem(1) = F(1);                      \
+        if (num > 2) {                          \
+            d->elem(2) = F(2);                  \
+            d->elem(3) = F(3);                  \
+            if (num > 4) {                      \
+                d->elem(4) = F(4);              \
+                d->elem(5) = F(5);              \
+                d->elem(6) = F(6);              \
+                d->elem(7) = F(7);              \
+            }                                   \
+        }                                       \
+    }
 
 SSE_HELPER_F(helper_pmovsxbw, W, 8, (int8_t) s->B)
 SSE_HELPER_F(helper_pmovsxbd, L, 4, (int8_t) s->B)
@@ -1570,16 +1634,16 @@ SSE_HELPER_F(helper_pmovzxwd, L, 4, s->W)
 SSE_HELPER_F(helper_pmovzxwq, Q, 2, s->W)
 SSE_HELPER_F(helper_pmovzxdq, Q, 2, s->L)
 
-void glue(helper_pmuldq, SUFFIX) (Reg *d, Reg *s)
+void glue(helper_pmuldq, SUFFIX)(Reg *d, Reg *s)
 {
-    d->Q(0) = (int64_t) (int32_t) d->L(0) * (int32_t) s->L(0);
-    d->Q(1) = (int64_t) (int32_t) d->L(2) * (int32_t) s->L(2);
+    d->Q(0) = (int64_t)(int32_t) d->L(0) * (int32_t) s->L(0);
+    d->Q(1) = (int64_t)(int32_t) d->L(2) * (int32_t) s->L(2);
 }
 
-#define FCMPEQQ(d, s) d == s ? -1 : 0
+#define FCMPEQQ(d, s) (d == s ? -1 : 0)
 SSE_HELPER_Q(helper_pcmpeqq, FCMPEQQ)
 
-void glue(helper_packusdw, SUFFIX) (Reg *d, Reg *s)
+void glue(helper_packusdw, SUFFIX)(Reg *d, Reg *s)
 {
     d->W(0) = satuw((int32_t) d->L(0));
     d->W(1) = satuw((int32_t) d->L(1));
@@ -1591,10 +1655,10 @@ void glue(helper_packusdw, SUFFIX) (Reg *d, Reg *s)
     d->W(7) = satuw((int32_t) s->L(3));
 }
 
-#define FMINSB(d, s) MIN((int8_t) d, (int8_t) s)
-#define FMINSD(d, s) MIN((int32_t) d, (int32_t) s)
-#define FMAXSB(d, s) MAX((int8_t) d, (int8_t) s)
-#define FMAXSD(d, s) MAX((int32_t) d, (int32_t) s)
+#define FMINSB(d, s) MIN((int8_t)d, (int8_t)s)
+#define FMINSD(d, s) MIN((int32_t)d, (int32_t)s)
+#define FMAXSB(d, s) MAX((int8_t)d, (int8_t)s)
+#define FMAXSD(d, s) MAX((int32_t)d, (int32_t)s)
 SSE_HELPER_B(helper_pminsb, FMINSB)
 SSE_HELPER_L(helper_pminsd, FMINSD)
 SSE_HELPER_W(helper_pminuw, MIN)
@@ -1604,27 +1668,34 @@ SSE_HELPER_L(helper_pmaxsd, FMAXSD)
 SSE_HELPER_W(helper_pmaxuw, MAX)
 SSE_HELPER_L(helper_pmaxud, MAX)
 
-#define FMULLD(d, s) (int32_t) d * (int32_t) s
+#define FMULLD(d, s) ((int32_t)d * (int32_t)s)
 SSE_HELPER_L(helper_pmulld, FMULLD)
 
-void glue(helper_phminposuw, SUFFIX) (Reg *d, Reg *s)
+void glue(helper_phminposuw, SUFFIX)(Reg *d, Reg *s)
 {
     int idx = 0;
 
-    if (s->W(1) < s->W(idx))
+    if (s->W(1) < s->W(idx)) {
         idx = 1;
-    if (s->W(2) < s->W(idx))
+    }
+    if (s->W(2) < s->W(idx)) {
         idx = 2;
-    if (s->W(3) < s->W(idx))
+    }
+    if (s->W(3) < s->W(idx)) {
         idx = 3;
-    if (s->W(4) < s->W(idx))
+    }
+    if (s->W(4) < s->W(idx)) {
         idx = 4;
-    if (s->W(5) < s->W(idx))
+    }
+    if (s->W(5) < s->W(idx)) {
         idx = 5;
-    if (s->W(6) < s->W(idx))
+    }
+    if (s->W(6) < s->W(idx)) {
         idx = 6;
-    if (s->W(7) < s->W(idx))
+    }
+    if (s->W(7) < s->W(idx)) {
         idx = 7;
+    }
 
     d->Q(1) = 0;
     d->L(1) = 0;
@@ -1632,12 +1703,12 @@ void glue(helper_phminposuw, SUFFIX) (Reg *d, Reg *s)
     d->W(0) = s->W(idx);
 }
 
-void glue(helper_roundps, SUFFIX) (Reg *d, Reg *s, uint32_t mode)
+void glue(helper_roundps, SUFFIX)(Reg *d, Reg *s, uint32_t mode)
 {
     signed char prev_rounding_mode;
 
     prev_rounding_mode = env->sse_status.float_rounding_mode;
-    if (!(mode & (1 << 2)))
+    if (!(mode & (1 << 2))) {
         switch (mode & 3) {
         case 0:
             set_float_rounding_mode(float_round_nearest_even, &env->sse_status);
@@ -1652,6 +1723,7 @@ void glue(helper_roundps, SUFFIX) (Reg *d, Reg *s, uint32_t mode)
             set_float_rounding_mode(float_round_to_zero, &env->sse_status);
             break;
         }
+    }
 
     d->XMM_S(0) = float32_round_to_int(s->XMM_S(0), &env->sse_status);
     d->XMM_S(1) = float32_round_to_int(s->XMM_S(1), &env->sse_status);
@@ -1659,21 +1731,21 @@ void glue(helper_roundps, SUFFIX) (Reg *d, Reg *s, uint32_t mode)
     d->XMM_S(3) = float32_round_to_int(s->XMM_S(3), &env->sse_status);
 
 #if 0 /* TODO */
-    if (mode & (1 << 3))
-        set_float_exception_flags(
-                        get_float_exception_flags(&env->sse_status) &
-                        ~float_flag_inexact,
-                        &env->sse_status);
+    if (mode & (1 << 3)) {
+        set_float_exception_flags(get_float_exception_flags(&env->sse_status) &
+                                  ~float_flag_inexact,
+                                  &env->sse_status);
+    }
 #endif
     env->sse_status.float_rounding_mode = prev_rounding_mode;
 }
 
-void glue(helper_roundpd, SUFFIX) (Reg *d, Reg *s, uint32_t mode)
+void glue(helper_roundpd, SUFFIX)(Reg *d, Reg *s, uint32_t mode)
 {
     signed char prev_rounding_mode;
 
     prev_rounding_mode = env->sse_status.float_rounding_mode;
-    if (!(mode & (1 << 2)))
+    if (!(mode & (1 << 2))) {
         switch (mode & 3) {
         case 0:
             set_float_rounding_mode(float_round_nearest_even, &env->sse_status);
@@ -1688,26 +1760,27 @@ void glue(helper_roundpd, SUFFIX) (Reg *d, Reg *s, uint32_t mode)
             set_float_rounding_mode(float_round_to_zero, &env->sse_status);
             break;
         }
+    }
 
     d->XMM_D(0) = float64_round_to_int(s->XMM_D(0), &env->sse_status);
     d->XMM_D(1) = float64_round_to_int(s->XMM_D(1), &env->sse_status);
 
 #if 0 /* TODO */
-    if (mode & (1 << 3))
-        set_float_exception_flags(
-                        get_float_exception_flags(&env->sse_status) &
-                        ~float_flag_inexact,
-                        &env->sse_status);
+    if (mode & (1 << 3)) {
+        set_float_exception_flags(get_float_exception_flags(&env->sse_status) &
+                                  ~float_flag_inexact,
+                                  &env->sse_status);
+    }
 #endif
     env->sse_status.float_rounding_mode = prev_rounding_mode;
 }
 
-void glue(helper_roundss, SUFFIX) (Reg *d, Reg *s, uint32_t mode)
+void glue(helper_roundss, SUFFIX)(Reg *d, Reg *s, uint32_t mode)
 {
     signed char prev_rounding_mode;
 
     prev_rounding_mode = env->sse_status.float_rounding_mode;
-    if (!(mode & (1 << 2)))
+    if (!(mode & (1 << 2))) {
         switch (mode & 3) {
         case 0:
             set_float_rounding_mode(float_round_nearest_even, &env->sse_status);
@@ -1722,25 +1795,26 @@ void glue(helper_roundss, SUFFIX) (Reg *d, Reg *s, uint32_t mode)
             set_float_rounding_mode(float_round_to_zero, &env->sse_status);
             break;
         }
+    }
 
     d->XMM_S(0) = float32_round_to_int(s->XMM_S(0), &env->sse_status);
 
 #if 0 /* TODO */
-    if (mode & (1 << 3))
-        set_float_exception_flags(
-                        get_float_exception_flags(&env->sse_status) &
-                        ~float_flag_inexact,
-                        &env->sse_status);
+    if (mode & (1 << 3)) {
+        set_float_exception_flags(get_float_exception_flags(&env->sse_status) &
+                                  ~float_flag_inexact,
+                                  &env->sse_status);
+    }
 #endif
     env->sse_status.float_rounding_mode = prev_rounding_mode;
 }
 
-void glue(helper_roundsd, SUFFIX) (Reg *d, Reg *s, uint32_t mode)
+void glue(helper_roundsd, SUFFIX)(Reg *d, Reg *s, uint32_t mode)
 {
     signed char prev_rounding_mode;
 
     prev_rounding_mode = env->sse_status.float_rounding_mode;
-    if (!(mode & (1 << 2)))
+    if (!(mode & (1 << 2))) {
         switch (mode & 3) {
         case 0:
             set_float_rounding_mode(float_round_nearest_even, &env->sse_status);
@@ -1755,67 +1829,80 @@ void glue(helper_roundsd, SUFFIX) (Reg *d, Reg *s, uint32_t mode)
             set_float_rounding_mode(float_round_to_zero, &env->sse_status);
             break;
         }
+    }
 
     d->XMM_D(0) = float64_round_to_int(s->XMM_D(0), &env->sse_status);
 
 #if 0 /* TODO */
-    if (mode & (1 << 3))
-        set_float_exception_flags(
-                        get_float_exception_flags(&env->sse_status) &
-                        ~float_flag_inexact,
-                        &env->sse_status);
+    if (mode & (1 << 3)) {
+        set_float_exception_flags(get_float_exception_flags(&env->sse_status) &
+                                  ~float_flag_inexact,
+                                  &env->sse_status);
+    }
 #endif
     env->sse_status.float_rounding_mode = prev_rounding_mode;
 }
 
-#define FBLENDP(d, s, m) m ? s : d
+#define FBLENDP(d, s, m) (m ? s : d)
 SSE_HELPER_I(helper_blendps, L, 4, FBLENDP)
 SSE_HELPER_I(helper_blendpd, Q, 2, FBLENDP)
 SSE_HELPER_I(helper_pblendw, W, 8, FBLENDP)
 
-void glue(helper_dpps, SUFFIX) (Reg *d, Reg *s, uint32_t mask)
+void glue(helper_dpps, SUFFIX)(Reg *d, Reg *s, uint32_t mask)
 {
     float32 iresult = float32_zero;
 
-    if (mask & (1 << 4))
+    if (mask & (1 << 4)) {
         iresult = float32_add(iresult,
-                        float32_mul(d->XMM_S(0), s->XMM_S(0), &env->sse_status),
-                        &env->sse_status);
-    if (mask & (1 << 5))
+                              float32_mul(d->XMM_S(0), s->XMM_S(0),
+                                          &env->sse_status),
+                              &env->sse_status);
+    }
+    if (mask & (1 << 5)) {
         iresult = float32_add(iresult,
-                        float32_mul(d->XMM_S(1), s->XMM_S(1), &env->sse_status),
-                        &env->sse_status);
-    if (mask & (1 << 6))
+                              float32_mul(d->XMM_S(1), s->XMM_S(1),
+                                          &env->sse_status),
+                              &env->sse_status);
+    }
+    if (mask & (1 << 6)) {
         iresult = float32_add(iresult,
-                        float32_mul(d->XMM_S(2), s->XMM_S(2), &env->sse_status),
-                        &env->sse_status);
-    if (mask & (1 << 7))
+                              float32_mul(d->XMM_S(2), s->XMM_S(2),
+                                          &env->sse_status),
+                              &env->sse_status);
+    }
+    if (mask & (1 << 7)) {
         iresult = float32_add(iresult,
-                        float32_mul(d->XMM_S(3), s->XMM_S(3), &env->sse_status),
-                        &env->sse_status);
+                              float32_mul(d->XMM_S(3), s->XMM_S(3),
+                                          &env->sse_status),
+                              &env->sse_status);
+    }
     d->XMM_S(0) = (mask & (1 << 0)) ? iresult : float32_zero;
     d->XMM_S(1) = (mask & (1 << 1)) ? iresult : float32_zero;
     d->XMM_S(2) = (mask & (1 << 2)) ? iresult : float32_zero;
     d->XMM_S(3) = (mask & (1 << 3)) ? iresult : float32_zero;
 }
 
-void glue(helper_dppd, SUFFIX) (Reg *d, Reg *s, uint32_t mask)
+void glue(helper_dppd, SUFFIX)(Reg *d, Reg *s, uint32_t mask)
 {
     float64 iresult = float64_zero;
 
-    if (mask & (1 << 4))
+    if (mask & (1 << 4)) {
         iresult = float64_add(iresult,
-                        float64_mul(d->XMM_D(0), s->XMM_D(0), &env->sse_status),
-                        &env->sse_status);
-    if (mask & (1 << 5))
+                              float64_mul(d->XMM_D(0), s->XMM_D(0),
+                                          &env->sse_status),
+                              &env->sse_status);
+    }
+    if (mask & (1 << 5)) {
         iresult = float64_add(iresult,
-                        float64_mul(d->XMM_D(1), s->XMM_D(1), &env->sse_status),
-                        &env->sse_status);
+                              float64_mul(d->XMM_D(1), s->XMM_D(1),
+                                          &env->sse_status),
+                              &env->sse_status);
+    }
     d->XMM_D(0) = (mask & (1 << 0)) ? iresult : float64_zero;
     d->XMM_D(1) = (mask & (1 << 1)) ? iresult : float64_zero;
 }
 
-void glue(helper_mpsadbw, SUFFIX) (Reg *d, Reg *s, uint32_t offset)
+void glue(helper_mpsadbw, SUFFIX)(Reg *d, Reg *s, uint32_t offset)
 {
     int s0 = (offset & 3) << 2;
     int d0 = (offset & 4) << 0;
@@ -1835,7 +1922,7 @@ void glue(helper_mpsadbw, SUFFIX) (Reg *d, Reg *s, uint32_t offset)
 
 /* SSE4.2 op helpers */
 /* it's unclear whether signed or unsigned */
-#define FCMPGTQ(d, s) d > s ? -1 : 0
+#define FCMPGTQ(d, s) (d > s ? -1 : 0)
 SSE_HELPER_Q(helper_pcmpgtq, FCMPGTQ)
 
 static inline int pcmp_elen(int reg, uint32_t ctrl)
@@ -1843,18 +1930,21 @@ static inline int pcmp_elen(int reg, uint32_t ctrl)
     int val;
 
     /* Presence of REX.W is indicated by a bit higher than 7 set */
-    if (ctrl >> 8)
-        val = abs1((int64_t) env->regs[reg]);
-    else
-        val = abs1((int32_t) env->regs[reg]);
+    if (ctrl >> 8) {
+        val = abs1((int64_t)env->regs[reg]);
+    } else {
+        val = abs1((int32_t)env->regs[reg]);
+    }
 
     if (ctrl & 1) {
-        if (val > 8)
+        if (val > 8) {
             return 8;
-    } else
-        if (val > 16)
+        }
+    } else {
+        if (val > 16) {
             return 16;
-
+        }
+    }
     return val;
 }
 
@@ -1863,11 +1953,14 @@ static inline int pcmp_ilen(Reg *r, uint8_t ctrl)
     int val = 0;
 
     if (ctrl & 1) {
-        while (val < 8 && r->W(val))
+        while (val < 8 && r->W(val)) {
             val++;
-    } else
-        while (val < 16 && r->B(val))
+        }
+    } else {
+        while (val < 16 && r->B(val)) {
             val++;
+        }
+    }
 
     return val;
 }
@@ -1880,15 +1973,15 @@ static inline int pcmp_val(Reg *r, uint8_t ctrl, int i)
     case 1:
         return r->W(i);
     case 2:
-        return (int8_t) r->B(i);
+        return (int8_t)r->B(i);
     case 3:
     default:
-        return (int16_t) r->W(i);
+        return (int16_t)r->W(i);
     }
 }
 
 static inline unsigned pcmpxstrx(Reg *d, Reg *s,
-                int8_t ctrl, int valids, int validd)
+                                 int8_t ctrl, int valids, int validd)
 {
     unsigned int res = 0;
     int v;
@@ -1905,17 +1998,19 @@ static inline unsigned pcmpxstrx(Reg *d, Reg *s,
         for (j = valids; j >= 0; j--) {
             res <<= 1;
             v = pcmp_val(s, ctrl, j);
-            for (i = validd; i >= 0; i--)
+            for (i = validd; i >= 0; i--) {
                 res |= (v == pcmp_val(d, ctrl, i));
+            }
         }
         break;
     case 1:
         for (j = valids; j >= 0; j--) {
             res <<= 1;
             v = pcmp_val(s, ctrl, j);
-            for (i = ((validd - 1) | 1); i >= 0; i -= 2)
+            for (i = ((validd - 1) | 1); i >= 0; i -= 2) {
                 res |= (pcmp_val(d, ctrl, i - 0) <= v &&
                         pcmp_val(d, ctrl, i - 1) >= v);
+            }
         }
         break;
     case 2:
@@ -1931,8 +2026,9 @@ static inline unsigned pcmpxstrx(Reg *d, Reg *s,
         for (j = valids - validd; j >= 0; j--) {
             res <<= 1;
             res |= 1;
-            for (i = MIN(upper - j, validd); i >= 0; i--)
+            for (i = MIN(upper - j, validd); i >= 0; i--) {
                 res &= (pcmp_val(s, ctrl, i + j) == pcmp_val(d, ctrl, i));
+            }
         }
         break;
     }
@@ -1946,10 +2042,12 @@ static inline unsigned pcmpxstrx(Reg *d, Reg *s,
         break;
     }
 
-    if (res)
-       CC_SRC |= CC_C;
-    if (res & 1)
-       CC_SRC |= CC_O;
+    if (res) {
+        CC_SRC |= CC_C;
+    }
+    if (res & 1) {
+        CC_SRC |= CC_O;
+    }
 
     return res;
 }
@@ -1958,11 +2056,12 @@ static inline int rffs1(unsigned int val)
 {
     int ret = 1, hi;
 
-    for (hi = sizeof(val) * 4; hi; hi /= 2)
+    for (hi = sizeof(val) * 4; hi; hi /= 2) {
         if (val >> hi) {
             val >>= hi;
             ret += hi;
         }
+    }
 
     return ret;
 }
@@ -1971,77 +2070,82 @@ static inline int ffs1(unsigned int val)
 {
     int ret = 1, hi;
 
-    for (hi = sizeof(val) * 4; hi; hi /= 2)
+    for (hi = sizeof(val) * 4; hi; hi /= 2) {
         if (val << hi) {
             val <<= hi;
             ret += hi;
         }
+    }
 
     return ret;
 }
 
-void glue(helper_pcmpestri, SUFFIX) (Reg *d, Reg *s, uint32_t ctrl)
+void glue(helper_pcmpestri, SUFFIX)(Reg *d, Reg *s, uint32_t ctrl)
 {
     unsigned int res = pcmpxstrx(d, s, ctrl,
-                    pcmp_elen(R_EDX, ctrl),
-                    pcmp_elen(R_EAX, ctrl));
+                                 pcmp_elen(R_EDX, ctrl),
+                                 pcmp_elen(R_EAX, ctrl));
 
-    if (res)
+    if (res) {
         env->regs[R_ECX] = ((ctrl & (1 << 6)) ? rffs1 : ffs1)(res) - 1;
-    else
+    } else {
         env->regs[R_ECX] = 16 >> (ctrl & (1 << 0));
+    }
 }
 
-void glue(helper_pcmpestrm, SUFFIX) (Reg *d, Reg *s, uint32_t ctrl)
+void glue(helper_pcmpestrm, SUFFIX)(Reg *d, Reg *s, uint32_t ctrl)
 {
     int i;
     unsigned int res = pcmpxstrx(d, s, ctrl,
-                    pcmp_elen(R_EDX, ctrl),
-                    pcmp_elen(R_EAX, ctrl));
+                                 pcmp_elen(R_EDX, ctrl),
+                                 pcmp_elen(R_EAX, ctrl));
 
     if ((ctrl >> 6) & 1) {
-        if (ctrl & 1)
+        if (ctrl & 1) {
             for (i = 0; i < 8; i++, res >>= 1) {
                 d->W(i) = (res & 1) ? ~0 : 0;
             }
-        else
+        } else {
             for (i = 0; i < 16; i++, res >>= 1) {
                 d->B(i) = (res & 1) ? ~0 : 0;
             }
+        }
     } else {
         d->Q(1) = 0;
         d->Q(0) = res;
     }
 }
 
-void glue(helper_pcmpistri, SUFFIX) (Reg *d, Reg *s, uint32_t ctrl)
+void glue(helper_pcmpistri, SUFFIX)(Reg *d, Reg *s, uint32_t ctrl)
 {
     unsigned int res = pcmpxstrx(d, s, ctrl,
-                    pcmp_ilen(s, ctrl),
-                    pcmp_ilen(d, ctrl));
+                                 pcmp_ilen(s, ctrl),
+                                 pcmp_ilen(d, ctrl));
 
-    if (res)
+    if (res) {
         env->regs[R_ECX] = ((ctrl & (1 << 6)) ? rffs1 : ffs1)(res) - 1;
-    else
+    } else {
         env->regs[R_ECX] = 16 >> (ctrl & (1 << 0));
+    }
 }
 
-void glue(helper_pcmpistrm, SUFFIX) (Reg *d, Reg *s, uint32_t ctrl)
+void glue(helper_pcmpistrm, SUFFIX)(Reg *d, Reg *s, uint32_t ctrl)
 {
     int i;
     unsigned int res = pcmpxstrx(d, s, ctrl,
-                    pcmp_ilen(s, ctrl),
-                    pcmp_ilen(d, ctrl));
+                                 pcmp_ilen(s, ctrl),
+                                 pcmp_ilen(d, ctrl));
 
     if ((ctrl >> 6) & 1) {
-        if (ctrl & 1)
+        if (ctrl & 1) {
             for (i = 0; i < 8; i++, res >>= 1) {
                 d->W(i) = (res & 1) ? ~0 : 0;
             }
-        else
+        } else {
             for (i = 0; i < 16; i++, res >>= 1) {
                 d->B(i) = (res & 1) ? ~0 : 0;
             }
+        }
     } else {
         d->Q(1) = 0;
         d->Q(0) = res;
@@ -2053,16 +2157,17 @@ void glue(helper_pcmpistrm, SUFFIX) (Reg *d, Reg *s, uint32_t ctrl)
 target_ulong helper_crc32(uint32_t crc1, target_ulong msg, uint32_t len)
 {
     target_ulong crc = (msg & ((target_ulong) -1 >>
-                            (TARGET_LONG_BITS - len))) ^ crc1;
+                               (TARGET_LONG_BITS - len))) ^ crc1;
 
-    while (len--)
+    while (len--) {
         crc = (crc >> 1) ^ ((crc & 1) ? CRCPOLY_BITREV : 0);
+    }
 
     return crc;
 }
 
 #define POPMASK(i)     ((target_ulong) -1 / ((1LL << (1 << i)) + 1))
-#define POPCOUNT(n, i) (n & POPMASK(i)) + ((n >> (1 << i)) & POPMASK(i))
+#define POPCOUNT(n, i) ((n & POPMASK(i)) + ((n >> (1 << i)) & POPMASK(i)))
 target_ulong helper_popcnt(target_ulong n, uint32_t type)
 {
     CC_SRC = n ? 0 : CC_Z;
@@ -2071,15 +2176,17 @@ target_ulong helper_popcnt(target_ulong n, uint32_t type)
     n = POPCOUNT(n, 1);
     n = POPCOUNT(n, 2);
     n = POPCOUNT(n, 3);
-    if (type == 1)
+    if (type == 1) {
         return n & 0xff;
+    }
 
     n = POPCOUNT(n, 4);
 #ifndef TARGET_X86_64
     return n;
 #else
-    if (type == 2)
+    if (type == 2) {
         return n & 0xff;
+    }
 
     return POPCOUNT(n, 5);
 #endif
commit 9dd69d65aa0c25692be1722d0a05315b9a02422e
Author: Blue Swirl <blauwirbel at gmail.com>
Date:   Sun Apr 29 09:07:22 2012 +0000

    x86: avoid an extern declaration
    
    After the previous patch, we can use the proper
    declaration in a common header file.
    
    Signed-off-by: Blue Swirl <blauwirbel at gmail.com>

diff --git a/target-i386/excp_helper.c b/target-i386/excp_helper.c
index 72bd46d..aaa5ca2 100644
--- a/target-i386/excp_helper.c
+++ b/target-i386/excp_helper.c
@@ -19,6 +19,7 @@
 
 #include "cpu.h"
 #include "qemu-log.h"
+#include "sysemu.h"
 #include "helper.h"
 
 #if 0
@@ -39,10 +40,6 @@ void helper_raise_exception(CPUX86State *env, int exception_index)
     raise_exception(env, exception_index);
 }
 
-
-/* This should come from sysemu.h - if we could include it here... */
-void qemu_system_reset_request(void);
-
 /*
  * Check nested exceptions and change to double or triple fault if
  * needed. It should only be called, if this is not an interrupt.
commit 599b9a5a51ee958af9b5d5b9b8460c0ec786c639
Author: Blue Swirl <blauwirbel at gmail.com>
Date:   Sat Apr 28 19:53:52 2012 +0000

    x86: split off exception handlers
    
    Move exception handlers from op_helper.c to excp_helper.c.
    
    Signed-off-by: Blue Swirl <blauwirbel at gmail.com>

diff --git a/target-i386/Makefile.objs b/target-i386/Makefile.objs
index f913755..c0feffe 100644
--- a/target-i386/Makefile.objs
+++ b/target-i386/Makefile.objs
@@ -1,4 +1,5 @@
 obj-y += translate.o op_helper.o helper.o cpu.o
+obj-y += excp_helper.o
 obj-$(CONFIG_SOFTMMU) += machine.o arch_memory_mapping.o arch_dump.o
 obj-$(CONFIG_KVM) += kvm.o hyperv.o
 obj-$(CONFIG_LINUX_USER) += ioport-user.o
diff --git a/target-i386/cpu.h b/target-i386/cpu.h
index c546723..cea8ecc 100644
--- a/target-i386/cpu.h
+++ b/target-i386/cpu.h
@@ -1071,12 +1071,16 @@ void cpu_x86_inject_mce(Monitor *mon, CPUX86State *cenv, int bank,
                         uint64_t status, uint64_t mcg_status, uint64_t addr,
                         uint64_t misc, int flags);
 
-/* op_helper.c */
-void do_interrupt(CPUX86State *env);
-void do_interrupt_x86_hardirq(CPUX86State *env, int intno, int is_hw);
+/* excp_helper.c */
 void QEMU_NORETURN raise_exception(CPUX86State *env, int exception_index);
 void QEMU_NORETURN raise_exception_err(CPUX86State *env, int exception_index,
                                        int error_code);
+void QEMU_NORETURN raise_interrupt(CPUX86State *nenv, int intno, int is_int,
+                                   int error_code, int next_eip_addend);
+
+/* op_helper.c */
+void do_interrupt(CPUX86State *env);
+void do_interrupt_x86_hardirq(CPUX86State *env, int intno, int is_hw);
 
 void do_smm_enter(CPUX86State *env1);
 
diff --git a/target-i386/excp_helper.c b/target-i386/excp_helper.c
new file mode 100644
index 0000000..72bd46d
--- /dev/null
+++ b/target-i386/excp_helper.c
@@ -0,0 +1,132 @@
+/*
+ *  x86 exception helpers
+ *
+ *  Copyright (c) 2003 Fabrice Bellard
+ *
+ * This library is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Lesser General Public
+ * License as published by the Free Software Foundation; either
+ * version 2 of the License, or (at your option) any later version.
+ *
+ * This library is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
+ * Lesser General Public License for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public
+ * License along with this library; if not, see <http://www.gnu.org/licenses/>.
+ */
+
+#include "cpu.h"
+#include "qemu-log.h"
+#include "helper.h"
+
+#if 0
+#define raise_exception_err(env, a, b)                                  \
+    do {                                                                \
+        qemu_log("raise_exception line=%d\n", __LINE__);                \
+        (raise_exception_err)(env, a, b);                               \
+    } while (0)
+#endif
+
+void helper_raise_interrupt(CPUX86State *env, int intno, int next_eip_addend)
+{
+    raise_interrupt(env, intno, 1, 0, next_eip_addend);
+}
+
+void helper_raise_exception(CPUX86State *env, int exception_index)
+{
+    raise_exception(env, exception_index);
+}
+
+
+/* This should come from sysemu.h - if we could include it here... */
+void qemu_system_reset_request(void);
+
+/*
+ * Check nested exceptions and change to double or triple fault if
+ * needed. It should only be called, if this is not an interrupt.
+ * Returns the new exception number.
+ */
+static int check_exception(CPUX86State *env, int intno, int *error_code)
+{
+    int first_contributory = env->old_exception == 0 ||
+                              (env->old_exception >= 10 &&
+                               env->old_exception <= 13);
+    int second_contributory = intno == 0 ||
+                               (intno >= 10 && intno <= 13);
+
+    qemu_log_mask(CPU_LOG_INT, "check_exception old: 0x%x new 0x%x\n",
+                env->old_exception, intno);
+
+#if !defined(CONFIG_USER_ONLY)
+    if (env->old_exception == EXCP08_DBLE) {
+        if (env->hflags & HF_SVMI_MASK) {
+            cpu_vmexit(env, SVM_EXIT_SHUTDOWN, 0); /* does not return */
+        }
+
+        qemu_log_mask(CPU_LOG_RESET, "Triple fault\n");
+
+        qemu_system_reset_request();
+        return EXCP_HLT;
+    }
+#endif
+
+    if ((first_contributory && second_contributory)
+        || (env->old_exception == EXCP0E_PAGE &&
+            (second_contributory || (intno == EXCP0E_PAGE)))) {
+        intno = EXCP08_DBLE;
+        *error_code = 0;
+    }
+
+    if (second_contributory || (intno == EXCP0E_PAGE) ||
+        (intno == EXCP08_DBLE)) {
+        env->old_exception = intno;
+    }
+
+    return intno;
+}
+
+/*
+ * Signal an interruption. It is executed in the main CPU loop.
+ * is_int is TRUE if coming from the int instruction. next_eip is the
+ * EIP value AFTER the interrupt instruction. It is only relevant if
+ * is_int is TRUE.
+ */
+static void QEMU_NORETURN raise_interrupt2(CPUX86State *env, int intno,
+                                           int is_int, int error_code,
+                                           int next_eip_addend)
+{
+    if (!is_int) {
+        cpu_svm_check_intercept_param(env, SVM_EXIT_EXCP_BASE + intno,
+                                      error_code);
+        intno = check_exception(env, intno, &error_code);
+    } else {
+        cpu_svm_check_intercept_param(env, SVM_EXIT_SWINT, 0);
+    }
+
+    env->exception_index = intno;
+    env->error_code = error_code;
+    env->exception_is_int = is_int;
+    env->exception_next_eip = env->eip + next_eip_addend;
+    cpu_loop_exit(env);
+}
+
+/* shortcuts to generate exceptions */
+
+void QEMU_NORETURN raise_interrupt(CPUX86State *env, int intno, int is_int,
+                                   int error_code, int next_eip_addend)
+{
+    raise_interrupt2(env, intno, is_int, error_code, next_eip_addend);
+}
+
+void raise_exception_err(CPUX86State *env, int exception_index,
+                         int error_code)
+{
+    raise_interrupt2(env, exception_index, 0, error_code, 0);
+}
+
+void raise_exception(CPUX86State *env, int exception_index)
+{
+    raise_interrupt2(env, exception_index, 0, 0, 0);
+}
diff --git a/target-i386/op_helper.c b/target-i386/op_helper.c
index 773148c..8625936 100644
--- a/target-i386/op_helper.c
+++ b/target-i386/op_helper.c
@@ -138,14 +138,6 @@ static inline void cpu_load_efer(CPUX86State *env, uint64_t val)
     }
 }
 
-#if 0
-#define raise_exception_err(env, a, b)                                  \
-    do {                                                                \
-        qemu_log("raise_exception line=%d\n", __LINE__);                \
-        (raise_exception_err)(env, a, b);                               \
-    } while (0)
-#endif
-
 static const uint8_t parity_table[256] = {
     CC_P, 0, 0, CC_P, 0, CC_P, CC_P, 0,
     0, CC_P, CC_P, 0, CC_P, 0, 0, CC_P,
@@ -1529,101 +1521,6 @@ void do_interrupt_x86_hardirq(CPUX86State *env1, int intno, int is_hw)
     env = saved_env;
 }
 
-/* This should come from sysemu.h - if we could include it here... */
-void qemu_system_reset_request(void);
-
-/*
- * Check nested exceptions and change to double or triple fault if
- * needed. It should only be called, if this is not an interrupt.
- * Returns the new exception number.
- */
-static int check_exception(CPUX86State *env, int intno, int *error_code)
-{
-    int first_contributory = env->old_exception == 0 ||
-                              (env->old_exception >= 10 &&
-                               env->old_exception <= 13);
-    int second_contributory = intno == 0 ||
-                               (intno >= 10 && intno <= 13);
-
-    qemu_log_mask(CPU_LOG_INT, "check_exception old: 0x%x new 0x%x\n",
-                env->old_exception, intno);
-
-#if !defined(CONFIG_USER_ONLY)
-    if (env->old_exception == EXCP08_DBLE) {
-        if (env->hflags & HF_SVMI_MASK) {
-            cpu_vmexit(env, SVM_EXIT_SHUTDOWN, 0); /* does not return */
-        }
-
-        qemu_log_mask(CPU_LOG_RESET, "Triple fault\n");
-
-        qemu_system_reset_request();
-        return EXCP_HLT;
-    }
-#endif
-
-    if ((first_contributory && second_contributory)
-        || (env->old_exception == EXCP0E_PAGE &&
-            (second_contributory || (intno == EXCP0E_PAGE)))) {
-        intno = EXCP08_DBLE;
-        *error_code = 0;
-    }
-
-    if (second_contributory || (intno == EXCP0E_PAGE) ||
-        (intno == EXCP08_DBLE)) {
-        env->old_exception = intno;
-    }
-
-    return intno;
-}
-
-/*
- * Signal an interruption. It is executed in the main CPU loop.
- * is_int is TRUE if coming from the int instruction. next_eip is the
- * EIP value AFTER the interrupt instruction. It is only relevant if
- * is_int is TRUE.
- */
-static void QEMU_NORETURN raise_interrupt2(CPUX86State *env, int intno,
-                                           int is_int, int error_code,
-                                           int next_eip_addend)
-{
-    if (!is_int) {
-        cpu_svm_check_intercept_param(env, SVM_EXIT_EXCP_BASE + intno,
-                                      error_code);
-        intno = check_exception(env, intno, &error_code);
-    } else {
-        cpu_svm_check_intercept_param(env, SVM_EXIT_SWINT, 0);
-    }
-
-    env->exception_index = intno;
-    env->error_code = error_code;
-    env->exception_is_int = is_int;
-    env->exception_next_eip = env->eip + next_eip_addend;
-    cpu_loop_exit(env);
-}
-
-/* shortcuts to generate exceptions */
-
-static void QEMU_NORETURN raise_interrupt(CPUX86State *nenv,
-                                          int intno, int is_int,
-                                          int error_code,
-                                          int next_eip_addend)
-{
-    env = nenv;
-    raise_interrupt2(env, intno, is_int, error_code, next_eip_addend);
-}
-
-void raise_exception_err(CPUX86State *nenv, int exception_index,
-                         int error_code)
-{
-    env = nenv;
-    raise_interrupt2(env, exception_index, 0, error_code, 0);
-}
-
-void raise_exception(CPUX86State *nenv, int exception_index)
-{
-    env = nenv;
-    raise_interrupt2(env, exception_index, 0, 0, 0);
-}
 /* SMM support */
 
 #if defined(CONFIG_USER_ONLY)
@@ -5221,16 +5118,6 @@ void helper_reset_rf(void)
     env->eflags &= ~RF_MASK;
 }
 
-void helper_raise_interrupt(CPUX86State *env, int intno, int next_eip_addend)
-{
-    raise_interrupt(env, intno, 1, 0, next_eip_addend);
-}
-
-void helper_raise_exception(CPUX86State *env, int exception_index)
-{
-    raise_exception(env, exception_index);
-}
-
 void helper_cli(void)
 {
     env->eflags &= ~IF_MASK;
commit 77b2bc2c096be44a36c45d777abb81a298c05c98
Author: Blue Swirl <blauwirbel at gmail.com>
Date:   Sat Apr 28 19:35:10 2012 +0000

    x86: avoid AREG0 for exceptions
    
    Add an explicit CPUX86State parameter instead of relying on AREG0.
    
    Merge raise_exception_env() to raise_exception(), likewise with
    raise_exception_err_env() and raise_exception_err().
    
    Introduce cpu_svm_check_intercept_param() and cpu_vmexit()
    as wrappers.
    
    Signed-off-by: Blue Swirl <blauwirbel at gmail.com>

diff --git a/cpu-exec.c b/cpu-exec.c
index 624c409..08c35f7 100644
--- a/cpu-exec.c
+++ b/cpu-exec.c
@@ -289,7 +289,8 @@ int cpu_exec(CPUArchState *env)
 #endif
 #if defined(TARGET_I386)
                     if (interrupt_request & CPU_INTERRUPT_INIT) {
-                            svm_check_intercept(env, SVM_EXIT_INIT);
+                            cpu_svm_check_intercept_param(env, SVM_EXIT_INIT,
+                                                          0);
                             do_cpu_init(x86_env_get_cpu(env));
                             env->exception_index = EXCP_HALTED;
                             cpu_loop_exit(env);
@@ -298,7 +299,8 @@ int cpu_exec(CPUArchState *env)
                     } else if (env->hflags2 & HF2_GIF_MASK) {
                         if ((interrupt_request & CPU_INTERRUPT_SMI) &&
                             !(env->hflags & HF_SMM_MASK)) {
-                            svm_check_intercept(env, SVM_EXIT_SMI);
+                            cpu_svm_check_intercept_param(env, SVM_EXIT_SMI,
+                                                          0);
                             env->interrupt_request &= ~CPU_INTERRUPT_SMI;
                             do_smm_enter(env);
                             next_tb = 0;
@@ -319,7 +321,8 @@ int cpu_exec(CPUArchState *env)
                                      (env->eflags & IF_MASK && 
                                       !(env->hflags & HF_INHIBIT_IRQ_MASK))))) {
                             int intno;
-                            svm_check_intercept(env, SVM_EXIT_INTR);
+                            cpu_svm_check_intercept_param(env, SVM_EXIT_INTR,
+                                                          0);
                             env->interrupt_request &= ~(CPU_INTERRUPT_HARD | CPU_INTERRUPT_VIRQ);
                             intno = cpu_get_pic_interrupt(env);
                             qemu_log_mask(CPU_LOG_TB_IN_ASM, "Servicing hardware INT=0x%02x\n", intno);
@@ -333,7 +336,8 @@ int cpu_exec(CPUArchState *env)
                                    !(env->hflags & HF_INHIBIT_IRQ_MASK)) {
                             int intno;
                             /* FIXME: this should respect TPR */
-                            svm_check_intercept(env, SVM_EXIT_VINTR);
+                            cpu_svm_check_intercept_param(env, SVM_EXIT_VINTR,
+                                                          0);
                             intno = ldl_phys(env->vm_vmcb + offsetof(struct vmcb, control.int_vector));
                             qemu_log_mask(CPU_LOG_TB_IN_ASM, "Servicing virtual hardware INT=0x%02x\n", intno);
                             do_interrupt_x86_hardirq(env, intno, 1);
diff --git a/target-i386/cpu.h b/target-i386/cpu.h
index bcf663e..c546723 100644
--- a/target-i386/cpu.h
+++ b/target-i386/cpu.h
@@ -1074,13 +1074,15 @@ void cpu_x86_inject_mce(Monitor *mon, CPUX86State *cenv, int bank,
 /* op_helper.c */
 void do_interrupt(CPUX86State *env);
 void do_interrupt_x86_hardirq(CPUX86State *env, int intno, int is_hw);
-void QEMU_NORETURN raise_exception_env(int exception_index, CPUX86State *nenv);
-void QEMU_NORETURN raise_exception_err_env(CPUX86State *nenv, int exception_index,
-                                           int error_code);
+void QEMU_NORETURN raise_exception(CPUX86State *env, int exception_index);
+void QEMU_NORETURN raise_exception_err(CPUX86State *env, int exception_index,
+                                       int error_code);
 
 void do_smm_enter(CPUX86State *env1);
 
-void svm_check_intercept(CPUX86State *env1, uint32_t type);
+void cpu_svm_check_intercept_param(CPUX86State *env1, uint32_t type,
+                                   uint64_t param);
+void cpu_vmexit(CPUX86State *nenv, uint32_t exit_code, uint64_t exit_info_1);
 
 uint32_t cpu_cc_compute_all(CPUX86State *env1, int op);
 
diff --git a/target-i386/helper.c b/target-i386/helper.c
index 2cc8097..d3af6ea 100644
--- a/target-i386/helper.c
+++ b/target-i386/helper.c
@@ -951,7 +951,7 @@ static void breakpoint_handler(CPUX86State *env)
         if (env->watchpoint_hit->flags & BP_CPU) {
             env->watchpoint_hit = NULL;
             if (check_hw_breakpoints(env, 0))
-                raise_exception_env(EXCP01_DB, env);
+                raise_exception(env, EXCP01_DB);
             else
                 cpu_resume_from_signal(env, NULL);
         }
@@ -960,7 +960,7 @@ static void breakpoint_handler(CPUX86State *env)
             if (bp->pc == env->eip) {
                 if (bp->flags & BP_CPU) {
                     check_hw_breakpoints(env, 1);
-                    raise_exception_env(EXCP01_DB, env);
+                    raise_exception(env, EXCP01_DB);
                 }
                 break;
             }
diff --git a/target-i386/helper.h b/target-i386/helper.h
index 761954e..99ca183 100644
--- a/target-i386/helper.h
+++ b/target-i386/helper.h
@@ -63,8 +63,8 @@ DEF_HELPER_1(monitor, void, tl)
 DEF_HELPER_1(mwait, void, int)
 DEF_HELPER_0(debug, void)
 DEF_HELPER_0(reset_rf, void)
-DEF_HELPER_2(raise_interrupt, void, int, int)
-DEF_HELPER_1(raise_exception, void, int)
+DEF_HELPER_3(raise_interrupt, void, env, int, int)
+DEF_HELPER_2(raise_exception, void, env, int)
 DEF_HELPER_0(cli, void)
 DEF_HELPER_0(sti, void)
 DEF_HELPER_0(set_inhibit_irq, void)
diff --git a/target-i386/op_helper.c b/target-i386/op_helper.c
index b9c1b93..773148c 100644
--- a/target-i386/op_helper.c
+++ b/target-i386/op_helper.c
@@ -139,16 +139,13 @@ static inline void cpu_load_efer(CPUX86State *env, uint64_t val)
 }
 
 #if 0
-#define raise_exception_err(a, b)                                       \
+#define raise_exception_err(env, a, b)                                  \
     do {                                                                \
         qemu_log("raise_exception line=%d\n", __LINE__);                \
-        (raise_exception_err)(a, b);                                    \
+        (raise_exception_err)(env, a, b);                               \
     } while (0)
 #endif
 
-static void QEMU_NORETURN raise_exception_err(int exception_index,
-                                              int error_code);
-
 static const uint8_t parity_table[256] = {
     CC_P, 0, 0, CC_P, 0, CC_P, CC_P, 0,
     0, CC_P, CC_P, 0, CC_P, 0, 0, CC_P,
@@ -317,7 +314,7 @@ static inline void get_ss_esp_from_tss(uint32_t *ss_ptr,
     shift = type >> 3;
     index = (dpl * 4 + 2) << shift;
     if (index + (4 << shift) - 1 > env->tr.limit) {
-        raise_exception_err(EXCP0A_TSS, env->tr.selector & 0xfffc);
+        raise_exception_err(env, EXCP0A_TSS, env->tr.selector & 0xfffc);
     }
     if (shift == 0) {
         *esp_ptr = lduw_kernel(env->tr.base + index);
@@ -336,47 +333,47 @@ static void tss_load_seg(int seg_reg, int selector)
 
     if ((selector & 0xfffc) != 0) {
         if (load_segment(&e1, &e2, selector) != 0) {
-            raise_exception_err(EXCP0A_TSS, selector & 0xfffc);
+            raise_exception_err(env, EXCP0A_TSS, selector & 0xfffc);
         }
         if (!(e2 & DESC_S_MASK)) {
-            raise_exception_err(EXCP0A_TSS, selector & 0xfffc);
+            raise_exception_err(env, EXCP0A_TSS, selector & 0xfffc);
         }
         rpl = selector & 3;
         dpl = (e2 >> DESC_DPL_SHIFT) & 3;
         cpl = env->hflags & HF_CPL_MASK;
         if (seg_reg == R_CS) {
             if (!(e2 & DESC_CS_MASK)) {
-                raise_exception_err(EXCP0A_TSS, selector & 0xfffc);
+                raise_exception_err(env, EXCP0A_TSS, selector & 0xfffc);
             }
             /* XXX: is it correct? */
             if (dpl != rpl) {
-                raise_exception_err(EXCP0A_TSS, selector & 0xfffc);
+                raise_exception_err(env, EXCP0A_TSS, selector & 0xfffc);
             }
             if ((e2 & DESC_C_MASK) && dpl > rpl) {
-                raise_exception_err(EXCP0A_TSS, selector & 0xfffc);
+                raise_exception_err(env, EXCP0A_TSS, selector & 0xfffc);
             }
         } else if (seg_reg == R_SS) {
             /* SS must be writable data */
             if ((e2 & DESC_CS_MASK) || !(e2 & DESC_W_MASK)) {
-                raise_exception_err(EXCP0A_TSS, selector & 0xfffc);
+                raise_exception_err(env, EXCP0A_TSS, selector & 0xfffc);
             }
             if (dpl != cpl || dpl != rpl) {
-                raise_exception_err(EXCP0A_TSS, selector & 0xfffc);
+                raise_exception_err(env, EXCP0A_TSS, selector & 0xfffc);
             }
         } else {
             /* not readable code */
             if ((e2 & DESC_CS_MASK) && !(e2 & DESC_R_MASK)) {
-                raise_exception_err(EXCP0A_TSS, selector & 0xfffc);
+                raise_exception_err(env, EXCP0A_TSS, selector & 0xfffc);
             }
             /* if data or non conforming code, checks the rights */
             if (((e2 >> DESC_TYPE_SHIFT) & 0xf) < 12) {
                 if (dpl < cpl || dpl < rpl) {
-                    raise_exception_err(EXCP0A_TSS, selector & 0xfffc);
+                    raise_exception_err(env, EXCP0A_TSS, selector & 0xfffc);
                 }
             }
         }
         if (!(e2 & DESC_P_MASK)) {
-            raise_exception_err(EXCP0B_NOSEG, selector & 0xfffc);
+            raise_exception_err(env, EXCP0B_NOSEG, selector & 0xfffc);
         }
         cpu_x86_load_seg_cache(env, seg_reg, selector,
                                get_seg_base(e1, e2),
@@ -384,7 +381,7 @@ static void tss_load_seg(int seg_reg, int selector)
                                e2);
     } else {
         if (seg_reg == R_SS || seg_reg == R_CS) {
-            raise_exception_err(EXCP0A_TSS, selector & 0xfffc);
+            raise_exception_err(env, EXCP0A_TSS, selector & 0xfffc);
         }
     }
 }
@@ -414,26 +411,26 @@ static void switch_tss(int tss_selector,
     /* if task gate, we read the TSS segment and we load it */
     if (type == 5) {
         if (!(e2 & DESC_P_MASK)) {
-            raise_exception_err(EXCP0B_NOSEG, tss_selector & 0xfffc);
+            raise_exception_err(env, EXCP0B_NOSEG, tss_selector & 0xfffc);
         }
         tss_selector = e1 >> 16;
         if (tss_selector & 4) {
-            raise_exception_err(EXCP0A_TSS, tss_selector & 0xfffc);
+            raise_exception_err(env, EXCP0A_TSS, tss_selector & 0xfffc);
         }
         if (load_segment(&e1, &e2, tss_selector) != 0) {
-            raise_exception_err(EXCP0D_GPF, tss_selector & 0xfffc);
+            raise_exception_err(env, EXCP0D_GPF, tss_selector & 0xfffc);
         }
         if (e2 & DESC_S_MASK) {
-            raise_exception_err(EXCP0D_GPF, tss_selector & 0xfffc);
+            raise_exception_err(env, EXCP0D_GPF, tss_selector & 0xfffc);
         }
         type = (e2 >> DESC_TYPE_SHIFT) & 0xf;
         if ((type & 7) != 1) {
-            raise_exception_err(EXCP0D_GPF, tss_selector & 0xfffc);
+            raise_exception_err(env, EXCP0D_GPF, tss_selector & 0xfffc);
         }
     }
 
     if (!(e2 & DESC_P_MASK)) {
-        raise_exception_err(EXCP0B_NOSEG, tss_selector & 0xfffc);
+        raise_exception_err(env, EXCP0B_NOSEG, tss_selector & 0xfffc);
     }
 
     if (type & 8) {
@@ -445,7 +442,7 @@ static void switch_tss(int tss_selector,
     tss_base = get_seg_base(e1, e2);
     if ((tss_selector & 4) != 0 ||
         tss_limit < tss_limit_max) {
-        raise_exception_err(EXCP0A_TSS, tss_selector & 0xfffc);
+        raise_exception_err(env, EXCP0A_TSS, tss_selector & 0xfffc);
     }
     old_type = (env->tr.flags >> DESC_TYPE_SHIFT) & 0xf;
     if (old_type & 8) {
@@ -619,23 +616,23 @@ static void switch_tss(int tss_selector,
 
     /* load the LDT */
     if (new_ldt & 4) {
-        raise_exception_err(EXCP0A_TSS, new_ldt & 0xfffc);
+        raise_exception_err(env, EXCP0A_TSS, new_ldt & 0xfffc);
     }
 
     if ((new_ldt & 0xfffc) != 0) {
         dt = &env->gdt;
         index = new_ldt & ~7;
         if ((index + 7) > dt->limit) {
-            raise_exception_err(EXCP0A_TSS, new_ldt & 0xfffc);
+            raise_exception_err(env, EXCP0A_TSS, new_ldt & 0xfffc);
         }
         ptr = dt->base + index;
         e1 = ldl_kernel(ptr);
         e2 = ldl_kernel(ptr + 4);
         if ((e2 & DESC_S_MASK) || ((e2 >> DESC_TYPE_SHIFT) & 0xf) != 2) {
-            raise_exception_err(EXCP0A_TSS, new_ldt & 0xfffc);
+            raise_exception_err(env, EXCP0A_TSS, new_ldt & 0xfffc);
         }
         if (!(e2 & DESC_P_MASK)) {
-            raise_exception_err(EXCP0A_TSS, new_ldt & 0xfffc);
+            raise_exception_err(env, EXCP0A_TSS, new_ldt & 0xfffc);
         }
         load_seg_cache_raw_dt(&env->ldt, e1, e2);
     }
@@ -653,7 +650,7 @@ static void switch_tss(int tss_selector,
     /* check that EIP is in the CS segment limits */
     if (new_eip > env->segs[R_CS].limit) {
         /* XXX: different exception if CALL? */
-        raise_exception_err(EXCP0D_GPF, 0);
+        raise_exception_err(env, EXCP0D_GPF, 0);
     }
 
 #ifndef CONFIG_USER_ONLY
@@ -692,7 +689,7 @@ static inline void check_io(int addr, int size)
     /* all bits must be zero to allow the I/O */
     if ((val & mask) != 0) {
     fail:
-        raise_exception_err(EXCP0D_GPF, 0);
+        raise_exception_err(env, EXCP0D_GPF, 0);
     }
 }
 
@@ -835,7 +832,7 @@ static void do_interrupt_protected(int intno, int is_int, int error_code,
 
     dt = &env->idt;
     if (intno * 8 + 7 > dt->limit) {
-        raise_exception_err(EXCP0D_GPF, intno * 8 + 2);
+        raise_exception_err(env, EXCP0D_GPF, intno * 8 + 2);
     }
     ptr = dt->base + intno * 8;
     e1 = ldl_kernel(ptr);
@@ -846,7 +843,7 @@ static void do_interrupt_protected(int intno, int is_int, int error_code,
     case 5: /* task gate */
         /* must do that check here to return the correct error code */
         if (!(e2 & DESC_P_MASK)) {
-            raise_exception_err(EXCP0B_NOSEG, intno * 8 + 2);
+            raise_exception_err(env, EXCP0B_NOSEG, intno * 8 + 2);
         }
         switch_tss(intno * 8, e1, e2, SWITCH_TSS_CALL, old_eip);
         if (has_error_code) {
@@ -877,60 +874,60 @@ static void do_interrupt_protected(int intno, int is_int, int error_code,
     case 15: /* 386 trap gate */
         break;
     default:
-        raise_exception_err(EXCP0D_GPF, intno * 8 + 2);
+        raise_exception_err(env, EXCP0D_GPF, intno * 8 + 2);
         break;
     }
     dpl = (e2 >> DESC_DPL_SHIFT) & 3;
     cpl = env->hflags & HF_CPL_MASK;
     /* check privilege if software int */
     if (is_int && dpl < cpl) {
-        raise_exception_err(EXCP0D_GPF, intno * 8 + 2);
+        raise_exception_err(env, EXCP0D_GPF, intno * 8 + 2);
     }
     /* check valid bit */
     if (!(e2 & DESC_P_MASK)) {
-        raise_exception_err(EXCP0B_NOSEG, intno * 8 + 2);
+        raise_exception_err(env, EXCP0B_NOSEG, intno * 8 + 2);
     }
     selector = e1 >> 16;
     offset = (e2 & 0xffff0000) | (e1 & 0x0000ffff);
     if ((selector & 0xfffc) == 0) {
-        raise_exception_err(EXCP0D_GPF, 0);
+        raise_exception_err(env, EXCP0D_GPF, 0);
     }
     if (load_segment(&e1, &e2, selector) != 0) {
-        raise_exception_err(EXCP0D_GPF, selector & 0xfffc);
+        raise_exception_err(env, EXCP0D_GPF, selector & 0xfffc);
     }
     if (!(e2 & DESC_S_MASK) || !(e2 & (DESC_CS_MASK))) {
-        raise_exception_err(EXCP0D_GPF, selector & 0xfffc);
+        raise_exception_err(env, EXCP0D_GPF, selector & 0xfffc);
     }
     dpl = (e2 >> DESC_DPL_SHIFT) & 3;
     if (dpl > cpl) {
-        raise_exception_err(EXCP0D_GPF, selector & 0xfffc);
+        raise_exception_err(env, EXCP0D_GPF, selector & 0xfffc);
     }
     if (!(e2 & DESC_P_MASK)) {
-        raise_exception_err(EXCP0B_NOSEG, selector & 0xfffc);
+        raise_exception_err(env, EXCP0B_NOSEG, selector & 0xfffc);
     }
     if (!(e2 & DESC_C_MASK) && dpl < cpl) {
         /* to inner privilege */
         get_ss_esp_from_tss(&ss, &esp, dpl);
         if ((ss & 0xfffc) == 0) {
-            raise_exception_err(EXCP0A_TSS, ss & 0xfffc);
+            raise_exception_err(env, EXCP0A_TSS, ss & 0xfffc);
         }
         if ((ss & 3) != dpl) {
-            raise_exception_err(EXCP0A_TSS, ss & 0xfffc);
+            raise_exception_err(env, EXCP0A_TSS, ss & 0xfffc);
         }
         if (load_segment(&ss_e1, &ss_e2, ss) != 0) {
-            raise_exception_err(EXCP0A_TSS, ss & 0xfffc);
+            raise_exception_err(env, EXCP0A_TSS, ss & 0xfffc);
         }
         ss_dpl = (ss_e2 >> DESC_DPL_SHIFT) & 3;
         if (ss_dpl != dpl) {
-            raise_exception_err(EXCP0A_TSS, ss & 0xfffc);
+            raise_exception_err(env, EXCP0A_TSS, ss & 0xfffc);
         }
         if (!(ss_e2 & DESC_S_MASK) ||
             (ss_e2 & DESC_CS_MASK) ||
             !(ss_e2 & DESC_W_MASK)) {
-            raise_exception_err(EXCP0A_TSS, ss & 0xfffc);
+            raise_exception_err(env, EXCP0A_TSS, ss & 0xfffc);
         }
         if (!(ss_e2 & DESC_P_MASK)) {
-            raise_exception_err(EXCP0A_TSS, ss & 0xfffc);
+            raise_exception_err(env, EXCP0A_TSS, ss & 0xfffc);
         }
         new_stack = 1;
         sp_mask = get_sp_mask(ss_e2);
@@ -938,7 +935,7 @@ static void do_interrupt_protected(int intno, int is_int, int error_code,
     } else if ((e2 & DESC_C_MASK) || dpl == cpl) {
         /* to same privilege */
         if (env->eflags & VM_MASK) {
-            raise_exception_err(EXCP0D_GPF, selector & 0xfffc);
+            raise_exception_err(env, EXCP0D_GPF, selector & 0xfffc);
         }
         new_stack = 0;
         sp_mask = get_sp_mask(env->segs[R_SS].flags);
@@ -946,7 +943,7 @@ static void do_interrupt_protected(int intno, int is_int, int error_code,
         esp = ESP;
         dpl = cpl;
     } else {
-        raise_exception_err(EXCP0D_GPF, selector & 0xfffc);
+        raise_exception_err(env, EXCP0D_GPF, selector & 0xfffc);
         new_stack = 0; /* avoid warning */
         sp_mask = 0; /* avoid warning */
         ssp = 0; /* avoid warning */
@@ -1055,7 +1052,7 @@ static inline target_ulong get_rsp_from_tss(int level)
     }
     index = 8 * level + 4;
     if ((index + 7) > env->tr.limit) {
-        raise_exception_err(EXCP0A_TSS, env->tr.selector & 0xfffc);
+        raise_exception_err(env, EXCP0A_TSS, env->tr.selector & 0xfffc);
     }
     return ldq_kernel(env->tr.base + index);
 }
@@ -1083,7 +1080,7 @@ static void do_interrupt64(int intno, int is_int, int error_code,
 
     dt = &env->idt;
     if (intno * 16 + 15 > dt->limit) {
-        raise_exception_err(EXCP0D_GPF, intno * 16 + 2);
+        raise_exception_err(env, EXCP0D_GPF, intno * 16 + 2);
     }
     ptr = dt->base + intno * 16;
     e1 = ldl_kernel(ptr);
@@ -1096,41 +1093,41 @@ static void do_interrupt64(int intno, int is_int, int error_code,
     case 15: /* 386 trap gate */
         break;
     default:
-        raise_exception_err(EXCP0D_GPF, intno * 16 + 2);
+        raise_exception_err(env, EXCP0D_GPF, intno * 16 + 2);
         break;
     }
     dpl = (e2 >> DESC_DPL_SHIFT) & 3;
     cpl = env->hflags & HF_CPL_MASK;
     /* check privilege if software int */
     if (is_int && dpl < cpl) {
-        raise_exception_err(EXCP0D_GPF, intno * 16 + 2);
+        raise_exception_err(env, EXCP0D_GPF, intno * 16 + 2);
     }
     /* check valid bit */
     if (!(e2 & DESC_P_MASK)) {
-        raise_exception_err(EXCP0B_NOSEG, intno * 16 + 2);
+        raise_exception_err(env, EXCP0B_NOSEG, intno * 16 + 2);
     }
     selector = e1 >> 16;
     offset = ((target_ulong)e3 << 32) | (e2 & 0xffff0000) | (e1 & 0x0000ffff);
     ist = e2 & 7;
     if ((selector & 0xfffc) == 0) {
-        raise_exception_err(EXCP0D_GPF, 0);
+        raise_exception_err(env, EXCP0D_GPF, 0);
     }
 
     if (load_segment(&e1, &e2, selector) != 0) {
-        raise_exception_err(EXCP0D_GPF, selector & 0xfffc);
+        raise_exception_err(env, EXCP0D_GPF, selector & 0xfffc);
     }
     if (!(e2 & DESC_S_MASK) || !(e2 & (DESC_CS_MASK))) {
-        raise_exception_err(EXCP0D_GPF, selector & 0xfffc);
+        raise_exception_err(env, EXCP0D_GPF, selector & 0xfffc);
     }
     dpl = (e2 >> DESC_DPL_SHIFT) & 3;
     if (dpl > cpl) {
-        raise_exception_err(EXCP0D_GPF, selector & 0xfffc);
+        raise_exception_err(env, EXCP0D_GPF, selector & 0xfffc);
     }
     if (!(e2 & DESC_P_MASK)) {
-        raise_exception_err(EXCP0B_NOSEG, selector & 0xfffc);
+        raise_exception_err(env, EXCP0B_NOSEG, selector & 0xfffc);
     }
     if (!(e2 & DESC_L_MASK) || (e2 & DESC_B_MASK)) {
-        raise_exception_err(EXCP0D_GPF, selector & 0xfffc);
+        raise_exception_err(env, EXCP0D_GPF, selector & 0xfffc);
     }
     if ((!(e2 & DESC_C_MASK) && dpl < cpl) || ist != 0) {
         /* to inner privilege */
@@ -1145,7 +1142,7 @@ static void do_interrupt64(int intno, int is_int, int error_code,
     } else if ((e2 & DESC_C_MASK) || dpl == cpl) {
         /* to same privilege */
         if (env->eflags & VM_MASK) {
-            raise_exception_err(EXCP0D_GPF, selector & 0xfffc);
+            raise_exception_err(env, EXCP0D_GPF, selector & 0xfffc);
         }
         new_stack = 0;
         if (ist != 0) {
@@ -1156,7 +1153,7 @@ static void do_interrupt64(int intno, int is_int, int error_code,
         esp &= ~0xfLL; /* align stack */
         dpl = cpl;
     } else {
-        raise_exception_err(EXCP0D_GPF, selector & 0xfffc);
+        raise_exception_err(env, EXCP0D_GPF, selector & 0xfffc);
         new_stack = 0; /* avoid warning */
         esp = 0; /* avoid warning */
     }
@@ -1206,7 +1203,7 @@ void helper_syscall(int next_eip_addend)
     int selector;
 
     if (!(env->efer & MSR_EFER_SCE)) {
-        raise_exception_err(EXCP06_ILLOP, 0);
+        raise_exception_err(env, EXCP06_ILLOP, 0);
     }
     selector = (env->star >> 32) & 0xffff;
     if (env->hflags & HF_LMA_MASK) {
@@ -1263,11 +1260,11 @@ void helper_sysret(int dflag)
     int cpl, selector;
 
     if (!(env->efer & MSR_EFER_SCE)) {
-        raise_exception_err(EXCP06_ILLOP, 0);
+        raise_exception_err(env, EXCP06_ILLOP, 0);
     }
     cpl = env->hflags & HF_CPL_MASK;
     if (!(env->cr[0] & CR0_PE_MASK) || cpl != 0) {
-        raise_exception_err(EXCP0D_GPF, 0);
+        raise_exception_err(env, EXCP0D_GPF, 0);
     }
     selector = (env->star >> 48) & 0xffff;
     if (env->hflags & HF_LMA_MASK) {
@@ -1326,7 +1323,7 @@ static void do_interrupt_real(int intno, int is_int, int error_code,
     /* real mode (simpler!) */
     dt = &env->idt;
     if (intno * 4 + 3 > dt->limit) {
-        raise_exception_err(EXCP0D_GPF, intno * 8 + 2);
+        raise_exception_err(env, EXCP0D_GPF, intno * 8 + 2);
     }
     ptr = dt->base + intno * 4;
     offset = lduw_kernel(ptr);
@@ -1375,7 +1372,7 @@ static void do_interrupt_user(int intno, int is_int, int error_code,
     cpl = env->hflags & HF_CPL_MASK;
     /* check privilege if software int */
     if (is_int && dpl < cpl) {
-        raise_exception_err(EXCP0D_GPF, (intno << shift) + 2);
+        raise_exception_err(env, EXCP0D_GPF, (intno << shift) + 2);
     }
 
     /* Since we emulate only user space, we cannot do more than
@@ -1540,7 +1537,7 @@ void qemu_system_reset_request(void);
  * needed. It should only be called, if this is not an interrupt.
  * Returns the new exception number.
  */
-static int check_exception(int intno, int *error_code)
+static int check_exception(CPUX86State *env, int intno, int *error_code)
 {
     int first_contributory = env->old_exception == 0 ||
                               (env->old_exception >= 10 &&
@@ -1554,7 +1551,7 @@ static int check_exception(int intno, int *error_code)
 #if !defined(CONFIG_USER_ONLY)
     if (env->old_exception == EXCP08_DBLE) {
         if (env->hflags & HF_SVMI_MASK) {
-            helper_vmexit(SVM_EXIT_SHUTDOWN, 0); /* does not return */
+            cpu_vmexit(env, SVM_EXIT_SHUTDOWN, 0); /* does not return */
         }
 
         qemu_log_mask(CPU_LOG_RESET, "Triple fault\n");
@@ -1585,15 +1582,16 @@ static int check_exception(int intno, int *error_code)
  * EIP value AFTER the interrupt instruction. It is only relevant if
  * is_int is TRUE.
  */
-static void QEMU_NORETURN raise_interrupt(int intno, int is_int, int error_code,
-                                          int next_eip_addend)
+static void QEMU_NORETURN raise_interrupt2(CPUX86State *env, int intno,
+                                           int is_int, int error_code,
+                                           int next_eip_addend)
 {
     if (!is_int) {
-        helper_svm_check_intercept_param(SVM_EXIT_EXCP_BASE + intno,
-                                         error_code);
-        intno = check_exception(intno, &error_code);
+        cpu_svm_check_intercept_param(env, SVM_EXIT_EXCP_BASE + intno,
+                                      error_code);
+        intno = check_exception(env, intno, &error_code);
     } else {
-        helper_svm_check_intercept_param(SVM_EXIT_SWINT, 0);
+        cpu_svm_check_intercept_param(env, SVM_EXIT_SWINT, 0);
     }
 
     env->exception_index = intno;
@@ -1605,28 +1603,26 @@ static void QEMU_NORETURN raise_interrupt(int intno, int is_int, int error_code,
 
 /* shortcuts to generate exceptions */
 
-static void QEMU_NORETURN raise_exception_err(int exception_index,
-                                              int error_code)
-{
-    raise_interrupt(exception_index, 0, error_code, 0);
-}
-
-void raise_exception_err_env(CPUX86State *nenv, int exception_index,
-                             int error_code)
+static void QEMU_NORETURN raise_interrupt(CPUX86State *nenv,
+                                          int intno, int is_int,
+                                          int error_code,
+                                          int next_eip_addend)
 {
     env = nenv;
-    raise_interrupt(exception_index, 0, error_code, 0);
+    raise_interrupt2(env, intno, is_int, error_code, next_eip_addend);
 }
 
-static void QEMU_NORETURN raise_exception(int exception_index)
+void raise_exception_err(CPUX86State *nenv, int exception_index,
+                         int error_code)
 {
-    raise_interrupt(exception_index, 0, 0, 0);
+    env = nenv;
+    raise_interrupt2(env, exception_index, 0, error_code, 0);
 }
 
-void raise_exception_env(int exception_index, CPUX86State *nenv)
+void raise_exception(CPUX86State *nenv, int exception_index)
 {
     env = nenv;
-    raise_exception(exception_index);
+    raise_interrupt2(env, exception_index, 0, 0, 0);
 }
 /* SMM support */
 
@@ -1922,11 +1918,11 @@ void helper_divb_AL(target_ulong t0)
     num = (EAX & 0xffff);
     den = (t0 & 0xff);
     if (den == 0) {
-        raise_exception(EXCP00_DIVZ);
+        raise_exception(env, EXCP00_DIVZ);
     }
     q = (num / den);
     if (q > 0xff) {
-        raise_exception(EXCP00_DIVZ);
+        raise_exception(env, EXCP00_DIVZ);
     }
     q &= 0xff;
     r = (num % den) & 0xff;
@@ -1940,11 +1936,11 @@ void helper_idivb_AL(target_ulong t0)
     num = (int16_t)EAX;
     den = (int8_t)t0;
     if (den == 0) {
-        raise_exception(EXCP00_DIVZ);
+        raise_exception(env, EXCP00_DIVZ);
     }
     q = (num / den);
     if (q != (int8_t)q) {
-        raise_exception(EXCP00_DIVZ);
+        raise_exception(env, EXCP00_DIVZ);
     }
     q &= 0xff;
     r = (num % den) & 0xff;
@@ -1958,11 +1954,11 @@ void helper_divw_AX(target_ulong t0)
     num = (EAX & 0xffff) | ((EDX & 0xffff) << 16);
     den = (t0 & 0xffff);
     if (den == 0) {
-        raise_exception(EXCP00_DIVZ);
+        raise_exception(env, EXCP00_DIVZ);
     }
     q = (num / den);
     if (q > 0xffff) {
-        raise_exception(EXCP00_DIVZ);
+        raise_exception(env, EXCP00_DIVZ);
     }
     q &= 0xffff;
     r = (num % den) & 0xffff;
@@ -1977,11 +1973,11 @@ void helper_idivw_AX(target_ulong t0)
     num = (EAX & 0xffff) | ((EDX & 0xffff) << 16);
     den = (int16_t)t0;
     if (den == 0) {
-        raise_exception(EXCP00_DIVZ);
+        raise_exception(env, EXCP00_DIVZ);
     }
     q = (num / den);
     if (q != (int16_t)q) {
-        raise_exception(EXCP00_DIVZ);
+        raise_exception(env, EXCP00_DIVZ);
     }
     q &= 0xffff;
     r = (num % den) & 0xffff;
@@ -1997,12 +1993,12 @@ void helper_divl_EAX(target_ulong t0)
     num = ((uint32_t)EAX) | ((uint64_t)((uint32_t)EDX) << 32);
     den = t0;
     if (den == 0) {
-        raise_exception(EXCP00_DIVZ);
+        raise_exception(env, EXCP00_DIVZ);
     }
     q = (num / den);
     r = (num % den);
     if (q > 0xffffffff) {
-        raise_exception(EXCP00_DIVZ);
+        raise_exception(env, EXCP00_DIVZ);
     }
     EAX = (uint32_t)q;
     EDX = (uint32_t)r;
@@ -2016,12 +2012,12 @@ void helper_idivl_EAX(target_ulong t0)
     num = ((uint32_t)EAX) | ((uint64_t)((uint32_t)EDX) << 32);
     den = t0;
     if (den == 0) {
-        raise_exception(EXCP00_DIVZ);
+        raise_exception(env, EXCP00_DIVZ);
     }
     q = (num / den);
     r = (num % den);
     if (q != (int32_t)q) {
-        raise_exception(EXCP00_DIVZ);
+        raise_exception(env, EXCP00_DIVZ);
     }
     EAX = (uint32_t)q;
     EDX = (uint32_t)r;
@@ -2164,7 +2160,7 @@ void helper_into(int next_eip_addend)
 
     eflags = helper_cc_compute_all(CC_OP);
     if (eflags & CC_O) {
-        raise_interrupt(EXCP04_INTO, 1, 0, next_eip_addend);
+        raise_interrupt(env, EXCP04_INTO, 1, 0, next_eip_addend);
     }
 }
 
@@ -2195,7 +2191,7 @@ void helper_cmpxchg16b(target_ulong a0)
     int eflags;
 
     if ((a0 & 0xf) != 0) {
-        raise_exception(EXCP0D_GPF);
+        raise_exception(env, EXCP0D_GPF);
     }
     eflags = helper_cc_compute_all(CC_OP);
     d0 = ldq(a0);
@@ -2222,7 +2218,7 @@ void helper_single_step(void)
     check_hw_breakpoints(env, 1);
     env->dr[6] |= DR6_BS;
 #endif
-    raise_exception(EXCP01_DB);
+    raise_exception(env, EXCP01_DB);
 }
 
 void helper_cpuid(void)
@@ -2316,7 +2312,7 @@ void helper_lldt(int selector)
         env->ldt.limit = 0;
     } else {
         if (selector & 0x4) {
-            raise_exception_err(EXCP0D_GPF, selector & 0xfffc);
+            raise_exception_err(env, EXCP0D_GPF, selector & 0xfffc);
         }
         dt = &env->gdt;
         index = selector & ~7;
@@ -2329,16 +2325,16 @@ void helper_lldt(int selector)
             entry_limit = 7;
         }
         if ((index + entry_limit) > dt->limit) {
-            raise_exception_err(EXCP0D_GPF, selector & 0xfffc);
+            raise_exception_err(env, EXCP0D_GPF, selector & 0xfffc);
         }
         ptr = dt->base + index;
         e1 = ldl_kernel(ptr);
         e2 = ldl_kernel(ptr + 4);
         if ((e2 & DESC_S_MASK) || ((e2 >> DESC_TYPE_SHIFT) & 0xf) != 2) {
-            raise_exception_err(EXCP0D_GPF, selector & 0xfffc);
+            raise_exception_err(env, EXCP0D_GPF, selector & 0xfffc);
         }
         if (!(e2 & DESC_P_MASK)) {
-            raise_exception_err(EXCP0B_NOSEG, selector & 0xfffc);
+            raise_exception_err(env, EXCP0B_NOSEG, selector & 0xfffc);
         }
 #ifdef TARGET_X86_64
         if (env->hflags & HF_LMA_MASK) {
@@ -2371,7 +2367,7 @@ void helper_ltr(int selector)
         env->tr.flags = 0;
     } else {
         if (selector & 0x4) {
-            raise_exception_err(EXCP0D_GPF, selector & 0xfffc);
+            raise_exception_err(env, EXCP0D_GPF, selector & 0xfffc);
         }
         dt = &env->gdt;
         index = selector & ~7;
@@ -2384,7 +2380,7 @@ void helper_ltr(int selector)
             entry_limit = 7;
         }
         if ((index + entry_limit) > dt->limit) {
-            raise_exception_err(EXCP0D_GPF, selector & 0xfffc);
+            raise_exception_err(env, EXCP0D_GPF, selector & 0xfffc);
         }
         ptr = dt->base + index;
         e1 = ldl_kernel(ptr);
@@ -2392,10 +2388,10 @@ void helper_ltr(int selector)
         type = (e2 >> DESC_TYPE_SHIFT) & 0xf;
         if ((e2 & DESC_S_MASK) ||
             (type != 1 && type != 9)) {
-            raise_exception_err(EXCP0D_GPF, selector & 0xfffc);
+            raise_exception_err(env, EXCP0D_GPF, selector & 0xfffc);
         }
         if (!(e2 & DESC_P_MASK)) {
-            raise_exception_err(EXCP0B_NOSEG, selector & 0xfffc);
+            raise_exception_err(env, EXCP0B_NOSEG, selector & 0xfffc);
         }
 #ifdef TARGET_X86_64
         if (env->hflags & HF_LMA_MASK) {
@@ -2404,7 +2400,7 @@ void helper_ltr(int selector)
             e3 = ldl_kernel(ptr + 8);
             e4 = ldl_kernel(ptr + 12);
             if ((e4 >> DESC_TYPE_SHIFT) & 0xf) {
-                raise_exception_err(EXCP0D_GPF, selector & 0xfffc);
+                raise_exception_err(env, EXCP0D_GPF, selector & 0xfffc);
             }
             load_seg_cache_raw_dt(&env->tr, e1, e2);
             env->tr.base |= (target_ulong)e3 << 32;
@@ -2437,7 +2433,7 @@ void helper_load_seg(int seg_reg, int selector)
             && (!(env->hflags & HF_CS64_MASK) || cpl == 3)
 #endif
             ) {
-            raise_exception_err(EXCP0D_GPF, 0);
+            raise_exception_err(env, EXCP0D_GPF, 0);
         }
         cpu_x86_load_seg_cache(env, seg_reg, selector, 0, 0, 0);
     } else {
@@ -2449,44 +2445,44 @@ void helper_load_seg(int seg_reg, int selector)
         }
         index = selector & ~7;
         if ((index + 7) > dt->limit) {
-            raise_exception_err(EXCP0D_GPF, selector & 0xfffc);
+            raise_exception_err(env, EXCP0D_GPF, selector & 0xfffc);
         }
         ptr = dt->base + index;
         e1 = ldl_kernel(ptr);
         e2 = ldl_kernel(ptr + 4);
 
         if (!(e2 & DESC_S_MASK)) {
-            raise_exception_err(EXCP0D_GPF, selector & 0xfffc);
+            raise_exception_err(env, EXCP0D_GPF, selector & 0xfffc);
         }
         rpl = selector & 3;
         dpl = (e2 >> DESC_DPL_SHIFT) & 3;
         if (seg_reg == R_SS) {
             /* must be writable segment */
             if ((e2 & DESC_CS_MASK) || !(e2 & DESC_W_MASK)) {
-                raise_exception_err(EXCP0D_GPF, selector & 0xfffc);
+                raise_exception_err(env, EXCP0D_GPF, selector & 0xfffc);
             }
             if (rpl != cpl || dpl != cpl) {
-                raise_exception_err(EXCP0D_GPF, selector & 0xfffc);
+                raise_exception_err(env, EXCP0D_GPF, selector & 0xfffc);
             }
         } else {
             /* must be readable segment */
             if ((e2 & (DESC_CS_MASK | DESC_R_MASK)) == DESC_CS_MASK) {
-                raise_exception_err(EXCP0D_GPF, selector & 0xfffc);
+                raise_exception_err(env, EXCP0D_GPF, selector & 0xfffc);
             }
 
             if (!(e2 & DESC_CS_MASK) || !(e2 & DESC_C_MASK)) {
                 /* if not conforming code, test rights */
                 if (dpl < cpl || dpl < rpl) {
-                    raise_exception_err(EXCP0D_GPF, selector & 0xfffc);
+                    raise_exception_err(env, EXCP0D_GPF, selector & 0xfffc);
                 }
             }
         }
 
         if (!(e2 & DESC_P_MASK)) {
             if (seg_reg == R_SS) {
-                raise_exception_err(EXCP0C_STACK, selector & 0xfffc);
+                raise_exception_err(env, EXCP0C_STACK, selector & 0xfffc);
             } else {
-                raise_exception_err(EXCP0B_NOSEG, selector & 0xfffc);
+                raise_exception_err(env, EXCP0B_NOSEG, selector & 0xfffc);
             }
         }
 
@@ -2516,39 +2512,39 @@ void helper_ljmp_protected(int new_cs, target_ulong new_eip,
     target_ulong next_eip;
 
     if ((new_cs & 0xfffc) == 0) {
-        raise_exception_err(EXCP0D_GPF, 0);
+        raise_exception_err(env, EXCP0D_GPF, 0);
     }
     if (load_segment(&e1, &e2, new_cs) != 0) {
-        raise_exception_err(EXCP0D_GPF, new_cs & 0xfffc);
+        raise_exception_err(env, EXCP0D_GPF, new_cs & 0xfffc);
     }
     cpl = env->hflags & HF_CPL_MASK;
     if (e2 & DESC_S_MASK) {
         if (!(e2 & DESC_CS_MASK)) {
-            raise_exception_err(EXCP0D_GPF, new_cs & 0xfffc);
+            raise_exception_err(env, EXCP0D_GPF, new_cs & 0xfffc);
         }
         dpl = (e2 >> DESC_DPL_SHIFT) & 3;
         if (e2 & DESC_C_MASK) {
             /* conforming code segment */
             if (dpl > cpl) {
-                raise_exception_err(EXCP0D_GPF, new_cs & 0xfffc);
+                raise_exception_err(env, EXCP0D_GPF, new_cs & 0xfffc);
             }
         } else {
             /* non conforming code segment */
             rpl = new_cs & 3;
             if (rpl > cpl) {
-                raise_exception_err(EXCP0D_GPF, new_cs & 0xfffc);
+                raise_exception_err(env, EXCP0D_GPF, new_cs & 0xfffc);
             }
             if (dpl != cpl) {
-                raise_exception_err(EXCP0D_GPF, new_cs & 0xfffc);
+                raise_exception_err(env, EXCP0D_GPF, new_cs & 0xfffc);
             }
         }
         if (!(e2 & DESC_P_MASK)) {
-            raise_exception_err(EXCP0B_NOSEG, new_cs & 0xfffc);
+            raise_exception_err(env, EXCP0B_NOSEG, new_cs & 0xfffc);
         }
         limit = get_seg_limit(e1, e2);
         if (new_eip > limit &&
             !(env->hflags & HF_LMA_MASK) && !(e2 & DESC_L_MASK)) {
-            raise_exception_err(EXCP0D_GPF, new_cs & 0xfffc);
+            raise_exception_err(env, EXCP0D_GPF, new_cs & 0xfffc);
         }
         cpu_x86_load_seg_cache(env, R_CS, (new_cs & 0xfffc) | cpl,
                        get_seg_base(e1, e2), limit, e2);
@@ -2564,7 +2560,7 @@ void helper_ljmp_protected(int new_cs, target_ulong new_eip,
         case 9: /* 386 TSS */
         case 5: /* task gate */
             if (dpl < cpl || dpl < rpl) {
-                raise_exception_err(EXCP0D_GPF, new_cs & 0xfffc);
+                raise_exception_err(env, EXCP0D_GPF, new_cs & 0xfffc);
             }
             next_eip = env->eip + next_eip_addend;
             switch_tss(new_cs, e1, e2, SWITCH_TSS_JMP, next_eip);
@@ -2573,10 +2569,10 @@ void helper_ljmp_protected(int new_cs, target_ulong new_eip,
         case 4: /* 286 call gate */
         case 12: /* 386 call gate */
             if ((dpl < cpl) || (dpl < rpl)) {
-                raise_exception_err(EXCP0D_GPF, new_cs & 0xfffc);
+                raise_exception_err(env, EXCP0D_GPF, new_cs & 0xfffc);
             }
             if (!(e2 & DESC_P_MASK)) {
-                raise_exception_err(EXCP0B_NOSEG, new_cs & 0xfffc);
+                raise_exception_err(env, EXCP0B_NOSEG, new_cs & 0xfffc);
             }
             gate_cs = e1 >> 16;
             new_eip = (e1 & 0xffff);
@@ -2584,31 +2580,31 @@ void helper_ljmp_protected(int new_cs, target_ulong new_eip,
                 new_eip |= (e2 & 0xffff0000);
             }
             if (load_segment(&e1, &e2, gate_cs) != 0) {
-                raise_exception_err(EXCP0D_GPF, gate_cs & 0xfffc);
+                raise_exception_err(env, EXCP0D_GPF, gate_cs & 0xfffc);
             }
             dpl = (e2 >> DESC_DPL_SHIFT) & 3;
             /* must be code segment */
             if (((e2 & (DESC_S_MASK | DESC_CS_MASK)) !=
                  (DESC_S_MASK | DESC_CS_MASK))) {
-                raise_exception_err(EXCP0D_GPF, gate_cs & 0xfffc);
+                raise_exception_err(env, EXCP0D_GPF, gate_cs & 0xfffc);
             }
             if (((e2 & DESC_C_MASK) && (dpl > cpl)) ||
                 (!(e2 & DESC_C_MASK) && (dpl != cpl))) {
-                raise_exception_err(EXCP0D_GPF, gate_cs & 0xfffc);
+                raise_exception_err(env, EXCP0D_GPF, gate_cs & 0xfffc);
             }
             if (!(e2 & DESC_P_MASK)) {
-                raise_exception_err(EXCP0D_GPF, gate_cs & 0xfffc);
+                raise_exception_err(env, EXCP0D_GPF, gate_cs & 0xfffc);
             }
             limit = get_seg_limit(e1, e2);
             if (new_eip > limit) {
-                raise_exception_err(EXCP0D_GPF, 0);
+                raise_exception_err(env, EXCP0D_GPF, 0);
             }
             cpu_x86_load_seg_cache(env, R_CS, (gate_cs & 0xfffc) | cpl,
                                    get_seg_base(e1, e2), limit, e2);
             EIP = new_eip;
             break;
         default:
-            raise_exception_err(EXCP0D_GPF, new_cs & 0xfffc);
+            raise_exception_err(env, EXCP0D_GPF, new_cs & 0xfffc);
             break;
         }
     }
@@ -2654,35 +2650,35 @@ void helper_lcall_protected(int new_cs, target_ulong new_eip,
     LOG_PCALL("lcall %04x:%08x s=%d\n", new_cs, (uint32_t)new_eip, shift);
     LOG_PCALL_STATE(env);
     if ((new_cs & 0xfffc) == 0) {
-        raise_exception_err(EXCP0D_GPF, 0);
+        raise_exception_err(env, EXCP0D_GPF, 0);
     }
     if (load_segment(&e1, &e2, new_cs) != 0) {
-        raise_exception_err(EXCP0D_GPF, new_cs & 0xfffc);
+        raise_exception_err(env, EXCP0D_GPF, new_cs & 0xfffc);
     }
     cpl = env->hflags & HF_CPL_MASK;
     LOG_PCALL("desc=%08x:%08x\n", e1, e2);
     if (e2 & DESC_S_MASK) {
         if (!(e2 & DESC_CS_MASK)) {
-            raise_exception_err(EXCP0D_GPF, new_cs & 0xfffc);
+            raise_exception_err(env, EXCP0D_GPF, new_cs & 0xfffc);
         }
         dpl = (e2 >> DESC_DPL_SHIFT) & 3;
         if (e2 & DESC_C_MASK) {
             /* conforming code segment */
             if (dpl > cpl) {
-                raise_exception_err(EXCP0D_GPF, new_cs & 0xfffc);
+                raise_exception_err(env, EXCP0D_GPF, new_cs & 0xfffc);
             }
         } else {
             /* non conforming code segment */
             rpl = new_cs & 3;
             if (rpl > cpl) {
-                raise_exception_err(EXCP0D_GPF, new_cs & 0xfffc);
+                raise_exception_err(env, EXCP0D_GPF, new_cs & 0xfffc);
             }
             if (dpl != cpl) {
-                raise_exception_err(EXCP0D_GPF, new_cs & 0xfffc);
+                raise_exception_err(env, EXCP0D_GPF, new_cs & 0xfffc);
             }
         }
         if (!(e2 & DESC_P_MASK)) {
-            raise_exception_err(EXCP0B_NOSEG, new_cs & 0xfffc);
+            raise_exception_err(env, EXCP0B_NOSEG, new_cs & 0xfffc);
         }
 
 #ifdef TARGET_X86_64
@@ -2716,7 +2712,7 @@ void helper_lcall_protected(int new_cs, target_ulong new_eip,
 
             limit = get_seg_limit(e1, e2);
             if (new_eip > limit) {
-                raise_exception_err(EXCP0D_GPF, new_cs & 0xfffc);
+                raise_exception_err(env, EXCP0D_GPF, new_cs & 0xfffc);
             }
             /* from this point, not restartable */
             SET_ESP(sp, sp_mask);
@@ -2734,7 +2730,7 @@ void helper_lcall_protected(int new_cs, target_ulong new_eip,
         case 9: /* available 386 TSS */
         case 5: /* task gate */
             if (dpl < cpl || dpl < rpl) {
-                raise_exception_err(EXCP0D_GPF, new_cs & 0xfffc);
+                raise_exception_err(env, EXCP0D_GPF, new_cs & 0xfffc);
             }
             switch_tss(new_cs, e1, e2, SWITCH_TSS_CALL, next_eip);
             CC_OP = CC_OP_EFLAGS;
@@ -2743,37 +2739,37 @@ void helper_lcall_protected(int new_cs, target_ulong new_eip,
         case 12: /* 386 call gate */
             break;
         default:
-            raise_exception_err(EXCP0D_GPF, new_cs & 0xfffc);
+            raise_exception_err(env, EXCP0D_GPF, new_cs & 0xfffc);
             break;
         }
         shift = type >> 3;
 
         if (dpl < cpl || dpl < rpl) {
-            raise_exception_err(EXCP0D_GPF, new_cs & 0xfffc);
+            raise_exception_err(env, EXCP0D_GPF, new_cs & 0xfffc);
         }
         /* check valid bit */
         if (!(e2 & DESC_P_MASK)) {
-            raise_exception_err(EXCP0B_NOSEG,  new_cs & 0xfffc);
+            raise_exception_err(env, EXCP0B_NOSEG,  new_cs & 0xfffc);
         }
         selector = e1 >> 16;
         offset = (e2 & 0xffff0000) | (e1 & 0x0000ffff);
         param_count = e2 & 0x1f;
         if ((selector & 0xfffc) == 0) {
-            raise_exception_err(EXCP0D_GPF, 0);
+            raise_exception_err(env, EXCP0D_GPF, 0);
         }
 
         if (load_segment(&e1, &e2, selector) != 0) {
-            raise_exception_err(EXCP0D_GPF, selector & 0xfffc);
+            raise_exception_err(env, EXCP0D_GPF, selector & 0xfffc);
         }
         if (!(e2 & DESC_S_MASK) || !(e2 & (DESC_CS_MASK))) {
-            raise_exception_err(EXCP0D_GPF, selector & 0xfffc);
+            raise_exception_err(env, EXCP0D_GPF, selector & 0xfffc);
         }
         dpl = (e2 >> DESC_DPL_SHIFT) & 3;
         if (dpl > cpl) {
-            raise_exception_err(EXCP0D_GPF, selector & 0xfffc);
+            raise_exception_err(env, EXCP0D_GPF, selector & 0xfffc);
         }
         if (!(e2 & DESC_P_MASK)) {
-            raise_exception_err(EXCP0B_NOSEG, selector & 0xfffc);
+            raise_exception_err(env, EXCP0B_NOSEG, selector & 0xfffc);
         }
 
         if (!(e2 & DESC_C_MASK) && dpl < cpl) {
@@ -2783,25 +2779,25 @@ void helper_lcall_protected(int new_cs, target_ulong new_eip,
                       "\n",
                       ss, sp, param_count, ESP);
             if ((ss & 0xfffc) == 0) {
-                raise_exception_err(EXCP0A_TSS, ss & 0xfffc);
+                raise_exception_err(env, EXCP0A_TSS, ss & 0xfffc);
             }
             if ((ss & 3) != dpl) {
-                raise_exception_err(EXCP0A_TSS, ss & 0xfffc);
+                raise_exception_err(env, EXCP0A_TSS, ss & 0xfffc);
             }
             if (load_segment(&ss_e1, &ss_e2, ss) != 0) {
-                raise_exception_err(EXCP0A_TSS, ss & 0xfffc);
+                raise_exception_err(env, EXCP0A_TSS, ss & 0xfffc);
             }
             ss_dpl = (ss_e2 >> DESC_DPL_SHIFT) & 3;
             if (ss_dpl != dpl) {
-                raise_exception_err(EXCP0A_TSS, ss & 0xfffc);
+                raise_exception_err(env, EXCP0A_TSS, ss & 0xfffc);
             }
             if (!(ss_e2 & DESC_S_MASK) ||
                 (ss_e2 & DESC_CS_MASK) ||
                 !(ss_e2 & DESC_W_MASK)) {
-                raise_exception_err(EXCP0A_TSS, ss & 0xfffc);
+                raise_exception_err(env, EXCP0A_TSS, ss & 0xfffc);
             }
             if (!(ss_e2 & DESC_P_MASK)) {
-                raise_exception_err(EXCP0A_TSS, ss & 0xfffc);
+                raise_exception_err(env, EXCP0A_TSS, ss & 0xfffc);
             }
 
             /* push_size = ((param_count * 2) + 8) << shift; */
@@ -2983,32 +2979,32 @@ static inline void helper_ret_protected(int shift, int is_iret, int addend)
               new_cs, new_eip, shift, addend);
     LOG_PCALL_STATE(env);
     if ((new_cs & 0xfffc) == 0) {
-        raise_exception_err(EXCP0D_GPF, new_cs & 0xfffc);
+        raise_exception_err(env, EXCP0D_GPF, new_cs & 0xfffc);
     }
     if (load_segment(&e1, &e2, new_cs) != 0) {
-        raise_exception_err(EXCP0D_GPF, new_cs & 0xfffc);
+        raise_exception_err(env, EXCP0D_GPF, new_cs & 0xfffc);
     }
     if (!(e2 & DESC_S_MASK) ||
         !(e2 & DESC_CS_MASK)) {
-        raise_exception_err(EXCP0D_GPF, new_cs & 0xfffc);
+        raise_exception_err(env, EXCP0D_GPF, new_cs & 0xfffc);
     }
     cpl = env->hflags & HF_CPL_MASK;
     rpl = new_cs & 3;
     if (rpl < cpl) {
-        raise_exception_err(EXCP0D_GPF, new_cs & 0xfffc);
+        raise_exception_err(env, EXCP0D_GPF, new_cs & 0xfffc);
     }
     dpl = (e2 >> DESC_DPL_SHIFT) & 3;
     if (e2 & DESC_C_MASK) {
         if (dpl > rpl) {
-            raise_exception_err(EXCP0D_GPF, new_cs & 0xfffc);
+            raise_exception_err(env, EXCP0D_GPF, new_cs & 0xfffc);
         }
     } else {
         if (dpl != rpl) {
-            raise_exception_err(EXCP0D_GPF, new_cs & 0xfffc);
+            raise_exception_err(env, EXCP0D_GPF, new_cs & 0xfffc);
         }
     }
     if (!(e2 & DESC_P_MASK)) {
-        raise_exception_err(EXCP0B_NOSEG, new_cs & 0xfffc);
+        raise_exception_err(env, EXCP0B_NOSEG, new_cs & 0xfffc);
     }
 
     sp += addend;
@@ -3056,26 +3052,26 @@ static inline void helper_ret_protected(int shift, int is_iret, int addend)
             } else
 #endif
             {
-                raise_exception_err(EXCP0D_GPF, 0);
+                raise_exception_err(env, EXCP0D_GPF, 0);
             }
         } else {
             if ((new_ss & 3) != rpl) {
-                raise_exception_err(EXCP0D_GPF, new_ss & 0xfffc);
+                raise_exception_err(env, EXCP0D_GPF, new_ss & 0xfffc);
             }
             if (load_segment(&ss_e1, &ss_e2, new_ss) != 0) {
-                raise_exception_err(EXCP0D_GPF, new_ss & 0xfffc);
+                raise_exception_err(env, EXCP0D_GPF, new_ss & 0xfffc);
             }
             if (!(ss_e2 & DESC_S_MASK) ||
                 (ss_e2 & DESC_CS_MASK) ||
                 !(ss_e2 & DESC_W_MASK)) {
-                raise_exception_err(EXCP0D_GPF, new_ss & 0xfffc);
+                raise_exception_err(env, EXCP0D_GPF, new_ss & 0xfffc);
             }
             dpl = (ss_e2 >> DESC_DPL_SHIFT) & 3;
             if (dpl != rpl) {
-                raise_exception_err(EXCP0D_GPF, new_ss & 0xfffc);
+                raise_exception_err(env, EXCP0D_GPF, new_ss & 0xfffc);
             }
             if (!(ss_e2 & DESC_P_MASK)) {
-                raise_exception_err(EXCP0B_NOSEG, new_ss & 0xfffc);
+                raise_exception_err(env, EXCP0B_NOSEG, new_ss & 0xfffc);
             }
             cpu_x86_load_seg_cache(env, R_SS, new_ss,
                                    get_seg_base(ss_e1, ss_e2),
@@ -3157,20 +3153,20 @@ void helper_iret_protected(int shift, int next_eip)
     if (env->eflags & NT_MASK) {
 #ifdef TARGET_X86_64
         if (env->hflags & HF_LMA_MASK) {
-            raise_exception_err(EXCP0D_GPF, 0);
+            raise_exception_err(env, EXCP0D_GPF, 0);
         }
 #endif
         tss_selector = lduw_kernel(env->tr.base + 0);
         if (tss_selector & 4) {
-            raise_exception_err(EXCP0A_TSS, tss_selector & 0xfffc);
+            raise_exception_err(env, EXCP0A_TSS, tss_selector & 0xfffc);
         }
         if (load_segment(&e1, &e2, tss_selector) != 0) {
-            raise_exception_err(EXCP0A_TSS, tss_selector & 0xfffc);
+            raise_exception_err(env, EXCP0A_TSS, tss_selector & 0xfffc);
         }
         type = (e2 >> DESC_TYPE_SHIFT) & 0x17;
         /* NOTE: we check both segment and busy TSS */
         if (type != 3) {
-            raise_exception_err(EXCP0A_TSS, tss_selector & 0xfffc);
+            raise_exception_err(env, EXCP0A_TSS, tss_selector & 0xfffc);
         }
         switch_tss(tss_selector, e1, e2, SWITCH_TSS_IRET, next_eip);
     } else {
@@ -3187,7 +3183,7 @@ void helper_lret_protected(int shift, int addend)
 void helper_sysenter(void)
 {
     if (env->sysenter_cs == 0) {
-        raise_exception_err(EXCP0D_GPF, 0);
+        raise_exception_err(env, EXCP0D_GPF, 0);
     }
     env->eflags &= ~(VM_MASK | IF_MASK | RF_MASK);
     cpu_x86_set_cpl(env, 0);
@@ -3224,7 +3220,7 @@ void helper_sysexit(int dflag)
 
     cpl = env->hflags & HF_CPL_MASK;
     if (env->sysenter_cs == 0 || cpl != 0) {
-        raise_exception_err(EXCP0D_GPF, 0);
+        raise_exception_err(env, EXCP0D_GPF, 0);
     }
     cpu_x86_set_cpl(env, 3);
 #ifdef TARGET_X86_64
@@ -3364,7 +3360,7 @@ void helper_rdtsc(void)
     uint64_t val;
 
     if ((env->cr[4] & CR4_TSD_MASK) && ((env->hflags & HF_CPL_MASK) != 0)) {
-        raise_exception(EXCP0D_GPF);
+        raise_exception(env, EXCP0D_GPF);
     }
     helper_svm_check_intercept_param(SVM_EXIT_RDTSC, 0);
 
@@ -3382,13 +3378,13 @@ void helper_rdtscp(void)
 void helper_rdpmc(void)
 {
     if ((env->cr[4] & CR4_PCE_MASK) && ((env->hflags & HF_CPL_MASK) != 0)) {
-        raise_exception(EXCP0D_GPF);
+        raise_exception(env, EXCP0D_GPF);
     }
     helper_svm_check_intercept_param(SVM_EXIT_RDPMC, 0);
 
     /* currently unimplemented */
     qemu_log_mask(LOG_UNIMP, "x86: unimplemented rdpmc\n");
-    raise_exception_err(EXCP06_ILLOP, 0);
+    raise_exception_err(env, EXCP06_ILLOP, 0);
 }
 
 #if defined(CONFIG_USER_ONLY)
@@ -3900,7 +3896,7 @@ static inline floatx80 helper_fdiv(floatx80 a, floatx80 b)
 static void fpu_raise_exception(void)
 {
     if (env->cr[0] & CR0_NE_MASK) {
-        raise_exception(EXCP10_COPR);
+        raise_exception(env, EXCP10_COPR);
     }
 #if !defined(CONFIG_USER_ONLY)
     else {
@@ -4894,7 +4890,7 @@ void helper_fxsave(target_ulong ptr, int data64)
 
     /* The operand must be 16 byte aligned */
     if (ptr & 0xf) {
-        raise_exception(EXCP0D_GPF);
+        raise_exception(env, EXCP0D_GPF);
     }
 
     fpus = (env->fpus & ~0x3800) | (env->fpstt & 0x7) << 11;
@@ -4956,7 +4952,7 @@ void helper_fxrstor(target_ulong ptr, int data64)
 
     /* The operand must be 16 byte aligned */
     if (ptr & 0xf) {
-        raise_exception(EXCP0D_GPF);
+        raise_exception(env, EXCP0D_GPF);
     }
 
     env->fpuc = lduw(ptr);
@@ -5144,12 +5140,12 @@ void helper_divq_EAX(target_ulong t0)
     uint64_t r0, r1;
 
     if (t0 == 0) {
-        raise_exception(EXCP00_DIVZ);
+        raise_exception(env, EXCP00_DIVZ);
     }
     r0 = EAX;
     r1 = EDX;
     if (div64(&r0, &r1, t0)) {
-        raise_exception(EXCP00_DIVZ);
+        raise_exception(env, EXCP00_DIVZ);
     }
     EAX = r0;
     EDX = r1;
@@ -5160,12 +5156,12 @@ void helper_idivq_EAX(target_ulong t0)
     uint64_t r0, r1;
 
     if (t0 == 0) {
-        raise_exception(EXCP00_DIVZ);
+        raise_exception(env, EXCP00_DIVZ);
     }
     r0 = EAX;
     r1 = EDX;
     if (idiv64(&r0, &r1, t0)) {
-        raise_exception(EXCP00_DIVZ);
+        raise_exception(env, EXCP00_DIVZ);
     }
     EAX = r0;
     EDX = r1;
@@ -5191,7 +5187,7 @@ void helper_hlt(int next_eip_addend)
 void helper_monitor(target_ulong ptr)
 {
     if ((uint32_t)ECX != 0) {
-        raise_exception(EXCP0D_GPF);
+        raise_exception(env, EXCP0D_GPF);
     }
     /* XXX: store address? */
     helper_svm_check_intercept_param(SVM_EXIT_MONITOR, 0);
@@ -5200,7 +5196,7 @@ void helper_monitor(target_ulong ptr)
 void helper_mwait(int next_eip_addend)
 {
     if ((uint32_t)ECX != 0) {
-        raise_exception(EXCP0D_GPF);
+        raise_exception(env, EXCP0D_GPF);
     }
     helper_svm_check_intercept_param(SVM_EXIT_MWAIT, 0);
     EIP += next_eip_addend;
@@ -5225,14 +5221,14 @@ void helper_reset_rf(void)
     env->eflags &= ~RF_MASK;
 }
 
-void helper_raise_interrupt(int intno, int next_eip_addend)
+void helper_raise_interrupt(CPUX86State *env, int intno, int next_eip_addend)
 {
-    raise_interrupt(intno, 1, 0, next_eip_addend);
+    raise_interrupt(env, intno, 1, 0, next_eip_addend);
 }
 
-void helper_raise_exception(int exception_index)
+void helper_raise_exception(CPUX86State *env, int exception_index)
 {
-    raise_exception(exception_index);
+    raise_exception(env, exception_index);
 }
 
 void helper_cli(void)
@@ -5256,7 +5252,7 @@ void helper_sti_vm(void)
 {
     env->eflags |= VIF_MASK;
     if (env->eflags & VIP_MASK) {
-        raise_exception(EXCP0D_GPF);
+        raise_exception(env, EXCP0D_GPF);
     }
 }
 #endif
@@ -5279,7 +5275,7 @@ void helper_boundw(target_ulong a0, int v)
     high = ldsw(a0 + 2);
     v = (int16_t)v;
     if (v < low || v > high) {
-        raise_exception(EXCP05_BOUND);
+        raise_exception(env, EXCP05_BOUND);
     }
 }
 
@@ -5290,7 +5286,7 @@ void helper_boundl(target_ulong a0, int v)
     low = ldl(a0);
     high = ldl(a0 + 4);
     if (v < low || v > high) {
-        raise_exception(EXCP05_BOUND);
+        raise_exception(env, EXCP05_BOUND);
     }
 }
 
@@ -5338,7 +5334,7 @@ void tlb_fill(CPUX86State *env1, target_ulong addr, int is_write, int mmu_idx,
                 cpu_restore_state(tb, env, retaddr);
             }
         }
-        raise_exception_err(env->exception_index, env->error_code);
+        raise_exception_err(env, env->exception_index, env->error_code);
     }
     env = saved_env;
 }
@@ -5384,11 +5380,16 @@ void helper_vmexit(uint32_t exit_code, uint64_t exit_info_1)
 {
 }
 
+void cpu_vmexit(CPUX86State *nenv, uint32_t exit_code, uint64_t exit_info_1)
+{
+}
+
 void helper_svm_check_intercept_param(uint32_t type, uint64_t param)
 {
 }
 
-void svm_check_intercept(CPUX86State *env1, uint32_t type)
+void cpu_svm_check_intercept_param(CPUX86State *env, uint32_t type,
+                                   uint64_t param)
 {
 }
 
@@ -5605,7 +5606,7 @@ void helper_vmrun(int aflag, int next_eip_addend)
             env->exception_next_eip = -1;
             qemu_log_mask(CPU_LOG_TB_IN_ASM, "INTR");
             /* XXX: is it always correct? */
-            do_interrupt_all(vector, 0, 0, 0, 1);
+            do_interrupt_x86_hardirq(env, vector, 1);
             break;
         case SVM_EVTINJ_TYPE_NMI:
             env->exception_index = EXCP02_NMI;
@@ -5640,7 +5641,7 @@ void helper_vmrun(int aflag, int next_eip_addend)
 void helper_vmmcall(void)
 {
     helper_svm_check_intercept_param(SVM_EXIT_VMMCALL, 0);
-    raise_exception(EXCP06_ILLOP);
+    raise_exception(env, EXCP06_ILLOP);
 }
 
 void helper_vmload(int aflag)
@@ -5741,7 +5742,7 @@ void helper_skinit(void)
 {
     helper_svm_check_intercept_param(SVM_EXIT_SKINIT, 0);
     /* XXX: not implemented */
-    raise_exception(EXCP06_ILLOP);
+    raise_exception(env, EXCP06_ILLOP);
 }
 
 void helper_invlpga(int aflag)
@@ -5834,13 +5835,14 @@ void helper_svm_check_intercept_param(uint32_t type, uint64_t param)
     }
 }
 
-void svm_check_intercept(CPUX86State *env1, uint32_t type)
+void cpu_svm_check_intercept_param(CPUX86State *env1, uint32_t type,
+                                   uint64_t param)
 {
     CPUX86State *saved_env;
 
     saved_env = env;
     env = env1;
-    helper_svm_check_intercept_param(type, 0);
+    helper_svm_check_intercept_param(type, param);
     env = saved_env;
 }
 
@@ -6022,6 +6024,12 @@ void helper_vmexit(uint32_t exit_code, uint64_t exit_info_1)
     cpu_loop_exit(env);
 }
 
+void cpu_vmexit(CPUX86State *nenv, uint32_t exit_code, uint64_t exit_info_1)
+{
+    env = nenv;
+    helper_vmexit(exit_code, exit_info_1);
+}
+
 #endif
 
 /* MMX/SSE */
diff --git a/target-i386/translate.c b/target-i386/translate.c
index c1ede1a..8ac6132 100644
--- a/target-i386/translate.c
+++ b/target-i386/translate.c
@@ -2659,7 +2659,7 @@ static void gen_exception(DisasContext *s, int trapno, target_ulong cur_eip)
     if (s->cc_op != CC_OP_DYNAMIC)
         gen_op_set_cc_op(s->cc_op);
     gen_jmp_im(cur_eip);
-    gen_helper_raise_exception(tcg_const_i32(trapno));
+    gen_helper_raise_exception(cpu_env, tcg_const_i32(trapno));
     s->is_jmp = DISAS_TB_JUMP;
 }
 
@@ -2671,7 +2671,7 @@ static void gen_interrupt(DisasContext *s, int intno,
     if (s->cc_op != CC_OP_DYNAMIC)
         gen_op_set_cc_op(s->cc_op);
     gen_jmp_im(cur_eip);
-    gen_helper_raise_interrupt(tcg_const_i32(intno), 
+    gen_helper_raise_interrupt(cpu_env, tcg_const_i32(intno),
                                tcg_const_i32(next_eip - cur_eip));
     s->is_jmp = DISAS_TB_JUMP;
 }
diff --git a/user-exec.c b/user-exec.c
index d8c2ad9..b2a4261 100644
--- a/user-exec.c
+++ b/user-exec.c
@@ -41,7 +41,7 @@
 static void exception_action(CPUArchState *env1)
 {
 #if defined(TARGET_I386)
-    raise_exception_err_env(env1, env1->exception_index, env1->error_code);
+    raise_exception_err(env1, env1->exception_index, env1->error_code);
 #else
     cpu_loop_exit(env1);
 #endif
commit 20054ef03e0bd051178edd9d1378aa59570dbcf5
Author: Blue Swirl <blauwirbel at gmail.com>
Date:   Sat Apr 28 15:33:48 2012 +0000

    x86: prepare op_helper.c for splitting
    
    Fix coding style and a few typos.
    
    Signed-off-by: Blue Swirl <blauwirbel at gmail.com>

diff --git a/target-i386/op_helper.c b/target-i386/op_helper.c
index 2862ea4..b9c1b93 100644
--- a/target-i386/op_helper.c
+++ b/target-i386/op_helper.c
@@ -31,14 +31,15 @@
 #endif /* !defined(CONFIG_USER_ONLY) */
 
 //#define DEBUG_PCALL
+//#define DEBUG_MULDIV
 
 #ifdef DEBUG_PCALL
-#  define LOG_PCALL(...) qemu_log_mask(CPU_LOG_PCALL, ## __VA_ARGS__)
-#  define LOG_PCALL_STATE(env) \
-          log_cpu_state_mask(CPU_LOG_PCALL, (env), X86_DUMP_CCOP)
+# define LOG_PCALL(...) qemu_log_mask(CPU_LOG_PCALL, ## __VA_ARGS__)
+# define LOG_PCALL_STATE(env)                                  \
+    log_cpu_state_mask(CPU_LOG_PCALL, (env), X86_DUMP_CCOP)
 #else
-#  define LOG_PCALL(...) do { } while (0)
-#  define LOG_PCALL_STATE(env) do { } while (0)
+# define LOG_PCALL(...) do { } while (0)
+# define LOG_PCALL_STATE(env) do { } while (0)
 #endif
 
 /* n must be a constant to be efficient */
@@ -75,7 +76,7 @@ static inline void fpush(void)
 
 static inline void fpop(void)
 {
-    env->fptags[env->fpstt] = 1; /* invvalidate stack entry */
+    env->fptags[env->fpstt] = 1; /* invalidate stack entry */
     env->fpstt = (env->fpstt + 1) & 7;
 }
 
@@ -124,7 +125,7 @@ static inline void load_eflags(int eflags, int update_mask)
 }
 
 /* load efer and update the corresponding hflags. XXX: do consistency
-   checks with cpuid bits ? */
+   checks with cpuid bits? */
 static inline void cpu_load_efer(CPUX86State *env, uint64_t val)
 {
     env->efer = val;
@@ -138,11 +139,11 @@ static inline void cpu_load_efer(CPUX86State *env, uint64_t val)
 }
 
 #if 0
-#define raise_exception_err(a, b)\
-do {\
-    qemu_log("raise_exception line=%d\n", __LINE__);\
-    (raise_exception_err)(a, b);\
-} while (0)
+#define raise_exception_err(a, b)                                       \
+    do {                                                                \
+        qemu_log("raise_exception line=%d\n", __LINE__);                \
+        (raise_exception_err)(a, b);                                    \
+    } while (0)
 #endif
 
 static void QEMU_NORETURN raise_exception_err(int exception_index,
@@ -186,9 +187,9 @@ static const uint8_t parity_table[256] = {
 /* modulo 17 table */
 static const uint8_t rclw_table[32] = {
     0, 1, 2, 3, 4, 5, 6, 7,
-    8, 9,10,11,12,13,14,15,
-   16, 0, 1, 2, 3, 4, 5, 6,
-    7, 8, 9,10,11,12,13,14,
+    8, 9, 10, 11, 12, 13, 14, 15,
+    16, 0, 1, 2, 3, 4, 5, 6,
+    7, 8, 9, 10, 11, 12, 13, 14,
 };
 
 /* modulo 9 table */
@@ -199,9 +200,9 @@ static const uint8_t rclb_table[32] = {
     6, 7, 8, 0, 1, 2, 3, 4,
 };
 
-#define floatx80_lg2 make_floatx80( 0x3ffd, 0x9a209a84fbcff799LL )
-#define floatx80_l2e make_floatx80( 0x3fff, 0xb8aa3b295c17f0bcLL )
-#define floatx80_l2t make_floatx80( 0x4000, 0xd49a784bcd1b8afeLL )
+#define floatx80_lg2 make_floatx80(0x3ffd, 0x9a209a84fbcff799LL)
+#define floatx80_l2e make_floatx80(0x3fff, 0xb8aa3b295c17f0bcLL)
+#define floatx80_l2t make_floatx80(0x4000, 0xd49a784bcd1b8afeLL)
 
 /* broken thread support */
 
@@ -225,6 +226,7 @@ void helper_write_eflags(target_ulong t0, uint32_t update_mask)
 target_ulong helper_read_eflags(void)
 {
     uint32_t eflags;
+
     eflags = helper_cc_compute_all(CC_OP);
     eflags |= (DF & DF_MASK);
     eflags |= env->eflags & ~(VM_MASK | RF_MASK);
@@ -239,13 +241,15 @@ static inline int load_segment(uint32_t *e1_ptr, uint32_t *e2_ptr,
     int index;
     target_ulong ptr;
 
-    if (selector & 0x4)
+    if (selector & 0x4) {
         dt = &env->ldt;
-    else
+    } else {
         dt = &env->gdt;
+    }
     index = selector & ~7;
-    if ((index + 7) > dt->limit)
+    if ((index + 7) > dt->limit) {
         return -1;
+    }
     ptr = dt->base + index;
     *e1_ptr = ldl_kernel(ptr);
     *e2_ptr = ldl_kernel(ptr + 4);
@@ -255,18 +259,21 @@ static inline int load_segment(uint32_t *e1_ptr, uint32_t *e2_ptr,
 static inline unsigned int get_seg_limit(uint32_t e1, uint32_t e2)
 {
     unsigned int limit;
+
     limit = (e1 & 0xffff) | (e2 & 0x000f0000);
-    if (e2 & DESC_G_MASK)
+    if (e2 & DESC_G_MASK) {
         limit = (limit << 12) | 0xfff;
+    }
     return limit;
 }
 
 static inline uint32_t get_seg_base(uint32_t e1, uint32_t e2)
 {
-    return ((e1 >> 16) | ((e2 & 0xff) << 16) | (e2 & 0xff000000));
+    return (e1 >> 16) | ((e2 & 0xff) << 16) | (e2 & 0xff000000);
 }
 
-static inline void load_seg_cache_raw_dt(SegmentCache *sc, uint32_t e1, uint32_t e2)
+static inline void load_seg_cache_raw_dt(SegmentCache *sc, uint32_t e1,
+                                         uint32_t e2)
 {
     sc->base = get_seg_base(e1, e2);
     sc->limit = get_seg_limit(e1, e2);
@@ -290,23 +297,28 @@ static inline void get_ss_esp_from_tss(uint32_t *ss_ptr,
     {
         int i;
         printf("TR: base=%p limit=%x\n", env->tr.base, env->tr.limit);
-        for(i=0;i<env->tr.limit;i++) {
+        for (i = 0; i < env->tr.limit; i++) {
             printf("%02x ", env->tr.base[i]);
-            if ((i & 7) == 7) printf("\n");
+            if ((i & 7) == 7) {
+                printf("\n");
+            }
         }
         printf("\n");
     }
 #endif
 
-    if (!(env->tr.flags & DESC_P_MASK))
+    if (!(env->tr.flags & DESC_P_MASK)) {
         cpu_abort(env, "invalid tss");
+    }
     type = (env->tr.flags >> DESC_TYPE_SHIFT) & 0xf;
-    if ((type & 7) != 1)
+    if ((type & 7) != 1) {
         cpu_abort(env, "invalid tss type");
+    }
     shift = type >> 3;
     index = (dpl * 4 + 2) << shift;
-    if (index + (4 << shift) - 1 > env->tr.limit)
+    if (index + (4 << shift) - 1 > env->tr.limit) {
         raise_exception_err(EXCP0A_TSS, env->tr.selector & 0xfffc);
+    }
     if (shift == 0) {
         *esp_ptr = lduw_kernel(env->tr.base + index);
         *ss_ptr = lduw_kernel(env->tr.base + index + 2);
@@ -323,46 +335,57 @@ static void tss_load_seg(int seg_reg, int selector)
     int rpl, dpl, cpl;
 
     if ((selector & 0xfffc) != 0) {
-        if (load_segment(&e1, &e2, selector) != 0)
+        if (load_segment(&e1, &e2, selector) != 0) {
             raise_exception_err(EXCP0A_TSS, selector & 0xfffc);
-        if (!(e2 & DESC_S_MASK))
+        }
+        if (!(e2 & DESC_S_MASK)) {
             raise_exception_err(EXCP0A_TSS, selector & 0xfffc);
+        }
         rpl = selector & 3;
         dpl = (e2 >> DESC_DPL_SHIFT) & 3;
         cpl = env->hflags & HF_CPL_MASK;
         if (seg_reg == R_CS) {
-            if (!(e2 & DESC_CS_MASK))
+            if (!(e2 & DESC_CS_MASK)) {
                 raise_exception_err(EXCP0A_TSS, selector & 0xfffc);
-            /* XXX: is it correct ? */
-            if (dpl != rpl)
+            }
+            /* XXX: is it correct? */
+            if (dpl != rpl) {
                 raise_exception_err(EXCP0A_TSS, selector & 0xfffc);
-            if ((e2 & DESC_C_MASK) && dpl > rpl)
+            }
+            if ((e2 & DESC_C_MASK) && dpl > rpl) {
                 raise_exception_err(EXCP0A_TSS, selector & 0xfffc);
+            }
         } else if (seg_reg == R_SS) {
             /* SS must be writable data */
-            if ((e2 & DESC_CS_MASK) || !(e2 & DESC_W_MASK))
+            if ((e2 & DESC_CS_MASK) || !(e2 & DESC_W_MASK)) {
                 raise_exception_err(EXCP0A_TSS, selector & 0xfffc);
-            if (dpl != cpl || dpl != rpl)
+            }
+            if (dpl != cpl || dpl != rpl) {
                 raise_exception_err(EXCP0A_TSS, selector & 0xfffc);
+            }
         } else {
             /* not readable code */
-            if ((e2 & DESC_CS_MASK) && !(e2 & DESC_R_MASK))
+            if ((e2 & DESC_CS_MASK) && !(e2 & DESC_R_MASK)) {
                 raise_exception_err(EXCP0A_TSS, selector & 0xfffc);
+            }
             /* if data or non conforming code, checks the rights */
             if (((e2 >> DESC_TYPE_SHIFT) & 0xf) < 12) {
-                if (dpl < cpl || dpl < rpl)
+                if (dpl < cpl || dpl < rpl) {
                     raise_exception_err(EXCP0A_TSS, selector & 0xfffc);
+                }
             }
         }
-        if (!(e2 & DESC_P_MASK))
+        if (!(e2 & DESC_P_MASK)) {
             raise_exception_err(EXCP0B_NOSEG, selector & 0xfffc);
+        }
         cpu_x86_load_seg_cache(env, seg_reg, selector,
-                       get_seg_base(e1, e2),
-                       get_seg_limit(e1, e2),
-                       e2);
+                               get_seg_base(e1, e2),
+                               get_seg_limit(e1, e2),
+                               e2);
     } else {
-        if (seg_reg == R_SS || seg_reg == R_CS)
+        if (seg_reg == R_SS || seg_reg == R_CS) {
             raise_exception_err(EXCP0A_TSS, selector & 0xfffc);
+        }
     }
 }
 
@@ -385,41 +408,51 @@ static void switch_tss(int tss_selector,
     target_ulong ptr;
 
     type = (e2 >> DESC_TYPE_SHIFT) & 0xf;
-    LOG_PCALL("switch_tss: sel=0x%04x type=%d src=%d\n", tss_selector, type, source);
+    LOG_PCALL("switch_tss: sel=0x%04x type=%d src=%d\n", tss_selector, type,
+              source);
 
     /* if task gate, we read the TSS segment and we load it */
     if (type == 5) {
-        if (!(e2 & DESC_P_MASK))
+        if (!(e2 & DESC_P_MASK)) {
             raise_exception_err(EXCP0B_NOSEG, tss_selector & 0xfffc);
+        }
         tss_selector = e1 >> 16;
-        if (tss_selector & 4)
+        if (tss_selector & 4) {
             raise_exception_err(EXCP0A_TSS, tss_selector & 0xfffc);
-        if (load_segment(&e1, &e2, tss_selector) != 0)
+        }
+        if (load_segment(&e1, &e2, tss_selector) != 0) {
             raise_exception_err(EXCP0D_GPF, tss_selector & 0xfffc);
-        if (e2 & DESC_S_MASK)
+        }
+        if (e2 & DESC_S_MASK) {
             raise_exception_err(EXCP0D_GPF, tss_selector & 0xfffc);
+        }
         type = (e2 >> DESC_TYPE_SHIFT) & 0xf;
-        if ((type & 7) != 1)
+        if ((type & 7) != 1) {
             raise_exception_err(EXCP0D_GPF, tss_selector & 0xfffc);
+        }
     }
 
-    if (!(e2 & DESC_P_MASK))
+    if (!(e2 & DESC_P_MASK)) {
         raise_exception_err(EXCP0B_NOSEG, tss_selector & 0xfffc);
+    }
 
-    if (type & 8)
+    if (type & 8) {
         tss_limit_max = 103;
-    else
+    } else {
         tss_limit_max = 43;
+    }
     tss_limit = get_seg_limit(e1, e2);
     tss_base = get_seg_base(e1, e2);
     if ((tss_selector & 4) != 0 ||
-        tss_limit < tss_limit_max)
+        tss_limit < tss_limit_max) {
         raise_exception_err(EXCP0A_TSS, tss_selector & 0xfffc);
+    }
     old_type = (env->tr.flags >> DESC_TYPE_SHIFT) & 0xf;
-    if (old_type & 8)
+    if (old_type & 8) {
         old_tss_limit_max = 103;
-    else
+    } else {
         old_tss_limit_max = 43;
+    }
 
     /* read all the registers from the new TSS */
     if (type & 8) {
@@ -427,10 +460,12 @@ static void switch_tss(int tss_selector,
         new_cr3 = ldl_kernel(tss_base + 0x1c);
         new_eip = ldl_kernel(tss_base + 0x20);
         new_eflags = ldl_kernel(tss_base + 0x24);
-        for(i = 0; i < 8; i++)
+        for (i = 0; i < 8; i++) {
             new_regs[i] = ldl_kernel(tss_base + (0x28 + i * 4));
-        for(i = 0; i < 6; i++)
+        }
+        for (i = 0; i < 6; i++) {
             new_segs[i] = lduw_kernel(tss_base + (0x48 + i * 4));
+        }
         new_ldt = lduw_kernel(tss_base + 0x60);
         new_trap = ldl_kernel(tss_base + 0x64);
     } else {
@@ -438,10 +473,12 @@ static void switch_tss(int tss_selector,
         new_cr3 = 0;
         new_eip = lduw_kernel(tss_base + 0x0e);
         new_eflags = lduw_kernel(tss_base + 0x10);
-        for(i = 0; i < 8; i++)
+        for (i = 0; i < 8; i++) {
             new_regs[i] = lduw_kernel(tss_base + (0x12 + i * 2)) | 0xffff0000;
-        for(i = 0; i < 4; i++)
+        }
+        for (i = 0; i < 4; i++) {
             new_segs[i] = lduw_kernel(tss_base + (0x22 + i * 4));
+        }
         new_ldt = lduw_kernel(tss_base + 0x2a);
         new_segs[R_FS] = 0;
         new_segs[R_GS] = 0;
@@ -466,14 +503,16 @@ static void switch_tss(int tss_selector,
     if (source == SWITCH_TSS_JMP || source == SWITCH_TSS_IRET) {
         target_ulong ptr;
         uint32_t e2;
+
         ptr = env->gdt.base + (env->tr.selector & ~7);
         e2 = ldl_kernel(ptr + 4);
         e2 &= ~DESC_TSS_BUSY_MASK;
         stl_kernel(ptr + 4, e2);
     }
     old_eflags = compute_eflags();
-    if (source == SWITCH_TSS_IRET)
+    if (source == SWITCH_TSS_IRET) {
         old_eflags &= ~NT_MASK;
+    }
 
     /* save the current state in the old TSS */
     if (type & 8) {
@@ -488,8 +527,9 @@ static void switch_tss(int tss_selector,
         stl_kernel(env->tr.base + (0x28 + 5 * 4), EBP);
         stl_kernel(env->tr.base + (0x28 + 6 * 4), ESI);
         stl_kernel(env->tr.base + (0x28 + 7 * 4), EDI);
-        for(i = 0; i < 6; i++)
+        for (i = 0; i < 6; i++) {
             stw_kernel(env->tr.base + (0x48 + i * 4), env->segs[i].selector);
+        }
     } else {
         /* 16 bit */
         stw_kernel(env->tr.base + 0x0e, next_eip);
@@ -502,8 +542,9 @@ static void switch_tss(int tss_selector,
         stw_kernel(env->tr.base + (0x12 + 5 * 2), EBP);
         stw_kernel(env->tr.base + (0x12 + 6 * 2), ESI);
         stw_kernel(env->tr.base + (0x12 + 7 * 2), EDI);
-        for(i = 0; i < 4; i++)
+        for (i = 0; i < 4; i++) {
             stw_kernel(env->tr.base + (0x22 + i * 4), env->segs[i].selector);
+        }
     }
 
     /* now if an exception occurs, it will occurs in the next task
@@ -518,6 +559,7 @@ static void switch_tss(int tss_selector,
     if (source == SWITCH_TSS_JMP || source == SWITCH_TSS_CALL) {
         target_ulong ptr;
         uint32_t e2;
+
         ptr = env->gdt.base + (tss_selector & ~7);
         e2 = ldl_kernel(ptr + 4);
         e2 |= DESC_TSS_BUSY_MASK;
@@ -542,10 +584,11 @@ static void switch_tss(int tss_selector,
     env->eip = new_eip;
     eflags_mask = TF_MASK | AC_MASK | ID_MASK |
         IF_MASK | IOPL_MASK | VM_MASK | RF_MASK | NT_MASK;
-    if (!(type & 8))
+    if (!(type & 8)) {
         eflags_mask &= 0xffff;
+    }
     load_eflags(new_eflags, eflags_mask);
-    /* XXX: what to do in 16 bit case ? */
+    /* XXX: what to do in 16 bit case? */
     EAX = new_regs[0];
     ECX = new_regs[1];
     EDX = new_regs[2];
@@ -555,16 +598,18 @@ static void switch_tss(int tss_selector,
     ESI = new_regs[6];
     EDI = new_regs[7];
     if (new_eflags & VM_MASK) {
-        for(i = 0; i < 6; i++)
+        for (i = 0; i < 6; i++) {
             load_seg_vm(i, new_segs[i]);
+        }
         /* in vm86, CPL is always 3 */
         cpu_x86_set_cpl(env, 3);
     } else {
         /* CPL is set the RPL of CS */
         cpu_x86_set_cpl(env, new_segs[R_CS] & 3);
         /* first just selectors as the rest may trigger exceptions */
-        for(i = 0; i < 6; i++)
+        for (i = 0; i < 6; i++) {
             cpu_x86_load_seg_cache(env, i, new_segs[i], 0, 0, 0);
+        }
     }
 
     env->ldt.selector = new_ldt & ~4;
@@ -573,21 +618,25 @@ static void switch_tss(int tss_selector,
     env->ldt.flags = 0;
 
     /* load the LDT */
-    if (new_ldt & 4)
+    if (new_ldt & 4) {
         raise_exception_err(EXCP0A_TSS, new_ldt & 0xfffc);
+    }
 
     if ((new_ldt & 0xfffc) != 0) {
         dt = &env->gdt;
         index = new_ldt & ~7;
-        if ((index + 7) > dt->limit)
+        if ((index + 7) > dt->limit) {
             raise_exception_err(EXCP0A_TSS, new_ldt & 0xfffc);
+        }
         ptr = dt->base + index;
         e1 = ldl_kernel(ptr);
         e2 = ldl_kernel(ptr + 4);
-        if ((e2 & DESC_S_MASK) || ((e2 >> DESC_TYPE_SHIFT) & 0xf) != 2)
+        if ((e2 & DESC_S_MASK) || ((e2 >> DESC_TYPE_SHIFT) & 0xf) != 2) {
             raise_exception_err(EXCP0A_TSS, new_ldt & 0xfffc);
-        if (!(e2 & DESC_P_MASK))
+        }
+        if (!(e2 & DESC_P_MASK)) {
             raise_exception_err(EXCP0A_TSS, new_ldt & 0xfffc);
+        }
         load_seg_cache_raw_dt(&env->ldt, e1, e2);
     }
 
@@ -603,7 +652,7 @@ static void switch_tss(int tss_selector,
 
     /* check that EIP is in the CS segment limits */
     if (new_eip > env->segs[R_CS].limit) {
-        /* XXX: different exception if CALL ? */
+        /* XXX: different exception if CALL? */
         raise_exception_err(EXCP0D_GPF, 0);
     }
 
@@ -611,8 +660,9 @@ static void switch_tss(int tss_selector,
     /* reset local breakpoints */
     if (env->dr[7] & 0x55) {
         for (i = 0; i < 4; i++) {
-            if (hw_breakpoint_enabled(env->dr[7], i) == 0x1)
+            if (hw_breakpoint_enabled(env->dr[7], i) == 0x1) {
                 hw_breakpoint_remove(env, i);
+            }
         }
         env->dr[7] &= ~0x55;
     }
@@ -627,13 +677,15 @@ static inline void check_io(int addr, int size)
     /* TSS must be a valid 32 bit one */
     if (!(env->tr.flags & DESC_P_MASK) ||
         ((env->tr.flags >> DESC_TYPE_SHIFT) & 0xf) != 9 ||
-        env->tr.limit < 103)
+        env->tr.limit < 103) {
         goto fail;
+    }
     io_offset = lduw_kernel(env->tr.base + 0x66);
     io_offset += (addr >> 3);
     /* Note: the check needs two bytes */
-    if ((io_offset + 1) > env->tr.limit)
+    if ((io_offset + 1) > env->tr.limit) {
         goto fail;
+    }
     val = lduw_kernel(env->tr.base + io_offset);
     val >>= (addr & 7);
     mask = (1 << size) - 1;
@@ -691,39 +743,44 @@ target_ulong helper_inl(uint32_t port)
 
 static inline unsigned int get_sp_mask(unsigned int e2)
 {
-    if (e2 & DESC_B_MASK)
+    if (e2 & DESC_B_MASK) {
         return 0xffffffff;
-    else
+    } else {
         return 0xffff;
+    }
 }
 
-static int exeption_has_error_code(int intno)
+static int exception_has_error_code(int intno)
 {
-        switch(intno) {
-        case 8:
-        case 10:
-        case 11:
-        case 12:
-        case 13:
-        case 14:
-        case 17:
-            return 1;
-        }
-	return 0;
+    switch (intno) {
+    case 8:
+    case 10:
+    case 11:
+    case 12:
+    case 13:
+    case 14:
+    case 17:
+        return 1;
+    }
+    return 0;
 }
 
 #ifdef TARGET_X86_64
-#define SET_ESP(val, sp_mask)\
-do {\
-    if ((sp_mask) == 0xffff)\
-        ESP = (ESP & ~0xffff) | ((val) & 0xffff);\
-    else if ((sp_mask) == 0xffffffffLL)\
-        ESP = (uint32_t)(val);\
-    else\
-        ESP = (val);\
-} while (0)
+#define SET_ESP(val, sp_mask)                           \
+    do {                                                \
+        if ((sp_mask) == 0xffff) {                      \
+            ESP = (ESP & ~0xffff) | ((val) & 0xffff);   \
+        } else if ((sp_mask) == 0xffffffffLL) {         \
+            ESP = (uint32_t)(val);                      \
+        } else {                                        \
+            ESP = (val);                                \
+        }                                               \
+    } while (0)
 #else
-#define SET_ESP(val, sp_mask) ESP = (ESP & ~(sp_mask)) | ((val) & (sp_mask))
+#define SET_ESP(val, sp_mask)                           \
+    do {                                                \
+        ESP = (ESP & ~(sp_mask)) | ((val) & (sp_mask)); \
+    } while (0)
 #endif
 
 /* in 64-bit machines, this can overflow. So this segment addition macro
@@ -731,29 +788,29 @@ do {\
 #define SEG_ADDL(ssp, sp, sp_mask) ((uint32_t)((ssp) + (sp & (sp_mask))))
 
 /* XXX: add a is_user flag to have proper security support */
-#define PUSHW(ssp, sp, sp_mask, val)\
-{\
-    sp -= 2;\
-    stw_kernel((ssp) + (sp & (sp_mask)), (val));\
-}
+#define PUSHW(ssp, sp, sp_mask, val)                    \
+    {                                                   \
+        sp -= 2;                                        \
+        stw_kernel((ssp) + (sp & (sp_mask)), (val));    \
+    }
 
-#define PUSHL(ssp, sp, sp_mask, val)\
-{\
-    sp -= 4;\
-    stl_kernel(SEG_ADDL(ssp, sp, sp_mask), (uint32_t)(val));\
-}
+#define PUSHL(ssp, sp, sp_mask, val)                                    \
+    {                                                                   \
+        sp -= 4;                                                        \
+        stl_kernel(SEG_ADDL(ssp, sp, sp_mask), (uint32_t)(val));        \
+    }
 
-#define POPW(ssp, sp, sp_mask, val)\
-{\
-    val = lduw_kernel((ssp) + (sp & (sp_mask)));\
-    sp += 2;\
-}
+#define POPW(ssp, sp, sp_mask, val)                     \
+    {                                                   \
+        val = lduw_kernel((ssp) + (sp & (sp_mask)));    \
+        sp += 2;                                        \
+    }
 
-#define POPL(ssp, sp, sp_mask, val)\
-{\
-    val = (uint32_t)ldl_kernel(SEG_ADDL(ssp, sp, sp_mask));\
-    sp += 4;\
-}
+#define POPL(ssp, sp, sp_mask, val)                             \
+    {                                                           \
+        val = (uint32_t)ldl_kernel(SEG_ADDL(ssp, sp, sp_mask)); \
+        sp += 4;                                                \
+    }
 
 /* protected mode interrupt */
 static void do_interrupt_protected(int intno, int is_int, int error_code,
@@ -767,43 +824,50 @@ static void do_interrupt_protected(int intno, int is_int, int error_code,
     uint32_t old_eip, sp_mask;
 
     has_error_code = 0;
-    if (!is_int && !is_hw)
-        has_error_code = exeption_has_error_code(intno);
-    if (is_int)
+    if (!is_int && !is_hw) {
+        has_error_code = exception_has_error_code(intno);
+    }
+    if (is_int) {
         old_eip = next_eip;
-    else
+    } else {
         old_eip = env->eip;
+    }
 
     dt = &env->idt;
-    if (intno * 8 + 7 > dt->limit)
+    if (intno * 8 + 7 > dt->limit) {
         raise_exception_err(EXCP0D_GPF, intno * 8 + 2);
+    }
     ptr = dt->base + intno * 8;
     e1 = ldl_kernel(ptr);
     e2 = ldl_kernel(ptr + 4);
     /* check gate type */
     type = (e2 >> DESC_TYPE_SHIFT) & 0x1f;
-    switch(type) {
+    switch (type) {
     case 5: /* task gate */
         /* must do that check here to return the correct error code */
-        if (!(e2 & DESC_P_MASK))
+        if (!(e2 & DESC_P_MASK)) {
             raise_exception_err(EXCP0B_NOSEG, intno * 8 + 2);
+        }
         switch_tss(intno * 8, e1, e2, SWITCH_TSS_CALL, old_eip);
         if (has_error_code) {
             int type;
             uint32_t mask;
+
             /* push the error code */
             type = (env->tr.flags >> DESC_TYPE_SHIFT) & 0xf;
             shift = type >> 3;
-            if (env->segs[R_SS].flags & DESC_B_MASK)
+            if (env->segs[R_SS].flags & DESC_B_MASK) {
                 mask = 0xffffffff;
-            else
+            } else {
                 mask = 0xffff;
+            }
             esp = (ESP - (2 << shift)) & mask;
             ssp = env->segs[R_SS].base + esp;
-            if (shift)
+            if (shift) {
                 stl_kernel(ssp, error_code);
-            else
+            } else {
                 stw_kernel(ssp, error_code);
+            }
             SET_ESP(esp, mask);
         }
         return;
@@ -819,50 +883,63 @@ static void do_interrupt_protected(int intno, int is_int, int error_code,
     dpl = (e2 >> DESC_DPL_SHIFT) & 3;
     cpl = env->hflags & HF_CPL_MASK;
     /* check privilege if software int */
-    if (is_int && dpl < cpl)
+    if (is_int && dpl < cpl) {
         raise_exception_err(EXCP0D_GPF, intno * 8 + 2);
+    }
     /* check valid bit */
-    if (!(e2 & DESC_P_MASK))
+    if (!(e2 & DESC_P_MASK)) {
         raise_exception_err(EXCP0B_NOSEG, intno * 8 + 2);
+    }
     selector = e1 >> 16;
     offset = (e2 & 0xffff0000) | (e1 & 0x0000ffff);
-    if ((selector & 0xfffc) == 0)
+    if ((selector & 0xfffc) == 0) {
         raise_exception_err(EXCP0D_GPF, 0);
-
-    if (load_segment(&e1, &e2, selector) != 0)
+    }
+    if (load_segment(&e1, &e2, selector) != 0) {
         raise_exception_err(EXCP0D_GPF, selector & 0xfffc);
-    if (!(e2 & DESC_S_MASK) || !(e2 & (DESC_CS_MASK)))
+    }
+    if (!(e2 & DESC_S_MASK) || !(e2 & (DESC_CS_MASK))) {
         raise_exception_err(EXCP0D_GPF, selector & 0xfffc);
+    }
     dpl = (e2 >> DESC_DPL_SHIFT) & 3;
-    if (dpl > cpl)
+    if (dpl > cpl) {
         raise_exception_err(EXCP0D_GPF, selector & 0xfffc);
-    if (!(e2 & DESC_P_MASK))
+    }
+    if (!(e2 & DESC_P_MASK)) {
         raise_exception_err(EXCP0B_NOSEG, selector & 0xfffc);
+    }
     if (!(e2 & DESC_C_MASK) && dpl < cpl) {
         /* to inner privilege */
         get_ss_esp_from_tss(&ss, &esp, dpl);
-        if ((ss & 0xfffc) == 0)
+        if ((ss & 0xfffc) == 0) {
             raise_exception_err(EXCP0A_TSS, ss & 0xfffc);
-        if ((ss & 3) != dpl)
+        }
+        if ((ss & 3) != dpl) {
             raise_exception_err(EXCP0A_TSS, ss & 0xfffc);
-        if (load_segment(&ss_e1, &ss_e2, ss) != 0)
+        }
+        if (load_segment(&ss_e1, &ss_e2, ss) != 0) {
             raise_exception_err(EXCP0A_TSS, ss & 0xfffc);
+        }
         ss_dpl = (ss_e2 >> DESC_DPL_SHIFT) & 3;
-        if (ss_dpl != dpl)
+        if (ss_dpl != dpl) {
             raise_exception_err(EXCP0A_TSS, ss & 0xfffc);
+        }
         if (!(ss_e2 & DESC_S_MASK) ||
             (ss_e2 & DESC_CS_MASK) ||
-            !(ss_e2 & DESC_W_MASK))
+            !(ss_e2 & DESC_W_MASK)) {
             raise_exception_err(EXCP0A_TSS, ss & 0xfffc);
-        if (!(ss_e2 & DESC_P_MASK))
+        }
+        if (!(ss_e2 & DESC_P_MASK)) {
             raise_exception_err(EXCP0A_TSS, ss & 0xfffc);
+        }
         new_stack = 1;
         sp_mask = get_sp_mask(ss_e2);
         ssp = get_seg_base(ss_e1, ss_e2);
     } else if ((e2 & DESC_C_MASK) || dpl == cpl) {
         /* to same privilege */
-        if (env->eflags & VM_MASK)
+        if (env->eflags & VM_MASK) {
             raise_exception_err(EXCP0D_GPF, selector & 0xfffc);
+        }
         new_stack = 0;
         sp_mask = get_sp_mask(env->segs[R_SS].flags);
         ssp = env->segs[R_SS].base;
@@ -881,8 +958,9 @@ static void do_interrupt_protected(int intno, int is_int, int error_code,
 #if 0
     /* XXX: check that enough room is available */
     push_size = 6 + (new_stack << 2) + (has_error_code << 1);
-    if (env->eflags & VM_MASK)
+    if (env->eflags & VM_MASK) {
         push_size += 8;
+    }
     push_size <<= shift;
 #endif
     if (shift == 1) {
@@ -951,17 +1029,17 @@ static void do_interrupt_protected(int intno, int is_int, int error_code,
 
 #ifdef TARGET_X86_64
 
-#define PUSHQ(sp, val)\
-{\
-    sp -= 8;\
-    stq_kernel(sp, (val));\
-}
+#define PUSHQ(sp, val)                          \
+    {                                           \
+        sp -= 8;                                \
+        stq_kernel(sp, (val));                  \
+    }
 
-#define POPQ(sp, val)\
-{\
-    val = ldq_kernel(sp);\
-    sp += 8;\
-}
+#define POPQ(sp, val)                           \
+    {                                           \
+        val = ldq_kernel(sp);                   \
+        sp += 8;                                \
+    }
 
 static inline target_ulong get_rsp_from_tss(int level)
 {
@@ -972,11 +1050,13 @@ static inline target_ulong get_rsp_from_tss(int level)
            env->tr.base, env->tr.limit);
 #endif
 
-    if (!(env->tr.flags & DESC_P_MASK))
+    if (!(env->tr.flags & DESC_P_MASK)) {
         cpu_abort(env, "invalid tss");
+    }
     index = 8 * level + 4;
-    if ((index + 7) > env->tr.limit)
+    if ((index + 7) > env->tr.limit) {
         raise_exception_err(EXCP0A_TSS, env->tr.selector & 0xfffc);
+    }
     return ldq_kernel(env->tr.base + index);
 }
 
@@ -992,23 +1072,26 @@ static void do_interrupt64(int intno, int is_int, int error_code,
     target_ulong old_eip, esp, offset;
 
     has_error_code = 0;
-    if (!is_int && !is_hw)
-        has_error_code = exeption_has_error_code(intno);
-    if (is_int)
+    if (!is_int && !is_hw) {
+        has_error_code = exception_has_error_code(intno);
+    }
+    if (is_int) {
         old_eip = next_eip;
-    else
+    } else {
         old_eip = env->eip;
+    }
 
     dt = &env->idt;
-    if (intno * 16 + 15 > dt->limit)
+    if (intno * 16 + 15 > dt->limit) {
         raise_exception_err(EXCP0D_GPF, intno * 16 + 2);
+    }
     ptr = dt->base + intno * 16;
     e1 = ldl_kernel(ptr);
     e2 = ldl_kernel(ptr + 4);
     e3 = ldl_kernel(ptr + 8);
     /* check gate type */
     type = (e2 >> DESC_TYPE_SHIFT) & 0x1f;
-    switch(type) {
+    switch (type) {
     case 14: /* 386 interrupt gate */
     case 15: /* 386 trap gate */
         break;
@@ -1019,46 +1102,57 @@ static void do_interrupt64(int intno, int is_int, int error_code,
     dpl = (e2 >> DESC_DPL_SHIFT) & 3;
     cpl = env->hflags & HF_CPL_MASK;
     /* check privilege if software int */
-    if (is_int && dpl < cpl)
+    if (is_int && dpl < cpl) {
         raise_exception_err(EXCP0D_GPF, intno * 16 + 2);
+    }
     /* check valid bit */
-    if (!(e2 & DESC_P_MASK))
+    if (!(e2 & DESC_P_MASK)) {
         raise_exception_err(EXCP0B_NOSEG, intno * 16 + 2);
+    }
     selector = e1 >> 16;
     offset = ((target_ulong)e3 << 32) | (e2 & 0xffff0000) | (e1 & 0x0000ffff);
     ist = e2 & 7;
-    if ((selector & 0xfffc) == 0)
+    if ((selector & 0xfffc) == 0) {
         raise_exception_err(EXCP0D_GPF, 0);
+    }
 
-    if (load_segment(&e1, &e2, selector) != 0)
+    if (load_segment(&e1, &e2, selector) != 0) {
         raise_exception_err(EXCP0D_GPF, selector & 0xfffc);
-    if (!(e2 & DESC_S_MASK) || !(e2 & (DESC_CS_MASK)))
+    }
+    if (!(e2 & DESC_S_MASK) || !(e2 & (DESC_CS_MASK))) {
         raise_exception_err(EXCP0D_GPF, selector & 0xfffc);
+    }
     dpl = (e2 >> DESC_DPL_SHIFT) & 3;
-    if (dpl > cpl)
+    if (dpl > cpl) {
         raise_exception_err(EXCP0D_GPF, selector & 0xfffc);
-    if (!(e2 & DESC_P_MASK))
+    }
+    if (!(e2 & DESC_P_MASK)) {
         raise_exception_err(EXCP0B_NOSEG, selector & 0xfffc);
-    if (!(e2 & DESC_L_MASK) || (e2 & DESC_B_MASK))
+    }
+    if (!(e2 & DESC_L_MASK) || (e2 & DESC_B_MASK)) {
         raise_exception_err(EXCP0D_GPF, selector & 0xfffc);
+    }
     if ((!(e2 & DESC_C_MASK) && dpl < cpl) || ist != 0) {
         /* to inner privilege */
-        if (ist != 0)
+        if (ist != 0) {
             esp = get_rsp_from_tss(ist + 3);
-        else
+        } else {
             esp = get_rsp_from_tss(dpl);
+        }
         esp &= ~0xfLL; /* align stack */
         ss = 0;
         new_stack = 1;
     } else if ((e2 & DESC_C_MASK) || dpl == cpl) {
         /* to same privilege */
-        if (env->eflags & VM_MASK)
+        if (env->eflags & VM_MASK) {
             raise_exception_err(EXCP0D_GPF, selector & 0xfffc);
+        }
         new_stack = 0;
-        if (ist != 0)
+        if (ist != 0) {
             esp = get_rsp_from_tss(ist + 3);
-        else
+        } else {
             esp = ESP;
+        }
         esp &= ~0xfLL; /* align stack */
         dpl = cpl;
     } else {
@@ -1128,7 +1222,8 @@ void helper_syscall(int next_eip_addend)
                            0, 0xffffffff,
                                DESC_G_MASK | DESC_P_MASK |
                                DESC_S_MASK |
-                               DESC_CS_MASK | DESC_R_MASK | DESC_A_MASK | DESC_L_MASK);
+                               DESC_CS_MASK | DESC_R_MASK | DESC_A_MASK |
+                               DESC_L_MASK);
         cpu_x86_load_seg_cache(env, R_SS, (selector + 8) & 0xfffc,
                                0, 0xffffffff,
                                DESC_G_MASK | DESC_B_MASK | DESC_P_MASK |
@@ -1136,10 +1231,11 @@ void helper_syscall(int next_eip_addend)
                                DESC_W_MASK | DESC_A_MASK);
         env->eflags &= ~env->fmask;
         load_eflags(env->eflags, 0);
-        if (code64)
+        if (code64) {
             env->eip = env->lstar;
-        else
+        } else {
             env->eip = env->cstar;
+        }
     } else {
         ECX = (uint32_t)(env->eip + next_eip_addend);
 
@@ -1227,21 +1323,23 @@ static void do_interrupt_real(int intno, int is_int, int error_code,
     uint32_t offset, esp;
     uint32_t old_cs, old_eip;
 
-    /* real mode (simpler !) */
+    /* real mode (simpler!) */
     dt = &env->idt;
-    if (intno * 4 + 3 > dt->limit)
+    if (intno * 4 + 3 > dt->limit) {
         raise_exception_err(EXCP0D_GPF, intno * 8 + 2);
+    }
     ptr = dt->base + intno * 4;
     offset = lduw_kernel(ptr);
     selector = lduw_kernel(ptr + 2);
     esp = ESP;
     ssp = env->segs[R_SS].base;
-    if (is_int)
+    if (is_int) {
         old_eip = next_eip;
-    else
+    } else {
         old_eip = env->eip;
+    }
     old_cs = env->segs[R_CS].selector;
-    /* XXX: use SS segment size ? */
+    /* XXX: use SS segment size? */
     PUSHW(ssp, esp, 0xffff, compute_eflags());
     PUSHW(ssp, esp, 0xffff, old_cs);
     PUSHW(ssp, esp, 0xffff, old_eip);
@@ -1276,34 +1374,43 @@ static void do_interrupt_user(int intno, int is_int, int error_code,
     dpl = (e2 >> DESC_DPL_SHIFT) & 3;
     cpl = env->hflags & HF_CPL_MASK;
     /* check privilege if software int */
-    if (is_int && dpl < cpl)
+    if (is_int && dpl < cpl) {
         raise_exception_err(EXCP0D_GPF, (intno << shift) + 2);
+    }
 
     /* Since we emulate only user space, we cannot do more than
        exiting the emulation with the suitable exception and error
        code */
-    if (is_int)
+    if (is_int) {
         EIP = next_eip;
+    }
 }
 
 #else
 
 static void handle_even_inj(int intno, int is_int, int error_code,
-		int is_hw, int rm)
+                            int is_hw, int rm)
 {
-    uint32_t event_inj = ldl_phys(env->vm_vmcb + offsetof(struct vmcb, control.event_inj));
+    uint32_t event_inj = ldl_phys(env->vm_vmcb + offsetof(struct vmcb,
+                                                          control.event_inj));
+
     if (!(event_inj & SVM_EVTINJ_VALID)) {
-	    int type;
-	    if (is_int)
-		    type = SVM_EVTINJ_TYPE_SOFT;
-	    else
-		    type = SVM_EVTINJ_TYPE_EXEPT;
-	    event_inj = intno | type | SVM_EVTINJ_VALID;
-	    if (!rm && exeption_has_error_code(intno)) {
-		    event_inj |= SVM_EVTINJ_VALID_ERR;
-		    stl_phys(env->vm_vmcb + offsetof(struct vmcb, control.event_inj_err), error_code);
-	    }
-	    stl_phys(env->vm_vmcb + offsetof(struct vmcb, control.event_inj), event_inj);
+        int type;
+
+        if (is_int) {
+            type = SVM_EVTINJ_TYPE_SOFT;
+        } else {
+            type = SVM_EVTINJ_TYPE_EXEPT;
+        }
+        event_inj = intno | type | SVM_EVTINJ_VALID;
+        if (!rm && exception_has_error_code(intno)) {
+            event_inj |= SVM_EVTINJ_VALID_ERR;
+            stl_phys(env->vm_vmcb + offsetof(struct vmcb,
+                                             control.event_inj_err),
+                     error_code);
+        }
+        stl_phys(env->vm_vmcb + offsetof(struct vmcb, control.event_inj),
+                 event_inj);
     }
 }
 #endif
@@ -1319,12 +1426,14 @@ static void do_interrupt_all(int intno, int is_int, int error_code,
     if (qemu_loglevel_mask(CPU_LOG_INT)) {
         if ((env->cr[0] & CR0_PE_MASK)) {
             static int count;
-            qemu_log("%6d: v=%02x e=%04x i=%d cpl=%d IP=%04x:" TARGET_FMT_lx " pc=" TARGET_FMT_lx " SP=%04x:" TARGET_FMT_lx,
-                    count, intno, error_code, is_int,
-                    env->hflags & HF_CPL_MASK,
-                    env->segs[R_CS].selector, EIP,
-                    (int)env->segs[R_CS].base + EIP,
-                    env->segs[R_SS].selector, ESP);
+
+            qemu_log("%6d: v=%02x e=%04x i=%d cpl=%d IP=%04x:" TARGET_FMT_lx
+                     " pc=" TARGET_FMT_lx " SP=%04x:" TARGET_FMT_lx,
+                     count, intno, error_code, is_int,
+                     env->hflags & HF_CPL_MASK,
+                     env->segs[R_CS].selector, EIP,
+                     (int)env->segs[R_CS].base + EIP,
+                     env->segs[R_SS].selector, ESP);
             if (intno == 0x0e) {
                 qemu_log(" CR2=" TARGET_FMT_lx, env->cr[2]);
             } else {
@@ -1336,9 +1445,10 @@ static void do_interrupt_all(int intno, int is_int, int error_code,
             {
                 int i;
                 target_ulong ptr;
+
                 qemu_log("       code=");
                 ptr = env->segs[R_CS].base + env->eip;
-                for(i = 0; i < 16; i++) {
+                for (i = 0; i < 16; i++) {
                     qemu_log(" %02x", ldub(ptr + i));
                 }
                 qemu_log("\n");
@@ -1349,8 +1459,9 @@ static void do_interrupt_all(int intno, int is_int, int error_code,
     }
     if (env->cr[0] & CR0_PE_MASK) {
 #if !defined(CONFIG_USER_ONLY)
-        if (env->hflags & HF_SVMI_MASK)
+        if (env->hflags & HF_SVMI_MASK) {
             handle_even_inj(intno, is_int, error_code, is_hw, 0);
+        }
 #endif
 #ifdef TARGET_X86_64
         if (env->hflags & HF_LMA_MASK) {
@@ -1362,16 +1473,21 @@ static void do_interrupt_all(int intno, int is_int, int error_code,
         }
     } else {
 #if !defined(CONFIG_USER_ONLY)
-        if (env->hflags & HF_SVMI_MASK)
+        if (env->hflags & HF_SVMI_MASK) {
             handle_even_inj(intno, is_int, error_code, is_hw, 1);
+        }
 #endif
         do_interrupt_real(intno, is_int, error_code, next_eip);
     }
 
 #if !defined(CONFIG_USER_ONLY)
     if (env->hflags & HF_SVMI_MASK) {
-	    uint32_t event_inj = ldl_phys(env->vm_vmcb + offsetof(struct vmcb, control.event_inj));
-	    stl_phys(env->vm_vmcb + offsetof(struct vmcb, control.event_inj), event_inj & ~SVM_EVTINJ_VALID);
+        uint32_t event_inj = ldl_phys(env->vm_vmcb +
+                                      offsetof(struct vmcb,
+                                               control.event_inj));
+
+        stl_phys(env->vm_vmcb + offsetof(struct vmcb, control.event_inj),
+                 event_inj & ~SVM_EVTINJ_VALID);
     }
 #endif
 }
@@ -1437,8 +1553,9 @@ static int check_exception(int intno, int *error_code)
 
 #if !defined(CONFIG_USER_ONLY)
     if (env->old_exception == EXCP08_DBLE) {
-        if (env->hflags & HF_SVMI_MASK)
+        if (env->hflags & HF_SVMI_MASK) {
             helper_vmexit(SVM_EXIT_SHUTDOWN, 0); /* does not return */
+        }
 
         qemu_log_mask(CPU_LOG_RESET, "Triple fault\n");
 
@@ -1455,8 +1572,9 @@ static int check_exception(int intno, int *error_code)
     }
 
     if (second_contributory || (intno == EXCP0E_PAGE) ||
-        (intno == EXCP08_DBLE))
+        (intno == EXCP08_DBLE)) {
         env->old_exception = intno;
+    }
 
     return intno;
 }
@@ -1471,7 +1589,8 @@ static void QEMU_NORETURN raise_interrupt(int intno, int is_int, int error_code,
                                           int next_eip_addend)
 {
     if (!is_int) {
-        helper_svm_check_intercept_param(SVM_EXIT_EXCP_BASE + intno, error_code);
+        helper_svm_check_intercept_param(SVM_EXIT_EXCP_BASE + intno,
+                                         error_code);
         intno = check_exception(intno, &error_code);
     } else {
         helper_svm_check_intercept_param(SVM_EXIT_SWINT, 0);
@@ -1548,7 +1667,7 @@ void do_smm_enter(CPUX86State *env1)
     sm_state = env->smbase + 0x8000;
 
 #ifdef TARGET_X86_64
-    for(i = 0; i < 6; i++) {
+    for (i = 0; i < 6; i++) {
         dt = &env->segs[i];
         offset = 0x7e00 + i * 16;
         stw_phys(sm_state + offset, dt->selector);
@@ -1583,8 +1702,9 @@ void do_smm_enter(CPUX86State *env1)
     stq_phys(sm_state + 0x7fd0, EBP);
     stq_phys(sm_state + 0x7fc8, ESI);
     stq_phys(sm_state + 0x7fc0, EDI);
-    for(i = 8; i < 16; i++)
+    for (i = 8; i < 16; i++) {
         stq_phys(sm_state + 0x7ff8 - i * 8, env->regs[i]);
+    }
     stq_phys(sm_state + 0x7f78, env->eip);
     stl_phys(sm_state + 0x7f70, compute_eflags());
     stl_phys(sm_state + 0x7f68, env->dr[6]);
@@ -1628,12 +1748,13 @@ void do_smm_enter(CPUX86State *env1)
     stl_phys(sm_state + 0x7f58, env->idt.base);
     stl_phys(sm_state + 0x7f54, env->idt.limit);
 
-    for(i = 0; i < 6; i++) {
+    for (i = 0; i < 6; i++) {
         dt = &env->segs[i];
-        if (i < 3)
+        if (i < 3) {
             offset = 0x7f84 + i * 12;
-        else
+        } else {
             offset = 0x7f2c + (i - 3) * 12;
+        }
         stl_phys(sm_state + 0x7fa8 + i * 4, dt->selector);
         stl_phys(sm_state + offset + 8, dt->base);
         stl_phys(sm_state + offset + 4, dt->limit);
@@ -1660,7 +1781,8 @@ void do_smm_enter(CPUX86State *env1)
     cpu_x86_load_seg_cache(env, R_GS, 0, 0, 0xffffffff, 0);
 
     cpu_x86_update_cr0(env,
-                       env->cr[0] & ~(CR0_PE_MASK | CR0_EM_MASK | CR0_TS_MASK | CR0_PG_MASK));
+                       env->cr[0] & ~(CR0_PE_MASK | CR0_EM_MASK | CR0_TS_MASK |
+                                      CR0_PG_MASK));
     cpu_x86_update_cr4(env, 0);
     env->dr[7] = 0x00000400;
     CC_OP = CC_OP_EFLAGS;
@@ -1677,13 +1799,14 @@ void helper_rsm(void)
 #ifdef TARGET_X86_64
     cpu_load_efer(env, ldq_phys(sm_state + 0x7ed0));
 
-    for(i = 0; i < 6; i++) {
+    for (i = 0; i < 6; i++) {
         offset = 0x7e00 + i * 16;
         cpu_x86_load_seg_cache(env, i,
                                lduw_phys(sm_state + offset),
                                ldq_phys(sm_state + offset + 8),
                                ldl_phys(sm_state + offset + 4),
-                               (lduw_phys(sm_state + offset + 2) & 0xf0ff) << 8);
+                               (lduw_phys(sm_state + offset + 2) &
+                                0xf0ff) << 8);
     }
 
     env->gdt.base = ldq_phys(sm_state + 0x7e68);
@@ -1710,8 +1833,9 @@ void helper_rsm(void)
     EBP = ldq_phys(sm_state + 0x7fd0);
     ESI = ldq_phys(sm_state + 0x7fc8);
     EDI = ldq_phys(sm_state + 0x7fc0);
-    for(i = 8; i < 16; i++)
+    for (i = 8; i < 16; i++) {
         env->regs[i] = ldq_phys(sm_state + 0x7ff8 - i * 8);
+    }
     env->eip = ldq_phys(sm_state + 0x7f78);
     load_eflags(ldl_phys(sm_state + 0x7f70),
                 ~(CC_O | CC_S | CC_Z | CC_A | CC_P | CC_C | DF_MASK));
@@ -1759,11 +1883,12 @@ void helper_rsm(void)
     env->idt.base = ldl_phys(sm_state + 0x7f58);
     env->idt.limit = ldl_phys(sm_state + 0x7f54);
 
-    for(i = 0; i < 6; i++) {
-        if (i < 3)
+    for (i = 0; i < 6; i++) {
+        if (i < 3) {
             offset = 0x7f84 + i * 12;
-        else
+        } else {
             offset = 0x7f2c + (i - 3) * 12;
+        }
         cpu_x86_load_seg_cache(env, i,
                                ldl_phys(sm_state + 0x7fa8 + i * 4) & 0xffff,
                                ldl_phys(sm_state + offset + 8),
@@ -1800,8 +1925,9 @@ void helper_divb_AL(target_ulong t0)
         raise_exception(EXCP00_DIVZ);
     }
     q = (num / den);
-    if (q > 0xff)
+    if (q > 0xff) {
         raise_exception(EXCP00_DIVZ);
+    }
     q &= 0xff;
     r = (num % den) & 0xff;
     EAX = (EAX & ~0xffff) | (r << 8) | q;
@@ -1817,8 +1943,9 @@ void helper_idivb_AL(target_ulong t0)
         raise_exception(EXCP00_DIVZ);
     }
     q = (num / den);
-    if (q != (int8_t)q)
+    if (q != (int8_t)q) {
         raise_exception(EXCP00_DIVZ);
+    }
     q &= 0xff;
     r = (num % den) & 0xff;
     EAX = (EAX & ~0xffff) | (r << 8) | q;
@@ -1834,8 +1961,9 @@ void helper_divw_AX(target_ulong t0)
         raise_exception(EXCP00_DIVZ);
     }
     q = (num / den);
-    if (q > 0xffff)
+    if (q > 0xffff) {
         raise_exception(EXCP00_DIVZ);
+    }
     q &= 0xffff;
     r = (num % den) & 0xffff;
     EAX = (EAX & ~0xffff) | q;
@@ -1852,8 +1980,9 @@ void helper_idivw_AX(target_ulong t0)
         raise_exception(EXCP00_DIVZ);
     }
     q = (num / den);
-    if (q != (int16_t)q)
+    if (q != (int16_t)q) {
         raise_exception(EXCP00_DIVZ);
+    }
     q &= 0xffff;
     r = (num % den) & 0xffff;
     EAX = (EAX & ~0xffff) | q;
@@ -1872,8 +2001,9 @@ void helper_divl_EAX(target_ulong t0)
     }
     q = (num / den);
     r = (num % den);
-    if (q > 0xffffffff)
+    if (q > 0xffffffff) {
         raise_exception(EXCP00_DIVZ);
+    }
     EAX = (uint32_t)q;
     EDX = (uint32_t)r;
 }
@@ -1890,8 +2020,9 @@ void helper_idivl_EAX(target_ulong t0)
     }
     q = (num / den);
     r = (num % den);
-    if (q != (int32_t)q)
+    if (q != (int32_t)q) {
         raise_exception(EXCP00_DIVZ);
+    }
     EAX = (uint32_t)q;
     EDX = (uint32_t)r;
 }
@@ -1902,6 +2033,7 @@ void helper_idivl_EAX(target_ulong t0)
 void helper_aam(int base)
 {
     int al, ah;
+
     al = EAX & 0xff;
     ah = al / base;
     al = al % base;
@@ -1912,6 +2044,7 @@ void helper_aam(int base)
 void helper_aad(int base)
 {
     int al, ah;
+
     al = EAX & 0xff;
     ah = (EAX >> 8) & 0xff;
     al = ((ah * base) + al) & 0xff;
@@ -1931,7 +2064,7 @@ void helper_aaa(void)
     ah = (EAX >> 8) & 0xff;
 
     icarry = (al > 0xf9);
-    if (((al & 0x0f) > 9 ) || af) {
+    if (((al & 0x0f) > 9) || af) {
         al = (al + 6) & 0x0f;
         ah = (ah + 1 + icarry) & 0xff;
         eflags |= CC_C | CC_A;
@@ -1955,7 +2088,7 @@ void helper_aas(void)
     ah = (EAX >> 8) & 0xff;
 
     icarry = (al < 6);
-    if (((al & 0x0f) > 9 ) || af) {
+    if (((al & 0x0f) > 9) || af) {
         al = (al - 6) & 0x0f;
         ah = (ah - 1 - icarry) & 0xff;
         eflags |= CC_C | CC_A;
@@ -1978,7 +2111,7 @@ void helper_daa(void)
     old_al = al = EAX & 0xff;
 
     eflags = 0;
-    if (((al & 0x0f) > 9 ) || af) {
+    if (((al & 0x0f) > 9) || af) {
         al = (al + 6) & 0xff;
         eflags |= CC_A;
     }
@@ -2006,10 +2139,11 @@ void helper_das(void)
 
     eflags = 0;
     al1 = al;
-    if (((al & 0x0f) > 9 ) || af) {
+    if (((al & 0x0f) > 9) || af) {
         eflags |= CC_A;
-        if (al < 6 || cf)
+        if (al < 6 || cf) {
             eflags |= CC_C;
+        }
         al = (al - 6) & 0xff;
     }
     if ((al1 > 0x99) || cf) {
@@ -2027,6 +2161,7 @@ void helper_das(void)
 void helper_into(int next_eip_addend)
 {
     int eflags;
+
     eflags = helper_cc_compute_all(CC_OP);
     if (eflags & CC_O) {
         raise_interrupt(EXCP04_INTO, 1, 0, next_eip_addend);
@@ -2045,7 +2180,7 @@ void helper_cmpxchg8b(target_ulong a0)
         eflags |= CC_Z;
     } else {
         /* always do the store */
-        stq(a0, d); 
+        stq(a0, d);
         EDX = (uint32_t)(d >> 32);
         EAX = (uint32_t)d;
         eflags &= ~CC_Z;
@@ -2059,8 +2194,9 @@ void helper_cmpxchg16b(target_ulong a0)
     uint64_t d0, d1;
     int eflags;
 
-    if ((a0 & 0xf) != 0)
+    if ((a0 & 0xf) != 0) {
         raise_exception(EXCP0D_GPF);
+    }
     eflags = helper_cc_compute_all(CC_OP);
     d0 = ldq(a0);
     d1 = ldq(a0 + 8);
@@ -2070,8 +2206,8 @@ void helper_cmpxchg16b(target_ulong a0)
         eflags |= CC_Z;
     } else {
         /* always do the store */
-        stq(a0, d0); 
-        stq(a0 + 8, d1); 
+        stq(a0, d0);
+        stq(a0 + 8, d1);
         EDX = d1;
         EAX = d0;
         eflags &= ~CC_Z;
@@ -2138,6 +2274,7 @@ void helper_enter_level(int level, int data32, target_ulong t1)
 void helper_enter64_level(int level, int data64, target_ulong t1)
 {
     target_ulong esp, ebp;
+
     ebp = EBP;
     esp = ESP;
 
@@ -2178,28 +2315,35 @@ void helper_lldt(int selector)
         env->ldt.base = 0;
         env->ldt.limit = 0;
     } else {
-        if (selector & 0x4)
+        if (selector & 0x4) {
             raise_exception_err(EXCP0D_GPF, selector & 0xfffc);
+        }
         dt = &env->gdt;
         index = selector & ~7;
 #ifdef TARGET_X86_64
-        if (env->hflags & HF_LMA_MASK)
+        if (env->hflags & HF_LMA_MASK) {
             entry_limit = 15;
-        else
+        } else
 #endif
+        {
             entry_limit = 7;
-        if ((index + entry_limit) > dt->limit)
+        }
+        if ((index + entry_limit) > dt->limit) {
             raise_exception_err(EXCP0D_GPF, selector & 0xfffc);
+        }
         ptr = dt->base + index;
         e1 = ldl_kernel(ptr);
         e2 = ldl_kernel(ptr + 4);
-        if ((e2 & DESC_S_MASK) || ((e2 >> DESC_TYPE_SHIFT) & 0xf) != 2)
+        if ((e2 & DESC_S_MASK) || ((e2 >> DESC_TYPE_SHIFT) & 0xf) != 2) {
             raise_exception_err(EXCP0D_GPF, selector & 0xfffc);
-        if (!(e2 & DESC_P_MASK))
+        }
+        if (!(e2 & DESC_P_MASK)) {
             raise_exception_err(EXCP0B_NOSEG, selector & 0xfffc);
+        }
 #ifdef TARGET_X86_64
         if (env->hflags & HF_LMA_MASK) {
             uint32_t e3;
+
             e3 = ldl_kernel(ptr + 8);
             load_seg_cache_raw_dt(&env->ldt, e1, e2);
             env->ldt.base |= (target_ulong)e3 << 32;
@@ -2226,34 +2370,42 @@ void helper_ltr(int selector)
         env->tr.limit = 0;
         env->tr.flags = 0;
     } else {
-        if (selector & 0x4)
+        if (selector & 0x4) {
             raise_exception_err(EXCP0D_GPF, selector & 0xfffc);
+        }
         dt = &env->gdt;
         index = selector & ~7;
 #ifdef TARGET_X86_64
-        if (env->hflags & HF_LMA_MASK)
+        if (env->hflags & HF_LMA_MASK) {
             entry_limit = 15;
-        else
+        } else
 #endif
+        {
             entry_limit = 7;
-        if ((index + entry_limit) > dt->limit)
+        }
+        if ((index + entry_limit) > dt->limit) {
             raise_exception_err(EXCP0D_GPF, selector & 0xfffc);
+        }
         ptr = dt->base + index;
         e1 = ldl_kernel(ptr);
         e2 = ldl_kernel(ptr + 4);
         type = (e2 >> DESC_TYPE_SHIFT) & 0xf;
         if ((e2 & DESC_S_MASK) ||
-            (type != 1 && type != 9))
+            (type != 1 && type != 9)) {
             raise_exception_err(EXCP0D_GPF, selector & 0xfffc);
-        if (!(e2 & DESC_P_MASK))
+        }
+        if (!(e2 & DESC_P_MASK)) {
             raise_exception_err(EXCP0B_NOSEG, selector & 0xfffc);
+        }
 #ifdef TARGET_X86_64
         if (env->hflags & HF_LMA_MASK) {
             uint32_t e3, e4;
+
             e3 = ldl_kernel(ptr + 8);
             e4 = ldl_kernel(ptr + 12);
-            if ((e4 >> DESC_TYPE_SHIFT) & 0xf)
+            if ((e4 >> DESC_TYPE_SHIFT) & 0xf) {
                 raise_exception_err(EXCP0D_GPF, selector & 0xfffc);
+            }
             load_seg_cache_raw_dt(&env->tr, e1, e2);
             env->tr.base |= (target_ulong)e3 << 32;
         } else
@@ -2284,49 +2436,58 @@ void helper_load_seg(int seg_reg, int selector)
 #ifdef TARGET_X86_64
             && (!(env->hflags & HF_CS64_MASK) || cpl == 3)
 #endif
-            )
+            ) {
             raise_exception_err(EXCP0D_GPF, 0);
+        }
         cpu_x86_load_seg_cache(env, seg_reg, selector, 0, 0, 0);
     } else {
 
-        if (selector & 0x4)
+        if (selector & 0x4) {
             dt = &env->ldt;
-        else
+        } else {
             dt = &env->gdt;
+        }
         index = selector & ~7;
-        if ((index + 7) > dt->limit)
+        if ((index + 7) > dt->limit) {
             raise_exception_err(EXCP0D_GPF, selector & 0xfffc);
+        }
         ptr = dt->base + index;
         e1 = ldl_kernel(ptr);
         e2 = ldl_kernel(ptr + 4);
 
-        if (!(e2 & DESC_S_MASK))
+        if (!(e2 & DESC_S_MASK)) {
             raise_exception_err(EXCP0D_GPF, selector & 0xfffc);
+        }
         rpl = selector & 3;
         dpl = (e2 >> DESC_DPL_SHIFT) & 3;
         if (seg_reg == R_SS) {
             /* must be writable segment */
-            if ((e2 & DESC_CS_MASK) || !(e2 & DESC_W_MASK))
+            if ((e2 & DESC_CS_MASK) || !(e2 & DESC_W_MASK)) {
                 raise_exception_err(EXCP0D_GPF, selector & 0xfffc);
-            if (rpl != cpl || dpl != cpl)
+            }
+            if (rpl != cpl || dpl != cpl) {
                 raise_exception_err(EXCP0D_GPF, selector & 0xfffc);
+            }
         } else {
             /* must be readable segment */
-            if ((e2 & (DESC_CS_MASK | DESC_R_MASK)) == DESC_CS_MASK)
+            if ((e2 & (DESC_CS_MASK | DESC_R_MASK)) == DESC_CS_MASK) {
                 raise_exception_err(EXCP0D_GPF, selector & 0xfffc);
+            }
 
             if (!(e2 & DESC_CS_MASK) || !(e2 & DESC_C_MASK)) {
                 /* if not conforming code, test rights */
-                if (dpl < cpl || dpl < rpl)
+                if (dpl < cpl || dpl < rpl) {
                     raise_exception_err(EXCP0D_GPF, selector & 0xfffc);
+                }
             }
         }
 
         if (!(e2 & DESC_P_MASK)) {
-            if (seg_reg == R_SS)
+            if (seg_reg == R_SS) {
                 raise_exception_err(EXCP0C_STACK, selector & 0xfffc);
-            else
+            } else {
                 raise_exception_err(EXCP0B_NOSEG, selector & 0xfffc);
+            }
         }
 
         /* set the access bit if not already set */
@@ -2354,33 +2515,41 @@ void helper_ljmp_protected(int new_cs, target_ulong new_eip,
     uint32_t e1, e2, cpl, dpl, rpl, limit;
     target_ulong next_eip;
 
-    if ((new_cs & 0xfffc) == 0)
+    if ((new_cs & 0xfffc) == 0) {
         raise_exception_err(EXCP0D_GPF, 0);
-    if (load_segment(&e1, &e2, new_cs) != 0)
+    }
+    if (load_segment(&e1, &e2, new_cs) != 0) {
         raise_exception_err(EXCP0D_GPF, new_cs & 0xfffc);
+    }
     cpl = env->hflags & HF_CPL_MASK;
     if (e2 & DESC_S_MASK) {
-        if (!(e2 & DESC_CS_MASK))
+        if (!(e2 & DESC_CS_MASK)) {
             raise_exception_err(EXCP0D_GPF, new_cs & 0xfffc);
+        }
         dpl = (e2 >> DESC_DPL_SHIFT) & 3;
         if (e2 & DESC_C_MASK) {
             /* conforming code segment */
-            if (dpl > cpl)
+            if (dpl > cpl) {
                 raise_exception_err(EXCP0D_GPF, new_cs & 0xfffc);
+            }
         } else {
             /* non conforming code segment */
             rpl = new_cs & 3;
-            if (rpl > cpl)
+            if (rpl > cpl) {
                 raise_exception_err(EXCP0D_GPF, new_cs & 0xfffc);
-            if (dpl != cpl)
+            }
+            if (dpl != cpl) {
                 raise_exception_err(EXCP0D_GPF, new_cs & 0xfffc);
+            }
         }
-        if (!(e2 & DESC_P_MASK))
+        if (!(e2 & DESC_P_MASK)) {
             raise_exception_err(EXCP0B_NOSEG, new_cs & 0xfffc);
+        }
         limit = get_seg_limit(e1, e2);
         if (new_eip > limit &&
-            !(env->hflags & HF_LMA_MASK) && !(e2 & DESC_L_MASK))
+            !(env->hflags & HF_LMA_MASK) && !(e2 & DESC_L_MASK)) {
             raise_exception_err(EXCP0D_GPF, new_cs & 0xfffc);
+        }
         cpu_x86_load_seg_cache(env, R_CS, (new_cs & 0xfffc) | cpl,
                        get_seg_base(e1, e2), limit, e2);
         EIP = new_eip;
@@ -2390,41 +2559,50 @@ void helper_ljmp_protected(int new_cs, target_ulong new_eip,
         rpl = new_cs & 3;
         cpl = env->hflags & HF_CPL_MASK;
         type = (e2 >> DESC_TYPE_SHIFT) & 0xf;
-        switch(type) {
+        switch (type) {
         case 1: /* 286 TSS */
         case 9: /* 386 TSS */
         case 5: /* task gate */
-            if (dpl < cpl || dpl < rpl)
+            if (dpl < cpl || dpl < rpl) {
                 raise_exception_err(EXCP0D_GPF, new_cs & 0xfffc);
+            }
             next_eip = env->eip + next_eip_addend;
             switch_tss(new_cs, e1, e2, SWITCH_TSS_JMP, next_eip);
             CC_OP = CC_OP_EFLAGS;
             break;
         case 4: /* 286 call gate */
         case 12: /* 386 call gate */
-            if ((dpl < cpl) || (dpl < rpl))
+            if ((dpl < cpl) || (dpl < rpl)) {
                 raise_exception_err(EXCP0D_GPF, new_cs & 0xfffc);
-            if (!(e2 & DESC_P_MASK))
+            }
+            if (!(e2 & DESC_P_MASK)) {
                 raise_exception_err(EXCP0B_NOSEG, new_cs & 0xfffc);
+            }
             gate_cs = e1 >> 16;
             new_eip = (e1 & 0xffff);
-            if (type == 12)
+            if (type == 12) {
                 new_eip |= (e2 & 0xffff0000);
-            if (load_segment(&e1, &e2, gate_cs) != 0)
+            }
+            if (load_segment(&e1, &e2, gate_cs) != 0) {
                 raise_exception_err(EXCP0D_GPF, gate_cs & 0xfffc);
+            }
             dpl = (e2 >> DESC_DPL_SHIFT) & 3;
             /* must be code segment */
             if (((e2 & (DESC_S_MASK | DESC_CS_MASK)) !=
-                 (DESC_S_MASK | DESC_CS_MASK)))
+                 (DESC_S_MASK | DESC_CS_MASK))) {
                 raise_exception_err(EXCP0D_GPF, gate_cs & 0xfffc);
+            }
             if (((e2 & DESC_C_MASK) && (dpl > cpl)) ||
-                (!(e2 & DESC_C_MASK) && (dpl != cpl)))
+                (!(e2 & DESC_C_MASK) && (dpl != cpl))) {
                 raise_exception_err(EXCP0D_GPF, gate_cs & 0xfffc);
-            if (!(e2 & DESC_P_MASK))
+            }
+            if (!(e2 & DESC_P_MASK)) {
                 raise_exception_err(EXCP0D_GPF, gate_cs & 0xfffc);
+            }
             limit = get_seg_limit(e1, e2);
-            if (new_eip > limit)
+            if (new_eip > limit) {
                 raise_exception_err(EXCP0D_GPF, 0);
+            }
             cpu_x86_load_seg_cache(env, R_CS, (gate_cs & 0xfffc) | cpl,
                                    get_seg_base(e1, e2), limit, e2);
             EIP = new_eip;
@@ -2463,7 +2641,7 @@ void helper_lcall_real(int new_cs, target_ulong new_eip1,
 }
 
 /* protected mode call */
-void helper_lcall_protected(int new_cs, target_ulong new_eip, 
+void helper_lcall_protected(int new_cs, target_ulong new_eip,
                             int shift, int next_eip_addend)
 {
     int new_stack, i;
@@ -2475,35 +2653,43 @@ void helper_lcall_protected(int new_cs, target_ulong new_eip,
     next_eip = env->eip + next_eip_addend;
     LOG_PCALL("lcall %04x:%08x s=%d\n", new_cs, (uint32_t)new_eip, shift);
     LOG_PCALL_STATE(env);
-    if ((new_cs & 0xfffc) == 0)
+    if ((new_cs & 0xfffc) == 0) {
         raise_exception_err(EXCP0D_GPF, 0);
-    if (load_segment(&e1, &e2, new_cs) != 0)
+    }
+    if (load_segment(&e1, &e2, new_cs) != 0) {
         raise_exception_err(EXCP0D_GPF, new_cs & 0xfffc);
+    }
     cpl = env->hflags & HF_CPL_MASK;
     LOG_PCALL("desc=%08x:%08x\n", e1, e2);
     if (e2 & DESC_S_MASK) {
-        if (!(e2 & DESC_CS_MASK))
+        if (!(e2 & DESC_CS_MASK)) {
             raise_exception_err(EXCP0D_GPF, new_cs & 0xfffc);
+        }
         dpl = (e2 >> DESC_DPL_SHIFT) & 3;
         if (e2 & DESC_C_MASK) {
             /* conforming code segment */
-            if (dpl > cpl)
+            if (dpl > cpl) {
                 raise_exception_err(EXCP0D_GPF, new_cs & 0xfffc);
+            }
         } else {
             /* non conforming code segment */
             rpl = new_cs & 3;
-            if (rpl > cpl)
+            if (rpl > cpl) {
                 raise_exception_err(EXCP0D_GPF, new_cs & 0xfffc);
-            if (dpl != cpl)
+            }
+            if (dpl != cpl) {
                 raise_exception_err(EXCP0D_GPF, new_cs & 0xfffc);
+            }
         }
-        if (!(e2 & DESC_P_MASK))
+        if (!(e2 & DESC_P_MASK)) {
             raise_exception_err(EXCP0B_NOSEG, new_cs & 0xfffc);
+        }
 
 #ifdef TARGET_X86_64
         /* XXX: check 16/32 bit cases in long mode */
         if (shift == 2) {
             target_ulong rsp;
+
             /* 64 bit case */
             rsp = ESP;
             PUSHQ(rsp, env->segs[R_CS].selector);
@@ -2529,8 +2715,9 @@ void helper_lcall_protected(int new_cs, target_ulong new_eip,
             }
 
             limit = get_seg_limit(e1, e2);
-            if (new_eip > limit)
+            if (new_eip > limit) {
                 raise_exception_err(EXCP0D_GPF, new_cs & 0xfffc);
+            }
             /* from this point, not restartable */
             SET_ESP(sp, sp_mask);
             cpu_x86_load_seg_cache(env, R_CS, (new_cs & 0xfffc) | cpl,
@@ -2542,12 +2729,13 @@ void helper_lcall_protected(int new_cs, target_ulong new_eip,
         type = (e2 >> DESC_TYPE_SHIFT) & 0x1f;
         dpl = (e2 >> DESC_DPL_SHIFT) & 3;
         rpl = new_cs & 3;
-        switch(type) {
+        switch (type) {
         case 1: /* available 286 TSS */
         case 9: /* available 386 TSS */
         case 5: /* task gate */
-            if (dpl < cpl || dpl < rpl)
+            if (dpl < cpl || dpl < rpl) {
                 raise_exception_err(EXCP0D_GPF, new_cs & 0xfffc);
+            }
             switch_tss(new_cs, e1, e2, SWITCH_TSS_CALL, next_eip);
             CC_OP = CC_OP_EFLAGS;
             return;
@@ -2560,49 +2748,63 @@ void helper_lcall_protected(int new_cs, target_ulong new_eip,
         }
         shift = type >> 3;
 
-        if (dpl < cpl || dpl < rpl)
+        if (dpl < cpl || dpl < rpl) {
             raise_exception_err(EXCP0D_GPF, new_cs & 0xfffc);
+        }
         /* check valid bit */
-        if (!(e2 & DESC_P_MASK))
+        if (!(e2 & DESC_P_MASK)) {
             raise_exception_err(EXCP0B_NOSEG,  new_cs & 0xfffc);
+        }
         selector = e1 >> 16;
         offset = (e2 & 0xffff0000) | (e1 & 0x0000ffff);
         param_count = e2 & 0x1f;
-        if ((selector & 0xfffc) == 0)
+        if ((selector & 0xfffc) == 0) {
             raise_exception_err(EXCP0D_GPF, 0);
+        }
 
-        if (load_segment(&e1, &e2, selector) != 0)
+        if (load_segment(&e1, &e2, selector) != 0) {
             raise_exception_err(EXCP0D_GPF, selector & 0xfffc);
-        if (!(e2 & DESC_S_MASK) || !(e2 & (DESC_CS_MASK)))
+        }
+        if (!(e2 & DESC_S_MASK) || !(e2 & (DESC_CS_MASK))) {
             raise_exception_err(EXCP0D_GPF, selector & 0xfffc);
+        }
         dpl = (e2 >> DESC_DPL_SHIFT) & 3;
-        if (dpl > cpl)
+        if (dpl > cpl) {
             raise_exception_err(EXCP0D_GPF, selector & 0xfffc);
-        if (!(e2 & DESC_P_MASK))
+        }
+        if (!(e2 & DESC_P_MASK)) {
             raise_exception_err(EXCP0B_NOSEG, selector & 0xfffc);
+        }
 
         if (!(e2 & DESC_C_MASK) && dpl < cpl) {
             /* to inner privilege */
             get_ss_esp_from_tss(&ss, &sp, dpl);
-            LOG_PCALL("new ss:esp=%04x:%08x param_count=%d ESP=" TARGET_FMT_lx "\n",
-                        ss, sp, param_count, ESP);
-            if ((ss & 0xfffc) == 0)
+            LOG_PCALL("new ss:esp=%04x:%08x param_count=%d ESP=" TARGET_FMT_lx
+                      "\n",
+                      ss, sp, param_count, ESP);
+            if ((ss & 0xfffc) == 0) {
                 raise_exception_err(EXCP0A_TSS, ss & 0xfffc);
-            if ((ss & 3) != dpl)
+            }
+            if ((ss & 3) != dpl) {
                 raise_exception_err(EXCP0A_TSS, ss & 0xfffc);
-            if (load_segment(&ss_e1, &ss_e2, ss) != 0)
+            }
+            if (load_segment(&ss_e1, &ss_e2, ss) != 0) {
                 raise_exception_err(EXCP0A_TSS, ss & 0xfffc);
+            }
             ss_dpl = (ss_e2 >> DESC_DPL_SHIFT) & 3;
-            if (ss_dpl != dpl)
+            if (ss_dpl != dpl) {
                 raise_exception_err(EXCP0A_TSS, ss & 0xfffc);
+            }
             if (!(ss_e2 & DESC_S_MASK) ||
                 (ss_e2 & DESC_CS_MASK) ||
-                !(ss_e2 & DESC_W_MASK))
+                !(ss_e2 & DESC_W_MASK)) {
                 raise_exception_err(EXCP0A_TSS, ss & 0xfffc);
-            if (!(ss_e2 & DESC_P_MASK))
+            }
+            if (!(ss_e2 & DESC_P_MASK)) {
                 raise_exception_err(EXCP0A_TSS, ss & 0xfffc);
+            }
 
-            //            push_size = ((param_count * 2) + 8) << shift;
+            /* push_size = ((param_count * 2) + 8) << shift; */
 
             old_sp_mask = get_sp_mask(env->segs[R_SS].flags);
             old_ssp = env->segs[R_SS].base;
@@ -2612,14 +2814,14 @@ void helper_lcall_protected(int new_cs, target_ulong new_eip,
             if (shift) {
                 PUSHL(ssp, sp, sp_mask, env->segs[R_SS].selector);
                 PUSHL(ssp, sp, sp_mask, ESP);
-                for(i = param_count - 1; i >= 0; i--) {
+                for (i = param_count - 1; i >= 0; i--) {
                     val = ldl_kernel(old_ssp + ((ESP + i * 4) & old_sp_mask));
                     PUSHL(ssp, sp, sp_mask, val);
                 }
             } else {
                 PUSHW(ssp, sp, sp_mask, env->segs[R_SS].selector);
                 PUSHW(ssp, sp, sp_mask, ESP);
-                for(i = param_count - 1; i >= 0; i--) {
+                for (i = param_count - 1; i >= 0; i--) {
                     val = lduw_kernel(old_ssp + ((ESP + i * 2) & old_sp_mask));
                     PUSHW(ssp, sp, sp_mask, val);
                 }
@@ -2630,7 +2832,7 @@ void helper_lcall_protected(int new_cs, target_ulong new_eip,
             sp = ESP;
             sp_mask = get_sp_mask(env->segs[R_SS].flags);
             ssp = env->segs[R_SS].base;
-            //            push_size = (4 << shift);
+            /* push_size = (4 << shift); */
             new_stack = 0;
         }
 
@@ -2670,7 +2872,7 @@ void helper_iret_real(int shift)
     target_ulong ssp;
     int eflags_mask;
 
-    sp_mask = 0xffff; /* XXXX: use SS segment size ? */
+    sp_mask = 0xffff; /* XXXX: use SS segment size? */
     sp = ESP;
     ssp = env->segs[R_SS].base;
     if (shift == 1) {
@@ -2689,12 +2891,16 @@ void helper_iret_real(int shift)
     env->segs[R_CS].selector = new_cs;
     env->segs[R_CS].base = (new_cs << 4);
     env->eip = new_eip;
-    if (env->eflags & VM_MASK)
-        eflags_mask = TF_MASK | AC_MASK | ID_MASK | IF_MASK | RF_MASK | NT_MASK;
-    else
-        eflags_mask = TF_MASK | AC_MASK | ID_MASK | IF_MASK | IOPL_MASK | RF_MASK | NT_MASK;
-    if (shift == 0)
+    if (env->eflags & VM_MASK) {
+        eflags_mask = TF_MASK | AC_MASK | ID_MASK | IF_MASK | RF_MASK |
+            NT_MASK;
+    } else {
+        eflags_mask = TF_MASK | AC_MASK | ID_MASK | IF_MASK | IOPL_MASK |
+            RF_MASK | NT_MASK;
+    }
+    if (shift == 0) {
         eflags_mask &= 0xffff;
+    }
     load_eflags(new_eflags, eflags_mask);
     env->hflags2 &= ~HF2_NMI_MASK;
 }
@@ -2708,8 +2914,9 @@ static inline void validate_seg(int seg_reg, int cpl)
        they may still contain a valid base. I would be interested to
        know how a real x86_64 CPU behaves */
     if ((seg_reg == R_FS || seg_reg == R_GS) &&
-        (env->segs[seg_reg].selector & 0xfffc) == 0)
+        (env->segs[seg_reg].selector & 0xfffc) == 0) {
         return;
+    }
 
     e2 = env->segs[seg_reg].flags;
     dpl = (e2 >> DESC_DPL_SHIFT) & 3;
@@ -2731,11 +2938,13 @@ static inline void helper_ret_protected(int shift, int is_iret, int addend)
     target_ulong ssp, sp, new_eip, new_esp, sp_mask;
 
 #ifdef TARGET_X86_64
-    if (shift == 2)
+    if (shift == 2) {
         sp_mask = -1;
-    else
+    } else
 #endif
+    {
         sp_mask = get_sp_mask(env->segs[R_SS].flags);
+    }
     sp = ESP;
     ssp = env->segs[R_SS].base;
     new_eflags = 0; /* avoid warning */
@@ -2749,47 +2958,58 @@ static inline void helper_ret_protected(int shift, int is_iret, int addend)
         }
     } else
 #endif
-    if (shift == 1) {
-        /* 32 bits */
-        POPL(ssp, sp, sp_mask, new_eip);
-        POPL(ssp, sp, sp_mask, new_cs);
-        new_cs &= 0xffff;
-        if (is_iret) {
-            POPL(ssp, sp, sp_mask, new_eflags);
-            if (new_eflags & VM_MASK)
-                goto return_to_vm86;
+    {
+        if (shift == 1) {
+            /* 32 bits */
+            POPL(ssp, sp, sp_mask, new_eip);
+            POPL(ssp, sp, sp_mask, new_cs);
+            new_cs &= 0xffff;
+            if (is_iret) {
+                POPL(ssp, sp, sp_mask, new_eflags);
+                if (new_eflags & VM_MASK) {
+                    goto return_to_vm86;
+                }
+            }
+        } else {
+            /* 16 bits */
+            POPW(ssp, sp, sp_mask, new_eip);
+            POPW(ssp, sp, sp_mask, new_cs);
+            if (is_iret) {
+                POPW(ssp, sp, sp_mask, new_eflags);
+            }
         }
-    } else {
-        /* 16 bits */
-        POPW(ssp, sp, sp_mask, new_eip);
-        POPW(ssp, sp, sp_mask, new_cs);
-        if (is_iret)
-            POPW(ssp, sp, sp_mask, new_eflags);
     }
     LOG_PCALL("lret new %04x:" TARGET_FMT_lx " s=%d addend=0x%x\n",
               new_cs, new_eip, shift, addend);
     LOG_PCALL_STATE(env);
-    if ((new_cs & 0xfffc) == 0)
+    if ((new_cs & 0xfffc) == 0) {
         raise_exception_err(EXCP0D_GPF, new_cs & 0xfffc);
-    if (load_segment(&e1, &e2, new_cs) != 0)
+    }
+    if (load_segment(&e1, &e2, new_cs) != 0) {
         raise_exception_err(EXCP0D_GPF, new_cs & 0xfffc);
+    }
     if (!(e2 & DESC_S_MASK) ||
-        !(e2 & DESC_CS_MASK))
+        !(e2 & DESC_CS_MASK)) {
         raise_exception_err(EXCP0D_GPF, new_cs & 0xfffc);
+    }
     cpl = env->hflags & HF_CPL_MASK;
     rpl = new_cs & 3;
-    if (rpl < cpl)
+    if (rpl < cpl) {
         raise_exception_err(EXCP0D_GPF, new_cs & 0xfffc);
+    }
     dpl = (e2 >> DESC_DPL_SHIFT) & 3;
     if (e2 & DESC_C_MASK) {
-        if (dpl > rpl)
+        if (dpl > rpl) {
             raise_exception_err(EXCP0D_GPF, new_cs & 0xfffc);
+        }
     } else {
-        if (dpl != rpl)
+        if (dpl != rpl) {
             raise_exception_err(EXCP0D_GPF, new_cs & 0xfffc);
+        }
     }
-    if (!(e2 & DESC_P_MASK))
+    if (!(e2 & DESC_P_MASK)) {
         raise_exception_err(EXCP0B_NOSEG, new_cs & 0xfffc);
+    }
 
     sp += addend;
     if (rpl == cpl && (!(env->hflags & HF_CS64_MASK) ||
@@ -2808,48 +3028,55 @@ static inline void helper_ret_protected(int shift, int is_iret, int addend)
             new_ss &= 0xffff;
         } else
 #endif
-        if (shift == 1) {
-            /* 32 bits */
-            POPL(ssp, sp, sp_mask, new_esp);
-            POPL(ssp, sp, sp_mask, new_ss);
-            new_ss &= 0xffff;
-        } else {
-            /* 16 bits */
-            POPW(ssp, sp, sp_mask, new_esp);
-            POPW(ssp, sp, sp_mask, new_ss);
+        {
+            if (shift == 1) {
+                /* 32 bits */
+                POPL(ssp, sp, sp_mask, new_esp);
+                POPL(ssp, sp, sp_mask, new_ss);
+                new_ss &= 0xffff;
+            } else {
+                /* 16 bits */
+                POPW(ssp, sp, sp_mask, new_esp);
+                POPW(ssp, sp, sp_mask, new_ss);
+            }
         }
         LOG_PCALL("new ss:esp=%04x:" TARGET_FMT_lx "\n",
-                    new_ss, new_esp);
+                  new_ss, new_esp);
         if ((new_ss & 0xfffc) == 0) {
 #ifdef TARGET_X86_64
-            /* NULL ss is allowed in long mode if cpl != 3*/
-            /* XXX: test CS64 ? */
+            /* NULL ss is allowed in long mode if cpl != 3 */
+            /* XXX: test CS64? */
             if ((env->hflags & HF_LMA_MASK) && rpl != 3) {
                 cpu_x86_load_seg_cache(env, R_SS, new_ss,
                                        0, 0xffffffff,
                                        DESC_G_MASK | DESC_B_MASK | DESC_P_MASK |
                                        DESC_S_MASK | (rpl << DESC_DPL_SHIFT) |
                                        DESC_W_MASK | DESC_A_MASK);
-                ss_e2 = DESC_B_MASK; /* XXX: should not be needed ? */
+                ss_e2 = DESC_B_MASK; /* XXX: should not be needed? */
             } else
 #endif
             {
                 raise_exception_err(EXCP0D_GPF, 0);
             }
         } else {
-            if ((new_ss & 3) != rpl)
+            if ((new_ss & 3) != rpl) {
                 raise_exception_err(EXCP0D_GPF, new_ss & 0xfffc);
-            if (load_segment(&ss_e1, &ss_e2, new_ss) != 0)
+            }
+            if (load_segment(&ss_e1, &ss_e2, new_ss) != 0) {
                 raise_exception_err(EXCP0D_GPF, new_ss & 0xfffc);
+            }
             if (!(ss_e2 & DESC_S_MASK) ||
                 (ss_e2 & DESC_CS_MASK) ||
-                !(ss_e2 & DESC_W_MASK))
+                !(ss_e2 & DESC_W_MASK)) {
                 raise_exception_err(EXCP0D_GPF, new_ss & 0xfffc);
+            }
             dpl = (ss_e2 >> DESC_DPL_SHIFT) & 3;
-            if (dpl != rpl)
+            if (dpl != rpl) {
                 raise_exception_err(EXCP0D_GPF, new_ss & 0xfffc);
-            if (!(ss_e2 & DESC_P_MASK))
+            }
+            if (!(ss_e2 & DESC_P_MASK)) {
                 raise_exception_err(EXCP0B_NOSEG, new_ss & 0xfffc);
+            }
             cpu_x86_load_seg_cache(env, R_SS, new_ss,
                                    get_seg_base(ss_e1, ss_e2),
                                    get_seg_limit(ss_e1, ss_e2),
@@ -2863,11 +3090,13 @@ static inline void helper_ret_protected(int shift, int is_iret, int addend)
         cpu_x86_set_cpl(env, rpl);
         sp = new_esp;
 #ifdef TARGET_X86_64
-        if (env->hflags & HF_CS64_MASK)
+        if (env->hflags & HF_CS64_MASK) {
             sp_mask = -1;
-        else
+        } else
 #endif
+        {
             sp_mask = get_sp_mask(ss_e2);
+        }
 
         /* validate data segments */
         validate_seg(R_ES, rpl);
@@ -2882,13 +3111,16 @@ static inline void helper_ret_protected(int shift, int is_iret, int addend)
     if (is_iret) {
         /* NOTE: 'cpl' is the _old_ CPL */
         eflags_mask = TF_MASK | AC_MASK | ID_MASK | RF_MASK | NT_MASK;
-        if (cpl == 0)
+        if (cpl == 0) {
             eflags_mask |= IOPL_MASK;
+        }
         iopl = (env->eflags >> IOPL_SHIFT) & 3;
-        if (cpl <= iopl)
+        if (cpl <= iopl) {
             eflags_mask |= IF_MASK;
-        if (shift == 0)
+        }
+        if (shift == 0) {
             eflags_mask &= 0xffff;
+        }
         load_eflags(new_eflags, eflags_mask);
     }
     return;
@@ -2924,18 +3156,22 @@ void helper_iret_protected(int shift, int next_eip)
     /* specific case for TSS */
     if (env->eflags & NT_MASK) {
 #ifdef TARGET_X86_64
-        if (env->hflags & HF_LMA_MASK)
+        if (env->hflags & HF_LMA_MASK) {
             raise_exception_err(EXCP0D_GPF, 0);
+        }
 #endif
         tss_selector = lduw_kernel(env->tr.base + 0);
-        if (tss_selector & 4)
+        if (tss_selector & 4) {
             raise_exception_err(EXCP0A_TSS, tss_selector & 0xfffc);
-        if (load_segment(&e1, &e2, tss_selector) != 0)
+        }
+        if (load_segment(&e1, &e2, tss_selector) != 0) {
             raise_exception_err(EXCP0A_TSS, tss_selector & 0xfffc);
+        }
         type = (e2 >> DESC_TYPE_SHIFT) & 0x17;
         /* NOTE: we check both segment and busy TSS */
-        if (type != 3)
+        if (type != 3) {
             raise_exception_err(EXCP0A_TSS, tss_selector & 0xfffc);
+        }
         switch_tss(tss_selector, e1, e2, SWITCH_TSS_IRET, next_eip);
     } else {
         helper_ret_protected(shift, 1, 0);
@@ -2962,7 +3198,8 @@ void helper_sysenter(void)
                                0, 0xffffffff,
                                DESC_G_MASK | DESC_B_MASK | DESC_P_MASK |
                                DESC_S_MASK |
-                               DESC_CS_MASK | DESC_R_MASK | DESC_A_MASK | DESC_L_MASK);
+                               DESC_CS_MASK | DESC_R_MASK | DESC_A_MASK |
+                               DESC_L_MASK);
     } else
 #endif
     {
@@ -2992,26 +3229,27 @@ void helper_sysexit(int dflag)
     cpu_x86_set_cpl(env, 3);
 #ifdef TARGET_X86_64
     if (dflag == 2) {
-        cpu_x86_load_seg_cache(env, R_CS, ((env->sysenter_cs + 32) & 0xfffc) | 3,
-                               0, 0xffffffff,
+        cpu_x86_load_seg_cache(env, R_CS, ((env->sysenter_cs + 32) & 0xfffc) |
+                               3, 0, 0xffffffff,
                                DESC_G_MASK | DESC_B_MASK | DESC_P_MASK |
                                DESC_S_MASK | (3 << DESC_DPL_SHIFT) |
-                               DESC_CS_MASK | DESC_R_MASK | DESC_A_MASK | DESC_L_MASK);
-        cpu_x86_load_seg_cache(env, R_SS, ((env->sysenter_cs + 40) & 0xfffc) | 3,
-                               0, 0xffffffff,
+                               DESC_CS_MASK | DESC_R_MASK | DESC_A_MASK |
+                               DESC_L_MASK);
+        cpu_x86_load_seg_cache(env, R_SS, ((env->sysenter_cs + 40) & 0xfffc) |
+                               3, 0, 0xffffffff,
                                DESC_G_MASK | DESC_B_MASK | DESC_P_MASK |
                                DESC_S_MASK | (3 << DESC_DPL_SHIFT) |
                                DESC_W_MASK | DESC_A_MASK);
     } else
 #endif
     {
-        cpu_x86_load_seg_cache(env, R_CS, ((env->sysenter_cs + 16) & 0xfffc) | 3,
-                               0, 0xffffffff,
+        cpu_x86_load_seg_cache(env, R_CS, ((env->sysenter_cs + 16) & 0xfffc) |
+                               3, 0, 0xffffffff,
                                DESC_G_MASK | DESC_B_MASK | DESC_P_MASK |
                                DESC_S_MASK | (3 << DESC_DPL_SHIFT) |
                                DESC_CS_MASK | DESC_R_MASK | DESC_A_MASK);
-        cpu_x86_load_seg_cache(env, R_SS, ((env->sysenter_cs + 24) & 0xfffc) | 3,
-                               0, 0xffffffff,
+        cpu_x86_load_seg_cache(env, R_SS, ((env->sysenter_cs + 24) & 0xfffc) |
+                               3, 0, 0xffffffff,
                                DESC_G_MASK | DESC_B_MASK | DESC_P_MASK |
                                DESC_S_MASK | (3 << DESC_DPL_SHIFT) |
                                DESC_W_MASK | DESC_A_MASK);
@@ -3039,7 +3277,7 @@ target_ulong helper_read_crN(int reg)
     target_ulong val;
 
     helper_svm_check_intercept_param(SVM_EXIT_READ_CR0 + reg, 0);
-    switch(reg) {
+    switch (reg) {
     default:
         val = env->cr[reg];
         break;
@@ -3057,7 +3295,7 @@ target_ulong helper_read_crN(int reg)
 void helper_write_crN(int reg, target_ulong t0)
 {
     helper_svm_check_intercept_param(SVM_EXIT_WRITE_CR0 + reg, 0);
-    switch(reg) {
+    switch (reg) {
     case 0:
         cpu_x86_update_cr0(env, t0);
         break;
@@ -3088,13 +3326,16 @@ void helper_movl_drN_T0(int reg, target_ulong t0)
         env->dr[reg] = t0;
         hw_breakpoint_insert(env, reg);
     } else if (reg == 7) {
-        for (i = 0; i < 4; i++)
+        for (i = 0; i < 4; i++) {
             hw_breakpoint_remove(env, i);
+        }
         env->dr[7] = t0;
-        for (i = 0; i < 4; i++)
+        for (i = 0; i < 4; i++) {
             hw_breakpoint_insert(env, i);
-    } else
+        }
+    } else {
         env->dr[reg] = t0;
+    }
 }
 #endif
 
@@ -3144,7 +3385,7 @@ void helper_rdpmc(void)
         raise_exception(EXCP0D_GPF);
     }
     helper_svm_check_intercept_param(SVM_EXIT_RDPMC, 0);
-    
+
     /* currently unimplemented */
     qemu_log_mask(LOG_UNIMP, "x86: unimplemented rdpmc\n");
     raise_exception_err(EXCP06_ILLOP, 0);
@@ -3167,7 +3408,7 @@ void helper_wrmsr(void)
 
     val = ((uint32_t)EAX) | ((uint64_t)((uint32_t)EDX) << 32);
 
-    switch((uint32_t)ECX) {
+    switch ((uint32_t)ECX) {
     case MSR_IA32_SYSENTER_CS:
         env->sysenter_cs = val & 0xffff;
         break;
@@ -3183,19 +3424,26 @@ void helper_wrmsr(void)
     case MSR_EFER:
         {
             uint64_t update_mask;
+
             update_mask = 0;
-            if (env->cpuid_ext2_features & CPUID_EXT2_SYSCALL)
+            if (env->cpuid_ext2_features & CPUID_EXT2_SYSCALL) {
                 update_mask |= MSR_EFER_SCE;
-            if (env->cpuid_ext2_features & CPUID_EXT2_LM)
+            }
+            if (env->cpuid_ext2_features & CPUID_EXT2_LM) {
                 update_mask |= MSR_EFER_LME;
-            if (env->cpuid_ext2_features & CPUID_EXT2_FFXSR)
+            }
+            if (env->cpuid_ext2_features & CPUID_EXT2_FFXSR) {
                 update_mask |= MSR_EFER_FFXSR;
-            if (env->cpuid_ext2_features & CPUID_EXT2_NX)
+            }
+            if (env->cpuid_ext2_features & CPUID_EXT2_NX) {
                 update_mask |= MSR_EFER_NXE;
-            if (env->cpuid_ext3_features & CPUID_EXT3_SVM)
+            }
+            if (env->cpuid_ext3_features & CPUID_EXT3_SVM) {
                 update_mask |= MSR_EFER_SVME;
-            if (env->cpuid_ext2_features & CPUID_EXT2_FFXSR)
+            }
+            if (env->cpuid_ext2_features & CPUID_EXT2_FFXSR) {
                 update_mask |= MSR_EFER_FFXSR;
+            }
             cpu_load_efer(env, (env->efer & ~update_mask) |
                           (val & update_mask));
         }
@@ -3274,8 +3522,9 @@ void helper_wrmsr(void)
         break;
     case MSR_MCG_CTL:
         if ((env->mcg_cap & MCG_CTL_P)
-            && (val == 0 || val == ~(uint64_t)0))
+            && (val == 0 || val == ~(uint64_t)0)) {
             env->mcg_ctl = val;
+        }
         break;
     case MSR_TSC_AUX:
         env->tsc_aux = val;
@@ -3288,11 +3537,12 @@ void helper_wrmsr(void)
             && (uint32_t)ECX < MSR_MC0_CTL + (4 * env->mcg_cap & 0xff)) {
             uint32_t offset = (uint32_t)ECX - MSR_MC0_CTL;
             if ((offset & 0x3) != 0
-                || (val == 0 || val == ~(uint64_t)0))
+                || (val == 0 || val == ~(uint64_t)0)) {
                 env->mce_banks[offset] = val;
+            }
             break;
         }
-        /* XXX: exception ? */
+        /* XXX: exception? */
         break;
     }
 }
@@ -3303,7 +3553,7 @@ void helper_rdmsr(void)
 
     helper_svm_check_intercept_param(SVM_EXIT_MSR, 0);
 
-    switch((uint32_t)ECX) {
+    switch ((uint32_t)ECX) {
     case MSR_IA32_SYSENTER_CS:
         val = env->sysenter_cs;
         break;
@@ -3398,20 +3648,23 @@ void helper_rdmsr(void)
         val = env->mtrr_deftype;
         break;
     case MSR_MTRRcap:
-        if (env->cpuid_features & CPUID_MTRR)
-            val = MSR_MTRRcap_VCNT | MSR_MTRRcap_FIXRANGE_SUPPORT | MSR_MTRRcap_WC_SUPPORTED;
-        else
-            /* XXX: exception ? */
+        if (env->cpuid_features & CPUID_MTRR) {
+            val = MSR_MTRRcap_VCNT | MSR_MTRRcap_FIXRANGE_SUPPORT |
+                MSR_MTRRcap_WC_SUPPORTED;
+        } else {
+            /* XXX: exception? */
             val = 0;
+        }
         break;
     case MSR_MCG_CAP:
         val = env->mcg_cap;
         break;
     case MSR_MCG_CTL:
-        if (env->mcg_cap & MCG_CTL_P)
+        if (env->mcg_cap & MCG_CTL_P) {
             val = env->mcg_ctl;
-        else
+        } else {
             val = 0;
+        }
         break;
     case MSR_MCG_STATUS:
         val = env->mcg_status;
@@ -3426,7 +3679,7 @@ void helper_rdmsr(void)
             val = env->mce_banks[offset];
             break;
         }
-        /* XXX: exception ? */
+        /* XXX: exception? */
         val = 0;
         break;
     }
@@ -3443,10 +3696,12 @@ target_ulong helper_lsl(target_ulong selector1)
 
     selector = selector1 & 0xffff;
     eflags = helper_cc_compute_all(CC_OP);
-    if ((selector & 0xfffc) == 0)
+    if ((selector & 0xfffc) == 0) {
         goto fail;
-    if (load_segment(&e1, &e2, selector) != 0)
+    }
+    if (load_segment(&e1, &e2, selector) != 0) {
         goto fail;
+    }
     rpl = selector & 3;
     dpl = (e2 >> DESC_DPL_SHIFT) & 3;
     cpl = env->hflags & HF_CPL_MASK;
@@ -3454,12 +3709,13 @@ target_ulong helper_lsl(target_ulong selector1)
         if ((e2 & DESC_CS_MASK) && (e2 & DESC_C_MASK)) {
             /* conforming */
         } else {
-            if (dpl < cpl || dpl < rpl)
+            if (dpl < cpl || dpl < rpl) {
                 goto fail;
+            }
         }
     } else {
         type = (e2 >> DESC_TYPE_SHIFT) & 0xf;
-        switch(type) {
+        switch (type) {
         case 1:
         case 2:
         case 3:
@@ -3487,10 +3743,12 @@ target_ulong helper_lar(target_ulong selector1)
 
     selector = selector1 & 0xffff;
     eflags = helper_cc_compute_all(CC_OP);
-    if ((selector & 0xfffc) == 0)
+    if ((selector & 0xfffc) == 0) {
         goto fail;
-    if (load_segment(&e1, &e2, selector) != 0)
+    }
+    if (load_segment(&e1, &e2, selector) != 0) {
         goto fail;
+    }
     rpl = selector & 3;
     dpl = (e2 >> DESC_DPL_SHIFT) & 3;
     cpl = env->hflags & HF_CPL_MASK;
@@ -3498,12 +3756,13 @@ target_ulong helper_lar(target_ulong selector1)
         if ((e2 & DESC_CS_MASK) && (e2 & DESC_C_MASK)) {
             /* conforming */
         } else {
-            if (dpl < cpl || dpl < rpl)
+            if (dpl < cpl || dpl < rpl) {
                 goto fail;
+            }
         }
     } else {
         type = (e2 >> DESC_TYPE_SHIFT) & 0xf;
-        switch(type) {
+        switch (type) {
         case 1:
         case 2:
         case 3:
@@ -3533,21 +3792,26 @@ void helper_verr(target_ulong selector1)
 
     selector = selector1 & 0xffff;
     eflags = helper_cc_compute_all(CC_OP);
-    if ((selector & 0xfffc) == 0)
+    if ((selector & 0xfffc) == 0) {
         goto fail;
-    if (load_segment(&e1, &e2, selector) != 0)
+    }
+    if (load_segment(&e1, &e2, selector) != 0) {
         goto fail;
-    if (!(e2 & DESC_S_MASK))
+    }
+    if (!(e2 & DESC_S_MASK)) {
         goto fail;
+    }
     rpl = selector & 3;
     dpl = (e2 >> DESC_DPL_SHIFT) & 3;
     cpl = env->hflags & HF_CPL_MASK;
     if (e2 & DESC_CS_MASK) {
-        if (!(e2 & DESC_R_MASK))
+        if (!(e2 & DESC_R_MASK)) {
             goto fail;
+        }
         if (!(e2 & DESC_C_MASK)) {
-            if (dpl < cpl || dpl < rpl)
+            if (dpl < cpl || dpl < rpl) {
                 goto fail;
+            }
         }
     } else {
         if (dpl < cpl || dpl < rpl) {
@@ -3566,20 +3830,24 @@ void helper_verw(target_ulong selector1)
 
     selector = selector1 & 0xffff;
     eflags = helper_cc_compute_all(CC_OP);
-    if ((selector & 0xfffc) == 0)
+    if ((selector & 0xfffc) == 0) {
         goto fail;
-    if (load_segment(&e1, &e2, selector) != 0)
+    }
+    if (load_segment(&e1, &e2, selector) != 0) {
         goto fail;
-    if (!(e2 & DESC_S_MASK))
+    }
+    if (!(e2 & DESC_S_MASK)) {
         goto fail;
+    }
     rpl = selector & 3;
     dpl = (e2 >> DESC_DPL_SHIFT) & 3;
     cpl = env->hflags & HF_CPL_MASK;
     if (e2 & DESC_CS_MASK) {
         goto fail;
     } else {
-        if (dpl < cpl || dpl < rpl)
+        if (dpl < cpl || dpl < rpl) {
             goto fail;
+        }
         if (!(e2 & DESC_W_MASK)) {
         fail:
             CC_SRC = eflags & ~CC_Z;
@@ -3616,8 +3884,9 @@ static inline floatx80 double_to_floatx80(double a)
 static void fpu_set_exception(int mask)
 {
     env->fpus |= mask;
-    if (env->fpus & (~env->fpuc & FPUC_EM))
+    if (env->fpus & (~env->fpuc & FPUC_EM)) {
         env->fpus |= FPUS_SE | FPUS_B;
+    }
 }
 
 static inline floatx80 helper_fdiv(floatx80 a, floatx80 b)
@@ -3646,6 +3915,7 @@ void helper_flds_FT0(uint32_t val)
         float32 f;
         uint32_t i;
     } u;
+
     u.i = val;
     FT0 = float32_to_floatx80(u.f, &env->fp_status);
 }
@@ -3656,6 +3926,7 @@ void helper_fldl_FT0(uint64_t val)
         float64 f;
         uint64_t i;
     } u;
+
     u.i = val;
     FT0 = float64_to_floatx80(u.f, &env->fp_status);
 }
@@ -3672,6 +3943,7 @@ void helper_flds_ST0(uint32_t val)
         float32 f;
         uint32_t i;
     } u;
+
     new_fpstt = (env->fpstt - 1) & 7;
     u.i = val;
     env->fpregs[new_fpstt].d = float32_to_floatx80(u.f, &env->fp_status);
@@ -3686,6 +3958,7 @@ void helper_fldl_ST0(uint64_t val)
         float64 f;
         uint64_t i;
     } u;
+
     new_fpstt = (env->fpstt - 1) & 7;
     u.i = val;
     env->fpregs[new_fpstt].d = float64_to_floatx80(u.f, &env->fp_status);
@@ -3696,6 +3969,7 @@ void helper_fldl_ST0(uint64_t val)
 void helper_fildl_ST0(int32_t val)
 {
     int new_fpstt;
+
     new_fpstt = (env->fpstt - 1) & 7;
     env->fpregs[new_fpstt].d = int32_to_floatx80(val, &env->fp_status);
     env->fpstt = new_fpstt;
@@ -3705,6 +3979,7 @@ void helper_fildl_ST0(int32_t val)
 void helper_fildll_ST0(int64_t val)
 {
     int new_fpstt;
+
     new_fpstt = (env->fpstt - 1) & 7;
     env->fpregs[new_fpstt].d = int64_to_floatx80(val, &env->fp_status);
     env->fpstt = new_fpstt;
@@ -3717,6 +3992,7 @@ uint32_t helper_fsts_ST0(void)
         float32 f;
         uint32_t i;
     } u;
+
     u.f = floatx80_to_float32(ST0, &env->fp_status);
     return u.i;
 }
@@ -3727,6 +4003,7 @@ uint64_t helper_fstl_ST0(void)
         float64 f;
         uint64_t i;
     } u;
+
     u.f = floatx80_to_float64(ST0, &env->fp_status);
     return u.i;
 }
@@ -3734,15 +4011,18 @@ uint64_t helper_fstl_ST0(void)
 int32_t helper_fist_ST0(void)
 {
     int32_t val;
+
     val = floatx80_to_int32(ST0, &env->fp_status);
-    if (val != (int16_t)val)
+    if (val != (int16_t)val) {
         val = -32768;
+    }
     return val;
 }
 
 int32_t helper_fistl_ST0(void)
 {
     int32_t val;
+
     val = floatx80_to_int32(ST0, &env->fp_status);
     return val;
 }
@@ -3750,6 +4030,7 @@ int32_t helper_fistl_ST0(void)
 int64_t helper_fistll_ST0(void)
 {
     int64_t val;
+
     val = floatx80_to_int64(ST0, &env->fp_status);
     return val;
 }
@@ -3757,15 +4038,18 @@ int64_t helper_fistll_ST0(void)
 int32_t helper_fistt_ST0(void)
 {
     int32_t val;
+
     val = floatx80_to_int32_round_to_zero(ST0, &env->fp_status);
-    if (val != (int16_t)val)
+    if (val != (int16_t)val) {
         val = -32768;
+    }
     return val;
 }
 
 int32_t helper_fisttl_ST0(void)
 {
     int32_t val;
+
     val = floatx80_to_int32_round_to_zero(ST0, &env->fp_status);
     return val;
 }
@@ -3773,6 +4057,7 @@ int32_t helper_fisttl_ST0(void)
 int64_t helper_fisttll_ST0(void)
 {
     int64_t val;
+
     val = floatx80_to_int64_round_to_zero(ST0, &env->fp_status);
     return val;
 }
@@ -3780,6 +4065,7 @@ int64_t helper_fisttll_ST0(void)
 void helper_fldt_ST0(target_ulong ptr)
 {
     int new_fpstt;
+
     new_fpstt = (env->fpstt - 1) & 7;
     env->fpregs[new_fpstt].d = helper_fldt(ptr);
     env->fpstt = new_fpstt;
@@ -3804,13 +4090,13 @@ void helper_fpop(void)
 void helper_fdecstp(void)
 {
     env->fpstt = (env->fpstt - 1) & 7;
-    env->fpus &= (~0x4700);
+    env->fpus &= ~0x4700;
 }
 
 void helper_fincstp(void)
 {
     env->fpstt = (env->fpstt + 1) & 7;
-    env->fpus &= (~0x4700);
+    env->fpus &= ~0x4700;
 }
 
 /* FPU move */
@@ -3843,6 +4129,7 @@ void helper_fmov_STN_ST0(int st_index)
 void helper_fxchg_ST0_STN(int st_index)
 {
     floatx80 tmp;
+
     tmp = ST(st_index);
     ST(st_index) = ST0;
     ST0 = tmp;
@@ -3865,7 +4152,7 @@ void helper_fucom_ST0_FT0(void)
     int ret;
 
     ret = floatx80_compare_quiet(ST0, FT0, &env->fp_status);
-    env->fpus = (env->fpus & ~0x4500) | fcom_ccval[ret+ 1];
+    env->fpus = (env->fpus & ~0x4500) | fcom_ccval[ret + 1];
 }
 
 static const int fcomi_ccval[4] = {CC_C, CC_Z, 0, CC_Z | CC_P | CC_C};
@@ -3947,6 +4234,7 @@ void helper_fsubr_STN_ST0(int st_index)
 void helper_fdiv_STN_ST0(int st_index)
 {
     floatx80 *p;
+
     p = &ST(st_index);
     *p = helper_fdiv(*p, ST0);
 }
@@ -3954,6 +4242,7 @@ void helper_fdiv_STN_ST0(int st_index)
 void helper_fdivr_STN_ST0(int st_index)
 {
     floatx80 *p;
+
     p = &ST(st_index);
     *p = helper_fdiv(ST0, *p);
 }
@@ -4024,7 +4313,7 @@ static void update_fp_status(void)
     int rnd_type;
 
     /* set rounding mode */
-    switch(env->fpuc & FPU_RC_MASK) {
+    switch (env->fpuc & FPU_RC_MASK) {
     default:
     case FPU_RC_NEAR:
         rnd_type = float_round_nearest_even;
@@ -4040,7 +4329,7 @@ static void update_fp_status(void)
         break;
     }
     set_float_rounding_mode(rnd_type, &env->fp_status);
-    switch((env->fpuc >> 8) & 3) {
+    switch ((env->fpuc >> 8) & 3) {
     case 0:
         rnd_type = 32;
         break;
@@ -4068,8 +4357,9 @@ void helper_fclex(void)
 
 void helper_fwait(void)
 {
-    if (env->fpus & FPUS_SE)
+    if (env->fpus & FPUS_SE) {
         fpu_raise_exception();
+    }
 }
 
 void helper_fninit(void)
@@ -4097,7 +4387,7 @@ void helper_fbld_ST0(target_ulong ptr)
     int i;
 
     val = 0;
-    for(i = 8; i >= 0; i--) {
+    for (i = 8; i >= 0; i--) {
         v = ldub(ptr + i);
         val = (val * 100) + ((v >> 4) * 10) + (v & 0xf);
     }
@@ -4125,8 +4415,9 @@ void helper_fbst_ST0(target_ulong ptr)
         stb(mem_end, 0x00);
     }
     while (mem_ref < mem_end) {
-        if (val == 0)
+        if (val == 0) {
             break;
+        }
         v = val % 100;
         val = val / 100;
         v = ((v / 10) << 4) | (v % 10);
@@ -4140,6 +4431,7 @@ void helper_fbst_ST0(target_ulong ptr)
 void helper_f2xm1(void)
 {
     double val = floatx80_to_double(ST0);
+
     val = pow(2.0, val) - 1.0;
     ST0 = double_to_floatx80(val);
 }
@@ -4148,13 +4440,13 @@ void helper_fyl2x(void)
 {
     double fptemp = floatx80_to_double(ST0);
 
-    if (fptemp>0.0){
-        fptemp = log(fptemp)/log(2.0);    /* log2(ST) */
+    if (fptemp > 0.0) {
+        fptemp = log(fptemp) / log(2.0); /* log2(ST) */
         fptemp *= floatx80_to_double(ST1);
         ST1 = double_to_floatx80(fptemp);
         fpop();
     } else {
-        env->fpus &= (~0x4700);
+        env->fpus &= ~0x4700;
         env->fpus |= 0x400;
     }
 }
@@ -4163,15 +4455,15 @@ void helper_fptan(void)
 {
     double fptemp = floatx80_to_double(ST0);
 
-    if((fptemp > MAXTAN)||(fptemp < -MAXTAN)) {
+    if ((fptemp > MAXTAN) || (fptemp < -MAXTAN)) {
         env->fpus |= 0x400;
     } else {
         fptemp = tan(fptemp);
         ST0 = double_to_floatx80(fptemp);
         fpush();
         ST0 = floatx80_one;
-        env->fpus &= (~0x400);  /* C2 <-- 0 */
-        /* the above code is for  |arg| < 2**52 only */
+        env->fpus &= ~0x400; /* C2 <-- 0 */
+        /* the above code is for |arg| < 2**52 only */
     }
 }
 
@@ -4193,14 +4485,15 @@ void helper_fxtract(void)
 
     if (floatx80_is_zero(ST0)) {
         /* Easy way to generate -inf and raising division by 0 exception */
-        ST0 = floatx80_div(floatx80_chs(floatx80_one), floatx80_zero, &env->fp_status);
+        ST0 = floatx80_div(floatx80_chs(floatx80_one), floatx80_zero,
+                           &env->fp_status);
         fpush();
         ST0 = temp.d;
     } else {
         int expdif;
 
         expdif = EXPD(temp) - EXPBIAS;
-        /*DP exponent bias*/
+        /* DP exponent bias */
         ST0 = int32_to_floatx80(expdif, &env->fp_status);
         fpush();
         BIASEXPONENT(temp);
@@ -4220,7 +4513,7 @@ void helper_fprem1(void)
 
     if (isinf(st0) || isnan(st0) || isnan(st1) || (st1 == 0.0)) {
         ST0 = double_to_floatx80(0.0 / 0.0); /* NaN */
-        env->fpus &= (~0x4700); /* (C3,C2,C1,C0) <-- 0000 */
+        env->fpus &= ~0x4700; /* (C3,C2,C1,C0) <-- 0000 */
         return;
     }
 
@@ -4232,7 +4525,7 @@ void helper_fprem1(void)
 
     if (expdif < 0) {
         /* optimisation? taken from the AMD docs */
-        env->fpus &= (~0x4700); /* (C3,C2,C1,C0) <-- 0000 */
+        env->fpus &= ~0x4700; /* (C3,C2,C1,C0) <-- 0000 */
         /* ST0 is unchanged */
         return;
     }
@@ -4244,13 +4537,14 @@ void helper_fprem1(void)
         st0 = fpsrcop - fptemp * dblq;
 
         /* convert dblq to q by truncating towards zero */
-        if (dblq < 0.0)
-           q = (signed long long int)(-dblq);
-        else
-           q = (signed long long int)dblq;
+        if (dblq < 0.0) {
+            q = (signed long long int)(-dblq);
+        } else {
+            q = (signed long long int)dblq;
+        }
 
-        env->fpus &= (~0x4700); /* (C3,C2,C1,C0) <-- 0000 */
-                                /* (C0,C3,C1) <-- (q2,q1,q0) */
+        env->fpus &= ~0x4700; /* (C3,C2,C1,C0) <-- 0000 */
+        /* (C0,C3,C1) <-- (q2,q1,q0) */
         env->fpus |= (q & 0x4) << (8 - 2);  /* (C0) <-- q2 */
         env->fpus |= (q & 0x2) << (14 - 1); /* (C3) <-- q1 */
         env->fpus |= (q & 0x1) << (9 - 0);  /* (C1) <-- q0 */
@@ -4277,9 +4571,9 @@ void helper_fprem(void)
     st1 = floatx80_to_double(ST1);
 
     if (isinf(st0) || isnan(st0) || isnan(st1) || (st1 == 0.0)) {
-       ST0 = double_to_floatx80(0.0 / 0.0); /* NaN */
-       env->fpus &= (~0x4700); /* (C3,C2,C1,C0) <-- 0000 */
-       return;
+        ST0 = double_to_floatx80(0.0 / 0.0); /* NaN */
+        env->fpus &= ~0x4700; /* (C3,C2,C1,C0) <-- 0000 */
+        return;
     }
 
     fpsrcop = st0;
@@ -4290,30 +4584,32 @@ void helper_fprem(void)
 
     if (expdif < 0) {
         /* optimisation? taken from the AMD docs */
-        env->fpus &= (~0x4700); /* (C3,C2,C1,C0) <-- 0000 */
+        env->fpus &= ~0x4700; /* (C3,C2,C1,C0) <-- 0000 */
         /* ST0 is unchanged */
         return;
     }
 
-    if ( expdif < 53 ) {
-        dblq = fpsrcop/*ST0*/ / fptemp/*ST1*/;
+    if (expdif < 53) {
+        dblq = fpsrcop / fptemp; /* ST0 / ST1 */
         /* round dblq towards zero */
         dblq = (dblq < 0.0) ? ceil(dblq) : floor(dblq);
-        st0 = fpsrcop/*ST0*/ - fptemp * dblq;
+        st0 = fpsrcop - fptemp * dblq; /* fpsrcop is ST0 */
 
         /* convert dblq to q by truncating towards zero */
-        if (dblq < 0.0)
-           q = (signed long long int)(-dblq);
-        else
-           q = (signed long long int)dblq;
+        if (dblq < 0.0) {
+            q = (signed long long int)(-dblq);
+        } else {
+            q = (signed long long int)dblq;
+        }
 
-        env->fpus &= (~0x4700); /* (C3,C2,C1,C0) <-- 0000 */
-                                /* (C0,C3,C1) <-- (q2,q1,q0) */
+        env->fpus &= ~0x4700; /* (C3,C2,C1,C0) <-- 0000 */
+        /* (C0,C3,C1) <-- (q2,q1,q0) */
         env->fpus |= (q & 0x4) << (8 - 2);  /* (C0) <-- q2 */
         env->fpus |= (q & 0x2) << (14 - 1); /* (C3) <-- q1 */
         env->fpus |= (q & 0x1) << (9 - 0);  /* (C1) <-- q0 */
     } else {
         int N = 32 + (expdif % 32); /* as per AMD docs */
+
         env->fpus |= 0x400;  /* C2 <-- 1 */
         fptemp = pow(2.0, (double)(expdif - N));
         fpsrcop = (st0 / st1) / fptemp;
@@ -4329,13 +4625,13 @@ void helper_fyl2xp1(void)
 {
     double fptemp = floatx80_to_double(ST0);
 
-    if ((fptemp+1.0)>0.0) {
-        fptemp = log(fptemp+1.0) / log(2.0); /* log2(ST+1.0) */
+    if ((fptemp + 1.0) > 0.0) {
+        fptemp = log(fptemp + 1.0) / log(2.0); /* log2(ST + 1.0) */
         fptemp *= floatx80_to_double(ST1);
         ST1 = double_to_floatx80(fptemp);
         fpop();
     } else {
-        env->fpus &= (~0x4700);
+        env->fpus &= ~0x4700;
         env->fpus |= 0x400;
     }
 }
@@ -4343,7 +4639,7 @@ void helper_fyl2xp1(void)
 void helper_fsqrt(void)
 {
     if (floatx80_is_neg(ST0)) {
-        env->fpus &= (~0x4700);  /* (C3,C2,C1,C0) <-- 0000 */
+        env->fpus &= ~0x4700;  /* (C3,C2,C1,C0) <-- 0000 */
         env->fpus |= 0x400;
     }
     ST0 = floatx80_sqrt(ST0, &env->fp_status);
@@ -4353,14 +4649,14 @@ void helper_fsincos(void)
 {
     double fptemp = floatx80_to_double(ST0);
 
-    if ((fptemp > MAXTAN)||(fptemp < -MAXTAN)) {
+    if ((fptemp > MAXTAN) || (fptemp < -MAXTAN)) {
         env->fpus |= 0x400;
     } else {
         ST0 = double_to_floatx80(sin(fptemp));
         fpush();
         ST0 = double_to_floatx80(cos(fptemp));
-        env->fpus &= (~0x400);  /* C2 <-- 0 */
-        /* the above code is for  |arg| < 2**63 only */
+        env->fpus &= ~0x400;  /* C2 <-- 0 */
+        /* the above code is for |arg| < 2**63 only */
     }
 }
 
@@ -4383,12 +4679,12 @@ void helper_fsin(void)
 {
     double fptemp = floatx80_to_double(ST0);
 
-    if ((fptemp > MAXTAN)||(fptemp < -MAXTAN)) {
+    if ((fptemp > MAXTAN) || (fptemp < -MAXTAN)) {
         env->fpus |= 0x400;
     } else {
         ST0 = double_to_floatx80(sin(fptemp));
-        env->fpus &= (~0x400);  /* C2 <-- 0 */
-        /* the above code is for  |arg| < 2**53 only */
+        env->fpus &= ~0x400;  /* C2 <-- 0 */
+        /* the above code is for |arg| < 2**53 only */
     }
 }
 
@@ -4396,12 +4692,12 @@ void helper_fcos(void)
 {
     double fptemp = floatx80_to_double(ST0);
 
-    if((fptemp > MAXTAN)||(fptemp < -MAXTAN)) {
+    if ((fptemp > MAXTAN) || (fptemp < -MAXTAN)) {
         env->fpus |= 0x400;
     } else {
         ST0 = double_to_floatx80(cos(fptemp));
-        env->fpus &= (~0x400);  /* C2 <-- 0 */
-        /* the above code is for  |arg5 < 2**63 only */
+        env->fpus &= ~0x400;  /* C2 <-- 0 */
+        /* the above code is for |arg| < 2**63 only */
     }
 }
 
@@ -4412,22 +4708,25 @@ void helper_fxam_ST0(void)
 
     temp.d = ST0;
 
-    env->fpus &= (~0x4700);  /* (C3,C2,C1,C0) <-- 0000 */
-    if (SIGND(temp))
+    env->fpus &= ~0x4700; /* (C3,C2,C1,C0) <-- 0000 */
+    if (SIGND(temp)) {
         env->fpus |= 0x200; /* C1 <-- 1 */
+    }
 
     /* XXX: test fptags too */
     expdif = EXPD(temp);
     if (expdif == MAXEXPD) {
-        if (MANTD(temp) == 0x8000000000000000ULL)
-            env->fpus |=  0x500 /*Infinity*/;
-        else
-            env->fpus |=  0x100 /*NaN*/;
+        if (MANTD(temp) == 0x8000000000000000ULL) {
+            env->fpus |= 0x500; /* Infinity */
+        } else {
+            env->fpus |= 0x100; /* NaN */
+        }
     } else if (expdif == 0) {
-        if (MANTD(temp) == 0)
-            env->fpus |=  0x4000 /*Zero*/;
-        else
-            env->fpus |= 0x4400 /*Denormal*/;
+        if (MANTD(temp) == 0) {
+            env->fpus |=  0x4000; /* Zero */
+        } else {
+            env->fpus |= 0x4400; /* Denormal */
+        }
     } else {
         env->fpus |= 0x400;
     }
@@ -4441,20 +4740,19 @@ void helper_fstenv(target_ulong ptr, int data32)
 
     fpus = (env->fpus & ~0x3800) | (env->fpstt & 0x7) << 11;
     fptag = 0;
-    for (i=7; i>=0; i--) {
-	fptag <<= 2;
-	if (env->fptags[i]) {
+    for (i = 7; i >= 0; i--) {
+        fptag <<= 2;
+        if (env->fptags[i]) {
             fptag |= 3;
-	} else {
+        } else {
             tmp.d = env->fpregs[i].d;
             exp = EXPD(tmp);
             mant = MANTD(tmp);
             if (exp == 0 && mant == 0) {
                 /* zero */
-	        fptag |= 1;
-	    } else if (exp == 0 || exp == MAXEXPD
-                       || (mant & (1LL << 63)) == 0
-                       ) {
+                fptag |= 1;
+            } else if (exp == 0 || exp == MAXEXPD
+                       || (mant & (1LL << 63)) == 0) {
                 /* NaNs, infinity, denormal */
                 fptag |= 2;
             }
@@ -4486,18 +4784,17 @@ void helper_fldenv(target_ulong ptr, int data32)
     int i, fpus, fptag;
 
     if (data32) {
-	env->fpuc = lduw(ptr);
+        env->fpuc = lduw(ptr);
         fpus = lduw(ptr + 4);
         fptag = lduw(ptr + 8);
-    }
-    else {
-	env->fpuc = lduw(ptr);
+    } else {
+        env->fpuc = lduw(ptr);
         fpus = lduw(ptr + 2);
         fptag = lduw(ptr + 4);
     }
     env->fpstt = (fpus >> 11) & 7;
     env->fpus = fpus & ~0x3800;
-    for(i = 0;i < 8; i++) {
+    for (i = 0; i < 8; i++) {
         env->fptags[i] = ((fptag & 3) == 3);
         fptag >>= 2;
     }
@@ -4511,7 +4808,7 @@ void helper_fsave(target_ulong ptr, int data32)
     helper_fstenv(ptr, data32);
 
     ptr += (14 << data32);
-    for(i = 0;i < 8; i++) {
+    for (i = 0; i < 8; i++) {
         tmp = ST(i);
         helper_fstt(tmp, ptr);
         ptr += 10;
@@ -4539,7 +4836,7 @@ void helper_frstor(target_ulong ptr, int data32)
     helper_fldenv(ptr, data32);
     ptr += (14 << data32);
 
-    for(i = 0;i < 8; i++) {
+    for (i = 0; i < 8; i++) {
         tmp = helper_fldt(ptr);
         ST(i) = tmp;
         ptr += 10;
@@ -4602,7 +4899,7 @@ void helper_fxsave(target_ulong ptr, int data64)
 
     fpus = (env->fpus & ~0x3800) | (env->fpstt & 0x7) << 11;
     fptag = 0;
-    for(i = 0; i < 8; i++) {
+    for (i = 0; i < 8; i++) {
         fptag |= (env->fptags[i] << i);
     }
     stw(ptr, env->fpuc);
@@ -4612,7 +4909,7 @@ void helper_fxsave(target_ulong ptr, int data64)
     if (data64) {
         stq(ptr + 0x08, 0); /* rip */
         stq(ptr + 0x10, 0); /* rdp */
-    } else 
+    } else
 #endif
     {
         stl(ptr + 0x08, 0); /* eip */
@@ -4622,7 +4919,7 @@ void helper_fxsave(target_ulong ptr, int data64)
     }
 
     addr = ptr + 0x20;
-    for(i = 0;i < 8; i++) {
+    for (i = 0; i < 8; i++) {
         tmp = ST(i);
         helper_fstt(tmp, addr);
         addr += 16;
@@ -4632,16 +4929,17 @@ void helper_fxsave(target_ulong ptr, int data64)
         /* XXX: finish it */
         stl(ptr + 0x18, env->mxcsr); /* mxcsr */
         stl(ptr + 0x1c, 0x0000ffff); /* mxcsr_mask */
-        if (env->hflags & HF_CS64_MASK)
+        if (env->hflags & HF_CS64_MASK) {
             nb_xmm_regs = 16;
-        else
+        } else {
             nb_xmm_regs = 8;
+        }
         addr = ptr + 0xa0;
         /* Fast FXSAVE leaves out the XMM registers */
         if (!(env->efer & MSR_EFER_FFXSR)
-          || (env->hflags & HF_CPL_MASK)
-          || !(env->hflags & HF_LMA_MASK)) {
-            for(i = 0; i < nb_xmm_regs; i++) {
+            || (env->hflags & HF_CPL_MASK)
+            || !(env->hflags & HF_LMA_MASK)) {
+            for (i = 0; i < nb_xmm_regs; i++) {
                 stq(addr, env->xmm_regs[i].XMM_Q(0));
                 stq(addr + 8, env->xmm_regs[i].XMM_Q(1));
                 addr += 16;
@@ -4667,12 +4965,12 @@ void helper_fxrstor(target_ulong ptr, int data64)
     env->fpstt = (fpus >> 11) & 7;
     env->fpus = fpus & ~0x3800;
     fptag ^= 0xff;
-    for(i = 0;i < 8; i++) {
+    for (i = 0; i < 8; i++) {
         env->fptags[i] = ((fptag >> i) & 1);
     }
 
     addr = ptr + 0x20;
-    for(i = 0;i < 8; i++) {
+    for (i = 0; i < 8; i++) {
         tmp = helper_fldt(addr);
         ST(i) = tmp;
         addr += 16;
@@ -4681,17 +4979,18 @@ void helper_fxrstor(target_ulong ptr, int data64)
     if (env->cr[4] & CR4_OSFXSR_MASK) {
         /* XXX: finish it */
         env->mxcsr = ldl(ptr + 0x18);
-        //ldl(ptr + 0x1c);
-        if (env->hflags & HF_CS64_MASK)
+        /* ldl(ptr + 0x1c); */
+        if (env->hflags & HF_CS64_MASK) {
             nb_xmm_regs = 16;
-        else
+        } else {
             nb_xmm_regs = 8;
+        }
         addr = ptr + 0xa0;
         /* Fast FXRESTORE leaves out the XMM registers */
         if (!(env->efer & MSR_EFER_FFXSR)
-          || (env->hflags & HF_CPL_MASK)
-          || !(env->hflags & HF_LMA_MASK)) {
-            for(i = 0; i < nb_xmm_regs; i++) {
+            || (env->hflags & HF_CPL_MASK)
+            || !(env->hflags & HF_LMA_MASK)) {
+            for (i = 0; i < nb_xmm_regs; i++) {
                 env->xmm_regs[i].XMM_Q(0) = ldq(addr);
                 env->xmm_regs[i].XMM_Q(1) = ldq(addr + 8);
                 addr += 16;
@@ -4719,22 +5018,20 @@ floatx80 cpu_set_fp80(uint64_t mant, uint16_t upper)
 }
 
 #ifdef TARGET_X86_64
-
-//#define DEBUG_MULDIV
-
 static void add128(uint64_t *plow, uint64_t *phigh, uint64_t a, uint64_t b)
 {
     *plow += a;
     /* carry test */
-    if (*plow < a)
+    if (*plow < a) {
         (*phigh)++;
+    }
     *phigh += b;
 }
 
 static void neg128(uint64_t *plow, uint64_t *phigh)
 {
-    *plow = ~ *plow;
-    *phigh = ~ *phigh;
+    *plow = ~*plow;
+    *phigh = ~*phigh;
     add128(plow, phigh, 1, 0);
 }
 
@@ -4752,10 +5049,11 @@ static int div64(uint64_t *plow, uint64_t *phigh, uint64_t b)
         *plow = q;
         *phigh = r;
     } else {
-        if (a1 >= b)
+        if (a1 >= b) {
             return 1;
+        }
         /* XXX: use a better algorithm */
-        for(i = 0; i < 64; i++) {
+        for (i = 0; i < 64; i++) {
             ab = a1 >> 63;
             a1 = (a1 << 1) | (a0 >> 63);
             if (ab || a1 >= b) {
@@ -4767,7 +5065,8 @@ static int div64(uint64_t *plow, uint64_t *phigh, uint64_t b)
             a0 = (a0 << 1) | qb;
         }
 #if defined(DEBUG_MULDIV)
-        printf("div: 0x%016" PRIx64 "%016" PRIx64 " / 0x%016" PRIx64 ": q=0x%016" PRIx64 " r=0x%016" PRIx64 "\n",
+        printf("div: 0x%016" PRIx64 "%016" PRIx64 " / 0x%016" PRIx64
+               ": q=0x%016" PRIx64 " r=0x%016" PRIx64 "\n",
                *phigh, *plow, b, a0, a1);
 #endif
         *plow = a0;
@@ -4780,24 +5079,31 @@ static int div64(uint64_t *plow, uint64_t *phigh, uint64_t b)
 static int idiv64(uint64_t *plow, uint64_t *phigh, int64_t b)
 {
     int sa, sb;
+
     sa = ((int64_t)*phigh < 0);
-    if (sa)
+    if (sa) {
         neg128(plow, phigh);
+    }
     sb = (b < 0);
-    if (sb)
+    if (sb) {
         b = -b;
-    if (div64(plow, phigh, b) != 0)
+    }
+    if (div64(plow, phigh, b) != 0) {
         return 1;
+    }
     if (sa ^ sb) {
-        if (*plow > (1ULL << 63))
+        if (*plow > (1ULL << 63)) {
             return 1;
-        *plow = - *plow;
+        }
+        *plow = -*plow;
     } else {
-        if (*plow >= (1ULL << 63))
+        if (*plow >= (1ULL << 63)) {
             return 1;
+        }
+    }
+    if (sa) {
+        *phigh = -*phigh;
     }
-    if (sa)
-        *phigh = - *phigh;
     return 0;
 }
 
@@ -4836,13 +5142,15 @@ target_ulong helper_imulq_T0_T1(target_ulong t0, target_ulong t1)
 void helper_divq_EAX(target_ulong t0)
 {
     uint64_t r0, r1;
+
     if (t0 == 0) {
         raise_exception(EXCP00_DIVZ);
     }
     r0 = EAX;
     r1 = EDX;
-    if (div64(&r0, &r1, t0))
+    if (div64(&r0, &r1, t0)) {
         raise_exception(EXCP00_DIVZ);
+    }
     EAX = r0;
     EDX = r1;
 }
@@ -4850,13 +5158,15 @@ void helper_divq_EAX(target_ulong t0)
 void helper_idivq_EAX(target_ulong t0)
 {
     uint64_t r0, r1;
+
     if (t0 == 0) {
         raise_exception(EXCP00_DIVZ);
     }
     r0 = EAX;
     r1 = EDX;
-    if (idiv64(&r0, &r1, t0))
+    if (idiv64(&r0, &r1, t0)) {
         raise_exception(EXCP00_DIVZ);
+    }
     EAX = r0;
     EDX = r1;
 }
@@ -4874,22 +5184,24 @@ void helper_hlt(int next_eip_addend)
 {
     helper_svm_check_intercept_param(SVM_EXIT_HLT, 0);
     EIP += next_eip_addend;
-    
+
     do_hlt();
 }
 
 void helper_monitor(target_ulong ptr)
 {
-    if ((uint32_t)ECX != 0)
+    if ((uint32_t)ECX != 0) {
         raise_exception(EXCP0D_GPF);
-    /* XXX: store address ? */
+    }
+    /* XXX: store address? */
     helper_svm_check_intercept_param(SVM_EXIT_MONITOR, 0);
 }
 
 void helper_mwait(int next_eip_addend)
 {
-    if ((uint32_t)ECX != 0)
+    if ((uint32_t)ECX != 0) {
         raise_exception(EXCP0D_GPF);
+    }
     helper_svm_check_intercept_param(SVM_EXIT_MWAIT, 0);
     EIP += next_eip_addend;
 
@@ -4962,6 +5274,7 @@ void helper_reset_inhibit_irq(void)
 void helper_boundw(target_ulong a0, int v)
 {
     int low, high;
+
     low = ldsw(a0);
     high = ldsw(a0 + 2);
     v = (int16_t)v;
@@ -4973,6 +5286,7 @@ void helper_boundw(target_ulong a0, int v)
 void helper_boundl(target_ulong a0, int v)
 {
     int low, high;
+
     low = ldl(a0);
     high = ldl(a0 + 4);
     if (v < low || v > high) {
@@ -5035,32 +5349,41 @@ void tlb_fill(CPUX86State *env1, target_ulong addr, int is_write, int mmu_idx,
 #if defined(CONFIG_USER_ONLY)
 
 void helper_vmrun(int aflag, int next_eip_addend)
-{ 
+{
 }
-void helper_vmmcall(void) 
-{ 
+
+void helper_vmmcall(void)
+{
 }
+
 void helper_vmload(int aflag)
-{ 
+{
 }
+
 void helper_vmsave(int aflag)
-{ 
+{
 }
+
 void helper_stgi(void)
 {
 }
+
 void helper_clgi(void)
 {
 }
-void helper_skinit(void) 
-{ 
+
+void helper_skinit(void)
+{
 }
+
 void helper_invlpga(int aflag)
-{ 
+{
 }
-void helper_vmexit(uint32_t exit_code, uint64_t exit_info_1) 
-{ 
+
+void helper_vmexit(uint32_t exit_code, uint64_t exit_info_1)
+{
 }
+
 void helper_svm_check_intercept_param(uint32_t type, uint64_t param)
 {
 }
@@ -5069,7 +5392,7 @@ void svm_check_intercept(CPUX86State *env1, uint32_t type)
 {
 }
 
-void helper_svm_check_io(uint32_t port, uint32_t param, 
+void helper_svm_check_io(uint32_t port, uint32_t param,
                          uint32_t next_eip_addend)
 {
 }
@@ -5078,16 +5401,16 @@ void helper_svm_check_io(uint32_t port, uint32_t param,
 static inline void svm_save_seg(target_phys_addr_t addr,
                                 const SegmentCache *sc)
 {
-    stw_phys(addr + offsetof(struct vmcb_seg, selector), 
+    stw_phys(addr + offsetof(struct vmcb_seg, selector),
              sc->selector);
-    stq_phys(addr + offsetof(struct vmcb_seg, base), 
+    stq_phys(addr + offsetof(struct vmcb_seg, base),
              sc->base);
-    stl_phys(addr + offsetof(struct vmcb_seg, limit), 
+    stl_phys(addr + offsetof(struct vmcb_seg, limit),
              sc->limit);
-    stw_phys(addr + offsetof(struct vmcb_seg, attrib), 
+    stw_phys(addr + offsetof(struct vmcb_seg, attrib),
              ((sc->flags >> 8) & 0xff) | ((sc->flags >> 12) & 0x0f00));
 }
-                                
+
 static inline void svm_load_seg(target_phys_addr_t addr, SegmentCache *sc)
 {
     unsigned int flags;
@@ -5099,10 +5422,11 @@ static inline void svm_load_seg(target_phys_addr_t addr, SegmentCache *sc)
     sc->flags = ((flags & 0xff) << 8) | ((flags & 0x0f00) << 12);
 }
 
-static inline void svm_load_seg_cache(target_phys_addr_t addr, 
+static inline void svm_load_seg_cache(target_phys_addr_t addr,
                                       CPUX86State *env, int seg_reg)
 {
     SegmentCache sc1, *sc = &sc1;
+
     svm_load_seg(addr, sc);
     cpu_x86_load_seg_cache(env, seg_reg, sc->selector,
                            sc->base, sc->limit, sc->flags);
@@ -5116,21 +5440,26 @@ void helper_vmrun(int aflag, int next_eip_addend)
 
     helper_svm_check_intercept_param(SVM_EXIT_VMRUN, 0);
 
-    if (aflag == 2)
+    if (aflag == 2) {
         addr = EAX;
-    else
+    } else {
         addr = (uint32_t)EAX;
+    }
 
     qemu_log_mask(CPU_LOG_TB_IN_ASM, "vmrun! " TARGET_FMT_lx "\n", addr);
 
     env->vm_vmcb = addr;
 
     /* save the current CPU state in the hsave page */
-    stq_phys(env->vm_hsave + offsetof(struct vmcb, save.gdtr.base), env->gdt.base);
-    stl_phys(env->vm_hsave + offsetof(struct vmcb, save.gdtr.limit), env->gdt.limit);
+    stq_phys(env->vm_hsave + offsetof(struct vmcb, save.gdtr.base),
+             env->gdt.base);
+    stl_phys(env->vm_hsave + offsetof(struct vmcb, save.gdtr.limit),
+             env->gdt.limit);
 
-    stq_phys(env->vm_hsave + offsetof(struct vmcb, save.idtr.base), env->idt.base);
-    stl_phys(env->vm_hsave + offsetof(struct vmcb, save.idtr.limit), env->idt.limit);
+    stq_phys(env->vm_hsave + offsetof(struct vmcb, save.idtr.base),
+             env->idt.base);
+    stl_phys(env->vm_hsave + offsetof(struct vmcb, save.idtr.limit),
+             env->idt.limit);
 
     stq_phys(env->vm_hsave + offsetof(struct vmcb, save.cr0), env->cr[0]);
     stq_phys(env->vm_hsave + offsetof(struct vmcb, save.cr2), env->cr[2]);
@@ -5140,15 +5469,16 @@ void helper_vmrun(int aflag, int next_eip_addend)
     stq_phys(env->vm_hsave + offsetof(struct vmcb, save.dr7), env->dr[7]);
 
     stq_phys(env->vm_hsave + offsetof(struct vmcb, save.efer), env->efer);
-    stq_phys(env->vm_hsave + offsetof(struct vmcb, save.rflags), compute_eflags());
+    stq_phys(env->vm_hsave + offsetof(struct vmcb, save.rflags),
+             compute_eflags());
 
-    svm_save_seg(env->vm_hsave + offsetof(struct vmcb, save.es), 
-                  &env->segs[R_ES]);
-    svm_save_seg(env->vm_hsave + offsetof(struct vmcb, save.cs), 
+    svm_save_seg(env->vm_hsave + offsetof(struct vmcb, save.es),
+                 &env->segs[R_ES]);
+    svm_save_seg(env->vm_hsave + offsetof(struct vmcb, save.cs),
                  &env->segs[R_CS]);
-    svm_save_seg(env->vm_hsave + offsetof(struct vmcb, save.ss), 
+    svm_save_seg(env->vm_hsave + offsetof(struct vmcb, save.ss),
                  &env->segs[R_SS]);
-    svm_save_seg(env->vm_hsave + offsetof(struct vmcb, save.ds), 
+    svm_save_seg(env->vm_hsave + offsetof(struct vmcb, save.ds),
                  &env->segs[R_DS]);
 
     stq_phys(env->vm_hsave + offsetof(struct vmcb, save.rip),
@@ -5158,41 +5488,62 @@ void helper_vmrun(int aflag, int next_eip_addend)
 
     /* load the interception bitmaps so we do not need to access the
        vmcb in svm mode */
-    env->intercept            = ldq_phys(env->vm_vmcb + offsetof(struct vmcb, control.intercept));
-    env->intercept_cr_read    = lduw_phys(env->vm_vmcb + offsetof(struct vmcb, control.intercept_cr_read));
-    env->intercept_cr_write   = lduw_phys(env->vm_vmcb + offsetof(struct vmcb, control.intercept_cr_write));
-    env->intercept_dr_read    = lduw_phys(env->vm_vmcb + offsetof(struct vmcb, control.intercept_dr_read));
-    env->intercept_dr_write   = lduw_phys(env->vm_vmcb + offsetof(struct vmcb, control.intercept_dr_write));
-    env->intercept_exceptions = ldl_phys(env->vm_vmcb + offsetof(struct vmcb, control.intercept_exceptions));
+    env->intercept = ldq_phys(env->vm_vmcb + offsetof(struct vmcb,
+                                                      control.intercept));
+    env->intercept_cr_read = lduw_phys(env->vm_vmcb +
+                                       offsetof(struct vmcb,
+                                                control.intercept_cr_read));
+    env->intercept_cr_write = lduw_phys(env->vm_vmcb +
+                                        offsetof(struct vmcb,
+                                                 control.intercept_cr_write));
+    env->intercept_dr_read = lduw_phys(env->vm_vmcb +
+                                       offsetof(struct vmcb,
+                                                control.intercept_dr_read));
+    env->intercept_dr_write = lduw_phys(env->vm_vmcb +
+                                        offsetof(struct vmcb,
+                                                 control.intercept_dr_write));
+    env->intercept_exceptions = ldl_phys(env->vm_vmcb +
+                                         offsetof(struct vmcb,
+                                                  control.intercept_exceptions
+                                                  ));
 
     /* enable intercepts */
     env->hflags |= HF_SVMI_MASK;
 
-    env->tsc_offset = ldq_phys(env->vm_vmcb + offsetof(struct vmcb, control.tsc_offset));
+    env->tsc_offset = ldq_phys(env->vm_vmcb +
+                               offsetof(struct vmcb, control.tsc_offset));
 
-    env->gdt.base  = ldq_phys(env->vm_vmcb + offsetof(struct vmcb, save.gdtr.base));
-    env->gdt.limit = ldl_phys(env->vm_vmcb + offsetof(struct vmcb, save.gdtr.limit));
+    env->gdt.base  = ldq_phys(env->vm_vmcb + offsetof(struct vmcb,
+                                                      save.gdtr.base));
+    env->gdt.limit = ldl_phys(env->vm_vmcb + offsetof(struct vmcb,
+                                                      save.gdtr.limit));
 
-    env->idt.base  = ldq_phys(env->vm_vmcb + offsetof(struct vmcb, save.idtr.base));
-    env->idt.limit = ldl_phys(env->vm_vmcb + offsetof(struct vmcb, save.idtr.limit));
+    env->idt.base  = ldq_phys(env->vm_vmcb + offsetof(struct vmcb,
+                                                      save.idtr.base));
+    env->idt.limit = ldl_phys(env->vm_vmcb + offsetof(struct vmcb,
+                                                      save.idtr.limit));
 
     /* clear exit_info_2 so we behave like the real hardware */
     stq_phys(env->vm_vmcb + offsetof(struct vmcb, control.exit_info_2), 0);
 
-    cpu_x86_update_cr0(env, ldq_phys(env->vm_vmcb + offsetof(struct vmcb, save.cr0)));
-    cpu_x86_update_cr4(env, ldq_phys(env->vm_vmcb + offsetof(struct vmcb, save.cr4)));
-    cpu_x86_update_cr3(env, ldq_phys(env->vm_vmcb + offsetof(struct vmcb, save.cr3)));
+    cpu_x86_update_cr0(env, ldq_phys(env->vm_vmcb + offsetof(struct vmcb,
+                                                             save.cr0)));
+    cpu_x86_update_cr4(env, ldq_phys(env->vm_vmcb + offsetof(struct vmcb,
+                                                             save.cr4)));
+    cpu_x86_update_cr3(env, ldq_phys(env->vm_vmcb + offsetof(struct vmcb,
+                                                             save.cr3)));
     env->cr[2] = ldq_phys(env->vm_vmcb + offsetof(struct vmcb, save.cr2));
     int_ctl = ldl_phys(env->vm_vmcb + offsetof(struct vmcb, control.int_ctl));
     env->hflags2 &= ~(HF2_HIF_MASK | HF2_VINTR_MASK);
     if (int_ctl & V_INTR_MASKING_MASK) {
         env->v_tpr = int_ctl & V_TPR_MASK;
         env->hflags2 |= HF2_VINTR_MASK;
-        if (env->eflags & IF_MASK)
+        if (env->eflags & IF_MASK) {
             env->hflags2 |= HF2_HIF_MASK;
+        }
     }
 
-    cpu_load_efer(env, 
+    cpu_load_efer(env,
                   ldq_phys(env->vm_vmcb + offsetof(struct vmcb, save.efer)));
     env->eflags = 0;
     load_eflags(ldq_phys(env->vm_vmcb + offsetof(struct vmcb, save.rflags)),
@@ -5214,16 +5565,17 @@ void helper_vmrun(int aflag, int next_eip_addend)
     EAX = ldq_phys(env->vm_vmcb + offsetof(struct vmcb, save.rax));
     env->dr[7] = ldq_phys(env->vm_vmcb + offsetof(struct vmcb, save.dr7));
     env->dr[6] = ldq_phys(env->vm_vmcb + offsetof(struct vmcb, save.dr6));
-    cpu_x86_set_cpl(env, ldub_phys(env->vm_vmcb + offsetof(struct vmcb, save.cpl)));
+    cpu_x86_set_cpl(env, ldub_phys(env->vm_vmcb + offsetof(struct vmcb,
+                                                           save.cpl)));
 
     /* FIXME: guest state consistency checks */
 
-    switch(ldub_phys(env->vm_vmcb + offsetof(struct vmcb, control.tlb_ctl))) {
-        case TLB_CONTROL_DO_NOTHING:
-            break;
-        case TLB_CONTROL_FLUSH_ALL_ASID:
-            /* FIXME: this is not 100% correct but should work for now */
-            tlb_flush(env, 1);
+    switch (ldub_phys(env->vm_vmcb + offsetof(struct vmcb, control.tlb_ctl))) {
+    case TLB_CONTROL_DO_NOTHING:
+        break;
+    case TLB_CONTROL_FLUSH_ALL_ASID:
+        /* FIXME: this is not 100% correct but should work for now */
+        tlb_flush(env, 1);
         break;
     }
 
@@ -5234,50 +5586,54 @@ void helper_vmrun(int aflag, int next_eip_addend)
     }
 
     /* maybe we need to inject an event */
-    event_inj = ldl_phys(env->vm_vmcb + offsetof(struct vmcb, control.event_inj));
+    event_inj = ldl_phys(env->vm_vmcb + offsetof(struct vmcb,
+                                                 control.event_inj));
     if (event_inj & SVM_EVTINJ_VALID) {
         uint8_t vector = event_inj & SVM_EVTINJ_VEC_MASK;
         uint16_t valid_err = event_inj & SVM_EVTINJ_VALID_ERR;
-        uint32_t event_inj_err = ldl_phys(env->vm_vmcb + offsetof(struct vmcb, control.event_inj_err));
+        uint32_t event_inj_err = ldl_phys(env->vm_vmcb +
+                                          offsetof(struct vmcb,
+                                                   control.event_inj_err));
 
         qemu_log_mask(CPU_LOG_TB_IN_ASM, "Injecting(%#hx): ", valid_err);
         /* FIXME: need to implement valid_err */
         switch (event_inj & SVM_EVTINJ_TYPE_MASK) {
         case SVM_EVTINJ_TYPE_INTR:
-                env->exception_index = vector;
-                env->error_code = event_inj_err;
-                env->exception_is_int = 0;
-                env->exception_next_eip = -1;
-                qemu_log_mask(CPU_LOG_TB_IN_ASM, "INTR");
-                /* XXX: is it always correct ? */
-                do_interrupt_all(vector, 0, 0, 0, 1);
-                break;
+            env->exception_index = vector;
+            env->error_code = event_inj_err;
+            env->exception_is_int = 0;
+            env->exception_next_eip = -1;
+            qemu_log_mask(CPU_LOG_TB_IN_ASM, "INTR");
+            /* XXX: is it always correct? */
+            do_interrupt_all(vector, 0, 0, 0, 1);
+            break;
         case SVM_EVTINJ_TYPE_NMI:
-                env->exception_index = EXCP02_NMI;
-                env->error_code = event_inj_err;
-                env->exception_is_int = 0;
-                env->exception_next_eip = EIP;
-                qemu_log_mask(CPU_LOG_TB_IN_ASM, "NMI");
-                cpu_loop_exit(env);
-                break;
+            env->exception_index = EXCP02_NMI;
+            env->error_code = event_inj_err;
+            env->exception_is_int = 0;
+            env->exception_next_eip = EIP;
+            qemu_log_mask(CPU_LOG_TB_IN_ASM, "NMI");
+            cpu_loop_exit(env);
+            break;
         case SVM_EVTINJ_TYPE_EXEPT:
-                env->exception_index = vector;
-                env->error_code = event_inj_err;
-                env->exception_is_int = 0;
-                env->exception_next_eip = -1;
-                qemu_log_mask(CPU_LOG_TB_IN_ASM, "EXEPT");
-                cpu_loop_exit(env);
-                break;
+            env->exception_index = vector;
+            env->error_code = event_inj_err;
+            env->exception_is_int = 0;
+            env->exception_next_eip = -1;
+            qemu_log_mask(CPU_LOG_TB_IN_ASM, "EXEPT");
+            cpu_loop_exit(env);
+            break;
         case SVM_EVTINJ_TYPE_SOFT:
-                env->exception_index = vector;
-                env->error_code = event_inj_err;
-                env->exception_is_int = 1;
-                env->exception_next_eip = EIP;
-                qemu_log_mask(CPU_LOG_TB_IN_ASM, "SOFT");
-                cpu_loop_exit(env);
-                break;
+            env->exception_index = vector;
+            env->error_code = event_inj_err;
+            env->exception_is_int = 1;
+            env->exception_next_eip = EIP;
+            qemu_log_mask(CPU_LOG_TB_IN_ASM, "SOFT");
+            cpu_loop_exit(env);
+            break;
         }
-        qemu_log_mask(CPU_LOG_TB_IN_ASM, " %#x %#x\n", env->exception_index, env->error_code);
+        qemu_log_mask(CPU_LOG_TB_IN_ASM, " %#x %#x\n", env->exception_index,
+                      env->error_code);
     }
 }
 
@@ -5290,16 +5646,19 @@ void helper_vmmcall(void)
 void helper_vmload(int aflag)
 {
     target_ulong addr;
+
     helper_svm_check_intercept_param(SVM_EXIT_VMLOAD, 0);
 
-    if (aflag == 2)
+    if (aflag == 2) {
         addr = EAX;
-    else
+    } else {
         addr = (uint32_t)EAX;
+    }
 
-    qemu_log_mask(CPU_LOG_TB_IN_ASM, "vmload! " TARGET_FMT_lx "\nFS: %016" PRIx64 " | " TARGET_FMT_lx "\n",
-                addr, ldq_phys(addr + offsetof(struct vmcb, save.fs.base)),
-                env->segs[R_FS].base);
+    qemu_log_mask(CPU_LOG_TB_IN_ASM, "vmload! " TARGET_FMT_lx
+                  "\nFS: %016" PRIx64 " | " TARGET_FMT_lx "\n",
+                  addr, ldq_phys(addr + offsetof(struct vmcb, save.fs.base)),
+                  env->segs[R_FS].base);
 
     svm_load_seg_cache(addr + offsetof(struct vmcb, save.fs),
                        env, R_FS);
@@ -5311,50 +5670,59 @@ void helper_vmload(int aflag)
                  &env->ldt);
 
 #ifdef TARGET_X86_64
-    env->kernelgsbase = ldq_phys(addr + offsetof(struct vmcb, save.kernel_gs_base));
+    env->kernelgsbase = ldq_phys(addr + offsetof(struct vmcb,
+                                                 save.kernel_gs_base));
     env->lstar = ldq_phys(addr + offsetof(struct vmcb, save.lstar));
     env->cstar = ldq_phys(addr + offsetof(struct vmcb, save.cstar));
     env->fmask = ldq_phys(addr + offsetof(struct vmcb, save.sfmask));
 #endif
     env->star = ldq_phys(addr + offsetof(struct vmcb, save.star));
     env->sysenter_cs = ldq_phys(addr + offsetof(struct vmcb, save.sysenter_cs));
-    env->sysenter_esp = ldq_phys(addr + offsetof(struct vmcb, save.sysenter_esp));
-    env->sysenter_eip = ldq_phys(addr + offsetof(struct vmcb, save.sysenter_eip));
+    env->sysenter_esp = ldq_phys(addr + offsetof(struct vmcb,
+                                                 save.sysenter_esp));
+    env->sysenter_eip = ldq_phys(addr + offsetof(struct vmcb,
+                                                 save.sysenter_eip));
 }
 
 void helper_vmsave(int aflag)
 {
     target_ulong addr;
+
     helper_svm_check_intercept_param(SVM_EXIT_VMSAVE, 0);
 
-    if (aflag == 2)
+    if (aflag == 2) {
         addr = EAX;
-    else
+    } else {
         addr = (uint32_t)EAX;
+    }
 
-    qemu_log_mask(CPU_LOG_TB_IN_ASM, "vmsave! " TARGET_FMT_lx "\nFS: %016" PRIx64 " | " TARGET_FMT_lx "\n",
-                addr, ldq_phys(addr + offsetof(struct vmcb, save.fs.base)),
-                env->segs[R_FS].base);
+    qemu_log_mask(CPU_LOG_TB_IN_ASM, "vmsave! " TARGET_FMT_lx
+                  "\nFS: %016" PRIx64 " | " TARGET_FMT_lx "\n",
+                  addr, ldq_phys(addr + offsetof(struct vmcb, save.fs.base)),
+                  env->segs[R_FS].base);
 
-    svm_save_seg(addr + offsetof(struct vmcb, save.fs), 
+    svm_save_seg(addr + offsetof(struct vmcb, save.fs),
                  &env->segs[R_FS]);
-    svm_save_seg(addr + offsetof(struct vmcb, save.gs), 
+    svm_save_seg(addr + offsetof(struct vmcb, save.gs),
                  &env->segs[R_GS]);
-    svm_save_seg(addr + offsetof(struct vmcb, save.tr), 
+    svm_save_seg(addr + offsetof(struct vmcb, save.tr),
                  &env->tr);
-    svm_save_seg(addr + offsetof(struct vmcb, save.ldtr), 
+    svm_save_seg(addr + offsetof(struct vmcb, save.ldtr),
                  &env->ldt);
 
 #ifdef TARGET_X86_64
-    stq_phys(addr + offsetof(struct vmcb, save.kernel_gs_base), env->kernelgsbase);
+    stq_phys(addr + offsetof(struct vmcb, save.kernel_gs_base),
+             env->kernelgsbase);
     stq_phys(addr + offsetof(struct vmcb, save.lstar), env->lstar);
     stq_phys(addr + offsetof(struct vmcb, save.cstar), env->cstar);
     stq_phys(addr + offsetof(struct vmcb, save.sfmask), env->fmask);
 #endif
     stq_phys(addr + offsetof(struct vmcb, save.star), env->star);
     stq_phys(addr + offsetof(struct vmcb, save.sysenter_cs), env->sysenter_cs);
-    stq_phys(addr + offsetof(struct vmcb, save.sysenter_esp), env->sysenter_esp);
-    stq_phys(addr + offsetof(struct vmcb, save.sysenter_eip), env->sysenter_eip);
+    stq_phys(addr + offsetof(struct vmcb, save.sysenter_esp),
+             env->sysenter_esp);
+    stq_phys(addr + offsetof(struct vmcb, save.sysenter_eip),
+             env->sysenter_eip);
 }
 
 void helper_stgi(void)
@@ -5379,12 +5747,14 @@ void helper_skinit(void)
 void helper_invlpga(int aflag)
 {
     target_ulong addr;
+
     helper_svm_check_intercept_param(SVM_EXIT_INVLPGA, 0);
-    
-    if (aflag == 2)
+
+    if (aflag == 2) {
         addr = EAX;
-    else
+    } else {
         addr = (uint32_t)EAX;
+    }
 
     /* XXX: could use the ASID to see if it is needed to do the
        flush */
@@ -5393,9 +5763,10 @@ void helper_invlpga(int aflag)
 
 void helper_svm_check_intercept_param(uint32_t type, uint64_t param)
 {
-    if (likely(!(env->hflags & HF_SVMI_MASK)))
+    if (likely(!(env->hflags & HF_SVMI_MASK))) {
         return;
-    switch(type) {
+    }
+    switch (type) {
     case SVM_EXIT_READ_CR0 ... SVM_EXIT_READ_CR0 + 8:
         if (env->intercept_cr_read & (1 << (type - SVM_EXIT_READ_CR0))) {
             helper_vmexit(type, param);
@@ -5424,9 +5795,12 @@ void helper_svm_check_intercept_param(uint32_t type, uint64_t param)
     case SVM_EXIT_MSR:
         if (env->intercept & (1ULL << (SVM_EXIT_MSR - SVM_EXIT_INTR))) {
             /* FIXME: this should be read in at vmrun (faster this way?) */
-            uint64_t addr = ldq_phys(env->vm_vmcb + offsetof(struct vmcb, control.msrpm_base_pa));
+            uint64_t addr = ldq_phys(env->vm_vmcb +
+                                     offsetof(struct vmcb,
+                                              control.msrpm_base_pa));
             uint32_t t0, t1;
-            switch((uint32_t)ECX) {
+
+            switch ((uint32_t)ECX) {
             case 0 ... 0x1fff:
                 t0 = (ECX * 2) % 8;
                 t1 = (ECX * 2) / 8;
@@ -5447,8 +5821,9 @@ void helper_svm_check_intercept_param(uint32_t type, uint64_t param)
                 t1 = 0;
                 break;
             }
-            if (ldub_phys(addr + t1) & ((1 << param) << t0))
+            if (ldub_phys(addr + t1) & ((1 << param) << t0)) {
                 helper_vmexit(type, param);
+            }
         }
         break;
     default:
@@ -5469,16 +5844,18 @@ void svm_check_intercept(CPUX86State *env1, uint32_t type)
     env = saved_env;
 }
 
-void helper_svm_check_io(uint32_t port, uint32_t param, 
+void helper_svm_check_io(uint32_t port, uint32_t param,
                          uint32_t next_eip_addend)
 {
     if (env->intercept & (1ULL << (SVM_EXIT_IOIO - SVM_EXIT_INTR))) {
         /* FIXME: this should be read in at vmrun (faster this way?) */
-        uint64_t addr = ldq_phys(env->vm_vmcb + offsetof(struct vmcb, control.iopm_base_pa));
+        uint64_t addr = ldq_phys(env->vm_vmcb +
+                                 offsetof(struct vmcb, control.iopm_base_pa));
         uint16_t mask = (1 << ((param >> 4) & 7)) - 1;
-        if(lduw_phys(addr + port / 8) & (mask << (port & 7))) {
+
+        if (lduw_phys(addr + port / 8) & (mask << (port & 7))) {
             /* next EIP */
-            stq_phys(env->vm_vmcb + offsetof(struct vmcb, control.exit_info_2), 
+            stq_phys(env->vm_vmcb + offsetof(struct vmcb, control.exit_info_2),
                      env->eip + next_eip_addend);
             helper_vmexit(SVM_EXIT_IOIO, param | (port << 16));
         }
@@ -5490,33 +5867,40 @@ void helper_vmexit(uint32_t exit_code, uint64_t exit_info_1)
 {
     uint32_t int_ctl;
 
-    qemu_log_mask(CPU_LOG_TB_IN_ASM, "vmexit(%08x, %016" PRIx64 ", %016" PRIx64 ", " TARGET_FMT_lx ")!\n",
-                exit_code, exit_info_1,
-                ldq_phys(env->vm_vmcb + offsetof(struct vmcb, control.exit_info_2)),
-                EIP);
+    qemu_log_mask(CPU_LOG_TB_IN_ASM, "vmexit(%08x, %016" PRIx64 ", %016"
+                  PRIx64 ", " TARGET_FMT_lx ")!\n",
+                  exit_code, exit_info_1,
+                  ldq_phys(env->vm_vmcb + offsetof(struct vmcb,
+                                                   control.exit_info_2)),
+                  EIP);
 
-    if(env->hflags & HF_INHIBIT_IRQ_MASK) {
-        stl_phys(env->vm_vmcb + offsetof(struct vmcb, control.int_state), SVM_INTERRUPT_SHADOW_MASK);
+    if (env->hflags & HF_INHIBIT_IRQ_MASK) {
+        stl_phys(env->vm_vmcb + offsetof(struct vmcb, control.int_state),
+                 SVM_INTERRUPT_SHADOW_MASK);
         env->hflags &= ~HF_INHIBIT_IRQ_MASK;
     } else {
         stl_phys(env->vm_vmcb + offsetof(struct vmcb, control.int_state), 0);
     }
 
     /* Save the VM state in the vmcb */
-    svm_save_seg(env->vm_vmcb + offsetof(struct vmcb, save.es), 
+    svm_save_seg(env->vm_vmcb + offsetof(struct vmcb, save.es),
                  &env->segs[R_ES]);
-    svm_save_seg(env->vm_vmcb + offsetof(struct vmcb, save.cs), 
+    svm_save_seg(env->vm_vmcb + offsetof(struct vmcb, save.cs),
                  &env->segs[R_CS]);
-    svm_save_seg(env->vm_vmcb + offsetof(struct vmcb, save.ss), 
+    svm_save_seg(env->vm_vmcb + offsetof(struct vmcb, save.ss),
                  &env->segs[R_SS]);
-    svm_save_seg(env->vm_vmcb + offsetof(struct vmcb, save.ds), 
+    svm_save_seg(env->vm_vmcb + offsetof(struct vmcb, save.ds),
                  &env->segs[R_DS]);
 
-    stq_phys(env->vm_vmcb + offsetof(struct vmcb, save.gdtr.base), env->gdt.base);
-    stl_phys(env->vm_vmcb + offsetof(struct vmcb, save.gdtr.limit), env->gdt.limit);
+    stq_phys(env->vm_vmcb + offsetof(struct vmcb, save.gdtr.base),
+             env->gdt.base);
+    stl_phys(env->vm_vmcb + offsetof(struct vmcb, save.gdtr.limit),
+             env->gdt.limit);
 
-    stq_phys(env->vm_vmcb + offsetof(struct vmcb, save.idtr.base), env->idt.base);
-    stl_phys(env->vm_vmcb + offsetof(struct vmcb, save.idtr.limit), env->idt.limit);
+    stq_phys(env->vm_vmcb + offsetof(struct vmcb, save.idtr.base),
+             env->idt.base);
+    stl_phys(env->vm_vmcb + offsetof(struct vmcb, save.idtr.limit),
+             env->idt.limit);
 
     stq_phys(env->vm_vmcb + offsetof(struct vmcb, save.efer), env->efer);
     stq_phys(env->vm_vmcb + offsetof(struct vmcb, save.cr0), env->cr[0]);
@@ -5527,17 +5911,20 @@ void helper_vmexit(uint32_t exit_code, uint64_t exit_info_1)
     int_ctl = ldl_phys(env->vm_vmcb + offsetof(struct vmcb, control.int_ctl));
     int_ctl &= ~(V_TPR_MASK | V_IRQ_MASK);
     int_ctl |= env->v_tpr & V_TPR_MASK;
-    if (env->interrupt_request & CPU_INTERRUPT_VIRQ)
+    if (env->interrupt_request & CPU_INTERRUPT_VIRQ) {
         int_ctl |= V_IRQ_MASK;
+    }
     stl_phys(env->vm_vmcb + offsetof(struct vmcb, control.int_ctl), int_ctl);
 
-    stq_phys(env->vm_vmcb + offsetof(struct vmcb, save.rflags), compute_eflags());
+    stq_phys(env->vm_vmcb + offsetof(struct vmcb, save.rflags),
+             compute_eflags());
     stq_phys(env->vm_vmcb + offsetof(struct vmcb, save.rip), env->eip);
     stq_phys(env->vm_vmcb + offsetof(struct vmcb, save.rsp), ESP);
     stq_phys(env->vm_vmcb + offsetof(struct vmcb, save.rax), EAX);
     stq_phys(env->vm_vmcb + offsetof(struct vmcb, save.dr7), env->dr[7]);
     stq_phys(env->vm_vmcb + offsetof(struct vmcb, save.dr6), env->dr[6]);
-    stb_phys(env->vm_vmcb + offsetof(struct vmcb, save.cpl), env->hflags & HF_CPL_MASK);
+    stb_phys(env->vm_vmcb + offsetof(struct vmcb, save.cpl),
+             env->hflags & HF_CPL_MASK);
 
     /* Reload the host state from vm_hsave */
     env->hflags2 &= ~(HF2_HIF_MASK | HF2_VINTR_MASK);
@@ -5547,19 +5934,27 @@ void helper_vmexit(uint32_t exit_code, uint64_t exit_info_1)
     env->interrupt_request &= ~CPU_INTERRUPT_VIRQ;
     env->tsc_offset = 0;
 
-    env->gdt.base  = ldq_phys(env->vm_hsave + offsetof(struct vmcb, save.gdtr.base));
-    env->gdt.limit = ldl_phys(env->vm_hsave + offsetof(struct vmcb, save.gdtr.limit));
-
-    env->idt.base  = ldq_phys(env->vm_hsave + offsetof(struct vmcb, save.idtr.base));
-    env->idt.limit = ldl_phys(env->vm_hsave + offsetof(struct vmcb, save.idtr.limit));
-
-    cpu_x86_update_cr0(env, ldq_phys(env->vm_hsave + offsetof(struct vmcb, save.cr0)) | CR0_PE_MASK);
-    cpu_x86_update_cr4(env, ldq_phys(env->vm_hsave + offsetof(struct vmcb, save.cr4)));
-    cpu_x86_update_cr3(env, ldq_phys(env->vm_hsave + offsetof(struct vmcb, save.cr3)));
+    env->gdt.base  = ldq_phys(env->vm_hsave + offsetof(struct vmcb,
+                                                       save.gdtr.base));
+    env->gdt.limit = ldl_phys(env->vm_hsave + offsetof(struct vmcb,
+                                                       save.gdtr.limit));
+
+    env->idt.base  = ldq_phys(env->vm_hsave + offsetof(struct vmcb,
+                                                       save.idtr.base));
+    env->idt.limit = ldl_phys(env->vm_hsave + offsetof(struct vmcb,
+                                                       save.idtr.limit));
+
+    cpu_x86_update_cr0(env, ldq_phys(env->vm_hsave + offsetof(struct vmcb,
+                                                              save.cr0)) |
+                       CR0_PE_MASK);
+    cpu_x86_update_cr4(env, ldq_phys(env->vm_hsave + offsetof(struct vmcb,
+                                                              save.cr4)));
+    cpu_x86_update_cr3(env, ldq_phys(env->vm_hsave + offsetof(struct vmcb,
+                                                              save.cr3)));
     /* we need to set the efer after the crs so the hidden flags get
        set properly */
-    cpu_load_efer(env, 
-                  ldq_phys(env->vm_hsave + offsetof(struct vmcb, save.efer)));
+    cpu_load_efer(env, ldq_phys(env->vm_hsave + offsetof(struct vmcb,
+                                                         save.efer)));
     env->eflags = 0;
     load_eflags(ldq_phys(env->vm_hsave + offsetof(struct vmcb, save.rflags)),
                 ~(CC_O | CC_S | CC_Z | CC_A | CC_P | CC_C | DF_MASK));
@@ -5583,13 +5978,17 @@ void helper_vmexit(uint32_t exit_code, uint64_t exit_info_1)
 
     /* other setups */
     cpu_x86_set_cpl(env, 0);
-    stq_phys(env->vm_vmcb + offsetof(struct vmcb, control.exit_code), exit_code);
-    stq_phys(env->vm_vmcb + offsetof(struct vmcb, control.exit_info_1), exit_info_1);
+    stq_phys(env->vm_vmcb + offsetof(struct vmcb, control.exit_code),
+             exit_code);
+    stq_phys(env->vm_vmcb + offsetof(struct vmcb, control.exit_info_1),
+             exit_info_1);
 
     stl_phys(env->vm_vmcb + offsetof(struct vmcb, control.exit_int_info),
-             ldl_phys(env->vm_vmcb + offsetof(struct vmcb, control.event_inj)));
+             ldl_phys(env->vm_vmcb + offsetof(struct vmcb,
+                                              control.event_inj)));
     stl_phys(env->vm_vmcb + offsetof(struct vmcb, control.exit_int_info_err),
-             ldl_phys(env->vm_vmcb + offsetof(struct vmcb, control.event_inj_err)));
+             ldl_phys(env->vm_vmcb + offsetof(struct vmcb,
+                                              control.event_inj_err)));
     stl_phys(env->vm_vmcb + offsetof(struct vmcb, control.event_inj), 0);
 
     env->hflags2 &= ~HF2_GIF_MASK;
@@ -5613,7 +6012,7 @@ void helper_vmexit(uint32_t exit_code, uint64_t exit_info_1)
 
     /* If the host's rIP reloaded by #VMEXIT is outside the limit of the
        host's code segment or non-canonical (in the case of long mode), a
-       #GP fault is delivered inside the host.) */
+       #GP fault is delivered inside the host. */
 
     /* remove any pending exception */
     env->exception_index = -1;
@@ -5641,7 +6040,7 @@ static void update_sse_status(void)
     int rnd_type;
 
     /* set rounding mode */
-    switch(env->mxcsr & SSE_RC_MASK) {
+    switch (env->mxcsr & SSE_RC_MASK) {
     default:
     case SSE_RC_NEAR:
         rnd_type = float_round_nearest_even;
@@ -5755,7 +6154,7 @@ target_ulong helper_lzcnt(target_ulong t0, int wordsize)
 
 target_ulong helper_bsr(target_ulong t0)
 {
-	return helper_lzcnt(t0, 0);
+    return helper_lzcnt(t0, 0);
 }
 
 static int compute_all_eflags(void)
@@ -5771,70 +6170,112 @@ static int compute_c_eflags(void)
 uint32_t helper_cc_compute_all(int op)
 {
     switch (op) {
-    default: /* should never happen */ return 0;
-
-    case CC_OP_EFLAGS: return compute_all_eflags();
-
-    case CC_OP_MULB: return compute_all_mulb();
-    case CC_OP_MULW: return compute_all_mulw();
-    case CC_OP_MULL: return compute_all_mull();
-
-    case CC_OP_ADDB: return compute_all_addb();
-    case CC_OP_ADDW: return compute_all_addw();
-    case CC_OP_ADDL: return compute_all_addl();
-
-    case CC_OP_ADCB: return compute_all_adcb();
-    case CC_OP_ADCW: return compute_all_adcw();
-    case CC_OP_ADCL: return compute_all_adcl();
-
-    case CC_OP_SUBB: return compute_all_subb();
-    case CC_OP_SUBW: return compute_all_subw();
-    case CC_OP_SUBL: return compute_all_subl();
-
-    case CC_OP_SBBB: return compute_all_sbbb();
-    case CC_OP_SBBW: return compute_all_sbbw();
-    case CC_OP_SBBL: return compute_all_sbbl();
-
-    case CC_OP_LOGICB: return compute_all_logicb();
-    case CC_OP_LOGICW: return compute_all_logicw();
-    case CC_OP_LOGICL: return compute_all_logicl();
-
-    case CC_OP_INCB: return compute_all_incb();
-    case CC_OP_INCW: return compute_all_incw();
-    case CC_OP_INCL: return compute_all_incl();
-
-    case CC_OP_DECB: return compute_all_decb();
-    case CC_OP_DECW: return compute_all_decw();
-    case CC_OP_DECL: return compute_all_decl();
-
-    case CC_OP_SHLB: return compute_all_shlb();
-    case CC_OP_SHLW: return compute_all_shlw();
-    case CC_OP_SHLL: return compute_all_shll();
-
-    case CC_OP_SARB: return compute_all_sarb();
-    case CC_OP_SARW: return compute_all_sarw();
-    case CC_OP_SARL: return compute_all_sarl();
+    default: /* should never happen */
+        return 0;
+
+    case CC_OP_EFLAGS:
+        return compute_all_eflags();
+
+    case CC_OP_MULB:
+        return compute_all_mulb();
+    case CC_OP_MULW:
+        return compute_all_mulw();
+    case CC_OP_MULL:
+        return compute_all_mull();
+
+    case CC_OP_ADDB:
+        return compute_all_addb();
+    case CC_OP_ADDW:
+        return compute_all_addw();
+    case CC_OP_ADDL:
+        return compute_all_addl();
+
+    case CC_OP_ADCB:
+        return compute_all_adcb();
+    case CC_OP_ADCW:
+        return compute_all_adcw();
+    case CC_OP_ADCL:
+        return compute_all_adcl();
+
+    case CC_OP_SUBB:
+        return compute_all_subb();
+    case CC_OP_SUBW:
+        return compute_all_subw();
+    case CC_OP_SUBL:
+        return compute_all_subl();
+
+    case CC_OP_SBBB:
+        return compute_all_sbbb();
+    case CC_OP_SBBW:
+        return compute_all_sbbw();
+    case CC_OP_SBBL:
+        return compute_all_sbbl();
+
+    case CC_OP_LOGICB:
+        return compute_all_logicb();
+    case CC_OP_LOGICW:
+        return compute_all_logicw();
+    case CC_OP_LOGICL:
+        return compute_all_logicl();
+
+    case CC_OP_INCB:
+        return compute_all_incb();
+    case CC_OP_INCW:
+        return compute_all_incw();
+    case CC_OP_INCL:
+        return compute_all_incl();
+
+    case CC_OP_DECB:
+        return compute_all_decb();
+    case CC_OP_DECW:
+        return compute_all_decw();
+    case CC_OP_DECL:
+        return compute_all_decl();
+
+    case CC_OP_SHLB:
+        return compute_all_shlb();
+    case CC_OP_SHLW:
+        return compute_all_shlw();
+    case CC_OP_SHLL:
+        return compute_all_shll();
+
+    case CC_OP_SARB:
+        return compute_all_sarb();
+    case CC_OP_SARW:
+        return compute_all_sarw();
+    case CC_OP_SARL:
+        return compute_all_sarl();
 
 #ifdef TARGET_X86_64
-    case CC_OP_MULQ: return compute_all_mulq();
+    case CC_OP_MULQ:
+        return compute_all_mulq();
 
-    case CC_OP_ADDQ: return compute_all_addq();
+    case CC_OP_ADDQ:
+        return compute_all_addq();
 
-    case CC_OP_ADCQ: return compute_all_adcq();
+    case CC_OP_ADCQ:
+        return compute_all_adcq();
 
-    case CC_OP_SUBQ: return compute_all_subq();
+    case CC_OP_SUBQ:
+        return compute_all_subq();
 
-    case CC_OP_SBBQ: return compute_all_sbbq();
+    case CC_OP_SBBQ:
+        return compute_all_sbbq();
 
-    case CC_OP_LOGICQ: return compute_all_logicq();
+    case CC_OP_LOGICQ:
+        return compute_all_logicq();
 
-    case CC_OP_INCQ: return compute_all_incq();
+    case CC_OP_INCQ:
+        return compute_all_incq();
 
-    case CC_OP_DECQ: return compute_all_decq();
+    case CC_OP_DECQ:
+        return compute_all_decq();
 
-    case CC_OP_SHLQ: return compute_all_shlq();
+    case CC_OP_SHLQ:
+        return compute_all_shlq();
 
-    case CC_OP_SARQ: return compute_all_sarq();
+    case CC_OP_SARQ:
+        return compute_all_sarq();
 #endif
     }
 }
@@ -5854,70 +6295,112 @@ uint32_t cpu_cc_compute_all(CPUX86State *env1, int op)
 uint32_t helper_cc_compute_c(int op)
 {
     switch (op) {
-    default: /* should never happen */ return 0;
-
-    case CC_OP_EFLAGS: return compute_c_eflags();
-
-    case CC_OP_MULB: return compute_c_mull();
-    case CC_OP_MULW: return compute_c_mull();
-    case CC_OP_MULL: return compute_c_mull();
-
-    case CC_OP_ADDB: return compute_c_addb();
-    case CC_OP_ADDW: return compute_c_addw();
-    case CC_OP_ADDL: return compute_c_addl();
-
-    case CC_OP_ADCB: return compute_c_adcb();
-    case CC_OP_ADCW: return compute_c_adcw();
-    case CC_OP_ADCL: return compute_c_adcl();
-
-    case CC_OP_SUBB: return compute_c_subb();
-    case CC_OP_SUBW: return compute_c_subw();
-    case CC_OP_SUBL: return compute_c_subl();
-
-    case CC_OP_SBBB: return compute_c_sbbb();
-    case CC_OP_SBBW: return compute_c_sbbw();
-    case CC_OP_SBBL: return compute_c_sbbl();
-
-    case CC_OP_LOGICB: return compute_c_logicb();
-    case CC_OP_LOGICW: return compute_c_logicw();
-    case CC_OP_LOGICL: return compute_c_logicl();
-
-    case CC_OP_INCB: return compute_c_incl();
-    case CC_OP_INCW: return compute_c_incl();
-    case CC_OP_INCL: return compute_c_incl();
-
-    case CC_OP_DECB: return compute_c_incl();
-    case CC_OP_DECW: return compute_c_incl();
-    case CC_OP_DECL: return compute_c_incl();
-
-    case CC_OP_SHLB: return compute_c_shlb();
-    case CC_OP_SHLW: return compute_c_shlw();
-    case CC_OP_SHLL: return compute_c_shll();
-
-    case CC_OP_SARB: return compute_c_sarl();
-    case CC_OP_SARW: return compute_c_sarl();
-    case CC_OP_SARL: return compute_c_sarl();
+    default: /* should never happen */
+        return 0;
+
+    case CC_OP_EFLAGS:
+        return compute_c_eflags();
+
+    case CC_OP_MULB:
+        return compute_c_mull();
+    case CC_OP_MULW:
+        return compute_c_mull();
+    case CC_OP_MULL:
+        return compute_c_mull();
+
+    case CC_OP_ADDB:
+        return compute_c_addb();
+    case CC_OP_ADDW:
+        return compute_c_addw();
+    case CC_OP_ADDL:
+        return compute_c_addl();
+
+    case CC_OP_ADCB:
+        return compute_c_adcb();
+    case CC_OP_ADCW:
+        return compute_c_adcw();
+    case CC_OP_ADCL:
+        return compute_c_adcl();
+
+    case CC_OP_SUBB:
+        return compute_c_subb();
+    case CC_OP_SUBW:
+        return compute_c_subw();
+    case CC_OP_SUBL:
+        return compute_c_subl();
+
+    case CC_OP_SBBB:
+        return compute_c_sbbb();
+    case CC_OP_SBBW:
+        return compute_c_sbbw();
+    case CC_OP_SBBL:
+        return compute_c_sbbl();
+
+    case CC_OP_LOGICB:
+        return compute_c_logicb();
+    case CC_OP_LOGICW:
+        return compute_c_logicw();
+    case CC_OP_LOGICL:
+        return compute_c_logicl();
+
+    case CC_OP_INCB:
+        return compute_c_incl();
+    case CC_OP_INCW:
+        return compute_c_incl();
+    case CC_OP_INCL:
+        return compute_c_incl();
+
+    case CC_OP_DECB:
+        return compute_c_incl();
+    case CC_OP_DECW:
+        return compute_c_incl();
+    case CC_OP_DECL:
+        return compute_c_incl();
+
+    case CC_OP_SHLB:
+        return compute_c_shlb();
+    case CC_OP_SHLW:
+        return compute_c_shlw();
+    case CC_OP_SHLL:
+        return compute_c_shll();
+
+    case CC_OP_SARB:
+        return compute_c_sarl();
+    case CC_OP_SARW:
+        return compute_c_sarl();
+    case CC_OP_SARL:
+        return compute_c_sarl();
 
 #ifdef TARGET_X86_64
-    case CC_OP_MULQ: return compute_c_mull();
+    case CC_OP_MULQ:
+        return compute_c_mull();
 
-    case CC_OP_ADDQ: return compute_c_addq();
+    case CC_OP_ADDQ:
+        return compute_c_addq();
 
-    case CC_OP_ADCQ: return compute_c_adcq();
+    case CC_OP_ADCQ:
+        return compute_c_adcq();
 
-    case CC_OP_SUBQ: return compute_c_subq();
+    case CC_OP_SUBQ:
+        return compute_c_subq();
 
-    case CC_OP_SBBQ: return compute_c_sbbq();
+    case CC_OP_SBBQ:
+        return compute_c_sbbq();
 
-    case CC_OP_LOGICQ: return compute_c_logicq();
+    case CC_OP_LOGICQ:
+        return compute_c_logicq();
 
-    case CC_OP_INCQ: return compute_c_incl();
+    case CC_OP_INCQ:
+        return compute_c_incl();
 
-    case CC_OP_DECQ: return compute_c_incl();
+    case CC_OP_DECQ:
+        return compute_c_incl();
 
-    case CC_OP_SHLQ: return compute_c_shlq();
+    case CC_OP_SHLQ:
+        return compute_c_shlq();
 
-    case CC_OP_SARQ: return compute_c_sarl();
+    case CC_OP_SARQ:
+        return compute_c_sarl();
 #endif
     }
 }
commit 7a0bac4da9c6a2e36d388412f3b4074b10429e8e
Author: Benjamin Herrenschmidt <benh at kernel.crashing.org>
Date:   Wed Jun 27 14:50:47 2012 +1000

    Add a memory barrier to DMA functions
    
    The emulated devices can run simultaneously with the guest, so
    we need to be careful with ordering of load and stores done by
    them to the guest system memory, which need to be observed in
    the right order by the guest operating system.
    
    This adds a barrier call to the basic DMA read/write ops which
    is currently implemented as a smp_mb(), but could be later
    improved for more fine grained control of barriers.
    
    Additionally, a _relaxed() variant of the accessors is provided
    to easily convert devices who would be performance sensitive
    and negatively impacted by the change.
    
    Signed-off-by: Benjamin Herrenschmidt <benh at kernel.crashing.org>
    Signed-off-by: Anthony Liguori <aliguori at us.ibm.com>

diff --git a/dma-helpers.c b/dma-helpers.c
index 2e09ceb..35cb500 100644
--- a/dma-helpers.c
+++ b/dma-helpers.c
@@ -31,6 +31,8 @@ static void do_dma_memory_set(dma_addr_t addr, uint8_t c, dma_addr_t len)
 
 int dma_memory_set(DMAContext *dma, dma_addr_t addr, uint8_t c, dma_addr_t len)
 {
+    dma_barrier(dma, DMA_DIRECTION_FROM_DEVICE);
+
     if (dma_has_iommu(dma)) {
         return iommu_dma_memory_set(dma, addr, c, len);
     }
diff --git a/dma.h b/dma.h
index f52a656..acacf1b 100644
--- a/dma.h
+++ b/dma.h
@@ -13,6 +13,7 @@
 #include <stdio.h>
 #include "hw/hw.h"
 #include "block.h"
+#include "kvm.h"
 
 typedef struct DMAContext DMAContext;
 typedef struct ScatterGatherEntry ScatterGatherEntry;
@@ -65,6 +66,31 @@ struct DMAContext {
     DMAUnmapFunc *unmap;
 };
 
+static inline void dma_barrier(DMAContext *dma, DMADirection dir)
+{
+    /*
+     * This is called before DMA read and write operations
+     * unless the _relaxed form is used and is responsible
+     * for providing some sane ordering of accesses vs
+     * concurrently running VCPUs.
+     *
+     * Users of map(), unmap() or lower level st/ld_*
+     * operations are responsible for providing their own
+     * ordering via barriers.
+     *
+     * This primitive implementation does a simple smp_mb()
+     * before each operation which provides pretty much full
+     * ordering.
+     *
+     * A smarter implementation can be devised if needed to
+     * use lighter barriers based on the direction of the
+     * transfer, the DMA context, etc...
+     */
+    if (kvm_enabled()) {
+        smp_mb();
+    }
+}
+
 static inline bool dma_has_iommu(DMAContext *dma)
 {
     return !!dma;
@@ -88,8 +114,9 @@ static inline bool dma_memory_valid(DMAContext *dma,
 
 int iommu_dma_memory_rw(DMAContext *dma, dma_addr_t addr,
                         void *buf, dma_addr_t len, DMADirection dir);
-static inline int dma_memory_rw(DMAContext *dma, dma_addr_t addr,
-                                void *buf, dma_addr_t len, DMADirection dir)
+static inline int dma_memory_rw_relaxed(DMAContext *dma, dma_addr_t addr,
+                                        void *buf, dma_addr_t len,
+                                        DMADirection dir)
 {
     if (!dma_has_iommu(dma)) {
         /* Fast-path for no IOMMU */
@@ -101,6 +128,28 @@ static inline int dma_memory_rw(DMAContext *dma, dma_addr_t addr,
     }
 }
 
+static inline int dma_memory_read_relaxed(DMAContext *dma, dma_addr_t addr,
+                                          void *buf, dma_addr_t len)
+{
+    return dma_memory_rw_relaxed(dma, addr, buf, len, DMA_DIRECTION_TO_DEVICE);
+}
+
+static inline int dma_memory_write_relaxed(DMAContext *dma, dma_addr_t addr,
+                                           const void *buf, dma_addr_t len)
+{
+    return dma_memory_rw_relaxed(dma, addr, (void *)buf, len,
+                                 DMA_DIRECTION_FROM_DEVICE);
+}
+
+static inline int dma_memory_rw(DMAContext *dma, dma_addr_t addr,
+                                void *buf, dma_addr_t len,
+                                DMADirection dir)
+{
+    dma_barrier(dma, dir);
+
+    return dma_memory_rw_relaxed(dma, addr, buf, len, dir);
+}
+
 static inline int dma_memory_read(DMAContext *dma, dma_addr_t addr,
                                   void *buf, dma_addr_t len)
 {
commit edded454067bd9bda8a4a2a3ef54ae19474407da
Author: David Gibson <david at gibson.dropbear.id.au>
Date:   Wed Jun 27 14:50:46 2012 +1000

    pseries: Implement IOMMU and DMA for PAPR PCI devices
    
    Currently the pseries machine emulation does not support DMA for emulated
    PCI devices, because the PAPR spec always requires a (guest visible,
    paravirtualized) IOMMU which was not implemented.  Now that we have
    infrastructure for IOMMU emulation, we can correct this and allow PCI DMA
    for pseries.
    
    With the existing PAPR IOMMU code used for VIO devices, this is almost
    trivial. We use a single DMAContext for each (virtual) PCI host bridge,
    which is the usual configuration on real PAPR machines (which often have
    _many_ PCI host bridges).
    
    Cc: Alex Graf <agraf at suse.de>
    
    Signed-off-by: Alexey Kardashevskiy <aik at ozlabs.ru>
    Signed-off-by: David Gibson <david at gibson.dropbear.id.au>
    Signed-off-by: Benjamin Herrenschmidt <benh at kernel.crashing.org>
    Signed-off-by: Anthony Liguori <aliguori at us.ibm.com>

diff --git a/hw/spapr.h b/hw/spapr.h
index 1c4d85f..9153f29 100644
--- a/hw/spapr.h
+++ b/hw/spapr.h
@@ -330,6 +330,7 @@ typedef struct sPAPRTCE {
 } sPAPRTCE;
 
 #define SPAPR_VIO_BASE_LIOBN    0x00000000
+#define SPAPR_PCI_BASE_LIOBN    0x80000000
 
 void spapr_iommu_init(void);
 DMAContext *spapr_tce_new_dma_context(uint32_t liobn, size_t window_size);
diff --git a/hw/spapr_iommu.c b/hw/spapr_iommu.c
index 5a769b9..388ffa4 100644
--- a/hw/spapr_iommu.c
+++ b/hw/spapr_iommu.c
@@ -162,6 +162,22 @@ void spapr_tce_free(DMAContext *dma)
     }
 }
 
+static target_ulong put_tce_emu(sPAPRTCETable *tcet, target_ulong ioba,
+                                target_ulong tce)
+{
+    sPAPRTCE *tcep;
+
+    if (ioba >= tcet->window_size) {
+        hcall_dprintf("spapr_vio_put_tce on out-of-boards IOBA 0x"
+                      TARGET_FMT_lx "\n", ioba);
+        return H_PARAMETER;
+    }
+
+    tcep = tcet->table + (ioba >> SPAPR_TCE_PAGE_SHIFT);
+    tcep->tce = tce;
+
+    return H_SUCCESS;
+}
 
 static target_ulong h_put_tce(CPUPPCState *env, sPAPREnvironment *spapr,
                               target_ulong opcode, target_ulong *args)
@@ -170,37 +186,25 @@ static target_ulong h_put_tce(CPUPPCState *env, sPAPREnvironment *spapr,
     target_ulong ioba = args[1];
     target_ulong tce = args[2];
     sPAPRTCETable *tcet = spapr_tce_find_by_liobn(liobn);
-    sPAPRTCE *tcep;
 
     if (liobn & 0xFFFFFFFF00000000ULL) {
         hcall_dprintf("spapr_vio_put_tce on out-of-boundsw LIOBN "
                       TARGET_FMT_lx "\n", liobn);
         return H_PARAMETER;
     }
-    if (!tcet) {
-        hcall_dprintf("spapr_vio_put_tce on non-existent LIOBN "
-                      TARGET_FMT_lx "\n", liobn);
-        return H_PARAMETER;
-    }
 
     ioba &= ~(SPAPR_TCE_PAGE_SIZE - 1);
 
+    if (tcet) {
+        return put_tce_emu(tcet, ioba, tce);
+    }
 #ifdef DEBUG_TCE
-    fprintf(stderr, "spapr_vio_put_tce on liobn=" TARGET_FMT_lx /*%s*/
+    fprintf(stderr, "%s on liobn=" TARGET_FMT_lx /*%s*/
             "  ioba 0x" TARGET_FMT_lx "  TCE 0x" TARGET_FMT_lx "\n",
-            liobn, /*dev->qdev.id, */ioba, tce);
+            __func__, liobn, /*dev->qdev.id, */ioba, tce);
 #endif
 
-    if (ioba >= tcet->window_size) {
-        hcall_dprintf("spapr_vio_put_tce on out-of-boards IOBA 0x"
-                      TARGET_FMT_lx "\n", ioba);
-        return H_PARAMETER;
-    }
-
-    tcep = tcet->table + (ioba >> SPAPR_TCE_PAGE_SHIFT);
-    tcep->tce = tce;
-
-    return H_SUCCESS;
+    return H_PARAMETER;
 }
 
 void spapr_iommu_init(void)
diff --git a/hw/spapr_pci.c b/hw/spapr_pci.c
index 97d417a..47ba5ff 100644
--- a/hw/spapr_pci.c
+++ b/hw/spapr_pci.c
@@ -266,12 +266,21 @@ static const MemoryRegionOps spapr_io_ops = {
 /*
  * PHB PCI device
  */
+static DMAContext *spapr_pci_dma_context_fn(PCIBus *bus, void *opaque,
+                                            int devfn)
+{
+    sPAPRPHBState *phb = opaque;
+
+    return phb->dma;
+}
+
 static int spapr_phb_init(SysBusDevice *s)
 {
     sPAPRPHBState *phb = FROM_SYSBUS(sPAPRPHBState, s);
     char *namebuf;
     int i;
     PCIBus *bus;
+    uint32_t liobn;
 
     phb->dtbusname = g_strdup_printf("pci@%" PRIx64, phb->buid);
     namebuf = alloca(strlen(phb->dtbusname) + 32);
@@ -312,6 +321,10 @@ static int spapr_phb_init(SysBusDevice *s)
                            PCI_DEVFN(0, 0), PCI_NUM_PINS);
     phb->host_state.bus = bus;
 
+    liobn = SPAPR_PCI_BASE_LIOBN | (pci_find_domain(bus) << 16);
+    phb->dma = spapr_tce_new_dma_context(liobn, 0x40000000);
+    pci_setup_iommu(bus, spapr_pci_dma_context_fn, phb);
+
     QLIST_INSERT_HEAD(&spapr->phbs, phb, list);
 
     /* Initialize the LSI table */
@@ -472,6 +485,8 @@ int spapr_populate_pci_devices(sPAPRPHBState *phb,
     _FDT(fdt_setprop(fdt, bus_off, "interrupt-map", &interrupt_map,
                      sizeof(interrupt_map)));
 
+    spapr_dma_dt(fdt, bus_off, "ibm,dma-window", phb->dma);
+
     return 0;
 }
 
diff --git a/hw/spapr_pci.h b/hw/spapr_pci.h
index f54c2e8..d9e46e2 100644
--- a/hw/spapr_pci.h
+++ b/hw/spapr_pci.h
@@ -38,6 +38,7 @@ typedef struct sPAPRPHBState {
     MemoryRegion memspace, iospace;
     target_phys_addr_t mem_win_addr, mem_win_size, io_win_addr, io_win_size;
     MemoryRegion memwindow, iowindow;
+    DMAContext *dma;
 
     struct {
         uint32_t dt_irq;
commit 5fa45de5623abd3a6d0b9575a4f014cbfe886b36
Author: David Gibson <david at gibson.dropbear.id.au>
Date:   Wed Jun 27 14:50:45 2012 +1000

    iommu: Allow PCI to use IOMMU infrastructure
    
    This patch adds some hooks to let PCI devices and busses use the new IOMMU
    infrastructure.  When IOMMU support is enabled, each PCI device now
    contains a DMAContext * which is used by the pci_dma_*() wrapper functions.
    
    By default, the contexts are initialized to NULL, assuming no IOMMU.
    However the platform or host bridge code which sets up the PCI bus can use
    pci_setup_iommu() to set a function which will determine the correct
    DMAContext for a given PCI device.
    
    Cc: Michael S. Tsirkin <mst at redhat.com>
    Cc: Richard Henderson <rth at twiddle.net>
    
    Signed-off-by: David Gibson <david at gibson.dropbear.id.au>
    Signed-off-by: Eduard - Gabriel Munteanu <eduard.munteanu at linux360.ro>
    Signed-off-by: Benjamin Herrenschmidt <benh at kernel.crashing.org>
    Signed-off-by: Anthony Liguori <aliguori at us.ibm.com>

diff --git a/hw/pci.c b/hw/pci.c
index 5c75f16..99a4304 100644
--- a/hw/pci.c
+++ b/hw/pci.c
@@ -775,6 +775,9 @@ static PCIDevice *do_pci_register_device(PCIDevice *pci_dev, PCIBus *bus,
         return NULL;
     }
     pci_dev->bus = bus;
+    if (bus->dma_context_fn) {
+        pci_dev->dma = bus->dma_context_fn(bus, bus->dma_context_opaque, devfn);
+    }
     pci_dev->devfn = devfn;
     pstrcpy(pci_dev->name, sizeof(pci_dev->name), name);
     pci_dev->irq_state = 0;
@@ -2024,6 +2027,12 @@ static void pci_device_class_init(ObjectClass *klass, void *data)
     k->props = pci_props;
 }
 
+void pci_setup_iommu(PCIBus *bus, PCIDMAContextFunc fn, void *opaque)
+{
+    bus->dma_context_fn = fn;
+    bus->dma_context_opaque = opaque;
+}
+
 static TypeInfo pci_device_type_info = {
     .name = TYPE_PCI_DEVICE,
     .parent = TYPE_DEVICE,
diff --git a/hw/pci.h b/hw/pci.h
index ee14a7f..79d38fd 100644
--- a/hw/pci.h
+++ b/hw/pci.h
@@ -179,6 +179,7 @@ typedef void (*MSIVectorReleaseNotifier)(PCIDevice *dev, unsigned int vector);
 
 struct PCIDevice {
     DeviceState qdev;
+
     /* PCI config space */
     uint8_t *config;
 
@@ -200,6 +201,7 @@ struct PCIDevice {
     int32_t devfn;
     char name[64];
     PCIIORegion io_regions[PCI_NUM_REGIONS];
+    DMAContext *dma;
 
     /* do not access the following fields */
     PCIConfigReadFunc *config_read;
@@ -326,6 +328,10 @@ int pci_read_devaddr(Monitor *mon, const char *addr, int *domp, int *busp,
 
 void pci_device_deassert_intx(PCIDevice *dev);
 
+typedef DMAContext *(*PCIDMAContextFunc)(PCIBus *, void *, int);
+
+void pci_setup_iommu(PCIBus *bus, PCIDMAContextFunc fn, void *opaque);
+
 static inline void
 pci_set_byte(uint8_t *config, uint8_t val)
 {
@@ -562,8 +568,7 @@ static inline uint32_t pci_config_size(const PCIDevice *d)
 /* DMA access functions */
 static inline DMAContext *pci_dma_context(PCIDevice *dev)
 {
-    /* Stub for when we have no PCI iommu support */
-    return NULL;
+    return dev->dma;
 }
 
 static inline int pci_dma_rw(PCIDevice *dev, dma_addr_t addr,
diff --git a/hw/pci_internals.h b/hw/pci_internals.h
index 399c6d4..e8bc9f6 100644
--- a/hw/pci_internals.h
+++ b/hw/pci_internals.h
@@ -17,6 +17,8 @@
 
 struct PCIBus {
     BusState qbus;
+    PCIDMAContextFunc dma_context_fn;
+    void *dma_context_opaque;
     uint8_t devfn_min;
     pci_set_irq_fn set_irq;
     pci_map_irq_fn map_irq;
commit ad0ebb91cd8b5fdc4a583b03645677771f420a46
Author: David Gibson <david at gibson.dropbear.id.au>
Date:   Wed Jun 27 14:50:44 2012 +1000

    pseries: Convert sPAPR TCEs to use generic IOMMU infrastructure
    
    The pseries platform already contains an IOMMU implementation, since it is
    essential for the platform's paravirtualized VIO devices.  This IOMMU
    support is currently built into the implementation of the VIO "bus" and
    the various VIO devices.
    
    This patch converts this code to make use of the new common IOMMU
    infrastructure.
    
    We don't yet handle synchronization of map/unmap callbacks vs. invalidations,
    this will require some complex interaction with the kernel and is not a
    major concern at this stage.
    
    Cc: Alex Graf <agraf at suse.de>
    
    Signed-off-by: David Gibson <david at gibson.dropbear.id.au>
    Signed-off-by: Benjamin Herrenschmidt <benh at kernel.crashing.org>
    Signed-off-by: Anthony Liguori <aliguori at us.ibm.com>

diff --git a/hw/ppc/Makefile.objs b/hw/ppc/Makefile.objs
index d18dbaf..aa4bbeb 100644
--- a/hw/ppc/Makefile.objs
+++ b/hw/ppc/Makefile.objs
@@ -10,7 +10,7 @@ obj-y += ppc_newworld.o
 # IBM pSeries (sPAPR)
 obj-$(CONFIG_PSERIES) += spapr.o spapr_hcall.o spapr_rtas.o spapr_vio.o
 obj-$(CONFIG_PSERIES) += xics.o spapr_vty.o spapr_llan.o spapr_vscsi.o
-obj-$(CONFIG_PSERIES) += spapr_pci.o pci-hotplug.o
+obj-$(CONFIG_PSERIES) += spapr_pci.o pci-hotplug.o spapr_iommu.o
 # PowerPC 4xx boards
 obj-y += ppc4xx_devs.o ppc4xx_pci.o ppc405_uc.o ppc405_boards.o
 obj-y += ppc440_bamboo.o
diff --git a/hw/spapr.c b/hw/spapr.c
index 09a23ff..81c9343 100644
--- a/hw/spapr.c
+++ b/hw/spapr.c
@@ -674,6 +674,9 @@ static void ppc_spapr_init(ram_addr_t ram_size,
     spapr->icp = xics_system_init(XICS_IRQS);
     spapr->next_irq = 16;
 
+    /* Set up IOMMU */
+    spapr_iommu_init();
+
     /* Set up VIO bus */
     spapr->vio_bus = spapr_vio_bus_init();
 
diff --git a/hw/spapr.h b/hw/spapr.h
index c75172e..1c4d85f 100644
--- a/hw/spapr.h
+++ b/hw/spapr.h
@@ -1,6 +1,7 @@
 #if !defined(__HW_SPAPR_H__)
 #define __HW_SPAPR_H__
 
+#include "dma.h"
 #include "hw/xics.h"
 
 struct VIOsPAPRBus;
@@ -320,4 +321,20 @@ target_ulong spapr_rtas_call(sPAPREnvironment *spapr,
 int spapr_rtas_device_tree_setup(void *fdt, target_phys_addr_t rtas_addr,
                                  target_phys_addr_t rtas_size);
 
+#define SPAPR_TCE_PAGE_SHIFT   12
+#define SPAPR_TCE_PAGE_SIZE    (1ULL << SPAPR_TCE_PAGE_SHIFT)
+#define SPAPR_TCE_PAGE_MASK    (SPAPR_TCE_PAGE_SIZE - 1)
+
+typedef struct sPAPRTCE {
+    uint64_t tce;
+} sPAPRTCE;
+
+#define SPAPR_VIO_BASE_LIOBN    0x00000000
+
+void spapr_iommu_init(void);
+DMAContext *spapr_tce_new_dma_context(uint32_t liobn, size_t window_size);
+void spapr_tce_free(DMAContext *dma);
+int spapr_dma_dt(void *fdt, int node_off, const char *propname,
+                 DMAContext *dma);
+
 #endif /* !defined (__HW_SPAPR_H__) */
diff --git a/hw/spapr_iommu.c b/hw/spapr_iommu.c
new file mode 100644
index 0000000..5a769b9
--- /dev/null
+++ b/hw/spapr_iommu.c
@@ -0,0 +1,242 @@
+/*
+ * QEMU sPAPR IOMMU (TCE) code
+ *
+ * Copyright (c) 2010 David Gibson, IBM Corporation <dwg at au1.ibm.com>
+ *
+ * This library is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Lesser General Public
+ * License as published by the Free Software Foundation; either
+ * version 2 of the License, or (at your option) any later version.
+ *
+ * This library is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
+ * Lesser General Public License for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public
+ * License along with this library; if not, see <http://www.gnu.org/licenses/>.
+ */
+#include "hw.h"
+#include "kvm.h"
+#include "qdev.h"
+#include "kvm_ppc.h"
+#include "dma.h"
+
+#include "hw/spapr.h"
+
+#include <libfdt.h>
+
+/* #define DEBUG_TCE */
+
+enum sPAPRTCEAccess {
+    SPAPR_TCE_FAULT = 0,
+    SPAPR_TCE_RO = 1,
+    SPAPR_TCE_WO = 2,
+    SPAPR_TCE_RW = 3,
+};
+
+typedef struct sPAPRTCETable sPAPRTCETable;
+
+struct sPAPRTCETable {
+    DMAContext dma;
+    uint32_t liobn;
+    uint32_t window_size;
+    sPAPRTCE *table;
+    int fd;
+    QLIST_ENTRY(sPAPRTCETable) list;
+};
+
+
+QLIST_HEAD(spapr_tce_tables, sPAPRTCETable) spapr_tce_tables;
+
+static sPAPRTCETable *spapr_tce_find_by_liobn(uint32_t liobn)
+{
+    sPAPRTCETable *tcet;
+
+    QLIST_FOREACH(tcet, &spapr_tce_tables, list) {
+        if (tcet->liobn == liobn) {
+            return tcet;
+        }
+    }
+
+    return NULL;
+}
+
+static int spapr_tce_translate(DMAContext *dma,
+                               dma_addr_t addr,
+                               target_phys_addr_t *paddr,
+                               target_phys_addr_t *len,
+                               DMADirection dir)
+{
+    sPAPRTCETable *tcet = DO_UPCAST(sPAPRTCETable, dma, dma);
+    enum sPAPRTCEAccess access = (dir == DMA_DIRECTION_FROM_DEVICE)
+        ? SPAPR_TCE_WO : SPAPR_TCE_RO;
+    uint64_t tce;
+
+#ifdef DEBUG_TCE
+    fprintf(stderr, "spapr_tce_translate liobn=0x%" PRIx32 " addr=0x"
+            DMA_ADDR_FMT "\n", tcet->liobn, addr);
+#endif
+
+    /* Check if we are in bound */
+    if (addr >= tcet->window_size) {
+#ifdef DEBUG_TCE
+        fprintf(stderr, "spapr_tce_translate out of bounds\n");
+#endif
+        return -EFAULT;
+    }
+
+    tce = tcet->table[addr >> SPAPR_TCE_PAGE_SHIFT].tce;
+
+    /* Check TCE */
+    if (!(tce & access)) {
+        return -EPERM;
+    }
+
+    /* How much til end of page ? */
+    *len = ((~addr) & SPAPR_TCE_PAGE_MASK) + 1;
+
+    /* Translate */
+    *paddr = (tce & ~SPAPR_TCE_PAGE_MASK) |
+        (addr & SPAPR_TCE_PAGE_MASK);
+
+#ifdef DEBUG_TCE
+    fprintf(stderr, " ->  *paddr=0x" TARGET_FMT_plx ", *len=0x"
+            TARGET_FMT_plx "\n", *paddr, *len);
+#endif
+
+    return 0;
+}
+
+DMAContext *spapr_tce_new_dma_context(uint32_t liobn, size_t window_size)
+{
+    sPAPRTCETable *tcet;
+
+    if (!window_size) {
+        return NULL;
+    }
+
+    tcet = g_malloc0(sizeof(*tcet));
+    dma_context_init(&tcet->dma, spapr_tce_translate, NULL, NULL);
+
+    tcet->liobn = liobn;
+    tcet->window_size = window_size;
+
+    if (kvm_enabled()) {
+        tcet->table = kvmppc_create_spapr_tce(liobn,
+                                              window_size,
+                                              &tcet->fd);
+    }
+
+    if (!tcet->table) {
+        size_t table_size = (window_size >> SPAPR_TCE_PAGE_SHIFT)
+            * sizeof(sPAPRTCE);
+        tcet->table = g_malloc0(table_size);
+    }
+
+#ifdef DEBUG_TCE
+    fprintf(stderr, "spapr_iommu: New TCE table, liobn=0x%x, context @ %p, "
+            "table @ %p, fd=%d\n", liobn, &tcet->dma, tcet->table, tcet->fd);
+#endif
+
+    QLIST_INSERT_HEAD(&spapr_tce_tables, tcet, list);
+
+    return &tcet->dma;
+}
+
+void spapr_tce_free(DMAContext *dma)
+{
+
+    if (dma) {
+        sPAPRTCETable *tcet = DO_UPCAST(sPAPRTCETable, dma, dma);
+
+        QLIST_REMOVE(tcet, list);
+
+        if (!kvm_enabled() ||
+            (kvmppc_remove_spapr_tce(tcet->table, tcet->fd,
+                                     tcet->window_size) != 0)) {
+            g_free(tcet->table);
+        }
+
+        g_free(tcet);
+    }
+}
+
+
+static target_ulong h_put_tce(CPUPPCState *env, sPAPREnvironment *spapr,
+                              target_ulong opcode, target_ulong *args)
+{
+    target_ulong liobn = args[0];
+    target_ulong ioba = args[1];
+    target_ulong tce = args[2];
+    sPAPRTCETable *tcet = spapr_tce_find_by_liobn(liobn);
+    sPAPRTCE *tcep;
+
+    if (liobn & 0xFFFFFFFF00000000ULL) {
+        hcall_dprintf("spapr_vio_put_tce on out-of-boundsw LIOBN "
+                      TARGET_FMT_lx "\n", liobn);
+        return H_PARAMETER;
+    }
+    if (!tcet) {
+        hcall_dprintf("spapr_vio_put_tce on non-existent LIOBN "
+                      TARGET_FMT_lx "\n", liobn);
+        return H_PARAMETER;
+    }
+
+    ioba &= ~(SPAPR_TCE_PAGE_SIZE - 1);
+
+#ifdef DEBUG_TCE
+    fprintf(stderr, "spapr_vio_put_tce on liobn=" TARGET_FMT_lx /*%s*/
+            "  ioba 0x" TARGET_FMT_lx "  TCE 0x" TARGET_FMT_lx "\n",
+            liobn, /*dev->qdev.id, */ioba, tce);
+#endif
+
+    if (ioba >= tcet->window_size) {
+        hcall_dprintf("spapr_vio_put_tce on out-of-boards IOBA 0x"
+                      TARGET_FMT_lx "\n", ioba);
+        return H_PARAMETER;
+    }
+
+    tcep = tcet->table + (ioba >> SPAPR_TCE_PAGE_SHIFT);
+    tcep->tce = tce;
+
+    return H_SUCCESS;
+}
+
+void spapr_iommu_init(void)
+{
+    QLIST_INIT(&spapr_tce_tables);
+
+    /* hcall-tce */
+    spapr_register_hypercall(H_PUT_TCE, h_put_tce);
+}
+
+int spapr_dma_dt(void *fdt, int node_off, const char *propname,
+                 DMAContext *dma)
+{
+    if (dma) {
+        sPAPRTCETable *tcet = DO_UPCAST(sPAPRTCETable, dma, dma);
+        uint32_t dma_prop[] = {cpu_to_be32(tcet->liobn),
+                               0, 0,
+                               0, cpu_to_be32(tcet->window_size)};
+        int ret;
+
+        ret = fdt_setprop_cell(fdt, node_off, "ibm,#dma-address-cells", 2);
+        if (ret < 0) {
+            return ret;
+        }
+
+        ret = fdt_setprop_cell(fdt, node_off, "ibm,#dma-size-cells", 2);
+        if (ret < 0) {
+            return ret;
+        }
+
+        ret = fdt_setprop(fdt, node_off, propname, dma_prop,
+                          sizeof(dma_prop));
+        if (ret < 0) {
+            return ret;
+        }
+    }
+
+    return 0;
+}
diff --git a/hw/spapr_llan.c b/hw/spapr_llan.c
index 8313043..d26fe9f 100644
--- a/hw/spapr_llan.c
+++ b/hw/spapr_llan.c
@@ -71,7 +71,7 @@ typedef uint64_t vlan_bd_t;
 #define VLAN_RXQ_BD_OFF      0
 #define VLAN_FILTER_BD_OFF   8
 #define VLAN_RX_BDS_OFF      16
-#define VLAN_MAX_BUFS        ((SPAPR_VIO_TCE_PAGE_SIZE - VLAN_RX_BDS_OFF) / 8)
+#define VLAN_MAX_BUFS        ((SPAPR_TCE_PAGE_SIZE - VLAN_RX_BDS_OFF) / 8)
 
 typedef struct VIOsPAPRVLANDevice {
     VIOsPAPRDevice sdev;
@@ -95,7 +95,7 @@ static ssize_t spapr_vlan_receive(VLANClientState *nc, const uint8_t *buf,
 {
     VIOsPAPRDevice *sdev = DO_UPCAST(NICState, nc, nc)->opaque;
     VIOsPAPRVLANDevice *dev = (VIOsPAPRVLANDevice *)sdev;
-    vlan_bd_t rxq_bd = ldq_tce(sdev, dev->buf_list + VLAN_RXQ_BD_OFF);
+    vlan_bd_t rxq_bd = vio_ldq(sdev, dev->buf_list + VLAN_RXQ_BD_OFF);
     vlan_bd_t bd;
     int buf_ptr = dev->use_buf_ptr;
     uint64_t handle;
@@ -114,11 +114,11 @@ static ssize_t spapr_vlan_receive(VLANClientState *nc, const uint8_t *buf,
 
     do {
         buf_ptr += 8;
-        if (buf_ptr >= SPAPR_VIO_TCE_PAGE_SIZE) {
+        if (buf_ptr >= SPAPR_TCE_PAGE_SIZE) {
             buf_ptr = VLAN_RX_BDS_OFF;
         }
 
-        bd = ldq_tce(sdev, dev->buf_list + buf_ptr);
+        bd = vio_ldq(sdev, dev->buf_list + buf_ptr);
         dprintf("use_buf_ptr=%d bd=0x%016llx\n",
                 buf_ptr, (unsigned long long)bd);
     } while ((!(bd & VLAN_BD_VALID) || (VLAN_BD_LEN(bd) < (size + 8)))
@@ -132,12 +132,12 @@ static ssize_t spapr_vlan_receive(VLANClientState *nc, const uint8_t *buf,
     /* Remove the buffer from the pool */
     dev->rx_bufs--;
     dev->use_buf_ptr = buf_ptr;
-    stq_tce(sdev, dev->buf_list + dev->use_buf_ptr, 0);
+    vio_stq(sdev, dev->buf_list + dev->use_buf_ptr, 0);
 
     dprintf("Found buffer: ptr=%d num=%d\n", dev->use_buf_ptr, dev->rx_bufs);
 
     /* Transfer the packet data */
-    if (spapr_tce_dma_write(sdev, VLAN_BD_ADDR(bd) + 8, buf, size) < 0) {
+    if (spapr_vio_dma_write(sdev, VLAN_BD_ADDR(bd) + 8, buf, size) < 0) {
         return -1;
     }
 
@@ -149,23 +149,23 @@ static ssize_t spapr_vlan_receive(VLANClientState *nc, const uint8_t *buf,
         control ^= VLAN_RXQC_TOGGLE;
     }
 
-    handle = ldq_tce(sdev, VLAN_BD_ADDR(bd));
-    stq_tce(sdev, VLAN_BD_ADDR(rxq_bd) + dev->rxq_ptr + 8, handle);
-    stw_tce(sdev, VLAN_BD_ADDR(rxq_bd) + dev->rxq_ptr + 4, size);
-    sth_tce(sdev, VLAN_BD_ADDR(rxq_bd) + dev->rxq_ptr + 2, 8);
-    stb_tce(sdev, VLAN_BD_ADDR(rxq_bd) + dev->rxq_ptr, control);
+    handle = vio_ldq(sdev, VLAN_BD_ADDR(bd));
+    vio_stq(sdev, VLAN_BD_ADDR(rxq_bd) + dev->rxq_ptr + 8, handle);
+    vio_stl(sdev, VLAN_BD_ADDR(rxq_bd) + dev->rxq_ptr + 4, size);
+    vio_sth(sdev, VLAN_BD_ADDR(rxq_bd) + dev->rxq_ptr + 2, 8);
+    vio_stb(sdev, VLAN_BD_ADDR(rxq_bd) + dev->rxq_ptr, control);
 
     dprintf("wrote rxq entry (ptr=0x%llx): 0x%016llx 0x%016llx\n",
             (unsigned long long)dev->rxq_ptr,
-            (unsigned long long)ldq_tce(sdev, VLAN_BD_ADDR(rxq_bd) +
+            (unsigned long long)vio_ldq(sdev, VLAN_BD_ADDR(rxq_bd) +
                                         dev->rxq_ptr),
-            (unsigned long long)ldq_tce(sdev, VLAN_BD_ADDR(rxq_bd) +
+            (unsigned long long)vio_ldq(sdev, VLAN_BD_ADDR(rxq_bd) +
                                         dev->rxq_ptr + 8));
 
     dev->rxq_ptr += 16;
     if (dev->rxq_ptr >= VLAN_BD_LEN(rxq_bd)) {
         dev->rxq_ptr = 0;
-        stq_tce(sdev, dev->buf_list + VLAN_RXQ_BD_OFF, rxq_bd ^ VLAN_BD_TOGGLE);
+        vio_stq(sdev, dev->buf_list + VLAN_RXQ_BD_OFF, rxq_bd ^ VLAN_BD_TOGGLE);
     }
 
     if (sdev->signal_state & 1) {
@@ -254,8 +254,10 @@ static int check_bd(VIOsPAPRVLANDevice *dev, vlan_bd_t bd,
         return -1;
     }
 
-    if (spapr_vio_check_tces(&dev->sdev, VLAN_BD_ADDR(bd),
-                             VLAN_BD_LEN(bd), SPAPR_TCE_RW) != 0) {
+    if (!spapr_vio_dma_valid(&dev->sdev, VLAN_BD_ADDR(bd),
+                             VLAN_BD_LEN(bd), DMA_DIRECTION_FROM_DEVICE)
+        || !spapr_vio_dma_valid(&dev->sdev, VLAN_BD_ADDR(bd),
+                                VLAN_BD_LEN(bd), DMA_DIRECTION_TO_DEVICE)) {
         return -1;
     }
 
@@ -285,14 +287,14 @@ static target_ulong h_register_logical_lan(CPUPPCState *env,
         return H_RESOURCE;
     }
 
-    if (check_bd(dev, VLAN_VALID_BD(buf_list, SPAPR_VIO_TCE_PAGE_SIZE),
-                 SPAPR_VIO_TCE_PAGE_SIZE) < 0) {
+    if (check_bd(dev, VLAN_VALID_BD(buf_list, SPAPR_TCE_PAGE_SIZE),
+                 SPAPR_TCE_PAGE_SIZE) < 0) {
         hcall_dprintf("Bad buf_list 0x" TARGET_FMT_lx "\n", buf_list);
         return H_PARAMETER;
     }
 
-    filter_list_bd = VLAN_VALID_BD(filter_list, SPAPR_VIO_TCE_PAGE_SIZE);
-    if (check_bd(dev, filter_list_bd, SPAPR_VIO_TCE_PAGE_SIZE) < 0) {
+    filter_list_bd = VLAN_VALID_BD(filter_list, SPAPR_TCE_PAGE_SIZE);
+    if (check_bd(dev, filter_list_bd, SPAPR_TCE_PAGE_SIZE) < 0) {
         hcall_dprintf("Bad filter_list 0x" TARGET_FMT_lx "\n", filter_list);
         return H_PARAMETER;
     }
@@ -309,17 +311,17 @@ static target_ulong h_register_logical_lan(CPUPPCState *env,
     rec_queue &= ~VLAN_BD_TOGGLE;
 
     /* Initialize the buffer list */
-    stq_tce(sdev, buf_list, rec_queue);
-    stq_tce(sdev, buf_list + 8, filter_list_bd);
-    spapr_tce_dma_zero(sdev, buf_list + VLAN_RX_BDS_OFF,
-                       SPAPR_VIO_TCE_PAGE_SIZE - VLAN_RX_BDS_OFF);
+    vio_stq(sdev, buf_list, rec_queue);
+    vio_stq(sdev, buf_list + 8, filter_list_bd);
+    spapr_vio_dma_set(sdev, buf_list + VLAN_RX_BDS_OFF, 0,
+                      SPAPR_TCE_PAGE_SIZE - VLAN_RX_BDS_OFF);
     dev->add_buf_ptr = VLAN_RX_BDS_OFF - 8;
     dev->use_buf_ptr = VLAN_RX_BDS_OFF - 8;
     dev->rx_bufs = 0;
     dev->rxq_ptr = 0;
 
     /* Initialize the receive queue */
-    spapr_tce_dma_zero(sdev, VLAN_BD_ADDR(rec_queue), VLAN_BD_LEN(rec_queue));
+    spapr_vio_dma_set(sdev, VLAN_BD_ADDR(rec_queue), 0, VLAN_BD_LEN(rec_queue));
 
     dev->isopen = 1;
     return H_SUCCESS;
@@ -378,14 +380,14 @@ static target_ulong h_add_logical_lan_buffer(CPUPPCState *env,
 
     do {
         dev->add_buf_ptr += 8;
-        if (dev->add_buf_ptr >= SPAPR_VIO_TCE_PAGE_SIZE) {
+        if (dev->add_buf_ptr >= SPAPR_TCE_PAGE_SIZE) {
             dev->add_buf_ptr = VLAN_RX_BDS_OFF;
         }
 
-        bd = ldq_tce(sdev, dev->buf_list + dev->add_buf_ptr);
+        bd = vio_ldq(sdev, dev->buf_list + dev->add_buf_ptr);
     } while (bd & VLAN_BD_VALID);
 
-    stq_tce(sdev, dev->buf_list + dev->add_buf_ptr, buf);
+    vio_stq(sdev, dev->buf_list + dev->add_buf_ptr, buf);
 
     dev->rx_bufs++;
 
@@ -451,7 +453,7 @@ static target_ulong h_send_logical_lan(CPUPPCState *env, sPAPREnvironment *spapr
     lbuf = alloca(total_len);
     p = lbuf;
     for (i = 0; i < nbufs; i++) {
-        ret = spapr_tce_dma_read(sdev, VLAN_BD_ADDR(bufs[i]),
+        ret = spapr_vio_dma_read(sdev, VLAN_BD_ADDR(bufs[i]),
                                  p, VLAN_BD_LEN(bufs[i]));
         if (ret < 0) {
             return ret;
@@ -479,7 +481,7 @@ static target_ulong h_multicast_ctrl(CPUPPCState *env, sPAPREnvironment *spapr,
 }
 
 static Property spapr_vlan_properties[] = {
-    DEFINE_SPAPR_PROPERTIES(VIOsPAPRVLANDevice, sdev, 0x10000000),
+    DEFINE_SPAPR_PROPERTIES(VIOsPAPRVLANDevice, sdev),
     DEFINE_NIC_PROPERTIES(VIOsPAPRVLANDevice, nicconf),
     DEFINE_PROP_END_OF_LIST(),
 };
@@ -497,6 +499,7 @@ static void spapr_vlan_class_init(ObjectClass *klass, void *data)
     k->dt_compatible = "IBM,l-lan";
     k->signal_mask = 0x1;
     dc->props = spapr_vlan_properties;
+    k->rtce_window_size = 0x10000000;
 }
 
 static TypeInfo spapr_vlan_info = {
diff --git a/hw/spapr_vio.c b/hw/spapr_vio.c
index c8271c6..05b5503 100644
--- a/hw/spapr_vio.c
+++ b/hw/spapr_vio.c
@@ -39,7 +39,6 @@
 #endif /* CONFIG_FDT */
 
 /* #define DEBUG_SPAPR */
-/* #define DEBUG_TCE */
 
 #ifdef DEBUG_SPAPR
 #define dprintf(fmt, ...) \
@@ -143,26 +142,9 @@ static int vio_make_devnode(VIOsPAPRDevice *dev,
         }
     }
 
-    if (dev->rtce_window_size) {
-        uint32_t dma_prop[] = {cpu_to_be32(dev->reg),
-                               0, 0,
-                               0, cpu_to_be32(dev->rtce_window_size)};
-
-        ret = fdt_setprop_cell(fdt, node_off, "ibm,#dma-address-cells", 2);
-        if (ret < 0) {
-            return ret;
-        }
-
-        ret = fdt_setprop_cell(fdt, node_off, "ibm,#dma-size-cells", 2);
-        if (ret < 0) {
-            return ret;
-        }
-
-        ret = fdt_setprop(fdt, node_off, "ibm,my-dma-window", dma_prop,
-                          sizeof(dma_prop));
-        if (ret < 0) {
-            return ret;
-        }
+    ret = spapr_dma_dt(fdt, node_off, "ibm,my-dma-window", dev->dma);
+    if (ret < 0) {
+        return ret;
     }
 
     if (pc->devnode) {
@@ -177,232 +159,6 @@ static int vio_make_devnode(VIOsPAPRDevice *dev,
 #endif /* CONFIG_FDT */
 
 /*
- * RTCE handling
- */
-
-static void rtce_init(VIOsPAPRDevice *dev)
-{
-    size_t size = (dev->rtce_window_size >> SPAPR_VIO_TCE_PAGE_SHIFT)
-        * sizeof(VIOsPAPR_RTCE);
-
-    if (size) {
-        dev->rtce_table = kvmppc_create_spapr_tce(dev->reg,
-                                                  dev->rtce_window_size,
-                                                  &dev->kvmtce_fd);
-
-        if (!dev->rtce_table) {
-            dev->rtce_table = g_malloc0(size);
-        }
-    }
-}
-
-static target_ulong h_put_tce(CPUPPCState *env, sPAPREnvironment *spapr,
-                              target_ulong opcode, target_ulong *args)
-{
-    target_ulong liobn = args[0];
-    target_ulong ioba = args[1];
-    target_ulong tce = args[2];
-    VIOsPAPRDevice *dev = spapr_vio_find_by_reg(spapr->vio_bus, liobn);
-    VIOsPAPR_RTCE *rtce;
-
-    if (!dev) {
-        hcall_dprintf("LIOBN 0x" TARGET_FMT_lx " does not exist\n", liobn);
-        return H_PARAMETER;
-    }
-
-    ioba &= ~(SPAPR_VIO_TCE_PAGE_SIZE - 1);
-
-#ifdef DEBUG_TCE
-    fprintf(stderr, "spapr_vio_put_tce on %s  ioba 0x" TARGET_FMT_lx
-            "  TCE 0x" TARGET_FMT_lx "\n", dev->qdev.id, ioba, tce);
-#endif
-
-    if (ioba >= dev->rtce_window_size) {
-        hcall_dprintf("Out-of-bounds IOBA 0x" TARGET_FMT_lx "\n", ioba);
-        return H_PARAMETER;
-    }
-
-    rtce = dev->rtce_table + (ioba >> SPAPR_VIO_TCE_PAGE_SHIFT);
-    rtce->tce = tce;
-
-    return H_SUCCESS;
-}
-
-int spapr_vio_check_tces(VIOsPAPRDevice *dev, target_ulong ioba,
-                         target_ulong len, enum VIOsPAPR_TCEAccess access)
-{
-    int start, end, i;
-
-    start = ioba >> SPAPR_VIO_TCE_PAGE_SHIFT;
-    end = (ioba + len - 1) >> SPAPR_VIO_TCE_PAGE_SHIFT;
-
-    for (i = start; i <= end; i++) {
-        if ((dev->rtce_table[i].tce & access) != access) {
-#ifdef DEBUG_TCE
-            fprintf(stderr, "FAIL on %d\n", i);
-#endif
-            return -1;
-        }
-    }
-
-    return 0;
-}
-
-int spapr_tce_dma_write(VIOsPAPRDevice *dev, uint64_t taddr, const void *buf,
-                        uint32_t size)
-{
-#ifdef DEBUG_TCE
-    fprintf(stderr, "spapr_tce_dma_write taddr=0x%llx size=0x%x\n",
-            (unsigned long long)taddr, size);
-#endif
-
-    /* Check for bypass */
-    if (dev->flags & VIO_PAPR_FLAG_DMA_BYPASS) {
-        cpu_physical_memory_write(taddr, buf, size);
-        return 0;
-    }
-
-    while (size) {
-        uint64_t tce;
-        uint32_t lsize;
-        uint64_t txaddr;
-
-        /* Check if we are in bound */
-        if (taddr >= dev->rtce_window_size) {
-#ifdef DEBUG_TCE
-            fprintf(stderr, "spapr_tce_dma_write out of bounds\n");
-#endif
-            return H_DEST_PARM;
-        }
-        tce = dev->rtce_table[taddr >> SPAPR_VIO_TCE_PAGE_SHIFT].tce;
-
-        /* How much til end of page ? */
-        lsize = MIN(size, ((~taddr) & SPAPR_VIO_TCE_PAGE_MASK) + 1);
-
-        /* Check TCE */
-        if (!(tce & 2)) {
-            return H_DEST_PARM;
-        }
-
-        /* Translate */
-        txaddr = (tce & ~SPAPR_VIO_TCE_PAGE_MASK) |
-            (taddr & SPAPR_VIO_TCE_PAGE_MASK);
-
-#ifdef DEBUG_TCE
-        fprintf(stderr, " -> write to txaddr=0x%llx, size=0x%x\n",
-                (unsigned long long)txaddr, lsize);
-#endif
-
-        /* Do it */
-        cpu_physical_memory_write(txaddr, buf, lsize);
-        buf += lsize;
-        taddr += lsize;
-        size -= lsize;
-    }
-    return 0;
-}
-
-int spapr_tce_dma_zero(VIOsPAPRDevice *dev, uint64_t taddr, uint32_t size)
-{
-    /* FIXME: allocating a temp buffer is nasty, but just stepping
-     * through writing zeroes is awkward.  This will do for now. */
-    uint8_t zeroes[size];
-
-#ifdef DEBUG_TCE
-    fprintf(stderr, "spapr_tce_dma_zero taddr=0x%llx size=0x%x\n",
-            (unsigned long long)taddr, size);
-#endif
-
-    memset(zeroes, 0, size);
-    return spapr_tce_dma_write(dev, taddr, zeroes, size);
-}
-
-void stb_tce(VIOsPAPRDevice *dev, uint64_t taddr, uint8_t val)
-{
-    spapr_tce_dma_write(dev, taddr, &val, sizeof(val));
-}
-
-void sth_tce(VIOsPAPRDevice *dev, uint64_t taddr, uint16_t val)
-{
-    val = tswap16(val);
-    spapr_tce_dma_write(dev, taddr, &val, sizeof(val));
-}
-
-
-void stw_tce(VIOsPAPRDevice *dev, uint64_t taddr, uint32_t val)
-{
-    val = tswap32(val);
-    spapr_tce_dma_write(dev, taddr, &val, sizeof(val));
-}
-
-void stq_tce(VIOsPAPRDevice *dev, uint64_t taddr, uint64_t val)
-{
-    val = tswap64(val);
-    spapr_tce_dma_write(dev, taddr, &val, sizeof(val));
-}
-
-int spapr_tce_dma_read(VIOsPAPRDevice *dev, uint64_t taddr, void *buf,
-                       uint32_t size)
-{
-#ifdef DEBUG_TCE
-    fprintf(stderr, "spapr_tce_dma_write taddr=0x%llx size=0x%x\n",
-            (unsigned long long)taddr, size);
-#endif
-
-    /* Check for bypass */
-    if (dev->flags & VIO_PAPR_FLAG_DMA_BYPASS) {
-        cpu_physical_memory_read(taddr, buf, size);
-        return 0;
-    }
-
-    while (size) {
-        uint64_t tce;
-        uint32_t lsize;
-        uint64_t txaddr;
-
-        /* Check if we are in bound */
-        if (taddr >= dev->rtce_window_size) {
-#ifdef DEBUG_TCE
-            fprintf(stderr, "spapr_tce_dma_read out of bounds\n");
-#endif
-            return H_DEST_PARM;
-        }
-        tce = dev->rtce_table[taddr >> SPAPR_VIO_TCE_PAGE_SHIFT].tce;
-
-        /* How much til end of page ? */
-        lsize = MIN(size, ((~taddr) & SPAPR_VIO_TCE_PAGE_MASK) + 1);
-
-        /* Check TCE */
-        if (!(tce & 1)) {
-            return H_DEST_PARM;
-        }
-
-        /* Translate */
-        txaddr = (tce & ~SPAPR_VIO_TCE_PAGE_MASK) |
-            (taddr & SPAPR_VIO_TCE_PAGE_MASK);
-
-#ifdef DEBUG_TCE
-        fprintf(stderr, " -> write to txaddr=0x%llx, size=0x%x\n",
-                (unsigned long long)txaddr, lsize);
-#endif
-        /* Do it */
-        cpu_physical_memory_read(txaddr, buf, lsize);
-        buf += lsize;
-        taddr += lsize;
-        size -= lsize;
-    }
-    return H_SUCCESS;
-}
-
-uint64_t ldq_tce(VIOsPAPRDevice *dev, uint64_t taddr)
-{
-    uint64_t val;
-
-    spapr_tce_dma_read(dev, taddr, &val, sizeof(val));
-    return tswap64(val);
-}
-
-/*
  * CRQ handling
  */
 static target_ulong h_reg_crq(CPUPPCState *env, sPAPREnvironment *spapr,
@@ -526,7 +282,7 @@ int spapr_vio_send_crq(VIOsPAPRDevice *dev, uint8_t *crq)
     }
 
     /* Maybe do a fast path for KVM just writing to the pages */
-    rc = spapr_tce_dma_read(dev, dev->crq.qladdr + dev->crq.qnext, &byte, 1);
+    rc = spapr_vio_dma_read(dev, dev->crq.qladdr + dev->crq.qnext, &byte, 1);
     if (rc) {
         return rc;
     }
@@ -534,7 +290,7 @@ int spapr_vio_send_crq(VIOsPAPRDevice *dev, uint8_t *crq)
         return 1;
     }
 
-    rc = spapr_tce_dma_write(dev, dev->crq.qladdr + dev->crq.qnext + 8,
+    rc = spapr_vio_dma_write(dev, dev->crq.qladdr + dev->crq.qnext + 8,
                              &crq[8], 8);
     if (rc) {
         return rc;
@@ -542,7 +298,7 @@ int spapr_vio_send_crq(VIOsPAPRDevice *dev, uint8_t *crq)
 
     kvmppc_eieio();
 
-    rc = spapr_tce_dma_write(dev, dev->crq.qladdr + dev->crq.qnext, crq, 8);
+    rc = spapr_vio_dma_write(dev, dev->crq.qladdr + dev->crq.qnext, crq, 8);
     if (rc) {
         return rc;
     }
@@ -560,13 +316,13 @@ int spapr_vio_send_crq(VIOsPAPRDevice *dev, uint8_t *crq)
 
 static void spapr_vio_quiesce_one(VIOsPAPRDevice *dev)
 {
-    dev->flags &= ~VIO_PAPR_FLAG_DMA_BYPASS;
+    VIOsPAPRDeviceClass *pc = VIO_SPAPR_DEVICE_GET_CLASS(dev);
+    uint32_t liobn = SPAPR_VIO_BASE_LIOBN | dev->reg;
 
-    if (dev->rtce_table) {
-        size_t size = (dev->rtce_window_size >> SPAPR_VIO_TCE_PAGE_SHIFT)
-            * sizeof(VIOsPAPR_RTCE);
-        memset(dev->rtce_table, 0, size);
+    if (dev->dma) {
+        spapr_tce_free(dev->dma);
     }
+    dev->dma = spapr_tce_new_dma_context(liobn, pc->rtce_window_size);
 
     dev->crq.qladdr = 0;
     dev->crq.qsize = 0;
@@ -593,9 +349,13 @@ static void rtas_set_tce_bypass(sPAPREnvironment *spapr, uint32_t token,
         return;
     }
     if (enable) {
-        dev->flags |= VIO_PAPR_FLAG_DMA_BYPASS;
+        spapr_tce_free(dev->dma);
+        dev->dma = NULL;
     } else {
-        dev->flags &= ~VIO_PAPR_FLAG_DMA_BYPASS;
+        VIOsPAPRDeviceClass *pc = VIO_SPAPR_DEVICE_GET_CLASS(dev);
+        uint32_t liobn = SPAPR_VIO_BASE_LIOBN | dev->reg;
+
+        dev->dma = spapr_tce_new_dma_context(liobn, pc->rtce_window_size);
     }
 
     rtas_st(rets, 0, 0);
@@ -662,6 +422,7 @@ static int spapr_vio_busdev_init(DeviceState *qdev)
 {
     VIOsPAPRDevice *dev = (VIOsPAPRDevice *)qdev;
     VIOsPAPRDeviceClass *pc = VIO_SPAPR_DEVICE_GET_CLASS(dev);
+    uint32_t liobn;
     char *id;
 
     if (dev->reg != -1) {
@@ -703,7 +464,8 @@ static int spapr_vio_busdev_init(DeviceState *qdev)
         return -1;
     }
 
-    rtce_init(dev);
+    liobn = SPAPR_VIO_BASE_LIOBN | dev->reg;
+    dev->dma = spapr_tce_new_dma_context(liobn, pc->rtce_window_size);
 
     return pc->init(dev);
 }
@@ -751,9 +513,6 @@ VIOsPAPRBus *spapr_vio_bus_init(void)
     /* hcall-vio */
     spapr_register_hypercall(H_VIO_SIGNAL, h_vio_signal);
 
-    /* hcall-tce */
-    spapr_register_hypercall(H_PUT_TCE, h_put_tce);
-
     /* hcall-crq */
     spapr_register_hypercall(H_REG_CRQ, h_reg_crq);
     spapr_register_hypercall(H_FREE_CRQ, h_free_crq);
diff --git a/hw/spapr_vio.h b/hw/spapr_vio.h
index 2adad77..6f9a498 100644
--- a/hw/spapr_vio.h
+++ b/hw/spapr_vio.h
@@ -21,16 +21,7 @@
  * License along with this library; if not, see <http://www.gnu.org/licenses/>.
  */
 
-#define SPAPR_VIO_TCE_PAGE_SHIFT   12
-#define SPAPR_VIO_TCE_PAGE_SIZE    (1ULL << SPAPR_VIO_TCE_PAGE_SHIFT)
-#define SPAPR_VIO_TCE_PAGE_MASK    (SPAPR_VIO_TCE_PAGE_SIZE - 1)
-
-enum VIOsPAPR_TCEAccess {
-    SPAPR_TCE_FAULT = 0,
-    SPAPR_TCE_RO = 1,
-    SPAPR_TCE_WO = 2,
-    SPAPR_TCE_RW = 3,
-};
+#include "dma.h"
 
 #define TYPE_VIO_SPAPR_DEVICE "vio-spapr-device"
 #define VIO_SPAPR_DEVICE(obj) \
@@ -45,10 +36,6 @@ enum VIOsPAPR_TCEAccess {
 
 struct VIOsPAPRDevice;
 
-typedef struct VIOsPAPR_RTCE {
-    uint64_t tce;
-} VIOsPAPR_RTCE;
-
 typedef struct VIOsPAPR_CRQ {
     uint64_t qladdr;
     uint32_t qsize;
@@ -64,6 +51,7 @@ typedef struct VIOsPAPRDeviceClass {
 
     const char *dt_name, *dt_type, *dt_compatible;
     target_ulong signal_mask;
+    uint32_t rtce_window_size;
     int (*init)(VIOsPAPRDevice *dev);
     void (*reset)(VIOsPAPRDevice *dev);
     int (*devnode)(VIOsPAPRDevice *dev, void *fdt, int node_off);
@@ -73,20 +61,15 @@ struct VIOsPAPRDevice {
     DeviceState qdev;
     uint32_t reg;
     uint32_t flags;
-#define VIO_PAPR_FLAG_DMA_BYPASS        0x1
     qemu_irq qirq;
     uint32_t vio_irq_num;
     target_ulong signal_state;
-    uint32_t rtce_window_size;
-    VIOsPAPR_RTCE *rtce_table;
-    int kvmtce_fd;
     VIOsPAPR_CRQ crq;
+    DMAContext *dma;
 };
 
-#define DEFINE_SPAPR_PROPERTIES(type, field, default_dma_window)       \
-        DEFINE_PROP_UINT32("reg", type, field.reg, -1),                \
-        DEFINE_PROP_UINT32("dma-window", type, field.rtce_window_size, \
-                           default_dma_window)
+#define DEFINE_SPAPR_PROPERTIES(type, field)           \
+        DEFINE_PROP_UINT32("reg", type, field.reg, -1)
 
 struct VIOsPAPRBus {
     BusState bus;
@@ -102,20 +85,38 @@ extern int spapr_populate_chosen_stdout(void *fdt, VIOsPAPRBus *bus);
 
 extern int spapr_vio_signal(VIOsPAPRDevice *dev, target_ulong mode);
 
-int spapr_vio_check_tces(VIOsPAPRDevice *dev, target_ulong ioba,
-                         target_ulong len,
-                         enum VIOsPAPR_TCEAccess access);
-
-int spapr_tce_dma_read(VIOsPAPRDevice *dev, uint64_t taddr,
-                       void *buf, uint32_t size);
-int spapr_tce_dma_write(VIOsPAPRDevice *dev, uint64_t taddr,
-                        const void *buf, uint32_t size);
-int spapr_tce_dma_zero(VIOsPAPRDevice *dev, uint64_t taddr, uint32_t size);
-void stb_tce(VIOsPAPRDevice *dev, uint64_t taddr, uint8_t val);
-void sth_tce(VIOsPAPRDevice *dev, uint64_t taddr, uint16_t val);
-void stw_tce(VIOsPAPRDevice *dev, uint64_t taddr, uint32_t val);
-void stq_tce(VIOsPAPRDevice *dev, uint64_t taddr, uint64_t val);
-uint64_t ldq_tce(VIOsPAPRDevice *dev, uint64_t taddr);
+static inline bool spapr_vio_dma_valid(VIOsPAPRDevice *dev, uint64_t taddr,
+                                       uint32_t size, DMADirection dir)
+{
+    return dma_memory_valid(dev->dma, taddr, size, dir);
+}
+
+static inline int spapr_vio_dma_read(VIOsPAPRDevice *dev, uint64_t taddr,
+                                     void *buf, uint32_t size)
+{
+    return (dma_memory_read(dev->dma, taddr, buf, size) != 0) ?
+        H_DEST_PARM : H_SUCCESS;
+}
+
+static inline int spapr_vio_dma_write(VIOsPAPRDevice *dev, uint64_t taddr,
+                                      const void *buf, uint32_t size)
+{
+    return (dma_memory_write(dev->dma, taddr, buf, size) != 0) ?
+        H_DEST_PARM : H_SUCCESS;
+}
+
+static inline int spapr_vio_dma_set(VIOsPAPRDevice *dev, uint64_t taddr,
+                                    uint8_t c, uint32_t size)
+{
+    return (dma_memory_set(dev->dma, taddr, c, size) != 0) ?
+        H_DEST_PARM : H_SUCCESS;
+}
+
+#define vio_stb(_dev, _addr, _val) (stb_dma((_dev)->dma, (_addr), (_val)))
+#define vio_sth(_dev, _addr, _val) (stw_be_dma((_dev)->dma, (_addr), (_val)))
+#define vio_stl(_dev, _addr, _val) (stl_be_dma((_dev)->dma, (_addr), (_val)))
+#define vio_stq(_dev, _addr, _val) (stq_be_dma((_dev)->dma, (_addr), (_val)))
+#define vio_ldq(_dev, _addr) (ldq_be_dma((_dev)->dma, (_addr)))
 
 int spapr_vio_send_crq(VIOsPAPRDevice *dev, uint8_t *crq);
 
diff --git a/hw/spapr_vscsi.c b/hw/spapr_vscsi.c
index 2f09616..3cf5844 100644
--- a/hw/spapr_vscsi.c
+++ b/hw/spapr_vscsi.c
@@ -165,7 +165,7 @@ static int vscsi_send_iu(VSCSIState *s, vscsi_req *req,
     long rc, rc1;
 
     /* First copy the SRP */
-    rc = spapr_tce_dma_write(&s->vdev, req->crq.s.IU_data_ptr,
+    rc = spapr_vio_dma_write(&s->vdev, req->crq.s.IU_data_ptr,
                              &req->iu, length);
     if (rc) {
         fprintf(stderr, "vscsi_send_iu: DMA write failure !\n");
@@ -281,9 +281,9 @@ static int vscsi_srp_direct_data(VSCSIState *s, vscsi_req *req,
     llen = MIN(len, md->len);
     if (llen) {
         if (req->writing) { /* writing = to device = reading from memory */
-            rc = spapr_tce_dma_read(&s->vdev, md->va, buf, llen);
+            rc = spapr_vio_dma_read(&s->vdev, md->va, buf, llen);
         } else {
-            rc = spapr_tce_dma_write(&s->vdev, md->va, buf, llen);
+            rc = spapr_vio_dma_write(&s->vdev, md->va, buf, llen);
         }
     }
     md->len -= llen;
@@ -329,10 +329,11 @@ static int vscsi_srp_indirect_data(VSCSIState *s, vscsi_req *req,
             md = req->cur_desc = &req->ext_desc;
             dprintf("VSCSI:   Reading desc from 0x%llx\n",
                     (unsigned long long)td->va);
-            rc = spapr_tce_dma_read(&s->vdev, td->va, md,
+            rc = spapr_vio_dma_read(&s->vdev, td->va, md,
                                     sizeof(struct srp_direct_buf));
             if (rc) {
-                dprintf("VSCSI: tce_dma_read -> %d reading ext_desc\n", rc);
+                dprintf("VSCSI: spapr_vio_dma_read -> %d reading ext_desc\n",
+                        rc);
                 break;
             }
             vscsi_swap_desc(md);
@@ -345,12 +346,12 @@ static int vscsi_srp_indirect_data(VSCSIState *s, vscsi_req *req,
         /* Perform transfer */
         llen = MIN(len, md->len);
         if (req->writing) { /* writing = to device = reading from memory */
-            rc = spapr_tce_dma_read(&s->vdev, md->va, buf, llen);
+            rc = spapr_vio_dma_read(&s->vdev, md->va, buf, llen);
         } else {
-            rc = spapr_tce_dma_write(&s->vdev, md->va, buf, llen);
+            rc = spapr_vio_dma_write(&s->vdev, md->va, buf, llen);
         }
         if (rc) {
-            dprintf("VSCSI: tce_dma_r/w(%d) -> %d\n", req->writing, rc);
+            dprintf("VSCSI: spapr_vio_dma_r/w(%d) -> %d\n", req->writing, rc);
             break;
         }
         dprintf("VSCSI:     data: %02x %02x %02x %02x...\n",
@@ -728,7 +729,7 @@ static int vscsi_send_adapter_info(VSCSIState *s, vscsi_req *req)
     sinfo = &req->iu.mad.adapter_info;
 
 #if 0 /* What for ? */
-    rc = spapr_tce_dma_read(&s->vdev, be64_to_cpu(sinfo->buffer),
+    rc = spapr_vio_dma_read(&s->vdev, be64_to_cpu(sinfo->buffer),
                             &info, be16_to_cpu(sinfo->common.length));
     if (rc) {
         fprintf(stderr, "vscsi_send_adapter_info: DMA read failure !\n");
@@ -742,7 +743,7 @@ static int vscsi_send_adapter_info(VSCSIState *s, vscsi_req *req)
     info.os_type = cpu_to_be32(2);
     info.port_max_txu[0] = cpu_to_be32(VSCSI_MAX_SECTORS << 9);
 
-    rc = spapr_tce_dma_write(&s->vdev, be64_to_cpu(sinfo->buffer),
+    rc = spapr_vio_dma_write(&s->vdev, be64_to_cpu(sinfo->buffer),
                              &info, be16_to_cpu(sinfo->common.length));
     if (rc)  {
         fprintf(stderr, "vscsi_send_adapter_info: DMA write failure !\n");
@@ -805,7 +806,7 @@ static void vscsi_got_payload(VSCSIState *s, vscsi_crq *crq)
     }
 
     /* XXX Handle failure differently ? */
-    if (spapr_tce_dma_read(&s->vdev, crq->s.IU_data_ptr, &req->iu,
+    if (spapr_vio_dma_read(&s->vdev, crq->s.IU_data_ptr, &req->iu,
                            crq->s.IU_length)) {
         fprintf(stderr, "vscsi_got_payload: DMA read failure !\n");
         vscsi_put_req(req);
@@ -947,7 +948,7 @@ static int spapr_vscsi_devnode(VIOsPAPRDevice *dev, void *fdt, int node_off)
 }
 
 static Property spapr_vscsi_properties[] = {
-    DEFINE_SPAPR_PROPERTIES(VSCSIState, vdev, 0x10000000),
+    DEFINE_SPAPR_PROPERTIES(VSCSIState, vdev),
     DEFINE_PROP_END_OF_LIST(),
 };
 
@@ -964,6 +965,7 @@ static void spapr_vscsi_class_init(ObjectClass *klass, void *data)
     k->dt_compatible = "IBM,v-scsi";
     k->signal_mask = 0x00000001;
     dc->props = spapr_vscsi_properties;
+    k->rtce_window_size = 0x10000000;
 }
 
 static TypeInfo spapr_vscsi_info = {
diff --git a/hw/spapr_vty.c b/hw/spapr_vty.c
index f340b83..99e52cc 100644
--- a/hw/spapr_vty.c
+++ b/hw/spapr_vty.c
@@ -133,7 +133,7 @@ void spapr_vty_create(VIOsPAPRBus *bus, CharDriverState *chardev)
 }
 
 static Property spapr_vty_properties[] = {
-    DEFINE_SPAPR_PROPERTIES(VIOsPAPRVTYDevice, sdev, 0),
+    DEFINE_SPAPR_PROPERTIES(VIOsPAPRVTYDevice, sdev),
     DEFINE_PROP_CHR("chardev", VIOsPAPRVTYDevice, chardev),
     DEFINE_PROP_END_OF_LIST(),
 };
diff --git a/target-ppc/kvm.c b/target-ppc/kvm.c
index b6ef72d..829e180 100644
--- a/target-ppc/kvm.c
+++ b/target-ppc/kvm.c
@@ -1067,7 +1067,7 @@ void *kvmppc_create_spapr_tce(uint32_t liobn, uint32_t window_size, int *pfd)
         return NULL;
     }
 
-    len = (window_size / SPAPR_VIO_TCE_PAGE_SIZE) * sizeof(VIOsPAPR_RTCE);
+    len = (window_size / SPAPR_TCE_PAGE_SIZE) * sizeof(sPAPRTCE);
     /* FIXME: round this up to page size */
 
     table = mmap(NULL, len, PROT_READ|PROT_WRITE, MAP_SHARED, fd, 0);
@@ -1090,7 +1090,7 @@ int kvmppc_remove_spapr_tce(void *table, int fd, uint32_t window_size)
         return -1;
     }
 
-    len = (window_size / SPAPR_VIO_TCE_PAGE_SIZE)*sizeof(VIOsPAPR_RTCE);
+    len = (window_size / SPAPR_TCE_PAGE_SIZE)*sizeof(sPAPRTCE);
     if ((munmap(table, len) < 0) ||
         (close(fd) < 0)) {
         fprintf(stderr, "KVM: Unexpected error removing TCE table: %s",
commit e5332e6334f375600b0c15f5c3540c1b72af7067
Author: David Gibson <david at gibson.dropbear.id.au>
Date:   Wed Jun 27 14:50:43 2012 +1000

    iommu: Introduce IOMMU emulation infrastructure
    
    This patch adds the basic infrastructure necessary to emulate an IOMMU
    visible to the guest.  The DMAContext structure is extended with
    information and a callback describing the translation, and the various
    DMA functions used by devices will now perform IOMMU translation using
    this callback.
    
    Cc: Michael S. Tsirkin <mst at redhat.com>
    Cc: Richard Henderson <rth at twiddle.net>
    
    Signed-off-by: Eduard - Gabriel Munteanu <eduard.munteanu at linux360.ro>
    Signed-off-by: David Gibson <david at gibson.dropbear.id.au>
    Signed-off-by: Benjamin Herrenschmidt <benh at kernel.crashing.org>
    Signed-off-by: Anthony Liguori <aliguori at us.ibm.com>

diff --git a/dma-helpers.c b/dma-helpers.c
index 4c9e529..2e09ceb 100644
--- a/dma-helpers.c
+++ b/dma-helpers.c
@@ -9,8 +9,12 @@
 
 #include "dma.h"
 #include "trace.h"
+#include "range.h"
+#include "qemu-thread.h"
 
-int dma_memory_set(DMAContext *dma, dma_addr_t addr, uint8_t c, dma_addr_t len)
+/* #define DEBUG_IOMMU */
+
+static void do_dma_memory_set(dma_addr_t addr, uint8_t c, dma_addr_t len)
 {
 #define FILLBUF_SIZE 512
     uint8_t fillbuf[FILLBUF_SIZE];
@@ -23,6 +27,15 @@ int dma_memory_set(DMAContext *dma, dma_addr_t addr, uint8_t c, dma_addr_t len)
         len -= len;
         addr += len;
     }
+}
+
+int dma_memory_set(DMAContext *dma, dma_addr_t addr, uint8_t c, dma_addr_t len)
+{
+    if (dma_has_iommu(dma)) {
+        return iommu_dma_memory_set(dma, addr, c, len);
+    }
+    do_dma_memory_set(addr, c, len);
+
     return 0;
 }
 
@@ -260,3 +273,160 @@ void dma_acct_start(BlockDriverState *bs, BlockAcctCookie *cookie,
 {
     bdrv_acct_start(bs, cookie, sg->size, type);
 }
+
+bool iommu_dma_memory_valid(DMAContext *dma, dma_addr_t addr, dma_addr_t len,
+                            DMADirection dir)
+{
+    target_phys_addr_t paddr, plen;
+
+#ifdef DEBUG_IOMMU
+    fprintf(stderr, "dma_memory_check context=%p addr=0x" DMA_ADDR_FMT
+            " len=0x" DMA_ADDR_FMT " dir=%d\n", dma, addr, len, dir);
+#endif
+
+    while (len) {
+        if (dma->translate(dma, addr, &paddr, &plen, dir) != 0) {
+            return false;
+        }
+
+        /* The translation might be valid for larger regions. */
+        if (plen > len) {
+            plen = len;
+        }
+
+        len -= plen;
+        addr += plen;
+    }
+
+    return true;
+}
+
+int iommu_dma_memory_rw(DMAContext *dma, dma_addr_t addr,
+                        void *buf, dma_addr_t len, DMADirection dir)
+{
+    target_phys_addr_t paddr, plen;
+    int err;
+
+#ifdef DEBUG_IOMMU
+    fprintf(stderr, "dma_memory_rw context=%p addr=0x" DMA_ADDR_FMT " len=0x"
+            DMA_ADDR_FMT " dir=%d\n", dma, addr, len, dir);
+#endif
+
+    while (len) {
+        err = dma->translate(dma, addr, &paddr, &plen, dir);
+        if (err) {
+	    /*
+             * In case of failure on reads from the guest, we clean the
+             * destination buffer so that a device that doesn't test
+             * for errors will not expose qemu internal memory.
+	     */
+	    memset(buf, 0, len);
+            return -1;
+        }
+
+        /* The translation might be valid for larger regions. */
+        if (plen > len) {
+            plen = len;
+        }
+
+        cpu_physical_memory_rw(paddr, buf, plen,
+                               dir == DMA_DIRECTION_FROM_DEVICE);
+
+        len -= plen;
+        addr += plen;
+        buf += plen;
+    }
+
+    return 0;
+}
+
+int iommu_dma_memory_set(DMAContext *dma, dma_addr_t addr, uint8_t c,
+                         dma_addr_t len)
+{
+    target_phys_addr_t paddr, plen;
+    int err;
+
+#ifdef DEBUG_IOMMU
+    fprintf(stderr, "dma_memory_set context=%p addr=0x" DMA_ADDR_FMT
+            " len=0x" DMA_ADDR_FMT "\n", dma, addr, len);
+#endif
+
+    while (len) {
+        err = dma->translate(dma, addr, &paddr, &plen,
+                             DMA_DIRECTION_FROM_DEVICE);
+        if (err) {
+            return err;
+        }
+
+        /* The translation might be valid for larger regions. */
+        if (plen > len) {
+            plen = len;
+        }
+
+        do_dma_memory_set(paddr, c, plen);
+
+        len -= plen;
+        addr += plen;
+    }
+
+    return 0;
+}
+
+void dma_context_init(DMAContext *dma, DMATranslateFunc translate,
+                      DMAMapFunc map, DMAUnmapFunc unmap)
+{
+#ifdef DEBUG_IOMMU
+    fprintf(stderr, "dma_context_init(%p, %p, %p, %p)\n",
+            dma, translate, map, unmap);
+#endif
+    dma->translate = translate;
+    dma->map = map;
+    dma->unmap = unmap;
+}
+
+void *iommu_dma_memory_map(DMAContext *dma, dma_addr_t addr, dma_addr_t *len,
+                           DMADirection dir)
+{
+    int err;
+    target_phys_addr_t paddr, plen;
+    void *buf;
+
+    if (dma->map) {
+        return dma->map(dma, addr, len, dir);
+    }
+
+    plen = *len;
+    err = dma->translate(dma, addr, &paddr, &plen, dir);
+    if (err) {
+        return NULL;
+    }
+
+    /*
+     * If this is true, the virtual region is contiguous,
+     * but the translated physical region isn't. We just
+     * clamp *len, much like cpu_physical_memory_map() does.
+     */
+    if (plen < *len) {
+        *len = plen;
+    }
+
+    buf = cpu_physical_memory_map(paddr, &plen,
+                                  dir == DMA_DIRECTION_FROM_DEVICE);
+    *len = plen;
+
+    return buf;
+}
+
+void iommu_dma_memory_unmap(DMAContext *dma, void *buffer, dma_addr_t len,
+                            DMADirection dir, dma_addr_t access_len)
+{
+    if (dma->unmap) {
+        dma->unmap(dma, buffer, len, dir, access_len);
+        return;
+    }
+
+    cpu_physical_memory_unmap(buffer, len,
+                              dir == DMA_DIRECTION_FROM_DEVICE,
+                              access_len);
+
+}
diff --git a/dma.h b/dma.h
index e93076a..f52a656 100644
--- a/dma.h
+++ b/dma.h
@@ -31,28 +31,74 @@ struct QEMUSGList {
 };
 
 #if defined(TARGET_PHYS_ADDR_BITS)
-typedef target_phys_addr_t dma_addr_t;
 
-#define DMA_ADDR_BITS TARGET_PHYS_ADDR_BITS
-#define DMA_ADDR_FMT TARGET_FMT_plx
+/*
+ * When an IOMMU is present, bus addresses become distinct from
+ * CPU/memory physical addresses and may be a different size.  Because
+ * the IOVA size depends more on the bus than on the platform, we more
+ * or less have to treat these as 64-bit always to cover all (or at
+ * least most) cases.
+ */
+typedef uint64_t dma_addr_t;
+
+#define DMA_ADDR_BITS 64
+#define DMA_ADDR_FMT "%" PRIx64
+
+typedef int DMATranslateFunc(DMAContext *dma,
+                             dma_addr_t addr,
+                             target_phys_addr_t *paddr,
+                             target_phys_addr_t *len,
+                             DMADirection dir);
+typedef void* DMAMapFunc(DMAContext *dma,
+                         dma_addr_t addr,
+                         dma_addr_t *len,
+                         DMADirection dir);
+typedef void DMAUnmapFunc(DMAContext *dma,
+                          void *buffer,
+                          dma_addr_t len,
+                          DMADirection dir,
+                          dma_addr_t access_len);
+
+struct DMAContext {
+    DMATranslateFunc *translate;
+    DMAMapFunc *map;
+    DMAUnmapFunc *unmap;
+};
+
+static inline bool dma_has_iommu(DMAContext *dma)
+{
+    return !!dma;
+}
 
 /* Checks that the given range of addresses is valid for DMA.  This is
  * useful for certain cases, but usually you should just use
  * dma_memory_{read,write}() and check for errors */
-static inline bool dma_memory_valid(DMAContext *dma, dma_addr_t addr,
-                                    dma_addr_t len, DMADirection dir)
+bool iommu_dma_memory_valid(DMAContext *dma, dma_addr_t addr, dma_addr_t len,
+                            DMADirection dir);
+static inline bool dma_memory_valid(DMAContext *dma,
+                                    dma_addr_t addr, dma_addr_t len,
+                                    DMADirection dir)
 {
-    /* Stub version, with no iommu we assume all bus addresses are valid */
-    return true;
+    if (!dma_has_iommu(dma)) {
+        return true;
+    } else {
+        return iommu_dma_memory_valid(dma, addr, len, dir);
+    }
 }
 
+int iommu_dma_memory_rw(DMAContext *dma, dma_addr_t addr,
+                        void *buf, dma_addr_t len, DMADirection dir);
 static inline int dma_memory_rw(DMAContext *dma, dma_addr_t addr,
                                 void *buf, dma_addr_t len, DMADirection dir)
 {
-    /* Stub version when we have no iommu support */
-    cpu_physical_memory_rw(addr, buf, (target_phys_addr_t)len,
-                           dir == DMA_DIRECTION_FROM_DEVICE);
-    return 0;
+    if (!dma_has_iommu(dma)) {
+        /* Fast-path for no IOMMU */
+        cpu_physical_memory_rw(addr, buf, len,
+                               dir == DMA_DIRECTION_FROM_DEVICE);
+        return 0;
+    } else {
+        return iommu_dma_memory_rw(dma, addr, buf, len, dir);
+    }
 }
 
 static inline int dma_memory_read(DMAContext *dma, dma_addr_t addr,
@@ -68,28 +114,45 @@ static inline int dma_memory_write(DMAContext *dma, dma_addr_t addr,
                          DMA_DIRECTION_FROM_DEVICE);
 }
 
+int iommu_dma_memory_set(DMAContext *dma, dma_addr_t addr, uint8_t c,
+			 dma_addr_t len);
+
 int dma_memory_set(DMAContext *dma, dma_addr_t addr, uint8_t c, dma_addr_t len);
 
+void *iommu_dma_memory_map(DMAContext *dma,
+                           dma_addr_t addr, dma_addr_t *len,
+                           DMADirection dir);
 static inline void *dma_memory_map(DMAContext *dma,
                                    dma_addr_t addr, dma_addr_t *len,
                                    DMADirection dir)
 {
-    target_phys_addr_t xlen = *len;
-    void *p;
-
-    p = cpu_physical_memory_map(addr, &xlen,
-                                dir == DMA_DIRECTION_FROM_DEVICE);
-    *len = xlen;
-    return p;
+    if (!dma_has_iommu(dma)) {
+        target_phys_addr_t xlen = *len;
+        void *p;
+
+        p = cpu_physical_memory_map(addr, &xlen,
+                                    dir == DMA_DIRECTION_FROM_DEVICE);
+        *len = xlen;
+        return p;
+    } else {
+        return iommu_dma_memory_map(dma, addr, len, dir);
+    }
 }
 
+void iommu_dma_memory_unmap(DMAContext *dma,
+                            void *buffer, dma_addr_t len,
+                            DMADirection dir, dma_addr_t access_len);
 static inline void dma_memory_unmap(DMAContext *dma,
                                     void *buffer, dma_addr_t len,
                                     DMADirection dir, dma_addr_t access_len)
 {
-    return cpu_physical_memory_unmap(buffer, (target_phys_addr_t)len,
-                                     dir == DMA_DIRECTION_FROM_DEVICE,
-                                     access_len);
+    if (!dma_has_iommu(dma)) {
+        return cpu_physical_memory_unmap(buffer, (target_phys_addr_t)len,
+                                         dir == DMA_DIRECTION_FROM_DEVICE,
+                                         access_len);
+    } else {
+        iommu_dma_memory_unmap(dma, buffer, len, dir, access_len);
+    }
 }
 
 #define DEFINE_LDST_DMA(_lname, _sname, _bits, _end) \
@@ -130,6 +193,9 @@ DEFINE_LDST_DMA(q, q, 64, be);
 
 #undef DEFINE_LDST_DMA
 
+void dma_context_init(DMAContext *dma, DMATranslateFunc translate,
+                      DMAMapFunc map, DMAUnmapFunc unmap);
+
 struct ScatterGatherEntry {
     dma_addr_t base;
     dma_addr_t len;
diff --git a/hw/qdev-dma.h b/hw/qdev-dma.h
index f0ff558..6812735 100644
--- a/hw/qdev-dma.h
+++ b/hw/qdev-dma.h
@@ -6,7 +6,5 @@
  * This work is licensed under the terms of the GNU GPL, version 2 or later.
  * See the COPYING file in the top-level directory.
  */
-#include "qdev-addr.h"
-
 #define DEFINE_PROP_DMAADDR(_n, _s, _f, _d)                               \
-    DEFINE_PROP_TADDR(_n, _s, _f, _d)
+    DEFINE_PROP_HEX64(_n, _s, _f, _d)
commit e2f89926f19d2940eda070542501f39f51a8c81f
Author: David Gibson <david at gibson.dropbear.id.au>
Date:   Wed Jun 27 14:50:42 2012 +1000

    usb: Convert usb_packet_{map, unmap} to universal DMA helpers
    
    The USB UHCI and EHCI drivers were converted some time ago to use the
    pci_dma_*() helper functions.  However, this conversion was not complete
    because in some places both these drivers do DMA via the usb_packet_map()
    function in usb-libhw.c.  That function directly used
    cpu_physical_memory_map().
    
    Now that the sglist code uses DMA wrappers properly, we can convert the
    functions in usb-libhw.c, thus conpleting the conversion of UHCI and EHCI
    to use the DMA wrappers.
    
    Note that usb_packet_map() invokes dma_memory_map() with a NULL invalidate
    callback function.  When IOMMU support is added, this will mean that
    usb_packet_map() and the corresponding usb_packet_unmap() must be called in
    close proximity without dropping the qemu device lock - otherwise the guest
    might invalidate IOMMU mappings while they are still in use by the device
    code.
    
    Signed-off-by: David Gibson <david at gibson.dropbear.id.au>
    Signed-off-by: Benjamin Herrenschmidt <benh at kernel.crashing.org>
    Signed-off-by: Anthony Liguori <aliguori at us.ibm.com>

diff --git a/hw/usb.h b/hw/usb.h
index 2a56fe5..a5623d3 100644
--- a/hw/usb.h
+++ b/hw/usb.h
@@ -345,7 +345,7 @@ void usb_packet_check_state(USBPacket *p, USBPacketState expected);
 void usb_packet_setup(USBPacket *p, int pid, USBEndpoint *ep);
 void usb_packet_addbuf(USBPacket *p, void *ptr, size_t len);
 int usb_packet_map(USBPacket *p, QEMUSGList *sgl);
-void usb_packet_unmap(USBPacket *p);
+void usb_packet_unmap(USBPacket *p, QEMUSGList *sgl);
 void usb_packet_copy(USBPacket *p, void *ptr, size_t bytes);
 void usb_packet_skip(USBPacket *p, size_t bytes);
 void usb_packet_cleanup(USBPacket *p);
diff --git a/hw/usb/hcd-ehci.c b/hw/usb/hcd-ehci.c
index 6d2d549..1582c2c 100644
--- a/hw/usb/hcd-ehci.c
+++ b/hw/usb/hcd-ehci.c
@@ -1426,8 +1426,8 @@ static void ehci_execute_complete(EHCIQueue *q)
         set_field(&q->qh.token, p->tbytes, QTD_TOKEN_TBYTES);
     }
     ehci_finish_transfer(q, p->usb_status);
+    usb_packet_unmap(&p->packet, &p->sgl);
     qemu_sglist_destroy(&p->sgl);
-    usb_packet_unmap(&p->packet);
 
     q->qh.token ^= QTD_TOKEN_DTOGGLE;
     q->qh.token &= ~QTD_TOKEN_ACTIVE;
@@ -1551,7 +1551,7 @@ static int ehci_process_itd(EHCIState *ehci,
                 usb_packet_map(&ehci->ipacket, &ehci->isgl);
                 ret = usb_handle_packet(dev, &ehci->ipacket);
                 assert(ret != USB_RET_ASYNC);
-                usb_packet_unmap(&ehci->ipacket);
+                usb_packet_unmap(&ehci->ipacket, &ehci->isgl);
             } else {
                 DPRINTF("ISOCH: attempt to addess non-iso endpoint\n");
                 ret = USB_RET_NAK;
diff --git a/hw/usb/hcd-uhci.c b/hw/usb/hcd-uhci.c
index 2ebce04..8f652d2 100644
--- a/hw/usb/hcd-uhci.c
+++ b/hw/usb/hcd-uhci.c
@@ -871,7 +871,7 @@ static int uhci_handle_td(UHCIState *s, uint32_t addr, UHCI_TD *td,
 
 done:
     len = uhci_complete_td(s, td, async, int_mask);
-    usb_packet_unmap(&async->packet);
+    usb_packet_unmap(&async->packet, &async->sgl);
     uhci_async_free(async);
     return len;
 }
diff --git a/hw/usb/libhw.c b/hw/usb/libhw.c
index 2462351..c0de30e 100644
--- a/hw/usb/libhw.c
+++ b/hw/usb/libhw.c
@@ -26,15 +26,15 @@
 
 int usb_packet_map(USBPacket *p, QEMUSGList *sgl)
 {
-    int is_write = (p->pid == USB_TOKEN_IN);
-    target_phys_addr_t len;
+    DMADirection dir = (p->pid == USB_TOKEN_IN) ?
+        DMA_DIRECTION_FROM_DEVICE : DMA_DIRECTION_TO_DEVICE;
+    dma_addr_t len;
     void *mem;
     int i;
 
     for (i = 0; i < sgl->nsg; i++) {
         len = sgl->sg[i].len;
-        mem = cpu_physical_memory_map(sgl->sg[i].base, &len,
-                                      is_write);
+        mem = dma_memory_map(sgl->dma, sgl->sg[i].base, &len, dir);
         if (!mem) {
             goto err;
         }
@@ -46,18 +46,19 @@ int usb_packet_map(USBPacket *p, QEMUSGList *sgl)
     return 0;
 
 err:
-    usb_packet_unmap(p);
+    usb_packet_unmap(p, sgl);
     return -1;
 }
 
-void usb_packet_unmap(USBPacket *p)
+void usb_packet_unmap(USBPacket *p, QEMUSGList *sgl)
 {
-    int is_write = (p->pid == USB_TOKEN_IN);
+    DMADirection dir = (p->pid == USB_TOKEN_IN) ?
+        DMA_DIRECTION_FROM_DEVICE : DMA_DIRECTION_TO_DEVICE;
     int i;
 
     for (i = 0; i < p->iov.niov; i++) {
-        cpu_physical_memory_unmap(p->iov.iov[i].iov_base,
-                                  p->iov.iov[i].iov_len, is_write,
-                                  p->iov.iov[i].iov_len);
+        dma_memory_unmap(sgl->dma, p->iov.iov[i].iov_base,
+                         p->iov.iov[i].iov_len, dir,
+                         p->iov.iov[i].iov_len);
     }
 }
commit 10ca2943aab6646839769d78f80b0d5499efcbe9
Author: David Gibson <david at gibson.dropbear.id.au>
Date:   Wed Jun 27 14:50:41 2012 +1000

    ide/ahci: Use universal DMA helper functions
    
    The AHCI device can provide both PCI and SysBus AHCI device
    emulations.  For this reason, it wasn't previously converted to use
    the pci_dma_*() helper functions.  Now that we have universal DMA
    helper functions, this converts AHCI to use them.
    
    The DMAContext is obtained from pci_dma_context() in the PCI case and
    set to NULL in the SysBus case (i.e. we assume for now that a SysBus
    AHCI has no IOMMU translation).
    
    Cc: Kevin Wolf <kwolf at redhat.com>
    Cc: Michael S. Tsirkin <mst at redhat.com>
    
    Signed-off-by: David Gibson <david at gibson.dropbear.id.au>
    Signed-off-by: Benjamin Herrenschmidt <benh at kernel.crashing.org>
    Signed-off-by: Anthony Liguori <aliguori at us.ibm.com>

diff --git a/hw/ide/ahci.c b/hw/ide/ahci.c
index 6c4226d..efea93f 100644
--- a/hw/ide/ahci.c
+++ b/hw/ide/ahci.c
@@ -588,7 +588,7 @@ static void ahci_write_fis_d2h(AHCIDevice *ad, uint8_t *cmd_fis)
     AHCIPortRegs *pr = &ad->port_regs;
     uint8_t *d2h_fis;
     int i;
-    target_phys_addr_t cmd_len = 0x80;
+    dma_addr_t cmd_len = 0x80;
     int cmd_mapped = 0;
 
     if (!ad->res_fis || !(pr->cmd & PORT_CMD_FIS_RX)) {
@@ -598,7 +598,8 @@ static void ahci_write_fis_d2h(AHCIDevice *ad, uint8_t *cmd_fis)
     if (!cmd_fis) {
         /* map cmd_fis */
         uint64_t tbl_addr = le64_to_cpu(ad->cur_cmd->tbl_addr);
-        cmd_fis = cpu_physical_memory_map(tbl_addr, &cmd_len, 0);
+        cmd_fis = dma_memory_map(ad->hba->dma, tbl_addr, &cmd_len,
+                                 DMA_DIRECTION_TO_DEVICE);
         cmd_mapped = 1;
     }
 
@@ -630,7 +631,8 @@ static void ahci_write_fis_d2h(AHCIDevice *ad, uint8_t *cmd_fis)
     ahci_trigger_irq(ad->hba, ad, PORT_IRQ_D2H_REG_FIS);
 
     if (cmd_mapped) {
-        cpu_physical_memory_unmap(cmd_fis, cmd_len, 0, cmd_len);
+        dma_memory_unmap(ad->hba->dma, cmd_fis, cmd_len,
+                         DMA_DIRECTION_TO_DEVICE, cmd_len);
     }
 }
 
@@ -640,8 +642,8 @@ static int ahci_populate_sglist(AHCIDevice *ad, QEMUSGList *sglist)
     uint32_t opts = le32_to_cpu(cmd->opts);
     uint64_t prdt_addr = le64_to_cpu(cmd->tbl_addr) + 0x80;
     int sglist_alloc_hint = opts >> AHCI_CMD_HDR_PRDT_LEN;
-    target_phys_addr_t prdt_len = (sglist_alloc_hint * sizeof(AHCI_SG));
-    target_phys_addr_t real_prdt_len = prdt_len;
+    dma_addr_t prdt_len = (sglist_alloc_hint * sizeof(AHCI_SG));
+    dma_addr_t real_prdt_len = prdt_len;
     uint8_t *prdt;
     int i;
     int r = 0;
@@ -652,7 +654,8 @@ static int ahci_populate_sglist(AHCIDevice *ad, QEMUSGList *sglist)
     }
 
     /* map PRDT */
-    if (!(prdt = cpu_physical_memory_map(prdt_addr, &prdt_len, 0))){
+    if (!(prdt = dma_memory_map(ad->hba->dma, prdt_addr, &prdt_len,
+                                DMA_DIRECTION_TO_DEVICE))){
         DPRINTF(ad->port_no, "map failed\n");
         return -1;
     }
@@ -667,8 +670,7 @@ static int ahci_populate_sglist(AHCIDevice *ad, QEMUSGList *sglist)
     if (sglist_alloc_hint > 0) {
         AHCI_SG *tbl = (AHCI_SG *)prdt;
 
-        /* FIXME: pass the correct DMAContext */
-        qemu_sglist_init(sglist, sglist_alloc_hint, NULL);
+        qemu_sglist_init(sglist, sglist_alloc_hint, ad->hba->dma);
         for (i = 0; i < sglist_alloc_hint; i++) {
             /* flags_size is zero-based */
             qemu_sglist_add(sglist, le64_to_cpu(tbl[i].addr),
@@ -677,7 +679,8 @@ static int ahci_populate_sglist(AHCIDevice *ad, QEMUSGList *sglist)
     }
 
 out:
-    cpu_physical_memory_unmap(prdt, prdt_len, 0, prdt_len);
+    dma_memory_unmap(ad->hba->dma, prdt, prdt_len,
+                     DMA_DIRECTION_TO_DEVICE, prdt_len);
     return r;
 }
 
@@ -787,7 +790,7 @@ static int handle_cmd(AHCIState *s, int port, int slot)
     uint64_t tbl_addr;
     AHCICmdHdr *cmd;
     uint8_t *cmd_fis;
-    target_phys_addr_t cmd_len;
+    dma_addr_t cmd_len;
 
     if (s->dev[port].port.ifs[0].status & (BUSY_STAT|DRQ_STAT)) {
         /* Engine currently busy, try again later */
@@ -809,7 +812,8 @@ static int handle_cmd(AHCIState *s, int port, int slot)
     tbl_addr = le64_to_cpu(cmd->tbl_addr);
 
     cmd_len = 0x80;
-    cmd_fis = cpu_physical_memory_map(tbl_addr, &cmd_len, 1);
+    cmd_fis = dma_memory_map(s->dma, tbl_addr, &cmd_len,
+                             DMA_DIRECTION_FROM_DEVICE);
 
     if (!cmd_fis) {
         DPRINTF(port, "error: guest passed us an invalid cmd fis\n");
@@ -935,7 +939,8 @@ static int handle_cmd(AHCIState *s, int port, int slot)
     }
 
 out:
-    cpu_physical_memory_unmap(cmd_fis, cmd_len, 1, cmd_len);
+    dma_memory_unmap(s->dma, cmd_fis, cmd_len, DMA_DIRECTION_FROM_DEVICE,
+                     cmd_len);
 
     if (s->dev[port].port.ifs[0].status & (BUSY_STAT|DRQ_STAT)) {
         /* async command, complete later */
@@ -1115,11 +1120,12 @@ static const IDEDMAOps ahci_dma_ops = {
     .reset = ahci_dma_reset,
 };
 
-void ahci_init(AHCIState *s, DeviceState *qdev, int ports)
+void ahci_init(AHCIState *s, DeviceState *qdev, DMAContext *dma, int ports)
 {
     qemu_irq *irqs;
     int i;
 
+    s->dma = dma;
     s->ports = ports;
     s->dev = g_malloc0(sizeof(AHCIDevice) * ports);
     ahci_reg_init(s);
@@ -1188,7 +1194,7 @@ static void sysbus_ahci_reset(DeviceState *dev)
 static int sysbus_ahci_init(SysBusDevice *dev)
 {
     SysbusAHCIState *s = FROM_SYSBUS(SysbusAHCIState, dev);
-    ahci_init(&s->ahci, &dev->qdev, s->num_ports);
+    ahci_init(&s->ahci, &dev->qdev, NULL, s->num_ports);
 
     sysbus_init_mmio(dev, &s->ahci.mem);
     sysbus_init_irq(dev, &s->ahci.irq);
diff --git a/hw/ide/ahci.h b/hw/ide/ahci.h
index ec1b6a5..1200a56 100644
--- a/hw/ide/ahci.h
+++ b/hw/ide/ahci.h
@@ -299,6 +299,7 @@ typedef struct AHCIState {
     uint32_t idp_index;     /* Current IDP index */
     int ports;
     qemu_irq irq;
+    DMAContext *dma;
 } AHCIState;
 
 typedef struct AHCIPCIState {
@@ -329,7 +330,7 @@ typedef struct NCQFrame {
     uint8_t reserved10;
 } QEMU_PACKED NCQFrame;
 
-void ahci_init(AHCIState *s, DeviceState *qdev, int ports);
+void ahci_init(AHCIState *s, DeviceState *qdev, DMAContext *dma, int ports);
 void ahci_uninit(AHCIState *s);
 
 void ahci_reset(AHCIState *s);
diff --git a/hw/ide/ich.c b/hw/ide/ich.c
index e3eaaea..319bc2b 100644
--- a/hw/ide/ich.c
+++ b/hw/ide/ich.c
@@ -98,7 +98,7 @@ static int pci_ich9_ahci_init(PCIDevice *dev)
     uint8_t *sata_cap;
     d = DO_UPCAST(struct AHCIPCIState, card, dev);
 
-    ahci_init(&d->ahci, &dev->qdev, 6);
+    ahci_init(&d->ahci, &dev->qdev, pci_dma_context(dev), 6);
 
     pci_config_set_prog_interface(d->card.config, AHCI_PROGMODE_MAJOR_REV_1);
 
commit c65bcef30659442a45ed0842de80d246d0162fd7
Author: David Gibson <david at gibson.dropbear.id.au>
Date:   Wed Jun 27 14:50:40 2012 +1000

    iommu: Make sglists and dma_bdrv helpers use new universal DMA helpers
    
    dma-helpers.c contains a number of helper functions for doing
    scatter/gather DMA, and various block device related DMA.  Currently,
    these directly access guest memory using cpu_physical_memory_*(),
    assuming no IOMMU translation.
    
    This patch updates this code to use the new universal DMA helper
    functions.  qemu_sglist_init() now takes a DMAContext * to describe
    the DMA address space in which the scatter/gather will take place.
    
    We minimally update the callers qemu_sglist_init() to pass NULL
    (i.e. no translation, same as current behaviour).  Some of those
    callers should pass something else in some cases to allow proper IOMMU
    translation in future, but that will be fixed in later patches.
    
    Cc: Kevin Wolf <kwolf at redhat.com>
    Cc: Michael S. Tsirkin <mst at redhat.com>
    Cc: Paolo Bonzini <pbonzini at redhat.com>
    
    Signed-off-by: David Gibson <david at gibson.dropbear.id.au>
    Signed-off-by: Benjamin Herrenschmidt <benh at kernel.crashing.org>
    Signed-off-by: Anthony Liguori <aliguori at us.ibm.com>

diff --git a/dma-helpers.c b/dma-helpers.c
index 5265132..4c9e529 100644
--- a/dma-helpers.c
+++ b/dma-helpers.c
@@ -26,12 +26,13 @@ int dma_memory_set(DMAContext *dma, dma_addr_t addr, uint8_t c, dma_addr_t len)
     return 0;
 }
 
-void qemu_sglist_init(QEMUSGList *qsg, int alloc_hint)
+void qemu_sglist_init(QEMUSGList *qsg, int alloc_hint, DMAContext *dma)
 {
     qsg->sg = g_malloc(alloc_hint * sizeof(ScatterGatherEntry));
     qsg->nsg = 0;
     qsg->nalloc = alloc_hint;
     qsg->size = 0;
+    qsg->dma = dma;
 }
 
 void qemu_sglist_add(QEMUSGList *qsg, dma_addr_t base, dma_addr_t len)
@@ -90,10 +91,9 @@ static void dma_bdrv_unmap(DMAAIOCB *dbs)
     int i;
 
     for (i = 0; i < dbs->iov.niov; ++i) {
-        cpu_physical_memory_unmap(dbs->iov.iov[i].iov_base,
-                                  dbs->iov.iov[i].iov_len,
-                                  dbs->dir != DMA_DIRECTION_TO_DEVICE,
-                                  dbs->iov.iov[i].iov_len);
+        dma_memory_unmap(dbs->sg->dma, dbs->iov.iov[i].iov_base,
+                         dbs->iov.iov[i].iov_len, dbs->dir,
+                         dbs->iov.iov[i].iov_len);
     }
     qemu_iovec_reset(&dbs->iov);
 }
@@ -122,7 +122,7 @@ static void dma_complete(DMAAIOCB *dbs, int ret)
 static void dma_bdrv_cb(void *opaque, int ret)
 {
     DMAAIOCB *dbs = (DMAAIOCB *)opaque;
-    target_phys_addr_t cur_addr, cur_len;
+    dma_addr_t cur_addr, cur_len;
     void *mem;
 
     trace_dma_bdrv_cb(dbs, ret);
@@ -139,8 +139,7 @@ static void dma_bdrv_cb(void *opaque, int ret)
     while (dbs->sg_cur_index < dbs->sg->nsg) {
         cur_addr = dbs->sg->sg[dbs->sg_cur_index].base + dbs->sg_cur_byte;
         cur_len = dbs->sg->sg[dbs->sg_cur_index].len - dbs->sg_cur_byte;
-        mem = cpu_physical_memory_map(cur_addr, &cur_len,
-                                      dbs->dir != DMA_DIRECTION_TO_DEVICE);
+        mem = dma_memory_map(dbs->sg->dma, cur_addr, &cur_len, dbs->dir);
         if (!mem)
             break;
         qemu_iovec_add(&dbs->iov, mem, cur_len);
@@ -225,7 +224,8 @@ BlockDriverAIOCB *dma_bdrv_write(BlockDriverState *bs,
 }
 
 
-static uint64_t dma_buf_rw(uint8_t *ptr, int32_t len, QEMUSGList *sg, bool to_dev)
+static uint64_t dma_buf_rw(uint8_t *ptr, int32_t len, QEMUSGList *sg,
+                           DMADirection dir)
 {
     uint64_t resid;
     int sg_cur_index;
@@ -236,7 +236,7 @@ static uint64_t dma_buf_rw(uint8_t *ptr, int32_t len, QEMUSGList *sg, bool to_de
     while (len > 0) {
         ScatterGatherEntry entry = sg->sg[sg_cur_index++];
         int32_t xfer = MIN(len, entry.len);
-        cpu_physical_memory_rw(entry.base, ptr, xfer, !to_dev);
+        dma_memory_rw(sg->dma, entry.base, ptr, xfer, dir);
         ptr += xfer;
         len -= xfer;
         resid -= xfer;
@@ -247,12 +247,12 @@ static uint64_t dma_buf_rw(uint8_t *ptr, int32_t len, QEMUSGList *sg, bool to_de
 
 uint64_t dma_buf_read(uint8_t *ptr, int32_t len, QEMUSGList *sg)
 {
-    return dma_buf_rw(ptr, len, sg, 0);
+    return dma_buf_rw(ptr, len, sg, DMA_DIRECTION_FROM_DEVICE);
 }
 
 uint64_t dma_buf_write(uint8_t *ptr, int32_t len, QEMUSGList *sg)
 {
-    return dma_buf_rw(ptr, len, sg, 1);
+    return dma_buf_rw(ptr, len, sg, DMA_DIRECTION_TO_DEVICE);
 }
 
 void dma_acct_start(BlockDriverState *bs, BlockAcctCookie *cookie,
diff --git a/dma.h b/dma.h
index 8912dfc..e93076a 100644
--- a/dma.h
+++ b/dma.h
@@ -27,6 +27,7 @@ struct QEMUSGList {
     int nsg;
     int nalloc;
     size_t size;
+    DMAContext *dma;
 };
 
 #if defined(TARGET_PHYS_ADDR_BITS)
@@ -134,7 +135,7 @@ struct ScatterGatherEntry {
     dma_addr_t len;
 };
 
-void qemu_sglist_init(QEMUSGList *qsg, int alloc_hint);
+void qemu_sglist_init(QEMUSGList *qsg, int alloc_hint, DMAContext *dma);
 void qemu_sglist_add(QEMUSGList *qsg, dma_addr_t base, dma_addr_t len);
 void qemu_sglist_destroy(QEMUSGList *qsg);
 #endif
diff --git a/hw/ide/ahci.c b/hw/ide/ahci.c
index e275e68..6c4226d 100644
--- a/hw/ide/ahci.c
+++ b/hw/ide/ahci.c
@@ -667,7 +667,8 @@ static int ahci_populate_sglist(AHCIDevice *ad, QEMUSGList *sglist)
     if (sglist_alloc_hint > 0) {
         AHCI_SG *tbl = (AHCI_SG *)prdt;
 
-        qemu_sglist_init(sglist, sglist_alloc_hint);
+        /* FIXME: pass the correct DMAContext */
+        qemu_sglist_init(sglist, sglist_alloc_hint, NULL);
         for (i = 0; i < sglist_alloc_hint; i++) {
             /* flags_size is zero-based */
             qemu_sglist_add(sglist, le64_to_cpu(tbl[i].addr),
diff --git a/hw/ide/macio.c b/hw/ide/macio.c
index 7b38d9e..848cb31 100644
--- a/hw/ide/macio.c
+++ b/hw/ide/macio.c
@@ -76,7 +76,7 @@ static void pmac_ide_atapi_transfer_cb(void *opaque, int ret)
 
     s->io_buffer_size = io->len;
 
-    qemu_sglist_init(&s->sg, io->len / MACIO_PAGE_SIZE + 1);
+    qemu_sglist_init(&s->sg, io->len / MACIO_PAGE_SIZE + 1, NULL);
     qemu_sglist_add(&s->sg, io->addr, io->len);
     io->addr += io->len;
     io->len = 0;
@@ -133,7 +133,7 @@ static void pmac_ide_transfer_cb(void *opaque, int ret)
     s->io_buffer_index = 0;
     s->io_buffer_size = io->len;
 
-    qemu_sglist_init(&s->sg, io->len / MACIO_PAGE_SIZE + 1);
+    qemu_sglist_init(&s->sg, io->len / MACIO_PAGE_SIZE + 1, NULL);
     qemu_sglist_add(&s->sg, io->addr, io->len);
     io->addr += io->len;
     io->len = 0;
diff --git a/hw/pci.h b/hw/pci.h
index f148613..ee14a7f 100644
--- a/hw/pci.h
+++ b/hw/pci.h
@@ -625,7 +625,7 @@ static inline void pci_dma_unmap(PCIDevice *dev, void *buffer, dma_addr_t len,
 static inline void pci_dma_sglist_init(QEMUSGList *qsg, PCIDevice *dev,
                                        int alloc_hint)
 {
-    qemu_sglist_init(qsg, alloc_hint);
+    qemu_sglist_init(qsg, alloc_hint, pci_dma_context(dev));
 }
 
 extern const VMStateDescription vmstate_pci_device;
commit 9ac6a217f26d2044929ac4261826d24cc8c3dda5
Author: David Gibson <david at gibson.dropbear.id.au>
Date:   Wed Jun 27 14:50:39 2012 +1000

    usb-ohci: Use universal DMA helper functions
    
    The OHCI device emulation can provide both PCI and SysBus OHCI
    implementations.  Because of this, it was not previously converted to
    use the PCI DMA helper functions.
    
    This patch converts it to use the new universal DMA helper functions.
    In the PCI case, it obtains its DMAContext from pci_dma_context(), in
    the SysBus case, it uses NULL - i.e. assumes for now that there will
    be no IOMMU translation for a SysBus OHCI.
    
    Cc: Gerd Hoffmann <kraxel at redhat.com>
    Cc: Michael S. Tsirkin <mst at redhat.com>
    
    Signed-off-by: David Gibson <david at gibson.dropbear.id.au>
    Signed-off-by: Benjamin Herrenschmidt <benh at kernel.crashing.org>
    Signed-off-by: Anthony Liguori <aliguori at us.ibm.com>

diff --git a/hw/usb/hcd-ohci.c b/hw/usb/hcd-ohci.c
index 1a1cc88..844e7ed 100644
--- a/hw/usb/hcd-ohci.c
+++ b/hw/usb/hcd-ohci.c
@@ -31,7 +31,7 @@
 #include "hw/usb.h"
 #include "hw/pci.h"
 #include "hw/sysbus.h"
-#include "hw/qdev-addr.h"
+#include "hw/qdev-dma.h"
 
 //#define DEBUG_OHCI
 /* Dump packet contents.  */
@@ -62,6 +62,7 @@ typedef struct {
     USBBus bus;
     qemu_irq irq;
     MemoryRegion mem;
+    DMAContext *dma;
     int num_ports;
     const char *name;
 
@@ -104,7 +105,7 @@ typedef struct {
     uint32_t htest;
 
     /* SM501 local memory offset */
-    target_phys_addr_t localmem_base;
+    dma_addr_t localmem_base;
 
     /* Active packets.  */
     uint32_t old_ctl;
@@ -482,14 +483,14 @@ static void ohci_reset(void *opaque)
 
 /* Get an array of dwords from main memory */
 static inline int get_dwords(OHCIState *ohci,
-                             uint32_t addr, uint32_t *buf, int num)
+                             dma_addr_t addr, uint32_t *buf, int num)
 {
     int i;
 
     addr += ohci->localmem_base;
 
     for (i = 0; i < num; i++, buf++, addr += sizeof(*buf)) {
-        cpu_physical_memory_read(addr, buf, sizeof(*buf));
+        dma_memory_read(ohci->dma, addr, buf, sizeof(*buf));
         *buf = le32_to_cpu(*buf);
     }
 
@@ -498,7 +499,7 @@ static inline int get_dwords(OHCIState *ohci,
 
 /* Put an array of dwords in to main memory */
 static inline int put_dwords(OHCIState *ohci,
-                             uint32_t addr, uint32_t *buf, int num)
+                             dma_addr_t addr, uint32_t *buf, int num)
 {
     int i;
 
@@ -506,7 +507,7 @@ static inline int put_dwords(OHCIState *ohci,
 
     for (i = 0; i < num; i++, buf++, addr += sizeof(*buf)) {
         uint32_t tmp = cpu_to_le32(*buf);
-        cpu_physical_memory_write(addr, &tmp, sizeof(tmp));
+        dma_memory_write(ohci->dma, addr, &tmp, sizeof(tmp));
     }
 
     return 1;
@@ -514,14 +515,14 @@ static inline int put_dwords(OHCIState *ohci,
 
 /* Get an array of words from main memory */
 static inline int get_words(OHCIState *ohci,
-                            uint32_t addr, uint16_t *buf, int num)
+                            dma_addr_t addr, uint16_t *buf, int num)
 {
     int i;
 
     addr += ohci->localmem_base;
 
     for (i = 0; i < num; i++, buf++, addr += sizeof(*buf)) {
-        cpu_physical_memory_read(addr, buf, sizeof(*buf));
+        dma_memory_read(ohci->dma, addr, buf, sizeof(*buf));
         *buf = le16_to_cpu(*buf);
     }
 
@@ -530,7 +531,7 @@ static inline int get_words(OHCIState *ohci,
 
 /* Put an array of words in to main memory */
 static inline int put_words(OHCIState *ohci,
-                            uint32_t addr, uint16_t *buf, int num)
+                            dma_addr_t addr, uint16_t *buf, int num)
 {
     int i;
 
@@ -538,40 +539,40 @@ static inline int put_words(OHCIState *ohci,
 
     for (i = 0; i < num; i++, buf++, addr += sizeof(*buf)) {
         uint16_t tmp = cpu_to_le16(*buf);
-        cpu_physical_memory_write(addr, &tmp, sizeof(tmp));
+        dma_memory_write(ohci->dma, addr, &tmp, sizeof(tmp));
     }
 
     return 1;
 }
 
 static inline int ohci_read_ed(OHCIState *ohci,
-                               uint32_t addr, struct ohci_ed *ed)
+                               dma_addr_t addr, struct ohci_ed *ed)
 {
     return get_dwords(ohci, addr, (uint32_t *)ed, sizeof(*ed) >> 2);
 }
 
 static inline int ohci_read_td(OHCIState *ohci,
-                               uint32_t addr, struct ohci_td *td)
+                               dma_addr_t addr, struct ohci_td *td)
 {
     return get_dwords(ohci, addr, (uint32_t *)td, sizeof(*td) >> 2);
 }
 
 static inline int ohci_read_iso_td(OHCIState *ohci,
-                                   uint32_t addr, struct ohci_iso_td *td)
+                                   dma_addr_t addr, struct ohci_iso_td *td)
 {
     return (get_dwords(ohci, addr, (uint32_t *)td, 4) &&
             get_words(ohci, addr + 16, td->offset, 8));
 }
 
 static inline int ohci_read_hcca(OHCIState *ohci,
-                                 uint32_t addr, struct ohci_hcca *hcca)
+                                 dma_addr_t addr, struct ohci_hcca *hcca)
 {
-    cpu_physical_memory_read(addr + ohci->localmem_base, hcca, sizeof(*hcca));
+    dma_memory_read(ohci->dma, addr + ohci->localmem_base, hcca, sizeof(*hcca));
     return 1;
 }
 
 static inline int ohci_put_ed(OHCIState *ohci,
-                              uint32_t addr, struct ohci_ed *ed)
+                              dma_addr_t addr, struct ohci_ed *ed)
 {
     /* ed->tail is under control of the HCD.
      * Since just ed->head is changed by HC, just write back this
@@ -583,64 +584,63 @@ static inline int ohci_put_ed(OHCIState *ohci,
 }
 
 static inline int ohci_put_td(OHCIState *ohci,
-                              uint32_t addr, struct ohci_td *td)
+                              dma_addr_t addr, struct ohci_td *td)
 {
     return put_dwords(ohci, addr, (uint32_t *)td, sizeof(*td) >> 2);
 }
 
 static inline int ohci_put_iso_td(OHCIState *ohci,
-                                  uint32_t addr, struct ohci_iso_td *td)
+                                  dma_addr_t addr, struct ohci_iso_td *td)
 {
     return (put_dwords(ohci, addr, (uint32_t *)td, 4) &&
             put_words(ohci, addr + 16, td->offset, 8));
 }
 
 static inline int ohci_put_hcca(OHCIState *ohci,
-                                uint32_t addr, struct ohci_hcca *hcca)
+                                dma_addr_t addr, struct ohci_hcca *hcca)
 {
-    cpu_physical_memory_write(addr + ohci->localmem_base + HCCA_WRITEBACK_OFFSET,
-                              (char *)hcca + HCCA_WRITEBACK_OFFSET,
-                              HCCA_WRITEBACK_SIZE);
+    dma_memory_write(ohci->dma,
+                     addr + ohci->localmem_base + HCCA_WRITEBACK_OFFSET,
+                     (char *)hcca + HCCA_WRITEBACK_OFFSET,
+                     HCCA_WRITEBACK_SIZE);
     return 1;
 }
 
 /* Read/Write the contents of a TD from/to main memory.  */
 static void ohci_copy_td(OHCIState *ohci, struct ohci_td *td,
-                         uint8_t *buf, int len, int write)
+                         uint8_t *buf, int len, DMADirection dir)
 {
-    uint32_t ptr;
-    uint32_t n;
+    dma_addr_t ptr, n;
 
     ptr = td->cbp;
     n = 0x1000 - (ptr & 0xfff);
     if (n > len)
         n = len;
-    cpu_physical_memory_rw(ptr + ohci->localmem_base, buf, n, write);
+    dma_memory_rw(ohci->dma, ptr + ohci->localmem_base, buf, n, dir);
     if (n == len)
         return;
     ptr = td->be & ~0xfffu;
     buf += n;
-    cpu_physical_memory_rw(ptr + ohci->localmem_base, buf, len - n, write);
+    dma_memory_rw(ohci->dma, ptr + ohci->localmem_base, buf, len - n, dir);
 }
 
 /* Read/Write the contents of an ISO TD from/to main memory.  */
 static void ohci_copy_iso_td(OHCIState *ohci,
                              uint32_t start_addr, uint32_t end_addr,
-                             uint8_t *buf, int len, int write)
+                             uint8_t *buf, int len, DMADirection dir)
 {
-    uint32_t ptr;
-    uint32_t n;
+    dma_addr_t ptr, n;
 
     ptr = start_addr;
     n = 0x1000 - (ptr & 0xfff);
     if (n > len)
         n = len;
-    cpu_physical_memory_rw(ptr + ohci->localmem_base, buf, n, write);
+    dma_memory_rw(ohci->dma, ptr + ohci->localmem_base, buf, n, dir);
     if (n == len)
         return;
     ptr = end_addr & ~0xfffu;
     buf += n;
-    cpu_physical_memory_rw(ptr + ohci->localmem_base, buf, len - n, write);
+    dma_memory_rw(ohci->dma, ptr + ohci->localmem_base, buf, len - n, dir);
 }
 
 static void ohci_process_lists(OHCIState *ohci, int completion);
@@ -803,7 +803,8 @@ static int ohci_service_iso_td(OHCIState *ohci, struct ohci_ed *ed,
     }
 
     if (len && dir != OHCI_TD_DIR_IN) {
-        ohci_copy_iso_td(ohci, start_addr, end_addr, ohci->usb_buf, len, 0);
+        ohci_copy_iso_td(ohci, start_addr, end_addr, ohci->usb_buf, len,
+                         DMA_DIRECTION_TO_DEVICE);
     }
 
     if (completion) {
@@ -827,7 +828,8 @@ static int ohci_service_iso_td(OHCIState *ohci, struct ohci_ed *ed,
     /* Writeback */
     if (dir == OHCI_TD_DIR_IN && ret >= 0 && ret <= len) {
         /* IN transfer succeeded */
-        ohci_copy_iso_td(ohci, start_addr, end_addr, ohci->usb_buf, ret, 1);
+        ohci_copy_iso_td(ohci, start_addr, end_addr, ohci->usb_buf, ret,
+                         DMA_DIRECTION_FROM_DEVICE);
         OHCI_SET_BM(iso_td.offset[relative_frame_number], TD_PSW_CC,
                     OHCI_CC_NOERROR);
         OHCI_SET_BM(iso_td.offset[relative_frame_number], TD_PSW_SIZE, ret);
@@ -971,7 +973,8 @@ static int ohci_service_td(OHCIState *ohci, struct ohci_ed *ed)
                 pktlen = len;
             }
             if (!completion) {
-                ohci_copy_td(ohci, &td, ohci->usb_buf, pktlen, 0);
+                ohci_copy_td(ohci, &td, ohci->usb_buf, pktlen,
+                             DMA_DIRECTION_TO_DEVICE);
             }
         }
     }
@@ -1021,7 +1024,8 @@ static int ohci_service_td(OHCIState *ohci, struct ohci_ed *ed)
     }
     if (ret >= 0) {
         if (dir == OHCI_TD_DIR_IN) {
-            ohci_copy_td(ohci, &td, ohci->usb_buf, ret, 1);
+            ohci_copy_td(ohci, &td, ohci->usb_buf, ret,
+                         DMA_DIRECTION_FROM_DEVICE);
 #ifdef DEBUG_PACKET
             DPRINTF("  data:");
             for (i = 0; i < ret; i++)
@@ -1748,11 +1752,14 @@ static USBBusOps ohci_bus_ops = {
 };
 
 static int usb_ohci_init(OHCIState *ohci, DeviceState *dev,
-                         int num_ports, uint32_t localmem_base,
-                         char *masterbus, uint32_t firstport)
+                         int num_ports, dma_addr_t localmem_base,
+                         char *masterbus, uint32_t firstport,
+                         DMAContext *dma)
 {
     int i;
 
+    ohci->dma = dma;
+
     if (usb_frame_time == 0) {
 #ifdef OHCI_TIME_WARP
         usb_frame_time = get_ticks_per_sec();
@@ -1817,7 +1824,8 @@ static int usb_ohci_initfn_pci(struct PCIDevice *dev)
     ohci->pci_dev.config[PCI_INTERRUPT_PIN] = 0x01; /* interrupt pin A */
 
     if (usb_ohci_init(&ohci->state, &dev->qdev, ohci->num_ports, 0,
-                      ohci->masterbus, ohci->firstport) != 0) {
+                      ohci->masterbus, ohci->firstport,
+                      pci_dma_context(dev)) != 0) {
         return -1;
     }
     ohci->state.irq = ohci->pci_dev.irq[0];
@@ -1831,7 +1839,7 @@ typedef struct {
     SysBusDevice busdev;
     OHCIState ohci;
     uint32_t num_ports;
-    target_phys_addr_t dma_offset;
+    dma_addr_t dma_offset;
 } OHCISysBusState;
 
 static int ohci_init_pxa(SysBusDevice *dev)
@@ -1839,7 +1847,8 @@ static int ohci_init_pxa(SysBusDevice *dev)
     OHCISysBusState *s = FROM_SYSBUS(OHCISysBusState, dev);
 
     /* Cannot fail as we pass NULL for masterbus */
-    usb_ohci_init(&s->ohci, &dev->qdev, s->num_ports, s->dma_offset, NULL, 0);
+    usb_ohci_init(&s->ohci, &dev->qdev, s->num_ports, s->dma_offset, NULL, 0,
+                  NULL);
     sysbus_init_irq(dev, &s->ohci.irq);
     sysbus_init_mmio(dev, &s->ohci.mem);
 
@@ -1875,7 +1884,7 @@ static TypeInfo ohci_pci_info = {
 
 static Property ohci_sysbus_properties[] = {
     DEFINE_PROP_UINT32("num-ports", OHCISysBusState, num_ports, 3),
-    DEFINE_PROP_TADDR("dma-offset", OHCISysBusState, dma_offset, 3),
+    DEFINE_PROP_DMAADDR("dma-offset", OHCISysBusState, dma_offset, 3),
     DEFINE_PROP_END_OF_LIST(),
 };
 
commit d86a77f8abb9ed4b598f86f6476ccb2dc0a433e6
Author: David Gibson <david at gibson.dropbear.id.au>
Date:   Wed Jun 27 14:50:38 2012 +1000

    iommu: Add universal DMA helper functions
    
    Not that long ago, every device implementation using DMA directly
    accessed guest memory using cpu_physical_memory_*().  This meant that
    adding support for a guest visible IOMMU would require changing every
    one of these devices to go through IOMMU translation.
    
    Shortly before qemu 1.0, I made a start on fixing this by providing
    helper functions for PCI DMA.  These are currently just stubs which
    call the direct access functions, but mean that an IOMMU can be
    implemented in one place, rather than for every PCI device.
    
    Clearly, this doesn't help for non PCI devices, which could also be
    IOMMU translated on some platforms.  It is also problematic for the
    devices which have both PCI and non-PCI version (e.g. OHCI, AHCI) - we
    cannot use the the pci_dma_*() functions, because they assume the
    presence of a PCIDevice, but we don't want to have to check between
    pci_dma_*() and cpu_physical_memory_*() every time we do a DMA in the
    device code.
    
    This patch makes the first step on addressing both these problems, by
    introducing new (stub) dma helper functions which can be used for any
    DMA capable device.
    
    These dma functions take a DMAContext *, a new (currently empty)
    variable describing the DMA address space in which the operation is to
    take place.  NULL indicates untranslated DMA directly into guest
    physical address space.  The intention is that in future non-NULL
    values will given information about any necessary IOMMU translation.
    
    DMA using devices must obtain a DMAContext (or, potentially, contexts)
    from their bus or platform.  For now this patch just converts the PCI
    wrappers to be implemented in terms of the universal wrappers,
    converting other drivers can take place over time.
    
    Cc: Michael S. Tsirkin <mst at redhat.com>
    Cc: Eduard - Gabriel Munteanu <eduard.munteanu at linux360.ro>
    Cc: Richard Henderson <rth at twiddle.net>
    
    Signed-off-by: David Gibson <david at gibson.dropbear.id.au>
    Signed-off-by: Benjamin Herrenschmidt <benh at kernel.crashing.org>
    Signed-off-by: Anthony Liguori <aliguori at us.ibm.com>

diff --git a/dma-helpers.c b/dma-helpers.c
index 7971a89..5265132 100644
--- a/dma-helpers.c
+++ b/dma-helpers.c
@@ -10,6 +10,22 @@
 #include "dma.h"
 #include "trace.h"
 
+int dma_memory_set(DMAContext *dma, dma_addr_t addr, uint8_t c, dma_addr_t len)
+{
+#define FILLBUF_SIZE 512
+    uint8_t fillbuf[FILLBUF_SIZE];
+    int l;
+
+    memset(fillbuf, c, FILLBUF_SIZE);
+    while (len > 0) {
+        l = len < FILLBUF_SIZE ? len : FILLBUF_SIZE;
+        cpu_physical_memory_rw(addr, fillbuf, l, true);
+        len -= len;
+        addr += len;
+    }
+    return 0;
+}
+
 void qemu_sglist_init(QEMUSGList *qsg, int alloc_hint)
 {
     qsg->sg = g_malloc(alloc_hint * sizeof(ScatterGatherEntry));
diff --git a/dma.h b/dma.h
index fe08b72..8912dfc 100644
--- a/dma.h
+++ b/dma.h
@@ -14,6 +14,7 @@
 #include "hw/hw.h"
 #include "block.h"
 
+typedef struct DMAContext DMAContext;
 typedef struct ScatterGatherEntry ScatterGatherEntry;
 
 typedef enum {
@@ -34,6 +35,100 @@ typedef target_phys_addr_t dma_addr_t;
 #define DMA_ADDR_BITS TARGET_PHYS_ADDR_BITS
 #define DMA_ADDR_FMT TARGET_FMT_plx
 
+/* Checks that the given range of addresses is valid for DMA.  This is
+ * useful for certain cases, but usually you should just use
+ * dma_memory_{read,write}() and check for errors */
+static inline bool dma_memory_valid(DMAContext *dma, dma_addr_t addr,
+                                    dma_addr_t len, DMADirection dir)
+{
+    /* Stub version, with no iommu we assume all bus addresses are valid */
+    return true;
+}
+
+static inline int dma_memory_rw(DMAContext *dma, dma_addr_t addr,
+                                void *buf, dma_addr_t len, DMADirection dir)
+{
+    /* Stub version when we have no iommu support */
+    cpu_physical_memory_rw(addr, buf, (target_phys_addr_t)len,
+                           dir == DMA_DIRECTION_FROM_DEVICE);
+    return 0;
+}
+
+static inline int dma_memory_read(DMAContext *dma, dma_addr_t addr,
+                                  void *buf, dma_addr_t len)
+{
+    return dma_memory_rw(dma, addr, buf, len, DMA_DIRECTION_TO_DEVICE);
+}
+
+static inline int dma_memory_write(DMAContext *dma, dma_addr_t addr,
+                                   const void *buf, dma_addr_t len)
+{
+    return dma_memory_rw(dma, addr, (void *)buf, len,
+                         DMA_DIRECTION_FROM_DEVICE);
+}
+
+int dma_memory_set(DMAContext *dma, dma_addr_t addr, uint8_t c, dma_addr_t len);
+
+static inline void *dma_memory_map(DMAContext *dma,
+                                   dma_addr_t addr, dma_addr_t *len,
+                                   DMADirection dir)
+{
+    target_phys_addr_t xlen = *len;
+    void *p;
+
+    p = cpu_physical_memory_map(addr, &xlen,
+                                dir == DMA_DIRECTION_FROM_DEVICE);
+    *len = xlen;
+    return p;
+}
+
+static inline void dma_memory_unmap(DMAContext *dma,
+                                    void *buffer, dma_addr_t len,
+                                    DMADirection dir, dma_addr_t access_len)
+{
+    return cpu_physical_memory_unmap(buffer, (target_phys_addr_t)len,
+                                     dir == DMA_DIRECTION_FROM_DEVICE,
+                                     access_len);
+}
+
+#define DEFINE_LDST_DMA(_lname, _sname, _bits, _end) \
+    static inline uint##_bits##_t ld##_lname##_##_end##_dma(DMAContext *dma, \
+                                                            dma_addr_t addr) \
+    {                                                                   \
+        uint##_bits##_t val;                                            \
+        dma_memory_read(dma, addr, &val, (_bits) / 8);                  \
+        return _end##_bits##_to_cpu(val);                               \
+    }                                                                   \
+    static inline void st##_sname##_##_end##_dma(DMAContext *dma,       \
+                                                 dma_addr_t addr,       \
+                                                 uint##_bits##_t val)   \
+    {                                                                   \
+        val = cpu_to_##_end##_bits(val);                                \
+        dma_memory_write(dma, addr, &val, (_bits) / 8);                 \
+    }
+
+static inline uint8_t ldub_dma(DMAContext *dma, dma_addr_t addr)
+{
+    uint8_t val;
+
+    dma_memory_read(dma, addr, &val, 1);
+    return val;
+}
+
+static inline void stb_dma(DMAContext *dma, dma_addr_t addr, uint8_t val)
+{
+    dma_memory_write(dma, addr, &val, 1);
+}
+
+DEFINE_LDST_DMA(uw, w, 16, le);
+DEFINE_LDST_DMA(l, l, 32, le);
+DEFINE_LDST_DMA(q, q, 64, le);
+DEFINE_LDST_DMA(uw, w, 16, be);
+DEFINE_LDST_DMA(l, l, 32, be);
+DEFINE_LDST_DMA(q, q, 64, be);
+
+#undef DEFINE_LDST_DMA
+
 struct ScatterGatherEntry {
     dma_addr_t base;
     dma_addr_t len;
diff --git a/hw/pci.h b/hw/pci.h
index 95b608c..f148613 100644
--- a/hw/pci.h
+++ b/hw/pci.h
@@ -560,10 +560,16 @@ static inline uint32_t pci_config_size(const PCIDevice *d)
 }
 
 /* DMA access functions */
+static inline DMAContext *pci_dma_context(PCIDevice *dev)
+{
+    /* Stub for when we have no PCI iommu support */
+    return NULL;
+}
+
 static inline int pci_dma_rw(PCIDevice *dev, dma_addr_t addr,
                              void *buf, dma_addr_t len, DMADirection dir)
 {
-    cpu_physical_memory_rw(addr, buf, len, dir == DMA_DIRECTION_FROM_DEVICE);
+    dma_memory_rw(pci_dma_context(dev), addr, buf, len, dir);
     return 0;
 }
 
@@ -583,12 +589,12 @@ static inline int pci_dma_write(PCIDevice *dev, dma_addr_t addr,
     static inline uint##_bits##_t ld##_l##_pci_dma(PCIDevice *dev,      \
                                                    dma_addr_t addr)     \
     {                                                                   \
-        return ld##_l##_phys(addr);                                     \
+        return ld##_l##_dma(pci_dma_context(dev), addr);                \
     }                                                                   \
     static inline void st##_s##_pci_dma(PCIDevice *dev,                 \
-                          dma_addr_t addr, uint##_bits##_t val)         \
+                                        dma_addr_t addr, uint##_bits##_t val) \
     {                                                                   \
-        st##_s##_phys(addr, val);                                       \
+        st##_s##_dma(pci_dma_context(dev), addr, val);                  \
     }
 
 PCI_DMA_DEFINE_LDST(ub, b, 8);
@@ -604,19 +610,16 @@ PCI_DMA_DEFINE_LDST(q_be, q_be, 64);
 static inline void *pci_dma_map(PCIDevice *dev, dma_addr_t addr,
                                 dma_addr_t *plen, DMADirection dir)
 {
-    target_phys_addr_t len = *plen;
     void *buf;
 
-    buf = cpu_physical_memory_map(addr, &len, dir == DMA_DIRECTION_FROM_DEVICE);
-    *plen = len;
+    buf = dma_memory_map(pci_dma_context(dev), addr, plen, dir);
     return buf;
 }
 
 static inline void pci_dma_unmap(PCIDevice *dev, void *buffer, dma_addr_t len,
                                  DMADirection dir, dma_addr_t access_len)
 {
-    cpu_physical_memory_unmap(buffer, len, dir == DMA_DIRECTION_FROM_DEVICE,
-                              access_len);
+    dma_memory_unmap(pci_dma_context(dev), buffer, len, dir, access_len);
 }
 
 static inline void pci_dma_sglist_init(QEMUSGList *qsg, PCIDevice *dev,
commit 8292f75ad2d65364387b09bb920dd65c8842a3a6
Author: David Gibson <david at gibson.dropbear.id.au>
Date:   Wed Jun 27 14:50:37 2012 +1000

    Better support for dma_addr_t variables
    
    A while back, we introduced the dma_addr_t type, which is supposed to
    be used for bus visible memory addresses.  At present, this is an
    alias for target_phys_addr_t, but this will change when we eventually
    add support for guest visible IOMMUs.
    
    There are some instances of target_phys_addr_t in the code now which
    should really be dma_addr_t, but can't be trivially converted due to
    missing features which this patch corrects.
    
     * We add DMA_ADDR_BITS analagous to TARGET_PHYS_ADDR_BITS.  This is
       important where we need to make a compile-time (#if) based on the
       size of dma_addr_t.
    
     * We add a new helper macro to create device properties which take a
       dma_addr_t, currently an alias to DEFINE_PROP_TADDR().
    
    Signed-off-by: David Gibson <david at gibson.dropbear.id.au>
    Signed-off-by: Benjamin Herrenschmidt <benh at kernel.crashing.org>
    Signed-off-by: Anthony Liguori <aliguori at us.ibm.com>

diff --git a/dma.h b/dma.h
index 8c1ec8f..fe08b72 100644
--- a/dma.h
+++ b/dma.h
@@ -31,6 +31,7 @@ struct QEMUSGList {
 #if defined(TARGET_PHYS_ADDR_BITS)
 typedef target_phys_addr_t dma_addr_t;
 
+#define DMA_ADDR_BITS TARGET_PHYS_ADDR_BITS
 #define DMA_ADDR_FMT TARGET_FMT_plx
 
 struct ScatterGatherEntry {
diff --git a/hw/qdev-dma.h b/hw/qdev-dma.h
new file mode 100644
index 0000000..f0ff558
--- /dev/null
+++ b/hw/qdev-dma.h
@@ -0,0 +1,12 @@
+/*
+ * Support for dma_addr_t typed properties
+ *
+ * Copyright (C) 2012 David Gibson, IBM Corporation.
+ *
+ * This work is licensed under the terms of the GNU GPL, version 2 or later.
+ * See the COPYING file in the top-level directory.
+ */
+#include "qdev-addr.h"
+
+#define DEFINE_PROP_DMAADDR(_n, _s, _f, _d)                               \
+    DEFINE_PROP_TADDR(_n, _s, _f, _d)
commit fcce6fd25f3e233f9da9ef01230a668ab35bd343
Author: Jason Wang <jasowang at redhat.com>
Date:   Thu May 17 13:25:43 2012 +0800

    rtl8139: validate rx ring before receiving packets
    
    Commit ff71f2e8cacefae99179993204172bc65e4303df prevent the possible
    crash during initialization of linux driver by checking the operating
    mode.This seems too strict as:
    
    - the real card could still work in mode other than normal
    - some buggy driver who does not set correct opmode after eeprom
     access
    
    So, considering rx ring address were reset to zero (which could be
    safely trated as an address not intened to DMA to), in order to
    both letting old guest work and preventing the unexpected DMA to
    guest, we can forbid packet receiving when rx ring address is zero.
    
    Tested-by: Avi Kivity <avi at redhat.com>
    Signed-off-by: Jason Wang <jasowang at redhat.com>
    Signed-off-by: Anthony Liguori <aliguori at us.ibm.com>

diff --git a/hw/rtl8139.c b/hw/rtl8139.c
index f6f144b..7b15047 100644
--- a/hw/rtl8139.c
+++ b/hw/rtl8139.c
@@ -781,6 +781,13 @@ static inline dma_addr_t rtl8139_addr64(uint32_t low, uint32_t high)
 #endif
 }
 
+/* Workaround for buggy guest driver such as linux who allocates rx
+ * rings after the receiver were enabled. */
+static bool rtl8139_cp_rx_valid(RTL8139State *s)
+{
+    return !(s->RxRingAddrLO == 0 && s->RxRingAddrHI == 0);
+}
+
 static int rtl8139_can_receive(VLANClientState *nc)
 {
     RTL8139State *s = DO_UPCAST(NICState, nc, nc)->opaque;
@@ -791,11 +798,8 @@ static int rtl8139_can_receive(VLANClientState *nc)
       return 1;
     if (!rtl8139_receiver_enabled(s))
       return 1;
-    /* network/host communication happens only in normal mode */
-    if ((s->Cfg9346 & Chip9346_op_mask) != Cfg9346_Normal)
-	return 0;
 
-    if (rtl8139_cp_receiver_enabled(s)) {
+    if (rtl8139_cp_receiver_enabled(s) && rtl8139_cp_rx_valid(s)) {
         /* ??? Flow control not implemented in c+ mode.
            This is a hack to work around slirp deficiencies anyway.  */
         return 1;
@@ -836,12 +840,6 @@ static ssize_t rtl8139_do_receive(VLANClientState *nc, const uint8_t *buf, size_
         return -1;
     }
 
-    /* check whether we are in normal mode */
-    if ((s->Cfg9346 & Chip9346_op_mask) != Cfg9346_Normal) {
-        DPRINTF("not in normal op mode\n");
-        return -1;
-    }
-
     /* XXX: check this */
     if (s->RxConfig & AcceptAllPhys) {
         /* promiscuous: receive all */
@@ -946,6 +944,10 @@ static ssize_t rtl8139_do_receive(VLANClientState *nc, const uint8_t *buf, size_
 
     if (rtl8139_cp_receiver_enabled(s))
     {
+        if (!rtl8139_cp_rx_valid(s)) {
+            return size;
+        }
+
         DPRINTF("in C+ Rx mode ================\n");
 
         /* begin C+ receiver mode */
commit 2624bab836662d37f08336408a99d97652fc9c4d
Author: Daniel P. Berrange <berrange at redhat.com>
Date:   Wed Jun 20 14:24:28 2012 +0100

    Remove support for non-threaded VNC server
    
    QEMU now has a fundamental requirement for pthreads, so there
    is no compelling reason to retain support for the non-threaded
    VNC server. Remove the --{enable,disable}-vnc-thread configure
    arguments, and all CONFIG_VNC_THREAD conditionals
    
    Signed-off-by: Daniel P. Berrange <berrange at redhat.com>
    Signed-off-by: Anthony Liguori <aliguori at us.ibm.com>

diff --git a/configure b/configure
index f575279..9f071b7 100755
--- a/configure
+++ b/configure
@@ -134,7 +134,6 @@ vnc_tls=""
 vnc_sasl=""
 vnc_jpeg=""
 vnc_png=""
-vnc_thread="no"
 xen=""
 xen_ctrl_version=""
 xen_pci_passthrough=""
@@ -667,10 +666,6 @@ for opt do
   ;;
   --enable-vnc-png) vnc_png="yes"
   ;;
-  --disable-vnc-thread) vnc_thread="no"
-  ;;
-  --enable-vnc-thread) vnc_thread="yes"
-  ;;
   --disable-slirp) slirp="no"
   ;;
   --disable-uuid) uuid="no"
@@ -3024,7 +3019,6 @@ if test "$vnc" = "yes" ; then
     echo "VNC SASL support  $vnc_sasl"
     echo "VNC JPEG support  $vnc_jpeg"
     echo "VNC PNG support   $vnc_png"
-    echo "VNC thread        $vnc_thread"
 fi
 if test -n "$sparc_cpu"; then
     echo "Target Sparc Arch $sparc_cpu"
@@ -3200,9 +3194,6 @@ if test "$vnc_png" = "yes" ; then
   echo "CONFIG_VNC_PNG=y" >> $config_host_mak
   echo "VNC_PNG_CFLAGS=$vnc_png_cflags" >> $config_host_mak
 fi
-if test "$vnc_thread" = "yes" ; then
-  echo "CONFIG_VNC_THREAD=y" >> $config_host_mak
-fi
 if test "$fnmatch" = "yes" ; then
   echo "CONFIG_FNMATCH=y" >> $config_host_mak
 fi
diff --git a/ui/Makefile.objs b/ui/Makefile.objs
index 3687c8a..adc07be 100644
--- a/ui/Makefile.objs
+++ b/ui/Makefile.objs
@@ -4,11 +4,7 @@ vnc-obj-y += vnc-enc-tight.o vnc-palette.o
 vnc-obj-y += vnc-enc-zrle.o
 vnc-obj-$(CONFIG_VNC_TLS) += vnc-tls.o vnc-auth-vencrypt.o
 vnc-obj-$(CONFIG_VNC_SASL) += vnc-auth-sasl.o
-ifdef CONFIG_VNC_THREAD
-vnc-obj-y += vnc-jobs-async.o
-else
-vnc-obj-y += vnc-jobs-sync.o
-endif
+vnc-obj-y += vnc-jobs.o
 
 common-obj-y += keymaps.o
 common-obj-$(CONFIG_SPICE) += spice-core.o spice-input.o spice-display.o
diff --git a/ui/vnc-jobs-async.c b/ui/vnc-jobs-async.c
deleted file mode 100644
index 087b84d..0000000
--- a/ui/vnc-jobs-async.c
+++ /dev/null
@@ -1,351 +0,0 @@
-/*
- * QEMU VNC display driver
- *
- * Copyright (C) 2006 Anthony Liguori <anthony at codemonkey.ws>
- * Copyright (C) 2006 Fabrice Bellard
- * Copyright (C) 2009 Red Hat, Inc
- * Copyright (C) 2010 Corentin Chary <corentin.chary at gmail.com>
- *
- * Permission is hereby granted, free of charge, to any person obtaining a copy
- * of this software and associated documentation files (the "Software"), to deal
- * in the Software without restriction, including without limitation the rights
- * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
- * copies of the Software, and to permit persons to whom the Software is
- * furnished to do so, subject to the following conditions:
- *
- * The above copyright notice and this permission notice shall be included in
- * all copies or substantial portions of the Software.
- *
- * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
- * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
- * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
- * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
- * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
- * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
- * THE SOFTWARE.
- */
-
-
-#include "vnc.h"
-#include "vnc-jobs.h"
-#include "qemu_socket.h"
-
-/*
- * Locking:
- *
- * There is three levels of locking:
- * - jobs queue lock: for each operation on the queue (push, pop, isEmpty?)
- * - VncDisplay global lock: mainly used for framebuffer updates to avoid
- *                      screen corruption if the framebuffer is updated
- *			while the worker is doing something.
- * - VncState::output lock: used to make sure the output buffer is not corrupted
- * 		   	 if two threads try to write on it at the same time
- *
- * While the VNC worker thread is working, the VncDisplay global lock is hold
- * to avoid screen corruptions (this does not block vnc_refresh() because it
- * uses trylock()) but the output lock is not hold because the thread work on
- * its own output buffer.
- * When the encoding job is done, the worker thread will hold the output lock
- * and copy its output buffer in vs->output.
-*/
-
-struct VncJobQueue {
-    QemuCond cond;
-    QemuMutex mutex;
-    QemuThread thread;
-    Buffer buffer;
-    bool exit;
-    QTAILQ_HEAD(, VncJob) jobs;
-};
-
-typedef struct VncJobQueue VncJobQueue;
-
-/*
- * We use a single global queue, but most of the functions are
- * already reetrant, so we can easilly add more than one encoding thread
- */
-static VncJobQueue *queue;
-
-static void vnc_lock_queue(VncJobQueue *queue)
-{
-    qemu_mutex_lock(&queue->mutex);
-}
-
-static void vnc_unlock_queue(VncJobQueue *queue)
-{
-    qemu_mutex_unlock(&queue->mutex);
-}
-
-VncJob *vnc_job_new(VncState *vs)
-{
-    VncJob *job = g_malloc0(sizeof(VncJob));
-
-    job->vs = vs;
-    vnc_lock_queue(queue);
-    QLIST_INIT(&job->rectangles);
-    vnc_unlock_queue(queue);
-    return job;
-}
-
-int vnc_job_add_rect(VncJob *job, int x, int y, int w, int h)
-{
-    VncRectEntry *entry = g_malloc0(sizeof(VncRectEntry));
-
-    entry->rect.x = x;
-    entry->rect.y = y;
-    entry->rect.w = w;
-    entry->rect.h = h;
-
-    vnc_lock_queue(queue);
-    QLIST_INSERT_HEAD(&job->rectangles, entry, next);
-    vnc_unlock_queue(queue);
-    return 1;
-}
-
-void vnc_job_push(VncJob *job)
-{
-    vnc_lock_queue(queue);
-    if (queue->exit || QLIST_EMPTY(&job->rectangles)) {
-        g_free(job);
-    } else {
-        QTAILQ_INSERT_TAIL(&queue->jobs, job, next);
-        qemu_cond_broadcast(&queue->cond);
-    }
-    vnc_unlock_queue(queue);
-}
-
-static bool vnc_has_job_locked(VncState *vs)
-{
-    VncJob *job;
-
-    QTAILQ_FOREACH(job, &queue->jobs, next) {
-        if (job->vs == vs || !vs) {
-            return true;
-        }
-    }
-    return false;
-}
-
-bool vnc_has_job(VncState *vs)
-{
-    bool ret;
-
-    vnc_lock_queue(queue);
-    ret = vnc_has_job_locked(vs);
-    vnc_unlock_queue(queue);
-    return ret;
-}
-
-void vnc_jobs_clear(VncState *vs)
-{
-    VncJob *job, *tmp;
-
-    vnc_lock_queue(queue);
-    QTAILQ_FOREACH_SAFE(job, &queue->jobs, next, tmp) {
-        if (job->vs == vs || !vs) {
-            QTAILQ_REMOVE(&queue->jobs, job, next);
-        }
-    }
-    vnc_unlock_queue(queue);
-}
-
-void vnc_jobs_join(VncState *vs)
-{
-    vnc_lock_queue(queue);
-    while (vnc_has_job_locked(vs)) {
-        qemu_cond_wait(&queue->cond, &queue->mutex);
-    }
-    vnc_unlock_queue(queue);
-    vnc_jobs_consume_buffer(vs);
-}
-
-void vnc_jobs_consume_buffer(VncState *vs)
-{
-    bool flush;
-
-    vnc_lock_output(vs);
-    if (vs->jobs_buffer.offset) {
-        vnc_write(vs, vs->jobs_buffer.buffer, vs->jobs_buffer.offset);
-        buffer_reset(&vs->jobs_buffer);
-    }
-    flush = vs->csock != -1 && vs->abort != true;
-    vnc_unlock_output(vs);
-
-    if (flush) {
-      vnc_flush(vs);
-    }
-}
-
-/*
- * Copy data for local use
- */
-static void vnc_async_encoding_start(VncState *orig, VncState *local)
-{
-    local->vnc_encoding = orig->vnc_encoding;
-    local->features = orig->features;
-    local->ds = orig->ds;
-    local->vd = orig->vd;
-    local->lossy_rect = orig->lossy_rect;
-    local->write_pixels = orig->write_pixels;
-    local->clientds = orig->clientds;
-    local->tight = orig->tight;
-    local->zlib = orig->zlib;
-    local->hextile = orig->hextile;
-    local->zrle = orig->zrle;
-    local->output =  queue->buffer;
-    local->csock = -1; /* Don't do any network work on this thread */
-
-    buffer_reset(&local->output);
-}
-
-static void vnc_async_encoding_end(VncState *orig, VncState *local)
-{
-    orig->tight = local->tight;
-    orig->zlib = local->zlib;
-    orig->hextile = local->hextile;
-    orig->zrle = local->zrle;
-    orig->lossy_rect = local->lossy_rect;
-
-    queue->buffer = local->output;
-}
-
-static int vnc_worker_thread_loop(VncJobQueue *queue)
-{
-    VncJob *job;
-    VncRectEntry *entry, *tmp;
-    VncState vs;
-    int n_rectangles;
-    int saved_offset;
-
-    vnc_lock_queue(queue);
-    while (QTAILQ_EMPTY(&queue->jobs) && !queue->exit) {
-        qemu_cond_wait(&queue->cond, &queue->mutex);
-    }
-    /* Here job can only be NULL if queue->exit is true */
-    job = QTAILQ_FIRST(&queue->jobs);
-    vnc_unlock_queue(queue);
-
-    if (queue->exit) {
-        return -1;
-    }
-
-    vnc_lock_output(job->vs);
-    if (job->vs->csock == -1 || job->vs->abort == true) {
-        vnc_unlock_output(job->vs);
-        goto disconnected;
-    }
-    vnc_unlock_output(job->vs);
-
-    /* Make a local copy of vs and switch output buffers */
-    vnc_async_encoding_start(job->vs, &vs);
-
-    /* Start sending rectangles */
-    n_rectangles = 0;
-    vnc_write_u8(&vs, VNC_MSG_SERVER_FRAMEBUFFER_UPDATE);
-    vnc_write_u8(&vs, 0);
-    saved_offset = vs.output.offset;
-    vnc_write_u16(&vs, 0);
-
-    vnc_lock_display(job->vs->vd);
-    QLIST_FOREACH_SAFE(entry, &job->rectangles, next, tmp) {
-        int n;
-
-        if (job->vs->csock == -1) {
-            vnc_unlock_display(job->vs->vd);
-            goto disconnected;
-        }
-
-        n = vnc_send_framebuffer_update(&vs, entry->rect.x, entry->rect.y,
-                                        entry->rect.w, entry->rect.h);
-
-        if (n >= 0) {
-            n_rectangles += n;
-        }
-        g_free(entry);
-    }
-    vnc_unlock_display(job->vs->vd);
-
-    /* Put n_rectangles at the beginning of the message */
-    vs.output.buffer[saved_offset] = (n_rectangles >> 8) & 0xFF;
-    vs.output.buffer[saved_offset + 1] = n_rectangles & 0xFF;
-
-    vnc_lock_output(job->vs);
-    if (job->vs->csock != -1) {
-        buffer_reserve(&job->vs->jobs_buffer, vs.output.offset);
-        buffer_append(&job->vs->jobs_buffer, vs.output.buffer,
-                      vs.output.offset);
-        /* Copy persistent encoding data */
-        vnc_async_encoding_end(job->vs, &vs);
-
-	qemu_bh_schedule(job->vs->bh);
-    }
-    vnc_unlock_output(job->vs);
-
-disconnected:
-    vnc_lock_queue(queue);
-    QTAILQ_REMOVE(&queue->jobs, job, next);
-    vnc_unlock_queue(queue);
-    qemu_cond_broadcast(&queue->cond);
-    g_free(job);
-    return 0;
-}
-
-static VncJobQueue *vnc_queue_init(void)
-{
-    VncJobQueue *queue = g_malloc0(sizeof(VncJobQueue));
-
-    qemu_cond_init(&queue->cond);
-    qemu_mutex_init(&queue->mutex);
-    QTAILQ_INIT(&queue->jobs);
-    return queue;
-}
-
-static void vnc_queue_clear(VncJobQueue *q)
-{
-    qemu_cond_destroy(&queue->cond);
-    qemu_mutex_destroy(&queue->mutex);
-    buffer_free(&queue->buffer);
-    g_free(q);
-    queue = NULL; /* Unset global queue */
-}
-
-static void *vnc_worker_thread(void *arg)
-{
-    VncJobQueue *queue = arg;
-
-    qemu_thread_get_self(&queue->thread);
-
-    while (!vnc_worker_thread_loop(queue)) ;
-    vnc_queue_clear(queue);
-    return NULL;
-}
-
-void vnc_start_worker_thread(void)
-{
-    VncJobQueue *q;
-
-    if (vnc_worker_thread_running())
-        return ;
-
-    q = vnc_queue_init();
-    qemu_thread_create(&q->thread, vnc_worker_thread, q, QEMU_THREAD_DETACHED);
-    queue = q; /* Set global queue */
-}
-
-bool vnc_worker_thread_running(void)
-{
-    return queue; /* Check global queue */
-}
-
-void vnc_stop_worker_thread(void)
-{
-    if (!vnc_worker_thread_running())
-        return ;
-
-    /* Remove all jobs and wake up the thread */
-    vnc_lock_queue(queue);
-    queue->exit = true;
-    vnc_unlock_queue(queue);
-    vnc_jobs_clear(NULL);
-    qemu_cond_broadcast(&queue->cond);
-}
diff --git a/ui/vnc-jobs-sync.c b/ui/vnc-jobs-sync.c
deleted file mode 100644
index 49b77af..0000000
--- a/ui/vnc-jobs-sync.c
+++ /dev/null
@@ -1,73 +0,0 @@
-/*
- * QEMU VNC display driver
- *
- * Copyright (C) 2006 Anthony Liguori <anthony at codemonkey.ws>
- * Copyright (C) 2006 Fabrice Bellard
- * Copyright (C) 2009 Red Hat, Inc
- * Copyright (C) 2010 Corentin Chary <corentin.chary at gmail.com>
- *
- * Permission is hereby granted, free of charge, to any person obtaining a copy
- * of this software and associated documentation files (the "Software"), to deal
- * in the Software without restriction, including without limitation the rights
- * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
- * copies of the Software, and to permit persons to whom the Software is
- * furnished to do so, subject to the following conditions:
- *
- * The above copyright notice and this permission notice shall be included in
- * all copies or substantial portions of the Software.
- *
- * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
- * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
- * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
- * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
- * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
- * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
- * THE SOFTWARE.
- */
-
-#include "vnc.h"
-#include "vnc-jobs.h"
-
-void vnc_jobs_clear(VncState *vs)
-{
-}
-
-void vnc_jobs_join(VncState *vs)
-{
-}
-
-VncJob *vnc_job_new(VncState *vs)
-{
-    vs->job.vs = vs;
-    vs->job.rectangles = 0;
-
-    vnc_write_u8(vs, VNC_MSG_SERVER_FRAMEBUFFER_UPDATE);
-    vnc_write_u8(vs, 0);
-    vs->job.saved_offset = vs->output.offset;
-    vnc_write_u16(vs, 0);
-    return &vs->job;
-}
-
-void vnc_job_push(VncJob *job)
-{
-    VncState *vs = job->vs;
-
-    vs->output.buffer[job->saved_offset] = (job->rectangles >> 8) & 0xFF;
-    vs->output.buffer[job->saved_offset + 1] = job->rectangles & 0xFF;
-    vnc_flush(job->vs);
-}
-
-int vnc_job_add_rect(VncJob *job, int x, int y, int w, int h)
-{
-    int n;
-
-    n = vnc_send_framebuffer_update(job->vs, x, y, w, h);
-    if (n >= 0)
-        job->rectangles += n;
-    return n;
-}
-
-bool vnc_has_job(VncState *vs)
-{
-    return false;
-}
diff --git a/ui/vnc-jobs.c b/ui/vnc-jobs.c
new file mode 100644
index 0000000..087b84d
--- /dev/null
+++ b/ui/vnc-jobs.c
@@ -0,0 +1,351 @@
+/*
+ * QEMU VNC display driver
+ *
+ * Copyright (C) 2006 Anthony Liguori <anthony at codemonkey.ws>
+ * Copyright (C) 2006 Fabrice Bellard
+ * Copyright (C) 2009 Red Hat, Inc
+ * Copyright (C) 2010 Corentin Chary <corentin.chary at gmail.com>
+ *
+ * Permission is hereby granted, free of charge, to any person obtaining a copy
+ * of this software and associated documentation files (the "Software"), to deal
+ * in the Software without restriction, including without limitation the rights
+ * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+ * copies of the Software, and to permit persons to whom the Software is
+ * furnished to do so, subject to the following conditions:
+ *
+ * The above copyright notice and this permission notice shall be included in
+ * all copies or substantial portions of the Software.
+ *
+ * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+ * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+ * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
+ * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+ * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
+ * THE SOFTWARE.
+ */
+
+
+#include "vnc.h"
+#include "vnc-jobs.h"
+#include "qemu_socket.h"
+
+/*
+ * Locking:
+ *
+ * There is three levels of locking:
+ * - jobs queue lock: for each operation on the queue (push, pop, isEmpty?)
+ * - VncDisplay global lock: mainly used for framebuffer updates to avoid
+ *                      screen corruption if the framebuffer is updated
+ *			while the worker is doing something.
+ * - VncState::output lock: used to make sure the output buffer is not corrupted
+ * 		   	 if two threads try to write on it at the same time
+ *
+ * While the VNC worker thread is working, the VncDisplay global lock is hold
+ * to avoid screen corruptions (this does not block vnc_refresh() because it
+ * uses trylock()) but the output lock is not hold because the thread work on
+ * its own output buffer.
+ * When the encoding job is done, the worker thread will hold the output lock
+ * and copy its output buffer in vs->output.
+*/
+
+struct VncJobQueue {
+    QemuCond cond;
+    QemuMutex mutex;
+    QemuThread thread;
+    Buffer buffer;
+    bool exit;
+    QTAILQ_HEAD(, VncJob) jobs;
+};
+
+typedef struct VncJobQueue VncJobQueue;
+
+/*
+ * We use a single global queue, but most of the functions are
+ * already reetrant, so we can easilly add more than one encoding thread
+ */
+static VncJobQueue *queue;
+
+static void vnc_lock_queue(VncJobQueue *queue)
+{
+    qemu_mutex_lock(&queue->mutex);
+}
+
+static void vnc_unlock_queue(VncJobQueue *queue)
+{
+    qemu_mutex_unlock(&queue->mutex);
+}
+
+VncJob *vnc_job_new(VncState *vs)
+{
+    VncJob *job = g_malloc0(sizeof(VncJob));
+
+    job->vs = vs;
+    vnc_lock_queue(queue);
+    QLIST_INIT(&job->rectangles);
+    vnc_unlock_queue(queue);
+    return job;
+}
+
+int vnc_job_add_rect(VncJob *job, int x, int y, int w, int h)
+{
+    VncRectEntry *entry = g_malloc0(sizeof(VncRectEntry));
+
+    entry->rect.x = x;
+    entry->rect.y = y;
+    entry->rect.w = w;
+    entry->rect.h = h;
+
+    vnc_lock_queue(queue);
+    QLIST_INSERT_HEAD(&job->rectangles, entry, next);
+    vnc_unlock_queue(queue);
+    return 1;
+}
+
+void vnc_job_push(VncJob *job)
+{
+    vnc_lock_queue(queue);
+    if (queue->exit || QLIST_EMPTY(&job->rectangles)) {
+        g_free(job);
+    } else {
+        QTAILQ_INSERT_TAIL(&queue->jobs, job, next);
+        qemu_cond_broadcast(&queue->cond);
+    }
+    vnc_unlock_queue(queue);
+}
+
+static bool vnc_has_job_locked(VncState *vs)
+{
+    VncJob *job;
+
+    QTAILQ_FOREACH(job, &queue->jobs, next) {
+        if (job->vs == vs || !vs) {
+            return true;
+        }
+    }
+    return false;
+}
+
+bool vnc_has_job(VncState *vs)
+{
+    bool ret;
+
+    vnc_lock_queue(queue);
+    ret = vnc_has_job_locked(vs);
+    vnc_unlock_queue(queue);
+    return ret;
+}
+
+void vnc_jobs_clear(VncState *vs)
+{
+    VncJob *job, *tmp;
+
+    vnc_lock_queue(queue);
+    QTAILQ_FOREACH_SAFE(job, &queue->jobs, next, tmp) {
+        if (job->vs == vs || !vs) {
+            QTAILQ_REMOVE(&queue->jobs, job, next);
+        }
+    }
+    vnc_unlock_queue(queue);
+}
+
+void vnc_jobs_join(VncState *vs)
+{
+    vnc_lock_queue(queue);
+    while (vnc_has_job_locked(vs)) {
+        qemu_cond_wait(&queue->cond, &queue->mutex);
+    }
+    vnc_unlock_queue(queue);
+    vnc_jobs_consume_buffer(vs);
+}
+
+void vnc_jobs_consume_buffer(VncState *vs)
+{
+    bool flush;
+
+    vnc_lock_output(vs);
+    if (vs->jobs_buffer.offset) {
+        vnc_write(vs, vs->jobs_buffer.buffer, vs->jobs_buffer.offset);
+        buffer_reset(&vs->jobs_buffer);
+    }
+    flush = vs->csock != -1 && vs->abort != true;
+    vnc_unlock_output(vs);
+
+    if (flush) {
+      vnc_flush(vs);
+    }
+}
+
+/*
+ * Copy data for local use
+ */
+static void vnc_async_encoding_start(VncState *orig, VncState *local)
+{
+    local->vnc_encoding = orig->vnc_encoding;
+    local->features = orig->features;
+    local->ds = orig->ds;
+    local->vd = orig->vd;
+    local->lossy_rect = orig->lossy_rect;
+    local->write_pixels = orig->write_pixels;
+    local->clientds = orig->clientds;
+    local->tight = orig->tight;
+    local->zlib = orig->zlib;
+    local->hextile = orig->hextile;
+    local->zrle = orig->zrle;
+    local->output =  queue->buffer;
+    local->csock = -1; /* Don't do any network work on this thread */
+
+    buffer_reset(&local->output);
+}
+
+static void vnc_async_encoding_end(VncState *orig, VncState *local)
+{
+    orig->tight = local->tight;
+    orig->zlib = local->zlib;
+    orig->hextile = local->hextile;
+    orig->zrle = local->zrle;
+    orig->lossy_rect = local->lossy_rect;
+
+    queue->buffer = local->output;
+}
+
+static int vnc_worker_thread_loop(VncJobQueue *queue)
+{
+    VncJob *job;
+    VncRectEntry *entry, *tmp;
+    VncState vs;
+    int n_rectangles;
+    int saved_offset;
+
+    vnc_lock_queue(queue);
+    while (QTAILQ_EMPTY(&queue->jobs) && !queue->exit) {
+        qemu_cond_wait(&queue->cond, &queue->mutex);
+    }
+    /* Here job can only be NULL if queue->exit is true */
+    job = QTAILQ_FIRST(&queue->jobs);
+    vnc_unlock_queue(queue);
+
+    if (queue->exit) {
+        return -1;
+    }
+
+    vnc_lock_output(job->vs);
+    if (job->vs->csock == -1 || job->vs->abort == true) {
+        vnc_unlock_output(job->vs);
+        goto disconnected;
+    }
+    vnc_unlock_output(job->vs);
+
+    /* Make a local copy of vs and switch output buffers */
+    vnc_async_encoding_start(job->vs, &vs);
+
+    /* Start sending rectangles */
+    n_rectangles = 0;
+    vnc_write_u8(&vs, VNC_MSG_SERVER_FRAMEBUFFER_UPDATE);
+    vnc_write_u8(&vs, 0);
+    saved_offset = vs.output.offset;
+    vnc_write_u16(&vs, 0);
+
+    vnc_lock_display(job->vs->vd);
+    QLIST_FOREACH_SAFE(entry, &job->rectangles, next, tmp) {
+        int n;
+
+        if (job->vs->csock == -1) {
+            vnc_unlock_display(job->vs->vd);
+            goto disconnected;
+        }
+
+        n = vnc_send_framebuffer_update(&vs, entry->rect.x, entry->rect.y,
+                                        entry->rect.w, entry->rect.h);
+
+        if (n >= 0) {
+            n_rectangles += n;
+        }
+        g_free(entry);
+    }
+    vnc_unlock_display(job->vs->vd);
+
+    /* Put n_rectangles at the beginning of the message */
+    vs.output.buffer[saved_offset] = (n_rectangles >> 8) & 0xFF;
+    vs.output.buffer[saved_offset + 1] = n_rectangles & 0xFF;
+
+    vnc_lock_output(job->vs);
+    if (job->vs->csock != -1) {
+        buffer_reserve(&job->vs->jobs_buffer, vs.output.offset);
+        buffer_append(&job->vs->jobs_buffer, vs.output.buffer,
+                      vs.output.offset);
+        /* Copy persistent encoding data */
+        vnc_async_encoding_end(job->vs, &vs);
+
+	qemu_bh_schedule(job->vs->bh);
+    }
+    vnc_unlock_output(job->vs);
+
+disconnected:
+    vnc_lock_queue(queue);
+    QTAILQ_REMOVE(&queue->jobs, job, next);
+    vnc_unlock_queue(queue);
+    qemu_cond_broadcast(&queue->cond);
+    g_free(job);
+    return 0;
+}
+
+static VncJobQueue *vnc_queue_init(void)
+{
+    VncJobQueue *queue = g_malloc0(sizeof(VncJobQueue));
+
+    qemu_cond_init(&queue->cond);
+    qemu_mutex_init(&queue->mutex);
+    QTAILQ_INIT(&queue->jobs);
+    return queue;
+}
+
+static void vnc_queue_clear(VncJobQueue *q)
+{
+    qemu_cond_destroy(&queue->cond);
+    qemu_mutex_destroy(&queue->mutex);
+    buffer_free(&queue->buffer);
+    g_free(q);
+    queue = NULL; /* Unset global queue */
+}
+
+static void *vnc_worker_thread(void *arg)
+{
+    VncJobQueue *queue = arg;
+
+    qemu_thread_get_self(&queue->thread);
+
+    while (!vnc_worker_thread_loop(queue)) ;
+    vnc_queue_clear(queue);
+    return NULL;
+}
+
+void vnc_start_worker_thread(void)
+{
+    VncJobQueue *q;
+
+    if (vnc_worker_thread_running())
+        return ;
+
+    q = vnc_queue_init();
+    qemu_thread_create(&q->thread, vnc_worker_thread, q, QEMU_THREAD_DETACHED);
+    queue = q; /* Set global queue */
+}
+
+bool vnc_worker_thread_running(void)
+{
+    return queue; /* Check global queue */
+}
+
+void vnc_stop_worker_thread(void)
+{
+    if (!vnc_worker_thread_running())
+        return ;
+
+    /* Remove all jobs and wake up the thread */
+    vnc_lock_queue(queue);
+    queue->exit = true;
+    vnc_unlock_queue(queue);
+    vnc_jobs_clear(NULL);
+    qemu_cond_broadcast(&queue->cond);
+}
diff --git a/ui/vnc-jobs.h b/ui/vnc-jobs.h
index 4c661f9..86e6d88 100644
--- a/ui/vnc-jobs.h
+++ b/ui/vnc-jobs.h
@@ -38,51 +38,35 @@ bool vnc_has_job(VncState *vs);
 void vnc_jobs_clear(VncState *vs);
 void vnc_jobs_join(VncState *vs);
 
-#ifdef CONFIG_VNC_THREAD
-
 void vnc_jobs_consume_buffer(VncState *vs);
 void vnc_start_worker_thread(void);
 bool vnc_worker_thread_running(void);
 void vnc_stop_worker_thread(void);
 
-#endif /* CONFIG_VNC_THREAD */
-
 /* Locks */
 static inline int vnc_trylock_display(VncDisplay *vd)
 {
-#ifdef CONFIG_VNC_THREAD
     return qemu_mutex_trylock(&vd->mutex);
-#else
-    return 0;
-#endif
 }
 
 static inline void vnc_lock_display(VncDisplay *vd)
 {
-#ifdef CONFIG_VNC_THREAD
     qemu_mutex_lock(&vd->mutex);
-#endif
 }
 
 static inline void vnc_unlock_display(VncDisplay *vd)
 {
-#ifdef CONFIG_VNC_THREAD
     qemu_mutex_unlock(&vd->mutex);
-#endif
 }
 
 static inline void vnc_lock_output(VncState *vs)
 {
-#ifdef CONFIG_VNC_THREAD
     qemu_mutex_lock(&vs->output_mutex);
-#endif
 }
 
 static inline void vnc_unlock_output(VncState *vs)
 {
-#ifdef CONFIG_VNC_THREAD
     qemu_mutex_unlock(&vs->output_mutex);
-#endif
 }
 
 #endif /* VNC_JOBS_H */
diff --git a/ui/vnc.c b/ui/vnc.c
index 54bc5ad..cf1cae2 100644
--- a/ui/vnc.c
+++ b/ui/vnc.c
@@ -526,7 +526,6 @@ static void vnc_desktop_resize(VncState *vs)
     vnc_flush(vs);
 }
 
-#ifdef CONFIG_VNC_THREAD
 static void vnc_abort_display_jobs(VncDisplay *vd)
 {
     VncState *vs;
@@ -545,11 +544,6 @@ static void vnc_abort_display_jobs(VncDisplay *vd)
         vnc_unlock_output(vs);
     }
 }
-#else
-static void vnc_abort_display_jobs(VncDisplay *vd)
-{
-}
-#endif
 
 static void vnc_dpy_resize(DisplayState *ds)
 {
@@ -867,19 +861,12 @@ static int find_and_clear_dirty_height(struct VncState *vs,
     return h;
 }
 
-#ifdef CONFIG_VNC_THREAD
 static int vnc_update_client_sync(VncState *vs, int has_dirty)
 {
     int ret = vnc_update_client(vs, has_dirty);
     vnc_jobs_join(vs);
     return ret;
 }
-#else
-static int vnc_update_client_sync(VncState *vs, int has_dirty)
-{
-    return vnc_update_client(vs, has_dirty);
-}
-#endif
 
 static int vnc_update_client(VncState *vs, int has_dirty)
 {
@@ -1066,11 +1053,9 @@ static void vnc_disconnect_finish(VncState *vs)
         qemu_remove_led_event_handler(vs->led);
     vnc_unlock_output(vs);
 
-#ifdef CONFIG_VNC_THREAD
     qemu_mutex_destroy(&vs->output_mutex);
     qemu_bh_delete(vs->bh);
     buffer_free(&vs->jobs_buffer);
-#endif
 
     for (i = 0; i < VNC_STAT_ROWS; ++i) {
         g_free(vs->lossy_rect[i]);
@@ -1286,14 +1271,12 @@ static long vnc_client_read_plain(VncState *vs)
     return ret;
 }
 
-#ifdef CONFIG_VNC_THREAD
 static void vnc_jobs_bh(void *opaque)
 {
     VncState *vs = opaque;
 
     vnc_jobs_consume_buffer(vs);
 }
-#endif
 
 /*
  * First function called whenever there is more data to be read from
@@ -2699,10 +2682,8 @@ static void vnc_connect(VncDisplay *vd, int csock, int skipauth)
     vs->as.fmt = AUD_FMT_S16;
     vs->as.endianness = 0;
 
-#ifdef CONFIG_VNC_THREAD
     qemu_mutex_init(&vs->output_mutex);
     vs->bh = qemu_bh_new(vnc_jobs_bh, vs);
-#endif
 
     QTAILQ_INSERT_HEAD(&vd->clients, vs, next);
 
@@ -2762,10 +2743,8 @@ void vnc_display_init(DisplayState *ds)
     if (!vs->kbd_layout)
         exit(1);
 
-#ifdef CONFIG_VNC_THREAD
     qemu_mutex_init(&vs->mutex);
     vnc_start_worker_thread();
-#endif
 
     dcl->dpy_copy = vnc_dpy_copy;
     dcl->dpy_update = vnc_dpy_update;
diff --git a/ui/vnc.h b/ui/vnc.h
index a851ebd..068c2fc 100644
--- a/ui/vnc.h
+++ b/ui/vnc.h
@@ -29,9 +29,7 @@
 
 #include "qemu-common.h"
 #include "qemu-queue.h"
-#ifdef CONFIG_VNC_THREAD
 #include "qemu-thread.h"
-#endif
 #include "console.h"
 #include "monitor.h"
 #include "audio/audio.h"
@@ -146,9 +144,7 @@ struct VncDisplay
     DisplayState *ds;
     kbd_layout_t *kbd_layout;
     int lock_key_sync;
-#ifdef CONFIG_VNC_THREAD
     QemuMutex mutex;
-#endif
 
     QEMUCursor *cursor;
     int cursor_msize;
@@ -216,7 +212,6 @@ typedef struct VncZywrle {
     int buf[VNC_ZRLE_TILE_WIDTH * VNC_ZRLE_TILE_HEIGHT];
 } VncZywrle;
 
-#ifdef CONFIG_VNC_THREAD
 struct VncRect
 {
     int x;
@@ -238,14 +233,6 @@ struct VncJob
     QLIST_HEAD(, VncRectEntry) rectangles;
     QTAILQ_ENTRY(VncJob) next;
 };
-#else
-struct VncJob
-{
-    VncState *vs;
-    int rectangles;
-    size_t saved_offset;
-};
-#endif
 
 struct VncState
 {
@@ -300,13 +287,9 @@ struct VncState
     QEMUPutLEDEntry *led;
 
     bool abort;
-#ifndef CONFIG_VNC_THREAD
-    VncJob job;
-#else
     QemuMutex output_mutex;
     QEMUBH *bh;
     Buffer jobs_buffer;
-#endif
 
     /* Encoding specific, if you add something here, don't forget to
      *  update vnc_async_encoding_start()
commit a307beb6e8c4490bc4f9c95dc2195599ae43d59a
Author: Andreas Färber <afaerber at suse.de>
Date:   Thu Jun 14 15:14:33 2012 +0000

    configure: Assure existence of linux-headers/ build directory
    
    Commit ec5b06d (configure: ensure directory exists when creating symlinks)
    moved the creation of directories into the symlink() function but forgot
    the case where no symlink is created.
    
    This leads to build errors on arm Linux due to -I../linux-headers.
    
    Unbreak the build on arm Linux by reverting part of that commit.
    
    Signed-off-by: Andreas Färber <afaerber at suse.de>
    Signed-off-by: Anthony Liguori <aliguori at us.ibm.com>

diff --git a/configure b/configure
index 37faee4..f575279 100755
--- a/configure
+++ b/configure
@@ -3491,6 +3491,7 @@ done
 
 # use included Linux headers
 if test "$linux" = "yes" ; then
+  mkdir -p linux-headers
   case "$cpu" in
   i386|x86_64)
     symlink "$source_path/linux-headers/asm-x86" linux-headers/asm
commit b54fa7ddde8ace758d1eb332ce4a10e35dbf7302
Author: Peter Maydell <peter.maydell at linaro.org>
Date:   Wed Jun 20 18:02:33 2012 +0100

    Makefile.target: Update clean command to clean hw/ directory
    
    Now we create object files in a hierarchy under hw/, so the
    'clean' target must also be updated to delete those object files.
    Rather than using a manual list of subdirectories which will
    easily drift out of date, we just delete all .o and .d files
    in the target directory hierarchy.
    
    Signed-off-by: Peter Maydell <peter.maydell at linaro.org>
    Signed-off-by: Anthony Liguori <aliguori at us.ibm.com>

diff --git a/Makefile.target b/Makefile.target
index 8f12b0f..127d573 100644
--- a/Makefile.target
+++ b/Makefile.target
@@ -193,8 +193,8 @@ qmp-commands-old.h: $(SRC_PATH)/qmp-commands.hx
 	$(call quiet-command,sh $(SRC_PATH)/scripts/hxtool -h < $< > $@,"  GEN   $(TARGET_DIR)$@")
 
 clean:
-	rm -f *.o *.a *~ $(PROGS) nwfpe/*.o fpu/*.o
-	rm -f *.d */*.d tcg/*.o ide/*.o 9pfs/*.o kvm/*.o
+	rm -f *.a *~ $(PROGS)
+	rm -f $(shell find . -name '*.[od]')
 	rm -f hmp-commands.h qmp-commands-old.h gdbstub-xml.c
 ifdef CONFIG_TRACE_SYSTEMTAP
 	rm -f *.stp
commit 039380a8e18f618cdacf72486449c04dc1b70eef
Author: Anthony Liguori <aliguori at us.ibm.com>
Date:   Wed Jun 27 08:20:43 2012 -0500

    qtest: fix infinite loop when QEMU aborts abruptly
    
    From Markus:
    
    Makes "make check" hang:
    
        QTEST_QEMU_BINARY=x86_64-softmmu/qemu-system-x86_64 gtester -k --verbose -m=quick tests/crash-test tests/rtc-test
        TEST: tests/crash-test... (pid=972)
        qemu-system-x86_64: Device needs media, but drive is empty
    [Nothing happens, wait a while, then hit ^C]
        make: *** [check-qtest-x86_64] Interrupt
    
    This was due to the fact that we weren't checked for errors when
    reading from the QMP socket.  This patch adds appropriate error
    checking.
    
    Reported-by: Markus Armbruster <armbru at redhat.com>
    Signed-off-by: Anthony Liguori <aliguori at us.ibm.com>

diff --git a/tests/libqtest.c b/tests/libqtest.c
index 1d73fd1..071b6be 100644
--- a/tests/libqtest.c
+++ b/tests/libqtest.c
@@ -291,6 +291,11 @@ void qtest_qmp(QTestState *s, const char *fmt, ...)
             continue;
         }
 
+        if (len == -1 || len == 0) {
+            fprintf(stderr, "Broken pipe\n");
+            exit(1);
+        }
+
         switch (c) {
         case '{':
             nesting++;
commit 7de3abe505e34398cef5bddf6c4d0bd9ee47007f
Author: Anthony Liguori <aliguori at us.ibm.com>
Date:   Wed Jun 27 07:37:54 2012 -0500

    qdev: fix use-after-free in the error path of qdev_init_nofail
    
    From Markus:
    
    Before:
    
        $ qemu-system-x86_64 -display none -drive if=ide
        qemu-system-x86_64: Device needs media, but drive is empty
        qemu-system-x86_64: Initialization of device ide-hd failed
        [Exit 1 ]
    
    After:
    
        $ qemu-system-x86_64 -display none -drive if=ide
        qemu-system-x86_64: Device needs media, but drive is empty
        Segmentation fault (core dumped)
        [Exit 139 (SIGSEGV)]
    
    This error always existed as qdev_init() frees the object.  But QOM
    goes a bit further and purposefully sets the class pointer to NULL to
    help find use-after-free.  It worked :-)
    
    Cc: Andreas Faerber <afaerber at suse.de>
    Reported-by: Markus Armbruster <armbru at redhat.com>
    Signed-off-by: Anthony Liguori <aliguori at us.ibm.com>

diff --git a/hw/qdev.c b/hw/qdev.c
index a6c4c02..af54467 100644
--- a/hw/qdev.c
+++ b/hw/qdev.c
@@ -258,9 +258,10 @@ int qdev_simple_unplug_cb(DeviceState *dev)
    way is somewhat unclean, and best avoided.  */
 void qdev_init_nofail(DeviceState *dev)
 {
+    const char *typename = object_get_typename(OBJECT(dev));
+
     if (qdev_init(dev) < 0) {
-        error_report("Initialization of device %s failed",
-                     object_get_typename(OBJECT(dev)));
+        error_report("Initialization of device %s failed", typename);
         exit(1);
     }
 }
commit d24b569a4162c54426ab5088637b824f54f6ac16
Author: Peter A. G. Crosthwaite <peter.crosthwaite at petalogix.com>
Date:   Tue Jun 26 14:29:42 2012 +1000

    MAINTAINERS: Added device tree
    
    Agreed between myself and Alex:
    http://lists.nongnu.org/archive/html/qemu-devel/2012-06/msg03561.html
    
    Signed-off-by: Peter A. G. Crosthwaite <peter.crosthwaite at petalogix.com>
    Acked-by: Alexander Graf <agraf at suse.de>
    Signed-off-by: Edgar E. Iglesias <edgar.iglesias at gmail.com>

diff --git a/MAINTAINERS b/MAINTAINERS
index e19f491..2a514fd 100644
--- a/MAINTAINERS
+++ b/MAINTAINERS
@@ -511,6 +511,12 @@ M: Anthony Liguori <aliguori at us.ibm.com>
 S: Maintained
 F: qemu-char.c
 
+Device Tree
+M: Peter Crosthwaite <peter.crosthwaite at petalogix.com>
+M: Alexander Graf <agraf at suse.de>
+S: Maintained
+F: device-tree.[ch]
+
 GDB stub
 M: qemu-devel at nongnu.org
 S: Odd Fixes
commit ab61d2405fa0be0a738b906674a0dbc7b198c433
Author: Peter A. G. Crosthwaite <peter.crosthwaite at petalogix.com>
Date:   Tue Jun 26 14:29:41 2012 +1000

    MAINTAINERS: Added Xilinx EDK devices
    
    Signed-off-by: Peter A. G. Crosthwaite <peter.crosthwaite at petalogix.com>
    Signed-off-by: Edgar E. Iglesias <edgar.iglesias at gmail.com>

diff --git a/MAINTAINERS b/MAINTAINERS
index d544a9c..e19f491 100644
--- a/MAINTAINERS
+++ b/MAINTAINERS
@@ -482,6 +482,17 @@ S: Supported
 F: hw/virtio-serial*
 F: hw/virtio-console*
 
+Xilinx EDK
+M: Peter Crosthwaite <peter.crosthwaite at petalogix.com>
+M: Edgar E. Iglesias <edgar.iglesias at gmail.com>
+S: Maintained
+F: hw/xilinx_axi*
+F: hw/xilinx_uartlite.c
+F: hw/xilinx_intc.c
+F: hw/xilinx_ethlite.c
+F: hw/xilinx_timer.c
+F: hw/xilinx.h
+
 Subsystems
 ----------
 Audio
commit d36e8ce73fd4e2c42367396d551513f32a95f7f6
Author: Peter A. G. Crosthwaite <peter.crosthwaite at petalogix.com>
Date:   Tue Jun 26 14:29:40 2012 +1000

    MAINTAINERS: Add Petalogix ml605 machine model
    
    Signed-off-by: Peter A. G. Crosthwaite <peter.crosthwaite at petalogix.com>
    Signed-off-by: Edgar E. Iglesias <edgar.iglesias at gmail.com>

diff --git a/MAINTAINERS b/MAINTAINERS
index b45f075..d544a9c 100644
--- a/MAINTAINERS
+++ b/MAINTAINERS
@@ -311,6 +311,11 @@ M: Edgar E. Iglesias <edgar.iglesias at gmail.com>
 S: Maintained
 F: hw/petalogix_s3adsp1800.c
 
+petalogix_ml605
+M: Peter Crosthwaite <peter.crosthwaite at petalogix.com>
+S: Maintained
+F: hw/petalogix_ml605_mmu.c
+
 MIPS Machines
 -------------
 Jazz
commit e0a3dc7cde83cedca3d54b43b3aff3f104b62911
Merge: 3aa42d3... 6a69226...
Author: Anthony Liguori <aliguori at us.ibm.com>
Date:   Tue Jun 26 15:09:47 2012 -0500

    Merge remote-tracking branch 'stefanha/trivial-patches' into staging
    
    * stefanha/trivial-patches:
      tci: Support INDEX_op_bswap64_i64
      target-i386: Use QEMU instead of Qemu
      Makefile.hw: avoid overly large 'make clean' rm command
      configure: Fix typo
      arm_gic: Send dbg msgs to stderr not stdout
      checkpatch: Add QEMU specific rule
      qemu-config: Use QEMU instead of Qemu
      libqtest: Fix socket_accept() to pass address_len
      Makefile.user: Define CONFIG_USER_ONLY for libuser/
      Makefile: Remove macro qapi-dir
      Makefile: Remove BUILD_DIR from qapi-dir
      Install 'bepo' keymap already included in Qemu source

commit 3aa42d329b4a26af6105ff199be1a785b9ddd461
Merge: 675658d... 9e56edc...
Author: Anthony Liguori <aliguori at us.ibm.com>
Date:   Tue Jun 26 15:07:03 2012 -0500

    Merge remote-tracking branch 'spice/spice.v58' into staging
    
    * spice/spice.v58:
      vga: raise default vgamem size
      add pc-1.2
      qxl: add vgamem_size_mb and vgamem_size
      vga: make vram size configurable
      vga: raise xres+yres limits
      qxl: reset current_async on qxl_soft_reset
      hw/qxl: ignore guest from guestbug until reset
      qxl: stop dirty loging when not in vga mode
      hw/qxl: s/qxl_guest_bug/qxl_set_guest_bug/
      ui/spice-display.c: add missing initialization for valgrind

commit 675658d97e86c42278fc08f8fb4c9531a027b4e7
Merge: 3978f46... eab5fd5...
Author: Anthony Liguori <aliguori at us.ibm.com>
Date:   Tue Jun 26 15:06:09 2012 -0500

    Merge remote-tracking branch 'mdroth/qga-pull-6-21-12' into staging
    
    * mdroth/qga-pull-6-21-12:
      qemu-ga: add guest-fstrim command
      qemu-ga: make names more generic for mount list functions

commit 3978f4612e7aa90469f6b1e0a04524833e77fbc6
Merge: 7a542b6... e108a3c...
Author: Anthony Liguori <aliguori at us.ibm.com>
Date:   Tue Jun 26 15:05:45 2012 -0500

    Merge remote-tracking branch 'sstabellini/compile-xs' into staging
    
    * sstabellini/compile-xs:
      xenstore: Use <xenstore.h>
      xen: Reorganize includes of Xen headers.

commit 7a542b67b32742ff5fe286f819df891d1df7bf56
Merge: b1a6609... 3854ca5...
Author: Anthony Liguori <aliguori at us.ibm.com>
Date:   Tue Jun 26 15:05:33 2012 -0500

    Merge remote-tracking branch 'sstabellini/xen-pt' into staging
    
    * sstabellini/xen-pt:
      Introduce Xen PCI Passthrough, MSI
      Introduce apic-msidef.h
      Introduce Xen PCI Passthrough, PCI config space helpers
      Introduce Xen PCI Passthrough, qdevice
      qdev-properties: Introduce pci-host-devaddr.
      pci.c: Add opaque argument to pci_for_each_device.
      Introduce XenHostPCIDevice to access a pci device on the host.
      configure: Introduce --enable-xen-pci-passthrough.
      pci_ids: Add INTEL_82599_SFP_VF id.

commit b1a6609e754330c657a057a96322e574c129bc29
Merge: cfee021... 77fa9ae...
Author: Anthony Liguori <aliguori at us.ibm.com>
Date:   Tue Jun 26 15:01:47 2012 -0500

    Merge remote-tracking branch 'kraxel/usb.54' into staging
    
    * kraxel/usb.54:
      uhci: fix uhci_async_cancel_all
      usb-host: live migration support
      usb-host: attach only to running guest
      ehci: tracing improvements
      usb: restore USBDevice->attached on vmload
      ehci: add live migration support

commit d65e9815b1ff90dff35e4e679bfb231c24e408f7
Author: Igor Mammedov <imammedo at redhat.com>
Date:   Tue Jun 19 15:39:46 2012 +0200

    target-i386: move tcg initialization into x86_cpu_initfn()
    
    In order to make cpu object not depended on external ad-hoc
    initialization routines, move tcg initialization from cpu_x86_init
    inside cpu object "x86_cpu_initfn()".
    
    Signed-off-by: Igor Mammedov <imammedo at redhat.com>
    Reviewed-by: Andreas Färber <afaerber at suse.de>

diff --git a/target-i386/cpu.c b/target-i386/cpu.c
index fdd95be..445274c 100644
--- a/target-i386/cpu.c
+++ b/target-i386/cpu.c
@@ -1716,6 +1716,7 @@ static void x86_cpu_initfn(Object *obj)
 {
     X86CPU *cpu = X86_CPU(obj);
     CPUX86State *env = &cpu->env;
+    static int inited;
 
     cpu_exec_init(env);
 
@@ -1745,6 +1746,15 @@ static void x86_cpu_initfn(Object *obj)
                         x86_cpuid_set_tsc_freq, NULL, NULL, NULL);
 
     env->cpuid_apic_id = env->cpu_index;
+
+    /* init various static tables used in TCG mode */
+    if (tcg_enabled() && !inited) {
+        inited = 1;
+        optimize_flags_init();
+#ifndef CONFIG_USER_ONLY
+        cpu_set_debug_excp_handler(breakpoint_handler);
+#endif
+    }
 }
 
 static void x86_cpu_common_class_init(ObjectClass *oc, void *data)
diff --git a/target-i386/cpu.h b/target-i386/cpu.h
index bcf663e..80dcb49 100644
--- a/target-i386/cpu.h
+++ b/target-i386/cpu.h
@@ -933,6 +933,7 @@ static inline int hw_breakpoint_len(unsigned long dr7, int index)
 void hw_breakpoint_insert(CPUX86State *env, int index);
 void hw_breakpoint_remove(CPUX86State *env, int index);
 int check_hw_breakpoints(CPUX86State *env, int force_dr6_update);
+void breakpoint_handler(CPUX86State *env);
 
 /* will be suppressed */
 void cpu_x86_update_cr0(CPUX86State *env, uint32_t new_cr0);
diff --git a/target-i386/helper.c b/target-i386/helper.c
index b9384f6..c52ec13 100644
--- a/target-i386/helper.c
+++ b/target-i386/helper.c
@@ -941,7 +941,7 @@ int check_hw_breakpoints(CPUX86State *env, int force_dr6_update)
     return hit_enabled;
 }
 
-static void breakpoint_handler(CPUX86State *env)
+void breakpoint_handler(CPUX86State *env)
 {
     CPUBreakpoint *bp;
 
@@ -1151,20 +1151,11 @@ X86CPU *cpu_x86_init(const char *cpu_model)
 {
     X86CPU *cpu;
     CPUX86State *env;
-    static int inited;
 
     cpu = X86_CPU(object_new(TYPE_X86_CPU));
     env = &cpu->env;
     env->cpu_model_str = cpu_model;
 
-    /* init various static tables used in TCG mode */
-    if (tcg_enabled() && !inited) {
-        inited = 1;
-        optimize_flags_init();
-#ifndef CONFIG_USER_ONLY
-        cpu_set_debug_excp_handler(breakpoint_handler);
-#endif
-    }
     if (cpu_x86_register(cpu, cpu_model) < 0) {
         object_delete(OBJECT(cpu));
         return NULL;
commit 84e3b6025930cd474d3ca9f1885801dbc100cecb
Author: Igor Mammedov <imammedo at redhat.com>
Date:   Thu Jun 21 18:29:38 2012 +0200

    cleanup cpu_set_debug_excp_handler
    
    There are no users left for previous exception handler returned from
    cpu_set_debug_excp_handler. It should simplify code a little.
    
    Signed-off-by: Igor Mammedov <imammedo at redhat.com>

diff --git a/cpu-exec.c b/cpu-exec.c
index 624c409..24607fb 100644
--- a/cpu-exec.c
+++ b/cpu-exec.c
@@ -156,12 +156,9 @@ static inline TranslationBlock *tb_find_fast(CPUArchState *env)
 
 static CPUDebugExcpHandler *debug_excp_handler;
 
-CPUDebugExcpHandler *cpu_set_debug_excp_handler(CPUDebugExcpHandler *handler)
+void cpu_set_debug_excp_handler(CPUDebugExcpHandler *handler)
 {
-    CPUDebugExcpHandler *old_handler = debug_excp_handler;
-
     debug_excp_handler = handler;
-    return old_handler;
 }
 
 static void cpu_handle_debug_exception(CPUArchState *env)
diff --git a/exec-all.h b/exec-all.h
index 9bda7f7..c5ec8e1 100644
--- a/exec-all.h
+++ b/exec-all.h
@@ -357,7 +357,7 @@ tb_page_addr_t get_page_addr_code(CPUArchState *env1, target_ulong addr);
 
 typedef void (CPUDebugExcpHandler)(CPUArchState *env);
 
-CPUDebugExcpHandler *cpu_set_debug_excp_handler(CPUDebugExcpHandler *handler);
+void cpu_set_debug_excp_handler(CPUDebugExcpHandler *handler);
 
 /* vl.c */
 extern int singlestep;
commit eeec69dc06a0b87a578f4935bbd699d03bc4f359
Author: Igor Mammedov <imammedo at redhat.com>
Date:   Thu Jun 21 17:57:19 2012 +0200

    target-xtensa: drop usage of prev_debug_excp_handler
    
    Chains of exception handlers are currently unused feature. Dropping it
    to be consistent with target-i386 but it may simplify qom-ifying CPU
    in future like for target-i386.
    
    Signed-off-by: Igor Mammedov <imammedo at redhat.com>

diff --git a/target-xtensa/helper.c b/target-xtensa/helper.c
index 044ce18..d5bb171 100644
--- a/target-xtensa/helper.c
+++ b/target-xtensa/helper.c
@@ -54,8 +54,6 @@ static uint32_t check_hw_breakpoints(CPUXtensaState *env)
     return 0;
 }
 
-static CPUDebugExcpHandler *prev_debug_excp_handler;
-
 static void breakpoint_handler(CPUXtensaState *env)
 {
     if (env->watchpoint_hit) {
@@ -70,9 +68,6 @@ static void breakpoint_handler(CPUXtensaState *env)
             cpu_resume_from_signal(env, NULL);
         }
     }
-    if (prev_debug_excp_handler) {
-        prev_debug_excp_handler(env);
-    }
 }
 
 XtensaCPU *cpu_xtensa_init(const char *cpu_model)
@@ -105,8 +100,7 @@ XtensaCPU *cpu_xtensa_init(const char *cpu_model)
 
     if (!debug_handler_inited && tcg_enabled()) {
         debug_handler_inited = 1;
-        prev_debug_excp_handler =
-            cpu_set_debug_excp_handler(breakpoint_handler);
+        cpu_set_debug_excp_handler(breakpoint_handler);
     }
 
     xtensa_irq_init(env);
commit 130a03855098a4057c227bc658c0688f8665b71f
Author: Igor Mammedov <imammedo at redhat.com>
Date:   Tue Jun 19 14:46:29 2012 +0200

    target-i386: drop usage of prev_debug_excp_handler
    
    Chains of exception handlers are currently unused feature, drop it
    for now so as not to expose prev_debug_excp_handler at global
    scope when moving tcg initialization into target-i386/cpu.c
    
    Later we probably could re-invent better interface for this.
    
    Signed-off-by: Igor Mammedov <imammedo at redhat.com>

diff --git a/target-i386/helper.c b/target-i386/helper.c
index 2cc8097..b9384f6 100644
--- a/target-i386/helper.c
+++ b/target-i386/helper.c
@@ -941,8 +941,6 @@ int check_hw_breakpoints(CPUX86State *env, int force_dr6_update)
     return hit_enabled;
 }
 
-static CPUDebugExcpHandler *prev_debug_excp_handler;
-
 static void breakpoint_handler(CPUX86State *env)
 {
     CPUBreakpoint *bp;
@@ -965,8 +963,6 @@ static void breakpoint_handler(CPUX86State *env)
                 break;
             }
     }
-    if (prev_debug_excp_handler)
-        prev_debug_excp_handler(env);
 }
 
 typedef struct MCEInjectionParams {
@@ -1166,8 +1162,7 @@ X86CPU *cpu_x86_init(const char *cpu_model)
         inited = 1;
         optimize_flags_init();
 #ifndef CONFIG_USER_ONLY
-        prev_debug_excp_handler =
-            cpu_set_debug_excp_handler(breakpoint_handler);
+        cpu_set_debug_excp_handler(breakpoint_handler);
 #endif
     }
     if (cpu_x86_register(cpu, cpu_model) < 0) {
commit cfee0218499ded471883aa490284fb53f9be53eb
Author: Stefan Weil <sw at weilnetz.de>
Date:   Sun Jun 24 04:18:41 2012 +0000

    target-ppc: Fix 2nd parameter for tcg_gen_shri_tl
    
    This fixes a compiler error when QEMU was configured with --enable-debug.
    
    Signed-off-by: Stefan Weil <sw at weilnetz.de>
    Signed-off-by: Alexander Graf <agraf at suse.de>

diff --git a/target-ppc/translate_init.c b/target-ppc/translate_init.c
index e6580ff..5742229 100644
--- a/target-ppc/translate_init.c
+++ b/target-ppc/translate_init.c
@@ -4475,7 +4475,7 @@ static void spr_write_mas73(void *opaque, int sprn, int gprn)
     TCGv val = tcg_temp_new();
     tcg_gen_ext32u_tl(val, cpu_gpr[gprn]);
     gen_store_spr(SPR_BOOKE_MAS3, val);
-    tcg_gen_shri_tl(val, gprn, 32);
+    tcg_gen_shri_tl(val, cpu_gpr[gprn], 32);
     gen_store_spr(SPR_BOOKE_MAS7, val);
     tcg_temp_free(val);
 }
commit 975e5463584211e6dd6eff3c8317ff516b8e983e
Author: Stefan Weil <sw at weilnetz.de>
Date:   Sun Jun 24 04:04:17 2012 +0000

    target-ppc: Fix build with --enable-debug
    
    The order of the arguments was wrong (copy+paste error).
    
    Signed-off-by: Stefan Weil <sw at weilnetz.de>
    Signed-off-by: Alexander Graf <agraf at suse.de>

diff --git a/target-ppc/translate.c b/target-ppc/translate.c
index 73ee74b..91eb7a0 100644
--- a/target-ppc/translate.c
+++ b/target-ppc/translate.c
@@ -5794,7 +5794,7 @@ static void gen_mtdcrux(DisasContext *ctx)
 {
     /* NIP cannot be restored if the memory exception comes from an helper */
     gen_update_nip(ctx, ctx->nip - 4);
-    gen_helper_store_dcr(cpu_gpr[rA(ctx->opcode)], cpu_env,
+    gen_helper_store_dcr(cpu_env, cpu_gpr[rA(ctx->opcode)],
                          cpu_gpr[rS(ctx->opcode)]);
     /* Note: Rc update flag set leads to undefined state of Rc0 */
 }
commit 3c01ae0ea29915d165c384d0bd1cbafcf4364a4d
Author: Scott Wood <scottwood at freescale.com>
Date:   Mon Jun 18 21:31:36 2012 -0500

    tci: don't write zero for reloc in tci_out_label
    
    If tci_out_label is called in the context of tcg_gen_code_search_pc, we
    could be overwriting an already patched relocation with zero -- and not
    repatch it because the set_label is past search_pc, causing a QEMU crash
    when it tries to branch to a zero label.
    
    Not writing anything to the relocation area seems to be in line with what
    other backends do from the couple I looked at (x86, ppc).
    
    Signed-off-by: Scott Wood <scottwood at freescale.com>
    Signed-off-by: Blue Swirl <blauwirbel at gmail.com>

diff --git a/tcg/tci/tcg-target.c b/tcg/tci/tcg-target.c
index d0a368d..ef8580f 100644
--- a/tcg/tci/tcg-target.c
+++ b/tcg/tci/tcg-target.c
@@ -487,7 +487,7 @@ static void tci_out_label(TCGContext *s, TCGArg arg)
         assert(label->u.value);
     } else {
         tcg_out_reloc(s, s->code_ptr, sizeof(tcg_target_ulong), arg, 0);
-        tcg_out_i(s, 0);
+        s->code_ptr += sizeof(tcg_target_ulong);
     }
 }
 
commit a483bdae10840e69457b55dc01df5eef8fc5c6b0
Author: Stefan Weil <sw at weilnetz.de>
Date:   Thu Jun 21 22:18:39 2012 +0200

    make: Fix dependencies for fpu/*.c and tcg/*.c
    
    Commit dcff25f2cd8c11a9368cc2369aeb0319c32d9e26 removed too many *.d
    files. The directories fpu/ and tcg/ still don't use the recursive
    subdir rules.
    
    Signed-off-by: Stefan Weil <sw at weilnetz.de>
    Signed-off-by: Blue Swirl <blauwirbel at gmail.com>

diff --git a/Makefile.target b/Makefile.target
index 550d889..8f12b0f 100644
--- a/Makefile.target
+++ b/Makefile.target
@@ -216,4 +216,4 @@ GENERATED_HEADERS += config-target.h
 Makefile: $(GENERATED_HEADERS)
 
 # Include automatically generated dependency files
--include $(wildcard *.d)
+-include $(wildcard *.d fpu/*.d tcg/*.d)
commit 726f8cbf868ecd6b6e57fcf8854b9b0e35c9a064
Author: Stefan Weil <sw at weilnetz.de>
Date:   Sat Jun 23 20:41:10 2012 +0200

    qemu-log: Add GCC format attribute
    
    The new inline function qemu_log_vprintf should use this attribute.
    
    Signed-off-by: Stefan Weil <sw at weilnetz.de>
    Signed-off-by: Blue Swirl <blauwirbel at gmail.com>

diff --git a/qemu-log.h b/qemu-log.h
index 2ed19d1..4cdc7c7 100644
--- a/qemu-log.h
+++ b/qemu-log.h
@@ -51,7 +51,8 @@ void GCC_FMT_ATTR(1, 2) qemu_log(const char *fmt, ...);
 
 /* vfprintf-like logging function
  */
-static inline void qemu_log_vprintf(const char *fmt, va_list va)
+static inline void GCC_FMT_ATTR(1, 0)
+qemu_log_vprintf(const char *fmt, va_list va)
 {
     if (qemu_logfile) {
         vfprintf(qemu_logfile, fmt, va);
commit 4e469a438f40a53dc6217fa5c3d456861b00d80c
Merge: 959a255... 9609169...
Author: Blue Swirl <blauwirbel at gmail.com>
Date:   Sun Jun 24 10:48:56 2012 +0000

    Merge branch 'ppc-for-upstream' of git://repo.or.cz/qemu/agraf
    
    * 'ppc-for-upstream' of git://repo.or.cz/qemu/agraf: (72 commits)
      PPC: BookE206: Bump MAS2 to 64bit
      PPC: BookE: Support 32 and 64 bit wide MAS2
      PPC: Extract SPR dump generation into its own function
      PPC: Add e5500 CPU target
      PPC: BookE: Make ivpr selectable by CPU type
      PPC: BookE: Implement EPR SPR
      PPC: Add support for MSR_CM
      PPC: Add some booke SPR defines
      uImage: increase the gzip load size
      PPC: e500: allow users to set the /compatible property via -machine
      dt: make setprop argument static
      PPC: e500: Refactor serial dt generation
      dt: Add global option to set phandle start offset
      PPC: e500: Extend address/size of / to 64bit
      PPC: e500: Define addresses as always 64bit
      PPC: e500: Use new SOC dt format
      PPC: e500: Use new MPIC dt format
      Revert "dt: temporarily disable subtree creation failure check"
      PPC: e500: enable manual loading of dtb blob
      PPC: e500: dt: use target_phys_addr_t for ramsize
      ...

commit 959a255dfbe085a47e00fd21c57e87ad4c92719e
Merge: 8dacfcb... b2d06f9...
Author: Blue Swirl <blauwirbel at gmail.com>
Date:   Sun Jun 24 10:48:01 2012 +0000

    Merge branch 'target-arm.for-upstream' of git://git.linaro.org/people/pmaydell/qemu-arm
    
    * 'target-arm.for-upstream' of git://git.linaro.org/people/pmaydell/qemu-arm: (33 commits)
      target-arm: Remove ARM_CPUID_* macros
      target-arm: Remove remaining old cp15 infrastructure
      target-arm: Move block cache ops to new cp15 framework
      target-arm: Remove c0_cachetype CPUARMState field
      target-arm: Convert final ID registers
      target-arm: Convert MPIDR
      target-arm: Convert cp15 cache ID registers
      target-arm: Convert cp15 crn=0 crm={1,2} feature registers
      target-arm: Convert cp15 crn=1 registers
      target-arm: Convert cp15 crn=9 registers
      target-arm: Convert cp15 crn=6 registers
      target-arm: convert cp15 crn=7 registers
      target-arm: Convert cp15 VA-PA translation registers
      target-arm: Convert cp15 MMU TLB control
      target-arm: Convert cp15 crn=15 registers
      target-arm: Convert cp15 crn=10 registers
      target-arm: Convert cp15 crn=13 registers
      target-arm: Convert cp15 crn=2 registers
      target-arm: Convert MMU fault status cp15 registers
      target-arm: Convert cp15 c3 register
      ...

commit 8dacfcb407aa83664bd875123d2ec86612758c22
Merge: 99918ce... 2fb70f6...
Author: Blue Swirl <blauwirbel at gmail.com>
Date:   Sun Jun 24 10:45:55 2012 +0000

    Merge branch 's390-for-upstream' of git://repo.or.cz/qemu/agraf
    
    * 's390-for-upstream' of git://repo.or.cz/qemu/agraf:
      s390: stop target cpu on sigp initial reset
      s390: make kvm_stat work on s390
      kvm: Update kernel headers
      s390x: fix s390 virtio aliases

commit 99918cec1968b94c8ac3afe51b2a34e5c78c81b3
Merge: affe518... 5e87975...
Author: Blue Swirl <blauwirbel at gmail.com>
Date:   Sun Jun 24 07:09:30 2012 +0000

    Merge branch 'arm-devs.for-upstream' of git://git.linaro.org/people/pmaydell/qemu-arm
    
    * 'arm-devs.for-upstream' of git://git.linaro.org/people/pmaydell/qemu-arm:
      arm_boot: Conditionalised DTB command line update
      cadence_ttc: changed master clock frequency
      cadence_gem: avoid stack-writing buffer-overrun
      hw/a9mpcore: Fix compilation failure if physaddrs are 64 bit
      hw/omap.h: Drop broken MEM_VERBOSE tracing
      hw/armv7m_nvic: Make the NVIC a freestanding class
      hw/arm_gic: Move CPU interface memory region setup into arm_gic_init
      hw/arm_gic.c: Make NVIC interrupt numbering a runtime setting
      hw/arm_gic: Make CPU target registers RAZ/WI on uniprocessor
      hw/arm_gic: Add qdev property for GIC revision
      hw/armv7m_nvic: Use MemoryRegions for NVIC specific registers
      hw/arm_gic: Move NVIC specific reset to armv7m_nvic_reset
      hw/arm_gic: Remove the special casing of NCPU for the NVIC
      hw/arm_gic: Remove NVIC ifdefs from gic_state struct
      arm_boot: Fix typos in comment
      ARM: Exynos4210 IRQ: Introduce new IRQ gate functionality.

commit 960916988b9ec45bb10400d892351f360b4aac96
Author: Alexander Graf <agraf at suse.de>
Date:   Thu Jun 21 13:34:20 2012 +0200

    PPC: BookE206: Bump MAS2 to 64bit
    
    On 64bit capable systems, MAS2 can actually hold a 64bit virtual page
    address. So increase the mask for its EPN.
    
    Signed-off-by: Alexander Graf <agraf at suse.de>

diff --git a/target-ppc/cpu.h b/target-ppc/cpu.h
index 652a35a..ca2fc21 100644
--- a/target-ppc/cpu.h
+++ b/target-ppc/cpu.h
@@ -693,7 +693,7 @@ enum {
 #define MAS1_VALID         0x80000000
 
 #define MAS2_EPN_SHIFT     12
-#define MAS2_EPN_MASK      (0xfffff << MAS2_EPN_SHIFT)
+#define MAS2_EPN_MASK      (~0ULL << MAS2_EPN_SHIFT)
 
 #define MAS2_ACM_SHIFT     6
 #define MAS2_ACM           (1 << MAS2_ACM_SHIFT)
commit ba38ab8d429a326c2a9c30110df84f0cad441094
Author: Alexander Graf <agraf at suse.de>
Date:   Thu Jun 21 14:01:06 2012 +0200

    PPC: BookE: Support 32 and 64 bit wide MAS2
    
    The MAS registers on BookE are all 32 bit wide, except for MAS2, which
    can hold up to 64 bit on 64 bit capable CPUs. Reflect this in the SPR
    setting code, so that the guest can never write invalid values in them.
    
    Signed-off-by: Alexander Graf <agraf at suse.de>

diff --git a/target-ppc/translate_init.c b/target-ppc/translate_init.c
index 8ff47ae..e6580ff 100644
--- a/target-ppc/translate_init.c
+++ b/target-ppc/translate_init.c
@@ -86,6 +86,19 @@ static void spr_write_generic (void *opaque, int sprn, int gprn)
 }
 
 #if !defined(CONFIG_USER_ONLY)
+static void spr_write_generic32(void *opaque, int sprn, int gprn)
+{
+#ifdef TARGET_PPC64
+    TCGv t0 = tcg_temp_new();
+    tcg_gen_ext32u_tl(t0, cpu_gpr[gprn]);
+    gen_store_spr(sprn, t0);
+    tcg_temp_free(t0);
+    spr_store_dump_spr(sprn);
+#else
+    spr_write_generic(opaque, sprn, gprn);
+#endif
+}
+
 static void spr_write_clear (void *opaque, int sprn, int gprn)
 {
     TCGv t0 = tcg_temp_new();
@@ -1597,10 +1610,14 @@ static void gen_spr_BookE206(CPUPPCState *env, uint32_t mas_mask,
     /* TLB assist registers */
     /* XXX : not implemented */
     for (i = 0; i < 8; i++) {
+        void (*uea_write)(void *o, int sprn, int gprn) = &spr_write_generic32;
+        if (i == 2 && (mas_mask & (1 << i)) && (env->insns_flags & PPC_64B)) {
+            uea_write = &spr_write_generic;
+        }
         if (mas_mask & (1 << i)) {
             spr_register(env, mas_sprn[i], mas_names[i],
                          SPR_NOACCESS, SPR_NOACCESS,
-                         &spr_read_generic, &spr_write_generic,
+                         &spr_read_generic, uea_write,
                          0x00000000);
         }
     }
commit 91f477fd9c1a6ff73d57a4352d78bd49b5180e30
Author: Alexander Graf <agraf at suse.de>
Date:   Thu Jun 21 13:39:48 2012 +0200

    PPC: Extract SPR dump generation into its own function
    
    This patch moves the debug #ifdef'ed SPR trace generation into its
    own function, so we can call it from multiple places.
    
    Signed-off-by: Alexander Graf <agraf at suse.de>

diff --git a/target-ppc/translate_init.c b/target-ppc/translate_init.c
index d185aaa..8ff47ae 100644
--- a/target-ppc/translate_init.c
+++ b/target-ppc/translate_init.c
@@ -55,28 +55,34 @@ PPC_IRQ_INIT_FN(e500);
 /* Generic callbacks:
  * do nothing but store/retrieve spr value
  */
+static void spr_load_dump_spr(int sprn)
+{
+#ifdef PPC_DUMP_SPR_ACCESSES
+    TCGv_i32 t0 = tcg_const_i32(sprn);
+    gen_helper_load_dump_spr(t0);
+    tcg_temp_free_i32(t0);
+#endif
+}
+
 static void spr_read_generic (void *opaque, int gprn, int sprn)
 {
     gen_load_spr(cpu_gpr[gprn], sprn);
+    spr_load_dump_spr(sprn);
+}
+
+static void spr_store_dump_spr(int sprn)
+{
 #ifdef PPC_DUMP_SPR_ACCESSES
-    {
-        TCGv_i32 t0 = tcg_const_i32(sprn);
-        gen_helper_load_dump_spr(t0);
-        tcg_temp_free_i32(t0);
-    }
+    TCGv_i32 t0 = tcg_const_i32(sprn);
+    gen_helper_store_dump_spr(t0);
+    tcg_temp_free_i32(t0);
 #endif
 }
 
 static void spr_write_generic (void *opaque, int sprn, int gprn)
 {
     gen_store_spr(sprn, cpu_gpr[gprn]);
-#ifdef PPC_DUMP_SPR_ACCESSES
-    {
-        TCGv_i32 t0 = tcg_const_i32(sprn);
-        gen_helper_store_dump_spr(t0);
-        tcg_temp_free_i32(t0);
-    }
-#endif
+    spr_store_dump_spr(sprn);
 }
 
 #if !defined(CONFIG_USER_ONLY)
commit b81ccf8ae7f157e5b150243e27c2845c7c7b7256
Author: Alexander Graf <agraf at suse.de>
Date:   Wed Jun 20 21:55:55 2012 +0200

    PPC: Add e5500 CPU target
    
    This patch adds e5500's CPU initialization to the TCG CPU initialization
    code.
    
    Signed-off-by: Alexander Graf <agraf at suse.de>

diff --git a/target-ppc/translate_init.c b/target-ppc/translate_init.c
index 98695ab..d185aaa 100644
--- a/target-ppc/translate_init.c
+++ b/target-ppc/translate_init.c
@@ -4424,16 +4424,69 @@ static void init_proc_e300 (CPUPPCState *env)
 #define check_pow_e500mc       check_pow_none
 #define init_proc_e500mc       init_proc_e500mc
 
+/* e5500 core                                                                 */
+#define POWERPC_INSNS_e5500    (PPC_INSNS_BASE | PPC_ISEL |                    \
+                                PPC_WRTEE | PPC_RFDI | PPC_RFMCI |             \
+                                PPC_CACHE | PPC_CACHE_LOCK | PPC_CACHE_ICBI |  \
+                                PPC_CACHE_DCBZ | PPC_CACHE_DCBA |              \
+                                PPC_FLOAT | PPC_FLOAT_FRES |                   \
+                                PPC_FLOAT_FRSQRTE | PPC_FLOAT_FSEL |           \
+                                PPC_FLOAT_STFIWX | PPC_WAIT |                  \
+                                PPC_MEM_TLBSYNC | PPC_TLBIVAX | PPC_MEM_SYNC | \
+                                PPC_64B | PPC_POPCNTB | PPC_POPCNTWD)
+#define POWERPC_INSNS2_e5500   (PPC2_BOOKE206 | PPC2_PRCNTL)
+#define POWERPC_MSRM_e5500     (0x000000009402FB36ULL)
+#define POWERPC_MMU_e5500      (POWERPC_MMU_BOOKE206)
+#define POWERPC_EXCP_e5500     (POWERPC_EXCP_BOOKE)
+#define POWERPC_INPUT_e5500    (PPC_FLAGS_INPUT_BookE)
+/* Fixme: figure out the correct flag for e5500 */
+#define POWERPC_BFDM_e5500     (bfd_mach_ppc_e500)
+#define POWERPC_FLAG_e5500     (POWERPC_FLAG_CE | POWERPC_FLAG_DE | \
+                                POWERPC_FLAG_PMM | POWERPC_FLAG_BUS_CLK)
+#define check_pow_e5500        check_pow_none
+#define init_proc_e5500        init_proc_e5500
+
+#if !defined(CONFIG_USER_ONLY)
+static void spr_write_mas73(void *opaque, int sprn, int gprn)
+{
+    TCGv val = tcg_temp_new();
+    tcg_gen_ext32u_tl(val, cpu_gpr[gprn]);
+    gen_store_spr(SPR_BOOKE_MAS3, val);
+    tcg_gen_shri_tl(val, gprn, 32);
+    gen_store_spr(SPR_BOOKE_MAS7, val);
+    tcg_temp_free(val);
+}
+
+static void spr_read_mas73(void *opaque, int gprn, int sprn)
+{
+    TCGv mas7 = tcg_temp_new();
+    TCGv mas3 = tcg_temp_new();
+    gen_load_spr(mas7, SPR_BOOKE_MAS7);
+    tcg_gen_shli_tl(mas7, mas7, 32);
+    gen_load_spr(mas3, SPR_BOOKE_MAS3);
+    tcg_gen_or_tl(cpu_gpr[gprn], mas3, mas7);
+    tcg_temp_free(mas3);
+    tcg_temp_free(mas7);
+}
+
+static void spr_load_epr(void *opaque, int gprn, int sprn)
+{
+    gen_helper_load_epr(cpu_gpr[gprn], cpu_env);
+}
+
+#endif
+
 enum fsl_e500_version {
     fsl_e500v1,
     fsl_e500v2,
     fsl_e500mc,
+    fsl_e5500,
 };
 
 static void init_proc_e500 (CPUPPCState *env, int version)
 {
     uint32_t tlbncfg[2];
-    uint64_t ivor_mask = 0x0000000F0000FFFFULL;
+    uint64_t ivor_mask;
     uint64_t ivpr_mask = 0xFFFF0000ULL;
     uint32_t l1cfg0 = 0x3800  /* 8 ways */
                     | 0x0020; /* 32 kb */
@@ -4448,8 +4501,16 @@ static void init_proc_e500 (CPUPPCState *env, int version)
      *     complain when accessing them.
      * gen_spr_BookE(env, 0x0000000F0000FD7FULL);
      */
-    if (version == fsl_e500mc) {
-        ivor_mask = 0x000003FE0000FFFFULL;
+    switch (version) {
+        case fsl_e500v1:
+        case fsl_e500v2:
+        default:
+            ivor_mask = 0x0000000F0000FFFFULL;
+            break;
+        case fsl_e500mc:
+        case fsl_e5500:
+            ivor_mask = 0x000003FE0000FFFFULL;
+            break;
     }
     gen_spr_BookE(env, ivor_mask);
     /* Processor identification */
@@ -4477,6 +4538,7 @@ static void init_proc_e500 (CPUPPCState *env, int version)
         tlbncfg[1] = gen_tlbncfg(16, 1, 12, TLBnCFG_AVAIL | TLBnCFG_IPROT, 16);
         break;
     case fsl_e500mc:
+    case fsl_e5500:
         tlbncfg[0] = gen_tlbncfg(4, 1, 1, 0, 512);
         tlbncfg[1] = gen_tlbncfg(64, 1, 12, TLBnCFG_AVAIL | TLBnCFG_IPROT, 64);
         break;
@@ -4492,6 +4554,7 @@ static void init_proc_e500 (CPUPPCState *env, int version)
         env->icache_line_size = 32;
         break;
     case fsl_e500mc:
+    case fsl_e5500:
         env->dcache_line_size = 64;
         env->icache_line_size = 64;
         l1cfg0 |= 0x1000000; /* 64 byte cache block size */
@@ -4567,6 +4630,22 @@ static void init_proc_e500 (CPUPPCState *env, int version)
                  SPR_NOACCESS, SPR_NOACCESS,
                  &spr_read_generic, &spr_write_booke206_mmucsr0,
                  0x00000000);
+    spr_register(env, SPR_BOOKE_EPR, "EPR",
+                 SPR_NOACCESS, SPR_NOACCESS,
+                 &spr_load_epr, SPR_NOACCESS,
+                 0x00000000);
+    /* XXX better abstract into Emb.xxx features */
+    if (version == fsl_e5500) {
+        spr_register(env, SPR_BOOKE_EPCR, "EPCR",
+                     SPR_NOACCESS, SPR_NOACCESS,
+                     &spr_read_generic, &spr_write_generic,
+                     0x00000000);
+        spr_register(env, SPR_BOOKE_MAS7_MAS3, "MAS7_MAS3",
+                     SPR_NOACCESS, SPR_NOACCESS,
+                     &spr_read_mas73, &spr_write_mas73,
+                     0x00000000);
+        ivpr_mask = (target_ulong)~0xFFFFULL;
+    }
 
 #if !defined(CONFIG_USER_ONLY)
     env->nb_tlb = 0;
@@ -4596,6 +4675,13 @@ static void init_proc_e500mc(CPUPPCState *env)
     init_proc_e500(env, fsl_e500mc);
 }
 
+#ifdef TARGET_PPC64
+static void init_proc_e5500(CPUPPCState *env)
+{
+    init_proc_e500(env, fsl_e5500);
+}
+#endif
+
 /* Non-embedded PowerPC                                                      */
 
 /* POWER : same as 601, without mfmsr, mfsr                                  */
@@ -7134,6 +7220,7 @@ enum {
     CPU_POWERPC_e500v2_v22         = 0x80210022,
     CPU_POWERPC_e500v2_v30         = 0x80210030,
     CPU_POWERPC_e500mc             = 0x80230020,
+    CPU_POWERPC_e5500              = 0x80240020,
     /* MPC85xx microcontrollers */
 #define CPU_POWERPC_MPC8533          CPU_POWERPC_MPC8533_v11
 #define CPU_POWERPC_MPC8533_v10      CPU_POWERPC_e500v2_v21
@@ -8528,6 +8615,9 @@ static const ppc_def_t ppc_defs[] = {
     /* PowerPC e500v2 v3.0 core                                              */
     POWERPC_DEF("e500v2_v30",    CPU_POWERPC_e500v2_v30,             e500v2),
     POWERPC_DEF("e500mc",        CPU_POWERPC_e500mc,                 e500mc),
+#ifdef TARGET_PPC64
+    POWERPC_DEF("e5500",         CPU_POWERPC_e5500,                  e5500),
+#endif
     /* PowerPC e500 microcontrollers                                         */
     /* MPC8533                                                               */
     POWERPC_DEF_SVR("MPC8533",
commit e9cd84b90b7c6df64044b1e57730b8a9be5de26b
Author: Alexander Graf <agraf at suse.de>
Date:   Thu Jun 21 15:17:59 2012 +0200

    PPC: BookE: Make ivpr selectable by CPU type
    
    IVPR can either hold 32 or 64 bit addresses, depending on the CPU type. Let
    the CPU initialization function pass in its mask itself, so we can easily
    extend it.
    
    Signed-off-by: Alexander Graf <agraf at suse.de>

diff --git a/target-ppc/translate_init.c b/target-ppc/translate_init.c
index 57027a2..98695ab 100644
--- a/target-ppc/translate_init.c
+++ b/target-ppc/translate_init.c
@@ -2804,7 +2804,7 @@ static void init_excp_G2 (CPUPPCState *env)
 #endif
 }
 
-static void init_excp_e200 (CPUPPCState *env)
+static void init_excp_e200(CPUPPCState *env, target_ulong ivpr_mask)
 {
 #if !defined(CONFIG_USER_ONLY)
     env->excp_vectors[POWERPC_EXCP_RESET]    = 0x00000FFC;
@@ -2829,7 +2829,7 @@ static void init_excp_e200 (CPUPPCState *env)
     env->excp_vectors[POWERPC_EXCP_EFPRI]    = 0x00000000;
     env->hreset_excp_prefix = 0x00000000UL;
     env->ivor_mask = 0x0000FFF7UL;
-    env->ivpr_mask = 0xFFFF0000UL;
+    env->ivpr_mask = ivpr_mask;
     /* Hardware reset vector */
     env->hreset_vector = 0xFFFFFFFCUL;
 #endif
@@ -4307,7 +4307,7 @@ static void init_proc_e200 (CPUPPCState *env)
     env->id_tlbs = 0;
     env->tlb_type = TLB_EMB;
 #endif
-    init_excp_e200(env);
+    init_excp_e200(env, 0xFFFF0000UL);
     env->dcache_line_size = 32;
     env->icache_line_size = 32;
     /* XXX: TODO: allocate internal IRQ controller */
@@ -4434,6 +4434,7 @@ static void init_proc_e500 (CPUPPCState *env, int version)
 {
     uint32_t tlbncfg[2];
     uint64_t ivor_mask = 0x0000000F0000FFFFULL;
+    uint64_t ivpr_mask = 0xFFFF0000ULL;
     uint32_t l1cfg0 = 0x3800  /* 8 ways */
                     | 0x0020; /* 32 kb */
 #if !defined(CONFIG_USER_ONLY)
@@ -4575,7 +4576,7 @@ static void init_proc_e500 (CPUPPCState *env, int version)
     }
 #endif
 
-    init_excp_e200(env);
+    init_excp_e200(env, ivpr_mask);
     /* Allocate hardware IRQ controller */
     ppce500_irq_init(env);
 }
commit 2a7a47fc6c19703a849a34243701a09052cb1bc6
Author: Alexander Graf <agraf at suse.de>
Date:   Wed Jun 20 21:27:02 2012 +0200

    PPC: BookE: Implement EPR SPR
    
    On the e500 series, accessing SPR_EPR magically turns into an access at
    that CPU's IACK register on the MPIC. Implement that logic to get kernels
    that make use of that feature work.
    
    Signed-off-by: Alexander Graf <agraf at suse.de>

diff --git a/hw/ppce500_mpc8544ds.c b/hw/ppce500_mpc8544ds.c
index d38ad99..8b9fd83 100644
--- a/hw/ppce500_mpc8544ds.c
+++ b/hw/ppce500_mpc8544ds.c
@@ -469,6 +469,7 @@ static void mpc8544ds_init(ram_addr_t ram_size,
         irqs[i][OPENPIC_OUTPUT_INT] = input[PPCE500_INPUT_INT];
         irqs[i][OPENPIC_OUTPUT_CINT] = input[PPCE500_INPUT_CINT];
         env->spr[SPR_BOOKE_PIR] = env->cpu_index = i;
+        env->mpic_cpu_base = MPC8544_MPIC_REGS_BASE + 0x20000;
 
         ppc_booke_timers_init(env, 400000000, PPC_TIMER_E500);
 
diff --git a/target-ppc/Makefile.objs b/target-ppc/Makefile.objs
index 6c11ef8..237a0ed 100644
--- a/target-ppc/Makefile.objs
+++ b/target-ppc/Makefile.objs
@@ -9,3 +9,4 @@ obj-y += mmu_helper.o
 obj-y += timebase_helper.o
 obj-y += misc_helper.o
 obj-y += mem_helper.o
+obj-y += mpic_helper.o
diff --git a/target-ppc/cpu.h b/target-ppc/cpu.h
index 7a77fff..652a35a 100644
--- a/target-ppc/cpu.h
+++ b/target-ppc/cpu.h
@@ -1066,6 +1066,7 @@ struct CPUPPCState {
     target_ulong ivor_mask;
     target_ulong ivpr_mask;
     target_ulong hreset_vector;
+    target_phys_addr_t mpic_cpu_base;
 #endif
 
     /* Those resources are used only during code translation */
diff --git a/target-ppc/helper.h b/target-ppc/helper.h
index ddab97b..fd04c06 100644
--- a/target-ppc/helper.h
+++ b/target-ppc/helper.h
@@ -405,6 +405,7 @@ DEF_HELPER_2(store_40x_dbcr0, void, env, tl)
 DEF_HELPER_2(store_40x_sler, void, env, tl)
 DEF_HELPER_2(store_booke_tcr, void, env, tl)
 DEF_HELPER_2(store_booke_tsr, void, env, tl)
+DEF_HELPER_1(load_epr, tl, env)
 DEF_HELPER_3(store_ibatl, void, env, i32, tl)
 DEF_HELPER_3(store_ibatu, void, env, i32, tl)
 DEF_HELPER_3(store_dbatl, void, env, i32, tl)
diff --git a/target-ppc/mpic_helper.c b/target-ppc/mpic_helper.c
new file mode 100644
index 0000000..2c6a4d3
--- /dev/null
+++ b/target-ppc/mpic_helper.c
@@ -0,0 +1,35 @@
+/*
+ *  PowerPC emulation helpers for QEMU.
+ *
+ *  Copyright (c) 2003-2007 Jocelyn Mayer
+ *
+ * This library is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Lesser General Public
+ * License as published by the Free Software Foundation; either
+ * version 2 of the License, or (at your option) any later version.
+ *
+ * This library is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
+ * Lesser General Public License for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public
+ * License along with this library; if not, see <http://www.gnu.org/licenses/>.
+ */
+#include "cpu.h"
+#include "helper.h"
+
+/*****************************************************************************/
+/* SPR accesses */
+
+#if !defined(CONFIG_USER_ONLY)
+/*
+ * This is an ugly helper for EPR, which is basically the same as accessing
+ * the IACK (PIAC) register on the MPIC. Because we model the MPIC as a device
+ * that can only talk to the CPU through MMIO, let's access it that way!
+ */
+target_ulong helper_load_epr(CPUPPCState *env)
+{
+    return ldl_phys(env->mpic_cpu_base + 0xA0);
+}
+#endif
commit e42a61f185f859246c14445b6e98e195eb3b977b
Author: Alexander Graf <agraf at suse.de>
Date:   Wed Jun 20 21:20:29 2012 +0200

    PPC: Add support for MSR_CM
    
    The BookE variant of MSR_SF is MSR_CM. Implement everything it takes in TCG to
    support running 64bit code with MSR_CM set.
    
    Signed-off-by: Alexander Graf <agraf at suse.de>

diff --git a/target-ppc/cpu.h b/target-ppc/cpu.h
index 12200ab..7a77fff 100644
--- a/target-ppc/cpu.h
+++ b/target-ppc/cpu.h
@@ -2212,6 +2212,15 @@ static inline uint32_t booke206_tlbnps(CPUPPCState *env, const int tlbn)
 
 #endif
 
+static inline bool msr_is_64bit(CPUPPCState *env, target_ulong msr)
+{
+    if (env->mmu_model == POWERPC_MMU_BOOKE206) {
+        return msr & (1ULL << MSR_CM);
+    }
+
+    return msr & (1ULL << MSR_SF);
+}
+
 extern void (*cpu_ppc_hypercall)(CPUPPCState *);
 
 static inline bool cpu_has_work(CPUPPCState *env)
diff --git a/target-ppc/excp_helper.c b/target-ppc/excp_helper.c
index c7762b9..1a593f6 100644
--- a/target-ppc/excp_helper.c
+++ b/target-ppc/excp_helper.c
@@ -608,10 +608,11 @@ static inline void powerpc_excp(CPUPPCState *env, int excp_model, int excp)
     vector |= env->excp_prefix;
 #if defined(TARGET_PPC64)
     if (excp_model == POWERPC_EXCP_BOOKE) {
-        if (!msr_icm) {
-            vector = (uint32_t)vector;
-        } else {
+        if (env->spr[SPR_BOOKE_EPCR] & EPCR_ICM) {
+            /* Cat.64-bit: EPCR.ICM is copied to MSR.CM */
             new_msr |= (target_ulong)1 << MSR_CM;
+        } else {
+            vector = (uint32_t)vector;
         }
     } else {
         if (!msr_isf && !(env->mmu_model & POWERPC_MMU_64)) {
@@ -803,7 +804,7 @@ static inline void do_rfi(CPUPPCState *env, target_ulong nip, target_ulong msr,
                           target_ulong msrm, int keep_msrh)
 {
 #if defined(TARGET_PPC64)
-    if (msr & (1ULL << MSR_SF)) {
+    if (msr_is_64bit(env, msr)) {
         nip = (uint64_t)nip;
         msr &= (uint64_t)msrm;
     } else {
diff --git a/target-ppc/mem_helper.c b/target-ppc/mem_helper.c
index ebcd7b2..5b5f1bd 100644
--- a/target-ppc/mem_helper.c
+++ b/target-ppc/mem_helper.c
@@ -35,7 +35,7 @@ static inline target_ulong addr_add(CPUPPCState *env, target_ulong addr,
                                     target_long arg)
 {
 #if defined(TARGET_PPC64)
-    if (!msr_sf) {
+    if (!msr_is_64bit(env, env->msr)) {
         return (uint32_t)(addr + arg);
     } else
 #endif
diff --git a/target-ppc/translate.c b/target-ppc/translate.c
index 9103fd5..73ee74b 100644
--- a/target-ppc/translate.c
+++ b/target-ppc/translate.c
@@ -9626,7 +9626,7 @@ static inline void gen_intermediate_code_internal(CPUPPCState *env,
     ctx.access_type = -1;
     ctx.le_mode = env->hflags & (1 << MSR_LE) ? 1 : 0;
 #if defined(TARGET_PPC64)
-    ctx.sf_mode = msr_sf;
+    ctx.sf_mode = msr_is_64bit(env, env->msr);
     ctx.has_cfar = !!(env->flags & POWERPC_FLAG_CFAR);
 #endif
     ctx.fpu_enabled = msr_fp;
commit 84755ed51e6266b115322834933ce404a2fbf3f9
Author: Alexander Graf <agraf at suse.de>
Date:   Wed Jun 20 21:19:09 2012 +0200

    PPC: Add some booke SPR defines
    
    The number of SPRs avaiable in different PowerPC chip is still increasing. Add
    definitions for the MAS7_MAS3 SPR and all currently known bits in EPCR.
    
    Signed-off-by: Alexander Graf <agraf at suse.de>

diff --git a/target-ppc/cpu.h b/target-ppc/cpu.h
index 67e699c..12200ab 100644
--- a/target-ppc/cpu.h
+++ b/target-ppc/cpu.h
@@ -1395,6 +1395,7 @@ static inline void cpu_clone_regs(CPUPPCState *env, target_ulong newsp)
 #define SPR_BOOKE_TLB1PS      (0x159)
 #define SPR_BOOKE_TLB2PS      (0x15A)
 #define SPR_BOOKE_TLB3PS      (0x15B)
+#define SPR_BOOKE_MAS7_MAS3   (0x174)
 #define SPR_BOOKE_IVOR0       (0x190)
 #define SPR_BOOKE_IVOR1       (0x191)
 #define SPR_BOOKE_IVOR2       (0x192)
@@ -1762,6 +1763,27 @@ static inline void cpu_clone_regs(CPUPPCState *env, target_ulong newsp)
 #define SPR_604_HID15         (0x3FF)
 #define SPR_E500_SVR          (0x3FF)
 
+/* Disable MAS Interrupt Updates for Hypervisor */
+#define EPCR_DMIUH            (1 << 22)
+/* Disable Guest TLB Management Instructions */
+#define EPCR_DGTMI            (1 << 23)
+/* Guest Interrupt Computation Mode */
+#define EPCR_GICM             (1 << 24)
+/* Interrupt Computation Mode */
+#define EPCR_ICM              (1 << 25)
+/* Disable Embedded Hypervisor Debug */
+#define EPCR_DUVD             (1 << 26)
+/* Instruction Storage Interrupt Directed to Guest State */
+#define EPCR_ISIGS            (1 << 27)
+/* Data Storage Interrupt Directed to Guest State */
+#define EPCR_DSIGS            (1 << 28)
+/* Instruction TLB Error Interrupt Directed to Guest State */
+#define EPCR_ITLBGS           (1 << 29)
+/* Data TLB Error Interrupt Directed to Guest State */
+#define EPCR_DTLBGS           (1 << 30)
+/* External Input Interrupt Directed to Guest State */
+#define EPCR_EXTGS            (1 << 31)
+
 /*****************************************************************************/
 /* PowerPC Instructions types definitions                                    */
 enum {
commit 5025d5421d3c6e705669f365192a7edf17b1aad8
Author: Alexander Graf <agraf at suse.de>
Date:   Wed Jun 20 20:58:27 2012 +0200

    uImage: increase the gzip load size
    
    Recent u-boot has different defines for its gzip extract buffer, but the
    common ground seems to be 64MB. So let's bump it up to that, enabling me
    to load my test image again ;).
    
    Signed-off-by: Alexander Graf <agraf at suse.de>

diff --git a/hw/loader.c b/hw/loader.c
index 7d64113..33acc2f 100644
--- a/hw/loader.c
+++ b/hw/loader.c
@@ -377,9 +377,9 @@ static void zfree(void *x, void *addr)
 
 #define DEFLATED	8
 
-/* This is the maximum in uboot, so if a uImage overflows this, it would
+/* This is the usual maximum in uboot, so if a uImage overflows this, it would
  * overflow on real hardware too. */
-#define UBOOT_MAX_GUNZIP_BYTES 0x800000
+#define UBOOT_MAX_GUNZIP_BYTES (64 << 20)
 
 static ssize_t gunzip(void *dst, size_t dstlen, uint8_t *src,
                       size_t srclen)
commit caedc737d27dd697641cb75ef6c5c27562c8044a
Author: Alexander Graf <agraf at suse.de>
Date:   Wed Jun 20 20:46:22 2012 +0200

    PPC: e500: allow users to set the /compatible property via -machine
    
    Device trees usually have a node /compatible, which indicate which machine
    type we're looking at. For quick prototyping, it can be very useful to change
    the contents of that node via the command line.
    
    Thus, introduce a new option to -machine called dt_compatible, which when
    set changes the /compatible contents to its value.
    
    Signed-off-by: Alexander Graf <agraf at suse.de>

diff --git a/hw/ppce500_mpc8544ds.c b/hw/ppce500_mpc8544ds.c
index f6da25b..d38ad99 100644
--- a/hw/ppce500_mpc8544ds.c
+++ b/hw/ppce500_mpc8544ds.c
@@ -119,7 +119,8 @@ static int mpc8544_load_device_tree(CPUPPCState *env,
     uint32_t clock_freq = 400000000;
     uint32_t tb_freq = 400000000;
     int i;
-    char compatible[] = "MPC8544DS\0MPC85xxDS";
+    const char *compatible = "MPC8544DS\0MPC85xxDS";
+    int compatible_len = sizeof("MPC8544DS\0MPC85xxDS");
     char compatible_sb[] = "fsl,mpc8544-immr\0simple-bus";
     char model[] = "MPC8544DS";
     char soc[128];
@@ -144,8 +145,14 @@ static int mpc8544_load_device_tree(CPUPPCState *env,
 
     machine_opts = qemu_opts_find(qemu_find_opts("machine"), 0);
     if (machine_opts) {
+        const char *tmp;
         dumpdtb = qemu_opt_get(machine_opts, "dumpdtb");
         dtb_file = qemu_opt_get(machine_opts, "dtb");
+        tmp = qemu_opt_get(machine_opts, "dt_compatible");
+        if (tmp) {
+            compatible = tmp;
+            compatible_len = strlen(compatible) + 1;
+        }
     }
 
     if (dtb_file) {
@@ -169,8 +176,7 @@ static int mpc8544_load_device_tree(CPUPPCState *env,
 
     /* Manipulate device tree in memory. */
     qemu_devtree_setprop_string(fdt, "/", "model", model);
-    qemu_devtree_setprop(fdt, "/", "compatible", compatible,
-                         sizeof(compatible));
+    qemu_devtree_setprop(fdt, "/", "compatible", compatible, compatible_len);
     qemu_devtree_setprop_cell(fdt, "/", "#address-cells", 2);
     qemu_devtree_setprop_cell(fdt, "/", "#size-cells", 2);
 
diff --git a/qemu-config.c b/qemu-config.c
index 2cd2726..5c3296b 100644
--- a/qemu-config.c
+++ b/qemu-config.c
@@ -591,6 +591,10 @@ static QemuOptsList qemu_machine_opts = {
             .name = "phandle_start",
             .type = QEMU_OPT_STRING,
             .help = "The first phandle ID we may generate dynamically",
+        }, {
+            .name = "dt_compatible",
+            .type = QEMU_OPT_STRING,
+            .help = "Overrides the \"compatible\" property of the dt root node",
         },
         { /* End of list */ }
     },
commit 45e9dfb2fdd6ab7b60f823a1ee5ed2f2722beaf6
Author: Alexander Graf <agraf at suse.de>
Date:   Wed Jun 20 20:39:59 2012 +0200

    dt: make setprop argument static
    
    Whatever we pass in to qemu_devtree_setprop to put into the device tree
    will not get modified by that function, so it can easily be declared const.
    
    Signed-off-by: Alexander Graf <agraf at suse.de>
    Reviewed-by: Peter Crosthwaite <peter.crosthwaite at petalogix.com>

diff --git a/device_tree.c b/device_tree.c
index acae53e..b366fdd 100644
--- a/device_tree.c
+++ b/device_tree.c
@@ -127,7 +127,7 @@ static int findnode_nofail(void *fdt, const char *node_path)
 }
 
 int qemu_devtree_setprop(void *fdt, const char *node_path,
-                         const char *property, void *val_array, int size)
+                         const char *property, const void *val_array, int size)
 {
     int r;
 
diff --git a/device_tree.h b/device_tree.h
index 4898d95..2244270 100644
--- a/device_tree.h
+++ b/device_tree.h
@@ -18,7 +18,7 @@ void *create_device_tree(int *sizep);
 void *load_device_tree(const char *filename_path, int *sizep);
 
 int qemu_devtree_setprop(void *fdt, const char *node_path,
-                         const char *property, void *val_array, int size);
+                         const char *property, const void *val_array, int size);
 int qemu_devtree_setprop_cell(void *fdt, const char *node_path,
                               const char *property, uint32_t val);
 int qemu_devtree_setprop_u64(void *fdt, const char *node_path,
commit a053a7cea61da679fe87ce491701f3874ae42371
Author: Alexander Graf <agraf at suse.de>
Date:   Wed Jun 6 01:19:40 2012 +0200

    PPC: e500: Refactor serial dt generation
    
    When generating serial port device tree nodes, we duplicate quite a bit
    of code, because there are 2 of them in the mpc8544ds board we emulate.
    
    Shove the generating code into a function, so we duplicate less code.
    
    Signed-off-by: Alexander Graf <agraf at suse.de>

diff --git a/hw/ppce500_mpc8544ds.c b/hw/ppce500_mpc8544ds.c
index bf48bc7..f6da25b 100644
--- a/hw/ppce500_mpc8544ds.c
+++ b/hw/ppce500_mpc8544ds.c
@@ -82,6 +82,28 @@ static void pci_map_create(void *fdt, uint32_t *pci_map, uint32_t mpic)
     }
 }
 
+static void dt_serial_create(void *fdt, unsigned long long offset,
+                             const char *soc, const char *mpic,
+                             const char *alias, int idx, bool defcon)
+{
+    char ser[128];
+
+    snprintf(ser, sizeof(ser), "%s/serial@%llx", soc, offset);
+    qemu_devtree_add_subnode(fdt, ser);
+    qemu_devtree_setprop_string(fdt, ser, "device_type", "serial");
+    qemu_devtree_setprop_string(fdt, ser, "compatible", "ns16550");
+    qemu_devtree_setprop_cells(fdt, ser, "reg", offset, 0x100);
+    qemu_devtree_setprop_cell(fdt, ser, "cell-index", idx);
+    qemu_devtree_setprop_cell(fdt, ser, "clock-frequency", 0);
+    qemu_devtree_setprop_cells(fdt, ser, "interrupts", 42, 2, 0, 0);
+    qemu_devtree_setprop_phandle(fdt, ser, "interrupt-parent", mpic);
+    qemu_devtree_setprop_string(fdt, "/aliases", alias, ser);
+
+    if (defcon) {
+        qemu_devtree_setprop_string(fdt, "/chosen", "linux,stdout-path", ser);
+    }
+}
+
 static int mpc8544_load_device_tree(CPUPPCState *env,
                                     target_phys_addr_t addr,
                                     target_phys_addr_t ramsize,
@@ -101,8 +123,6 @@ static int mpc8544_load_device_tree(CPUPPCState *env,
     char compatible_sb[] = "fsl,mpc8544-immr\0simple-bus";
     char model[] = "MPC8544DS";
     char soc[128];
-    char ser0[128];
-    char ser1[128];
     char mpic[128];
     uint32_t mpic_ph;
     char gutil[128];
@@ -274,32 +294,10 @@ static int mpc8544_load_device_tree(CPUPPCState *env,
      * device it finds in the dt as serial output device. And we generate
      * devices in reverse order to the dt.
      */
-    snprintf(ser1, sizeof(ser1), "%s/serial@%llx", soc,
-             MPC8544_SERIAL1_REGS_BASE - MPC8544_CCSRBAR_BASE);
-    qemu_devtree_add_subnode(fdt, ser1);
-    qemu_devtree_setprop_string(fdt, ser1, "device_type", "serial");
-    qemu_devtree_setprop_string(fdt, ser1, "compatible", "ns16550");
-    qemu_devtree_setprop_cells(fdt, ser1, "reg", MPC8544_SERIAL1_REGS_BASE -
-                               MPC8544_CCSRBAR_BASE, 0x100);
-    qemu_devtree_setprop_cell(fdt, ser1, "cell-index", 1);
-    qemu_devtree_setprop_cell(fdt, ser1, "clock-frequency", 0);
-    qemu_devtree_setprop_cells(fdt, ser1, "interrupts", 42, 2, 0, 0);
-    qemu_devtree_setprop_phandle(fdt, ser1, "interrupt-parent", mpic);
-    qemu_devtree_setprop_string(fdt, "/aliases", "serial1", ser1);
-
-    snprintf(ser0, sizeof(ser0), "%s/serial@%llx", soc,
-             MPC8544_SERIAL0_REGS_BASE - MPC8544_CCSRBAR_BASE);
-    qemu_devtree_add_subnode(fdt, ser0);
-    qemu_devtree_setprop_string(fdt, ser0, "device_type", "serial");
-    qemu_devtree_setprop_string(fdt, ser0, "compatible", "ns16550");
-    qemu_devtree_setprop_cells(fdt, ser0, "reg", MPC8544_SERIAL0_REGS_BASE -
-                               MPC8544_CCSRBAR_BASE, 0x100);
-    qemu_devtree_setprop_cell(fdt, ser0, "cell-index", 0);
-    qemu_devtree_setprop_cell(fdt, ser0, "clock-frequency", 0);
-    qemu_devtree_setprop_cells(fdt, ser0, "interrupts", 42, 2, 0, 0);
-    qemu_devtree_setprop_phandle(fdt, ser0, "interrupt-parent", mpic);
-    qemu_devtree_setprop_string(fdt, "/aliases", "serial0", ser0);
-    qemu_devtree_setprop_string(fdt, "/chosen", "linux,stdout-path", ser0);
+    dt_serial_create(fdt, MPC8544_SERIAL1_REGS_BASE - MPC8544_CCSRBAR_BASE,
+                     soc, mpic, "serial1", 1, false);
+    dt_serial_create(fdt, MPC8544_SERIAL0_REGS_BASE - MPC8544_CCSRBAR_BASE,
+                     soc, mpic, "serial0", 0, true);
 
     snprintf(gutil, sizeof(gutil), "%s/global-utilities@%llx", soc,
              MPC8544_UTIL_BASE - MPC8544_CCSRBAR_BASE);
commit 4b1b1c896fb38d435f3d350c44b1bdc8b56600a4
Author: Alexander Graf <agraf at suse.de>
Date:   Wed Jun 6 01:01:23 2012 +0200

    dt: Add global option to set phandle start offset
    
    If anyone outside of QEMU wants to mess with a QEMU generated device tree,
    he needs to know which range phandles are valid in. So let's expose a
    machine option that an external program can use to set the start allocate
    id for phandles in QEMU.
    
    Signed-off-by: Alexander Graf <agraf at suse.de>

diff --git a/device_tree.c b/device_tree.c
index cc83f0f..acae53e 100644
--- a/device_tree.c
+++ b/device_tree.c
@@ -22,6 +22,8 @@
 #include "qemu-common.h"
 #include "device_tree.h"
 #include "hw/loader.h"
+#include "qemu-option.h"
+#include "qemu-config.h"
 
 #include <libfdt.h>
 
@@ -200,7 +202,31 @@ int qemu_devtree_setprop_phandle(void *fdt, const char *node_path,
 
 uint32_t qemu_devtree_alloc_phandle(void *fdt)
 {
-    static int phandle = 0x8000;
+    static int phandle = 0x0;
+
+    /*
+     * We need to find out if the user gave us special instruction at
+     * which phandle id to start allocting phandles.
+     */
+    if (!phandle) {
+        QemuOpts *machine_opts;
+        machine_opts = qemu_opts_find(qemu_find_opts("machine"), 0);
+        if (machine_opts) {
+            const char *phandle_start;
+            phandle_start = qemu_opt_get(machine_opts, "phandle_start");
+            if (phandle_start) {
+                phandle = strtoul(phandle_start, NULL, 0);
+            }
+        }
+    }
+
+    if (!phandle) {
+        /*
+         * None or invalid phandle given on the command line, so fall back to
+         * default starting point.
+         */
+        phandle = 0x8000;
+    }
 
     return phandle++;
 }
diff --git a/qemu-config.c b/qemu-config.c
index 5bbebaf..2cd2726 100644
--- a/qemu-config.c
+++ b/qemu-config.c
@@ -587,6 +587,10 @@ static QemuOptsList qemu_machine_opts = {
             .name = "dumpdtb",
             .type = QEMU_OPT_STRING,
             .help = "Dump current dtb to a file and quit",
+        }, {
+            .name = "phandle_start",
+            .type = QEMU_OPT_STRING,
+            .help = "The first phandle ID we may generate dynamically",
         },
         { /* End of list */ }
     },
commit 3627757e32e2c9fcee84e218746639aa2bfb1723
Author: Alexander Graf <agraf at suse.de>
Date:   Wed Jun 6 00:25:06 2012 +0200

    PPC: e500: Extend address/size of / to 64bit
    
    We want to be able to support >= 4GB of RAM. To do so, we need to be able
    to tell the guest OS how much RAM it has.
    
    However, that information today is capped to 32bit. So let's extend the
    offset and size fields to 64bit, so we can fit in big addresses and even
    one day - if we wish to do so - map devices above 32bit.
    
    Signed-off-by: Alexander Graf <agraf at suse.de>

diff --git a/hw/ppce500_mpc8544ds.c b/hw/ppce500_mpc8544ds.c
index c6a09bb..bf48bc7 100644
--- a/hw/ppce500_mpc8544ds.c
+++ b/hw/ppce500_mpc8544ds.c
@@ -90,7 +90,7 @@ static int mpc8544_load_device_tree(CPUPPCState *env,
                                     const char *kernel_cmdline)
 {
     int ret = -1;
-    uint32_t mem_reg_property[] = {0, cpu_to_be32(ramsize)};
+    uint64_t mem_reg_property[] = { 0, cpu_to_be64(ramsize) };
     int fdt_size;
     void *fdt;
     uint8_t hypercall[16];
@@ -108,9 +108,16 @@ static int mpc8544_load_device_tree(CPUPPCState *env,
     char gutil[128];
     char pci[128];
     uint32_t pci_map[9 * 8];
-    uint32_t pci_ranges[12] = { 0x2000000, 0x0, 0xc0000000, 0xc0000000, 0x0,
-                                0x20000000, 0x1000000, 0x0, 0x0, 0xe1000000,
-                                0x0, 0x10000 };
+    uint32_t pci_ranges[14] =
+        {
+            0x2000000, 0x0, 0xc0000000,
+            0x0, 0xc0000000,
+            0x0, 0x20000000,
+
+            0x1000000, 0x0, 0x0,
+            0x0, 0xe1000000,
+            0x0, 0x10000,
+        };
     QemuOpts *machine_opts;
     const char *dumpdtb = NULL;
     const char *dtb_file = NULL;
@@ -144,8 +151,8 @@ static int mpc8544_load_device_tree(CPUPPCState *env,
     qemu_devtree_setprop_string(fdt, "/", "model", model);
     qemu_devtree_setprop(fdt, "/", "compatible", compatible,
                          sizeof(compatible));
-    qemu_devtree_setprop_cell(fdt, "/", "#address-cells", 1);
-    qemu_devtree_setprop_cell(fdt, "/", "#size-cells", 1);
+    qemu_devtree_setprop_cell(fdt, "/", "#address-cells", 2);
+    qemu_devtree_setprop_cell(fdt, "/", "#size-cells", 2);
 
     qemu_devtree_add_subnode(fdt, "/memory");
     qemu_devtree_setprop_string(fdt, "/memory", "device_type", "memory");
@@ -239,7 +246,8 @@ static int mpc8544_load_device_tree(CPUPPCState *env,
                          sizeof(compatible_sb));
     qemu_devtree_setprop_cell(fdt, soc, "#address-cells", 1);
     qemu_devtree_setprop_cell(fdt, soc, "#size-cells", 1);
-    qemu_devtree_setprop_cells(fdt, soc, "ranges", 0x0, MPC8544_CCSRBAR_BASE,
+    qemu_devtree_setprop_cells(fdt, soc, "ranges", 0x0,
+                               MPC8544_CCSRBAR_BASE >> 32, MPC8544_CCSRBAR_BASE,
                                MPC8544_CCSRBAR_SIZE);
     /* XXX should contain a reasonable value */
     qemu_devtree_setprop_cell(fdt, soc, "bus-frequency", 0);
@@ -313,12 +321,12 @@ static int mpc8544_load_device_tree(CPUPPCState *env,
     qemu_devtree_setprop_phandle(fdt, pci, "interrupt-parent", mpic);
     qemu_devtree_setprop_cells(fdt, pci, "interrupts", 24, 2, 0, 0);
     qemu_devtree_setprop_cells(fdt, pci, "bus-range", 0, 255);
-    for (i = 0; i < 12; i++) {
+    for (i = 0; i < 14; i++) {
         pci_ranges[i] = cpu_to_be32(pci_ranges[i]);
     }
     qemu_devtree_setprop(fdt, pci, "ranges", pci_ranges, sizeof(pci_ranges));
-    qemu_devtree_setprop_cells(fdt, pci, "reg", MPC8544_PCI_REGS_BASE,
-                               0x1000);
+    qemu_devtree_setprop_cells(fdt, pci, "reg", MPC8544_PCI_REGS_BASE >> 32,
+                               MPC8544_PCI_REGS_BASE, 0, 0x1000);
     qemu_devtree_setprop_cell(fdt, pci, "clock-frequency", 66666666);
     qemu_devtree_setprop_cell(fdt, pci, "#interrupt-cells", 1);
     qemu_devtree_setprop_cell(fdt, pci, "#size-cells", 2);
commit ed2bc496eff0d78544d46c637cf11a29114666c5
Author: Alexander Graf <agraf at suse.de>
Date:   Wed Jun 6 00:30:36 2012 +0200

    PPC: e500: Define addresses as always 64bit
    
    Every time we use an address constant, it needs to potentially fit into
    a 64bit physical address space. So let's define things accordingly.
    
    Signed-off-by: Alexander Graf <agraf at suse.de>

diff --git a/hw/ppce500_mpc8544ds.c b/hw/ppce500_mpc8544ds.c
index 7dc3a07..c6a09bb 100644
--- a/hw/ppce500_mpc8544ds.c
+++ b/hw/ppce500_mpc8544ds.c
@@ -42,17 +42,17 @@
 
 #define RAM_SIZES_ALIGN            (64UL << 20)
 
-#define MPC8544_CCSRBAR_BASE       0xE0000000
-#define MPC8544_CCSRBAR_SIZE       0x00100000
-#define MPC8544_MPIC_REGS_BASE     (MPC8544_CCSRBAR_BASE + 0x40000)
-#define MPC8544_SERIAL0_REGS_BASE  (MPC8544_CCSRBAR_BASE + 0x4500)
-#define MPC8544_SERIAL1_REGS_BASE  (MPC8544_CCSRBAR_BASE + 0x4600)
-#define MPC8544_PCI_REGS_BASE      (MPC8544_CCSRBAR_BASE + 0x8000)
-#define MPC8544_PCI_REGS_SIZE      0x1000
-#define MPC8544_PCI_IO             0xE1000000
-#define MPC8544_PCI_IOLEN          0x10000
-#define MPC8544_UTIL_BASE          (MPC8544_CCSRBAR_BASE + 0xe0000)
-#define MPC8544_SPIN_BASE          0xEF000000
+#define MPC8544_CCSRBAR_BASE       0xE0000000ULL
+#define MPC8544_CCSRBAR_SIZE       0x00100000ULL
+#define MPC8544_MPIC_REGS_BASE     (MPC8544_CCSRBAR_BASE + 0x40000ULL)
+#define MPC8544_SERIAL0_REGS_BASE  (MPC8544_CCSRBAR_BASE + 0x4500ULL)
+#define MPC8544_SERIAL1_REGS_BASE  (MPC8544_CCSRBAR_BASE + 0x4600ULL)
+#define MPC8544_PCI_REGS_BASE      (MPC8544_CCSRBAR_BASE + 0x8000ULL)
+#define MPC8544_PCI_REGS_SIZE      0x1000ULL
+#define MPC8544_PCI_IO             0xE1000000ULL
+#define MPC8544_PCI_IOLEN          0x10000ULL
+#define MPC8544_UTIL_BASE          (MPC8544_CCSRBAR_BASE + 0xe0000ULL)
+#define MPC8544_SPIN_BASE          0xEF000000ULL
 
 struct boot_info
 {
@@ -232,7 +232,7 @@ static int mpc8544_load_device_tree(CPUPPCState *env,
 
     qemu_devtree_add_subnode(fdt, "/aliases");
     /* XXX These should go into their respective devices' code */
-    snprintf(soc, sizeof(soc), "/soc@%x", MPC8544_CCSRBAR_BASE);
+    snprintf(soc, sizeof(soc), "/soc@%llx", MPC8544_CCSRBAR_BASE);
     qemu_devtree_add_subnode(fdt, soc);
     qemu_devtree_setprop_string(fdt, soc, "device_type", "soc");
     qemu_devtree_setprop(fdt, soc, "compatible", compatible_sb,
@@ -244,7 +244,7 @@ static int mpc8544_load_device_tree(CPUPPCState *env,
     /* XXX should contain a reasonable value */
     qemu_devtree_setprop_cell(fdt, soc, "bus-frequency", 0);
 
-    snprintf(mpic, sizeof(mpic), "%s/pic@%x", soc,
+    snprintf(mpic, sizeof(mpic), "%s/pic@%llx", soc,
              MPC8544_MPIC_REGS_BASE - MPC8544_CCSRBAR_BASE);
     qemu_devtree_add_subnode(fdt, mpic);
     qemu_devtree_setprop_string(fdt, mpic, "device_type", "open-pic");
@@ -266,7 +266,7 @@ static int mpc8544_load_device_tree(CPUPPCState *env,
      * device it finds in the dt as serial output device. And we generate
      * devices in reverse order to the dt.
      */
-    snprintf(ser1, sizeof(ser1), "%s/serial@%x", soc,
+    snprintf(ser1, sizeof(ser1), "%s/serial@%llx", soc,
              MPC8544_SERIAL1_REGS_BASE - MPC8544_CCSRBAR_BASE);
     qemu_devtree_add_subnode(fdt, ser1);
     qemu_devtree_setprop_string(fdt, ser1, "device_type", "serial");
@@ -279,7 +279,7 @@ static int mpc8544_load_device_tree(CPUPPCState *env,
     qemu_devtree_setprop_phandle(fdt, ser1, "interrupt-parent", mpic);
     qemu_devtree_setprop_string(fdt, "/aliases", "serial1", ser1);
 
-    snprintf(ser0, sizeof(ser0), "%s/serial@%x", soc,
+    snprintf(ser0, sizeof(ser0), "%s/serial@%llx", soc,
              MPC8544_SERIAL0_REGS_BASE - MPC8544_CCSRBAR_BASE);
     qemu_devtree_add_subnode(fdt, ser0);
     qemu_devtree_setprop_string(fdt, ser0, "device_type", "serial");
@@ -293,7 +293,7 @@ static int mpc8544_load_device_tree(CPUPPCState *env,
     qemu_devtree_setprop_string(fdt, "/aliases", "serial0", ser0);
     qemu_devtree_setprop_string(fdt, "/chosen", "linux,stdout-path", ser0);
 
-    snprintf(gutil, sizeof(gutil), "%s/global-utilities@%x", soc,
+    snprintf(gutil, sizeof(gutil), "%s/global-utilities@%llx", soc,
              MPC8544_UTIL_BASE - MPC8544_CCSRBAR_BASE);
     qemu_devtree_add_subnode(fdt, gutil);
     qemu_devtree_setprop_string(fdt, gutil, "compatible", "fsl,mpc8544-guts");
@@ -301,7 +301,7 @@ static int mpc8544_load_device_tree(CPUPPCState *env,
                                MPC8544_CCSRBAR_BASE, 0x1000);
     qemu_devtree_setprop(fdt, gutil, "fsl,has-rstcr", NULL, 0);
 
-    snprintf(pci, sizeof(pci), "/pci@%x", MPC8544_PCI_REGS_BASE);
+    snprintf(pci, sizeof(pci), "/pci@%llx", MPC8544_PCI_REGS_BASE);
     qemu_devtree_add_subnode(fdt, pci);
     qemu_devtree_setprop_cell(fdt, pci, "cell-index", 0);
     qemu_devtree_setprop_string(fdt, pci, "compatible", "fsl,mpc8540-pci");
commit ebb9518aab7a6c8bb78636494fa60b2742d00251
Author: Alexander Graf <agraf at suse.de>
Date:   Wed Jun 6 00:20:20 2012 +0200

    PPC: e500: Use new SOC dt format
    
    Due to popular demand, let's clean up the soc node a bit and use
    more recent dt notions.
    
    Requested-by: Scott Wood <scottwood at freescale.com>
    Signed-off-by: Alexander Graf <agraf at suse.de>

diff --git a/hw/ppce500_mpc8544ds.c b/hw/ppce500_mpc8544ds.c
index e3e0659..7dc3a07 100644
--- a/hw/ppce500_mpc8544ds.c
+++ b/hw/ppce500_mpc8544ds.c
@@ -43,7 +43,6 @@
 #define RAM_SIZES_ALIGN            (64UL << 20)
 
 #define MPC8544_CCSRBAR_BASE       0xE0000000
-#define MPC8544_CCSRBAR_REGSIZE    0x00001000
 #define MPC8544_CCSRBAR_SIZE       0x00100000
 #define MPC8544_MPIC_REGS_BASE     (MPC8544_CCSRBAR_BASE + 0x40000)
 #define MPC8544_SERIAL0_REGS_BASE  (MPC8544_CCSRBAR_BASE + 0x4500)
@@ -99,6 +98,7 @@ static int mpc8544_load_device_tree(CPUPPCState *env,
     uint32_t tb_freq = 400000000;
     int i;
     char compatible[] = "MPC8544DS\0MPC85xxDS";
+    char compatible_sb[] = "fsl,mpc8544-immr\0simple-bus";
     char model[] = "MPC8544DS";
     char soc[128];
     char ser0[128];
@@ -232,16 +232,15 @@ static int mpc8544_load_device_tree(CPUPPCState *env,
 
     qemu_devtree_add_subnode(fdt, "/aliases");
     /* XXX These should go into their respective devices' code */
-    snprintf(soc, sizeof(soc), "/soc8544@%x", MPC8544_CCSRBAR_BASE);
+    snprintf(soc, sizeof(soc), "/soc@%x", MPC8544_CCSRBAR_BASE);
     qemu_devtree_add_subnode(fdt, soc);
     qemu_devtree_setprop_string(fdt, soc, "device_type", "soc");
-    qemu_devtree_setprop_string(fdt, soc, "compatible", "simple-bus");
+    qemu_devtree_setprop(fdt, soc, "compatible", compatible_sb,
+                         sizeof(compatible_sb));
     qemu_devtree_setprop_cell(fdt, soc, "#address-cells", 1);
     qemu_devtree_setprop_cell(fdt, soc, "#size-cells", 1);
     qemu_devtree_setprop_cells(fdt, soc, "ranges", 0x0, MPC8544_CCSRBAR_BASE,
                                MPC8544_CCSRBAR_SIZE);
-    qemu_devtree_setprop_cells(fdt, soc, "reg", MPC8544_CCSRBAR_BASE,
-                               MPC8544_CCSRBAR_REGSIZE);
     /* XXX should contain a reasonable value */
     qemu_devtree_setprop_cell(fdt, soc, "bus-frequency", 0);
 
commit 518c7fb44f2182cde943dc64f88cb2fd4e4ff6b5
Author: Alexander Graf <agraf at suse.de>
Date:   Wed Jun 6 00:14:34 2012 +0200

    PPC: e500: Use new MPIC dt format
    
    Due to popular demand, we're updating the way we generate the MPIC
    node and interrupt lines based on what the current state of art is.
    
    Requested-by: Scott Wood <scottwood at freescale.com>
    Signed-off-by: Alexander Graf <agraf at suse.de>

diff --git a/hw/ppce500_mpc8544ds.c b/hw/ppce500_mpc8544ds.c
index fa10df2..e3e0659 100644
--- a/hw/ppce500_mpc8544ds.c
+++ b/hw/ppce500_mpc8544ds.c
@@ -67,18 +67,18 @@ static void pci_map_create(void *fdt, uint32_t *pci_map, uint32_t mpic)
     int i;
     const uint32_t tmp[] = {
                              /* IDSEL 0x11 J17 Slot 1 */
-                             0x8800, 0x0, 0x0, 0x1, mpic, 0x2, 0x1,
-                             0x8800, 0x0, 0x0, 0x2, mpic, 0x3, 0x1,
-                             0x8800, 0x0, 0x0, 0x3, mpic, 0x4, 0x1,
-                             0x8800, 0x0, 0x0, 0x4, mpic, 0x1, 0x1,
+                             0x8800, 0x0, 0x0, 0x1, mpic, 0x2, 0x1, 0x0, 0x0,
+                             0x8800, 0x0, 0x0, 0x2, mpic, 0x3, 0x1, 0x0, 0x0,
+                             0x8800, 0x0, 0x0, 0x3, mpic, 0x4, 0x1, 0x0, 0x0,
+                             0x8800, 0x0, 0x0, 0x4, mpic, 0x1, 0x1, 0x0, 0x0,
 
                              /* IDSEL 0x12 J16 Slot 2 */
-                             0x9000, 0x0, 0x0, 0x1, mpic, 0x3, 0x1,
-                             0x9000, 0x0, 0x0, 0x2, mpic, 0x4, 0x1,
-                             0x9000, 0x0, 0x0, 0x3, mpic, 0x2, 0x1,
-                             0x9000, 0x0, 0x0, 0x4, mpic, 0x1, 0x1,
+                             0x9000, 0x0, 0x0, 0x1, mpic, 0x3, 0x1, 0x0, 0x0,
+                             0x9000, 0x0, 0x0, 0x2, mpic, 0x4, 0x1, 0x0, 0x0,
+                             0x9000, 0x0, 0x0, 0x3, mpic, 0x2, 0x1, 0x0, 0x0,
+                             0x9000, 0x0, 0x0, 0x4, mpic, 0x1, 0x1, 0x0, 0x0,
                            };
-    for (i = 0; i < (7 * 8); i++) {
+    for (i = 0; i < ARRAY_SIZE(tmp); i++) {
         pci_map[i] = cpu_to_be32(tmp[i]);
     }
 }
@@ -107,7 +107,7 @@ static int mpc8544_load_device_tree(CPUPPCState *env,
     uint32_t mpic_ph;
     char gutil[128];
     char pci[128];
-    uint32_t pci_map[7 * 8];
+    uint32_t pci_map[9 * 8];
     uint32_t pci_ranges[12] = { 0x2000000, 0x0, 0xc0000000, 0xc0000000, 0x0,
                                 0x20000000, 0x1000000, 0x0, 0x0, 0xe1000000,
                                 0x0, 0x10000 };
@@ -249,15 +249,18 @@ static int mpc8544_load_device_tree(CPUPPCState *env,
              MPC8544_MPIC_REGS_BASE - MPC8544_CCSRBAR_BASE);
     qemu_devtree_add_subnode(fdt, mpic);
     qemu_devtree_setprop_string(fdt, mpic, "device_type", "open-pic");
-    qemu_devtree_setprop_string(fdt, mpic, "compatible", "chrp,open-pic");
+    qemu_devtree_setprop_string(fdt, mpic, "compatible", "fsl,mpic");
     qemu_devtree_setprop_cells(fdt, mpic, "reg", MPC8544_MPIC_REGS_BASE -
                                MPC8544_CCSRBAR_BASE, 0x40000);
     qemu_devtree_setprop_cell(fdt, mpic, "#address-cells", 0);
-    qemu_devtree_setprop_cell(fdt, mpic, "#interrupt-cells", 2);
+    qemu_devtree_setprop_cell(fdt, mpic, "#interrupt-cells", 4);
     mpic_ph = qemu_devtree_alloc_phandle(fdt);
     qemu_devtree_setprop_cell(fdt, mpic, "phandle", mpic_ph);
     qemu_devtree_setprop_cell(fdt, mpic, "linux,phandle", mpic_ph);
     qemu_devtree_setprop(fdt, mpic, "interrupt-controller", NULL, 0);
+    qemu_devtree_setprop(fdt, mpic, "big-endian", NULL, 0);
+    qemu_devtree_setprop(fdt, mpic, "single-cpu-affinity", NULL, 0);
+    qemu_devtree_setprop_cell(fdt, mpic, "last-interrupt-source", 255);
 
     /*
      * We have to generate ser1 first, because Linux takes the first
@@ -273,7 +276,7 @@ static int mpc8544_load_device_tree(CPUPPCState *env,
                                MPC8544_CCSRBAR_BASE, 0x100);
     qemu_devtree_setprop_cell(fdt, ser1, "cell-index", 1);
     qemu_devtree_setprop_cell(fdt, ser1, "clock-frequency", 0);
-    qemu_devtree_setprop_cells(fdt, ser1, "interrupts", 42, 2);
+    qemu_devtree_setprop_cells(fdt, ser1, "interrupts", 42, 2, 0, 0);
     qemu_devtree_setprop_phandle(fdt, ser1, "interrupt-parent", mpic);
     qemu_devtree_setprop_string(fdt, "/aliases", "serial1", ser1);
 
@@ -286,7 +289,7 @@ static int mpc8544_load_device_tree(CPUPPCState *env,
                                MPC8544_CCSRBAR_BASE, 0x100);
     qemu_devtree_setprop_cell(fdt, ser0, "cell-index", 0);
     qemu_devtree_setprop_cell(fdt, ser0, "clock-frequency", 0);
-    qemu_devtree_setprop_cells(fdt, ser0, "interrupts", 42, 2);
+    qemu_devtree_setprop_cells(fdt, ser0, "interrupts", 42, 2, 0, 0);
     qemu_devtree_setprop_phandle(fdt, ser0, "interrupt-parent", mpic);
     qemu_devtree_setprop_string(fdt, "/aliases", "serial0", ser0);
     qemu_devtree_setprop_string(fdt, "/chosen", "linux,stdout-path", ser0);
@@ -309,7 +312,7 @@ static int mpc8544_load_device_tree(CPUPPCState *env,
     pci_map_create(fdt, pci_map, qemu_devtree_get_phandle(fdt, mpic));
     qemu_devtree_setprop(fdt, pci, "interrupt-map", pci_map, sizeof(pci_map));
     qemu_devtree_setprop_phandle(fdt, pci, "interrupt-parent", mpic);
-    qemu_devtree_setprop_cells(fdt, pci, "interrupts", 24, 2);
+    qemu_devtree_setprop_cells(fdt, pci, "interrupts", 24, 2, 0, 0);
     qemu_devtree_setprop_cells(fdt, pci, "bus-range", 0, 255);
     for (i = 0; i < 12; i++) {
         pci_ranges[i] = cpu_to_be32(pci_ranges[i]);
commit 1337ae1e5b20802d3167563d6c733172da513ca7
Author: Alexander Graf <agraf at suse.de>
Date:   Fri May 18 01:45:01 2012 +0200

    Revert "dt: temporarily disable subtree creation failure check"
    
    This reverts commit "dt: temporarily disable subtree creation
    failure check" which was meant as a temporary solution to keep
    external and dynamic device tree construction intact.
    
    Now that we switched to fully dynamic dt construction, it's no
    longer necessary.
    
    Signed-off-by: Alexander Graf <agraf at suse.de>

diff --git a/device_tree.c b/device_tree.c
index c8d68c2..cc83f0f 100644
--- a/device_tree.c
+++ b/device_tree.c
@@ -239,13 +239,11 @@ int qemu_devtree_add_subnode(void *fdt, const char *name)
     }
 
     retval = fdt_add_subnode(fdt, parent, basename);
-#if 0
     if (retval < 0) {
         fprintf(stderr, "FDT: Failed to create subnode %s: %s\n", name,
                 fdt_strerror(retval));
         exit(1);
     }
-#endif
 
     g_free(dupname);
     return retval;
commit d1b935659b77ff8e9d4cb84e3f75679f634401f3
Author: Alexander Graf <agraf at suse.de>
Date:   Tue May 22 14:28:50 2012 +0200

    PPC: e500: enable manual loading of dtb blob
    
    We want to be able to override the automatically created device tree
    by using the -dtb option. Implement this for the mpc8544ds machine.
    
    Signed-off-by: Alexander Graf <agraf at suse.de>

diff --git a/hw/ppce500_mpc8544ds.c b/hw/ppce500_mpc8544ds.c
index f8a3d9a..fa10df2 100644
--- a/hw/ppce500_mpc8544ds.c
+++ b/hw/ppce500_mpc8544ds.c
@@ -113,6 +113,27 @@ static int mpc8544_load_device_tree(CPUPPCState *env,
                                 0x0, 0x10000 };
     QemuOpts *machine_opts;
     const char *dumpdtb = NULL;
+    const char *dtb_file = NULL;
+
+    machine_opts = qemu_opts_find(qemu_find_opts("machine"), 0);
+    if (machine_opts) {
+        dumpdtb = qemu_opt_get(machine_opts, "dumpdtb");
+        dtb_file = qemu_opt_get(machine_opts, "dtb");
+    }
+
+    if (dtb_file) {
+        char *filename;
+        filename = qemu_find_file(QEMU_FILE_TYPE_BIOS, dtb_file);
+        if (!filename) {
+            goto out;
+        }
+
+        fdt = load_device_tree(filename, &fdt_size);
+        if (!fdt) {
+            goto out;
+        }
+        goto done;
+    }
 
     fdt = create_device_tree(&fdt_size);
     if (fdt == NULL) {
@@ -302,10 +323,7 @@ static int mpc8544_load_device_tree(CPUPPCState *env,
     qemu_devtree_setprop_cell(fdt, pci, "#address-cells", 3);
     qemu_devtree_setprop_string(fdt, "/aliases", "pci0", pci);
 
-    machine_opts = qemu_opts_find(qemu_find_opts("machine"), 0);
-    if (machine_opts) {
-        dumpdtb = qemu_opt_get(machine_opts, "dumpdtb");
-    }
+done:
     if (dumpdtb) {
         /* Dump the dtb to a file and quit */
         FILE *f = fopen(dumpdtb, "wb");
commit 7f47b41f3f36fd0618758580121ddeb0407069b7
Author: Alexander Graf <agraf at suse.de>
Date:   Fri May 18 02:14:46 2012 +0200

    PPC: e500: dt: use target_phys_addr_t for ramsize
    
    We're passing the ram size as uint32_t, capping it to 32 bits atm.
    Change to target_phys_addr_t (uint64_t) to make sure we have all
    the bits.
    
    Signed-off-by: Alexander Graf <agraf at suse.de>

diff --git a/hw/ppce500_mpc8544ds.c b/hw/ppce500_mpc8544ds.c
index 5fa2089..f8a3d9a 100644
--- a/hw/ppce500_mpc8544ds.c
+++ b/hw/ppce500_mpc8544ds.c
@@ -85,7 +85,7 @@ static void pci_map_create(void *fdt, uint32_t *pci_map, uint32_t mpic)
 
 static int mpc8544_load_device_tree(CPUPPCState *env,
                                     target_phys_addr_t addr,
-                                    uint32_t ramsize,
+                                    target_phys_addr_t ramsize,
                                     target_phys_addr_t initrd_base,
                                     target_phys_addr_t initrd_size,
                                     const char *kernel_cmdline)
commit 1d2e5c5235dc722bc9e12218d5f00c12f8bdc5bb
Author: Alexander Graf <agraf at suse.de>
Date:   Fri May 18 01:56:46 2012 +0200

    PPC: e500: dt: use 64bit cell helper
    
    We have a nice 64bit helper to ease the device tree generation and
    make the code more readable when creating 64bit 2-cell parameters.
    Use it when generating the device tree.
    
    Signed-off-by: Alexander Graf <agraf at suse.de>

diff --git a/hw/ppce500_mpc8544ds.c b/hw/ppce500_mpc8544ds.c
index 7c6edc2..5fa2089 100644
--- a/hw/ppce500_mpc8544ds.c
+++ b/hw/ppce500_mpc8544ds.c
@@ -174,7 +174,7 @@ static int mpc8544_load_device_tree(CPUPPCState *env,
        the first node as boot node and be happy */
     for (i = smp_cpus - 1; i >= 0; i--) {
         char cpu_name[128];
-        uint64_t cpu_release_addr = cpu_to_be64(MPC8544_SPIN_BASE + (i * 0x20));
+        uint64_t cpu_release_addr = MPC8544_SPIN_BASE + (i * 0x20);
 
         for (env = first_cpu; env != NULL; env = env->next_cpu) {
             if (env->cpu_index == i) {
@@ -202,8 +202,8 @@ static int mpc8544_load_device_tree(CPUPPCState *env,
         if (env->cpu_index) {
             qemu_devtree_setprop_string(fdt, cpu_name, "status", "disabled");
             qemu_devtree_setprop_string(fdt, cpu_name, "enable-method", "spin-table");
-            qemu_devtree_setprop(fdt, cpu_name, "cpu-release-addr",
-                                 &cpu_release_addr, sizeof(cpu_release_addr));
+            qemu_devtree_setprop_u64(fdt, cpu_name, "cpu-release-addr",
+                                     cpu_release_addr);
         } else {
             qemu_devtree_setprop_string(fdt, cpu_name, "status", "okay");
         }
commit 25b42708cd011e7d4b37313f7f83ac2551e5370f
Author: Alexander Graf <agraf at suse.de>
Date:   Fri May 18 00:11:33 2012 +0200

    dt: Add -machine dumpdtb option to dump the current dtb
    
    Now that we are dynamically creating the dtb, it's really useful to
    be able to dump the created blob for debugging.
    
    This patch implements a -machine dumpdtb=<file> option for e500 that
    dumps the dtb exactly in the form the guest would get it to disk. It
    can then be analyzed by dtc to get information about the guest
    configuration.
    
    Signed-off-by: Alexander Graf <agraf at suse.de>

diff --git a/hw/ppce500_mpc8544ds.c b/hw/ppce500_mpc8544ds.c
index 880ed55..7c6edc2 100644
--- a/hw/ppce500_mpc8544ds.c
+++ b/hw/ppce500_mpc8544ds.c
@@ -111,6 +111,8 @@ static int mpc8544_load_device_tree(CPUPPCState *env,
     uint32_t pci_ranges[12] = { 0x2000000, 0x0, 0xc0000000, 0xc0000000, 0x0,
                                 0x20000000, 0x1000000, 0x0, 0x0, 0xe1000000,
                                 0x0, 0x10000 };
+    QemuOpts *machine_opts;
+    const char *dumpdtb = NULL;
 
     fdt = create_device_tree(&fdt_size);
     if (fdt == NULL) {
@@ -300,6 +302,22 @@ static int mpc8544_load_device_tree(CPUPPCState *env,
     qemu_devtree_setprop_cell(fdt, pci, "#address-cells", 3);
     qemu_devtree_setprop_string(fdt, "/aliases", "pci0", pci);
 
+    machine_opts = qemu_opts_find(qemu_find_opts("machine"), 0);
+    if (machine_opts) {
+        dumpdtb = qemu_opt_get(machine_opts, "dumpdtb");
+    }
+    if (dumpdtb) {
+        /* Dump the dtb to a file and quit */
+        FILE *f = fopen(dumpdtb, "wb");
+        size_t len;
+        len = fwrite(fdt, fdt_size, 1, f);
+        fclose(f);
+        if (len != fdt_size) {
+            exit(1);
+        }
+        exit(0);
+    }
+
     ret = rom_add_blob_fixed(BINARY_DEVICE_TREE_FILE, fdt, fdt_size, addr);
     if (ret < 0) {
         goto out;
diff --git a/qemu-config.c b/qemu-config.c
index bb3bff4..5bbebaf 100644
--- a/qemu-config.c
+++ b/qemu-config.c
@@ -583,6 +583,10 @@ static QemuOptsList qemu_machine_opts = {
             .name = "dtb",
             .type = QEMU_OPT_STRING,
             .help = "Linux kernel device tree file",
+        }, {
+            .name = "dumpdtb",
+            .type = QEMU_OPT_STRING,
+            .help = "Dump current dtb to a file and quit",
         },
         { /* End of list */ }
     },
commit 2636fcb6532eafbb3f1fafba69a107664218e3c8
Author: Alexander Graf <agraf at suse.de>
Date:   Thu May 17 15:50:14 2012 +0200

    PPC: e500: dt: start with empty device tree
    
    Now that all of the device tree bits are generated during runtime, we
    can get rid of the device tree blob and instead start from scratch with
    an empty device tree.
    
    Signed-off-by: Alexander Graf <agraf at suse.de>

diff --git a/Makefile b/Makefile
index a7281b0..827e1ad 100644
--- a/Makefile
+++ b/Makefile
@@ -260,7 +260,6 @@ pxe-e1000.rom pxe-eepro100.rom pxe-ne2k_pci.rom \
 pxe-pcnet.rom pxe-rtl8139.rom pxe-virtio.rom \
 qemu-icon.bmp \
 bamboo.dtb petalogix-s3adsp1800.dtb petalogix-ml605.dtb \
-mpc8544ds.dtb \
 multiboot.bin linuxboot.bin kvmvapic.bin \
 s390-zipl.rom \
 spapr-rtas.bin slof.bin \
diff --git a/hw/ppce500_mpc8544ds.c b/hw/ppce500_mpc8544ds.c
index 15df515..880ed55 100644
--- a/hw/ppce500_mpc8544ds.c
+++ b/hw/ppce500_mpc8544ds.c
@@ -92,7 +92,6 @@ static int mpc8544_load_device_tree(CPUPPCState *env,
 {
     int ret = -1;
     uint32_t mem_reg_property[] = {0, cpu_to_be32(ramsize)};
-    char *filename;
     int fdt_size;
     void *fdt;
     uint8_t hypercall[16];
@@ -113,12 +112,7 @@ static int mpc8544_load_device_tree(CPUPPCState *env,
                                 0x20000000, 0x1000000, 0x0, 0x0, 0xe1000000,
                                 0x0, 0x10000 };
 
-    filename = qemu_find_file(QEMU_FILE_TYPE_BIOS, BINARY_DEVICE_TREE_FILE);
-    if (!filename) {
-        goto out;
-    }
-    fdt = load_device_tree(filename, &fdt_size);
-    g_free(filename);
+    fdt = create_device_tree(&fdt_size);
     if (fdt == NULL) {
         goto out;
     }
diff --git a/pc-bios/mpc8544ds.dtb b/pc-bios/mpc8544ds.dtb
deleted file mode 100644
index 90ef5c0..0000000
Binary files a/pc-bios/mpc8544ds.dtb and /dev/null differ
diff --git a/pc-bios/mpc8544ds.dts b/pc-bios/mpc8544ds.dts
deleted file mode 100644
index 16aba2b..0000000
--- a/pc-bios/mpc8544ds.dts
+++ /dev/null
@@ -1,14 +0,0 @@
-/*
- * MPC8544 DS Device Tree Source
- *
- * Copyright 2007, 2008 Freescale Semiconductor Inc.
- *
- * This program is free software; you can redistribute  it and/or modify it
- * under  the terms of  the GNU General  Public License as published by the
- * Free Software Foundation;  either version 2 of the  License, or (at your
- * option) any later version.
- */
-
-/dts-v1/;
-/ {
-};
commit 0dbc07985b15940ff3f19529c1f6fd734d535971
Author: Alexander Graf <agraf at suse.de>
Date:   Thu May 17 15:34:34 2012 +0200

    PPC: e500: dt: create pci node dynamically
    
    Signed-off-by: Alexander Graf <agraf at suse.de>

diff --git a/hw/ppce500_mpc8544ds.c b/hw/ppce500_mpc8544ds.c
index 03938b2..15df515 100644
--- a/hw/ppce500_mpc8544ds.c
+++ b/hw/ppce500_mpc8544ds.c
@@ -62,6 +62,27 @@ struct boot_info
     uint32_t entry;
 };
 
+static void pci_map_create(void *fdt, uint32_t *pci_map, uint32_t mpic)
+{
+    int i;
+    const uint32_t tmp[] = {
+                             /* IDSEL 0x11 J17 Slot 1 */
+                             0x8800, 0x0, 0x0, 0x1, mpic, 0x2, 0x1,
+                             0x8800, 0x0, 0x0, 0x2, mpic, 0x3, 0x1,
+                             0x8800, 0x0, 0x0, 0x3, mpic, 0x4, 0x1,
+                             0x8800, 0x0, 0x0, 0x4, mpic, 0x1, 0x1,
+
+                             /* IDSEL 0x12 J16 Slot 2 */
+                             0x9000, 0x0, 0x0, 0x1, mpic, 0x3, 0x1,
+                             0x9000, 0x0, 0x0, 0x2, mpic, 0x4, 0x1,
+                             0x9000, 0x0, 0x0, 0x3, mpic, 0x2, 0x1,
+                             0x9000, 0x0, 0x0, 0x4, mpic, 0x1, 0x1,
+                           };
+    for (i = 0; i < (7 * 8); i++) {
+        pci_map[i] = cpu_to_be32(tmp[i]);
+    }
+}
+
 static int mpc8544_load_device_tree(CPUPPCState *env,
                                     target_phys_addr_t addr,
                                     uint32_t ramsize,
@@ -86,6 +107,11 @@ static int mpc8544_load_device_tree(CPUPPCState *env,
     char mpic[128];
     uint32_t mpic_ph;
     char gutil[128];
+    char pci[128];
+    uint32_t pci_map[7 * 8];
+    uint32_t pci_ranges[12] = { 0x2000000, 0x0, 0xc0000000, 0xc0000000, 0x0,
+                                0x20000000, 0x1000000, 0x0, 0x0, 0xe1000000,
+                                0x0, 0x10000 };
 
     filename = qemu_find_file(QEMU_FILE_TYPE_BIOS, BINARY_DEVICE_TREE_FILE);
     if (!filename) {
@@ -256,6 +282,30 @@ static int mpc8544_load_device_tree(CPUPPCState *env,
                                MPC8544_CCSRBAR_BASE, 0x1000);
     qemu_devtree_setprop(fdt, gutil, "fsl,has-rstcr", NULL, 0);
 
+    snprintf(pci, sizeof(pci), "/pci@%x", MPC8544_PCI_REGS_BASE);
+    qemu_devtree_add_subnode(fdt, pci);
+    qemu_devtree_setprop_cell(fdt, pci, "cell-index", 0);
+    qemu_devtree_setprop_string(fdt, pci, "compatible", "fsl,mpc8540-pci");
+    qemu_devtree_setprop_string(fdt, pci, "device_type", "pci");
+    qemu_devtree_setprop_cells(fdt, pci, "interrupt-map-mask", 0xf800, 0x0,
+                               0x0, 0x7);
+    pci_map_create(fdt, pci_map, qemu_devtree_get_phandle(fdt, mpic));
+    qemu_devtree_setprop(fdt, pci, "interrupt-map", pci_map, sizeof(pci_map));
+    qemu_devtree_setprop_phandle(fdt, pci, "interrupt-parent", mpic);
+    qemu_devtree_setprop_cells(fdt, pci, "interrupts", 24, 2);
+    qemu_devtree_setprop_cells(fdt, pci, "bus-range", 0, 255);
+    for (i = 0; i < 12; i++) {
+        pci_ranges[i] = cpu_to_be32(pci_ranges[i]);
+    }
+    qemu_devtree_setprop(fdt, pci, "ranges", pci_ranges, sizeof(pci_ranges));
+    qemu_devtree_setprop_cells(fdt, pci, "reg", MPC8544_PCI_REGS_BASE,
+                               0x1000);
+    qemu_devtree_setprop_cell(fdt, pci, "clock-frequency", 66666666);
+    qemu_devtree_setprop_cell(fdt, pci, "#interrupt-cells", 1);
+    qemu_devtree_setprop_cell(fdt, pci, "#size-cells", 2);
+    qemu_devtree_setprop_cell(fdt, pci, "#address-cells", 3);
+    qemu_devtree_setprop_string(fdt, "/aliases", "pci0", pci);
+
     ret = rom_add_blob_fixed(BINARY_DEVICE_TREE_FILE, fdt, fdt_size, addr);
     if (ret < 0) {
         goto out;
diff --git a/pc-bios/mpc8544ds.dtb b/pc-bios/mpc8544ds.dtb
index 25d92f6..90ef5c0 100644
Binary files a/pc-bios/mpc8544ds.dtb and b/pc-bios/mpc8544ds.dtb differ
diff --git a/pc-bios/mpc8544ds.dts b/pc-bios/mpc8544ds.dts
index 4c7bd75..16aba2b 100644
--- a/pc-bios/mpc8544ds.dts
+++ b/pc-bios/mpc8544ds.dts
@@ -11,50 +11,4 @@
 
 /dts-v1/;
 / {
-	aliases {
-		pci0 = &pci0;
-	};
-
-	soc8544 at e0000000 {
-		mpic: pic at 40000 {
-			interrupt-controller;
-			#address-cells = <0>;
-			#interrupt-cells = <2>;
-			reg = <0x40000 0x40000>;
-			compatible = "chrp,open-pic";
-			device_type = "open-pic";
-		};
-	};
-
-	pci0: pci at e0008000 {
-		cell-index = <0>;
-		compatible = "fsl,mpc8540-pci";
-		device_type = "pci";
-		interrupt-map-mask = <0xf800 0x0 0x0 0x7>;
-		interrupt-map = <
-
-			/* IDSEL 0x11 J17 Slot 1 */
-			0x8800 0x0 0x0 0x1 &mpic 0x2 0x1
-			0x8800 0x0 0x0 0x2 &mpic 0x3 0x1
-			0x8800 0x0 0x0 0x3 &mpic 0x4 0x1
-			0x8800 0x0 0x0 0x4 &mpic 0x1 0x1
-
-			/* IDSEL 0x12 J16 Slot 2 */
-
-			0x9000 0x0 0x0 0x1 &mpic 0x3 0x1
-			0x9000 0x0 0x0 0x2 &mpic 0x4 0x1
-			0x9000 0x0 0x0 0x3 &mpic 0x2 0x1
-			0x9000 0x0 0x0 0x4 &mpic 0x1 0x1>;
-
-		interrupt-parent = <&mpic>;
-		interrupts = <24 2>;
-		bus-range = <0 255>;
-		ranges = <0x2000000 0x0 0xc0000000 0xc0000000 0x0 0x20000000
-			  0x1000000 0x0 0x0 0xe1000000 0x0 0x10000>;
-		clock-frequency = <66666666>;
-		#interrupt-cells = <1>;
-		#size-cells = <2>;
-		#address-cells = <3>;
-		reg = <0xe0008000 0x1000>;
-	};
 };
commit f5038483e4e752b7b4f7053e90873b127bfe4064
Author: Alexander Graf <agraf at suse.de>
Date:   Thu May 17 14:52:46 2012 +0200

    PPC: e500: dt: create global-utils node dynamically
    
    Signed-off-by: Alexander Graf <agraf at suse.de>

diff --git a/hw/ppce500_mpc8544ds.c b/hw/ppce500_mpc8544ds.c
index 5c2b6ab..03938b2 100644
--- a/hw/ppce500_mpc8544ds.c
+++ b/hw/ppce500_mpc8544ds.c
@@ -85,6 +85,7 @@ static int mpc8544_load_device_tree(CPUPPCState *env,
     char ser1[128];
     char mpic[128];
     uint32_t mpic_ph;
+    char gutil[128];
 
     filename = qemu_find_file(QEMU_FILE_TYPE_BIOS, BINARY_DEVICE_TREE_FILE);
     if (!filename) {
@@ -247,6 +248,14 @@ static int mpc8544_load_device_tree(CPUPPCState *env,
     qemu_devtree_setprop_string(fdt, "/aliases", "serial0", ser0);
     qemu_devtree_setprop_string(fdt, "/chosen", "linux,stdout-path", ser0);
 
+    snprintf(gutil, sizeof(gutil), "%s/global-utilities@%x", soc,
+             MPC8544_UTIL_BASE - MPC8544_CCSRBAR_BASE);
+    qemu_devtree_add_subnode(fdt, gutil);
+    qemu_devtree_setprop_string(fdt, gutil, "compatible", "fsl,mpc8544-guts");
+    qemu_devtree_setprop_cells(fdt, gutil, "reg", MPC8544_UTIL_BASE -
+                               MPC8544_CCSRBAR_BASE, 0x1000);
+    qemu_devtree_setprop(fdt, gutil, "fsl,has-rstcr", NULL, 0);
+
     ret = rom_add_blob_fixed(BINARY_DEVICE_TREE_FILE, fdt, fdt_size, addr);
     if (ret < 0) {
         goto out;
diff --git a/pc-bios/mpc8544ds.dts b/pc-bios/mpc8544ds.dts
index e536ab1..4c7bd75 100644
--- a/pc-bios/mpc8544ds.dts
+++ b/pc-bios/mpc8544ds.dts
@@ -24,12 +24,6 @@
 			compatible = "chrp,open-pic";
 			device_type = "open-pic";
 		};
-
-                global-utilities at e0000 {        //global utilities block
-                        compatible = "fsl,mpc8544-guts";
-                        reg = <0xe0000 0x1000>;
-                        fsl,has-rstcr;
-                };
 	};
 
 	pci0: pci at e0008000 {
commit 19ac9deacbadf77532723950ce3e128e18c31573
Author: Alexander Graf <agraf at suse.de>
Date:   Thu May 17 14:51:51 2012 +0200

    PPC: e500: dt: create mpic node dynamically
    
    Signed-off-by: Alexander Graf <agraf at suse.de>

diff --git a/hw/ppce500_mpc8544ds.c b/hw/ppce500_mpc8544ds.c
index c68e994..5c2b6ab 100644
--- a/hw/ppce500_mpc8544ds.c
+++ b/hw/ppce500_mpc8544ds.c
@@ -83,6 +83,8 @@ static int mpc8544_load_device_tree(CPUPPCState *env,
     char soc[128];
     char ser0[128];
     char ser1[128];
+    char mpic[128];
+    uint32_t mpic_ph;
 
     filename = qemu_find_file(QEMU_FILE_TYPE_BIOS, BINARY_DEVICE_TREE_FILE);
     if (!filename) {
@@ -199,6 +201,20 @@ static int mpc8544_load_device_tree(CPUPPCState *env,
     /* XXX should contain a reasonable value */
     qemu_devtree_setprop_cell(fdt, soc, "bus-frequency", 0);
 
+    snprintf(mpic, sizeof(mpic), "%s/pic@%x", soc,
+             MPC8544_MPIC_REGS_BASE - MPC8544_CCSRBAR_BASE);
+    qemu_devtree_add_subnode(fdt, mpic);
+    qemu_devtree_setprop_string(fdt, mpic, "device_type", "open-pic");
+    qemu_devtree_setprop_string(fdt, mpic, "compatible", "chrp,open-pic");
+    qemu_devtree_setprop_cells(fdt, mpic, "reg", MPC8544_MPIC_REGS_BASE -
+                               MPC8544_CCSRBAR_BASE, 0x40000);
+    qemu_devtree_setprop_cell(fdt, mpic, "#address-cells", 0);
+    qemu_devtree_setprop_cell(fdt, mpic, "#interrupt-cells", 2);
+    mpic_ph = qemu_devtree_alloc_phandle(fdt);
+    qemu_devtree_setprop_cell(fdt, mpic, "phandle", mpic_ph);
+    qemu_devtree_setprop_cell(fdt, mpic, "linux,phandle", mpic_ph);
+    qemu_devtree_setprop(fdt, mpic, "interrupt-controller", NULL, 0);
+
     /*
      * We have to generate ser1 first, because Linux takes the first
      * device it finds in the dt as serial output device. And we generate
commit 0cfc6e8d9e18856b1db0cb5cd5624df7fb19b469
Author: Alexander Graf <agraf at suse.de>
Date:   Thu May 17 14:51:34 2012 +0200

    PPC: e500: dt: create serial nodes dynamically
    
    Signed-off-by: Alexander Graf <agraf at suse.de>

diff --git a/hw/ppce500_mpc8544ds.c b/hw/ppce500_mpc8544ds.c
index c7c16c1..c68e994 100644
--- a/hw/ppce500_mpc8544ds.c
+++ b/hw/ppce500_mpc8544ds.c
@@ -81,6 +81,8 @@ static int mpc8544_load_device_tree(CPUPPCState *env,
     char compatible[] = "MPC8544DS\0MPC85xxDS";
     char model[] = "MPC8544DS";
     char soc[128];
+    char ser0[128];
+    char ser1[128];
 
     filename = qemu_find_file(QEMU_FILE_TYPE_BIOS, BINARY_DEVICE_TREE_FILE);
     if (!filename) {
@@ -182,6 +184,7 @@ static int mpc8544_load_device_tree(CPUPPCState *env,
         }
     }
 
+    qemu_devtree_add_subnode(fdt, "/aliases");
     /* XXX These should go into their respective devices' code */
     snprintf(soc, sizeof(soc), "/soc8544@%x", MPC8544_CCSRBAR_BASE);
     qemu_devtree_add_subnode(fdt, soc);
@@ -196,6 +199,38 @@ static int mpc8544_load_device_tree(CPUPPCState *env,
     /* XXX should contain a reasonable value */
     qemu_devtree_setprop_cell(fdt, soc, "bus-frequency", 0);
 
+    /*
+     * We have to generate ser1 first, because Linux takes the first
+     * device it finds in the dt as serial output device. And we generate
+     * devices in reverse order to the dt.
+     */
+    snprintf(ser1, sizeof(ser1), "%s/serial@%x", soc,
+             MPC8544_SERIAL1_REGS_BASE - MPC8544_CCSRBAR_BASE);
+    qemu_devtree_add_subnode(fdt, ser1);
+    qemu_devtree_setprop_string(fdt, ser1, "device_type", "serial");
+    qemu_devtree_setprop_string(fdt, ser1, "compatible", "ns16550");
+    qemu_devtree_setprop_cells(fdt, ser1, "reg", MPC8544_SERIAL1_REGS_BASE -
+                               MPC8544_CCSRBAR_BASE, 0x100);
+    qemu_devtree_setprop_cell(fdt, ser1, "cell-index", 1);
+    qemu_devtree_setprop_cell(fdt, ser1, "clock-frequency", 0);
+    qemu_devtree_setprop_cells(fdt, ser1, "interrupts", 42, 2);
+    qemu_devtree_setprop_phandle(fdt, ser1, "interrupt-parent", mpic);
+    qemu_devtree_setprop_string(fdt, "/aliases", "serial1", ser1);
+
+    snprintf(ser0, sizeof(ser0), "%s/serial@%x", soc,
+             MPC8544_SERIAL0_REGS_BASE - MPC8544_CCSRBAR_BASE);
+    qemu_devtree_add_subnode(fdt, ser0);
+    qemu_devtree_setprop_string(fdt, ser0, "device_type", "serial");
+    qemu_devtree_setprop_string(fdt, ser0, "compatible", "ns16550");
+    qemu_devtree_setprop_cells(fdt, ser0, "reg", MPC8544_SERIAL0_REGS_BASE -
+                               MPC8544_CCSRBAR_BASE, 0x100);
+    qemu_devtree_setprop_cell(fdt, ser0, "cell-index", 0);
+    qemu_devtree_setprop_cell(fdt, ser0, "clock-frequency", 0);
+    qemu_devtree_setprop_cells(fdt, ser0, "interrupts", 42, 2);
+    qemu_devtree_setprop_phandle(fdt, ser0, "interrupt-parent", mpic);
+    qemu_devtree_setprop_string(fdt, "/aliases", "serial0", ser0);
+    qemu_devtree_setprop_string(fdt, "/chosen", "linux,stdout-path", ser0);
+
     ret = rom_add_blob_fixed(BINARY_DEVICE_TREE_FILE, fdt, fdt_size, addr);
     if (ret < 0) {
         goto out;
diff --git a/pc-bios/mpc8544ds.dts b/pc-bios/mpc8544ds.dts
index 01b53ba..e536ab1 100644
--- a/pc-bios/mpc8544ds.dts
+++ b/pc-bios/mpc8544ds.dts
@@ -12,32 +12,10 @@
 /dts-v1/;
 / {
 	aliases {
-		serial0 = &serial0;
-		serial1 = &serial1;
 		pci0 = &pci0;
 	};
 
 	soc8544 at e0000000 {
-		serial0: serial at 4500 {
-			cell-index = <0>;
-			device_type = "serial";
-			compatible = "ns16550";
-			reg = <0x4500 0x100>;
-			clock-frequency = <0>;
-			interrupts = <42 2>;
-			interrupt-parent = <&mpic>;
-		};
-
-		serial1: serial at 4600 {
-			cell-index = <1>;
-			device_type = "serial";
-			compatible = "ns16550";
-			reg = <0x4600 0x100>;
-			clock-frequency = <0>;
-			interrupts = <42 2>;
-			interrupt-parent = <&mpic>;
-		};
-
 		mpic: pic at 40000 {
 			interrupt-controller;
 			#address-cells = <0>;
@@ -85,8 +63,4 @@
 		#address-cells = <3>;
 		reg = <0xe0008000 0x1000>;
 	};
-
-	chosen {
-		linux,stdout-path = "/soc8544 at e0000000/serial at 4500";
-	};
 };
commit 5da96624391b27f9ead1e0639dbca416926cd660
Author: Alexander Graf <agraf at suse.de>
Date:   Thu May 17 14:51:07 2012 +0200

    PPC: e500: dt: create /soc8544 node dynamically
    
    Signed-off-by: Alexander Graf <agraf at suse.de>

diff --git a/hw/ppce500_mpc8544ds.c b/hw/ppce500_mpc8544ds.c
index a078e24..c7c16c1 100644
--- a/hw/ppce500_mpc8544ds.c
+++ b/hw/ppce500_mpc8544ds.c
@@ -43,6 +43,8 @@
 #define RAM_SIZES_ALIGN            (64UL << 20)
 
 #define MPC8544_CCSRBAR_BASE       0xE0000000
+#define MPC8544_CCSRBAR_REGSIZE    0x00001000
+#define MPC8544_CCSRBAR_SIZE       0x00100000
 #define MPC8544_MPIC_REGS_BASE     (MPC8544_CCSRBAR_BASE + 0x40000)
 #define MPC8544_SERIAL0_REGS_BASE  (MPC8544_CCSRBAR_BASE + 0x4500)
 #define MPC8544_SERIAL1_REGS_BASE  (MPC8544_CCSRBAR_BASE + 0x4600)
@@ -78,6 +80,7 @@ static int mpc8544_load_device_tree(CPUPPCState *env,
     int i;
     char compatible[] = "MPC8544DS\0MPC85xxDS";
     char model[] = "MPC8544DS";
+    char soc[128];
 
     filename = qemu_find_file(QEMU_FILE_TYPE_BIOS, BINARY_DEVICE_TREE_FILE);
     if (!filename) {
@@ -179,6 +182,20 @@ static int mpc8544_load_device_tree(CPUPPCState *env,
         }
     }
 
+    /* XXX These should go into their respective devices' code */
+    snprintf(soc, sizeof(soc), "/soc8544@%x", MPC8544_CCSRBAR_BASE);
+    qemu_devtree_add_subnode(fdt, soc);
+    qemu_devtree_setprop_string(fdt, soc, "device_type", "soc");
+    qemu_devtree_setprop_string(fdt, soc, "compatible", "simple-bus");
+    qemu_devtree_setprop_cell(fdt, soc, "#address-cells", 1);
+    qemu_devtree_setprop_cell(fdt, soc, "#size-cells", 1);
+    qemu_devtree_setprop_cells(fdt, soc, "ranges", 0x0, MPC8544_CCSRBAR_BASE,
+                               MPC8544_CCSRBAR_SIZE);
+    qemu_devtree_setprop_cells(fdt, soc, "reg", MPC8544_CCSRBAR_BASE,
+                               MPC8544_CCSRBAR_REGSIZE);
+    /* XXX should contain a reasonable value */
+    qemu_devtree_setprop_cell(fdt, soc, "bus-frequency", 0);
+
     ret = rom_add_blob_fixed(BINARY_DEVICE_TREE_FILE, fdt, fdt_size, addr);
     if (ret < 0) {
         goto out;
diff --git a/pc-bios/mpc8544ds.dts b/pc-bios/mpc8544ds.dts
index 1eac8ef..01b53ba 100644
--- a/pc-bios/mpc8544ds.dts
+++ b/pc-bios/mpc8544ds.dts
@@ -18,15 +18,6 @@
 	};
 
 	soc8544 at e0000000 {
-		#address-cells = <1>;
-		#size-cells = <1>;
-		device_type = "soc";
-		compatible = "simple-bus";
-
-		ranges = <0x0 0xe0000000 0x100000>;
-		reg = <0xe0000000 0x1000>;	// CCSRBAR 1M
-		bus-frequency = <0>;		// Filled out by uboot.
-
 		serial0: serial at 4500 {
 			cell-index = <0>;
 			device_type = "serial";
commit f5231aafbfcbf4c43c7612785daa8f26e54ab5bb
Author: Alexander Graf <agraf at suse.de>
Date:   Thu May 17 14:49:20 2012 +0200

    PPC: e500: dt: create /chosen node dynamically
    
    Signed-off-by: Alexander Graf <agraf at suse.de>

diff --git a/hw/ppce500_mpc8544ds.c b/hw/ppce500_mpc8544ds.c
index 28c7c8c..a078e24 100644
--- a/hw/ppce500_mpc8544ds.c
+++ b/hw/ppce500_mpc8544ds.c
@@ -101,6 +101,7 @@ static int mpc8544_load_device_tree(CPUPPCState *env,
     qemu_devtree_setprop(fdt, "/memory", "reg", mem_reg_property,
                          sizeof(mem_reg_property));
 
+    qemu_devtree_add_subnode(fdt, "/chosen");
     if (initrd_size) {
         ret = qemu_devtree_setprop_cell(fdt, "/chosen", "linux,initrd-start",
                                         initrd_base);
commit 51b852b74c999f099338fba1b26bbbb4ab8a0bd4
Author: Alexander Graf <agraf at suse.de>
Date:   Thu May 17 12:20:50 2012 +0200

    PPC: e500: dt: create / node dynamically
    
    Signed-off-by: Alexander Graf <agraf at suse.de>

diff --git a/hw/ppce500_mpc8544ds.c b/hw/ppce500_mpc8544ds.c
index 54e7ec7..28c7c8c 100644
--- a/hw/ppce500_mpc8544ds.c
+++ b/hw/ppce500_mpc8544ds.c
@@ -76,6 +76,8 @@ static int mpc8544_load_device_tree(CPUPPCState *env,
     uint32_t clock_freq = 400000000;
     uint32_t tb_freq = 400000000;
     int i;
+    char compatible[] = "MPC8544DS\0MPC85xxDS";
+    char model[] = "MPC8544DS";
 
     filename = qemu_find_file(QEMU_FILE_TYPE_BIOS, BINARY_DEVICE_TREE_FILE);
     if (!filename) {
@@ -88,6 +90,12 @@ static int mpc8544_load_device_tree(CPUPPCState *env,
     }
 
     /* Manipulate device tree in memory. */
+    qemu_devtree_setprop_string(fdt, "/", "model", model);
+    qemu_devtree_setprop(fdt, "/", "compatible", compatible,
+                         sizeof(compatible));
+    qemu_devtree_setprop_cell(fdt, "/", "#address-cells", 1);
+    qemu_devtree_setprop_cell(fdt, "/", "#size-cells", 1);
+
     qemu_devtree_add_subnode(fdt, "/memory");
     qemu_devtree_setprop_string(fdt, "/memory", "device_type", "memory");
     qemu_devtree_setprop(fdt, "/memory", "reg", mem_reg_property,
diff --git a/pc-bios/mpc8544ds.dtb b/pc-bios/mpc8544ds.dtb
index 8194aa2..25d92f6 100644
Binary files a/pc-bios/mpc8544ds.dtb and b/pc-bios/mpc8544ds.dtb differ
diff --git a/pc-bios/mpc8544ds.dts b/pc-bios/mpc8544ds.dts
index 2ca7c54..1eac8ef 100644
--- a/pc-bios/mpc8544ds.dts
+++ b/pc-bios/mpc8544ds.dts
@@ -11,11 +11,6 @@
 
 /dts-v1/;
 / {
-	model = "MPC8544DS";
-	compatible = "MPC8544DS", "MPC85xxDS";
-	#address-cells = <1>;
-	#size-cells = <1>;
-
 	aliases {
 		serial0 = &serial0;
 		serial1 = &serial1;
commit d50f71a5fda5515021a33e8e391decb5602f6328
Author: Alexander Graf <agraf at suse.de>
Date:   Thu May 17 11:50:05 2012 +0200

    PPC: e500: dt: create /hypervisor node dynamically
    
    Signed-off-by: Alexander Graf <agraf at suse.de>

diff --git a/hw/ppce500_mpc8544ds.c b/hw/ppce500_mpc8544ds.c
index c046206..54e7ec7 100644
--- a/hw/ppce500_mpc8544ds.c
+++ b/hw/ppce500_mpc8544ds.c
@@ -118,6 +118,7 @@ static int mpc8544_load_device_tree(CPUPPCState *env,
         tb_freq = kvmppc_get_tbfreq();
 
         /* indicate KVM hypercall interface */
+        qemu_devtree_add_subnode(fdt, "/hypervisor");
         qemu_devtree_setprop_string(fdt, "/hypervisor", "compatible",
                                     "linux,kvm");
         kvmppc_get_hypercall(env, hypercall, sizeof(hypercall));
diff --git a/pc-bios/mpc8544ds.dtb b/pc-bios/mpc8544ds.dtb
index a85b93c..8194aa2 100644
Binary files a/pc-bios/mpc8544ds.dtb and b/pc-bios/mpc8544ds.dtb differ
diff --git a/pc-bios/mpc8544ds.dts b/pc-bios/mpc8544ds.dts
index 1fcb865..2ca7c54 100644
--- a/pc-bios/mpc8544ds.dts
+++ b/pc-bios/mpc8544ds.dts
@@ -103,7 +103,4 @@
 	chosen {
 		linux,stdout-path = "/soc8544 at e0000000/serial at 4500";
 	};
-
-	hypervisor {
-	};
 };
commit 625e665b61184cabce0d556910de05cc8a70169c
Author: Alexander Graf <agraf at suse.de>
Date:   Thu May 17 11:48:16 2012 +0200

    PPC: e500: dt: create /cpus node dynamically
    
    Signed-off-by: Alexander Graf <agraf at suse.de>

diff --git a/hw/ppce500_mpc8544ds.c b/hw/ppce500_mpc8544ds.c
index 3ec9013..c046206 100644
--- a/hw/ppce500_mpc8544ds.c
+++ b/hw/ppce500_mpc8544ds.c
@@ -125,6 +125,11 @@ static int mpc8544_load_device_tree(CPUPPCState *env,
                              hypercall, sizeof(hypercall));
     }
 
+    /* Create CPU nodes */
+    qemu_devtree_add_subnode(fdt, "/cpus");
+    qemu_devtree_setprop_cell(fdt, "/cpus", "#address-cells", 1);
+    qemu_devtree_setprop_cell(fdt, "/cpus", "#size-cells", 0);
+
     /* We need to generate the cpu nodes in reverse order, so Linux can pick
        the first node as boot node and be happy */
     for (i = smp_cpus - 1; i >= 0; i--) {
diff --git a/pc-bios/mpc8544ds.dtb b/pc-bios/mpc8544ds.dtb
index db9fb70..a85b93c 100644
Binary files a/pc-bios/mpc8544ds.dtb and b/pc-bios/mpc8544ds.dtb differ
diff --git a/pc-bios/mpc8544ds.dts b/pc-bios/mpc8544ds.dts
index f46e9ed..1fcb865 100644
--- a/pc-bios/mpc8544ds.dts
+++ b/pc-bios/mpc8544ds.dts
@@ -22,11 +22,6 @@
 		pci0 = &pci0;
 	};
 
-	cpus {
-		#address-cells = <1>;
-		#size-cells = <0>;
-	};
-
 	soc8544 at e0000000 {
 		#address-cells = <1>;
 		#size-cells = <1>;
commit dd0bcfca64d12f557fae67a0ca318bf9b5579dd9
Author: Alexander Graf <agraf at suse.de>
Date:   Thu May 17 11:34:50 2012 +0200

    PPC: e500: dt: create memory node dynamically
    
    Signed-off-by: Alexander Graf <agraf at suse.de>

diff --git a/hw/ppce500_mpc8544ds.c b/hw/ppce500_mpc8544ds.c
index 506ddf3..3ec9013 100644
--- a/hw/ppce500_mpc8544ds.c
+++ b/hw/ppce500_mpc8544ds.c
@@ -88,10 +88,10 @@ static int mpc8544_load_device_tree(CPUPPCState *env,
     }
 
     /* Manipulate device tree in memory. */
-    ret = qemu_devtree_setprop(fdt, "/memory", "reg", mem_reg_property,
-                               sizeof(mem_reg_property));
-    if (ret < 0)
-        fprintf(stderr, "couldn't set /memory/reg\n");
+    qemu_devtree_add_subnode(fdt, "/memory");
+    qemu_devtree_setprop_string(fdt, "/memory", "device_type", "memory");
+    qemu_devtree_setprop(fdt, "/memory", "reg", mem_reg_property,
+                         sizeof(mem_reg_property));
 
     if (initrd_size) {
         ret = qemu_devtree_setprop_cell(fdt, "/chosen", "linux,initrd-start",
diff --git a/pc-bios/mpc8544ds.dtb b/pc-bios/mpc8544ds.dtb
index c6d3021..db9fb70 100644
Binary files a/pc-bios/mpc8544ds.dtb and b/pc-bios/mpc8544ds.dtb differ
diff --git a/pc-bios/mpc8544ds.dts b/pc-bios/mpc8544ds.dts
index 7eb3160..f46e9ed 100644
--- a/pc-bios/mpc8544ds.dts
+++ b/pc-bios/mpc8544ds.dts
@@ -27,11 +27,6 @@
 		#size-cells = <0>;
 	};
 
-	memory {
-		device_type = "memory";
-		reg = <0x0 0x0>;	// Filled by U-Boot
-	};
-
 	soc8544 at e0000000 {
 		#address-cells = <1>;
 		#size-cells = <1>;
commit 63397dd0be8d03d62393620e8192dafe0db72f8f
Author: Alexander Graf <agraf at suse.de>
Date:   Thu May 17 12:23:41 2012 +0200

    PPC: e500: require libfdt
    
    Now that we're moving all of the device tree generation from an external
    pre-execution generated blob to runtime generation using libfdt, we absolutely
    must have libfdt around.
    
    This requirement was there before already, as the only way to not require libfdt
    with e500 was to not use -kernel, which was the only way to boot the mpc8544ds
    machine. This patch only manifests said requirement in the build system.
    
    Signed-off-by: Alexander Graf <agraf at suse.de>

diff --git a/hw/ppc/Makefile.objs b/hw/ppc/Makefile.objs
index 44a1e8c..d18dbaf 100644
--- a/hw/ppc/Makefile.objs
+++ b/hw/ppc/Makefile.objs
@@ -15,7 +15,7 @@ obj-$(CONFIG_PSERIES) += spapr_pci.o pci-hotplug.o
 obj-y += ppc4xx_devs.o ppc4xx_pci.o ppc405_uc.o ppc405_boards.o
 obj-y += ppc440_bamboo.o
 # PowerPC E500 boards
-obj-y += ppce500_mpc8544ds.o mpc8544_guts.o ppce500_spin.o
+obj-$(CONFIG_FDT) += ppce500_mpc8544ds.o mpc8544_guts.o ppce500_spin.o
 # PowerPC 440 Xilinx ML507 reference board.
 obj-y += virtex_ml507.o
 # PowerPC OpenPIC
diff --git a/hw/ppce500_mpc8544ds.c b/hw/ppce500_mpc8544ds.c
index b1a0b8c..506ddf3 100644
--- a/hw/ppce500_mpc8544ds.c
+++ b/hw/ppce500_mpc8544ds.c
@@ -68,7 +68,6 @@ static int mpc8544_load_device_tree(CPUPPCState *env,
                                     const char *kernel_cmdline)
 {
     int ret = -1;
-#ifdef CONFIG_FDT
     uint32_t mem_reg_property[] = {0, cpu_to_be32(ramsize)};
     char *filename;
     int fdt_size;
@@ -173,7 +172,6 @@ static int mpc8544_load_device_tree(CPUPPCState *env,
     ret = fdt_size;
 
 out:
-#endif
 
     return ret;
 }
@@ -391,9 +389,6 @@ static void mpc8544ds_init(ram_addr_t ram_size,
         struct boot_info *boot_info;
         int dt_size;
 
-#ifndef CONFIG_FDT
-        cpu_abort(env, "Compiled without FDT support - can't load kernel\n");
-#endif
         dt_base = (loadaddr + kernel_size + DTC_LOAD_PAD) & ~DTC_PAD_MASK;
         dt_size = mpc8544_load_device_tree(env, dt_base, ram_size, initrd_base,
                                            initrd_size, kernel_cmdline);
commit bb28eb3797b0fbb4baa6d87edf69b3a0ff499e94
Author: Alexander Graf <agraf at suse.de>
Date:   Fri May 18 01:53:01 2012 +0200

    dt: add helper for 64bit cell adds
    
    Some times in the device tree, we find an array of 2 u32 cells that
    really are a single u64 value. This patch adds a helper to make the
    creation of these easy.
    
    Signed-off-by: Alexander Graf <agraf at suse.de>
    Reviewed-by: Peter Crosthwaite <peter.crosthwaite at petalogix.com>

diff --git a/device_tree.c b/device_tree.c
index 7541274..c8d68c2 100644
--- a/device_tree.c
+++ b/device_tree.c
@@ -154,6 +154,13 @@ int qemu_devtree_setprop_cell(void *fdt, const char *node_path,
     return r;
 }
 
+int qemu_devtree_setprop_u64(void *fdt, const char *node_path,
+                             const char *property, uint64_t val)
+{
+    val = cpu_to_be64(val);
+    return qemu_devtree_setprop(fdt, node_path, property, &val, sizeof(val));
+}
+
 int qemu_devtree_setprop_string(void *fdt, const char *node_path,
                                 const char *property, const char *string)
 {
diff --git a/device_tree.h b/device_tree.h
index 97af345..4898d95 100644
--- a/device_tree.h
+++ b/device_tree.h
@@ -21,6 +21,8 @@ int qemu_devtree_setprop(void *fdt, const char *node_path,
                          const char *property, void *val_array, int size);
 int qemu_devtree_setprop_cell(void *fdt, const char *node_path,
                               const char *property, uint32_t val);
+int qemu_devtree_setprop_u64(void *fdt, const char *node_path,
+                             const char *property, uint64_t val);
 int qemu_devtree_setprop_string(void *fdt, const char *node_path,
                                 const char *property, const char *string);
 int qemu_devtree_setprop_phandle(void *fdt, const char *node_path,
commit 3601b572820ee5f3676ab24c068a4e011b72236d
Author: Alexander Graf <agraf at suse.de>
Date:   Thu May 17 16:58:55 2012 +0200

    dt: add helper for phandle allocation
    
    Phandle references work by having 2 pieces:
    
      - a "phandle" 1-cell property in the device tree node
      - a reference to the same value in a property we want to point
        to the other node
    
    To generate the 1-cell property, we need an allocation mechanism that
    gives us a unique number space. This patch adds an allocator for these
    properties.
    
    Signed-off-by: Alexander Graf <agraf at suse.de>

diff --git a/device_tree.c b/device_tree.c
index d037896..7541274 100644
--- a/device_tree.c
+++ b/device_tree.c
@@ -191,6 +191,13 @@ int qemu_devtree_setprop_phandle(void *fdt, const char *node_path,
     return qemu_devtree_setprop_cell(fdt, node_path, property, phandle);
 }
 
+uint32_t qemu_devtree_alloc_phandle(void *fdt)
+{
+    static int phandle = 0x8000;
+
+    return phandle++;
+}
+
 int qemu_devtree_nop_node(void *fdt, const char *node_path)
 {
     int r;
diff --git a/device_tree.h b/device_tree.h
index 5f76f40..97af345 100644
--- a/device_tree.h
+++ b/device_tree.h
@@ -27,6 +27,7 @@ int qemu_devtree_setprop_phandle(void *fdt, const char *node_path,
                                  const char *property,
                                  const char *target_node_path);
 uint32_t qemu_devtree_get_phandle(void *fdt, const char *path);
+uint32_t qemu_devtree_alloc_phandle(void *fdt);
 int qemu_devtree_nop_node(void *fdt, const char *node_path);
 int qemu_devtree_add_subnode(void *fdt, const char *name);
 
commit ce36252cc1711a5e222ed68e72235088aec2529d
Author: Alexander Graf <agraf at suse.de>
Date:   Thu May 17 15:33:54 2012 +0200

    dt: add helper for empty dt creation
    
    We want to get rid of the concept of loading an external device tree and instead
    generate our own. However, to do this we need to also create a device tree
    template programatically.
    
    This patch adds a helper to create an empty device tree in memory.
    
    Signed-off-by: Alexander Graf <agraf at suse.de>
    Reviewed-by: Peter Crosthwaite <peter.crosthwaite at petalogix.com>

diff --git a/device_tree.c b/device_tree.c
index 2f127b7..d037896 100644
--- a/device_tree.c
+++ b/device_tree.c
@@ -25,6 +25,43 @@
 
 #include <libfdt.h>
 
+#define FDT_MAX_SIZE  0x10000
+
+void *create_device_tree(int *sizep)
+{
+    void *fdt;
+    int ret;
+
+    *sizep = FDT_MAX_SIZE;
+    fdt = g_malloc0(FDT_MAX_SIZE);
+    ret = fdt_create(fdt, FDT_MAX_SIZE);
+    if (ret < 0) {
+        goto fail;
+    }
+    ret = fdt_begin_node(fdt, "");
+    if (ret < 0) {
+        goto fail;
+    }
+    ret = fdt_end_node(fdt);
+    if (ret < 0) {
+        goto fail;
+    }
+    ret = fdt_finish(fdt);
+    if (ret < 0) {
+        goto fail;
+    }
+    ret = fdt_open_into(fdt, fdt, *sizep);
+    if (ret) {
+        fprintf(stderr, "Unable to copy device tree in memory\n");
+        exit(1);
+    }
+
+    return fdt;
+fail:
+    fprintf(stderr, "%s Couldn't create dt: %s\n", __func__, fdt_strerror(ret));
+    exit(1);
+}
+
 void *load_device_tree(const char *filename_path, int *sizep)
 {
     int dt_size;
diff --git a/device_tree.h b/device_tree.h
index 36fc9db..5f76f40 100644
--- a/device_tree.h
+++ b/device_tree.h
@@ -14,6 +14,7 @@
 #ifndef __DEVICE_TREE_H__
 #define __DEVICE_TREE_H__
 
+void *create_device_tree(int *sizep);
 void *load_device_tree(const char *filename_path, int *sizep);
 
 int qemu_devtree_setprop(void *fdt, const char *node_path,
commit 7d5fd1089c36391ffc53a694101f441ab8cbbc05
Author: Alexander Graf <agraf at suse.de>
Date:   Thu May 17 15:23:39 2012 +0200

    dt: add helper for phandle enumeration
    
    This patch adds a helper to search for a node's phandle by its path. This
    is especially useful when the phandle is part of an array, not just a single
    cell in which case qemu_devtree_setprop_phandle would be the easy choice.
    
    Signed-off-by: Alexander Graf <agraf at suse.de>
    Reviewed-by: Peter Crosthwaite <peter.crosthwaite at petalogix.com>

diff --git a/device_tree.c b/device_tree.c
index 967c97a..2f127b7 100644
--- a/device_tree.c
+++ b/device_tree.c
@@ -132,11 +132,25 @@ int qemu_devtree_setprop_string(void *fdt, const char *node_path,
     return r;
 }
 
+uint32_t qemu_devtree_get_phandle(void *fdt, const char *path)
+{
+    uint32_t r;
+
+    r = fdt_get_phandle(fdt, findnode_nofail(fdt, path));
+    if (r <= 0) {
+        fprintf(stderr, "%s: Couldn't get phandle for %s: %s\n", __func__,
+                path, fdt_strerror(r));
+        exit(1);
+    }
+
+    return r;
+}
+
 int qemu_devtree_setprop_phandle(void *fdt, const char *node_path,
                                  const char *property,
                                  const char *target_node_path)
 {
-    uint32_t phandle = fdt_get_phandle(fdt, findnode_nofail(fdt, target_node_path));
+    uint32_t phandle = qemu_devtree_get_phandle(fdt, target_node_path);
     return qemu_devtree_setprop_cell(fdt, node_path, property, phandle);
 }
 
diff --git a/device_tree.h b/device_tree.h
index 754bd2b..36fc9db 100644
--- a/device_tree.h
+++ b/device_tree.h
@@ -25,6 +25,7 @@ int qemu_devtree_setprop_string(void *fdt, const char *node_path,
 int qemu_devtree_setprop_phandle(void *fdt, const char *node_path,
                                  const char *property,
                                  const char *target_node_path);
+uint32_t qemu_devtree_get_phandle(void *fdt, const char *path);
 int qemu_devtree_nop_node(void *fdt, const char *node_path);
 int qemu_devtree_add_subnode(void *fdt, const char *name);
 
commit ef5d833fc6f04119ded9fca294d26ce225d69490
Author: Alexander Graf <agraf at suse.de>
Date:   Thu May 17 14:12:57 2012 +0200

    dt: temporarily disable subtree creation failure check
    
    Usually we want to know when creating a subtree fails. However, while
    introducing this patch set we have to modify the device tree and some
    times have the code to create a subtree in both the binary tree and
    the dynamically created tree.
    
    So ignore failures about this for now and enable them once we got rid
    of the binary device tree.
    
    Signed-off-by: Alexander Graf <agraf at suse.de>

diff --git a/device_tree.c b/device_tree.c
index 2905f9a..967c97a 100644
--- a/device_tree.c
+++ b/device_tree.c
@@ -174,11 +174,13 @@ int qemu_devtree_add_subnode(void *fdt, const char *name)
     }
 
     retval = fdt_add_subnode(fdt, parent, basename);
+#if 0
     if (retval < 0) {
         fprintf(stderr, "FDT: Failed to create subnode %s: %s\n", name,
                 fdt_strerror(retval));
         exit(1);
     }
+#endif
 
     g_free(dupname);
     return retval;
commit 8535ab125853d1ba9067ba408c532c2ad79146e6
Author: Alexander Graf <agraf at suse.de>
Date:   Thu May 17 14:11:52 2012 +0200

    dt: add helper for phandle references
    
    Phandles are the fancy device tree name for "pointer to another node".
    To create a phandle property, we most likely want to reference to the
    node we're pointing to by its path. So create a helper that allows
    us to do so.
    
    Signed-off-by: Alexander Graf <agraf at suse.de>
    Reviewed-by: Peter Crosthwaite <peter.crosthwaite at petalogix.com>

diff --git a/device_tree.c b/device_tree.c
index 94a239e..2905f9a 100644
--- a/device_tree.c
+++ b/device_tree.c
@@ -132,6 +132,14 @@ int qemu_devtree_setprop_string(void *fdt, const char *node_path,
     return r;
 }
 
+int qemu_devtree_setprop_phandle(void *fdt, const char *node_path,
+                                 const char *property,
+                                 const char *target_node_path)
+{
+    uint32_t phandle = fdt_get_phandle(fdt, findnode_nofail(fdt, target_node_path));
+    return qemu_devtree_setprop_cell(fdt, node_path, property, phandle);
+}
+
 int qemu_devtree_nop_node(void *fdt, const char *node_path)
 {
     int r;
diff --git a/device_tree.h b/device_tree.h
index 1e671e2..754bd2b 100644
--- a/device_tree.h
+++ b/device_tree.h
@@ -22,6 +22,9 @@ int qemu_devtree_setprop_cell(void *fdt, const char *node_path,
                               const char *property, uint32_t val);
 int qemu_devtree_setprop_string(void *fdt, const char *node_path,
                                 const char *property, const char *string);
+int qemu_devtree_setprop_phandle(void *fdt, const char *node_path,
+                                 const char *property,
+                                 const char *target_node_path);
 int qemu_devtree_nop_node(void *fdt, const char *node_path);
 int qemu_devtree_add_subnode(void *fdt, const char *name);
 
commit 7ae2291e8e0f34ac520044c8af0437a701e1c967
Author: Alexander Graf <agraf at suse.de>
Date:   Thu May 17 12:47:57 2012 +0200

    dt: add helpers for multi-cell adds
    
    We have device tree helpers that allow us to create single cell (u32)
    wide properties. However, when creating properties that contain an array of
    cells, we need to jump through hoops, manually passing in an array with
    converted endianness.
    
    To ease the pain of this, create a generic macro helper that allows us
    to pass the cells as arguments.
    
    Signed-off-by: Alexander Graf <agraf at suse.de>
    Reviewed-by: Peter Crosthwaite <peter.crosthwaite at petalogix.com>

diff --git a/device_tree.h b/device_tree.h
index 4378685..1e671e2 100644
--- a/device_tree.h
+++ b/device_tree.h
@@ -25,4 +25,16 @@ int qemu_devtree_setprop_string(void *fdt, const char *node_path,
 int qemu_devtree_nop_node(void *fdt, const char *node_path);
 int qemu_devtree_add_subnode(void *fdt, const char *name);
 
+#define qemu_devtree_setprop_cells(fdt, node_path, property, ...)             \
+    do {                                                                      \
+        uint32_t qdt_tmp[] = { __VA_ARGS__ };                                 \
+        int i;                                                                \
+                                                                              \
+        for (i = 0; i < ARRAY_SIZE(qdt_tmp); i++) {                           \
+            qdt_tmp[i] = cpu_to_be32(qdt_tmp[i]);                             \
+        }                                                                     \
+        qemu_devtree_setprop(fdt, node_path, property, qdt_tmp,               \
+                             sizeof(qdt_tmp));                                \
+    } while (0)
+
 #endif /* __DEVICE_TREE_H__ */
commit c640d088349acaf23161e7afb3dfeb5d6a7007f1
Author: Alexander Graf <agraf at suse.de>
Date:   Thu May 17 11:40:42 2012 +0200

    dt: allow add_subnode to create root subnodes
    
    Our subnode creation helper can't handle creation of root subnodes,
    like "/memory". Fix this by allowing the parent node to be an empty
    string, indicating the root node.
    
    Signed-off-by: Alexander Graf <agraf at suse.de>
    Reviewed-by: Peter Crosthwaite <peter.crosthwaite at petalogix.com>

diff --git a/device_tree.c b/device_tree.c
index 86a694c..94a239e 100644
--- a/device_tree.c
+++ b/device_tree.c
@@ -151,6 +151,7 @@ int qemu_devtree_add_subnode(void *fdt, const char *name)
     char *dupname = g_strdup(name);
     char *basename = strrchr(dupname, '/');
     int retval;
+    int parent = 0;
 
     if (!basename) {
         g_free(dupname);
@@ -160,7 +161,11 @@ int qemu_devtree_add_subnode(void *fdt, const char *name)
     basename[0] = '\0';
     basename++;
 
-    retval = fdt_add_subnode(fdt, findnode_nofail(fdt, dupname), basename);
+    if (dupname[0]) {
+        parent = findnode_nofail(fdt, dupname);
+    }
+
+    retval = fdt_add_subnode(fdt, parent, basename);
     if (retval < 0) {
         fprintf(stderr, "FDT: Failed to create subnode %s: %s\n", name,
                 fdt_strerror(retval));
commit 94282e714628ee4b130b46f3b06b34da45b2fe6a
Author: Kevin Wolf <kwolf at redhat.com>
Date:   Tue Jun 19 22:02:51 2012 +0000

    raw-posix: Fix build without is_allocated support
    
    Move the declaration of s into the #ifdef sections that actually make
    use of it.
    
    Signed-off-by: Kevin Wolf <kwolf at redhat.com>
    Signed-off-by: Alexander Graf <agraf at suse.de>

diff --git a/block/raw-posix.c b/block/raw-posix.c
index bf7700a..0dce089 100644
--- a/block/raw-posix.c
+++ b/block/raw-posix.c
@@ -606,7 +606,6 @@ static int coroutine_fn raw_co_is_allocated(BlockDriverState *bs,
                                             int64_t sector_num,
                                             int nb_sectors, int *pnum)
 {
-    BDRVRawState *s = bs->opaque;
     off_t start, data, hole;
     int ret;
 
@@ -616,11 +615,15 @@ static int coroutine_fn raw_co_is_allocated(BlockDriverState *bs,
     }
 
     start = sector_num * BDRV_SECTOR_SIZE;
+
 #ifdef CONFIG_FIEMAP
+
+    BDRVRawState *s = bs->opaque;
     struct {
         struct fiemap fm;
         struct fiemap_extent fe;
     } f;
+
     f.fm.fm_start = start;
     f.fm.fm_length = (int64_t)nb_sectors * BDRV_SECTOR_SIZE;
     f.fm.fm_flags = 0;
@@ -643,7 +646,11 @@ static int coroutine_fn raw_co_is_allocated(BlockDriverState *bs,
         data = f.fe.fe_logical;
         hole = f.fe.fe_logical + f.fe.fe_length;
     }
+
 #elif defined SEEK_HOLE && defined SEEK_DATA
+
+    BDRVRawState *s = bs->opaque;
+
     hole = lseek(s->fd, start, SEEK_HOLE);
     if (hole == -1) {
         /* -ENXIO indicates that sector_num was past the end of the file.
commit c73e3771ea79ab3898da3ba51ff6fc5b05948d85
Author: Benjamin Herrenschmidt <benh at kernel.crashing.org>
Date:   Mon Jun 18 20:21:37 2012 +0000

    spapr: Add "memop" hypercall
    
    This adds a qemu-specific hypervisor call to the pseries machine
    which allows to do what amounts to memmove, memcpy and xor over
    regions of physical memory such as the framebuffer.
    
    This is the simplest way to get usable framebuffer speed from
    SLOF since the framebuffer isn't mapped in the VRMA and so would
    otherwise require an hcall per 8 bytes access.
    
    The performance is still not great but usable, and can be improved
    with a more complex implementation of the hcall itself if needed.
    
    This also adds some documentation for the qemu-specific hypercalls
    that we add to PAPR along with a new qemu,hypertas-functions property
    that mirrors ibm,hypertas-functions and provides some discoverability
    for the new calls.
    
    Note: I chose note to advertise H_RTAS to the guest via that mechanism.
    This is done on purpose, the guest uses the normal RTAS interfaces
    provided by qemu (including SLOF) which internally calls H_RTAS.
    
    We might in the future implement part (or even all) of RTAS inside the
    guest like IBM's firmware does and replace H_RTAS with some finer grained
    set of private hypercalls.
    
    Signed-off-by: Benjamin Herrenschmidt <benh at kernel.crashing.org>
    Signed-off-by: Alexander Graf <agraf at suse.de>

diff --git a/docs/specs/ppc-spapr-hcalls.txt b/docs/specs/ppc-spapr-hcalls.txt
new file mode 100644
index 0000000..52ba8d4
--- /dev/null
+++ b/docs/specs/ppc-spapr-hcalls.txt
@@ -0,0 +1,78 @@
+When used with the "pseries" machine type, QEMU-system-ppc64 implements
+a set of hypervisor calls using a subset of the server "PAPR" specification
+(IBM internal at this point), which is also what IBM's proprietary hypervisor
+adheres too.
+
+The subset is selected based on the requirements of Linux as a guest.
+
+In addition to those calls, we have added our own private hypervisor
+calls which are mostly used as a private interface between the firmware
+running in the guest and QEMU.
+
+All those hypercalls start at hcall number 0xf000 which correspond
+to a implementation specific range in PAPR.
+
+- H_RTAS (0xf000)
+
+RTAS is a set of runtime services generally provided by the firmware
+inside the guest to the operating system. It predates the existence
+of hypervisors (it was originally an extension to Open Firmware) and
+is still used by PAPR to provide various services that aren't performance
+sensitive.
+
+We currently implement the RTAS services in QEMU itself. The actual RTAS
+"firmware" blob in the guest is a small stub of a few instructions which
+calls our private H_RTAS hypervisor call to pass the RTAS calls to QEMU.
+
+Arguments:
+
+  r3 : H_RTAS (0xf000)
+  r4 : Guest physical address of RTAS parameter block
+
+Returns:
+
+  H_SUCCESS   : Successully called the RTAS function (RTAS result
+                will have been stored in the parameter block)
+  H_PARAMETER : Unknown token
+
+- H_LOGICAL_MEMOP (0xf001)
+
+When the guest runs in "real mode" (in powerpc lingua this means
+with MMU disabled, ie guest effective == guest physical), it only
+has access to a subset of memory and no IOs.
+
+PAPR provides a set of hypervisor calls to perform cachable or
+non-cachable accesses to any guest physical addresses that the
+guest can use in order to access IO devices while in real mode.
+
+This is typically used by the firmware running in the guest.
+
+However, doing a hypercall for each access is extremely inefficient
+(even more so when running KVM) when accessing the frame buffer. In
+that case, things like scrolling become unusably slow.
+
+This hypercall allows the guest to request a "memory op" to be applied
+to memory. The supported memory ops at this point are to copy a range
+of memory (supports overlap of source and destination) and XOR which
+is used by our SLOF firmware to invert the screen.
+
+Arguments:
+
+  r3: H_LOGICAL_MEMOP (0xf001)
+  r4: Guest physical address of destination
+  r5: Guest physical address of source
+  r6: Individual element size
+        0 = 1 byte
+        1 = 2 bytes
+        2 = 4 bytes
+        3 = 8 bytes
+  r7: Number of elements
+  r8: Operation
+        0 = copy
+        1 = xor
+
+Returns:
+
+  H_SUCCESS   : Success
+  H_PARAMETER : Invalid argument
+
diff --git a/hw/spapr.c b/hw/spapr.c
index 1b01d64..09a23ff 100644
--- a/hw/spapr.c
+++ b/hw/spapr.c
@@ -197,6 +197,7 @@ static void *spapr_create_fdt_skel(const char *cpu_model,
     uint32_t pft_size_prop[] = {0, cpu_to_be32(hash_shift)};
     char hypertas_prop[] = "hcall-pft\0hcall-term\0hcall-dabr\0hcall-interrupt"
         "\0hcall-tce\0hcall-vio\0hcall-splpar\0hcall-bulk";
+    char qemu_hypertas_prop[] = "hcall-memop1";
     uint32_t interrupt_server_ranges_prop[] = {0, cpu_to_be32(smp_cpus)};
     int i;
     char *modelname;
@@ -417,6 +418,8 @@ static void *spapr_create_fdt_skel(const char *cpu_model,
 
     _FDT((fdt_property(fdt, "ibm,hypertas-functions", hypertas_prop,
                        sizeof(hypertas_prop))));
+    _FDT((fdt_property(fdt, "qemu,hypertas-functions", qemu_hypertas_prop,
+                       sizeof(qemu_hypertas_prop))));
 
     _FDT((fdt_property(fdt, "ibm,associativity-reference-points",
         refpoints, sizeof(refpoints))));
diff --git a/hw/spapr.h b/hw/spapr.h
index 654a7a8..c75172e 100644
--- a/hw/spapr.h
+++ b/hw/spapr.h
@@ -264,7 +264,8 @@ typedef struct sPAPREnvironment {
  */
 #define KVMPPC_HCALL_BASE       0xf000
 #define KVMPPC_H_RTAS           (KVMPPC_HCALL_BASE + 0x0)
-#define KVMPPC_HCALL_MAX        KVMPPC_H_RTAS
+#define KVMPPC_H_LOGICAL_MEMOP  (KVMPPC_HCALL_BASE + 0x1)
+#define KVMPPC_HCALL_MAX        KVMPPC_H_LOGICAL_MEMOP
 
 extern sPAPREnvironment *spapr;
 
diff --git a/hw/spapr_hcall.c b/hw/spapr_hcall.c
index 94bb504..a5990a9 100644
--- a/hw/spapr_hcall.c
+++ b/hw/spapr_hcall.c
@@ -608,6 +608,73 @@ static target_ulong h_logical_store(CPUPPCState *env, sPAPREnvironment *spapr,
     return H_PARAMETER;
 }
 
+static target_ulong h_logical_memop(CPUPPCState *env, sPAPREnvironment *spapr,
+                                    target_ulong opcode, target_ulong *args)
+{
+    target_ulong dst   = args[0]; /* Destination address */
+    target_ulong src   = args[1]; /* Source address */
+    target_ulong esize = args[2]; /* Element size (0=1,1=2,2=4,3=8) */
+    target_ulong count = args[3]; /* Element count */
+    target_ulong op    = args[4]; /* 0 = copy, 1 = invert */
+    uint64_t tmp;
+    unsigned int mask = (1 << esize) - 1;
+    int step = 1 << esize;
+
+    if (count > 0x80000000) {
+        return H_PARAMETER;
+    }
+
+    if ((dst & mask) || (src & mask) || (op > 1)) {
+        return H_PARAMETER;
+    }
+
+    if (dst >= src && dst < (src + (count << esize))) {
+            dst = dst + ((count - 1) << esize);
+            src = src + ((count - 1) << esize);
+            step = -step;
+    }
+
+    while (count--) {
+        switch (esize) {
+        case 0:
+            tmp = ldub_phys(src);
+            break;
+        case 1:
+            tmp = lduw_phys(src);
+            break;
+        case 2:
+            tmp = ldl_phys(src);
+            break;
+        case 3:
+            tmp = ldq_phys(src);
+            break;
+        default:
+            return H_PARAMETER;
+        }
+        if (op == 1) {
+            tmp = ~tmp;
+        }
+        switch (esize) {
+        case 0:
+            stb_phys(dst, tmp);
+            break;
+        case 1:
+            stw_phys(dst, tmp);
+            break;
+        case 2:
+            stl_phys(dst, tmp);
+            break;
+        case 3:
+            stq_phys(dst, tmp);
+            break;
+        }
+        dst = dst + step;
+        src = src + step;
+    }
+
+    return H_SUCCESS;
+}
+
 static target_ulong h_logical_icbi(CPUPPCState *env, sPAPREnvironment *spapr,
                                    target_ulong opcode, target_ulong *args)
 {
@@ -700,6 +767,7 @@ static void hypercall_register_types(void)
     spapr_register_hypercall(H_LOGICAL_CACHE_STORE, h_logical_store);
     spapr_register_hypercall(H_LOGICAL_ICBI, h_logical_icbi);
     spapr_register_hypercall(H_LOGICAL_DCBF, h_logical_dcbf);
+    spapr_register_hypercall(KVMPPC_H_LOGICAL_MEMOP, h_logical_memop);
 
     /* qemu/KVM-PPC specific hcalls */
     spapr_register_hypercall(KVMPPC_H_RTAS, h_rtas);
commit a4d8e8daee324e230b0155915f562743f4fff5d8
Author: Benjamin Herrenschmidt <benh at kernel.crashing.org>
Date:   Mon Jun 18 20:02:38 2012 +0000

    spapr_vscsi: Error handling fixes
    
    We were incorrectly g_free'ing an object that isn't allocated
    in one error path and failed to release it completely in another
    
    This fixes qemu crashes with some cases of IO errors.
    
    Signed-off-by: Benjamin Herrenschmidt <benh at kernel.crashing.org>
    Signed-off-by: Alexander Graf <agraf at suse.de>

diff --git a/hw/spapr_vscsi.c b/hw/spapr_vscsi.c
index 037867a..2f09616 100644
--- a/hw/spapr_vscsi.c
+++ b/hw/spapr_vscsi.c
@@ -800,6 +800,7 @@ static void vscsi_got_payload(VSCSIState *s, vscsi_crq *crq)
     if (crq->s.IU_length > sizeof(union viosrp_iu)) {
         fprintf(stderr, "VSCSI: SRP IU too long (%d bytes) !\n",
                 crq->s.IU_length);
+        vscsi_put_req(req);
         return;
     }
 
@@ -807,7 +808,8 @@ static void vscsi_got_payload(VSCSIState *s, vscsi_crq *crq)
     if (spapr_tce_dma_read(&s->vdev, crq->s.IU_data_ptr, &req->iu,
                            crq->s.IU_length)) {
         fprintf(stderr, "vscsi_got_payload: DMA read failure !\n");
-        g_free(req);
+        vscsi_put_req(req);
+        return;
     }
     memcpy(&req->crq, crq, sizeof(vscsi_crq));
 
commit 5af9873d301cf5affec57e2f93650e8700f8251a
Author: Benjamin Herrenschmidt <benh at kernel.crashing.org>
Date:   Mon Jun 18 19:56:30 2012 +0000

    pseries: Correctly create ibm,segment-page-sizes property
    
    The core tcg/kvm code for ppc64 now has at least the outline
    capability to support pagesizes beyond the standard 4k and 16MB.  The
    CPUState is initialized with information advertising the available
    pagesizes and their correct encodings, and under the right KVM setup
    this will be populated with page sizes beyond the standard.
    
    Obviously guests can't use the extra page sizes unless they know
    they're present.  For the pseries machine, at least, there is a
    defined method for conveying exactly this information, the
    "ibm-segment-page-sizes" property in the guest device tree.
    
    This patch generates this property using the supported page size
    information that's already in the CPUState.
    
    Signed-off-by: Nishanth Aravamudan <nacc at us.ibm.com>
    Signed-off-by: David Gibson <david at gibson.dropbear.id.au>
    Signed-off-by: Benjamin Herrenschmidt <benh at kernel.crashing.org>
    Signed-off-by: Alexander Graf <agraf at suse.de>

diff --git a/hw/spapr.c b/hw/spapr.c
index d0bddbc..1b01d64 100644
--- a/hw/spapr.c
+++ b/hw/spapr.c
@@ -146,6 +146,40 @@ static int spapr_set_associativity(void *fdt, sPAPREnvironment *spapr)
     return ret;
 }
 
+
+static size_t create_page_sizes_prop(CPUPPCState *env, uint32_t *prop,
+                                     size_t maxsize)
+{
+    size_t maxcells = maxsize / sizeof(uint32_t);
+    int i, j, count;
+    uint32_t *p = prop;
+
+    for (i = 0; i < PPC_PAGE_SIZES_MAX_SZ; i++) {
+        struct ppc_one_seg_page_size *sps = &env->sps.sps[i];
+
+        if (!sps->page_shift) {
+            break;
+        }
+        for (count = 0; count < PPC_PAGE_SIZES_MAX_SZ; count++) {
+            if (sps->enc[count].page_shift == 0) {
+                break;
+            }
+        }
+        if ((p - prop) >= (maxcells - 3 - count * 2)) {
+            break;
+        }
+        *(p++) = cpu_to_be32(sps->page_shift);
+        *(p++) = cpu_to_be32(sps->slb_enc);
+        *(p++) = cpu_to_be32(count);
+        for (j = 0; j < count; j++) {
+            *(p++) = cpu_to_be32(sps->enc[j].page_shift);
+            *(p++) = cpu_to_be32(sps->enc[j].pte_enc);
+        }
+    }
+
+    return (p - prop) * sizeof(uint32_t);
+}
+
 static void *spapr_create_fdt_skel(const char *cpu_model,
                                    target_phys_addr_t rma_size,
                                    target_phys_addr_t initrd_base,
@@ -298,6 +332,8 @@ static void *spapr_create_fdt_skel(const char *cpu_model,
                            0xffffffff, 0xffffffff};
         uint32_t tbfreq = kvm_enabled() ? kvmppc_get_tbfreq() : TIMEBASE_FREQ;
         uint32_t cpufreq = kvm_enabled() ? kvmppc_get_clockfreq() : 1000000000;
+        uint32_t page_sizes_prop[64];
+        size_t page_sizes_prop_size;
 
         if ((index % smt) != 0) {
             continue;
@@ -362,6 +398,13 @@ static void *spapr_create_fdt_skel(const char *cpu_model,
             _FDT((fdt_property_cell(fdt, "ibm,dfp", 1)));
         }
 
+        page_sizes_prop_size = create_page_sizes_prop(env, page_sizes_prop,
+                                                      sizeof(page_sizes_prop));
+        if (page_sizes_prop_size) {
+            _FDT((fdt_property(fdt, "ibm,segment-page-sizes",
+                               page_sizes_prop, page_sizes_prop_size)));
+        }
+
         _FDT((fdt_end_node(fdt)));
     }
 
commit 4656e1f01289cc3aa20986deb6a407165826abe5
Author: Benjamin Herrenschmidt <benh at kernel.crashing.org>
Date:   Mon Jun 18 19:56:25 2012 +0000

    ppc64: Rudimentary Support for extra page sizes on server CPUs
    
    More recent Power server chips (i.e. based on the 64 bit hash MMU)
    support more than just the traditional 4k and 16M page sizes.  This
    can get quite complicated, because which page sizes are supported,
    which combinations are supported within an MMU segment and how these
    page sizes are encoded both in the SLB entry and the hash PTE can vary
    depending on the CPU model (they are not specified by the
    architecture).  In addition the firmware or hypervisor may not permit
    use of certain page sizes, for various reasons.  Whether various page
    sizes are supported on KVM, for example, depends on whether the PR or
    HV variant of KVM is in use, and on the page size of the memory
    backing the guest's RAM.
    
    This patch adds information to the CPUState and cpu defs to describe
    the supported page sizes and encodings.  Since TCG does not yet
    support any extended page sizes, we just set this to NULL in the
    static CPU definitions, expanding this to the default 4k and 16M page
    sizes when we initialize the cpu state.  When using KVM, however, we
    instead determine available page sizes using the new
    KVM_PPC_GET_SMMU_INFO call.  For old kernels without that call, we use
    some defaults, with some guesswork which should do the right thing for
    existing HV and PR implementations.  The fallback might not be correct
    for future versions, but that's ok, because they'll have
    KVM_PPC_GET_SMMU_INFO.
    
    Signed-off-by: Benjamin Herrenschmidt <benh at kernel.crashing.org>
    Signed-off-by: David Gibson <david at gibson.dropbear.id.au>
    Signed-off-by: Alexander Graf <agraf at suse.de>

diff --git a/target-ppc/cpu.h b/target-ppc/cpu.h
index 9b157f0..67e699c 100644
--- a/target-ppc/cpu.h
+++ b/target-ppc/cpu.h
@@ -119,6 +119,8 @@ enum powerpc_mmu_t {
     POWERPC_MMU_620        = POWERPC_MMU_64 | 0x00000002,
     /* Architecture 2.06 variant                               */
     POWERPC_MMU_2_06       = POWERPC_MMU_64 | POWERPC_MMU_1TSEG | 0x00000003,
+    /* Architecture 2.06 "degraded" (no 1T segments)           */
+    POWERPC_MMU_2_06d      = POWERPC_MMU_64 | 0x00000003,
 #endif /* defined(TARGET_PPC64) */
 };
 
@@ -874,6 +876,29 @@ enum {
 #define DBELL_PIRTAG_MASK              0x3fff
 
 /*****************************************************************************/
+/* Segment page size information, used by recent hash MMUs
+ * The format of this structure mirrors kvm_ppc_smmu_info
+ */
+
+#define PPC_PAGE_SIZES_MAX_SZ   8
+
+struct ppc_one_page_size {
+    uint32_t page_shift;  /* Page shift (or 0) */
+    uint32_t pte_enc;     /* Encoding in the HPTE (>>12) */
+};
+
+struct ppc_one_seg_page_size {
+    uint32_t page_shift;  /* Base page shift of segment (or 0) */
+    uint32_t slb_enc;     /* SLB encoding for BookS */
+    struct ppc_one_page_size enc[PPC_PAGE_SIZES_MAX_SZ];
+};
+
+struct ppc_segment_page_sizes {
+    struct ppc_one_seg_page_size sps[PPC_PAGE_SIZES_MAX_SZ];
+};
+
+
+/*****************************************************************************/
 /* The whole PowerPC CPU context */
 #define NB_MMU_MODES 3
 
@@ -889,6 +914,9 @@ struct ppc_def_t {
     powerpc_input_t bus_model;
     uint32_t flags;
     int bfd_mach;
+#if defined(TARGET_PPC64)
+    const struct ppc_segment_page_sizes *sps;
+#endif
     void (*init_proc)(CPUPPCState *env);
     int  (*check_pow)(CPUPPCState *env);
 };
@@ -1012,6 +1040,9 @@ struct CPUPPCState {
     uint32_t flags;
     uint64_t insns_flags;
     uint64_t insns_flags2;
+#if defined(TARGET_PPC64)
+    struct ppc_segment_page_sizes sps;
+#endif
 
 #if defined(TARGET_PPC64) && !defined(CONFIG_USER_ONLY)
     target_phys_addr_t vpa;
diff --git a/target-ppc/kvm.c b/target-ppc/kvm.c
index c09cc39..b6ef72d 100644
--- a/target-ppc/kvm.c
+++ b/target-ppc/kvm.c
@@ -18,6 +18,7 @@
 #include <sys/types.h>
 #include <sys/ioctl.h>
 #include <sys/mman.h>
+#include <sys/vfs.h>
 
 #include <linux/kvm.h>
 
@@ -167,10 +168,217 @@ static int kvm_booke206_tlb_init(CPUPPCState *env)
     return 0;
 }
 
+
+#if defined(TARGET_PPC64)
+static void kvm_get_fallback_smmu_info(CPUPPCState *env,
+                                       struct kvm_ppc_smmu_info *info)
+{
+    memset(info, 0, sizeof(*info));
+
+    /* We don't have the new KVM_PPC_GET_SMMU_INFO ioctl, so
+     * need to "guess" what the supported page sizes are.
+     *
+     * For that to work we make a few assumptions:
+     *
+     * - If KVM_CAP_PPC_GET_PVINFO is supported we are running "PR"
+     *   KVM which only supports 4K and 16M pages, but supports them
+     *   regardless of the backing store characteritics. We also don't
+     *   support 1T segments.
+     *
+     *   This is safe as if HV KVM ever supports that capability or PR
+     *   KVM grows supports for more page/segment sizes, those versions
+     *   will have implemented KVM_CAP_PPC_GET_SMMU_INFO and thus we
+     *   will not hit this fallback
+     *
+     * - Else we are running HV KVM. This means we only support page
+     *   sizes that fit in the backing store. Additionally we only
+     *   advertize 64K pages if the processor is ARCH 2.06 and we assume
+     *   P7 encodings for the SLB and hash table. Here too, we assume
+     *   support for any newer processor will mean a kernel that
+     *   implements KVM_CAP_PPC_GET_SMMU_INFO and thus doesn't hit
+     *   this fallback.
+     */
+    if (kvm_check_extension(env->kvm_state, KVM_CAP_PPC_GET_PVINFO)) {
+        /* No flags */
+        info->flags = 0;
+        info->slb_size = 64;
+
+        /* Standard 4k base page size segment */
+        info->sps[0].page_shift = 12;
+        info->sps[0].slb_enc = 0;
+        info->sps[0].enc[0].page_shift = 12;
+        info->sps[0].enc[0].pte_enc = 0;
+
+        /* Standard 16M large page size segment */
+        info->sps[1].page_shift = 24;
+        info->sps[1].slb_enc = SLB_VSID_L;
+        info->sps[1].enc[0].page_shift = 24;
+        info->sps[1].enc[0].pte_enc = 0;
+    } else {
+        int i = 0;
+
+        /* HV KVM has backing store size restrictions */
+        info->flags = KVM_PPC_PAGE_SIZES_REAL;
+
+        if (env->mmu_model & POWERPC_MMU_1TSEG) {
+            info->flags |= KVM_PPC_1T_SEGMENTS;
+        }
+
+        if (env->mmu_model == POWERPC_MMU_2_06) {
+            info->slb_size = 32;
+        } else {
+            info->slb_size = 64;
+        }
+
+        /* Standard 4k base page size segment */
+        info->sps[i].page_shift = 12;
+        info->sps[i].slb_enc = 0;
+        info->sps[i].enc[0].page_shift = 12;
+        info->sps[i].enc[0].pte_enc = 0;
+        i++;
+
+        /* 64K on MMU 2.06 */
+        if (env->mmu_model == POWERPC_MMU_2_06) {
+            info->sps[i].page_shift = 16;
+            info->sps[i].slb_enc = 0x110;
+            info->sps[i].enc[0].page_shift = 16;
+            info->sps[i].enc[0].pte_enc = 1;
+            i++;
+        }
+
+        /* Standard 16M large page size segment */
+        info->sps[i].page_shift = 24;
+        info->sps[i].slb_enc = SLB_VSID_L;
+        info->sps[i].enc[0].page_shift = 24;
+        info->sps[i].enc[0].pte_enc = 0;
+    }
+}
+
+static void kvm_get_smmu_info(CPUPPCState *env, struct kvm_ppc_smmu_info *info)
+{
+    int ret;
+
+    if (kvm_check_extension(env->kvm_state, KVM_CAP_PPC_GET_SMMU_INFO)) {
+        ret = kvm_vm_ioctl(env->kvm_state, KVM_PPC_GET_SMMU_INFO, info);
+        if (ret == 0) {
+            return;
+        }
+    }
+
+    kvm_get_fallback_smmu_info(env, info);
+}
+
+static long getrampagesize(void)
+{
+    struct statfs fs;
+    int ret;
+
+    if (!mem_path) {
+        /* guest RAM is backed by normal anonymous pages */
+        return getpagesize();
+    }
+
+    do {
+        ret = statfs(mem_path, &fs);
+    } while (ret != 0 && errno == EINTR);
+
+    if (ret != 0) {
+        fprintf(stderr, "Couldn't statfs() memory path: %s\n",
+                strerror(errno));
+        exit(1);
+    }
+
+#define HUGETLBFS_MAGIC       0x958458f6
+
+    if (fs.f_type != HUGETLBFS_MAGIC) {
+        /* Explicit mempath, but it's ordinary pages */
+        return getpagesize();
+    }
+
+    /* It's hugepage, return the huge page size */
+    return fs.f_bsize;
+}
+
+static bool kvm_valid_page_size(uint32_t flags, long rampgsize, uint32_t shift)
+{
+    if (!(flags & KVM_PPC_PAGE_SIZES_REAL)) {
+        return true;
+    }
+
+    return (1ul << shift) <= rampgsize;
+}
+
+static void kvm_fixup_page_sizes(CPUPPCState *env)
+{
+    static struct kvm_ppc_smmu_info smmu_info;
+    static bool has_smmu_info;
+    long rampagesize;
+    int iq, ik, jq, jk;
+
+    /* We only handle page sizes for 64-bit server guests for now */
+    if (!(env->mmu_model & POWERPC_MMU_64)) {
+        return;
+    }
+
+    /* Collect MMU info from kernel if not already */
+    if (!has_smmu_info) {
+        kvm_get_smmu_info(env, &smmu_info);
+        has_smmu_info = true;
+    }
+
+    rampagesize = getrampagesize();
+
+    /* Convert to QEMU form */
+    memset(&env->sps, 0, sizeof(env->sps));
+
+    for (ik = iq = 0; ik < KVM_PPC_PAGE_SIZES_MAX_SZ; ik++) {
+        struct ppc_one_seg_page_size *qsps = &env->sps.sps[iq];
+        struct kvm_ppc_one_seg_page_size *ksps = &smmu_info.sps[ik];
+
+        if (!kvm_valid_page_size(smmu_info.flags, rampagesize,
+                                 ksps->page_shift)) {
+            continue;
+        }
+        qsps->page_shift = ksps->page_shift;
+        qsps->slb_enc = ksps->slb_enc;
+        for (jk = jq = 0; jk < KVM_PPC_PAGE_SIZES_MAX_SZ; jk++) {
+            if (!kvm_valid_page_size(smmu_info.flags, rampagesize,
+                                     ksps->enc[jk].page_shift)) {
+                continue;
+            }
+            qsps->enc[jq].page_shift = ksps->enc[jk].page_shift;
+            qsps->enc[jq].pte_enc = ksps->enc[jk].pte_enc;
+            if (++jq >= PPC_PAGE_SIZES_MAX_SZ) {
+                break;
+            }
+        }
+        if (++iq >= PPC_PAGE_SIZES_MAX_SZ) {
+            break;
+        }
+    }
+    env->slb_nr = smmu_info.slb_size;
+    if (smmu_info.flags & KVM_PPC_1T_SEGMENTS) {
+        env->mmu_model |= POWERPC_MMU_1TSEG;
+    } else {
+        env->mmu_model &= ~POWERPC_MMU_1TSEG;
+    }
+}
+#else /* defined (TARGET_PPC64) */
+
+static inline void kvm_fixup_page_sizes(CPUPPCState *env)
+{
+}
+
+#endif /* !defined (TARGET_PPC64) */
+
 int kvm_arch_init_vcpu(CPUPPCState *cenv)
 {
     int ret;
 
+    /* Gather server mmu info from KVM and update the CPU state */
+    kvm_fixup_page_sizes(cenv);
+
+    /* Synchronize sregs with kvm */
     ret = kvm_arch_sync_sregs(cenv);
     if (ret) {
         return ret;
diff --git a/target-ppc/kvm_ppc.h b/target-ppc/kvm_ppc.h
index 34ecad3..e2f8703 100644
--- a/target-ppc/kvm_ppc.h
+++ b/target-ppc/kvm_ppc.h
@@ -58,6 +58,11 @@ static inline int kvmppc_get_hypercall(CPUPPCState *env, uint8_t *buf, int buf_l
     return -1;
 }
 
+static inline int kvmppc_read_segment_page_sizes(uint32_t *prop, int maxcells)
+{
+    return -1;
+}
+
 static inline int kvmppc_set_interrupt(CPUPPCState *env, int irq, int level)
 {
     return -1;
diff --git a/target-ppc/mmu_helper.c b/target-ppc/mmu_helper.c
index c4e79d9..d2664ac 100644
--- a/target-ppc/mmu_helper.c
+++ b/target-ppc/mmu_helper.c
@@ -1634,6 +1634,7 @@ void dump_mmu(FILE *f, fprintf_function cpu_fprintf, CPUPPCState *env)
 #if defined(TARGET_PPC64)
     case POWERPC_MMU_64B:
     case POWERPC_MMU_2_06:
+    case POWERPC_MMU_2_06d:
         mmubooks_dump_mmu(f, cpu_fprintf, env);
         break;
 #endif
@@ -1664,6 +1665,7 @@ static inline int check_physical(CPUPPCState *env, mmu_ctx_t *ctx,
     case POWERPC_MMU_620:
     case POWERPC_MMU_64B:
     case POWERPC_MMU_2_06:
+    case POWERPC_MMU_2_06d:
         /* Real address are 60 bits long */
         ctx->raddr &= 0x0FFFFFFFFFFFFFFFULL;
         ctx->prot |= PAGE_WRITE;
@@ -1745,6 +1747,7 @@ int get_physical_address(CPUPPCState *env, mmu_ctx_t *ctx, target_ulong eaddr,
         case POWERPC_MMU_620:
         case POWERPC_MMU_64B:
         case POWERPC_MMU_2_06:
+        case POWERPC_MMU_2_06d:
 #endif
             if (ret < 0) {
                 /* We didn't match any BAT entry or don't have BATs */
@@ -1886,6 +1889,7 @@ int cpu_ppc_handle_mmu_fault(CPUPPCState *env, target_ulong address, int rw,
                 case POWERPC_MMU_620:
                 case POWERPC_MMU_64B:
                 case POWERPC_MMU_2_06:
+                case POWERPC_MMU_2_06d:
 #endif
                     env->exception_index = POWERPC_EXCP_ISI;
                     env->error_code = 0x40000000;
@@ -1997,6 +2001,7 @@ int cpu_ppc_handle_mmu_fault(CPUPPCState *env, target_ulong address, int rw,
                 case POWERPC_MMU_620:
                 case POWERPC_MMU_64B:
                 case POWERPC_MMU_2_06:
+                case POWERPC_MMU_2_06d:
 #endif
                     env->exception_index = POWERPC_EXCP_DSI;
                     env->error_code = 0;
@@ -2326,6 +2331,7 @@ void ppc_tlb_invalidate_all(CPUPPCState *env)
     case POWERPC_MMU_620:
     case POWERPC_MMU_64B:
     case POWERPC_MMU_2_06:
+    case POWERPC_MMU_2_06d:
 #endif /* defined(TARGET_PPC64) */
         tlb_flush(env, 1);
         break;
@@ -2395,6 +2401,7 @@ void ppc_tlb_invalidate_one(CPUPPCState *env, target_ulong addr)
     case POWERPC_MMU_620:
     case POWERPC_MMU_64B:
     case POWERPC_MMU_2_06:
+    case POWERPC_MMU_2_06d:
         /* tlbie invalidate TLBs for all segments */
         /* XXX: given the fact that there are too many segments to invalidate,
          *      and we still don't have a tlb_flush_mask(env, n, mask) in QEMU,
diff --git a/target-ppc/translate_init.c b/target-ppc/translate_init.c
index f6ac589..57027a2 100644
--- a/target-ppc/translate_init.c
+++ b/target-ppc/translate_init.c
@@ -9928,6 +9928,27 @@ int cpu_ppc_register_internal (CPUPPCState *env, const ppc_def_t *def)
     env->bfd_mach = def->bfd_mach;
     env->check_pow = def->check_pow;
 
+#if defined(TARGET_PPC64)
+    if (def->sps)
+        env->sps = *def->sps;
+    else if (env->mmu_model & POWERPC_MMU_64) {
+        /* Use default sets of page sizes */
+        static const struct ppc_segment_page_sizes defsps = {
+            .sps = {
+                { .page_shift = 12, /* 4K */
+                  .slb_enc = 0,
+                  .enc = { { .page_shift = 12, .pte_enc = 0 } }
+                },
+                { .page_shift = 24, /* 16M */
+                  .slb_enc = 0x100,
+                  .enc = { { .page_shift = 24, .pte_enc = 0 } }
+                },
+            },
+        };
+        env->sps = defsps;
+    }
+#endif /* defined(TARGET_PPC64) */
+
     if (kvm_enabled()) {
         if (kvmppc_fixup_cpu(env) != 0) {
             fprintf(stderr, "Unable to virtualize selected CPU with KVM\n");
commit 77c2cf33fe8d272e5375b55c588202a18af0e27c
Author: Fabien Chouteau <chouteau at adacore.com>
Date:   Mon May 21 06:11:06 2012 +0000

    booke_206_tlbwe: Discard invalid bits in MAS2
    
    The size of EPN field in MAS2 depends on page size. This patch adds a
    mask to discard invalid bits in EPN field.
    
    Definition of EPN field from e500v2 RM:
    EPN Effective page number: Depending on page size, only the bits
    associated with a page boundary are valid. Bits that represent offsets
    within a page are ignored and should be cleared.
    
    There is a similar (but more complicated) definition in PowerISA V2.06.
    
    Signed-off-by: Fabien Chouteau <chouteau at adacore.com>
    Signed-off-by: Alexander Graf <agraf at suse.de>

diff --git a/target-ppc/mmu_helper.c b/target-ppc/mmu_helper.c
index d65d290..c4e79d9 100644
--- a/target-ppc/mmu_helper.c
+++ b/target-ppc/mmu_helper.c
@@ -3019,6 +3019,8 @@ void helper_booke206_tlbwe(CPUPPCState *env)
     uint32_t tlbncfg, tlbn;
     ppcmas_tlb_t *tlb;
     uint32_t size_tlb, size_ps;
+    target_ulong mask;
+
 
     switch (env->spr[SPR_BOOKE_MAS0] & MAS0_WQ_MASK) {
     case MAS0_WQ_ALWAYS:
@@ -3081,8 +3083,19 @@ void helper_booke206_tlbwe(CPUPPCState *env)
         tlb->mas1 |= (tlbncfg & TLBnCFG_MINSIZE) >> 12;
     }
 
-    /* XXX needs to change when supporting 64-bit e500 */
-    tlb->mas2 = env->spr[SPR_BOOKE_MAS2] & 0xffffffff;
+    /* Make a mask from TLB size to discard invalid bits in EPN field */
+    mask = ~(booke206_tlb_to_page_size(env, tlb) - 1);
+    /* Add a mask for page attributes */
+    mask |= MAS2_ACM | MAS2_VLE | MAS2_W | MAS2_I | MAS2_M | MAS2_G | MAS2_E;
+
+    if (!msr_cm) {
+        /* Executing a tlbwe instruction in 32-bit mode will set
+         * bits 0:31 of the TLB EPN field to zero.
+         */
+        mask &= 0xffffffff;
+    }
+
+    tlb->mas2 = env->spr[SPR_BOOKE_MAS2] & mask;
 
     if (!(tlbncfg & TLBnCFG_IPROT)) {
         /* no IPROT supported by TLB */
commit c8f803e77a39584af30082b7ba11e69a9f046224
Author: Fabien Chouteau <chouteau at adacore.com>
Date:   Mon May 14 23:39:09 2012 +0000

    Avoid segfault in cpu_dump_state
    
    Do not call cpu_dump_state if logfile is NULL.
    
    Signed-off-by: Fabien Chouteau <chouteau at adacore.com>
    [agraf: adjust to inline functions]
    Signed-off-by: Alexander Graf <agraf at suse.de>

diff --git a/qemu-log.h b/qemu-log.h
index 40f8b7b..2ed19d1 100644
--- a/qemu-log.h
+++ b/qemu-log.h
@@ -69,7 +69,9 @@ void GCC_FMT_ATTR(2, 3) qemu_log_mask(int mask, const char *fmt, ...);
 /* cpu_dump_state() logging functions: */
 static inline void log_cpu_state(CPUArchState *env1, int flags)
 {
-    cpu_dump_state(env1, qemu_logfile, fprintf, flags);
+    if (qemu_log_enabled()) {
+        cpu_dump_state(env1, qemu_logfile, fprintf, flags);
+    }
 }
 
 static inline void log_cpu_state_mask(int mask, CPUArchState *env1, int flags)
commit cba2026a410328216f26db276a6ecf0e55a06e17
Author: Alexander Graf <agraf at suse.de>
Date:   Sat May 19 00:48:50 2012 +0200

    PPC: mpc8544ds: Span initial TLB entry over as much RAM as we need
    
    The initial TLB entry is supposed to help us run the guest -kernel payload.
    This means the guest needs to be able to access its own memory, the initrd
    memory and the device tree.
    
    So far we only statically reserved a TLB entry from [0;256M[. This patch
    fixes it to span from [0;dt_end[, allowing the guest payload to access
    everything initially.
    
    Reported-by: Stuart Yoder <stuart.yoder at freescale.com>
    Signed-off-by: Alexander Graf <agraf at suse.de>

diff --git a/hw/ppce500_mpc8544ds.c b/hw/ppce500_mpc8544ds.c
index 3eb8a23..b1a0b8c 100644
--- a/hw/ppce500_mpc8544ds.c
+++ b/hw/ppce500_mpc8544ds.c
@@ -31,6 +31,7 @@
 #include "elf.h"
 #include "sysbus.h"
 #include "exec-memory.h"
+#include "host-utils.h"
 
 #define BINARY_DEVICE_TREE_FILE    "mpc8544ds.dtb"
 #define UIMAGE_LOAD_BASE           0
@@ -55,6 +56,7 @@
 struct boot_info
 {
     uint32_t dt_base;
+    uint32_t dt_size;
     uint32_t entry;
 };
 
@@ -164,7 +166,11 @@ static int mpc8544_load_device_tree(CPUPPCState *env,
     }
 
     ret = rom_add_blob_fixed(BINARY_DEVICE_TREE_FILE, fdt, fdt_size, addr);
+    if (ret < 0) {
+        goto out;
+    }
     g_free(fdt);
+    ret = fdt_size;
 
 out:
 #endif
@@ -172,23 +178,27 @@ out:
     return ret;
 }
 
-/* Create -kernel TLB entries for BookE, linearly spanning 256MB.  */
+/* Create -kernel TLB entries for BookE.  */
 static inline target_phys_addr_t booke206_page_size_to_tlb(uint64_t size)
 {
-    return ffs(size >> 10) - 1;
+    return 63 - clz64(size >> 10);
 }
 
-static void mmubooke_create_initial_mapping(CPUPPCState *env,
-                                     target_ulong va,
-                                     target_phys_addr_t pa)
+static void mmubooke_create_initial_mapping(CPUPPCState *env)
 {
+    struct boot_info *bi = env->load_info;
     ppcmas_tlb_t *tlb = booke206_get_tlbm(env, 1, 0, 0);
-    target_phys_addr_t size;
-
-    size = (booke206_page_size_to_tlb(256 * 1024 * 1024) << MAS1_TSIZE_SHIFT);
+    target_phys_addr_t size, dt_end;
+    int ps;
+
+    /* Our initial TLB entry needs to cover everything from 0 to
+       the device tree top */
+    dt_end = bi->dt_base + bi->dt_size;
+    ps = booke206_page_size_to_tlb(dt_end) + 1;
+    size = (ps << MAS1_TSIZE_SHIFT);
     tlb->mas1 = MAS1_VALID | size;
-    tlb->mas2 = va & TARGET_PAGE_MASK;
-    tlb->mas7_3 = pa & TARGET_PAGE_MASK;
+    tlb->mas2 = 0;
+    tlb->mas7_3 = 0;
     tlb->mas7_3 |= MAS3_UR | MAS3_UW | MAS3_UX | MAS3_SR | MAS3_SW | MAS3_SX;
 
     env->tlb_dirty = true;
@@ -220,7 +230,7 @@ static void mpc8544ds_cpu_reset(void *opaque)
     env->gpr[1] = (16<<20) - 8;
     env->gpr[3] = bi->dt_base;
     env->nip = bi->entry;
-    mmubooke_create_initial_mapping(env, 0, 0);
+    mmubooke_create_initial_mapping(env);
 }
 
 static void mpc8544ds_init(ram_addr_t ram_size,
@@ -379,13 +389,15 @@ static void mpc8544ds_init(ram_addr_t ram_size,
     /* If we're loading a kernel directly, we must load the device tree too. */
     if (kernel_filename) {
         struct boot_info *boot_info;
+        int dt_size;
 
 #ifndef CONFIG_FDT
         cpu_abort(env, "Compiled without FDT support - can't load kernel\n");
 #endif
-        dt_base = (kernel_size + DTC_LOAD_PAD) & ~DTC_PAD_MASK;
-        if (mpc8544_load_device_tree(env, dt_base, ram_size,
-                    initrd_base, initrd_size, kernel_cmdline) < 0) {
+        dt_base = (loadaddr + kernel_size + DTC_LOAD_PAD) & ~DTC_PAD_MASK;
+        dt_size = mpc8544_load_device_tree(env, dt_base, ram_size, initrd_base,
+                                           initrd_size, kernel_cmdline);
+        if (dt_size < 0) {
             fprintf(stderr, "couldn't load device tree\n");
             exit(1);
         }
@@ -393,6 +405,7 @@ static void mpc8544ds_init(ram_addr_t ram_size,
         boot_info = env->load_info;
         boot_info->entry = entry;
         boot_info->dt_base = dt_base;
+        boot_info->dt_size = dt_size;
     }
 
     if (kvm_enabled()) {
commit ea6c0dac4bf161bb696ef0867d94b6223e9432c0
Author: Blue Swirl <blauwirbel at gmail.com>
Date:   Wed May 30 04:23:42 2012 +0000

    ppc: Make hbrev table const
    
    Lookup table 'hbrev' is never written to, so add a 'const' qualifier.
    
    Signed-off-by: Blue Swirl <blauwirbel at gmail.com>
    Signed-off-by: Alexander Graf <agraf at suse.de>
    Signed-off-by: Andreas Färber <afaerber at suse.de>
    Signed-off-by: Alexander Graf <agraf at suse.de>

diff --git a/target-ppc/int_helper.c b/target-ppc/int_helper.c
index 3173f11..f638b2a 100644
--- a/target-ppc/int_helper.c
+++ b/target-ppc/int_helper.c
@@ -1484,7 +1484,7 @@ VUPK(lsh, s32, s16, UPKLO)
 /*****************************************************************************/
 /* SPE extension helpers */
 /* Use a table to make this quicker */
-static uint8_t hbrev[16] = {
+static const uint8_t hbrev[16] = {
     0x0, 0x8, 0x4, 0xC, 0x2, 0xA, 0x6, 0xE,
     0x1, 0x9, 0x5, 0xD, 0x3, 0xB, 0x7, 0xF,
 };
commit 9063825538ad8fc9131191fceefcbb149fa5d199
Author: Blue Swirl <blauwirbel at gmail.com>
Date:   Wed May 30 04:23:41 2012 +0000

    ppc: Add missing break
    
    Add obviously missing 'break' statement.
    
    Signed-off-by: Blue Swirl <blauwirbel at gmail.com>
    Signed-off-by: Alexander Graf <agraf at suse.de>
    Signed-off-by: Andreas Färber <afaerber at suse.de>
    Signed-off-by: Alexander Graf <agraf at suse.de>

diff --git a/target-ppc/fpu_helper.c b/target-ppc/fpu_helper.c
index d90636f..9d67926 100644
--- a/target-ppc/fpu_helper.c
+++ b/target-ppc/fpu_helper.c
@@ -310,6 +310,7 @@ void helper_fpscr_setbit(CPUPPCState *env, uint32_t bit)
             if (fpscr_ve) {
                 goto raise_ve;
             }
+            break;
         case FPSCR_OX:
             env->fpscr |= 1 << FPSCR_FX;
             if (fpscr_oe) {
commit 2f5a189caefe2ecbd32faf528a0fbf8c915dfa08
Author: Blue Swirl <blauwirbel at gmail.com>
Date:   Wed May 30 04:23:40 2012 +0000

    ppc: Move load and store helpers, switch to AREG0 free mode
    
    Add an explicit CPUPPCState parameter instead of relying on AREG0
    and rename op_helper.c (which only contains load and store helpers)
    to mem_helper.c. Remove AREG0 swapping in
    tlb_fill().
    
    Switch to AREG0 free mode. Use cpu_ld{l,uw}_code in translation
    and interrupt handling, cpu_{ld,st}{l,uw}_data in loads and stores.
    
    Signed-off-by: Blue Swirl <blauwirbel at gmail.com>
    Signed-off-by: Alexander Graf <agraf at suse.de>
    Signed-off-by: Andreas Färber <afaerber at suse.de>
    Signed-off-by: Alexander Graf <agraf at suse.de>

diff --git a/configure b/configure
index b68c0ca..6128ba7 100755
--- a/configure
+++ b/configure
@@ -3679,7 +3679,7 @@ symlink "$source_path/Makefile.target" "$target_dir/Makefile"
 
 
 case "$target_arch2" in
-  alpha | sparc* | xtensa*)
+  alpha | sparc* | xtensa* | ppc*)
     echo "CONFIG_TCG_PASS_AREG0=y" >> $config_target_mak
   ;;
 esac
diff --git a/cpu-all.h b/cpu-all.h
index 50c8b62..9dc249a 100644
--- a/cpu-all.h
+++ b/cpu-all.h
@@ -291,6 +291,15 @@ extern unsigned long reserved_va;
 #define stfl_kernel(p, v) stfl_raw(p, v)
 #define stfq_kernel(p, vt) stfq_raw(p, v)
 
+#ifdef CONFIG_TCG_PASS_AREG0
+#define cpu_ldub_data(env, addr) ldub_raw(addr)
+#define cpu_lduw_data(env, addr) lduw_raw(addr)
+#define cpu_ldl_data(env, addr) ldl_raw(addr)
+
+#define cpu_stb_data(env, addr, data) stb_raw(addr, data)
+#define cpu_stw_data(env, addr, data) stw_raw(addr, data)
+#define cpu_stl_data(env, addr, data) stl_raw(addr, data)
+#endif
 #endif /* defined(CONFIG_USER_ONLY) */
 
 /* page related stuff */
diff --git a/target-ppc/Makefile.objs b/target-ppc/Makefile.objs
index 8d4d16b..6c11ef8 100644
--- a/target-ppc/Makefile.objs
+++ b/target-ppc/Makefile.objs
@@ -1,12 +1,11 @@
-obj-y += translate.o op_helper.o helper.o
+obj-y += translate.o helper.o
 obj-$(CONFIG_SOFTMMU) += machine.o
 obj-$(CONFIG_KVM) += kvm.o kvm_ppc.o
-obj-y += op_helper.o helper.o
+obj-y += helper.o
 obj-y += excp_helper.o
 obj-y += fpu_helper.o
 obj-y += int_helper.o
 obj-y += mmu_helper.o
 obj-y += timebase_helper.o
 obj-y += misc_helper.o
-
-$(obj)/op_helper.o: QEMU_CFLAGS += $(HELPER_CFLAGS)
+obj-y += mem_helper.o
diff --git a/target-ppc/excp_helper.c b/target-ppc/excp_helper.c
index 7fa7a59..c7762b9 100644
--- a/target-ppc/excp_helper.c
+++ b/target-ppc/excp_helper.c
@@ -179,7 +179,8 @@ static inline void powerpc_excp(CPUPPCState *env, int excp_model, int excp)
         }
         /* XXX: this is false */
         /* Get rS/rD and rA from faulting opcode */
-        env->spr[SPR_DSISR] |= (ldl_code((env->nip - 4)) & 0x03FF0000) >> 16;
+        env->spr[SPR_DSISR] |= (cpu_ldl_code(env, (env->nip - 4))
+                                & 0x03FF0000) >> 16;
         goto store_current;
     case POWERPC_EXCP_PROGRAM:   /* Program exception                        */
         switch (env->error_code & ~0xF) {
diff --git a/target-ppc/helper.h b/target-ppc/helper.h
index b7a157e..ddab97b 100644
--- a/target-ppc/helper.h
+++ b/target-ppc/helper.h
@@ -20,15 +20,15 @@ DEF_HELPER_1(hrfid, void, env)
 #endif
 #endif
 
-DEF_HELPER_2(lmw, void, tl, i32)
-DEF_HELPER_2(stmw, void, tl, i32)
-DEF_HELPER_3(lsw, void, tl, i32, i32)
-DEF_HELPER_4(lswx, void, tl, i32, i32, i32)
-DEF_HELPER_3(stsw, void, tl, i32, i32)
-DEF_HELPER_1(dcbz, void, tl)
-DEF_HELPER_1(dcbz_970, void, tl)
-DEF_HELPER_1(icbi, void, tl)
-DEF_HELPER_4(lscbx, tl, tl, i32, i32, i32)
+DEF_HELPER_3(lmw, void, env, tl, i32)
+DEF_HELPER_3(stmw, void, env, tl, i32)
+DEF_HELPER_4(lsw, void, env, tl, i32, i32)
+DEF_HELPER_5(lswx, void, env, tl, i32, i32, i32)
+DEF_HELPER_4(stsw, void, env, tl, i32, i32)
+DEF_HELPER_2(dcbz, void, env, tl)
+DEF_HELPER_2(dcbz_970, void, env, tl)
+DEF_HELPER_2(icbi, void, env, tl)
+DEF_HELPER_5(lscbx, tl, env, tl, i32, i32, i32)
 
 #if defined(TARGET_PPC64)
 DEF_HELPER_FLAGS_2(mulhd, TCG_CALL_CONST | TCG_CALL_PURE, i64, i64, i64)
@@ -226,12 +226,12 @@ DEF_HELPER_5(vmsumshm, void, env, avr, avr, avr, avr)
 DEF_HELPER_5(vmsumshs, void, env, avr, avr, avr, avr)
 DEF_HELPER_4(vmladduhm, void, avr, avr, avr, avr)
 DEF_HELPER_2(mtvscr, void, env, avr);
-DEF_HELPER_2(lvebx, void, avr, tl)
-DEF_HELPER_2(lvehx, void, avr, tl)
-DEF_HELPER_2(lvewx, void, avr, tl)
-DEF_HELPER_2(stvebx, void, avr, tl)
-DEF_HELPER_2(stvehx, void, avr, tl)
-DEF_HELPER_2(stvewx, void, avr, tl)
+DEF_HELPER_3(lvebx, void, env, avr, tl)
+DEF_HELPER_3(lvehx, void, env, avr, tl)
+DEF_HELPER_3(lvewx, void, env, avr, tl)
+DEF_HELPER_3(stvebx, void, env, avr, tl)
+DEF_HELPER_3(stvehx, void, env, avr, tl)
+DEF_HELPER_3(stvewx, void, env, avr, tl)
 DEF_HELPER_4(vsumsws, void, env, avr, avr, avr)
 DEF_HELPER_4(vsum2sws, void, env, avr, avr, avr)
 DEF_HELPER_4(vsum4sbs, void, env, avr, avr, avr)
diff --git a/target-ppc/mem_helper.c b/target-ppc/mem_helper.c
new file mode 100644
index 0000000..ebcd7b2
--- /dev/null
+++ b/target-ppc/mem_helper.c
@@ -0,0 +1,295 @@
+/*
+ *  PowerPC memory access emulation helpers for QEMU.
+ *
+ *  Copyright (c) 2003-2007 Jocelyn Mayer
+ *
+ * This library is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Lesser General Public
+ * License as published by the Free Software Foundation; either
+ * version 2 of the License, or (at your option) any later version.
+ *
+ * This library is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
+ * Lesser General Public License for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public
+ * License along with this library; if not, see <http://www.gnu.org/licenses/>.
+ */
+#include "cpu.h"
+#include "host-utils.h"
+#include "helper.h"
+
+#include "helper_regs.h"
+
+#if !defined(CONFIG_USER_ONLY)
+#include "softmmu_exec.h"
+#endif /* !defined(CONFIG_USER_ONLY) */
+
+//#define DEBUG_OP
+
+/*****************************************************************************/
+/* Memory load and stores */
+
+static inline target_ulong addr_add(CPUPPCState *env, target_ulong addr,
+                                    target_long arg)
+{
+#if defined(TARGET_PPC64)
+    if (!msr_sf) {
+        return (uint32_t)(addr + arg);
+    } else
+#endif
+    {
+        return addr + arg;
+    }
+}
+
+void helper_lmw(CPUPPCState *env, target_ulong addr, uint32_t reg)
+{
+    for (; reg < 32; reg++) {
+        if (msr_le) {
+            env->gpr[reg] = bswap32(cpu_ldl_data(env, addr));
+        } else {
+            env->gpr[reg] = cpu_ldl_data(env, addr);
+        }
+        addr = addr_add(env, addr, 4);
+    }
+}
+
+void helper_stmw(CPUPPCState *env, target_ulong addr, uint32_t reg)
+{
+    for (; reg < 32; reg++) {
+        if (msr_le) {
+            cpu_stl_data(env, addr, bswap32((uint32_t)env->gpr[reg]));
+        } else {
+            cpu_stl_data(env, addr, (uint32_t)env->gpr[reg]);
+        }
+        addr = addr_add(env, addr, 4);
+    }
+}
+
+void helper_lsw(CPUPPCState *env, target_ulong addr, uint32_t nb, uint32_t reg)
+{
+    int sh;
+
+    for (; nb > 3; nb -= 4) {
+        env->gpr[reg] = cpu_ldl_data(env, addr);
+        reg = (reg + 1) % 32;
+        addr = addr_add(env, addr, 4);
+    }
+    if (unlikely(nb > 0)) {
+        env->gpr[reg] = 0;
+        for (sh = 24; nb > 0; nb--, sh -= 8) {
+            env->gpr[reg] |= cpu_ldub_data(env, addr) << sh;
+            addr = addr_add(env, addr, 1);
+        }
+    }
+}
+/* PPC32 specification says we must generate an exception if
+ * rA is in the range of registers to be loaded.
+ * In an other hand, IBM says this is valid, but rA won't be loaded.
+ * For now, I'll follow the spec...
+ */
+void helper_lswx(CPUPPCState *env, target_ulong addr, uint32_t reg,
+                 uint32_t ra, uint32_t rb)
+{
+    if (likely(xer_bc != 0)) {
+        if (unlikely((ra != 0 && reg < ra && (reg + xer_bc) > ra) ||
+                     (reg < rb && (reg + xer_bc) > rb))) {
+            helper_raise_exception_err(env, POWERPC_EXCP_PROGRAM,
+                                       POWERPC_EXCP_INVAL |
+                                       POWERPC_EXCP_INVAL_LSWX);
+        } else {
+            helper_lsw(env, addr, xer_bc, reg);
+        }
+    }
+}
+
+void helper_stsw(CPUPPCState *env, target_ulong addr, uint32_t nb,
+                 uint32_t reg)
+{
+    int sh;
+
+    for (; nb > 3; nb -= 4) {
+        cpu_stl_data(env, addr, env->gpr[reg]);
+        reg = (reg + 1) % 32;
+        addr = addr_add(env, addr, 4);
+    }
+    if (unlikely(nb > 0)) {
+        for (sh = 24; nb > 0; nb--, sh -= 8) {
+            cpu_stb_data(env, addr, (env->gpr[reg] >> sh) & 0xFF);
+            addr = addr_add(env, addr, 1);
+        }
+    }
+}
+
+static void do_dcbz(CPUPPCState *env, target_ulong addr, int dcache_line_size)
+{
+    int i;
+
+    addr &= ~(dcache_line_size - 1);
+    for (i = 0; i < dcache_line_size; i += 4) {
+        cpu_stl_data(env, addr + i, 0);
+    }
+    if (env->reserve_addr == addr) {
+        env->reserve_addr = (target_ulong)-1ULL;
+    }
+}
+
+void helper_dcbz(CPUPPCState *env, target_ulong addr)
+{
+    do_dcbz(env, addr, env->dcache_line_size);
+}
+
+void helper_dcbz_970(CPUPPCState *env, target_ulong addr)
+{
+    if (((env->spr[SPR_970_HID5] >> 7) & 0x3) == 1) {
+        do_dcbz(env, addr, 32);
+    } else {
+        do_dcbz(env, addr, env->dcache_line_size);
+    }
+}
+
+void helper_icbi(CPUPPCState *env, target_ulong addr)
+{
+    addr &= ~(env->dcache_line_size - 1);
+    /* Invalidate one cache line :
+     * PowerPC specification says this is to be treated like a load
+     * (not a fetch) by the MMU. To be sure it will be so,
+     * do the load "by hand".
+     */
+    cpu_ldl_data(env, addr);
+}
+
+/* XXX: to be tested */
+target_ulong helper_lscbx(CPUPPCState *env, target_ulong addr, uint32_t reg,
+                          uint32_t ra, uint32_t rb)
+{
+    int i, c, d;
+
+    d = 24;
+    for (i = 0; i < xer_bc; i++) {
+        c = cpu_ldub_data(env, addr);
+        addr = addr_add(env, addr, 1);
+        /* ra (if not 0) and rb are never modified */
+        if (likely(reg != rb && (ra == 0 || reg != ra))) {
+            env->gpr[reg] = (env->gpr[reg] & ~(0xFF << d)) | (c << d);
+        }
+        if (unlikely(c == xer_cmp)) {
+            break;
+        }
+        if (likely(d != 0)) {
+            d -= 8;
+        } else {
+            d = 24;
+            reg++;
+            reg = reg & 0x1F;
+        }
+    }
+    return i;
+}
+
+/*****************************************************************************/
+/* Altivec extension helpers */
+#if defined(HOST_WORDS_BIGENDIAN)
+#define HI_IDX 0
+#define LO_IDX 1
+#else
+#define HI_IDX 1
+#define LO_IDX 0
+#endif
+
+#define LVE(name, access, swap, element)                        \
+    void helper_##name(CPUPPCState *env, ppc_avr_t *r,          \
+                       target_ulong addr)                       \
+    {                                                           \
+        size_t n_elems = ARRAY_SIZE(r->element);                \
+        int adjust = HI_IDX*(n_elems - 1);                      \
+        int sh = sizeof(r->element[0]) >> 1;                    \
+        int index = (addr & 0xf) >> sh;                         \
+                                                                \
+        if (msr_le) {                                           \
+            r->element[LO_IDX ? index : (adjust - index)] =     \
+                swap(access(env, addr));                        \
+        } else {                                                \
+            r->element[LO_IDX ? index : (adjust - index)] =     \
+                access(env, addr);                              \
+        }                                                       \
+    }
+#define I(x) (x)
+LVE(lvebx, cpu_ldub_data, I, u8)
+LVE(lvehx, cpu_lduw_data, bswap16, u16)
+LVE(lvewx, cpu_ldl_data, bswap32, u32)
+#undef I
+#undef LVE
+
+#define STVE(name, access, swap, element)                               \
+    void helper_##name(CPUPPCState *env, ppc_avr_t *r,                  \
+                       target_ulong addr)                               \
+    {                                                                   \
+        size_t n_elems = ARRAY_SIZE(r->element);                        \
+        int adjust = HI_IDX * (n_elems - 1);                            \
+        int sh = sizeof(r->element[0]) >> 1;                            \
+        int index = (addr & 0xf) >> sh;                                 \
+                                                                        \
+        if (msr_le) {                                                   \
+            access(env, addr, swap(r->element[LO_IDX ? index :          \
+                                              (adjust - index)]));      \
+        } else {                                                        \
+            access(env, addr, r->element[LO_IDX ? index :               \
+                                         (adjust - index)]);            \
+        }                                                               \
+    }
+#define I(x) (x)
+STVE(stvebx, cpu_stb_data, I, u8)
+STVE(stvehx, cpu_stw_data, bswap16, u16)
+STVE(stvewx, cpu_stl_data, bswap32, u32)
+#undef I
+#undef LVE
+
+#undef HI_IDX
+#undef LO_IDX
+
+/*****************************************************************************/
+/* Softmmu support */
+#if !defined(CONFIG_USER_ONLY)
+
+#define MMUSUFFIX _mmu
+
+#define SHIFT 0
+#include "softmmu_template.h"
+
+#define SHIFT 1
+#include "softmmu_template.h"
+
+#define SHIFT 2
+#include "softmmu_template.h"
+
+#define SHIFT 3
+#include "softmmu_template.h"
+
+/* try to fill the TLB and return an exception if error. If retaddr is
+   NULL, it means that the function was called in C code (i.e. not
+   from generated code or from helper.c) */
+/* XXX: fix it to restore all registers */
+void tlb_fill(CPUPPCState *env, target_ulong addr, int is_write, int mmu_idx,
+              uintptr_t retaddr)
+{
+    TranslationBlock *tb;
+    int ret;
+
+    ret = cpu_ppc_handle_mmu_fault(env, addr, is_write, mmu_idx);
+    if (unlikely(ret != 0)) {
+        if (likely(retaddr)) {
+            /* now we have a real cpu fault */
+            tb = tb_find_pc(retaddr);
+            if (likely(tb)) {
+                /* the PC is inside the translated code. It means that we have
+                   a virtual CPU fault */
+                cpu_restore_state(tb, env, retaddr);
+            }
+        }
+        helper_raise_exception_err(env, env->exception_index, env->error_code);
+    }
+}
+#endif /* !CONFIG_USER_ONLY */
diff --git a/target-ppc/op_helper.c b/target-ppc/op_helper.c
deleted file mode 100644
index cd1a533..0000000
--- a/target-ppc/op_helper.c
+++ /dev/null
@@ -1,294 +0,0 @@
-/*
- *  PowerPC emulation helpers for QEMU.
- *
- *  Copyright (c) 2003-2007 Jocelyn Mayer
- *
- * This library is free software; you can redistribute it and/or
- * modify it under the terms of the GNU Lesser General Public
- * License as published by the Free Software Foundation; either
- * version 2 of the License, or (at your option) any later version.
- *
- * This library is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
- * Lesser General Public License for more details.
- *
- * You should have received a copy of the GNU Lesser General Public
- * License along with this library; if not, see <http://www.gnu.org/licenses/>.
- */
-#include <string.h>
-#include "cpu.h"
-#include "dyngen-exec.h"
-#include "host-utils.h"
-#include "helper.h"
-
-#include "helper_regs.h"
-
-#if !defined(CONFIG_USER_ONLY)
-#include "softmmu_exec.h"
-#endif /* !defined(CONFIG_USER_ONLY) */
-
-//#define DEBUG_OP
-
-/*****************************************************************************/
-/* Memory load and stores */
-
-static inline target_ulong addr_add(target_ulong addr, target_long arg)
-{
-#if defined(TARGET_PPC64)
-    if (!msr_sf) {
-        return (uint32_t)(addr + arg);
-    } else
-#endif
-    {
-        return addr + arg;
-    }
-}
-
-void helper_lmw(target_ulong addr, uint32_t reg)
-{
-    for (; reg < 32; reg++) {
-        if (msr_le) {
-            env->gpr[reg] = bswap32(ldl(addr));
-        } else {
-            env->gpr[reg] = ldl(addr);
-        }
-        addr = addr_add(addr, 4);
-    }
-}
-
-void helper_stmw(target_ulong addr, uint32_t reg)
-{
-    for (; reg < 32; reg++) {
-        if (msr_le) {
-            stl(addr, bswap32((uint32_t)env->gpr[reg]));
-        } else {
-            stl(addr, (uint32_t)env->gpr[reg]);
-        }
-        addr = addr_add(addr, 4);
-    }
-}
-
-void helper_lsw(target_ulong addr, uint32_t nb, uint32_t reg)
-{
-    int sh;
-
-    for (; nb > 3; nb -= 4) {
-        env->gpr[reg] = ldl(addr);
-        reg = (reg + 1) % 32;
-        addr = addr_add(addr, 4);
-    }
-    if (unlikely(nb > 0)) {
-        env->gpr[reg] = 0;
-        for (sh = 24; nb > 0; nb--, sh -= 8) {
-            env->gpr[reg] |= ldub(addr) << sh;
-            addr = addr_add(addr, 1);
-        }
-    }
-}
-/* PPC32 specification says we must generate an exception if
- * rA is in the range of registers to be loaded.
- * In an other hand, IBM says this is valid, but rA won't be loaded.
- * For now, I'll follow the spec...
- */
-void helper_lswx(target_ulong addr, uint32_t reg, uint32_t ra, uint32_t rb)
-{
-    if (likely(xer_bc != 0)) {
-        if (unlikely((ra != 0 && reg < ra && (reg + xer_bc) > ra) ||
-                     (reg < rb && (reg + xer_bc) > rb))) {
-            helper_raise_exception_err(env, POWERPC_EXCP_PROGRAM,
-                                       POWERPC_EXCP_INVAL |
-                                       POWERPC_EXCP_INVAL_LSWX);
-        } else {
-            helper_lsw(addr, xer_bc, reg);
-        }
-    }
-}
-
-void helper_stsw(target_ulong addr, uint32_t nb, uint32_t reg)
-{
-    int sh;
-
-    for (; nb > 3; nb -= 4) {
-        stl(addr, env->gpr[reg]);
-        reg = (reg + 1) % 32;
-        addr = addr_add(addr, 4);
-    }
-    if (unlikely(nb > 0)) {
-        for (sh = 24; nb > 0; nb--, sh -= 8) {
-            stb(addr, (env->gpr[reg] >> sh) & 0xFF);
-            addr = addr_add(addr, 1);
-        }
-    }
-}
-
-static void do_dcbz(target_ulong addr, int dcache_line_size)
-{
-    int i;
-
-    addr &= ~(dcache_line_size - 1);
-    for (i = 0; i < dcache_line_size; i += 4) {
-        stl(addr + i, 0);
-    }
-    if (env->reserve_addr == addr) {
-        env->reserve_addr = (target_ulong)-1ULL;
-    }
-}
-
-void helper_dcbz(target_ulong addr)
-{
-    do_dcbz(addr, env->dcache_line_size);
-}
-
-void helper_dcbz_970(target_ulong addr)
-{
-    if (((env->spr[SPR_970_HID5] >> 7) & 0x3) == 1) {
-        do_dcbz(addr, 32);
-    } else {
-        do_dcbz(addr, env->dcache_line_size);
-    }
-}
-
-void helper_icbi(target_ulong addr)
-{
-    addr &= ~(env->dcache_line_size - 1);
-    /* Invalidate one cache line :
-     * PowerPC specification says this is to be treated like a load
-     * (not a fetch) by the MMU. To be sure it will be so,
-     * do the load "by hand".
-     */
-    ldl(addr);
-}
-
-/* XXX: to be tested */
-target_ulong helper_lscbx(target_ulong addr, uint32_t reg, uint32_t ra,
-                          uint32_t rb)
-{
-    int i, c, d;
-
-    d = 24;
-    for (i = 0; i < xer_bc; i++) {
-        c = ldub(addr);
-        addr = addr_add(addr, 1);
-        /* ra (if not 0) and rb are never modified */
-        if (likely(reg != rb && (ra == 0 || reg != ra))) {
-            env->gpr[reg] = (env->gpr[reg] & ~(0xFF << d)) | (c << d);
-        }
-        if (unlikely(c == xer_cmp)) {
-            break;
-        }
-        if (likely(d != 0)) {
-            d -= 8;
-        } else {
-            d = 24;
-            reg++;
-            reg = reg & 0x1F;
-        }
-    }
-    return i;
-}
-
-/*****************************************************************************/
-/* Altivec extension helpers */
-#if defined(HOST_WORDS_BIGENDIAN)
-#define HI_IDX 0
-#define LO_IDX 1
-#else
-#define HI_IDX 1
-#define LO_IDX 0
-#endif
-
-#define LVE(name, access, swap, element)                        \
-    void helper_##name(ppc_avr_t *r, target_ulong addr)         \
-    {                                                           \
-        size_t n_elems = ARRAY_SIZE(r->element);                \
-        int adjust = HI_IDX*(n_elems - 1);                      \
-        int sh = sizeof(r->element[0]) >> 1;                    \
-        int index = (addr & 0xf) >> sh;                         \
-                                                                \
-        if (msr_le) {                                           \
-            r->element[LO_IDX ? index : (adjust - index)] =     \
-                swap(access(addr));                             \
-        } else {                                                \
-            r->element[LO_IDX ? index : (adjust - index)] =     \
-                access(addr);                                   \
-        }                                                       \
-    }
-#define I(x) (x)
-LVE(lvebx, ldub, I, u8)
-LVE(lvehx, lduw, bswap16, u16)
-LVE(lvewx, ldl, bswap32, u32)
-#undef I
-#undef LVE
-
-#define STVE(name, access, swap, element)                               \
-    void helper_##name(ppc_avr_t *r, target_ulong addr)                 \
-    {                                                                   \
-        size_t n_elems = ARRAY_SIZE(r->element);                        \
-        int adjust = HI_IDX * (n_elems - 1);                            \
-        int sh = sizeof(r->element[0]) >> 1;                            \
-        int index = (addr & 0xf) >> sh;                                 \
-                                                                        \
-        if (msr_le) {                                                   \
-            access(addr, swap(r->element[LO_IDX ? index : (adjust - index)])); \
-        } else {                                                        \
-            access(addr, r->element[LO_IDX ? index : (adjust - index)]); \
-        }                                                               \
-    }
-#define I(x) (x)
-STVE(stvebx, stb, I, u8)
-STVE(stvehx, stw, bswap16, u16)
-STVE(stvewx, stl, bswap32, u32)
-#undef I
-#undef LVE
-
-#undef HI_IDX
-#undef LO_IDX
-
-/*****************************************************************************/
-/* Softmmu support */
-#if !defined(CONFIG_USER_ONLY)
-
-#define MMUSUFFIX _mmu
-
-#define SHIFT 0
-#include "softmmu_template.h"
-
-#define SHIFT 1
-#include "softmmu_template.h"
-
-#define SHIFT 2
-#include "softmmu_template.h"
-
-#define SHIFT 3
-#include "softmmu_template.h"
-
-/* try to fill the TLB and return an exception if error. If retaddr is
-   NULL, it means that the function was called in C code (i.e. not
-   from generated code or from helper.c) */
-/* XXX: fix it to restore all registers */
-void tlb_fill(CPUPPCState *env1, target_ulong addr, int is_write, int mmu_idx,
-              uintptr_t retaddr)
-{
-    TranslationBlock *tb;
-    CPUPPCState *saved_env;
-    int ret;
-
-    saved_env = env;
-    env = env1;
-    ret = cpu_ppc_handle_mmu_fault(env, addr, is_write, mmu_idx);
-    if (unlikely(ret != 0)) {
-        if (likely(retaddr)) {
-            /* now we have a real cpu fault */
-            tb = tb_find_pc(retaddr);
-            if (likely(tb)) {
-                /* the PC is inside the translated code. It means that we have
-                   a virtual CPU fault */
-                cpu_restore_state(tb, env, retaddr);
-            }
-        }
-        helper_raise_exception_err(env, env->exception_index, env->error_code);
-    }
-    env = saved_env;
-}
-#endif /* !CONFIG_USER_ONLY */
diff --git a/target-ppc/translate.c b/target-ppc/translate.c
index bcc9933..9103fd5 100644
--- a/target-ppc/translate.c
+++ b/target-ppc/translate.c
@@ -2989,7 +2989,7 @@ static void gen_lmw(DisasContext *ctx)
     t0 = tcg_temp_new();
     t1 = tcg_const_i32(rD(ctx->opcode));
     gen_addr_imm_index(ctx, t0, 0);
-    gen_helper_lmw(t0, t1);
+    gen_helper_lmw(cpu_env, t0, t1);
     tcg_temp_free(t0);
     tcg_temp_free_i32(t1);
 }
@@ -3005,7 +3005,7 @@ static void gen_stmw(DisasContext *ctx)
     t0 = tcg_temp_new();
     t1 = tcg_const_i32(rS(ctx->opcode));
     gen_addr_imm_index(ctx, t0, 0);
-    gen_helper_stmw(t0, t1);
+    gen_helper_stmw(cpu_env, t0, t1);
     tcg_temp_free(t0);
     tcg_temp_free_i32(t1);
 }
@@ -3043,7 +3043,7 @@ static void gen_lswi(DisasContext *ctx)
     gen_addr_register(ctx, t0);
     t1 = tcg_const_i32(nb);
     t2 = tcg_const_i32(start);
-    gen_helper_lsw(t0, t1, t2);
+    gen_helper_lsw(cpu_env, t0, t1, t2);
     tcg_temp_free(t0);
     tcg_temp_free_i32(t1);
     tcg_temp_free_i32(t2);
@@ -3062,7 +3062,7 @@ static void gen_lswx(DisasContext *ctx)
     t1 = tcg_const_i32(rD(ctx->opcode));
     t2 = tcg_const_i32(rA(ctx->opcode));
     t3 = tcg_const_i32(rB(ctx->opcode));
-    gen_helper_lswx(t0, t1, t2, t3);
+    gen_helper_lswx(cpu_env, t0, t1, t2, t3);
     tcg_temp_free(t0);
     tcg_temp_free_i32(t1);
     tcg_temp_free_i32(t2);
@@ -3084,7 +3084,7 @@ static void gen_stswi(DisasContext *ctx)
         nb = 32;
     t1 = tcg_const_i32(nb);
     t2 = tcg_const_i32(rS(ctx->opcode));
-    gen_helper_stsw(t0, t1, t2);
+    gen_helper_stsw(cpu_env, t0, t1, t2);
     tcg_temp_free(t0);
     tcg_temp_free_i32(t1);
     tcg_temp_free_i32(t2);
@@ -3104,7 +3104,7 @@ static void gen_stswx(DisasContext *ctx)
     tcg_gen_trunc_tl_i32(t1, cpu_xer);
     tcg_gen_andi_i32(t1, t1, 0x7F);
     t2 = tcg_const_i32(rS(ctx->opcode));
-    gen_helper_stsw(t0, t1, t2);
+    gen_helper_stsw(cpu_env, t0, t1, t2);
     tcg_temp_free(t0);
     tcg_temp_free_i32(t1);
     tcg_temp_free_i32(t2);
@@ -4116,7 +4116,7 @@ static void gen_dcbz(DisasContext *ctx)
     gen_update_nip(ctx, ctx->nip - 4);
     t0 = tcg_temp_new();
     gen_addr_reg_index(ctx, t0);
-    gen_helper_dcbz(t0);
+    gen_helper_dcbz(cpu_env, t0);
     tcg_temp_free(t0);
 }
 
@@ -4129,9 +4129,9 @@ static void gen_dcbz_970(DisasContext *ctx)
     t0 = tcg_temp_new();
     gen_addr_reg_index(ctx, t0);
     if (ctx->opcode & 0x00200000)
-        gen_helper_dcbz(t0);
+        gen_helper_dcbz(cpu_env, t0);
     else
-        gen_helper_dcbz_970(t0);
+        gen_helper_dcbz_970(cpu_env, t0);
     tcg_temp_free(t0);
 }
 
@@ -4171,7 +4171,7 @@ static void gen_icbi(DisasContext *ctx)
     gen_update_nip(ctx, ctx->nip - 4);
     t0 = tcg_temp_new();
     gen_addr_reg_index(ctx, t0);
-    gen_helper_icbi(t0);
+    gen_helper_icbi(cpu_env, t0);
     tcg_temp_free(t0);
 }
 
@@ -4663,7 +4663,7 @@ static void gen_lscbx(DisasContext *ctx)
     gen_addr_reg_index(ctx, t0);
     /* NIP cannot be restored if the memory exception comes from an helper */
     gen_update_nip(ctx, ctx->nip - 4);
-    gen_helper_lscbx(t0, t0, t1, t2, t3);
+    gen_helper_lscbx(t0, cpu_env, t0, t1, t2, t3);
     tcg_temp_free_i32(t1);
     tcg_temp_free_i32(t2);
     tcg_temp_free_i32(t3);
@@ -6387,7 +6387,7 @@ static void gen_lve##name(DisasContext *ctx)                            \
         EA = tcg_temp_new();                                            \
         gen_addr_reg_index(ctx, EA);                                    \
         rs = gen_avr_ptr(rS(ctx->opcode));                              \
-        gen_helper_lve##name (rs, EA);                                  \
+        gen_helper_lve##name(cpu_env, rs, EA);                          \
         tcg_temp_free(EA);                                              \
         tcg_temp_free_ptr(rs);                                          \
     }
@@ -6405,7 +6405,7 @@ static void gen_stve##name(DisasContext *ctx)                           \
         EA = tcg_temp_new();                                            \
         gen_addr_reg_index(ctx, EA);                                    \
         rs = gen_avr_ptr(rS(ctx->opcode));                              \
-        gen_helper_stve##name (rs, EA);                                 \
+        gen_helper_stve##name(cpu_env, rs, EA);                         \
         tcg_temp_free(EA);                                              \
         tcg_temp_free_ptr(rs);                                          \
     }
@@ -9683,9 +9683,9 @@ static inline void gen_intermediate_code_internal(CPUPPCState *env,
         if (num_insns + 1 == max_insns && (tb->cflags & CF_LAST_IO))
             gen_io_start();
         if (unlikely(ctx.le_mode)) {
-            ctx.opcode = bswap32(ldl_code(ctx.nip));
+            ctx.opcode = bswap32(cpu_ldl_code(env, ctx.nip));
         } else {
-            ctx.opcode = ldl_code(ctx.nip);
+            ctx.opcode = cpu_ldl_code(env, ctx.nip);
         }
         LOG_DISAS("translate opcode %08x (%02x %02x %02x) (%s)\n",
                     ctx.opcode, opc1(ctx.opcode), opc2(ctx.opcode),
commit 8555f71dcbbe562429bbb25e0028f71e5741b752
Author: Blue Swirl <blauwirbel at gmail.com>
Date:   Wed May 30 04:23:39 2012 +0000

    ppc: Move misc helpers from helper.c to misc_helper.c
    
    Move more misc helpers from helper.c to misc_helper.c.
    
    Signed-off-by: Blue Swirl <blauwirbel at gmail.com>
    Signed-off-by: Alexander Graf <agraf at suse.de>
    Signed-off-by: Andreas Färber <afaerber at suse.de>
    Signed-off-by: Alexander Graf <agraf at suse.de>

diff --git a/target-ppc/helper.c b/target-ppc/helper.c
index 24d109d..48b19a7 100644
--- a/target-ppc/helper.c
+++ b/target-ppc/helper.c
@@ -23,15 +23,6 @@
 #include "kvm_ppc.h"
 #include "cpus.h"
 
-/*****************************************************************************/
-/* Special registers manipulation */
-
-/* GDBstub can read and write MSR... */
-void ppc_store_msr(CPUPPCState *env, target_ulong value)
-{
-    hreg_store_msr(env, value, 0);
-}
-
 PowerPCCPU *cpu_ppc_init(const char *cpu_model)
 {
     PowerPCCPU *cpu;
diff --git a/target-ppc/misc_helper.c b/target-ppc/misc_helper.c
index b194d19..26edcca 100644
--- a/target-ppc/misc_helper.c
+++ b/target-ppc/misc_helper.c
@@ -113,3 +113,12 @@ target_ulong helper_clcs(CPUPPCState *env, uint32_t arg)
         break;
     }
 }
+
+/*****************************************************************************/
+/* Special registers manipulation */
+
+/* GDBstub can read and write MSR... */
+void ppc_store_msr(CPUPPCState *env, target_ulong value)
+{
+    hreg_store_msr(env, value, 0);
+}
commit d523dd00a7d73b28f2e99acf45a4b3f92e56e40a
Author: Blue Swirl <blauwirbel at gmail.com>
Date:   Wed May 30 04:23:38 2012 +0000

    ppc: Avoid AREG0 for misc helpers
    
    Add an explicit CPUPPCState parameter instead of relying on AREG0.
    
    Signed-off-by: Blue Swirl <blauwirbel at gmail.com>
    Signed-off-by: Alexander Graf <agraf at suse.de>
    Signed-off-by: Andreas Färber <afaerber at suse.de>
    Signed-off-by: Alexander Graf <agraf at suse.de>

diff --git a/target-ppc/Makefile.objs b/target-ppc/Makefile.objs
index 3a444eb..8d4d16b 100644
--- a/target-ppc/Makefile.objs
+++ b/target-ppc/Makefile.objs
@@ -9,5 +9,4 @@ obj-y += mmu_helper.o
 obj-y += timebase_helper.o
 obj-y += misc_helper.o
 
-$(obj)/misc_helper.o: QEMU_CFLAGS += $(HELPER_CFLAGS)
 $(obj)/op_helper.o: QEMU_CFLAGS += $(HELPER_CFLAGS)
diff --git a/target-ppc/helper.h b/target-ppc/helper.h
index 81fc40e..b7a157e 100644
--- a/target-ppc/helper.h
+++ b/target-ppc/helper.h
@@ -363,7 +363,7 @@ DEF_HELPER_2(msgclr, void, env, tl)
 #endif
 
 DEF_HELPER_4(dlmzb, tl, env, tl, tl, i32)
-DEF_HELPER_FLAGS_1(clcs, TCG_CALL_CONST | TCG_CALL_PURE, tl, i32)
+DEF_HELPER_FLAGS_2(clcs, TCG_CALL_CONST | TCG_CALL_PURE, tl, env, i32)
 #if !defined(CONFIG_USER_ONLY)
 DEF_HELPER_2(rac, tl, env, tl)
 #endif
@@ -375,8 +375,8 @@ DEF_HELPER_3(divso, tl, env, tl, tl)
 DEF_HELPER_2(load_dcr, tl, env, tl);
 DEF_HELPER_3(store_dcr, void, env, tl, tl)
 
-DEF_HELPER_1(load_dump_spr, void, i32)
-DEF_HELPER_1(store_dump_spr, void, i32)
+DEF_HELPER_2(load_dump_spr, void, env, i32)
+DEF_HELPER_2(store_dump_spr, void, env, i32)
 DEF_HELPER_1(load_tbl, tl, env)
 DEF_HELPER_1(load_tbu, tl, env)
 DEF_HELPER_1(load_atbl, tl, env)
@@ -385,10 +385,10 @@ DEF_HELPER_1(load_601_rtcl, tl, env)
 DEF_HELPER_1(load_601_rtcu, tl, env)
 #if !defined(CONFIG_USER_ONLY)
 #if defined(TARGET_PPC64)
-DEF_HELPER_1(store_asr, void, tl)
+DEF_HELPER_2(store_asr, void, env, tl)
 DEF_HELPER_1(load_purr, tl, env)
 #endif
-DEF_HELPER_1(store_sdr1, void, tl)
+DEF_HELPER_2(store_sdr1, void, env, tl)
 DEF_HELPER_2(store_tbl, void, env, tl)
 DEF_HELPER_2(store_tbu, void, env, tl)
 DEF_HELPER_2(store_atbl, void, env, tl)
@@ -397,12 +397,12 @@ DEF_HELPER_2(store_601_rtcl, void, env, tl)
 DEF_HELPER_2(store_601_rtcu, void, env, tl)
 DEF_HELPER_1(load_decr, tl, env)
 DEF_HELPER_2(store_decr, void, env, tl)
-DEF_HELPER_1(store_hid0_601, void, tl)
-DEF_HELPER_2(store_403_pbr, void, i32, tl)
+DEF_HELPER_2(store_hid0_601, void, env, tl)
+DEF_HELPER_3(store_403_pbr, void, env, i32, tl)
 DEF_HELPER_1(load_40x_pit, tl, env)
 DEF_HELPER_2(store_40x_pit, void, env, tl)
-DEF_HELPER_1(store_40x_dbcr0, void, tl)
-DEF_HELPER_1(store_40x_sler, void, tl)
+DEF_HELPER_2(store_40x_dbcr0, void, env, tl)
+DEF_HELPER_2(store_40x_sler, void, env, tl)
 DEF_HELPER_2(store_booke_tcr, void, env, tl)
 DEF_HELPER_2(store_booke_tsr, void, env, tl)
 DEF_HELPER_3(store_ibatl, void, env, i32, tl)
diff --git a/target-ppc/misc_helper.c b/target-ppc/misc_helper.c
index 67eab08..b194d19 100644
--- a/target-ppc/misc_helper.c
+++ b/target-ppc/misc_helper.c
@@ -17,38 +17,37 @@
  * License along with this library; if not, see <http://www.gnu.org/licenses/>.
  */
 #include "cpu.h"
-#include "dyngen-exec.h"
 #include "helper.h"
 
 #include "helper_regs.h"
 
 /*****************************************************************************/
 /* SPR accesses */
-void helper_load_dump_spr(uint32_t sprn)
+void helper_load_dump_spr(CPUPPCState *env, uint32_t sprn)
 {
     qemu_log("Read SPR %d %03x => " TARGET_FMT_lx "\n", sprn, sprn,
              env->spr[sprn]);
 }
 
-void helper_store_dump_spr(uint32_t sprn)
+void helper_store_dump_spr(CPUPPCState *env, uint32_t sprn)
 {
     qemu_log("Write SPR %d %03x <= " TARGET_FMT_lx "\n", sprn, sprn,
              env->spr[sprn]);
 }
 #if !defined(CONFIG_USER_ONLY)
 #if defined(TARGET_PPC64)
-void helper_store_asr(target_ulong val)
+void helper_store_asr(CPUPPCState *env, target_ulong val)
 {
     ppc_store_asr(env, val);
 }
 #endif
 
-void helper_store_sdr1(target_ulong val)
+void helper_store_sdr1(CPUPPCState *env, target_ulong val)
 {
     ppc_store_sdr1(env, val);
 }
 
-void helper_store_hid0_601(target_ulong val)
+void helper_store_hid0_601(CPUPPCState *env, target_ulong val)
 {
     target_ulong hid0;
 
@@ -65,7 +64,7 @@ void helper_store_hid0_601(target_ulong val)
     env->spr[SPR_HID0] = (uint32_t)val;
 }
 
-void helper_store_403_pbr(uint32_t num, target_ulong value)
+void helper_store_403_pbr(CPUPPCState *env, uint32_t num, target_ulong value)
 {
     if (likely(env->pb[num] != value)) {
         env->pb[num] = value;
@@ -74,12 +73,12 @@ void helper_store_403_pbr(uint32_t num, target_ulong value)
     }
 }
 
-void helper_store_40x_dbcr0(target_ulong val)
+void helper_store_40x_dbcr0(CPUPPCState *env, target_ulong val)
 {
     store_40x_dbcr0(env, val);
 }
 
-void helper_store_40x_sler(target_ulong val)
+void helper_store_40x_sler(CPUPPCState *env, target_ulong val)
 {
     store_40x_sler(env, val);
 }
@@ -87,7 +86,7 @@ void helper_store_40x_sler(target_ulong val)
 /*****************************************************************************/
 /* PowerPC 601 specific instructions (POWER bridge) */
 
-target_ulong helper_clcs(uint32_t arg)
+target_ulong helper_clcs(CPUPPCState *env, uint32_t arg)
 {
     switch (arg) {
     case 0x0CUL:
diff --git a/target-ppc/translate.c b/target-ppc/translate.c
index 5eec4b0..bcc9933 100644
--- a/target-ppc/translate.c
+++ b/target-ppc/translate.c
@@ -4551,7 +4551,7 @@ static void gen_abso(DisasContext *ctx)
 static void gen_clcs(DisasContext *ctx)
 {
     TCGv_i32 t0 = tcg_const_i32(rA(ctx->opcode));
-    gen_helper_clcs(cpu_gpr[rD(ctx->opcode)], t0);
+    gen_helper_clcs(cpu_gpr[rD(ctx->opcode)], cpu_env, t0);
     tcg_temp_free_i32(t0);
     /* Rc=1 sets CR0 to an undefined state */
 }
diff --git a/target-ppc/translate_init.c b/target-ppc/translate_init.c
index f3a8aa5..f6ac589 100644
--- a/target-ppc/translate_init.c
+++ b/target-ppc/translate_init.c
@@ -347,7 +347,7 @@ static void spr_write_dbatl_h (void *opaque, int sprn, int gprn)
 /* SDR1 */
 static void spr_write_sdr1 (void *opaque, int sprn, int gprn)
 {
-    gen_helper_store_sdr1(cpu_gpr[gprn]);
+    gen_helper_store_sdr1(cpu_env, cpu_gpr[gprn]);
 }
 
 /* 64 bits PowerPC specific SPRs */
@@ -373,7 +373,7 @@ static void spr_read_asr (void *opaque, int gprn, int sprn)
 
 static void spr_write_asr (void *opaque, int sprn, int gprn)
 {
-    gen_helper_store_asr(cpu_gpr[gprn]);
+    gen_helper_store_asr(cpu_env, cpu_gpr[gprn]);
 }
 #endif
 #endif
@@ -405,7 +405,7 @@ static void spr_write_hid0_601 (void *opaque, int sprn, int gprn)
 {
     DisasContext *ctx = opaque;
 
-    gen_helper_store_hid0_601(cpu_gpr[gprn]);
+    gen_helper_store_hid0_601(cpu_env, cpu_gpr[gprn]);
     /* Must stop the translation as endianness may have changed */
     gen_stop_exception(ctx);
 }
@@ -449,14 +449,14 @@ static void spr_write_40x_dbcr0 (void *opaque, int sprn, int gprn)
 {
     DisasContext *ctx = opaque;
 
-    gen_helper_store_40x_dbcr0(cpu_gpr[gprn]);
+    gen_helper_store_40x_dbcr0(cpu_env, cpu_gpr[gprn]);
     /* We must stop translation as we may have rebooted */
     gen_stop_exception(ctx);
 }
 
 static void spr_write_40x_sler (void *opaque, int sprn, int gprn)
 {
-    gen_helper_store_40x_sler(cpu_gpr[gprn]);
+    gen_helper_store_40x_sler(cpu_env, cpu_gpr[gprn]);
 }
 
 static void spr_write_booke_tcr (void *opaque, int sprn, int gprn)
@@ -481,7 +481,7 @@ static void spr_read_403_pbr (void *opaque, int gprn, int sprn)
 static void spr_write_403_pbr (void *opaque, int sprn, int gprn)
 {
     TCGv_i32 t0 = tcg_const_i32(sprn - SPR_403_PBL1);
-    gen_helper_store_403_pbr(t0, cpu_gpr[gprn]);
+    gen_helper_store_403_pbr(cpu_env, t0, cpu_gpr[gprn]);
     tcg_temp_free_i32(t0);
 }
 
commit 901c4eaf9670060c837987dac7912e5ab46df58a
Author: Blue Swirl <blauwirbel at gmail.com>
Date:   Wed May 30 04:23:37 2012 +0000

    ppc: Split off misc helpers
    
    Move misc helpers from op_helper.c to misc_helpers.c.
    
    Signed-off-by: Blue Swirl <blauwirbel at gmail.com>
    Signed-off-by: Alexander Graf <agraf at suse.de>
    Signed-off-by: Andreas Färber <afaerber at suse.de>
    Signed-off-by: Alexander Graf <agraf at suse.de>

diff --git a/target-ppc/Makefile.objs b/target-ppc/Makefile.objs
index 4a88641..3a444eb 100644
--- a/target-ppc/Makefile.objs
+++ b/target-ppc/Makefile.objs
@@ -7,5 +7,7 @@ obj-y += fpu_helper.o
 obj-y += int_helper.o
 obj-y += mmu_helper.o
 obj-y += timebase_helper.o
+obj-y += misc_helper.o
 
+$(obj)/misc_helper.o: QEMU_CFLAGS += $(HELPER_CFLAGS)
 $(obj)/op_helper.o: QEMU_CFLAGS += $(HELPER_CFLAGS)
diff --git a/target-ppc/misc_helper.c b/target-ppc/misc_helper.c
new file mode 100644
index 0000000..67eab08
--- /dev/null
+++ b/target-ppc/misc_helper.c
@@ -0,0 +1,116 @@
+/*
+ * Miscellaneous PowerPC emulation helpers for QEMU.
+ *
+ *  Copyright (c) 2003-2007 Jocelyn Mayer
+ *
+ * This library is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Lesser General Public
+ * License as published by the Free Software Foundation; either
+ * version 2 of the License, or (at your option) any later version.
+ *
+ * This library is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
+ * Lesser General Public License for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public
+ * License along with this library; if not, see <http://www.gnu.org/licenses/>.
+ */
+#include "cpu.h"
+#include "dyngen-exec.h"
+#include "helper.h"
+
+#include "helper_regs.h"
+
+/*****************************************************************************/
+/* SPR accesses */
+void helper_load_dump_spr(uint32_t sprn)
+{
+    qemu_log("Read SPR %d %03x => " TARGET_FMT_lx "\n", sprn, sprn,
+             env->spr[sprn]);
+}
+
+void helper_store_dump_spr(uint32_t sprn)
+{
+    qemu_log("Write SPR %d %03x <= " TARGET_FMT_lx "\n", sprn, sprn,
+             env->spr[sprn]);
+}
+#if !defined(CONFIG_USER_ONLY)
+#if defined(TARGET_PPC64)
+void helper_store_asr(target_ulong val)
+{
+    ppc_store_asr(env, val);
+}
+#endif
+
+void helper_store_sdr1(target_ulong val)
+{
+    ppc_store_sdr1(env, val);
+}
+
+void helper_store_hid0_601(target_ulong val)
+{
+    target_ulong hid0;
+
+    hid0 = env->spr[SPR_HID0];
+    if ((val ^ hid0) & 0x00000008) {
+        /* Change current endianness */
+        env->hflags &= ~(1 << MSR_LE);
+        env->hflags_nmsr &= ~(1 << MSR_LE);
+        env->hflags_nmsr |= (1 << MSR_LE) & (((val >> 3) & 1) << MSR_LE);
+        env->hflags |= env->hflags_nmsr;
+        qemu_log("%s: set endianness to %c => " TARGET_FMT_lx "\n", __func__,
+                 val & 0x8 ? 'l' : 'b', env->hflags);
+    }
+    env->spr[SPR_HID0] = (uint32_t)val;
+}
+
+void helper_store_403_pbr(uint32_t num, target_ulong value)
+{
+    if (likely(env->pb[num] != value)) {
+        env->pb[num] = value;
+        /* Should be optimized */
+        tlb_flush(env, 1);
+    }
+}
+
+void helper_store_40x_dbcr0(target_ulong val)
+{
+    store_40x_dbcr0(env, val);
+}
+
+void helper_store_40x_sler(target_ulong val)
+{
+    store_40x_sler(env, val);
+}
+#endif
+/*****************************************************************************/
+/* PowerPC 601 specific instructions (POWER bridge) */
+
+target_ulong helper_clcs(uint32_t arg)
+{
+    switch (arg) {
+    case 0x0CUL:
+        /* Instruction cache line size */
+        return env->icache_line_size;
+        break;
+    case 0x0DUL:
+        /* Data cache line size */
+        return env->dcache_line_size;
+        break;
+    case 0x0EUL:
+        /* Minimum cache line size */
+        return (env->icache_line_size < env->dcache_line_size) ?
+            env->icache_line_size : env->dcache_line_size;
+        break;
+    case 0x0FUL:
+        /* Maximum cache line size */
+        return (env->icache_line_size > env->dcache_line_size) ?
+            env->icache_line_size : env->dcache_line_size;
+        break;
+    default:
+        /* Undefined */
+        return 0;
+        break;
+    }
+}
diff --git a/target-ppc/op_helper.c b/target-ppc/op_helper.c
index 0929906..cd1a533 100644
--- a/target-ppc/op_helper.c
+++ b/target-ppc/op_helper.c
@@ -31,69 +31,6 @@
 //#define DEBUG_OP
 
 /*****************************************************************************/
-/* SPR accesses */
-void helper_load_dump_spr(uint32_t sprn)
-{
-    qemu_log("Read SPR %d %03x => " TARGET_FMT_lx "\n", sprn, sprn,
-             env->spr[sprn]);
-}
-
-void helper_store_dump_spr(uint32_t sprn)
-{
-    qemu_log("Write SPR %d %03x <= " TARGET_FMT_lx "\n", sprn, sprn,
-             env->spr[sprn]);
-}
-#if !defined(CONFIG_USER_ONLY)
-#if defined(TARGET_PPC64)
-void helper_store_asr(target_ulong val)
-{
-    ppc_store_asr(env, val);
-}
-#endif
-
-void helper_store_sdr1(target_ulong val)
-{
-    ppc_store_sdr1(env, val);
-}
-
-void helper_store_hid0_601(target_ulong val)
-{
-    target_ulong hid0;
-
-    hid0 = env->spr[SPR_HID0];
-    if ((val ^ hid0) & 0x00000008) {
-        /* Change current endianness */
-        env->hflags &= ~(1 << MSR_LE);
-        env->hflags_nmsr &= ~(1 << MSR_LE);
-        env->hflags_nmsr |= (1 << MSR_LE) & (((val >> 3) & 1) << MSR_LE);
-        env->hflags |= env->hflags_nmsr;
-        qemu_log("%s: set endianness to %c => " TARGET_FMT_lx "\n", __func__,
-                 val & 0x8 ? 'l' : 'b', env->hflags);
-    }
-    env->spr[SPR_HID0] = (uint32_t)val;
-}
-
-void helper_store_403_pbr(uint32_t num, target_ulong value)
-{
-    if (likely(env->pb[num] != value)) {
-        env->pb[num] = value;
-        /* Should be optimized */
-        tlb_flush(env, 1);
-    }
-}
-
-void helper_store_40x_dbcr0(target_ulong val)
-{
-    store_40x_dbcr0(env, val);
-}
-
-void helper_store_40x_sler(target_ulong val)
-{
-    store_40x_sler(env, val);
-}
-#endif
-
-/*****************************************************************************/
 /* Memory load and stores */
 
 static inline target_ulong addr_add(target_ulong addr, target_long arg)
@@ -252,37 +189,6 @@ target_ulong helper_lscbx(target_ulong addr, uint32_t reg, uint32_t ra,
 }
 
 /*****************************************************************************/
-/* PowerPC 601 specific instructions (POWER bridge) */
-
-target_ulong helper_clcs(uint32_t arg)
-{
-    switch (arg) {
-    case 0x0CUL:
-        /* Instruction cache line size */
-        return env->icache_line_size;
-        break;
-    case 0x0DUL:
-        /* Data cache line size */
-        return env->dcache_line_size;
-        break;
-    case 0x0EUL:
-        /* Minimum cache line size */
-        return (env->icache_line_size < env->dcache_line_size) ?
-            env->icache_line_size : env->dcache_line_size;
-        break;
-    case 0x0FUL:
-        /* Maximum cache line size */
-        return (env->icache_line_size > env->dcache_line_size) ?
-            env->icache_line_size : env->dcache_line_size;
-        break;
-    default:
-        /* Undefined */
-        return 0;
-        break;
-    }
-}
-
-/*****************************************************************************/
 /* Altivec extension helpers */
 #if defined(HOST_WORDS_BIGENDIAN)
 #define HI_IDX 0
commit d0f1562d6ace0fdb7d2db190dd5a9a2e7492c3b3
Author: Blue Swirl <blauwirbel at gmail.com>
Date:   Wed May 30 04:23:36 2012 +0000

    ppc: Avoid AREG0 for timebase helpers
    
    Add an explicit CPUPPCState parameter instead of relying on AREG0.
    
    Signed-off-by: Blue Swirl <blauwirbel at gmail.com>
    Signed-off-by: Alexander Graf <agraf at suse.de>
    Signed-off-by: Andreas Färber <afaerber at suse.de>
    Signed-off-by: Alexander Graf <agraf at suse.de>

diff --git a/target-ppc/Makefile.objs b/target-ppc/Makefile.objs
index 19dc744..4a88641 100644
--- a/target-ppc/Makefile.objs
+++ b/target-ppc/Makefile.objs
@@ -8,5 +8,4 @@ obj-y += int_helper.o
 obj-y += mmu_helper.o
 obj-y += timebase_helper.o
 
-$(obj)/timebase_helper.o: QEMU_CFLAGS += $(HELPER_CFLAGS)
 $(obj)/op_helper.o: QEMU_CFLAGS += $(HELPER_CFLAGS)
diff --git a/target-ppc/helper.h b/target-ppc/helper.h
index b1f7ba5..81fc40e 100644
--- a/target-ppc/helper.h
+++ b/target-ppc/helper.h
@@ -372,39 +372,39 @@ DEF_HELPER_3(divo, tl, env, tl, tl)
 DEF_HELPER_3(divs, tl, env, tl, tl)
 DEF_HELPER_3(divso, tl, env, tl, tl)
 
-DEF_HELPER_1(load_dcr, tl, tl);
-DEF_HELPER_2(store_dcr, void, tl, tl)
+DEF_HELPER_2(load_dcr, tl, env, tl);
+DEF_HELPER_3(store_dcr, void, env, tl, tl)
 
 DEF_HELPER_1(load_dump_spr, void, i32)
 DEF_HELPER_1(store_dump_spr, void, i32)
-DEF_HELPER_0(load_tbl, tl)
-DEF_HELPER_0(load_tbu, tl)
-DEF_HELPER_0(load_atbl, tl)
-DEF_HELPER_0(load_atbu, tl)
-DEF_HELPER_0(load_601_rtcl, tl)
-DEF_HELPER_0(load_601_rtcu, tl)
+DEF_HELPER_1(load_tbl, tl, env)
+DEF_HELPER_1(load_tbu, tl, env)
+DEF_HELPER_1(load_atbl, tl, env)
+DEF_HELPER_1(load_atbu, tl, env)
+DEF_HELPER_1(load_601_rtcl, tl, env)
+DEF_HELPER_1(load_601_rtcu, tl, env)
 #if !defined(CONFIG_USER_ONLY)
 #if defined(TARGET_PPC64)
 DEF_HELPER_1(store_asr, void, tl)
-DEF_HELPER_0(load_purr, tl)
+DEF_HELPER_1(load_purr, tl, env)
 #endif
 DEF_HELPER_1(store_sdr1, void, tl)
-DEF_HELPER_1(store_tbl, void, tl)
-DEF_HELPER_1(store_tbu, void, tl)
-DEF_HELPER_1(store_atbl, void, tl)
-DEF_HELPER_1(store_atbu, void, tl)
-DEF_HELPER_1(store_601_rtcl, void, tl)
-DEF_HELPER_1(store_601_rtcu, void, tl)
-DEF_HELPER_0(load_decr, tl)
-DEF_HELPER_1(store_decr, void, tl)
+DEF_HELPER_2(store_tbl, void, env, tl)
+DEF_HELPER_2(store_tbu, void, env, tl)
+DEF_HELPER_2(store_atbl, void, env, tl)
+DEF_HELPER_2(store_atbu, void, env, tl)
+DEF_HELPER_2(store_601_rtcl, void, env, tl)
+DEF_HELPER_2(store_601_rtcu, void, env, tl)
+DEF_HELPER_1(load_decr, tl, env)
+DEF_HELPER_2(store_decr, void, env, tl)
 DEF_HELPER_1(store_hid0_601, void, tl)
 DEF_HELPER_2(store_403_pbr, void, i32, tl)
-DEF_HELPER_0(load_40x_pit, tl)
-DEF_HELPER_1(store_40x_pit, void, tl)
+DEF_HELPER_1(load_40x_pit, tl, env)
+DEF_HELPER_2(store_40x_pit, void, env, tl)
 DEF_HELPER_1(store_40x_dbcr0, void, tl)
 DEF_HELPER_1(store_40x_sler, void, tl)
-DEF_HELPER_1(store_booke_tcr, void, tl)
-DEF_HELPER_1(store_booke_tsr, void, tl)
+DEF_HELPER_2(store_booke_tcr, void, env, tl)
+DEF_HELPER_2(store_booke_tsr, void, env, tl)
 DEF_HELPER_3(store_ibatl, void, env, i32, tl)
 DEF_HELPER_3(store_ibatu, void, env, i32, tl)
 DEF_HELPER_3(store_dbatl, void, env, i32, tl)
diff --git a/target-ppc/timebase_helper.c b/target-ppc/timebase_helper.c
index 23f5cfa..fad738a 100644
--- a/target-ppc/timebase_helper.c
+++ b/target-ppc/timebase_helper.c
@@ -17,106 +17,105 @@
  * License along with this library; if not, see <http://www.gnu.org/licenses/>.
  */
 #include "cpu.h"
-#include "dyngen-exec.h"
 #include "helper.h"
 
 /*****************************************************************************/
 /* SPR accesses */
 
-target_ulong helper_load_tbl(void)
+target_ulong helper_load_tbl(CPUPPCState *env)
 {
     return (target_ulong)cpu_ppc_load_tbl(env);
 }
 
-target_ulong helper_load_tbu(void)
+target_ulong helper_load_tbu(CPUPPCState *env)
 {
     return cpu_ppc_load_tbu(env);
 }
 
-target_ulong helper_load_atbl(void)
+target_ulong helper_load_atbl(CPUPPCState *env)
 {
     return (target_ulong)cpu_ppc_load_atbl(env);
 }
 
-target_ulong helper_load_atbu(void)
+target_ulong helper_load_atbu(CPUPPCState *env)
 {
     return cpu_ppc_load_atbu(env);
 }
 
 #if defined(TARGET_PPC64) && !defined(CONFIG_USER_ONLY)
-target_ulong helper_load_purr(void)
+target_ulong helper_load_purr(CPUPPCState *env)
 {
     return (target_ulong)cpu_ppc_load_purr(env);
 }
 #endif
 
-target_ulong helper_load_601_rtcl(void)
+target_ulong helper_load_601_rtcl(CPUPPCState *env)
 {
     return cpu_ppc601_load_rtcl(env);
 }
 
-target_ulong helper_load_601_rtcu(void)
+target_ulong helper_load_601_rtcu(CPUPPCState *env)
 {
     return cpu_ppc601_load_rtcu(env);
 }
 
 #if !defined(CONFIG_USER_ONLY)
-void helper_store_tbl(target_ulong val)
+void helper_store_tbl(CPUPPCState *env, target_ulong val)
 {
     cpu_ppc_store_tbl(env, val);
 }
 
-void helper_store_tbu(target_ulong val)
+void helper_store_tbu(CPUPPCState *env, target_ulong val)
 {
     cpu_ppc_store_tbu(env, val);
 }
 
-void helper_store_atbl(target_ulong val)
+void helper_store_atbl(CPUPPCState *env, target_ulong val)
 {
     cpu_ppc_store_atbl(env, val);
 }
 
-void helper_store_atbu(target_ulong val)
+void helper_store_atbu(CPUPPCState *env, target_ulong val)
 {
     cpu_ppc_store_atbu(env, val);
 }
 
-void helper_store_601_rtcl(target_ulong val)
+void helper_store_601_rtcl(CPUPPCState *env, target_ulong val)
 {
     cpu_ppc601_store_rtcl(env, val);
 }
 
-void helper_store_601_rtcu(target_ulong val)
+void helper_store_601_rtcu(CPUPPCState *env, target_ulong val)
 {
     cpu_ppc601_store_rtcu(env, val);
 }
 
-target_ulong helper_load_decr(void)
+target_ulong helper_load_decr(CPUPPCState *env)
 {
     return cpu_ppc_load_decr(env);
 }
 
-void helper_store_decr(target_ulong val)
+void helper_store_decr(CPUPPCState *env, target_ulong val)
 {
     cpu_ppc_store_decr(env, val);
 }
 
-target_ulong helper_load_40x_pit(void)
+target_ulong helper_load_40x_pit(CPUPPCState *env)
 {
     return load_40x_pit(env);
 }
 
-void helper_store_40x_pit(target_ulong val)
+void helper_store_40x_pit(CPUPPCState *env, target_ulong val)
 {
     store_40x_pit(env, val);
 }
 
-void helper_store_booke_tcr(target_ulong val)
+void helper_store_booke_tcr(CPUPPCState *env, target_ulong val)
 {
     store_booke_tcr(env, val);
 }
 
-void helper_store_booke_tsr(target_ulong val)
+void helper_store_booke_tsr(CPUPPCState *env, target_ulong val)
 {
     store_booke_tsr(env, val);
 }
@@ -126,7 +125,7 @@ void helper_store_booke_tsr(target_ulong val)
 /* Embedded PowerPC specific helpers */
 
 /* XXX: to be improved to check access rights when in user-mode */
-target_ulong helper_load_dcr(target_ulong dcrn)
+target_ulong helper_load_dcr(CPUPPCState *env, target_ulong dcrn)
 {
     uint32_t val = 0;
 
@@ -144,7 +143,7 @@ target_ulong helper_load_dcr(target_ulong dcrn)
     return val;
 }
 
-void helper_store_dcr(target_ulong dcrn, target_ulong val)
+void helper_store_dcr(CPUPPCState *env, target_ulong dcrn, target_ulong val)
 {
     if (unlikely(env->dcr_env == NULL)) {
         qemu_log("No DCR environment\n");
diff --git a/target-ppc/translate.c b/target-ppc/translate.c
index 446f97e..5eec4b0 100644
--- a/target-ppc/translate.c
+++ b/target-ppc/translate.c
@@ -5717,7 +5717,7 @@ static void gen_mfdcr(DisasContext *ctx)
     /* NIP cannot be restored if the memory exception comes from an helper */
     gen_update_nip(ctx, ctx->nip - 4);
     dcrn = tcg_const_tl(SPR(ctx->opcode));
-    gen_helper_load_dcr(cpu_gpr[rD(ctx->opcode)], dcrn);
+    gen_helper_load_dcr(cpu_gpr[rD(ctx->opcode)], cpu_env, dcrn);
     tcg_temp_free(dcrn);
 #endif
 }
@@ -5736,7 +5736,7 @@ static void gen_mtdcr(DisasContext *ctx)
     /* NIP cannot be restored if the memory exception comes from an helper */
     gen_update_nip(ctx, ctx->nip - 4);
     dcrn = tcg_const_tl(SPR(ctx->opcode));
-    gen_helper_store_dcr(dcrn, cpu_gpr[rS(ctx->opcode)]);
+    gen_helper_store_dcr(cpu_env, dcrn, cpu_gpr[rS(ctx->opcode)]);
     tcg_temp_free(dcrn);
 #endif
 }
@@ -5754,7 +5754,8 @@ static void gen_mfdcrx(DisasContext *ctx)
     }
     /* NIP cannot be restored if the memory exception comes from an helper */
     gen_update_nip(ctx, ctx->nip - 4);
-    gen_helper_load_dcr(cpu_gpr[rD(ctx->opcode)], cpu_gpr[rA(ctx->opcode)]);
+    gen_helper_load_dcr(cpu_gpr[rD(ctx->opcode)], cpu_env,
+                        cpu_gpr[rA(ctx->opcode)]);
     /* Note: Rc update flag set leads to undefined state of Rc0 */
 #endif
 }
@@ -5772,7 +5773,8 @@ static void gen_mtdcrx(DisasContext *ctx)
     }
     /* NIP cannot be restored if the memory exception comes from an helper */
     gen_update_nip(ctx, ctx->nip - 4);
-    gen_helper_store_dcr(cpu_gpr[rA(ctx->opcode)], cpu_gpr[rS(ctx->opcode)]);
+    gen_helper_store_dcr(cpu_env, cpu_gpr[rA(ctx->opcode)],
+                         cpu_gpr[rS(ctx->opcode)]);
     /* Note: Rc update flag set leads to undefined state of Rc0 */
 #endif
 }
@@ -5782,7 +5784,8 @@ static void gen_mfdcrux(DisasContext *ctx)
 {
     /* NIP cannot be restored if the memory exception comes from an helper */
     gen_update_nip(ctx, ctx->nip - 4);
-    gen_helper_load_dcr(cpu_gpr[rD(ctx->opcode)], cpu_gpr[rA(ctx->opcode)]);
+    gen_helper_load_dcr(cpu_gpr[rD(ctx->opcode)], cpu_env,
+                        cpu_gpr[rA(ctx->opcode)]);
     /* Note: Rc update flag set leads to undefined state of Rc0 */
 }
 
@@ -5791,7 +5794,8 @@ static void gen_mtdcrux(DisasContext *ctx)
 {
     /* NIP cannot be restored if the memory exception comes from an helper */
     gen_update_nip(ctx, ctx->nip - 4);
-    gen_helper_store_dcr(cpu_gpr[rA(ctx->opcode)], cpu_gpr[rS(ctx->opcode)]);
+    gen_helper_store_dcr(cpu_gpr[rA(ctx->opcode)], cpu_env,
+                         cpu_gpr[rS(ctx->opcode)]);
     /* Note: Rc update flag set leads to undefined state of Rc0 */
 }
 
diff --git a/target-ppc/translate_init.c b/target-ppc/translate_init.c
index 1e15fd9..f3a8aa5 100644
--- a/target-ppc/translate_init.c
+++ b/target-ppc/translate_init.c
@@ -159,7 +159,7 @@ static void spr_read_decr (void *opaque, int gprn, int sprn)
     if (use_icount) {
         gen_io_start();
     }
-    gen_helper_load_decr(cpu_gpr[gprn]);
+    gen_helper_load_decr(cpu_gpr[gprn], cpu_env);
     if (use_icount) {
         gen_io_end();
         gen_stop_exception(opaque);
@@ -171,7 +171,7 @@ static void spr_write_decr (void *opaque, int sprn, int gprn)
     if (use_icount) {
         gen_io_start();
     }
-    gen_helper_store_decr(cpu_gpr[gprn]);
+    gen_helper_store_decr(cpu_env, cpu_gpr[gprn]);
     if (use_icount) {
         gen_io_end();
         gen_stop_exception(opaque);
@@ -186,7 +186,7 @@ static void spr_read_tbl (void *opaque, int gprn, int sprn)
     if (use_icount) {
         gen_io_start();
     }
-    gen_helper_load_tbl(cpu_gpr[gprn]);
+    gen_helper_load_tbl(cpu_gpr[gprn], cpu_env);
     if (use_icount) {
         gen_io_end();
         gen_stop_exception(opaque);
@@ -198,7 +198,7 @@ static void spr_read_tbu (void *opaque, int gprn, int sprn)
     if (use_icount) {
         gen_io_start();
     }
-    gen_helper_load_tbu(cpu_gpr[gprn]);
+    gen_helper_load_tbu(cpu_gpr[gprn], cpu_env);
     if (use_icount) {
         gen_io_end();
         gen_stop_exception(opaque);
@@ -208,13 +208,13 @@ static void spr_read_tbu (void *opaque, int gprn, int sprn)
 __attribute__ (( unused ))
 static void spr_read_atbl (void *opaque, int gprn, int sprn)
 {
-    gen_helper_load_atbl(cpu_gpr[gprn]);
+    gen_helper_load_atbl(cpu_gpr[gprn], cpu_env);
 }
 
 __attribute__ (( unused ))
 static void spr_read_atbu (void *opaque, int gprn, int sprn)
 {
-    gen_helper_load_atbu(cpu_gpr[gprn]);
+    gen_helper_load_atbu(cpu_gpr[gprn], cpu_env);
 }
 
 #if !defined(CONFIG_USER_ONLY)
@@ -223,7 +223,7 @@ static void spr_write_tbl (void *opaque, int sprn, int gprn)
     if (use_icount) {
         gen_io_start();
     }
-    gen_helper_store_tbl(cpu_gpr[gprn]);
+    gen_helper_store_tbl(cpu_env, cpu_gpr[gprn]);
     if (use_icount) {
         gen_io_end();
         gen_stop_exception(opaque);
@@ -235,7 +235,7 @@ static void spr_write_tbu (void *opaque, int sprn, int gprn)
     if (use_icount) {
         gen_io_start();
     }
-    gen_helper_store_tbu(cpu_gpr[gprn]);
+    gen_helper_store_tbu(cpu_env, cpu_gpr[gprn]);
     if (use_icount) {
         gen_io_end();
         gen_stop_exception(opaque);
@@ -245,20 +245,20 @@ static void spr_write_tbu (void *opaque, int sprn, int gprn)
 __attribute__ (( unused ))
 static void spr_write_atbl (void *opaque, int sprn, int gprn)
 {
-    gen_helper_store_atbl(cpu_gpr[gprn]);
+    gen_helper_store_atbl(cpu_env, cpu_gpr[gprn]);
 }
 
 __attribute__ (( unused ))
 static void spr_write_atbu (void *opaque, int sprn, int gprn)
 {
-    gen_helper_store_atbu(cpu_gpr[gprn]);
+    gen_helper_store_atbu(cpu_env, cpu_gpr[gprn]);
 }
 
 #if defined(TARGET_PPC64)
 __attribute__ (( unused ))
 static void spr_read_purr (void *opaque, int gprn, int sprn)
 {
-    gen_helper_load_purr(cpu_gpr[gprn]);
+    gen_helper_load_purr(cpu_gpr[gprn], cpu_env);
 }
 #endif
 #endif
@@ -382,23 +382,23 @@ static void spr_write_asr (void *opaque, int sprn, int gprn)
 /* RTC */
 static void spr_read_601_rtcl (void *opaque, int gprn, int sprn)
 {
-    gen_helper_load_601_rtcl(cpu_gpr[gprn]);
+    gen_helper_load_601_rtcl(cpu_gpr[gprn], cpu_env);
 }
 
 static void spr_read_601_rtcu (void *opaque, int gprn, int sprn)
 {
-    gen_helper_load_601_rtcu(cpu_gpr[gprn]);
+    gen_helper_load_601_rtcu(cpu_gpr[gprn], cpu_env);
 }
 
 #if !defined(CONFIG_USER_ONLY)
 static void spr_write_601_rtcu (void *opaque, int sprn, int gprn)
 {
-    gen_helper_store_601_rtcu(cpu_gpr[gprn]);
+    gen_helper_store_601_rtcu(cpu_env, cpu_gpr[gprn]);
 }
 
 static void spr_write_601_rtcl (void *opaque, int sprn, int gprn)
 {
-    gen_helper_store_601_rtcl(cpu_gpr[gprn]);
+    gen_helper_store_601_rtcl(cpu_env, cpu_gpr[gprn]);
 }
 
 static void spr_write_hid0_601 (void *opaque, int sprn, int gprn)
@@ -437,12 +437,12 @@ static void spr_write_601_ubatl (void *opaque, int sprn, int gprn)
 #if !defined(CONFIG_USER_ONLY)
 static void spr_read_40x_pit (void *opaque, int gprn, int sprn)
 {
-    gen_helper_load_40x_pit(cpu_gpr[gprn]);
+    gen_helper_load_40x_pit(cpu_gpr[gprn], cpu_env);
 }
 
 static void spr_write_40x_pit (void *opaque, int sprn, int gprn)
 {
-    gen_helper_store_40x_pit(cpu_gpr[gprn]);
+    gen_helper_store_40x_pit(cpu_env, cpu_gpr[gprn]);
 }
 
 static void spr_write_40x_dbcr0 (void *opaque, int sprn, int gprn)
@@ -461,12 +461,12 @@ static void spr_write_40x_sler (void *opaque, int sprn, int gprn)
 
 static void spr_write_booke_tcr (void *opaque, int sprn, int gprn)
 {
-    gen_helper_store_booke_tcr(cpu_gpr[gprn]);
+    gen_helper_store_booke_tcr(cpu_env, cpu_gpr[gprn]);
 }
 
 static void spr_write_booke_tsr (void *opaque, int sprn, int gprn)
 {
-    gen_helper_store_booke_tsr(cpu_gpr[gprn]);
+    gen_helper_store_booke_tsr(cpu_env, cpu_gpr[gprn]);
 }
 #endif
 
commit 6de673d40660abc43605789fa2010f20abc5a7a4
Author: Blue Swirl <blauwirbel at gmail.com>
Date:   Wed May 30 04:23:35 2012 +0000

    ppc: Split off timebase helpers
    
    Move decrementer and timebase helpers to a dedicated file.
    
    Signed-off-by: Blue Swirl <blauwirbel at gmail.com>
    Signed-off-by: Alexander Graf <agraf at suse.de>
    Signed-off-by: Andreas Färber <afaerber at suse.de>
    Signed-off-by: Alexander Graf <agraf at suse.de>

diff --git a/target-ppc/Makefile.objs b/target-ppc/Makefile.objs
index 71e25b1..19dc744 100644
--- a/target-ppc/Makefile.objs
+++ b/target-ppc/Makefile.objs
@@ -6,5 +6,7 @@ obj-y += excp_helper.o
 obj-y += fpu_helper.o
 obj-y += int_helper.o
 obj-y += mmu_helper.o
+obj-y += timebase_helper.o
 
+$(obj)/timebase_helper.o: QEMU_CFLAGS += $(HELPER_CFLAGS)
 $(obj)/op_helper.o: QEMU_CFLAGS += $(HELPER_CFLAGS)
diff --git a/target-ppc/op_helper.c b/target-ppc/op_helper.c
index c854c71..0929906 100644
--- a/target-ppc/op_helper.c
+++ b/target-ppc/op_helper.c
@@ -43,44 +43,6 @@ void helper_store_dump_spr(uint32_t sprn)
     qemu_log("Write SPR %d %03x <= " TARGET_FMT_lx "\n", sprn, sprn,
              env->spr[sprn]);
 }
-
-target_ulong helper_load_tbl(void)
-{
-    return (target_ulong)cpu_ppc_load_tbl(env);
-}
-
-target_ulong helper_load_tbu(void)
-{
-    return cpu_ppc_load_tbu(env);
-}
-
-target_ulong helper_load_atbl(void)
-{
-    return (target_ulong)cpu_ppc_load_atbl(env);
-}
-
-target_ulong helper_load_atbu(void)
-{
-    return cpu_ppc_load_atbu(env);
-}
-
-#if defined(TARGET_PPC64) && !defined(CONFIG_USER_ONLY)
-target_ulong helper_load_purr(void)
-{
-    return (target_ulong)cpu_ppc_load_purr(env);
-}
-#endif
-
-target_ulong helper_load_601_rtcl(void)
-{
-    return cpu_ppc601_load_rtcl(env);
-}
-
-target_ulong helper_load_601_rtcu(void)
-{
-    return cpu_ppc601_load_rtcu(env);
-}
-
 #if !defined(CONFIG_USER_ONLY)
 #if defined(TARGET_PPC64)
 void helper_store_asr(target_ulong val)
@@ -94,46 +56,6 @@ void helper_store_sdr1(target_ulong val)
     ppc_store_sdr1(env, val);
 }
 
-void helper_store_tbl(target_ulong val)
-{
-    cpu_ppc_store_tbl(env, val);
-}
-
-void helper_store_tbu(target_ulong val)
-{
-    cpu_ppc_store_tbu(env, val);
-}
-
-void helper_store_atbl(target_ulong val)
-{
-    cpu_ppc_store_atbl(env, val);
-}
-
-void helper_store_atbu(target_ulong val)
-{
-    cpu_ppc_store_atbu(env, val);
-}
-
-void helper_store_601_rtcl(target_ulong val)
-{
-    cpu_ppc601_store_rtcl(env, val);
-}
-
-void helper_store_601_rtcu(target_ulong val)
-{
-    cpu_ppc601_store_rtcu(env, val);
-}
-
-target_ulong helper_load_decr(void)
-{
-    return cpu_ppc_load_decr(env);
-}
-
-void helper_store_decr(target_ulong val)
-{
-    cpu_ppc_store_decr(env, val);
-}
-
 void helper_store_hid0_601(target_ulong val)
 {
     target_ulong hid0;
@@ -160,16 +82,6 @@ void helper_store_403_pbr(uint32_t num, target_ulong value)
     }
 }
 
-target_ulong helper_load_40x_pit(void)
-{
-    return load_40x_pit(env);
-}
-
-void helper_store_40x_pit(target_ulong val)
-{
-    store_40x_pit(env, val);
-}
-
 void helper_store_40x_dbcr0(target_ulong val)
 {
     store_40x_dbcr0(env, val);
@@ -179,16 +91,6 @@ void helper_store_40x_sler(target_ulong val)
 {
     store_40x_sler(env, val);
 }
-
-void helper_store_booke_tcr(target_ulong val)
-{
-    store_booke_tcr(env, val);
-}
-
-void helper_store_booke_tsr(target_ulong val)
-{
-    store_booke_tsr(env, val);
-}
 #endif
 
 /*****************************************************************************/
@@ -381,43 +283,6 @@ target_ulong helper_clcs(uint32_t arg)
 }
 
 /*****************************************************************************/
-/* Embedded PowerPC specific helpers */
-
-/* XXX: to be improved to check access rights when in user-mode */
-target_ulong helper_load_dcr(target_ulong dcrn)
-{
-    uint32_t val = 0;
-
-    if (unlikely(env->dcr_env == NULL)) {
-        qemu_log("No DCR environment\n");
-        helper_raise_exception_err(env, POWERPC_EXCP_PROGRAM,
-                                   POWERPC_EXCP_INVAL |
-                                   POWERPC_EXCP_INVAL_INVAL);
-    } else if (unlikely(ppc_dcr_read(env->dcr_env,
-                                     (uint32_t)dcrn, &val) != 0)) {
-        qemu_log("DCR read error %d %03x\n", (uint32_t)dcrn, (uint32_t)dcrn);
-        helper_raise_exception_err(env, POWERPC_EXCP_PROGRAM,
-                                   POWERPC_EXCP_INVAL | POWERPC_EXCP_PRIV_REG);
-    }
-    return val;
-}
-
-void helper_store_dcr(target_ulong dcrn, target_ulong val)
-{
-    if (unlikely(env->dcr_env == NULL)) {
-        qemu_log("No DCR environment\n");
-        helper_raise_exception_err(env, POWERPC_EXCP_PROGRAM,
-                                   POWERPC_EXCP_INVAL |
-                                   POWERPC_EXCP_INVAL_INVAL);
-    } else if (unlikely(ppc_dcr_write(env->dcr_env, (uint32_t)dcrn,
-                                      (uint32_t)val) != 0)) {
-        qemu_log("DCR write error %d %03x\n", (uint32_t)dcrn, (uint32_t)dcrn);
-        helper_raise_exception_err(env, POWERPC_EXCP_PROGRAM,
-                                   POWERPC_EXCP_INVAL | POWERPC_EXCP_PRIV_REG);
-    }
-}
-
-/*****************************************************************************/
 /* Altivec extension helpers */
 #if defined(HOST_WORDS_BIGENDIAN)
 #define HI_IDX 0
diff --git a/target-ppc/timebase_helper.c b/target-ppc/timebase_helper.c
new file mode 100644
index 0000000..23f5cfa
--- /dev/null
+++ b/target-ppc/timebase_helper.c
@@ -0,0 +1,160 @@
+/*
+ *  PowerPC emulation helpers for QEMU.
+ *
+ *  Copyright (c) 2003-2007 Jocelyn Mayer
+ *
+ * This library is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Lesser General Public
+ * License as published by the Free Software Foundation; either
+ * version 2 of the License, or (at your option) any later version.
+ *
+ * This library is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
+ * Lesser General Public License for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public
+ * License along with this library; if not, see <http://www.gnu.org/licenses/>.
+ */
+#include "cpu.h"
+#include "dyngen-exec.h"
+#include "helper.h"
+
+/*****************************************************************************/
+/* SPR accesses */
+
+target_ulong helper_load_tbl(void)
+{
+    return (target_ulong)cpu_ppc_load_tbl(env);
+}
+
+target_ulong helper_load_tbu(void)
+{
+    return cpu_ppc_load_tbu(env);
+}
+
+target_ulong helper_load_atbl(void)
+{
+    return (target_ulong)cpu_ppc_load_atbl(env);
+}
+
+target_ulong helper_load_atbu(void)
+{
+    return cpu_ppc_load_atbu(env);
+}
+
+#if defined(TARGET_PPC64) && !defined(CONFIG_USER_ONLY)
+target_ulong helper_load_purr(void)
+{
+    return (target_ulong)cpu_ppc_load_purr(env);
+}
+#endif
+
+target_ulong helper_load_601_rtcl(void)
+{
+    return cpu_ppc601_load_rtcl(env);
+}
+
+target_ulong helper_load_601_rtcu(void)
+{
+    return cpu_ppc601_load_rtcu(env);
+}
+
+#if !defined(CONFIG_USER_ONLY)
+void helper_store_tbl(target_ulong val)
+{
+    cpu_ppc_store_tbl(env, val);
+}
+
+void helper_store_tbu(target_ulong val)
+{
+    cpu_ppc_store_tbu(env, val);
+}
+
+void helper_store_atbl(target_ulong val)
+{
+    cpu_ppc_store_atbl(env, val);
+}
+
+void helper_store_atbu(target_ulong val)
+{
+    cpu_ppc_store_atbu(env, val);
+}
+
+void helper_store_601_rtcl(target_ulong val)
+{
+    cpu_ppc601_store_rtcl(env, val);
+}
+
+void helper_store_601_rtcu(target_ulong val)
+{
+    cpu_ppc601_store_rtcu(env, val);
+}
+
+target_ulong helper_load_decr(void)
+{
+    return cpu_ppc_load_decr(env);
+}
+
+void helper_store_decr(target_ulong val)
+{
+    cpu_ppc_store_decr(env, val);
+}
+
+target_ulong helper_load_40x_pit(void)
+{
+    return load_40x_pit(env);
+}
+
+void helper_store_40x_pit(target_ulong val)
+{
+    store_40x_pit(env, val);
+}
+
+void helper_store_booke_tcr(target_ulong val)
+{
+    store_booke_tcr(env, val);
+}
+
+void helper_store_booke_tsr(target_ulong val)
+{
+    store_booke_tsr(env, val);
+}
+#endif
+
+/*****************************************************************************/
+/* Embedded PowerPC specific helpers */
+
+/* XXX: to be improved to check access rights when in user-mode */
+target_ulong helper_load_dcr(target_ulong dcrn)
+{
+    uint32_t val = 0;
+
+    if (unlikely(env->dcr_env == NULL)) {
+        qemu_log("No DCR environment\n");
+        helper_raise_exception_err(env, POWERPC_EXCP_PROGRAM,
+                                   POWERPC_EXCP_INVAL |
+                                   POWERPC_EXCP_INVAL_INVAL);
+    } else if (unlikely(ppc_dcr_read(env->dcr_env,
+                                     (uint32_t)dcrn, &val) != 0)) {
+        qemu_log("DCR read error %d %03x\n", (uint32_t)dcrn, (uint32_t)dcrn);
+        helper_raise_exception_err(env, POWERPC_EXCP_PROGRAM,
+                                   POWERPC_EXCP_INVAL | POWERPC_EXCP_PRIV_REG);
+    }
+    return val;
+}
+
+void helper_store_dcr(target_ulong dcrn, target_ulong val)
+{
+    if (unlikely(env->dcr_env == NULL)) {
+        qemu_log("No DCR environment\n");
+        helper_raise_exception_err(env, POWERPC_EXCP_PROGRAM,
+                                   POWERPC_EXCP_INVAL |
+                                   POWERPC_EXCP_INVAL_INVAL);
+    } else if (unlikely(ppc_dcr_write(env->dcr_env, (uint32_t)dcrn,
+                                      (uint32_t)val) != 0)) {
+        qemu_log("DCR write error %d %03x\n", (uint32_t)dcrn, (uint32_t)dcrn);
+        helper_raise_exception_err(env, POWERPC_EXCP_PROGRAM,
+                                   POWERPC_EXCP_INVAL | POWERPC_EXCP_PRIV_REG);
+    }
+}
commit 9aa5b15848b58a4879d2c4d971d102f22b6001a3
Author: Blue Swirl <blauwirbel at gmail.com>
Date:   Wed May 30 04:23:34 2012 +0000

    ppc: Cleanup MMU merge
    
    Remove useless wrappers. In some cases 'int' parameters are
    changed to uint32_t.
    
    Make internal functions static.
    
    Signed-off-by: Blue Swirl <blauwirbel at gmail.com>
    [agraf: fix kvm compilation]
    Signed-off-by: Alexander Graf <agraf at suse.de>
    Signed-off-by: Andreas Färber <afaerber at suse.de>
    Signed-off-by: Alexander Graf <agraf at suse.de>

diff --git a/target-ppc/cpu.h b/target-ppc/cpu.h
index 32cfcef..9b157f0 100644
--- a/target-ppc/cpu.h
+++ b/target-ppc/cpu.h
@@ -1118,24 +1118,11 @@ void do_interrupt (CPUPPCState *env);
 void ppc_hw_interrupt (CPUPPCState *env);
 
 #if !defined(CONFIG_USER_ONLY)
-void ppc6xx_tlb_store (CPUPPCState *env, target_ulong EPN, int way, int is_code,
-                       target_ulong pte0, target_ulong pte1);
-void ppc_store_ibatu (CPUPPCState *env, int nr, target_ulong value);
-void ppc_store_ibatl (CPUPPCState *env, int nr, target_ulong value);
-void ppc_store_dbatu (CPUPPCState *env, int nr, target_ulong value);
-void ppc_store_dbatl (CPUPPCState *env, int nr, target_ulong value);
-void ppc_store_ibatu_601 (CPUPPCState *env, int nr, target_ulong value);
-void ppc_store_ibatl_601 (CPUPPCState *env, int nr, target_ulong value);
 void ppc_store_sdr1 (CPUPPCState *env, target_ulong value);
 #if defined(TARGET_PPC64)
 void ppc_store_asr (CPUPPCState *env, target_ulong value);
-target_ulong ppc_load_slb (CPUPPCState *env, int slb_nr);
-target_ulong ppc_load_sr (CPUPPCState *env, int sr_nr);
 int ppc_store_slb (CPUPPCState *env, target_ulong rb, target_ulong rs);
-int ppc_load_slb_esid (CPUPPCState *env, target_ulong rb, target_ulong *rt);
-int ppc_load_slb_vsid (CPUPPCState *env, target_ulong rb, target_ulong *rt);
 #endif /* defined(TARGET_PPC64) */
-void ppc_store_sr (CPUPPCState *env, int srnum, target_ulong value);
 #endif /* !defined(CONFIG_USER_ONLY) */
 void ppc_store_msr (CPUPPCState *env, target_ulong value);
 
@@ -1174,19 +1161,11 @@ void store_booke_tcr (CPUPPCState *env, target_ulong val);
 void store_booke_tsr (CPUPPCState *env, target_ulong val);
 void booke206_flush_tlb(CPUPPCState *env, int flags, const int check_iprot);
 target_phys_addr_t booke206_tlb_to_page_size(CPUPPCState *env, ppcmas_tlb_t *tlb);
-int ppcemb_tlb_check(CPUPPCState *env, ppcemb_tlb_t *tlb,
-                     target_phys_addr_t *raddrp, target_ulong address,
-                     uint32_t pid, int ext, int i);
 int ppcmas_tlb_check(CPUPPCState *env, ppcmas_tlb_t *tlb,
                      target_phys_addr_t *raddrp, target_ulong address,
                      uint32_t pid);
 void ppc_tlb_invalidate_all (CPUPPCState *env);
 void ppc_tlb_invalidate_one (CPUPPCState *env, target_ulong addr);
-#if defined(TARGET_PPC64)
-void ppc_slb_invalidate_all (CPUPPCState *env);
-void ppc_slb_invalidate_one (CPUPPCState *env, uint64_t T0);
-#endif
-int ppcemb_tlb_search (CPUPPCState *env, target_ulong address, uint32_t pid);
 #endif
 #endif
 
diff --git a/target-ppc/mmu_helper.c b/target-ppc/mmu_helper.c
index 1f67451..d65d290 100644
--- a/target-ppc/mmu_helper.c
+++ b/target-ppc/mmu_helper.c
@@ -347,8 +347,8 @@ static inline void ppc6xx_tlb_invalidate_virt(CPUPPCState *env,
     ppc6xx_tlb_invalidate_virt2(env, eaddr, is_code, 0);
 }
 
-void ppc6xx_tlb_store(CPUPPCState *env, target_ulong EPN, int way, int is_code,
-                      target_ulong pte0, target_ulong pte1)
+static void ppc6xx_tlb_store(CPUPPCState *env, target_ulong EPN, int way,
+                             int is_code, target_ulong pte0, target_ulong pte1)
 {
     ppc6xx_tlb_t *tlb;
     int nr;
@@ -712,7 +712,10 @@ static inline ppc_slb_t *slb_lookup(CPUPPCState *env, target_ulong eaddr)
     return NULL;
 }
 
-void ppc_slb_invalidate_all(CPUPPCState *env)
+/*****************************************************************************/
+/* SPR accesses */
+
+void helper_slbia(CPUPPCState *env)
 {
     int n, do_invalidate;
 
@@ -735,11 +738,11 @@ void ppc_slb_invalidate_all(CPUPPCState *env)
     }
 }
 
-void ppc_slb_invalidate_one(CPUPPCState *env, uint64_t T0)
+void helper_slbie(CPUPPCState *env, target_ulong addr)
 {
     ppc_slb_t *slb;
 
-    slb = slb_lookup(env, T0);
+    slb = slb_lookup(env, addr);
     if (!slb) {
         return;
     }
@@ -781,7 +784,8 @@ int ppc_store_slb(CPUPPCState *env, target_ulong rb, target_ulong rs)
     return 0;
 }
 
-int ppc_load_slb_esid(CPUPPCState *env, target_ulong rb, target_ulong *rt)
+static int ppc_load_slb_esid(CPUPPCState *env, target_ulong rb,
+                             target_ulong *rt)
 {
     int slot = rb & 0xfff;
     ppc_slb_t *slb = &env->slb[slot];
@@ -794,7 +798,8 @@ int ppc_load_slb_esid(CPUPPCState *env, target_ulong rb, target_ulong *rt)
     return 0;
 }
 
-int ppc_load_slb_vsid(CPUPPCState *env, target_ulong rb, target_ulong *rt)
+static int ppc_load_slb_vsid(CPUPPCState *env, target_ulong rb,
+                             target_ulong *rt)
 {
     int slot = rb & 0xfff;
     ppc_slb_t *slb = &env->slb[slot];
@@ -1003,10 +1008,10 @@ static inline int get_segment(CPUPPCState *env, mmu_ctx_t *ctx,
 }
 
 /* Generic TLB check function for embedded PowerPC implementations */
-int ppcemb_tlb_check(CPUPPCState *env, ppcemb_tlb_t *tlb,
-                     target_phys_addr_t *raddrp,
-                     target_ulong address, uint32_t pid, int ext,
-                     int i)
+static int ppcemb_tlb_check(CPUPPCState *env, ppcemb_tlb_t *tlb,
+                            target_phys_addr_t *raddrp,
+                            target_ulong address, uint32_t pid, int ext,
+                            int i)
 {
     target_ulong mask;
 
@@ -1038,7 +1043,8 @@ int ppcemb_tlb_check(CPUPPCState *env, ppcemb_tlb_t *tlb,
 }
 
 /* Generic TLB search function for PowerPC embedded implementations */
-int ppcemb_tlb_search(CPUPPCState *env, target_ulong address, uint32_t pid)
+static int ppcemb_tlb_search(CPUPPCState *env, target_ulong address,
+                             uint32_t pid)
 {
     ppcemb_tlb_t *tlb;
     target_phys_addr_t raddr;
@@ -2144,7 +2150,7 @@ static inline void dump_store_bat(CPUPPCState *env, char ID, int ul, int nr,
              nr, ul == 0 ? 'u' : 'l', value, env->nip);
 }
 
-void ppc_store_ibatu(CPUPPCState *env, int nr, target_ulong value)
+void helper_store_ibatu(CPUPPCState *env, uint32_t nr, target_ulong value)
 {
     target_ulong mask;
 
@@ -2170,13 +2176,13 @@ void ppc_store_ibatu(CPUPPCState *env, int nr, target_ulong value)
     }
 }
 
-void ppc_store_ibatl(CPUPPCState *env, int nr, target_ulong value)
+void helper_store_ibatl(CPUPPCState *env, uint32_t nr, target_ulong value)
 {
     dump_store_bat(env, 'I', 1, nr, value);
     env->IBAT[1][nr] = value;
 }
 
-void ppc_store_dbatu(CPUPPCState *env, int nr, target_ulong value)
+void helper_store_dbatu(CPUPPCState *env, uint32_t nr, target_ulong value)
 {
     target_ulong mask;
 
@@ -2202,13 +2208,13 @@ void ppc_store_dbatu(CPUPPCState *env, int nr, target_ulong value)
     }
 }
 
-void ppc_store_dbatl(CPUPPCState *env, int nr, target_ulong value)
+void helper_store_dbatl(CPUPPCState *env, uint32_t nr, target_ulong value)
 {
     dump_store_bat(env, 'D', 1, nr, value);
     env->DBAT[1][nr] = value;
 }
 
-void ppc_store_ibatu_601(CPUPPCState *env, int nr, target_ulong value)
+void helper_store_601_batu(CPUPPCState *env, uint32_t nr, target_ulong value)
 {
     target_ulong mask;
 #if defined(FLUSH_ALL_TLBS)
@@ -2250,7 +2256,7 @@ void ppc_store_ibatu_601(CPUPPCState *env, int nr, target_ulong value)
     }
 }
 
-void ppc_store_ibatl_601(CPUPPCState *env, int nr, target_ulong value)
+void helper_store_601_batl(CPUPPCState *env, uint32_t nr, target_ulong value)
 {
     target_ulong mask;
 #if defined(FLUSH_ALL_TLBS)
@@ -2446,18 +2452,22 @@ void ppc_store_sdr1(CPUPPCState *env, target_ulong value)
     }
 }
 
-#if defined(TARGET_PPC64)
-target_ulong ppc_load_sr(CPUPPCState *env, int slb_nr)
+/* Segment registers load and store */
+target_ulong helper_load_sr(CPUPPCState *env, target_ulong sr_num)
 {
-    /* XXX */
-    return 0;
-}
+#if defined(TARGET_PPC64)
+    if (env->mmu_model & POWERPC_MMU_64) {
+        /* XXX */
+        return 0;
+    }
 #endif
+    return env->sr[sr_num];
+}
 
-void ppc_store_sr(CPUPPCState *env, int srnum, target_ulong value)
+void helper_store_sr(CPUPPCState *env, target_ulong srnum, target_ulong value)
 {
     LOG_MMU("%s: reg=%d " TARGET_FMT_lx " " TARGET_FMT_lx "\n", __func__,
-            srnum, value, env->sr[srnum]);
+            (int)srnum, value, env->sr[srnum]);
 #if defined(TARGET_PPC64)
     if (env->mmu_model & POWERPC_MMU_64) {
         uint64_t rb = 0, rs = 0;
@@ -2498,56 +2508,7 @@ void ppc_store_sr(CPUPPCState *env, int srnum, target_ulong value)
 }
 #endif /* !defined(CONFIG_USER_ONLY) */
 
-/*****************************************************************************/
-/* SPR accesses */
-
 #if !defined(CONFIG_USER_ONLY)
-void helper_store_ibatu(CPUPPCState *env, uint32_t nr, target_ulong val)
-{
-    ppc_store_ibatu(env, nr, val);
-}
-
-void helper_store_ibatl(CPUPPCState *env, uint32_t nr, target_ulong val)
-{
-    ppc_store_ibatl(env, nr, val);
-}
-
-void helper_store_dbatu(CPUPPCState *env, uint32_t nr, target_ulong val)
-{
-    ppc_store_dbatu(env, nr, val);
-}
-
-void helper_store_dbatl(CPUPPCState *env, uint32_t nr, target_ulong val)
-{
-    ppc_store_dbatl(env, nr, val);
-}
-
-void helper_store_601_batl(CPUPPCState *env, uint32_t nr, target_ulong val)
-{
-    ppc_store_ibatl_601(env, nr, val);
-}
-
-void helper_store_601_batu(CPUPPCState *env, uint32_t nr, target_ulong val)
-{
-    ppc_store_ibatu_601(env, nr, val);
-}
-
-/* Segment registers load and store */
-target_ulong helper_load_sr(CPUPPCState *env, target_ulong sr_num)
-{
-#if defined(TARGET_PPC64)
-    if (env->mmu_model & POWERPC_MMU_64) {
-        return ppc_load_sr(env, sr_num);
-    }
-#endif
-    return env->sr[sr_num];
-}
-
-void helper_store_sr(CPUPPCState *env, target_ulong sr_num, target_ulong val)
-{
-    ppc_store_sr(env, sr_num, val);
-}
-
 /* SLB management */
 #if defined(TARGET_PPC64)
 void helper_store_slb(CPUPPCState *env, target_ulong rb, target_ulong rs)
@@ -2579,17 +2540,6 @@ target_ulong helper_load_slb_vsid(CPUPPCState *env, target_ulong rb)
     }
     return rt;
 }
-
-void helper_slbia(CPUPPCState *env)
-{
-    ppc_slb_invalidate_all(env);
-}
-
-void helper_slbie(CPUPPCState *env, target_ulong addr)
-{
-    ppc_slb_invalidate_one(env, addr);
-}
-
 #endif /* defined(TARGET_PPC64) */
 
 /* TLB management */
commit 8cbbe3851c0ed3dad2231245e47bad5acf9e2a9a
Author: Blue Swirl <blauwirbel at gmail.com>
Date:   Wed May 30 04:23:33 2012 +0000

    ppc: Move MMU helpers from helper.c to mmu_helper.c
    
    Move more MMU helpers from helper.c to mmu_helper.c.
    
    Signed-off-by: Blue Swirl <blauwirbel at gmail.com>
    Signed-off-by: Alexander Graf <agraf at suse.de>
    Signed-off-by: Andreas Färber <afaerber at suse.de>
    [update to current helper.c state]
    Signed-off-by: Alexander Graf <agraf at suse.de>

diff --git a/target-ppc/helper.c b/target-ppc/helper.c
index 17e72a9..24d109d 100644
--- a/target-ppc/helper.c
+++ b/target-ppc/helper.c
@@ -23,2483 +23,8 @@
 #include "kvm_ppc.h"
 #include "cpus.h"
 
-//#define DEBUG_MMU
-//#define DEBUG_BATS
-//#define DEBUG_SLB
-//#define DEBUG_SOFTWARE_TLB
-//#define DUMP_PAGE_TABLES
-//#define FLUSH_ALL_TLBS
-
-#ifdef DEBUG_MMU
-#  define LOG_MMU(...) qemu_log(__VA_ARGS__)
-#  define LOG_MMU_STATE(env) log_cpu_state((env), 0)
-#else
-#  define LOG_MMU(...) do { } while (0)
-#  define LOG_MMU_STATE(...) do { } while (0)
-#endif
-
-
-#ifdef DEBUG_SOFTWARE_TLB
-#  define LOG_SWTLB(...) qemu_log(__VA_ARGS__)
-#else
-#  define LOG_SWTLB(...) do { } while (0)
-#endif
-
-#ifdef DEBUG_BATS
-#  define LOG_BATS(...) qemu_log(__VA_ARGS__)
-#else
-#  define LOG_BATS(...) do { } while (0)
-#endif
-
-#ifdef DEBUG_SLB
-#  define LOG_SLB(...) qemu_log(__VA_ARGS__)
-#else
-#  define LOG_SLB(...) do { } while (0)
-#endif
-
-/*****************************************************************************/
-/* PowerPC MMU emulation */
-
-#if defined(CONFIG_USER_ONLY)
-int cpu_ppc_handle_mmu_fault(CPUPPCState *env, target_ulong address, int rw,
-                             int mmu_idx)
-{
-    int exception, error_code;
-
-    if (rw == 2) {
-        exception = POWERPC_EXCP_ISI;
-        error_code = 0x40000000;
-    } else {
-        exception = POWERPC_EXCP_DSI;
-        error_code = 0x40000000;
-        if (rw) {
-            error_code |= 0x02000000;
-        }
-        env->spr[SPR_DAR] = address;
-        env->spr[SPR_DSISR] = error_code;
-    }
-    env->exception_index = exception;
-    env->error_code = error_code;
-
-    return 1;
-}
-
-#else
-/* Common routines used by software and hardware TLBs emulation */
-static inline int pte_is_valid(target_ulong pte0)
-{
-    return pte0 & 0x80000000 ? 1 : 0;
-}
-
-static inline void pte_invalidate(target_ulong *pte0)
-{
-    *pte0 &= ~0x80000000;
-}
-
-#if defined(TARGET_PPC64)
-static inline int pte64_is_valid(target_ulong pte0)
-{
-    return pte0 & 0x0000000000000001ULL ? 1 : 0;
-}
-
-static inline void pte64_invalidate(target_ulong *pte0)
-{
-    *pte0 &= ~0x0000000000000001ULL;
-}
-#endif
-
-#define PTE_PTEM_MASK 0x7FFFFFBF
-#define PTE_CHECK_MASK (TARGET_PAGE_MASK | 0x7B)
-#if defined(TARGET_PPC64)
-#define PTE64_PTEM_MASK 0xFFFFFFFFFFFFFF80ULL
-#define PTE64_CHECK_MASK (TARGET_PAGE_MASK | 0x7F)
-#endif
-
-static inline int pp_check(int key, int pp, int nx)
-{
-    int access;
-
-    /* Compute access rights */
-    /* When pp is 3/7, the result is undefined. Set it to noaccess */
-    access = 0;
-    if (key == 0) {
-        switch (pp) {
-        case 0x0:
-        case 0x1:
-        case 0x2:
-            access |= PAGE_WRITE;
-            /* No break here */
-        case 0x3:
-        case 0x6:
-            access |= PAGE_READ;
-            break;
-        }
-    } else {
-        switch (pp) {
-        case 0x0:
-        case 0x6:
-            access = 0;
-            break;
-        case 0x1:
-        case 0x3:
-            access = PAGE_READ;
-            break;
-        case 0x2:
-            access = PAGE_READ | PAGE_WRITE;
-            break;
-        }
-    }
-    if (nx == 0) {
-        access |= PAGE_EXEC;
-    }
-
-    return access;
-}
-
-static inline int check_prot(int prot, int rw, int access_type)
-{
-    int ret;
-
-    if (access_type == ACCESS_CODE) {
-        if (prot & PAGE_EXEC) {
-            ret = 0;
-        } else {
-            ret = -2;
-        }
-    } else if (rw) {
-        if (prot & PAGE_WRITE) {
-            ret = 0;
-        } else {
-            ret = -2;
-        }
-    } else {
-        if (prot & PAGE_READ) {
-            ret = 0;
-        } else {
-            ret = -2;
-        }
-    }
-
-    return ret;
-}
-
-static inline int pte_check(mmu_ctx_t *ctx, int is_64b, target_ulong pte0,
-                            target_ulong pte1, int h, int rw, int type)
-{
-    target_ulong ptem, mmask;
-    int access, ret, pteh, ptev, pp;
-
-    ret = -1;
-    /* Check validity and table match */
-#if defined(TARGET_PPC64)
-    if (is_64b) {
-        ptev = pte64_is_valid(pte0);
-        pteh = (pte0 >> 1) & 1;
-    } else
-#endif
-    {
-        ptev = pte_is_valid(pte0);
-        pteh = (pte0 >> 6) & 1;
-    }
-    if (ptev && h == pteh) {
-        /* Check vsid & api */
-#if defined(TARGET_PPC64)
-        if (is_64b) {
-            ptem = pte0 & PTE64_PTEM_MASK;
-            mmask = PTE64_CHECK_MASK;
-            pp = (pte1 & 0x00000003) | ((pte1 >> 61) & 0x00000004);
-            ctx->nx  = (pte1 >> 2) & 1; /* No execute bit */
-            ctx->nx |= (pte1 >> 3) & 1; /* Guarded bit    */
-        } else
-#endif
-        {
-            ptem = pte0 & PTE_PTEM_MASK;
-            mmask = PTE_CHECK_MASK;
-            pp = pte1 & 0x00000003;
-        }
-        if (ptem == ctx->ptem) {
-            if (ctx->raddr != (target_phys_addr_t)-1ULL) {
-                /* all matches should have equal RPN, WIMG & PP */
-                if ((ctx->raddr & mmask) != (pte1 & mmask)) {
-                    qemu_log("Bad RPN/WIMG/PP\n");
-                    return -3;
-                }
-            }
-            /* Compute access rights */
-            access = pp_check(ctx->key, pp, ctx->nx);
-            /* Keep the matching PTE informations */
-            ctx->raddr = pte1;
-            ctx->prot = access;
-            ret = check_prot(ctx->prot, rw, type);
-            if (ret == 0) {
-                /* Access granted */
-                LOG_MMU("PTE access granted !\n");
-            } else {
-                /* Access right violation */
-                LOG_MMU("PTE access rejected\n");
-            }
-        }
-    }
-
-    return ret;
-}
-
-static inline int pte32_check(mmu_ctx_t *ctx, target_ulong pte0,
-                              target_ulong pte1, int h, int rw, int type)
-{
-    return pte_check(ctx, 0, pte0, pte1, h, rw, type);
-}
-
-#if defined(TARGET_PPC64)
-static inline int pte64_check(mmu_ctx_t *ctx, target_ulong pte0,
-                              target_ulong pte1, int h, int rw, int type)
-{
-    return pte_check(ctx, 1, pte0, pte1, h, rw, type);
-}
-#endif
-
-static inline int pte_update_flags(mmu_ctx_t *ctx, target_ulong *pte1p,
-                                   int ret, int rw)
-{
-    int store = 0;
-
-    /* Update page flags */
-    if (!(*pte1p & 0x00000100)) {
-        /* Update accessed flag */
-        *pte1p |= 0x00000100;
-        store = 1;
-    }
-    if (!(*pte1p & 0x00000080)) {
-        if (rw == 1 && ret == 0) {
-            /* Update changed flag */
-            *pte1p |= 0x00000080;
-            store = 1;
-        } else {
-            /* Force page fault for first write access */
-            ctx->prot &= ~PAGE_WRITE;
-        }
-    }
-
-    return store;
-}
-
-/* Software driven TLB helpers */
-static inline int ppc6xx_tlb_getnum(CPUPPCState *env, target_ulong eaddr,
-                                    int way, int is_code)
-{
-    int nr;
-
-    /* Select TLB num in a way from address */
-    nr = (eaddr >> TARGET_PAGE_BITS) & (env->tlb_per_way - 1);
-    /* Select TLB way */
-    nr += env->tlb_per_way * way;
-    /* 6xx have separate TLBs for instructions and data */
-    if (is_code && env->id_tlbs == 1) {
-        nr += env->nb_tlb;
-    }
-
-    return nr;
-}
-
-static inline void ppc6xx_tlb_invalidate_all(CPUPPCState *env)
-{
-    ppc6xx_tlb_t *tlb;
-    int nr, max;
-
-    /* LOG_SWTLB("Invalidate all TLBs\n"); */
-    /* Invalidate all defined software TLB */
-    max = env->nb_tlb;
-    if (env->id_tlbs == 1) {
-        max *= 2;
-    }
-    for (nr = 0; nr < max; nr++) {
-        tlb = &env->tlb.tlb6[nr];
-        pte_invalidate(&tlb->pte0);
-    }
-    tlb_flush(env, 1);
-}
-
-static inline void ppc6xx_tlb_invalidate_virt2(CPUPPCState *env,
-                                               target_ulong eaddr,
-                                               int is_code, int match_epn)
-{
-#if !defined(FLUSH_ALL_TLBS)
-    ppc6xx_tlb_t *tlb;
-    int way, nr;
-
-    /* Invalidate ITLB + DTLB, all ways */
-    for (way = 0; way < env->nb_ways; way++) {
-        nr = ppc6xx_tlb_getnum(env, eaddr, way, is_code);
-        tlb = &env->tlb.tlb6[nr];
-        if (pte_is_valid(tlb->pte0) && (match_epn == 0 || eaddr == tlb->EPN)) {
-            LOG_SWTLB("TLB invalidate %d/%d " TARGET_FMT_lx "\n", nr,
-                      env->nb_tlb, eaddr);
-            pte_invalidate(&tlb->pte0);
-            tlb_flush_page(env, tlb->EPN);
-        }
-    }
-#else
-    /* XXX: PowerPC specification say this is valid as well */
-    ppc6xx_tlb_invalidate_all(env);
-#endif
-}
-
-static inline void ppc6xx_tlb_invalidate_virt(CPUPPCState *env,
-                                              target_ulong eaddr, int is_code)
-{
-    ppc6xx_tlb_invalidate_virt2(env, eaddr, is_code, 0);
-}
-
-void ppc6xx_tlb_store(CPUPPCState *env, target_ulong EPN, int way, int is_code,
-                      target_ulong pte0, target_ulong pte1)
-{
-    ppc6xx_tlb_t *tlb;
-    int nr;
-
-    nr = ppc6xx_tlb_getnum(env, EPN, way, is_code);
-    tlb = &env->tlb.tlb6[nr];
-    LOG_SWTLB("Set TLB %d/%d EPN " TARGET_FMT_lx " PTE0 " TARGET_FMT_lx
-              " PTE1 " TARGET_FMT_lx "\n", nr, env->nb_tlb, EPN, pte0, pte1);
-    /* Invalidate any pending reference in QEMU for this virtual address */
-    ppc6xx_tlb_invalidate_virt2(env, EPN, is_code, 1);
-    tlb->pte0 = pte0;
-    tlb->pte1 = pte1;
-    tlb->EPN = EPN;
-    /* Store last way for LRU mechanism */
-    env->last_way = way;
-}
-
-static inline int ppc6xx_tlb_check(CPUPPCState *env, mmu_ctx_t *ctx,
-                                   target_ulong eaddr, int rw, int access_type)
-{
-    ppc6xx_tlb_t *tlb;
-    int nr, best, way;
-    int ret;
-
-    best = -1;
-    ret = -1; /* No TLB found */
-    for (way = 0; way < env->nb_ways; way++) {
-        nr = ppc6xx_tlb_getnum(env, eaddr, way,
-                               access_type == ACCESS_CODE ? 1 : 0);
-        tlb = &env->tlb.tlb6[nr];
-        /* This test "emulates" the PTE index match for hardware TLBs */
-        if ((eaddr & TARGET_PAGE_MASK) != tlb->EPN) {
-            LOG_SWTLB("TLB %d/%d %s [" TARGET_FMT_lx " " TARGET_FMT_lx
-                      "] <> " TARGET_FMT_lx "\n", nr, env->nb_tlb,
-                      pte_is_valid(tlb->pte0) ? "valid" : "inval",
-                      tlb->EPN, tlb->EPN + TARGET_PAGE_SIZE, eaddr);
-            continue;
-        }
-        LOG_SWTLB("TLB %d/%d %s " TARGET_FMT_lx " <> " TARGET_FMT_lx " "
-                  TARGET_FMT_lx " %c %c\n", nr, env->nb_tlb,
-                  pte_is_valid(tlb->pte0) ? "valid" : "inval",
-                  tlb->EPN, eaddr, tlb->pte1,
-                  rw ? 'S' : 'L', access_type == ACCESS_CODE ? 'I' : 'D');
-        switch (pte32_check(ctx, tlb->pte0, tlb->pte1, 0, rw, access_type)) {
-        case -3:
-            /* TLB inconsistency */
-            return -1;
-        case -2:
-            /* Access violation */
-            ret = -2;
-            best = nr;
-            break;
-        case -1:
-        default:
-            /* No match */
-            break;
-        case 0:
-            /* access granted */
-            /* XXX: we should go on looping to check all TLBs consistency
-             *      but we can speed-up the whole thing as the
-             *      result would be undefined if TLBs are not consistent.
-             */
-            ret = 0;
-            best = nr;
-            goto done;
-        }
-    }
-    if (best != -1) {
-    done:
-        LOG_SWTLB("found TLB at addr " TARGET_FMT_plx " prot=%01x ret=%d\n",
-                  ctx->raddr & TARGET_PAGE_MASK, ctx->prot, ret);
-        /* Update page flags */
-        pte_update_flags(ctx, &env->tlb.tlb6[best].pte1, ret, rw);
-    }
-
-    return ret;
-}
-
-/* Perform BAT hit & translation */
-static inline void bat_size_prot(CPUPPCState *env, target_ulong *blp,
-                                 int *validp, int *protp, target_ulong *BATu,
-                                 target_ulong *BATl)
-{
-    target_ulong bl;
-    int pp, valid, prot;
-
-    bl = (*BATu & 0x00001FFC) << 15;
-    valid = 0;
-    prot = 0;
-    if (((msr_pr == 0) && (*BATu & 0x00000002)) ||
-        ((msr_pr != 0) && (*BATu & 0x00000001))) {
-        valid = 1;
-        pp = *BATl & 0x00000003;
-        if (pp != 0) {
-            prot = PAGE_READ | PAGE_EXEC;
-            if (pp == 0x2) {
-                prot |= PAGE_WRITE;
-            }
-        }
-    }
-    *blp = bl;
-    *validp = valid;
-    *protp = prot;
-}
-
-static inline void bat_601_size_prot(CPUPPCState *env, target_ulong *blp,
-                                     int *validp, int *protp,
-                                     target_ulong *BATu, target_ulong *BATl)
-{
-    target_ulong bl;
-    int key, pp, valid, prot;
-
-    bl = (*BATl & 0x0000003F) << 17;
-    LOG_BATS("b %02x ==> bl " TARGET_FMT_lx " msk " TARGET_FMT_lx "\n",
-             (uint8_t)(*BATl & 0x0000003F), bl, ~bl);
-    prot = 0;
-    valid = (*BATl >> 6) & 1;
-    if (valid) {
-        pp = *BATu & 0x00000003;
-        if (msr_pr == 0) {
-            key = (*BATu >> 3) & 1;
-        } else {
-            key = (*BATu >> 2) & 1;
-        }
-        prot = pp_check(key, pp, 0);
-    }
-    *blp = bl;
-    *validp = valid;
-    *protp = prot;
-}
-
-static inline int get_bat(CPUPPCState *env, mmu_ctx_t *ctx,
-                          target_ulong virtual, int rw, int type)
-{
-    target_ulong *BATlt, *BATut, *BATu, *BATl;
-    target_ulong BEPIl, BEPIu, bl;
-    int i, valid, prot;
-    int ret = -1;
-
-    LOG_BATS("%s: %cBAT v " TARGET_FMT_lx "\n", __func__,
-             type == ACCESS_CODE ? 'I' : 'D', virtual);
-    switch (type) {
-    case ACCESS_CODE:
-        BATlt = env->IBAT[1];
-        BATut = env->IBAT[0];
-        break;
-    default:
-        BATlt = env->DBAT[1];
-        BATut = env->DBAT[0];
-        break;
-    }
-    for (i = 0; i < env->nb_BATs; i++) {
-        BATu = &BATut[i];
-        BATl = &BATlt[i];
-        BEPIu = *BATu & 0xF0000000;
-        BEPIl = *BATu & 0x0FFE0000;
-        if (unlikely(env->mmu_model == POWERPC_MMU_601)) {
-            bat_601_size_prot(env, &bl, &valid, &prot, BATu, BATl);
-        } else {
-            bat_size_prot(env, &bl, &valid, &prot, BATu, BATl);
-        }
-        LOG_BATS("%s: %cBAT%d v " TARGET_FMT_lx " BATu " TARGET_FMT_lx
-                 " BATl " TARGET_FMT_lx "\n", __func__,
-                 type == ACCESS_CODE ? 'I' : 'D', i, virtual, *BATu, *BATl);
-        if ((virtual & 0xF0000000) == BEPIu &&
-            ((virtual & 0x0FFE0000) & ~bl) == BEPIl) {
-            /* BAT matches */
-            if (valid != 0) {
-                /* Get physical address */
-                ctx->raddr = (*BATl & 0xF0000000) |
-                    ((virtual & 0x0FFE0000 & bl) | (*BATl & 0x0FFE0000)) |
-                    (virtual & 0x0001F000);
-                /* Compute access rights */
-                ctx->prot = prot;
-                ret = check_prot(ctx->prot, rw, type);
-                if (ret == 0) {
-                    LOG_BATS("BAT %d match: r " TARGET_FMT_plx " prot=%c%c\n",
-                             i, ctx->raddr, ctx->prot & PAGE_READ ? 'R' : '-',
-                             ctx->prot & PAGE_WRITE ? 'W' : '-');
-                }
-                break;
-            }
-        }
-    }
-    if (ret < 0) {
-#if defined(DEBUG_BATS)
-        if (qemu_log_enabled()) {
-            LOG_BATS("no BAT match for " TARGET_FMT_lx ":\n", virtual);
-            for (i = 0; i < 4; i++) {
-                BATu = &BATut[i];
-                BATl = &BATlt[i];
-                BEPIu = *BATu & 0xF0000000;
-                BEPIl = *BATu & 0x0FFE0000;
-                bl = (*BATu & 0x00001FFC) << 15;
-                LOG_BATS("%s: %cBAT%d v " TARGET_FMT_lx " BATu " TARGET_FMT_lx
-                         " BATl " TARGET_FMT_lx "\n\t" TARGET_FMT_lx " "
-                         TARGET_FMT_lx " " TARGET_FMT_lx "\n",
-                         __func__, type == ACCESS_CODE ? 'I' : 'D', i, virtual,
-                         *BATu, *BATl, BEPIu, BEPIl, bl);
-            }
-        }
-#endif
-    }
-    /* No hit */
-    return ret;
-}
-
-static inline target_phys_addr_t get_pteg_offset(CPUPPCState *env,
-                                                 target_phys_addr_t hash,
-                                                 int pte_size)
-{
-    return (hash * pte_size * 8) & env->htab_mask;
-}
-
-/* PTE table lookup */
-static inline int find_pte2(CPUPPCState *env, mmu_ctx_t *ctx, int is_64b, int h,
-                            int rw, int type, int target_page_bits)
-{
-    target_phys_addr_t pteg_off;
-    target_ulong pte0, pte1;
-    int i, good = -1;
-    int ret, r;
-
-    ret = -1; /* No entry found */
-    pteg_off = get_pteg_offset(env, ctx->hash[h],
-                               is_64b ? HASH_PTE_SIZE_64 : HASH_PTE_SIZE_32);
-    for (i = 0; i < 8; i++) {
-#if defined(TARGET_PPC64)
-        if (is_64b) {
-            if (env->external_htab) {
-                pte0 = ldq_p(env->external_htab + pteg_off + (i * 16));
-                pte1 = ldq_p(env->external_htab + pteg_off + (i * 16) + 8);
-            } else {
-                pte0 = ldq_phys(env->htab_base + pteg_off + (i * 16));
-                pte1 = ldq_phys(env->htab_base + pteg_off + (i * 16) + 8);
-            }
-
-            r = pte64_check(ctx, pte0, pte1, h, rw, type);
-            LOG_MMU("Load pte from " TARGET_FMT_lx " => " TARGET_FMT_lx " "
-                    TARGET_FMT_lx " %d %d %d " TARGET_FMT_lx "\n",
-                    pteg_off + (i * 16), pte0, pte1, (int)(pte0 & 1), h,
-                    (int)((pte0 >> 1) & 1), ctx->ptem);
-        } else
-#endif
-        {
-            if (env->external_htab) {
-                pte0 = ldl_p(env->external_htab + pteg_off + (i * 8));
-                pte1 = ldl_p(env->external_htab + pteg_off + (i * 8) + 4);
-            } else {
-                pte0 = ldl_phys(env->htab_base + pteg_off + (i * 8));
-                pte1 = ldl_phys(env->htab_base + pteg_off + (i * 8) + 4);
-            }
-            r = pte32_check(ctx, pte0, pte1, h, rw, type);
-            LOG_MMU("Load pte from " TARGET_FMT_lx " => " TARGET_FMT_lx " "
-                    TARGET_FMT_lx " %d %d %d " TARGET_FMT_lx "\n",
-                    pteg_off + (i * 8), pte0, pte1, (int)(pte0 >> 31), h,
-                    (int)((pte0 >> 6) & 1), ctx->ptem);
-        }
-        switch (r) {
-        case -3:
-            /* PTE inconsistency */
-            return -1;
-        case -2:
-            /* Access violation */
-            ret = -2;
-            good = i;
-            break;
-        case -1:
-        default:
-            /* No PTE match */
-            break;
-        case 0:
-            /* access granted */
-            /* XXX: we should go on looping to check all PTEs consistency
-             *      but if we can speed-up the whole thing as the
-             *      result would be undefined if PTEs are not consistent.
-             */
-            ret = 0;
-            good = i;
-            goto done;
-        }
-    }
-    if (good != -1) {
-    done:
-        LOG_MMU("found PTE at addr " TARGET_FMT_lx " prot=%01x ret=%d\n",
-                ctx->raddr, ctx->prot, ret);
-        /* Update page flags */
-        pte1 = ctx->raddr;
-        if (pte_update_flags(ctx, &pte1, ret, rw) == 1) {
-#if defined(TARGET_PPC64)
-            if (is_64b) {
-                if (env->external_htab) {
-                    stq_p(env->external_htab + pteg_off + (good * 16) + 8,
-                          pte1);
-                } else {
-                    stq_phys_notdirty(env->htab_base + pteg_off +
-                                      (good * 16) + 8, pte1);
-                }
-            } else
-#endif
-            {
-                if (env->external_htab) {
-                    stl_p(env->external_htab + pteg_off + (good * 8) + 4,
-                          pte1);
-                } else {
-                    stl_phys_notdirty(env->htab_base + pteg_off +
-                                      (good * 8) + 4, pte1);
-                }
-            }
-        }
-    }
-
-    /* We have a TLB that saves 4K pages, so let's
-     * split a huge page to 4k chunks */
-    if (target_page_bits != TARGET_PAGE_BITS) {
-        ctx->raddr |= (ctx->eaddr & ((1 << target_page_bits) - 1))
-                      & TARGET_PAGE_MASK;
-    }
-    return ret;
-}
-
-static inline int find_pte(CPUPPCState *env, mmu_ctx_t *ctx, int h, int rw,
-                           int type, int target_page_bits)
-{
-#if defined(TARGET_PPC64)
-    if (env->mmu_model & POWERPC_MMU_64) {
-        return find_pte2(env, ctx, 1, h, rw, type, target_page_bits);
-    }
-#endif
-
-    return find_pte2(env, ctx, 0, h, rw, type, target_page_bits);
-}
-
-#if defined(TARGET_PPC64)
-static inline ppc_slb_t *slb_lookup(CPUPPCState *env, target_ulong eaddr)
-{
-    uint64_t esid_256M, esid_1T;
-    int n;
-
-    LOG_SLB("%s: eaddr " TARGET_FMT_lx "\n", __func__, eaddr);
-
-    esid_256M = (eaddr & SEGMENT_MASK_256M) | SLB_ESID_V;
-    esid_1T = (eaddr & SEGMENT_MASK_1T) | SLB_ESID_V;
-
-    for (n = 0; n < env->slb_nr; n++) {
-        ppc_slb_t *slb = &env->slb[n];
-
-        LOG_SLB("%s: slot %d %016" PRIx64 " %016"
-                    PRIx64 "\n", __func__, n, slb->esid, slb->vsid);
-        /* We check for 1T matches on all MMUs here - if the MMU
-         * doesn't have 1T segment support, we will have prevented 1T
-         * entries from being inserted in the slbmte code. */
-        if (((slb->esid == esid_256M) &&
-             ((slb->vsid & SLB_VSID_B) == SLB_VSID_B_256M))
-            || ((slb->esid == esid_1T) &&
-                ((slb->vsid & SLB_VSID_B) == SLB_VSID_B_1T))) {
-            return slb;
-        }
-    }
-
-    return NULL;
-}
-
-void ppc_slb_invalidate_all(CPUPPCState *env)
-{
-    int n, do_invalidate;
-
-    do_invalidate = 0;
-    /* XXX: Warning: slbia never invalidates the first segment */
-    for (n = 1; n < env->slb_nr; n++) {
-        ppc_slb_t *slb = &env->slb[n];
-
-        if (slb->esid & SLB_ESID_V) {
-            slb->esid &= ~SLB_ESID_V;
-            /* XXX: given the fact that segment size is 256 MB or 1TB,
-             *      and we still don't have a tlb_flush_mask(env, n, mask)
-             *      in QEMU, we just invalidate all TLBs
-             */
-            do_invalidate = 1;
-        }
-    }
-    if (do_invalidate) {
-        tlb_flush(env, 1);
-    }
-}
-
-void ppc_slb_invalidate_one(CPUPPCState *env, uint64_t T0)
-{
-    ppc_slb_t *slb;
-
-    slb = slb_lookup(env, T0);
-    if (!slb) {
-        return;
-    }
-
-    if (slb->esid & SLB_ESID_V) {
-        slb->esid &= ~SLB_ESID_V;
-
-        /* XXX: given the fact that segment size is 256 MB or 1TB,
-         *      and we still don't have a tlb_flush_mask(env, n, mask)
-         *      in QEMU, we just invalidate all TLBs
-         */
-        tlb_flush(env, 1);
-    }
-}
-
-int ppc_store_slb(CPUPPCState *env, target_ulong rb, target_ulong rs)
-{
-    int slot = rb & 0xfff;
-    ppc_slb_t *slb = &env->slb[slot];
-
-    if (rb & (0x1000 - env->slb_nr)) {
-        return -1; /* Reserved bits set or slot too high */
-    }
-    if (rs & (SLB_VSID_B & ~SLB_VSID_B_1T)) {
-        return -1; /* Bad segment size */
-    }
-    if ((rs & SLB_VSID_B) && !(env->mmu_model & POWERPC_MMU_1TSEG)) {
-        return -1; /* 1T segment on MMU that doesn't support it */
-    }
-
-    /* Mask out the slot number as we store the entry */
-    slb->esid = rb & (SLB_ESID_ESID | SLB_ESID_V);
-    slb->vsid = rs;
-
-    LOG_SLB("%s: %d " TARGET_FMT_lx " - " TARGET_FMT_lx " => %016" PRIx64
-            " %016" PRIx64 "\n", __func__, slot, rb, rs,
-            slb->esid, slb->vsid);
-
-    return 0;
-}
-
-int ppc_load_slb_esid(CPUPPCState *env, target_ulong rb, target_ulong *rt)
-{
-    int slot = rb & 0xfff;
-    ppc_slb_t *slb = &env->slb[slot];
-
-    if (slot >= env->slb_nr) {
-        return -1;
-    }
-
-    *rt = slb->esid;
-    return 0;
-}
-
-int ppc_load_slb_vsid(CPUPPCState *env, target_ulong rb, target_ulong *rt)
-{
-    int slot = rb & 0xfff;
-    ppc_slb_t *slb = &env->slb[slot];
-
-    if (slot >= env->slb_nr) {
-        return -1;
-    }
-
-    *rt = slb->vsid;
-    return 0;
-}
-#endif /* defined(TARGET_PPC64) */
-
-/* Perform segment based translation */
-static inline int get_segment(CPUPPCState *env, mmu_ctx_t *ctx,
-                              target_ulong eaddr, int rw, int type)
-{
-    target_phys_addr_t hash;
-    target_ulong vsid;
-    int ds, pr, target_page_bits;
-    int ret, ret2;
-
-    pr = msr_pr;
-    ctx->eaddr = eaddr;
-#if defined(TARGET_PPC64)
-    if (env->mmu_model & POWERPC_MMU_64) {
-        ppc_slb_t *slb;
-        target_ulong pageaddr;
-        int segment_bits;
-
-        LOG_MMU("Check SLBs\n");
-        slb = slb_lookup(env, eaddr);
-        if (!slb) {
-            return -5;
-        }
-
-        if (slb->vsid & SLB_VSID_B) {
-            vsid = (slb->vsid & SLB_VSID_VSID) >> SLB_VSID_SHIFT_1T;
-            segment_bits = 40;
-        } else {
-            vsid = (slb->vsid & SLB_VSID_VSID) >> SLB_VSID_SHIFT;
-            segment_bits = 28;
-        }
-
-        target_page_bits = (slb->vsid & SLB_VSID_L)
-            ? TARGET_PAGE_BITS_16M : TARGET_PAGE_BITS;
-        ctx->key = !!(pr ? (slb->vsid & SLB_VSID_KP)
-                      : (slb->vsid & SLB_VSID_KS));
-        ds = 0;
-        ctx->nx = !!(slb->vsid & SLB_VSID_N);
-
-        pageaddr = eaddr & ((1ULL << segment_bits)
-                            - (1ULL << target_page_bits));
-        if (slb->vsid & SLB_VSID_B) {
-            hash = vsid ^ (vsid << 25) ^ (pageaddr >> target_page_bits);
-        } else {
-            hash = vsid ^ (pageaddr >> target_page_bits);
-        }
-        /* Only 5 bits of the page index are used in the AVPN */
-        ctx->ptem = (slb->vsid & SLB_VSID_PTEM) |
-            ((pageaddr >> 16) & ((1ULL << segment_bits) - 0x80));
-    } else
-#endif /* defined(TARGET_PPC64) */
-    {
-        target_ulong sr, pgidx;
-
-        sr = env->sr[eaddr >> 28];
-        ctx->key = (((sr & 0x20000000) && (pr != 0)) ||
-                    ((sr & 0x40000000) && (pr == 0))) ? 1 : 0;
-        ds = sr & 0x80000000 ? 1 : 0;
-        ctx->nx = sr & 0x10000000 ? 1 : 0;
-        vsid = sr & 0x00FFFFFF;
-        target_page_bits = TARGET_PAGE_BITS;
-        LOG_MMU("Check segment v=" TARGET_FMT_lx " %d " TARGET_FMT_lx " nip="
-                TARGET_FMT_lx " lr=" TARGET_FMT_lx
-                " ir=%d dr=%d pr=%d %d t=%d\n",
-                eaddr, (int)(eaddr >> 28), sr, env->nip, env->lr, (int)msr_ir,
-                (int)msr_dr, pr != 0 ? 1 : 0, rw, type);
-        pgidx = (eaddr & ~SEGMENT_MASK_256M) >> target_page_bits;
-        hash = vsid ^ pgidx;
-        ctx->ptem = (vsid << 7) | (pgidx >> 10);
-    }
-    LOG_MMU("pte segment: key=%d ds %d nx %d vsid " TARGET_FMT_lx "\n",
-            ctx->key, ds, ctx->nx, vsid);
-    ret = -1;
-    if (!ds) {
-        /* Check if instruction fetch is allowed, if needed */
-        if (type != ACCESS_CODE || ctx->nx == 0) {
-            /* Page address translation */
-            LOG_MMU("htab_base " TARGET_FMT_plx " htab_mask " TARGET_FMT_plx
-                    " hash " TARGET_FMT_plx "\n",
-                    env->htab_base, env->htab_mask, hash);
-            ctx->hash[0] = hash;
-            ctx->hash[1] = ~hash;
-
-            /* Initialize real address with an invalid value */
-            ctx->raddr = (target_phys_addr_t)-1ULL;
-            if (unlikely(env->mmu_model == POWERPC_MMU_SOFT_6xx ||
-                         env->mmu_model == POWERPC_MMU_SOFT_74xx)) {
-                /* Software TLB search */
-                ret = ppc6xx_tlb_check(env, ctx, eaddr, rw, type);
-            } else {
-                LOG_MMU("0 htab=" TARGET_FMT_plx "/" TARGET_FMT_plx
-                        " vsid=" TARGET_FMT_lx " ptem=" TARGET_FMT_lx
-                        " hash=" TARGET_FMT_plx "\n",
-                        env->htab_base, env->htab_mask, vsid, ctx->ptem,
-                        ctx->hash[0]);
-                /* Primary table lookup */
-                ret = find_pte(env, ctx, 0, rw, type, target_page_bits);
-                if (ret < 0) {
-                    /* Secondary table lookup */
-                    if (eaddr != 0xEFFFFFFF) {
-                        LOG_MMU("1 htab=" TARGET_FMT_plx "/" TARGET_FMT_plx
-                                " vsid=" TARGET_FMT_lx " api=" TARGET_FMT_lx
-                                " hash=" TARGET_FMT_plx "\n", env->htab_base,
-                                env->htab_mask, vsid, ctx->ptem, ctx->hash[1]);
-                    }
-                    ret2 = find_pte(env, ctx, 1, rw, type,
-                                    target_page_bits);
-                    if (ret2 != -1) {
-                        ret = ret2;
-                    }
-                }
-            }
-#if defined(DUMP_PAGE_TABLES)
-            if (qemu_log_enabled()) {
-                target_phys_addr_t curaddr;
-                uint32_t a0, a1, a2, a3;
-
-                qemu_log("Page table: " TARGET_FMT_plx " len " TARGET_FMT_plx
-                         "\n", sdr, mask + 0x80);
-                for (curaddr = sdr; curaddr < (sdr + mask + 0x80);
-                     curaddr += 16) {
-                    a0 = ldl_phys(curaddr);
-                    a1 = ldl_phys(curaddr + 4);
-                    a2 = ldl_phys(curaddr + 8);
-                    a3 = ldl_phys(curaddr + 12);
-                    if (a0 != 0 || a1 != 0 || a2 != 0 || a3 != 0) {
-                        qemu_log(TARGET_FMT_plx ": %08x %08x %08x %08x\n",
-                                 curaddr, a0, a1, a2, a3);
-                    }
-                }
-            }
-#endif
-        } else {
-            LOG_MMU("No access allowed\n");
-            ret = -3;
-        }
-    } else {
-        target_ulong sr;
-
-        LOG_MMU("direct store...\n");
-        /* Direct-store segment : absolutely *BUGGY* for now */
-
-        /* Direct-store implies a 32-bit MMU.
-         * Check the Segment Register's bus unit ID (BUID).
-         */
-        sr = env->sr[eaddr >> 28];
-        if ((sr & 0x1FF00000) >> 20 == 0x07f) {
-            /* Memory-forced I/O controller interface access */
-            /* If T=1 and BUID=x'07F', the 601 performs a memory access
-             * to SR[28-31] LA[4-31], bypassing all protection mechanisms.
-             */
-            ctx->raddr = ((sr & 0xF) << 28) | (eaddr & 0x0FFFFFFF);
-            ctx->prot = PAGE_READ | PAGE_WRITE | PAGE_EXEC;
-            return 0;
-        }
-
-        switch (type) {
-        case ACCESS_INT:
-            /* Integer load/store : only access allowed */
-            break;
-        case ACCESS_CODE:
-            /* No code fetch is allowed in direct-store areas */
-            return -4;
-        case ACCESS_FLOAT:
-            /* Floating point load/store */
-            return -4;
-        case ACCESS_RES:
-            /* lwarx, ldarx or srwcx. */
-            return -4;
-        case ACCESS_CACHE:
-            /* dcba, dcbt, dcbtst, dcbf, dcbi, dcbst, dcbz, or icbi */
-            /* Should make the instruction do no-op.
-             * As it already do no-op, it's quite easy :-)
-             */
-            ctx->raddr = eaddr;
-            return 0;
-        case ACCESS_EXT:
-            /* eciwx or ecowx */
-            return -4;
-        default:
-            qemu_log("ERROR: instruction should not need "
-                        "address translation\n");
-            return -4;
-        }
-        if ((rw == 1 || ctx->key != 1) && (rw == 0 || ctx->key != 0)) {
-            ctx->raddr = eaddr;
-            ret = 2;
-        } else {
-            ret = -2;
-        }
-    }
-
-    return ret;
-}
-
-/* Generic TLB check function for embedded PowerPC implementations */
-int ppcemb_tlb_check(CPUPPCState *env, ppcemb_tlb_t *tlb,
-                     target_phys_addr_t *raddrp,
-                     target_ulong address, uint32_t pid, int ext,
-                     int i)
-{
-    target_ulong mask;
-
-    /* Check valid flag */
-    if (!(tlb->prot & PAGE_VALID)) {
-        return -1;
-    }
-    mask = ~(tlb->size - 1);
-    LOG_SWTLB("%s: TLB %d address " TARGET_FMT_lx " PID %u <=> " TARGET_FMT_lx
-              " " TARGET_FMT_lx " %u %x\n", __func__, i, address, pid, tlb->EPN,
-              mask, (uint32_t)tlb->PID, tlb->prot);
-    /* Check PID */
-    if (tlb->PID != 0 && tlb->PID != pid) {
-        return -1;
-    }
-    /* Check effective address */
-    if ((address & mask) != tlb->EPN) {
-        return -1;
-    }
-    *raddrp = (tlb->RPN & mask) | (address & ~mask);
-#if (TARGET_PHYS_ADDR_BITS >= 36)
-    if (ext) {
-        /* Extend the physical address to 36 bits */
-        *raddrp |= (target_phys_addr_t)(tlb->RPN & 0xF) << 32;
-    }
-#endif
-
-    return 0;
-}
-
-/* Generic TLB search function for PowerPC embedded implementations */
-int ppcemb_tlb_search(CPUPPCState *env, target_ulong address, uint32_t pid)
-{
-    ppcemb_tlb_t *tlb;
-    target_phys_addr_t raddr;
-    int i, ret;
-
-    /* Default return value is no match */
-    ret = -1;
-    for (i = 0; i < env->nb_tlb; i++) {
-        tlb = &env->tlb.tlbe[i];
-        if (ppcemb_tlb_check(env, tlb, &raddr, address, pid, 0, i) == 0) {
-            ret = i;
-            break;
-        }
-    }
-
-    return ret;
-}
-
-/* Helpers specific to PowerPC 40x implementations */
-static inline void ppc4xx_tlb_invalidate_all(CPUPPCState *env)
-{
-    ppcemb_tlb_t *tlb;
-    int i;
-
-    for (i = 0; i < env->nb_tlb; i++) {
-        tlb = &env->tlb.tlbe[i];
-        tlb->prot &= ~PAGE_VALID;
-    }
-    tlb_flush(env, 1);
-}
-
-static inline void ppc4xx_tlb_invalidate_virt(CPUPPCState *env,
-                                              target_ulong eaddr, uint32_t pid)
-{
-#if !defined(FLUSH_ALL_TLBS)
-    ppcemb_tlb_t *tlb;
-    target_phys_addr_t raddr;
-    target_ulong page, end;
-    int i;
-
-    for (i = 0; i < env->nb_tlb; i++) {
-        tlb = &env->tlb.tlbe[i];
-        if (ppcemb_tlb_check(env, tlb, &raddr, eaddr, pid, 0, i) == 0) {
-            end = tlb->EPN + tlb->size;
-            for (page = tlb->EPN; page < end; page += TARGET_PAGE_SIZE) {
-                tlb_flush_page(env, page);
-            }
-            tlb->prot &= ~PAGE_VALID;
-            break;
-        }
-    }
-#else
-    ppc4xx_tlb_invalidate_all(env);
-#endif
-}
-
-static int mmu40x_get_physical_address(CPUPPCState *env, mmu_ctx_t *ctx,
-                                       target_ulong address, int rw,
-                                       int access_type)
-{
-    ppcemb_tlb_t *tlb;
-    target_phys_addr_t raddr;
-    int i, ret, zsel, zpr, pr;
-
-    ret = -1;
-    raddr = (target_phys_addr_t)-1ULL;
-    pr = msr_pr;
-    for (i = 0; i < env->nb_tlb; i++) {
-        tlb = &env->tlb.tlbe[i];
-        if (ppcemb_tlb_check(env, tlb, &raddr, address,
-                             env->spr[SPR_40x_PID], 0, i) < 0) {
-            continue;
-        }
-        zsel = (tlb->attr >> 4) & 0xF;
-        zpr = (env->spr[SPR_40x_ZPR] >> (30 - (2 * zsel))) & 0x3;
-        LOG_SWTLB("%s: TLB %d zsel %d zpr %d rw %d attr %08x\n",
-                    __func__, i, zsel, zpr, rw, tlb->attr);
-        /* Check execute enable bit */
-        switch (zpr) {
-        case 0x2:
-            if (pr != 0) {
-                goto check_perms;
-            }
-            /* No break here */
-        case 0x3:
-            /* All accesses granted */
-            ctx->prot = PAGE_READ | PAGE_WRITE | PAGE_EXEC;
-            ret = 0;
-            break;
-        case 0x0:
-            if (pr != 0) {
-                /* Raise Zone protection fault.  */
-                env->spr[SPR_40x_ESR] = 1 << 22;
-                ctx->prot = 0;
-                ret = -2;
-                break;
-            }
-            /* No break here */
-        case 0x1:
-        check_perms:
-            /* Check from TLB entry */
-            ctx->prot = tlb->prot;
-            ret = check_prot(ctx->prot, rw, access_type);
-            if (ret == -2) {
-                env->spr[SPR_40x_ESR] = 0;
-            }
-            break;
-        }
-        if (ret >= 0) {
-            ctx->raddr = raddr;
-            LOG_SWTLB("%s: access granted " TARGET_FMT_lx " => " TARGET_FMT_plx
-                      " %d %d\n", __func__, address, ctx->raddr, ctx->prot,
-                      ret);
-            return 0;
-        }
-    }
-    LOG_SWTLB("%s: access refused " TARGET_FMT_lx " => " TARGET_FMT_plx
-              " %d %d\n", __func__, address, raddr, ctx->prot, ret);
-
-    return ret;
-}
-
-void store_40x_sler(CPUPPCState *env, uint32_t val)
-{
-    /* XXX: TO BE FIXED */
-    if (val != 0x00000000) {
-        cpu_abort(env, "Little-endian regions are not supported by now\n");
-    }
-    env->spr[SPR_405_SLER] = val;
-}
-
-static inline int mmubooke_check_tlb(CPUPPCState *env, ppcemb_tlb_t *tlb,
-                                     target_phys_addr_t *raddr, int *prot,
-                                     target_ulong address, int rw,
-                                     int access_type, int i)
-{
-    int ret, prot2;
-
-    if (ppcemb_tlb_check(env, tlb, raddr, address,
-                         env->spr[SPR_BOOKE_PID],
-                         !env->nb_pids, i) >= 0) {
-        goto found_tlb;
-    }
-
-    if (env->spr[SPR_BOOKE_PID1] &&
-        ppcemb_tlb_check(env, tlb, raddr, address,
-                         env->spr[SPR_BOOKE_PID1], 0, i) >= 0) {
-        goto found_tlb;
-    }
-
-    if (env->spr[SPR_BOOKE_PID2] &&
-        ppcemb_tlb_check(env, tlb, raddr, address,
-                         env->spr[SPR_BOOKE_PID2], 0, i) >= 0) {
-        goto found_tlb;
-    }
-
-    LOG_SWTLB("%s: TLB entry not found\n", __func__);
-    return -1;
-
-found_tlb:
-
-    if (msr_pr != 0) {
-        prot2 = tlb->prot & 0xF;
-    } else {
-        prot2 = (tlb->prot >> 4) & 0xF;
-    }
-
-    /* Check the address space */
-    if (access_type == ACCESS_CODE) {
-        if (msr_ir != (tlb->attr & 1)) {
-            LOG_SWTLB("%s: AS doesn't match\n", __func__);
-            return -1;
-        }
-
-        *prot = prot2;
-        if (prot2 & PAGE_EXEC) {
-            LOG_SWTLB("%s: good TLB!\n", __func__);
-            return 0;
-        }
-
-        LOG_SWTLB("%s: no PAGE_EXEC: %x\n", __func__, prot2);
-        ret = -3;
-    } else {
-        if (msr_dr != (tlb->attr & 1)) {
-            LOG_SWTLB("%s: AS doesn't match\n", __func__);
-            return -1;
-        }
-
-        *prot = prot2;
-        if ((!rw && prot2 & PAGE_READ) || (rw && (prot2 & PAGE_WRITE))) {
-            LOG_SWTLB("%s: found TLB!\n", __func__);
-            return 0;
-        }
-
-        LOG_SWTLB("%s: PAGE_READ/WRITE doesn't match: %x\n", __func__, prot2);
-        ret = -2;
-    }
-
-    return ret;
-}
-
-static int mmubooke_get_physical_address(CPUPPCState *env, mmu_ctx_t *ctx,
-                                         target_ulong address, int rw,
-                                         int access_type)
-{
-    ppcemb_tlb_t *tlb;
-    target_phys_addr_t raddr;
-    int i, ret;
-
-    ret = -1;
-    raddr = (target_phys_addr_t)-1ULL;
-    for (i = 0; i < env->nb_tlb; i++) {
-        tlb = &env->tlb.tlbe[i];
-        ret = mmubooke_check_tlb(env, tlb, &raddr, &ctx->prot, address, rw,
-                                 access_type, i);
-        if (!ret) {
-            break;
-        }
-    }
-
-    if (ret >= 0) {
-        ctx->raddr = raddr;
-        LOG_SWTLB("%s: access granted " TARGET_FMT_lx " => " TARGET_FMT_plx
-                  " %d %d\n", __func__, address, ctx->raddr, ctx->prot,
-                  ret);
-    } else {
-        LOG_SWTLB("%s: access refused " TARGET_FMT_lx " => " TARGET_FMT_plx
-                  " %d %d\n", __func__, address, raddr, ctx->prot, ret);
-    }
-
-    return ret;
-}
-
-void booke206_flush_tlb(CPUPPCState *env, int flags, const int check_iprot)
-{
-    int tlb_size;
-    int i, j;
-    ppcmas_tlb_t *tlb = env->tlb.tlbm;
-
-    for (i = 0; i < BOOKE206_MAX_TLBN; i++) {
-        if (flags & (1 << i)) {
-            tlb_size = booke206_tlb_size(env, i);
-            for (j = 0; j < tlb_size; j++) {
-                if (!check_iprot || !(tlb[j].mas1 & MAS1_IPROT)) {
-                    tlb[j].mas1 &= ~MAS1_VALID;
-                }
-            }
-        }
-        tlb += booke206_tlb_size(env, i);
-    }
-
-    tlb_flush(env, 1);
-}
-
-target_phys_addr_t booke206_tlb_to_page_size(CPUPPCState *env,
-                                             ppcmas_tlb_t *tlb)
-{
-    int tlbm_size;
-
-    tlbm_size = (tlb->mas1 & MAS1_TSIZE_MASK) >> MAS1_TSIZE_SHIFT;
-
-    return 1024ULL << tlbm_size;
-}
-
-/* TLB check function for MAS based SoftTLBs */
-int ppcmas_tlb_check(CPUPPCState *env, ppcmas_tlb_t *tlb,
-                     target_phys_addr_t *raddrp,
-                     target_ulong address, uint32_t pid)
-{
-    target_ulong mask;
-    uint32_t tlb_pid;
-
-    /* Check valid flag */
-    if (!(tlb->mas1 & MAS1_VALID)) {
-        return -1;
-    }
-
-    mask = ~(booke206_tlb_to_page_size(env, tlb) - 1);
-    LOG_SWTLB("%s: TLB ADDR=0x" TARGET_FMT_lx " PID=0x%x MAS1=0x%x MAS2=0x%"
-              PRIx64 " mask=0x" TARGET_FMT_lx " MAS7_3=0x%" PRIx64 " MAS8=%x\n",
-              __func__, address, pid, tlb->mas1, tlb->mas2, mask, tlb->mas7_3,
-              tlb->mas8);
-
-    /* Check PID */
-    tlb_pid = (tlb->mas1 & MAS1_TID_MASK) >> MAS1_TID_SHIFT;
-    if (tlb_pid != 0 && tlb_pid != pid) {
-        return -1;
-    }
-
-    /* Check effective address */
-    if ((address & mask) != (tlb->mas2 & MAS2_EPN_MASK)) {
-        return -1;
-    }
-
-    if (raddrp) {
-        *raddrp = (tlb->mas7_3 & mask) | (address & ~mask);
-    }
-
-    return 0;
-}
-
-static int mmubooke206_check_tlb(CPUPPCState *env, ppcmas_tlb_t *tlb,
-                                 target_phys_addr_t *raddr, int *prot,
-                                 target_ulong address, int rw,
-                                 int access_type)
-{
-    int ret;
-    int prot2 = 0;
-
-    if (ppcmas_tlb_check(env, tlb, raddr, address,
-                         env->spr[SPR_BOOKE_PID]) >= 0) {
-        goto found_tlb;
-    }
-
-    if (env->spr[SPR_BOOKE_PID1] &&
-        ppcmas_tlb_check(env, tlb, raddr, address,
-                         env->spr[SPR_BOOKE_PID1]) >= 0) {
-        goto found_tlb;
-    }
-
-    if (env->spr[SPR_BOOKE_PID2] &&
-        ppcmas_tlb_check(env, tlb, raddr, address,
-                         env->spr[SPR_BOOKE_PID2]) >= 0) {
-        goto found_tlb;
-    }
-
-    LOG_SWTLB("%s: TLB entry not found\n", __func__);
-    return -1;
-
-found_tlb:
-
-    if (msr_pr != 0) {
-        if (tlb->mas7_3 & MAS3_UR) {
-            prot2 |= PAGE_READ;
-        }
-        if (tlb->mas7_3 & MAS3_UW) {
-            prot2 |= PAGE_WRITE;
-        }
-        if (tlb->mas7_3 & MAS3_UX) {
-            prot2 |= PAGE_EXEC;
-        }
-    } else {
-        if (tlb->mas7_3 & MAS3_SR) {
-            prot2 |= PAGE_READ;
-        }
-        if (tlb->mas7_3 & MAS3_SW) {
-            prot2 |= PAGE_WRITE;
-        }
-        if (tlb->mas7_3 & MAS3_SX) {
-            prot2 |= PAGE_EXEC;
-        }
-    }
-
-    /* Check the address space and permissions */
-    if (access_type == ACCESS_CODE) {
-        if (msr_ir != ((tlb->mas1 & MAS1_TS) >> MAS1_TS_SHIFT)) {
-            LOG_SWTLB("%s: AS doesn't match\n", __func__);
-            return -1;
-        }
-
-        *prot = prot2;
-        if (prot2 & PAGE_EXEC) {
-            LOG_SWTLB("%s: good TLB!\n", __func__);
-            return 0;
-        }
-
-        LOG_SWTLB("%s: no PAGE_EXEC: %x\n", __func__, prot2);
-        ret = -3;
-    } else {
-        if (msr_dr != ((tlb->mas1 & MAS1_TS) >> MAS1_TS_SHIFT)) {
-            LOG_SWTLB("%s: AS doesn't match\n", __func__);
-            return -1;
-        }
-
-        *prot = prot2;
-        if ((!rw && prot2 & PAGE_READ) || (rw && (prot2 & PAGE_WRITE))) {
-            LOG_SWTLB("%s: found TLB!\n", __func__);
-            return 0;
-        }
-
-        LOG_SWTLB("%s: PAGE_READ/WRITE doesn't match: %x\n", __func__, prot2);
-        ret = -2;
-    }
-
-    return ret;
-}
-
-static int mmubooke206_get_physical_address(CPUPPCState *env, mmu_ctx_t *ctx,
-                                            target_ulong address, int rw,
-                                            int access_type)
-{
-    ppcmas_tlb_t *tlb;
-    target_phys_addr_t raddr;
-    int i, j, ret;
-
-    ret = -1;
-    raddr = (target_phys_addr_t)-1ULL;
-
-    for (i = 0; i < BOOKE206_MAX_TLBN; i++) {
-        int ways = booke206_tlb_ways(env, i);
-
-        for (j = 0; j < ways; j++) {
-            tlb = booke206_get_tlbm(env, i, address, j);
-            if (!tlb) {
-                continue;
-            }
-            ret = mmubooke206_check_tlb(env, tlb, &raddr, &ctx->prot, address,
-                                        rw, access_type);
-            if (ret != -1) {
-                goto found_tlb;
-            }
-        }
-    }
-
-found_tlb:
-
-    if (ret >= 0) {
-        ctx->raddr = raddr;
-        LOG_SWTLB("%s: access granted " TARGET_FMT_lx " => " TARGET_FMT_plx
-                  " %d %d\n", __func__, address, ctx->raddr, ctx->prot,
-                  ret);
-    } else {
-        LOG_SWTLB("%s: access refused " TARGET_FMT_lx " => " TARGET_FMT_plx
-                  " %d %d\n", __func__, address, raddr, ctx->prot, ret);
-    }
-
-    return ret;
-}
-
-static const char *book3e_tsize_to_str[32] = {
-    "1K", "2K", "4K", "8K", "16K", "32K", "64K", "128K", "256K", "512K",
-    "1M", "2M", "4M", "8M", "16M", "32M", "64M", "128M", "256M", "512M",
-    "1G", "2G", "4G", "8G", "16G", "32G", "64G", "128G", "256G", "512G",
-    "1T", "2T"
-};
-
-static void mmubooke_dump_mmu(FILE *f, fprintf_function cpu_fprintf,
-                                 CPUPPCState *env)
-{
-    ppcemb_tlb_t *entry;
-    int i;
-
-    if (kvm_enabled() && !env->kvm_sw_tlb) {
-        cpu_fprintf(f, "Cannot access KVM TLB\n");
-        return;
-    }
-
-    cpu_fprintf(f, "\nTLB:\n");
-    cpu_fprintf(f, "Effective          Physical           Size PID   Prot     "
-                "Attr\n");
-
-    entry = &env->tlb.tlbe[0];
-    for (i = 0; i < env->nb_tlb; i++, entry++) {
-        target_phys_addr_t ea, pa;
-        target_ulong mask;
-        uint64_t size = (uint64_t)entry->size;
-        char size_buf[20];
-
-        /* Check valid flag */
-        if (!(entry->prot & PAGE_VALID)) {
-            continue;
-        }
-
-        mask = ~(entry->size - 1);
-        ea = entry->EPN & mask;
-        pa = entry->RPN & mask;
-#if (TARGET_PHYS_ADDR_BITS >= 36)
-        /* Extend the physical address to 36 bits */
-        pa |= (target_phys_addr_t)(entry->RPN & 0xF) << 32;
-#endif
-        size /= 1024;
-        if (size >= 1024) {
-            snprintf(size_buf, sizeof(size_buf), "%3" PRId64 "M", size / 1024);
-        } else {
-            snprintf(size_buf, sizeof(size_buf), "%3" PRId64 "k", size);
-        }
-        cpu_fprintf(f, "0x%016" PRIx64 " 0x%016" PRIx64 " %s %-5u %08x %08x\n",
-                    (uint64_t)ea, (uint64_t)pa, size_buf, (uint32_t)entry->PID,
-                    entry->prot, entry->attr);
-    }
-
-}
-
-static void mmubooke206_dump_one_tlb(FILE *f, fprintf_function cpu_fprintf,
-                                     CPUPPCState *env, int tlbn, int offset,
-                                     int tlbsize)
-{
-    ppcmas_tlb_t *entry;
-    int i;
-
-    cpu_fprintf(f, "\nTLB%d:\n", tlbn);
-    cpu_fprintf(f, "Effective          Physical           Size TID   TS SRWX"
-                " URWX WIMGE U0123\n");
-
-    entry = &env->tlb.tlbm[offset];
-    for (i = 0; i < tlbsize; i++, entry++) {
-        target_phys_addr_t ea, pa, size;
-        int tsize;
-
-        if (!(entry->mas1 & MAS1_VALID)) {
-            continue;
-        }
-
-        tsize = (entry->mas1 & MAS1_TSIZE_MASK) >> MAS1_TSIZE_SHIFT;
-        size = 1024ULL << tsize;
-        ea = entry->mas2 & ~(size - 1);
-        pa = entry->mas7_3 & ~(size - 1);
-
-        cpu_fprintf(f, "0x%016" PRIx64 " 0x%016" PRIx64 " %4s %-5u %1u  S%c%c%c"
-                    "U%c%c%c %c%c%c%c%c U%c%c%c%c\n",
-                    (uint64_t)ea, (uint64_t)pa,
-                    book3e_tsize_to_str[tsize],
-                    (entry->mas1 & MAS1_TID_MASK) >> MAS1_TID_SHIFT,
-                    (entry->mas1 & MAS1_TS) >> MAS1_TS_SHIFT,
-                    entry->mas7_3 & MAS3_SR ? 'R' : '-',
-                    entry->mas7_3 & MAS3_SW ? 'W' : '-',
-                    entry->mas7_3 & MAS3_SX ? 'X' : '-',
-                    entry->mas7_3 & MAS3_UR ? 'R' : '-',
-                    entry->mas7_3 & MAS3_UW ? 'W' : '-',
-                    entry->mas7_3 & MAS3_UX ? 'X' : '-',
-                    entry->mas2 & MAS2_W ? 'W' : '-',
-                    entry->mas2 & MAS2_I ? 'I' : '-',
-                    entry->mas2 & MAS2_M ? 'M' : '-',
-                    entry->mas2 & MAS2_G ? 'G' : '-',
-                    entry->mas2 & MAS2_E ? 'E' : '-',
-                    entry->mas7_3 & MAS3_U0 ? '0' : '-',
-                    entry->mas7_3 & MAS3_U1 ? '1' : '-',
-                    entry->mas7_3 & MAS3_U2 ? '2' : '-',
-                    entry->mas7_3 & MAS3_U3 ? '3' : '-');
-    }
-}
-
-static void mmubooke206_dump_mmu(FILE *f, fprintf_function cpu_fprintf,
-                                 CPUPPCState *env)
-{
-    int offset = 0;
-    int i;
-
-    if (kvm_enabled() && !env->kvm_sw_tlb) {
-        cpu_fprintf(f, "Cannot access KVM TLB\n");
-        return;
-    }
-
-    for (i = 0; i < BOOKE206_MAX_TLBN; i++) {
-        int size = booke206_tlb_size(env, i);
-
-        if (size == 0) {
-            continue;
-        }
-
-        mmubooke206_dump_one_tlb(f, cpu_fprintf, env, i, offset, size);
-        offset += size;
-    }
-}
-
-#if defined(TARGET_PPC64)
-static void mmubooks_dump_mmu(FILE *f, fprintf_function cpu_fprintf,
-                              CPUPPCState *env)
-{
-    int i;
-    uint64_t slbe, slbv;
-
-    cpu_synchronize_state(env);
-
-    cpu_fprintf(f, "SLB\tESID\t\t\tVSID\n");
-    for (i = 0; i < env->slb_nr; i++) {
-        slbe = env->slb[i].esid;
-        slbv = env->slb[i].vsid;
-        if (slbe == 0 && slbv == 0) {
-            continue;
-        }
-        cpu_fprintf(f, "%d\t0x%016" PRIx64 "\t0x%016" PRIx64 "\n",
-                    i, slbe, slbv);
-    }
-}
-#endif
-
-void dump_mmu(FILE *f, fprintf_function cpu_fprintf, CPUPPCState *env)
-{
-    switch (env->mmu_model) {
-    case POWERPC_MMU_BOOKE:
-        mmubooke_dump_mmu(f, cpu_fprintf, env);
-        break;
-    case POWERPC_MMU_BOOKE206:
-        mmubooke206_dump_mmu(f, cpu_fprintf, env);
-        break;
-#if defined(TARGET_PPC64)
-    case POWERPC_MMU_64B:
-    case POWERPC_MMU_2_06:
-        mmubooks_dump_mmu(f, cpu_fprintf, env);
-        break;
-#endif
-    default:
-        qemu_log_mask(LOG_UNIMP, "%s: unimplemented\n", __func__);
-    }
-}
-
-static inline int check_physical(CPUPPCState *env, mmu_ctx_t *ctx,
-                                 target_ulong eaddr, int rw)
-{
-    int in_plb, ret;
-
-    ctx->raddr = eaddr;
-    ctx->prot = PAGE_READ | PAGE_EXEC;
-    ret = 0;
-    switch (env->mmu_model) {
-    case POWERPC_MMU_32B:
-    case POWERPC_MMU_601:
-    case POWERPC_MMU_SOFT_6xx:
-    case POWERPC_MMU_SOFT_74xx:
-    case POWERPC_MMU_SOFT_4xx:
-    case POWERPC_MMU_REAL:
-    case POWERPC_MMU_BOOKE:
-        ctx->prot |= PAGE_WRITE;
-        break;
-#if defined(TARGET_PPC64)
-    case POWERPC_MMU_620:
-    case POWERPC_MMU_64B:
-    case POWERPC_MMU_2_06:
-        /* Real address are 60 bits long */
-        ctx->raddr &= 0x0FFFFFFFFFFFFFFFULL;
-        ctx->prot |= PAGE_WRITE;
-        break;
-#endif
-    case POWERPC_MMU_SOFT_4xx_Z:
-        if (unlikely(msr_pe != 0)) {
-            /* 403 family add some particular protections,
-             * using PBL/PBU registers for accesses with no translation.
-             */
-            in_plb =
-                /* Check PLB validity */
-                (env->pb[0] < env->pb[1] &&
-                 /* and address in plb area */
-                 eaddr >= env->pb[0] && eaddr < env->pb[1]) ||
-                (env->pb[2] < env->pb[3] &&
-                 eaddr >= env->pb[2] && eaddr < env->pb[3]) ? 1 : 0;
-            if (in_plb ^ msr_px) {
-                /* Access in protected area */
-                if (rw == 1) {
-                    /* Access is not allowed */
-                    ret = -2;
-                }
-            } else {
-                /* Read-write access is allowed */
-                ctx->prot |= PAGE_WRITE;
-            }
-        }
-        break;
-    case POWERPC_MMU_MPC8xx:
-        /* XXX: TODO */
-        cpu_abort(env, "MPC8xx MMU model is not implemented\n");
-        break;
-    case POWERPC_MMU_BOOKE206:
-        cpu_abort(env, "BookE 2.06 MMU doesn't have physical real mode\n");
-        break;
-    default:
-        cpu_abort(env, "Unknown or invalid MMU model\n");
-        return -1;
-    }
-
-    return ret;
-}
-
-int get_physical_address(CPUPPCState *env, mmu_ctx_t *ctx, target_ulong eaddr,
-                         int rw, int access_type)
-{
-    int ret;
-
-#if 0
-    qemu_log("%s\n", __func__);
-#endif
-    if ((access_type == ACCESS_CODE && msr_ir == 0) ||
-        (access_type != ACCESS_CODE && msr_dr == 0)) {
-        if (env->mmu_model == POWERPC_MMU_BOOKE) {
-            /* The BookE MMU always performs address translation. The
-               IS and DS bits only affect the address space.  */
-            ret = mmubooke_get_physical_address(env, ctx, eaddr,
-                                                rw, access_type);
-        } else if (env->mmu_model == POWERPC_MMU_BOOKE206) {
-            ret = mmubooke206_get_physical_address(env, ctx, eaddr, rw,
-                                                   access_type);
-        } else {
-            /* No address translation.  */
-            ret = check_physical(env, ctx, eaddr, rw);
-        }
-    } else {
-        ret = -1;
-        switch (env->mmu_model) {
-        case POWERPC_MMU_32B:
-        case POWERPC_MMU_601:
-        case POWERPC_MMU_SOFT_6xx:
-        case POWERPC_MMU_SOFT_74xx:
-            /* Try to find a BAT */
-            if (env->nb_BATs != 0) {
-                ret = get_bat(env, ctx, eaddr, rw, access_type);
-            }
-#if defined(TARGET_PPC64)
-        case POWERPC_MMU_620:
-        case POWERPC_MMU_64B:
-        case POWERPC_MMU_2_06:
-#endif
-            if (ret < 0) {
-                /* We didn't match any BAT entry or don't have BATs */
-                ret = get_segment(env, ctx, eaddr, rw, access_type);
-            }
-            break;
-        case POWERPC_MMU_SOFT_4xx:
-        case POWERPC_MMU_SOFT_4xx_Z:
-            ret = mmu40x_get_physical_address(env, ctx, eaddr,
-                                              rw, access_type);
-            break;
-        case POWERPC_MMU_BOOKE:
-            ret = mmubooke_get_physical_address(env, ctx, eaddr,
-                                                rw, access_type);
-            break;
-        case POWERPC_MMU_BOOKE206:
-            ret = mmubooke206_get_physical_address(env, ctx, eaddr, rw,
-                                               access_type);
-            break;
-        case POWERPC_MMU_MPC8xx:
-            /* XXX: TODO */
-            cpu_abort(env, "MPC8xx MMU model is not implemented\n");
-            break;
-        case POWERPC_MMU_REAL:
-            cpu_abort(env, "PowerPC in real mode do not do any translation\n");
-            return -1;
-        default:
-            cpu_abort(env, "Unknown or invalid MMU model\n");
-            return -1;
-        }
-    }
-#if 0
-    qemu_log("%s address " TARGET_FMT_lx " => %d " TARGET_FMT_plx "\n",
-             __func__, eaddr, ret, ctx->raddr);
-#endif
-
-    return ret;
-}
-
-target_phys_addr_t cpu_get_phys_page_debug(CPUPPCState *env, target_ulong addr)
-{
-    mmu_ctx_t ctx;
-
-    if (unlikely(get_physical_address(env, &ctx, addr, 0, ACCESS_INT) != 0)) {
-        return -1;
-    }
-
-    return ctx.raddr & TARGET_PAGE_MASK;
-}
-
-static void booke206_update_mas_tlb_miss(CPUPPCState *env, target_ulong address,
-                                     int rw)
-{
-    env->spr[SPR_BOOKE_MAS0] = env->spr[SPR_BOOKE_MAS4] & MAS4_TLBSELD_MASK;
-    env->spr[SPR_BOOKE_MAS1] = env->spr[SPR_BOOKE_MAS4] & MAS4_TSIZED_MASK;
-    env->spr[SPR_BOOKE_MAS2] = env->spr[SPR_BOOKE_MAS4] & MAS4_WIMGED_MASK;
-    env->spr[SPR_BOOKE_MAS3] = 0;
-    env->spr[SPR_BOOKE_MAS6] = 0;
-    env->spr[SPR_BOOKE_MAS7] = 0;
-
-    /* AS */
-    if (((rw == 2) && msr_ir) || ((rw != 2) && msr_dr)) {
-        env->spr[SPR_BOOKE_MAS1] |= MAS1_TS;
-        env->spr[SPR_BOOKE_MAS6] |= MAS6_SAS;
-    }
-
-    env->spr[SPR_BOOKE_MAS1] |= MAS1_VALID;
-    env->spr[SPR_BOOKE_MAS2] |= address & MAS2_EPN_MASK;
-
-    switch (env->spr[SPR_BOOKE_MAS4] & MAS4_TIDSELD_PIDZ) {
-    case MAS4_TIDSELD_PID0:
-        env->spr[SPR_BOOKE_MAS1] |= env->spr[SPR_BOOKE_PID] << MAS1_TID_SHIFT;
-        break;
-    case MAS4_TIDSELD_PID1:
-        env->spr[SPR_BOOKE_MAS1] |= env->spr[SPR_BOOKE_PID1] << MAS1_TID_SHIFT;
-        break;
-    case MAS4_TIDSELD_PID2:
-        env->spr[SPR_BOOKE_MAS1] |= env->spr[SPR_BOOKE_PID2] << MAS1_TID_SHIFT;
-        break;
-    }
-
-    env->spr[SPR_BOOKE_MAS6] |= env->spr[SPR_BOOKE_PID] << 16;
-
-    /* next victim logic */
-    env->spr[SPR_BOOKE_MAS0] |= env->last_way << MAS0_ESEL_SHIFT;
-    env->last_way++;
-    env->last_way &= booke206_tlb_ways(env, 0) - 1;
-    env->spr[SPR_BOOKE_MAS0] |= env->last_way << MAS0_NV_SHIFT;
-}
-
-/* Perform address translation */
-int cpu_ppc_handle_mmu_fault(CPUPPCState *env, target_ulong address, int rw,
-                             int mmu_idx)
-{
-    mmu_ctx_t ctx;
-    int access_type;
-    int ret = 0;
-
-    if (rw == 2) {
-        /* code access */
-        rw = 0;
-        access_type = ACCESS_CODE;
-    } else {
-        /* data access */
-        access_type = env->access_type;
-    }
-    ret = get_physical_address(env, &ctx, address, rw, access_type);
-    if (ret == 0) {
-        tlb_set_page(env, address & TARGET_PAGE_MASK,
-                     ctx.raddr & TARGET_PAGE_MASK, ctx.prot,
-                     mmu_idx, TARGET_PAGE_SIZE);
-        ret = 0;
-    } else if (ret < 0) {
-        LOG_MMU_STATE(env);
-        if (access_type == ACCESS_CODE) {
-            switch (ret) {
-            case -1:
-                /* No matches in page tables or TLB */
-                switch (env->mmu_model) {
-                case POWERPC_MMU_SOFT_6xx:
-                    env->exception_index = POWERPC_EXCP_IFTLB;
-                    env->error_code = 1 << 18;
-                    env->spr[SPR_IMISS] = address;
-                    env->spr[SPR_ICMP] = 0x80000000 | ctx.ptem;
-                    goto tlb_miss;
-                case POWERPC_MMU_SOFT_74xx:
-                    env->exception_index = POWERPC_EXCP_IFTLB;
-                    goto tlb_miss_74xx;
-                case POWERPC_MMU_SOFT_4xx:
-                case POWERPC_MMU_SOFT_4xx_Z:
-                    env->exception_index = POWERPC_EXCP_ITLB;
-                    env->error_code = 0;
-                    env->spr[SPR_40x_DEAR] = address;
-                    env->spr[SPR_40x_ESR] = 0x00000000;
-                    break;
-                case POWERPC_MMU_32B:
-                case POWERPC_MMU_601:
-#if defined(TARGET_PPC64)
-                case POWERPC_MMU_620:
-                case POWERPC_MMU_64B:
-                case POWERPC_MMU_2_06:
-#endif
-                    env->exception_index = POWERPC_EXCP_ISI;
-                    env->error_code = 0x40000000;
-                    break;
-                case POWERPC_MMU_BOOKE206:
-                    booke206_update_mas_tlb_miss(env, address, rw);
-                    /* fall through */
-                case POWERPC_MMU_BOOKE:
-                    env->exception_index = POWERPC_EXCP_ITLB;
-                    env->error_code = 0;
-                    env->spr[SPR_BOOKE_DEAR] = address;
-                    return -1;
-                case POWERPC_MMU_MPC8xx:
-                    /* XXX: TODO */
-                    cpu_abort(env, "MPC8xx MMU model is not implemented\n");
-                    break;
-                case POWERPC_MMU_REAL:
-                    cpu_abort(env, "PowerPC in real mode should never raise "
-                              "any MMU exceptions\n");
-                    return -1;
-                default:
-                    cpu_abort(env, "Unknown or invalid MMU model\n");
-                    return -1;
-                }
-                break;
-            case -2:
-                /* Access rights violation */
-                env->exception_index = POWERPC_EXCP_ISI;
-                env->error_code = 0x08000000;
-                break;
-            case -3:
-                /* No execute protection violation */
-                if ((env->mmu_model == POWERPC_MMU_BOOKE) ||
-                    (env->mmu_model == POWERPC_MMU_BOOKE206)) {
-                    env->spr[SPR_BOOKE_ESR] = 0x00000000;
-                }
-                env->exception_index = POWERPC_EXCP_ISI;
-                env->error_code = 0x10000000;
-                break;
-            case -4:
-                /* Direct store exception */
-                /* No code fetch is allowed in direct-store areas */
-                env->exception_index = POWERPC_EXCP_ISI;
-                env->error_code = 0x10000000;
-                break;
-#if defined(TARGET_PPC64)
-            case -5:
-                /* No match in segment table */
-                if (env->mmu_model == POWERPC_MMU_620) {
-                    env->exception_index = POWERPC_EXCP_ISI;
-                    /* XXX: this might be incorrect */
-                    env->error_code = 0x40000000;
-                } else {
-                    env->exception_index = POWERPC_EXCP_ISEG;
-                    env->error_code = 0;
-                }
-                break;
-#endif
-            }
-        } else {
-            switch (ret) {
-            case -1:
-                /* No matches in page tables or TLB */
-                switch (env->mmu_model) {
-                case POWERPC_MMU_SOFT_6xx:
-                    if (rw == 1) {
-                        env->exception_index = POWERPC_EXCP_DSTLB;
-                        env->error_code = 1 << 16;
-                    } else {
-                        env->exception_index = POWERPC_EXCP_DLTLB;
-                        env->error_code = 0;
-                    }
-                    env->spr[SPR_DMISS] = address;
-                    env->spr[SPR_DCMP] = 0x80000000 | ctx.ptem;
-                tlb_miss:
-                    env->error_code |= ctx.key << 19;
-                    env->spr[SPR_HASH1] = env->htab_base +
-                        get_pteg_offset(env, ctx.hash[0], HASH_PTE_SIZE_32);
-                    env->spr[SPR_HASH2] = env->htab_base +
-                        get_pteg_offset(env, ctx.hash[1], HASH_PTE_SIZE_32);
-                    break;
-                case POWERPC_MMU_SOFT_74xx:
-                    if (rw == 1) {
-                        env->exception_index = POWERPC_EXCP_DSTLB;
-                    } else {
-                        env->exception_index = POWERPC_EXCP_DLTLB;
-                    }
-                tlb_miss_74xx:
-                    /* Implement LRU algorithm */
-                    env->error_code = ctx.key << 19;
-                    env->spr[SPR_TLBMISS] = (address & ~((target_ulong)0x3)) |
-                        ((env->last_way + 1) & (env->nb_ways - 1));
-                    env->spr[SPR_PTEHI] = 0x80000000 | ctx.ptem;
-                    break;
-                case POWERPC_MMU_SOFT_4xx:
-                case POWERPC_MMU_SOFT_4xx_Z:
-                    env->exception_index = POWERPC_EXCP_DTLB;
-                    env->error_code = 0;
-                    env->spr[SPR_40x_DEAR] = address;
-                    if (rw) {
-                        env->spr[SPR_40x_ESR] = 0x00800000;
-                    } else {
-                        env->spr[SPR_40x_ESR] = 0x00000000;
-                    }
-                    break;
-                case POWERPC_MMU_32B:
-                case POWERPC_MMU_601:
-#if defined(TARGET_PPC64)
-                case POWERPC_MMU_620:
-                case POWERPC_MMU_64B:
-                case POWERPC_MMU_2_06:
-#endif
-                    env->exception_index = POWERPC_EXCP_DSI;
-                    env->error_code = 0;
-                    env->spr[SPR_DAR] = address;
-                    if (rw == 1) {
-                        env->spr[SPR_DSISR] = 0x42000000;
-                    } else {
-                        env->spr[SPR_DSISR] = 0x40000000;
-                    }
-                    break;
-                case POWERPC_MMU_MPC8xx:
-                    /* XXX: TODO */
-                    cpu_abort(env, "MPC8xx MMU model is not implemented\n");
-                    break;
-                case POWERPC_MMU_BOOKE206:
-                    booke206_update_mas_tlb_miss(env, address, rw);
-                    /* fall through */
-                case POWERPC_MMU_BOOKE:
-                    env->exception_index = POWERPC_EXCP_DTLB;
-                    env->error_code = 0;
-                    env->spr[SPR_BOOKE_DEAR] = address;
-                    env->spr[SPR_BOOKE_ESR] = rw ? ESR_ST : 0;
-                    return -1;
-                case POWERPC_MMU_REAL:
-                    cpu_abort(env, "PowerPC in real mode should never raise "
-                              "any MMU exceptions\n");
-                    return -1;
-                default:
-                    cpu_abort(env, "Unknown or invalid MMU model\n");
-                    return -1;
-                }
-                break;
-            case -2:
-                /* Access rights violation */
-                env->exception_index = POWERPC_EXCP_DSI;
-                env->error_code = 0;
-                if (env->mmu_model == POWERPC_MMU_SOFT_4xx
-                    || env->mmu_model == POWERPC_MMU_SOFT_4xx_Z) {
-                    env->spr[SPR_40x_DEAR] = address;
-                    if (rw) {
-                        env->spr[SPR_40x_ESR] |= 0x00800000;
-                    }
-                } else if ((env->mmu_model == POWERPC_MMU_BOOKE) ||
-                           (env->mmu_model == POWERPC_MMU_BOOKE206)) {
-                    env->spr[SPR_BOOKE_DEAR] = address;
-                    env->spr[SPR_BOOKE_ESR] = rw ? ESR_ST : 0;
-                } else {
-                    env->spr[SPR_DAR] = address;
-                    if (rw == 1) {
-                        env->spr[SPR_DSISR] = 0x0A000000;
-                    } else {
-                        env->spr[SPR_DSISR] = 0x08000000;
-                    }
-                }
-                break;
-            case -4:
-                /* Direct store exception */
-                switch (access_type) {
-                case ACCESS_FLOAT:
-                    /* Floating point load/store */
-                    env->exception_index = POWERPC_EXCP_ALIGN;
-                    env->error_code = POWERPC_EXCP_ALIGN_FP;
-                    env->spr[SPR_DAR] = address;
-                    break;
-                case ACCESS_RES:
-                    /* lwarx, ldarx or stwcx. */
-                    env->exception_index = POWERPC_EXCP_DSI;
-                    env->error_code = 0;
-                    env->spr[SPR_DAR] = address;
-                    if (rw == 1) {
-                        env->spr[SPR_DSISR] = 0x06000000;
-                    } else {
-                        env->spr[SPR_DSISR] = 0x04000000;
-                    }
-                    break;
-                case ACCESS_EXT:
-                    /* eciwx or ecowx */
-                    env->exception_index = POWERPC_EXCP_DSI;
-                    env->error_code = 0;
-                    env->spr[SPR_DAR] = address;
-                    if (rw == 1) {
-                        env->spr[SPR_DSISR] = 0x06100000;
-                    } else {
-                        env->spr[SPR_DSISR] = 0x04100000;
-                    }
-                    break;
-                default:
-                    printf("DSI: invalid exception (%d)\n", ret);
-                    env->exception_index = POWERPC_EXCP_PROGRAM;
-                    env->error_code =
-                        POWERPC_EXCP_INVAL | POWERPC_EXCP_INVAL_INVAL;
-                    env->spr[SPR_DAR] = address;
-                    break;
-                }
-                break;
-#if defined(TARGET_PPC64)
-            case -5:
-                /* No match in segment table */
-                if (env->mmu_model == POWERPC_MMU_620) {
-                    env->exception_index = POWERPC_EXCP_DSI;
-                    env->error_code = 0;
-                    env->spr[SPR_DAR] = address;
-                    /* XXX: this might be incorrect */
-                    if (rw == 1) {
-                        env->spr[SPR_DSISR] = 0x42000000;
-                    } else {
-                        env->spr[SPR_DSISR] = 0x40000000;
-                    }
-                } else {
-                    env->exception_index = POWERPC_EXCP_DSEG;
-                    env->error_code = 0;
-                    env->spr[SPR_DAR] = address;
-                }
-                break;
-#endif
-            }
-        }
-#if 0
-        printf("%s: set exception to %d %02x\n", __func__,
-               env->exception, env->error_code);
-#endif
-        ret = 1;
-    }
-
-    return ret;
-}
-
-/*****************************************************************************/
-/* BATs management */
-#if !defined(FLUSH_ALL_TLBS)
-static inline void do_invalidate_BAT(CPUPPCState *env, target_ulong BATu,
-                                     target_ulong mask)
-{
-    target_ulong base, end, page;
-
-    base = BATu & ~0x0001FFFF;
-    end = base + mask + 0x00020000;
-    LOG_BATS("Flush BAT from " TARGET_FMT_lx " to " TARGET_FMT_lx " ("
-             TARGET_FMT_lx ")\n", base, end, mask);
-    for (page = base; page != end; page += TARGET_PAGE_SIZE) {
-        tlb_flush_page(env, page);
-    }
-    LOG_BATS("Flush done\n");
-}
-#endif
-
-static inline void dump_store_bat(CPUPPCState *env, char ID, int ul, int nr,
-                                  target_ulong value)
-{
-    LOG_BATS("Set %cBAT%d%c to " TARGET_FMT_lx " (" TARGET_FMT_lx ")\n", ID,
-             nr, ul == 0 ? 'u' : 'l', value, env->nip);
-}
-
-void ppc_store_ibatu(CPUPPCState *env, int nr, target_ulong value)
-{
-    target_ulong mask;
-
-    dump_store_bat(env, 'I', 0, nr, value);
-    if (env->IBAT[0][nr] != value) {
-        mask = (value << 15) & 0x0FFE0000UL;
-#if !defined(FLUSH_ALL_TLBS)
-        do_invalidate_BAT(env, env->IBAT[0][nr], mask);
-#endif
-        /* When storing valid upper BAT, mask BEPI and BRPN
-         * and invalidate all TLBs covered by this BAT
-         */
-        mask = (value << 15) & 0x0FFE0000UL;
-        env->IBAT[0][nr] = (value & 0x00001FFFUL) |
-            (value & ~0x0001FFFFUL & ~mask);
-        env->IBAT[1][nr] = (env->IBAT[1][nr] & 0x0000007B) |
-            (env->IBAT[1][nr] & ~0x0001FFFF & ~mask);
-#if !defined(FLUSH_ALL_TLBS)
-        do_invalidate_BAT(env, env->IBAT[0][nr], mask);
-#else
-        tlb_flush(env, 1);
-#endif
-    }
-}
-
-void ppc_store_ibatl(CPUPPCState *env, int nr, target_ulong value)
-{
-    dump_store_bat(env, 'I', 1, nr, value);
-    env->IBAT[1][nr] = value;
-}
-
-void ppc_store_dbatu(CPUPPCState *env, int nr, target_ulong value)
-{
-    target_ulong mask;
-
-    dump_store_bat(env, 'D', 0, nr, value);
-    if (env->DBAT[0][nr] != value) {
-        /* When storing valid upper BAT, mask BEPI and BRPN
-         * and invalidate all TLBs covered by this BAT
-         */
-        mask = (value << 15) & 0x0FFE0000UL;
-#if !defined(FLUSH_ALL_TLBS)
-        do_invalidate_BAT(env, env->DBAT[0][nr], mask);
-#endif
-        mask = (value << 15) & 0x0FFE0000UL;
-        env->DBAT[0][nr] = (value & 0x00001FFFUL) |
-            (value & ~0x0001FFFFUL & ~mask);
-        env->DBAT[1][nr] = (env->DBAT[1][nr] & 0x0000007B) |
-            (env->DBAT[1][nr] & ~0x0001FFFF & ~mask);
-#if !defined(FLUSH_ALL_TLBS)
-        do_invalidate_BAT(env, env->DBAT[0][nr], mask);
-#else
-        tlb_flush(env, 1);
-#endif
-    }
-}
-
-void ppc_store_dbatl(CPUPPCState *env, int nr, target_ulong value)
-{
-    dump_store_bat(env, 'D', 1, nr, value);
-    env->DBAT[1][nr] = value;
-}
-
-void ppc_store_ibatu_601(CPUPPCState *env, int nr, target_ulong value)
-{
-    target_ulong mask;
-#if defined(FLUSH_ALL_TLBS)
-    int do_inval;
-#endif
-
-    dump_store_bat(env, 'I', 0, nr, value);
-    if (env->IBAT[0][nr] != value) {
-#if defined(FLUSH_ALL_TLBS)
-        do_inval = 0;
-#endif
-        mask = (env->IBAT[1][nr] << 17) & 0x0FFE0000UL;
-        if (env->IBAT[1][nr] & 0x40) {
-            /* Invalidate BAT only if it is valid */
-#if !defined(FLUSH_ALL_TLBS)
-            do_invalidate_BAT(env, env->IBAT[0][nr], mask);
-#else
-            do_inval = 1;
-#endif
-        }
-        /* When storing valid upper BAT, mask BEPI and BRPN
-         * and invalidate all TLBs covered by this BAT
-         */
-        env->IBAT[0][nr] = (value & 0x00001FFFUL) |
-            (value & ~0x0001FFFFUL & ~mask);
-        env->DBAT[0][nr] = env->IBAT[0][nr];
-        if (env->IBAT[1][nr] & 0x40) {
-#if !defined(FLUSH_ALL_TLBS)
-            do_invalidate_BAT(env, env->IBAT[0][nr], mask);
-#else
-            do_inval = 1;
-#endif
-        }
-#if defined(FLUSH_ALL_TLBS)
-        if (do_inval) {
-            tlb_flush(env, 1);
-        }
-#endif
-    }
-}
-
-void ppc_store_ibatl_601(CPUPPCState *env, int nr, target_ulong value)
-{
-    target_ulong mask;
-#if defined(FLUSH_ALL_TLBS)
-    int do_inval;
-#endif
-
-    dump_store_bat(env, 'I', 1, nr, value);
-    if (env->IBAT[1][nr] != value) {
-#if defined(FLUSH_ALL_TLBS)
-        do_inval = 0;
-#endif
-        if (env->IBAT[1][nr] & 0x40) {
-#if !defined(FLUSH_ALL_TLBS)
-            mask = (env->IBAT[1][nr] << 17) & 0x0FFE0000UL;
-            do_invalidate_BAT(env, env->IBAT[0][nr], mask);
-#else
-            do_inval = 1;
-#endif
-        }
-        if (value & 0x40) {
-#if !defined(FLUSH_ALL_TLBS)
-            mask = (value << 17) & 0x0FFE0000UL;
-            do_invalidate_BAT(env, env->IBAT[0][nr], mask);
-#else
-            do_inval = 1;
-#endif
-        }
-        env->IBAT[1][nr] = value;
-        env->DBAT[1][nr] = value;
-#if defined(FLUSH_ALL_TLBS)
-        if (do_inval) {
-            tlb_flush(env, 1);
-        }
-#endif
-    }
-}
-
-/*****************************************************************************/
-/* TLB management */
-void ppc_tlb_invalidate_all(CPUPPCState *env)
-{
-    switch (env->mmu_model) {
-    case POWERPC_MMU_SOFT_6xx:
-    case POWERPC_MMU_SOFT_74xx:
-        ppc6xx_tlb_invalidate_all(env);
-        break;
-    case POWERPC_MMU_SOFT_4xx:
-    case POWERPC_MMU_SOFT_4xx_Z:
-        ppc4xx_tlb_invalidate_all(env);
-        break;
-    case POWERPC_MMU_REAL:
-        cpu_abort(env, "No TLB for PowerPC 4xx in real mode\n");
-        break;
-    case POWERPC_MMU_MPC8xx:
-        /* XXX: TODO */
-        cpu_abort(env, "MPC8xx MMU model is not implemented\n");
-        break;
-    case POWERPC_MMU_BOOKE:
-        tlb_flush(env, 1);
-        break;
-    case POWERPC_MMU_BOOKE206:
-        booke206_flush_tlb(env, -1, 0);
-        break;
-    case POWERPC_MMU_32B:
-    case POWERPC_MMU_601:
-#if defined(TARGET_PPC64)
-    case POWERPC_MMU_620:
-    case POWERPC_MMU_64B:
-    case POWERPC_MMU_2_06:
-#endif /* defined(TARGET_PPC64) */
-        tlb_flush(env, 1);
-        break;
-    default:
-        /* XXX: TODO */
-        cpu_abort(env, "Unknown MMU model\n");
-        break;
-    }
-}
-
-void ppc_tlb_invalidate_one(CPUPPCState *env, target_ulong addr)
-{
-#if !defined(FLUSH_ALL_TLBS)
-    addr &= TARGET_PAGE_MASK;
-    switch (env->mmu_model) {
-    case POWERPC_MMU_SOFT_6xx:
-    case POWERPC_MMU_SOFT_74xx:
-        ppc6xx_tlb_invalidate_virt(env, addr, 0);
-        if (env->id_tlbs == 1) {
-            ppc6xx_tlb_invalidate_virt(env, addr, 1);
-        }
-        break;
-    case POWERPC_MMU_SOFT_4xx:
-    case POWERPC_MMU_SOFT_4xx_Z:
-        ppc4xx_tlb_invalidate_virt(env, addr, env->spr[SPR_40x_PID]);
-        break;
-    case POWERPC_MMU_REAL:
-        cpu_abort(env, "No TLB for PowerPC 4xx in real mode\n");
-        break;
-    case POWERPC_MMU_MPC8xx:
-        /* XXX: TODO */
-        cpu_abort(env, "MPC8xx MMU model is not implemented\n");
-        break;
-    case POWERPC_MMU_BOOKE:
-        /* XXX: TODO */
-        cpu_abort(env, "BookE MMU model is not implemented\n");
-        break;
-    case POWERPC_MMU_BOOKE206:
-        /* XXX: TODO */
-        cpu_abort(env, "BookE 2.06 MMU model is not implemented\n");
-        break;
-    case POWERPC_MMU_32B:
-    case POWERPC_MMU_601:
-        /* tlbie invalidate TLBs for all segments */
-        addr &= ~((target_ulong)-1ULL << 28);
-        /* XXX: this case should be optimized,
-         * giving a mask to tlb_flush_page
-         */
-        tlb_flush_page(env, addr | (0x0 << 28));
-        tlb_flush_page(env, addr | (0x1 << 28));
-        tlb_flush_page(env, addr | (0x2 << 28));
-        tlb_flush_page(env, addr | (0x3 << 28));
-        tlb_flush_page(env, addr | (0x4 << 28));
-        tlb_flush_page(env, addr | (0x5 << 28));
-        tlb_flush_page(env, addr | (0x6 << 28));
-        tlb_flush_page(env, addr | (0x7 << 28));
-        tlb_flush_page(env, addr | (0x8 << 28));
-        tlb_flush_page(env, addr | (0x9 << 28));
-        tlb_flush_page(env, addr | (0xA << 28));
-        tlb_flush_page(env, addr | (0xB << 28));
-        tlb_flush_page(env, addr | (0xC << 28));
-        tlb_flush_page(env, addr | (0xD << 28));
-        tlb_flush_page(env, addr | (0xE << 28));
-        tlb_flush_page(env, addr | (0xF << 28));
-        break;
-#if defined(TARGET_PPC64)
-    case POWERPC_MMU_620:
-    case POWERPC_MMU_64B:
-    case POWERPC_MMU_2_06:
-        /* tlbie invalidate TLBs for all segments */
-        /* XXX: given the fact that there are too many segments to invalidate,
-         *      and we still don't have a tlb_flush_mask(env, n, mask) in QEMU,
-         *      we just invalidate all TLBs
-         */
-        tlb_flush(env, 1);
-        break;
-#endif /* defined(TARGET_PPC64) */
-    default:
-        /* XXX: TODO */
-        cpu_abort(env, "Unknown MMU model\n");
-        break;
-    }
-#else
-    ppc_tlb_invalidate_all(env);
-#endif
-}
-
 /*****************************************************************************/
 /* Special registers manipulation */
-#if defined(TARGET_PPC64)
-void ppc_store_asr(CPUPPCState *env, target_ulong value)
-{
-    if (env->asr != value) {
-        env->asr = value;
-        tlb_flush(env, 1);
-    }
-}
-#endif
-
-void ppc_store_sdr1(CPUPPCState *env, target_ulong value)
-{
-    LOG_MMU("%s: " TARGET_FMT_lx "\n", __func__, value);
-    if (env->spr[SPR_SDR1] != value) {
-        env->spr[SPR_SDR1] = value;
-#if defined(TARGET_PPC64)
-        if (env->mmu_model & POWERPC_MMU_64) {
-            target_ulong htabsize = value & SDR_64_HTABSIZE;
-
-            if (htabsize > 28) {
-                fprintf(stderr, "Invalid HTABSIZE 0x" TARGET_FMT_lx
-                        " stored in SDR1\n", htabsize);
-                htabsize = 28;
-            }
-            env->htab_mask = (1ULL << (htabsize + 18)) - 1;
-            env->htab_base = value & SDR_64_HTABORG;
-        } else
-#endif /* defined(TARGET_PPC64) */
-        {
-            /* FIXME: Should check for valid HTABMASK values */
-            env->htab_mask = ((value & SDR_32_HTABMASK) << 16) | 0xFFFF;
-            env->htab_base = value & SDR_32_HTABORG;
-        }
-        tlb_flush(env, 1);
-    }
-}
-
-#if defined(TARGET_PPC64)
-target_ulong ppc_load_sr(CPUPPCState *env, int slb_nr)
-{
-    /* XXX */
-    return 0;
-}
-#endif
-
-void ppc_store_sr(CPUPPCState *env, int srnum, target_ulong value)
-{
-    LOG_MMU("%s: reg=%d " TARGET_FMT_lx " " TARGET_FMT_lx "\n", __func__,
-            srnum, value, env->sr[srnum]);
-#if defined(TARGET_PPC64)
-    if (env->mmu_model & POWERPC_MMU_64) {
-        uint64_t rb = 0, rs = 0;
-
-        /* ESID = srnum */
-        rb |= ((uint32_t)srnum & 0xf) << 28;
-        /* Set the valid bit */
-        rb |= 1 << 27;
-        /* Index = ESID */
-        rb |= (uint32_t)srnum;
-
-        /* VSID = VSID */
-        rs |= (value & 0xfffffff) << 12;
-        /* flags = flags */
-        rs |= ((value >> 27) & 0xf) << 8;
-
-        ppc_store_slb(env, rb, rs);
-    } else
-#endif
-    if (env->sr[srnum] != value) {
-        env->sr[srnum] = value;
-/* Invalidating 256MB of virtual memory in 4kB pages is way longer than
-   flusing the whole TLB. */
-#if !defined(FLUSH_ALL_TLBS) && 0
-        {
-            target_ulong page, end;
-            /* Invalidate 256 MB of virtual memory */
-            page = (16 << 20) * srnum;
-            end = page + (16 << 20);
-            for (; page != end; page += TARGET_PAGE_SIZE) {
-                tlb_flush_page(env, page);
-            }
-        }
-#else
-        tlb_flush(env, 1);
-#endif
-    }
-}
-#endif /* !defined(CONFIG_USER_ONLY) */
 
 /* GDBstub can read and write MSR... */
 void ppc_store_msr(CPUPPCState *env, target_ulong value)
diff --git a/target-ppc/mmu_helper.c b/target-ppc/mmu_helper.c
index e79b8f2..1f67451 100644
--- a/target-ppc/mmu_helper.c
+++ b/target-ppc/mmu_helper.c
@@ -18,8 +18,24 @@
  */
 #include "cpu.h"
 #include "helper.h"
+#include "kvm.h"
+#include "kvm_ppc.h"
 
+//#define DEBUG_MMU
+//#define DEBUG_BATS
+//#define DEBUG_SLB
 //#define DEBUG_SOFTWARE_TLB
+//#define DUMP_PAGE_TABLES
+//#define DEBUG_SOFTWARE_TLB
+//#define FLUSH_ALL_TLBS
+
+#ifdef DEBUG_MMU
+#  define LOG_MMU(...) qemu_log(__VA_ARGS__)
+#  define LOG_MMU_STATE(env) log_cpu_state((env), 0)
+#else
+#  define LOG_MMU(...) do { } while (0)
+#  define LOG_MMU_STATE(...) do { } while (0)
+#endif
 
 #ifdef DEBUG_SOFTWARE_TLB
 #  define LOG_SWTLB(...) qemu_log(__VA_ARGS__)
@@ -27,6 +43,2461 @@
 #  define LOG_SWTLB(...) do { } while (0)
 #endif
 
+#ifdef DEBUG_BATS
+#  define LOG_BATS(...) qemu_log(__VA_ARGS__)
+#else
+#  define LOG_BATS(...) do { } while (0)
+#endif
+
+#ifdef DEBUG_SLB
+#  define LOG_SLB(...) qemu_log(__VA_ARGS__)
+#else
+#  define LOG_SLB(...) do { } while (0)
+#endif
+
+/*****************************************************************************/
+/* PowerPC MMU emulation */
+#if defined(CONFIG_USER_ONLY)
+int cpu_ppc_handle_mmu_fault(CPUPPCState *env, target_ulong address, int rw,
+                             int mmu_idx)
+{
+    int exception, error_code;
+
+    if (rw == 2) {
+        exception = POWERPC_EXCP_ISI;
+        error_code = 0x40000000;
+    } else {
+        exception = POWERPC_EXCP_DSI;
+        error_code = 0x40000000;
+        if (rw) {
+            error_code |= 0x02000000;
+        }
+        env->spr[SPR_DAR] = address;
+        env->spr[SPR_DSISR] = error_code;
+    }
+    env->exception_index = exception;
+    env->error_code = error_code;
+
+    return 1;
+}
+
+#else
+/* Common routines used by software and hardware TLBs emulation */
+static inline int pte_is_valid(target_ulong pte0)
+{
+    return pte0 & 0x80000000 ? 1 : 0;
+}
+
+static inline void pte_invalidate(target_ulong *pte0)
+{
+    *pte0 &= ~0x80000000;
+}
+
+#if defined(TARGET_PPC64)
+static inline int pte64_is_valid(target_ulong pte0)
+{
+    return pte0 & 0x0000000000000001ULL ? 1 : 0;
+}
+
+static inline void pte64_invalidate(target_ulong *pte0)
+{
+    *pte0 &= ~0x0000000000000001ULL;
+}
+#endif
+
+#define PTE_PTEM_MASK 0x7FFFFFBF
+#define PTE_CHECK_MASK (TARGET_PAGE_MASK | 0x7B)
+#if defined(TARGET_PPC64)
+#define PTE64_PTEM_MASK 0xFFFFFFFFFFFFFF80ULL
+#define PTE64_CHECK_MASK (TARGET_PAGE_MASK | 0x7F)
+#endif
+
+static inline int pp_check(int key, int pp, int nx)
+{
+    int access;
+
+    /* Compute access rights */
+    /* When pp is 3/7, the result is undefined. Set it to noaccess */
+    access = 0;
+    if (key == 0) {
+        switch (pp) {
+        case 0x0:
+        case 0x1:
+        case 0x2:
+            access |= PAGE_WRITE;
+            /* No break here */
+        case 0x3:
+        case 0x6:
+            access |= PAGE_READ;
+            break;
+        }
+    } else {
+        switch (pp) {
+        case 0x0:
+        case 0x6:
+            access = 0;
+            break;
+        case 0x1:
+        case 0x3:
+            access = PAGE_READ;
+            break;
+        case 0x2:
+            access = PAGE_READ | PAGE_WRITE;
+            break;
+        }
+    }
+    if (nx == 0) {
+        access |= PAGE_EXEC;
+    }
+
+    return access;
+}
+
+static inline int check_prot(int prot, int rw, int access_type)
+{
+    int ret;
+
+    if (access_type == ACCESS_CODE) {
+        if (prot & PAGE_EXEC) {
+            ret = 0;
+        } else {
+            ret = -2;
+        }
+    } else if (rw) {
+        if (prot & PAGE_WRITE) {
+            ret = 0;
+        } else {
+            ret = -2;
+        }
+    } else {
+        if (prot & PAGE_READ) {
+            ret = 0;
+        } else {
+            ret = -2;
+        }
+    }
+
+    return ret;
+}
+
+static inline int pte_check(mmu_ctx_t *ctx, int is_64b, target_ulong pte0,
+                            target_ulong pte1, int h, int rw, int type)
+{
+    target_ulong ptem, mmask;
+    int access, ret, pteh, ptev, pp;
+
+    ret = -1;
+    /* Check validity and table match */
+#if defined(TARGET_PPC64)
+    if (is_64b) {
+        ptev = pte64_is_valid(pte0);
+        pteh = (pte0 >> 1) & 1;
+    } else
+#endif
+    {
+        ptev = pte_is_valid(pte0);
+        pteh = (pte0 >> 6) & 1;
+    }
+    if (ptev && h == pteh) {
+        /* Check vsid & api */
+#if defined(TARGET_PPC64)
+        if (is_64b) {
+            ptem = pte0 & PTE64_PTEM_MASK;
+            mmask = PTE64_CHECK_MASK;
+            pp = (pte1 & 0x00000003) | ((pte1 >> 61) & 0x00000004);
+            ctx->nx  = (pte1 >> 2) & 1; /* No execute bit */
+            ctx->nx |= (pte1 >> 3) & 1; /* Guarded bit    */
+        } else
+#endif
+        {
+            ptem = pte0 & PTE_PTEM_MASK;
+            mmask = PTE_CHECK_MASK;
+            pp = pte1 & 0x00000003;
+        }
+        if (ptem == ctx->ptem) {
+            if (ctx->raddr != (target_phys_addr_t)-1ULL) {
+                /* all matches should have equal RPN, WIMG & PP */
+                if ((ctx->raddr & mmask) != (pte1 & mmask)) {
+                    qemu_log("Bad RPN/WIMG/PP\n");
+                    return -3;
+                }
+            }
+            /* Compute access rights */
+            access = pp_check(ctx->key, pp, ctx->nx);
+            /* Keep the matching PTE informations */
+            ctx->raddr = pte1;
+            ctx->prot = access;
+            ret = check_prot(ctx->prot, rw, type);
+            if (ret == 0) {
+                /* Access granted */
+                LOG_MMU("PTE access granted !\n");
+            } else {
+                /* Access right violation */
+                LOG_MMU("PTE access rejected\n");
+            }
+        }
+    }
+
+    return ret;
+}
+
+static inline int pte32_check(mmu_ctx_t *ctx, target_ulong pte0,
+                              target_ulong pte1, int h, int rw, int type)
+{
+    return pte_check(ctx, 0, pte0, pte1, h, rw, type);
+}
+
+#if defined(TARGET_PPC64)
+static inline int pte64_check(mmu_ctx_t *ctx, target_ulong pte0,
+                              target_ulong pte1, int h, int rw, int type)
+{
+    return pte_check(ctx, 1, pte0, pte1, h, rw, type);
+}
+#endif
+
+static inline int pte_update_flags(mmu_ctx_t *ctx, target_ulong *pte1p,
+                                   int ret, int rw)
+{
+    int store = 0;
+
+    /* Update page flags */
+    if (!(*pte1p & 0x00000100)) {
+        /* Update accessed flag */
+        *pte1p |= 0x00000100;
+        store = 1;
+    }
+    if (!(*pte1p & 0x00000080)) {
+        if (rw == 1 && ret == 0) {
+            /* Update changed flag */
+            *pte1p |= 0x00000080;
+            store = 1;
+        } else {
+            /* Force page fault for first write access */
+            ctx->prot &= ~PAGE_WRITE;
+        }
+    }
+
+    return store;
+}
+
+/* Software driven TLB helpers */
+static inline int ppc6xx_tlb_getnum(CPUPPCState *env, target_ulong eaddr,
+                                    int way, int is_code)
+{
+    int nr;
+
+    /* Select TLB num in a way from address */
+    nr = (eaddr >> TARGET_PAGE_BITS) & (env->tlb_per_way - 1);
+    /* Select TLB way */
+    nr += env->tlb_per_way * way;
+    /* 6xx have separate TLBs for instructions and data */
+    if (is_code && env->id_tlbs == 1) {
+        nr += env->nb_tlb;
+    }
+
+    return nr;
+}
+
+static inline void ppc6xx_tlb_invalidate_all(CPUPPCState *env)
+{
+    ppc6xx_tlb_t *tlb;
+    int nr, max;
+
+    /* LOG_SWTLB("Invalidate all TLBs\n"); */
+    /* Invalidate all defined software TLB */
+    max = env->nb_tlb;
+    if (env->id_tlbs == 1) {
+        max *= 2;
+    }
+    for (nr = 0; nr < max; nr++) {
+        tlb = &env->tlb.tlb6[nr];
+        pte_invalidate(&tlb->pte0);
+    }
+    tlb_flush(env, 1);
+}
+
+static inline void ppc6xx_tlb_invalidate_virt2(CPUPPCState *env,
+                                               target_ulong eaddr,
+                                               int is_code, int match_epn)
+{
+#if !defined(FLUSH_ALL_TLBS)
+    ppc6xx_tlb_t *tlb;
+    int way, nr;
+
+    /* Invalidate ITLB + DTLB, all ways */
+    for (way = 0; way < env->nb_ways; way++) {
+        nr = ppc6xx_tlb_getnum(env, eaddr, way, is_code);
+        tlb = &env->tlb.tlb6[nr];
+        if (pte_is_valid(tlb->pte0) && (match_epn == 0 || eaddr == tlb->EPN)) {
+            LOG_SWTLB("TLB invalidate %d/%d " TARGET_FMT_lx "\n", nr,
+                      env->nb_tlb, eaddr);
+            pte_invalidate(&tlb->pte0);
+            tlb_flush_page(env, tlb->EPN);
+        }
+    }
+#else
+    /* XXX: PowerPC specification say this is valid as well */
+    ppc6xx_tlb_invalidate_all(env);
+#endif
+}
+
+static inline void ppc6xx_tlb_invalidate_virt(CPUPPCState *env,
+                                              target_ulong eaddr, int is_code)
+{
+    ppc6xx_tlb_invalidate_virt2(env, eaddr, is_code, 0);
+}
+
+void ppc6xx_tlb_store(CPUPPCState *env, target_ulong EPN, int way, int is_code,
+                      target_ulong pte0, target_ulong pte1)
+{
+    ppc6xx_tlb_t *tlb;
+    int nr;
+
+    nr = ppc6xx_tlb_getnum(env, EPN, way, is_code);
+    tlb = &env->tlb.tlb6[nr];
+    LOG_SWTLB("Set TLB %d/%d EPN " TARGET_FMT_lx " PTE0 " TARGET_FMT_lx
+              " PTE1 " TARGET_FMT_lx "\n", nr, env->nb_tlb, EPN, pte0, pte1);
+    /* Invalidate any pending reference in QEMU for this virtual address */
+    ppc6xx_tlb_invalidate_virt2(env, EPN, is_code, 1);
+    tlb->pte0 = pte0;
+    tlb->pte1 = pte1;
+    tlb->EPN = EPN;
+    /* Store last way for LRU mechanism */
+    env->last_way = way;
+}
+
+static inline int ppc6xx_tlb_check(CPUPPCState *env, mmu_ctx_t *ctx,
+                                   target_ulong eaddr, int rw, int access_type)
+{
+    ppc6xx_tlb_t *tlb;
+    int nr, best, way;
+    int ret;
+
+    best = -1;
+    ret = -1; /* No TLB found */
+    for (way = 0; way < env->nb_ways; way++) {
+        nr = ppc6xx_tlb_getnum(env, eaddr, way,
+                               access_type == ACCESS_CODE ? 1 : 0);
+        tlb = &env->tlb.tlb6[nr];
+        /* This test "emulates" the PTE index match for hardware TLBs */
+        if ((eaddr & TARGET_PAGE_MASK) != tlb->EPN) {
+            LOG_SWTLB("TLB %d/%d %s [" TARGET_FMT_lx " " TARGET_FMT_lx
+                      "] <> " TARGET_FMT_lx "\n", nr, env->nb_tlb,
+                      pte_is_valid(tlb->pte0) ? "valid" : "inval",
+                      tlb->EPN, tlb->EPN + TARGET_PAGE_SIZE, eaddr);
+            continue;
+        }
+        LOG_SWTLB("TLB %d/%d %s " TARGET_FMT_lx " <> " TARGET_FMT_lx " "
+                  TARGET_FMT_lx " %c %c\n", nr, env->nb_tlb,
+                  pte_is_valid(tlb->pte0) ? "valid" : "inval",
+                  tlb->EPN, eaddr, tlb->pte1,
+                  rw ? 'S' : 'L', access_type == ACCESS_CODE ? 'I' : 'D');
+        switch (pte32_check(ctx, tlb->pte0, tlb->pte1, 0, rw, access_type)) {
+        case -3:
+            /* TLB inconsistency */
+            return -1;
+        case -2:
+            /* Access violation */
+            ret = -2;
+            best = nr;
+            break;
+        case -1:
+        default:
+            /* No match */
+            break;
+        case 0:
+            /* access granted */
+            /* XXX: we should go on looping to check all TLBs consistency
+             *      but we can speed-up the whole thing as the
+             *      result would be undefined if TLBs are not consistent.
+             */
+            ret = 0;
+            best = nr;
+            goto done;
+        }
+    }
+    if (best != -1) {
+    done:
+        LOG_SWTLB("found TLB at addr " TARGET_FMT_plx " prot=%01x ret=%d\n",
+                  ctx->raddr & TARGET_PAGE_MASK, ctx->prot, ret);
+        /* Update page flags */
+        pte_update_flags(ctx, &env->tlb.tlb6[best].pte1, ret, rw);
+    }
+
+    return ret;
+}
+
+/* Perform BAT hit & translation */
+static inline void bat_size_prot(CPUPPCState *env, target_ulong *blp,
+                                 int *validp, int *protp, target_ulong *BATu,
+                                 target_ulong *BATl)
+{
+    target_ulong bl;
+    int pp, valid, prot;
+
+    bl = (*BATu & 0x00001FFC) << 15;
+    valid = 0;
+    prot = 0;
+    if (((msr_pr == 0) && (*BATu & 0x00000002)) ||
+        ((msr_pr != 0) && (*BATu & 0x00000001))) {
+        valid = 1;
+        pp = *BATl & 0x00000003;
+        if (pp != 0) {
+            prot = PAGE_READ | PAGE_EXEC;
+            if (pp == 0x2) {
+                prot |= PAGE_WRITE;
+            }
+        }
+    }
+    *blp = bl;
+    *validp = valid;
+    *protp = prot;
+}
+
+static inline void bat_601_size_prot(CPUPPCState *env, target_ulong *blp,
+                                     int *validp, int *protp,
+                                     target_ulong *BATu, target_ulong *BATl)
+{
+    target_ulong bl;
+    int key, pp, valid, prot;
+
+    bl = (*BATl & 0x0000003F) << 17;
+    LOG_BATS("b %02x ==> bl " TARGET_FMT_lx " msk " TARGET_FMT_lx "\n",
+             (uint8_t)(*BATl & 0x0000003F), bl, ~bl);
+    prot = 0;
+    valid = (*BATl >> 6) & 1;
+    if (valid) {
+        pp = *BATu & 0x00000003;
+        if (msr_pr == 0) {
+            key = (*BATu >> 3) & 1;
+        } else {
+            key = (*BATu >> 2) & 1;
+        }
+        prot = pp_check(key, pp, 0);
+    }
+    *blp = bl;
+    *validp = valid;
+    *protp = prot;
+}
+
+static inline int get_bat(CPUPPCState *env, mmu_ctx_t *ctx,
+                          target_ulong virtual, int rw, int type)
+{
+    target_ulong *BATlt, *BATut, *BATu, *BATl;
+    target_ulong BEPIl, BEPIu, bl;
+    int i, valid, prot;
+    int ret = -1;
+
+    LOG_BATS("%s: %cBAT v " TARGET_FMT_lx "\n", __func__,
+             type == ACCESS_CODE ? 'I' : 'D', virtual);
+    switch (type) {
+    case ACCESS_CODE:
+        BATlt = env->IBAT[1];
+        BATut = env->IBAT[0];
+        break;
+    default:
+        BATlt = env->DBAT[1];
+        BATut = env->DBAT[0];
+        break;
+    }
+    for (i = 0; i < env->nb_BATs; i++) {
+        BATu = &BATut[i];
+        BATl = &BATlt[i];
+        BEPIu = *BATu & 0xF0000000;
+        BEPIl = *BATu & 0x0FFE0000;
+        if (unlikely(env->mmu_model == POWERPC_MMU_601)) {
+            bat_601_size_prot(env, &bl, &valid, &prot, BATu, BATl);
+        } else {
+            bat_size_prot(env, &bl, &valid, &prot, BATu, BATl);
+        }
+        LOG_BATS("%s: %cBAT%d v " TARGET_FMT_lx " BATu " TARGET_FMT_lx
+                 " BATl " TARGET_FMT_lx "\n", __func__,
+                 type == ACCESS_CODE ? 'I' : 'D', i, virtual, *BATu, *BATl);
+        if ((virtual & 0xF0000000) == BEPIu &&
+            ((virtual & 0x0FFE0000) & ~bl) == BEPIl) {
+            /* BAT matches */
+            if (valid != 0) {
+                /* Get physical address */
+                ctx->raddr = (*BATl & 0xF0000000) |
+                    ((virtual & 0x0FFE0000 & bl) | (*BATl & 0x0FFE0000)) |
+                    (virtual & 0x0001F000);
+                /* Compute access rights */
+                ctx->prot = prot;
+                ret = check_prot(ctx->prot, rw, type);
+                if (ret == 0) {
+                    LOG_BATS("BAT %d match: r " TARGET_FMT_plx " prot=%c%c\n",
+                             i, ctx->raddr, ctx->prot & PAGE_READ ? 'R' : '-',
+                             ctx->prot & PAGE_WRITE ? 'W' : '-');
+                }
+                break;
+            }
+        }
+    }
+    if (ret < 0) {
+#if defined(DEBUG_BATS)
+        if (qemu_log_enabled()) {
+            LOG_BATS("no BAT match for " TARGET_FMT_lx ":\n", virtual);
+            for (i = 0; i < 4; i++) {
+                BATu = &BATut[i];
+                BATl = &BATlt[i];
+                BEPIu = *BATu & 0xF0000000;
+                BEPIl = *BATu & 0x0FFE0000;
+                bl = (*BATu & 0x00001FFC) << 15;
+                LOG_BATS("%s: %cBAT%d v " TARGET_FMT_lx " BATu " TARGET_FMT_lx
+                         " BATl " TARGET_FMT_lx "\n\t" TARGET_FMT_lx " "
+                         TARGET_FMT_lx " " TARGET_FMT_lx "\n",
+                         __func__, type == ACCESS_CODE ? 'I' : 'D', i, virtual,
+                         *BATu, *BATl, BEPIu, BEPIl, bl);
+            }
+        }
+#endif
+    }
+    /* No hit */
+    return ret;
+}
+
+static inline target_phys_addr_t get_pteg_offset(CPUPPCState *env,
+                                                 target_phys_addr_t hash,
+                                                 int pte_size)
+{
+    return (hash * pte_size * 8) & env->htab_mask;
+}
+
+/* PTE table lookup */
+static inline int find_pte2(CPUPPCState *env, mmu_ctx_t *ctx, int is_64b, int h,
+                            int rw, int type, int target_page_bits)
+{
+    target_phys_addr_t pteg_off;
+    target_ulong pte0, pte1;
+    int i, good = -1;
+    int ret, r;
+
+    ret = -1; /* No entry found */
+    pteg_off = get_pteg_offset(env, ctx->hash[h],
+                               is_64b ? HASH_PTE_SIZE_64 : HASH_PTE_SIZE_32);
+    for (i = 0; i < 8; i++) {
+#if defined(TARGET_PPC64)
+        if (is_64b) {
+            if (env->external_htab) {
+                pte0 = ldq_p(env->external_htab + pteg_off + (i * 16));
+                pte1 = ldq_p(env->external_htab + pteg_off + (i * 16) + 8);
+            } else {
+                pte0 = ldq_phys(env->htab_base + pteg_off + (i * 16));
+                pte1 = ldq_phys(env->htab_base + pteg_off + (i * 16) + 8);
+            }
+
+            r = pte64_check(ctx, pte0, pte1, h, rw, type);
+            LOG_MMU("Load pte from " TARGET_FMT_lx " => " TARGET_FMT_lx " "
+                    TARGET_FMT_lx " %d %d %d " TARGET_FMT_lx "\n",
+                    pteg_off + (i * 16), pte0, pte1, (int)(pte0 & 1), h,
+                    (int)((pte0 >> 1) & 1), ctx->ptem);
+        } else
+#endif
+        {
+            if (env->external_htab) {
+                pte0 = ldl_p(env->external_htab + pteg_off + (i * 8));
+                pte1 = ldl_p(env->external_htab + pteg_off + (i * 8) + 4);
+            } else {
+                pte0 = ldl_phys(env->htab_base + pteg_off + (i * 8));
+                pte1 = ldl_phys(env->htab_base + pteg_off + (i * 8) + 4);
+            }
+            r = pte32_check(ctx, pte0, pte1, h, rw, type);
+            LOG_MMU("Load pte from " TARGET_FMT_lx " => " TARGET_FMT_lx " "
+                    TARGET_FMT_lx " %d %d %d " TARGET_FMT_lx "\n",
+                    pteg_off + (i * 8), pte0, pte1, (int)(pte0 >> 31), h,
+                    (int)((pte0 >> 6) & 1), ctx->ptem);
+        }
+        switch (r) {
+        case -3:
+            /* PTE inconsistency */
+            return -1;
+        case -2:
+            /* Access violation */
+            ret = -2;
+            good = i;
+            break;
+        case -1:
+        default:
+            /* No PTE match */
+            break;
+        case 0:
+            /* access granted */
+            /* XXX: we should go on looping to check all PTEs consistency
+             *      but if we can speed-up the whole thing as the
+             *      result would be undefined if PTEs are not consistent.
+             */
+            ret = 0;
+            good = i;
+            goto done;
+        }
+    }
+    if (good != -1) {
+    done:
+        LOG_MMU("found PTE at addr " TARGET_FMT_lx " prot=%01x ret=%d\n",
+                ctx->raddr, ctx->prot, ret);
+        /* Update page flags */
+        pte1 = ctx->raddr;
+        if (pte_update_flags(ctx, &pte1, ret, rw) == 1) {
+#if defined(TARGET_PPC64)
+            if (is_64b) {
+                if (env->external_htab) {
+                    stq_p(env->external_htab + pteg_off + (good * 16) + 8,
+                          pte1);
+                } else {
+                    stq_phys_notdirty(env->htab_base + pteg_off +
+                                      (good * 16) + 8, pte1);
+                }
+            } else
+#endif
+            {
+                if (env->external_htab) {
+                    stl_p(env->external_htab + pteg_off + (good * 8) + 4,
+                          pte1);
+                } else {
+                    stl_phys_notdirty(env->htab_base + pteg_off +
+                                      (good * 8) + 4, pte1);
+                }
+            }
+        }
+    }
+
+    /* We have a TLB that saves 4K pages, so let's
+     * split a huge page to 4k chunks */
+    if (target_page_bits != TARGET_PAGE_BITS) {
+        ctx->raddr |= (ctx->eaddr & ((1 << target_page_bits) - 1))
+                      & TARGET_PAGE_MASK;
+    }
+    return ret;
+}
+
+static inline int find_pte(CPUPPCState *env, mmu_ctx_t *ctx, int h, int rw,
+                           int type, int target_page_bits)
+{
+#if defined(TARGET_PPC64)
+    if (env->mmu_model & POWERPC_MMU_64) {
+        return find_pte2(env, ctx, 1, h, rw, type, target_page_bits);
+    }
+#endif
+
+    return find_pte2(env, ctx, 0, h, rw, type, target_page_bits);
+}
+
+#if defined(TARGET_PPC64)
+static inline ppc_slb_t *slb_lookup(CPUPPCState *env, target_ulong eaddr)
+{
+    uint64_t esid_256M, esid_1T;
+    int n;
+
+    LOG_SLB("%s: eaddr " TARGET_FMT_lx "\n", __func__, eaddr);
+
+    esid_256M = (eaddr & SEGMENT_MASK_256M) | SLB_ESID_V;
+    esid_1T = (eaddr & SEGMENT_MASK_1T) | SLB_ESID_V;
+
+    for (n = 0; n < env->slb_nr; n++) {
+        ppc_slb_t *slb = &env->slb[n];
+
+        LOG_SLB("%s: slot %d %016" PRIx64 " %016"
+                    PRIx64 "\n", __func__, n, slb->esid, slb->vsid);
+        /* We check for 1T matches on all MMUs here - if the MMU
+         * doesn't have 1T segment support, we will have prevented 1T
+         * entries from being inserted in the slbmte code. */
+        if (((slb->esid == esid_256M) &&
+             ((slb->vsid & SLB_VSID_B) == SLB_VSID_B_256M))
+            || ((slb->esid == esid_1T) &&
+                ((slb->vsid & SLB_VSID_B) == SLB_VSID_B_1T))) {
+            return slb;
+        }
+    }
+
+    return NULL;
+}
+
+void ppc_slb_invalidate_all(CPUPPCState *env)
+{
+    int n, do_invalidate;
+
+    do_invalidate = 0;
+    /* XXX: Warning: slbia never invalidates the first segment */
+    for (n = 1; n < env->slb_nr; n++) {
+        ppc_slb_t *slb = &env->slb[n];
+
+        if (slb->esid & SLB_ESID_V) {
+            slb->esid &= ~SLB_ESID_V;
+            /* XXX: given the fact that segment size is 256 MB or 1TB,
+             *      and we still don't have a tlb_flush_mask(env, n, mask)
+             *      in QEMU, we just invalidate all TLBs
+             */
+            do_invalidate = 1;
+        }
+    }
+    if (do_invalidate) {
+        tlb_flush(env, 1);
+    }
+}
+
+void ppc_slb_invalidate_one(CPUPPCState *env, uint64_t T0)
+{
+    ppc_slb_t *slb;
+
+    slb = slb_lookup(env, T0);
+    if (!slb) {
+        return;
+    }
+
+    if (slb->esid & SLB_ESID_V) {
+        slb->esid &= ~SLB_ESID_V;
+
+        /* XXX: given the fact that segment size is 256 MB or 1TB,
+         *      and we still don't have a tlb_flush_mask(env, n, mask)
+         *      in QEMU, we just invalidate all TLBs
+         */
+        tlb_flush(env, 1);
+    }
+}
+
+int ppc_store_slb(CPUPPCState *env, target_ulong rb, target_ulong rs)
+{
+    int slot = rb & 0xfff;
+    ppc_slb_t *slb = &env->slb[slot];
+
+    if (rb & (0x1000 - env->slb_nr)) {
+        return -1; /* Reserved bits set or slot too high */
+    }
+    if (rs & (SLB_VSID_B & ~SLB_VSID_B_1T)) {
+        return -1; /* Bad segment size */
+    }
+    if ((rs & SLB_VSID_B) && !(env->mmu_model & POWERPC_MMU_1TSEG)) {
+        return -1; /* 1T segment on MMU that doesn't support it */
+    }
+
+    /* Mask out the slot number as we store the entry */
+    slb->esid = rb & (SLB_ESID_ESID | SLB_ESID_V);
+    slb->vsid = rs;
+
+    LOG_SLB("%s: %d " TARGET_FMT_lx " - " TARGET_FMT_lx " => %016" PRIx64
+            " %016" PRIx64 "\n", __func__, slot, rb, rs,
+            slb->esid, slb->vsid);
+
+    return 0;
+}
+
+int ppc_load_slb_esid(CPUPPCState *env, target_ulong rb, target_ulong *rt)
+{
+    int slot = rb & 0xfff;
+    ppc_slb_t *slb = &env->slb[slot];
+
+    if (slot >= env->slb_nr) {
+        return -1;
+    }
+
+    *rt = slb->esid;
+    return 0;
+}
+
+int ppc_load_slb_vsid(CPUPPCState *env, target_ulong rb, target_ulong *rt)
+{
+    int slot = rb & 0xfff;
+    ppc_slb_t *slb = &env->slb[slot];
+
+    if (slot >= env->slb_nr) {
+        return -1;
+    }
+
+    *rt = slb->vsid;
+    return 0;
+}
+#endif /* defined(TARGET_PPC64) */
+
+/* Perform segment based translation */
+static inline int get_segment(CPUPPCState *env, mmu_ctx_t *ctx,
+                              target_ulong eaddr, int rw, int type)
+{
+    target_phys_addr_t hash;
+    target_ulong vsid;
+    int ds, pr, target_page_bits;
+    int ret, ret2;
+
+    pr = msr_pr;
+    ctx->eaddr = eaddr;
+#if defined(TARGET_PPC64)
+    if (env->mmu_model & POWERPC_MMU_64) {
+        ppc_slb_t *slb;
+        target_ulong pageaddr;
+        int segment_bits;
+
+        LOG_MMU("Check SLBs\n");
+        slb = slb_lookup(env, eaddr);
+        if (!slb) {
+            return -5;
+        }
+
+        if (slb->vsid & SLB_VSID_B) {
+            vsid = (slb->vsid & SLB_VSID_VSID) >> SLB_VSID_SHIFT_1T;
+            segment_bits = 40;
+        } else {
+            vsid = (slb->vsid & SLB_VSID_VSID) >> SLB_VSID_SHIFT;
+            segment_bits = 28;
+        }
+
+        target_page_bits = (slb->vsid & SLB_VSID_L)
+            ? TARGET_PAGE_BITS_16M : TARGET_PAGE_BITS;
+        ctx->key = !!(pr ? (slb->vsid & SLB_VSID_KP)
+                      : (slb->vsid & SLB_VSID_KS));
+        ds = 0;
+        ctx->nx = !!(slb->vsid & SLB_VSID_N);
+
+        pageaddr = eaddr & ((1ULL << segment_bits)
+                            - (1ULL << target_page_bits));
+        if (slb->vsid & SLB_VSID_B) {
+            hash = vsid ^ (vsid << 25) ^ (pageaddr >> target_page_bits);
+        } else {
+            hash = vsid ^ (pageaddr >> target_page_bits);
+        }
+        /* Only 5 bits of the page index are used in the AVPN */
+        ctx->ptem = (slb->vsid & SLB_VSID_PTEM) |
+            ((pageaddr >> 16) & ((1ULL << segment_bits) - 0x80));
+    } else
+#endif /* defined(TARGET_PPC64) */
+    {
+        target_ulong sr, pgidx;
+
+        sr = env->sr[eaddr >> 28];
+        ctx->key = (((sr & 0x20000000) && (pr != 0)) ||
+                    ((sr & 0x40000000) && (pr == 0))) ? 1 : 0;
+        ds = sr & 0x80000000 ? 1 : 0;
+        ctx->nx = sr & 0x10000000 ? 1 : 0;
+        vsid = sr & 0x00FFFFFF;
+        target_page_bits = TARGET_PAGE_BITS;
+        LOG_MMU("Check segment v=" TARGET_FMT_lx " %d " TARGET_FMT_lx " nip="
+                TARGET_FMT_lx " lr=" TARGET_FMT_lx
+                " ir=%d dr=%d pr=%d %d t=%d\n",
+                eaddr, (int)(eaddr >> 28), sr, env->nip, env->lr, (int)msr_ir,
+                (int)msr_dr, pr != 0 ? 1 : 0, rw, type);
+        pgidx = (eaddr & ~SEGMENT_MASK_256M) >> target_page_bits;
+        hash = vsid ^ pgidx;
+        ctx->ptem = (vsid << 7) | (pgidx >> 10);
+    }
+    LOG_MMU("pte segment: key=%d ds %d nx %d vsid " TARGET_FMT_lx "\n",
+            ctx->key, ds, ctx->nx, vsid);
+    ret = -1;
+    if (!ds) {
+        /* Check if instruction fetch is allowed, if needed */
+        if (type != ACCESS_CODE || ctx->nx == 0) {
+            /* Page address translation */
+            LOG_MMU("htab_base " TARGET_FMT_plx " htab_mask " TARGET_FMT_plx
+                    " hash " TARGET_FMT_plx "\n",
+                    env->htab_base, env->htab_mask, hash);
+            ctx->hash[0] = hash;
+            ctx->hash[1] = ~hash;
+
+            /* Initialize real address with an invalid value */
+            ctx->raddr = (target_phys_addr_t)-1ULL;
+            if (unlikely(env->mmu_model == POWERPC_MMU_SOFT_6xx ||
+                         env->mmu_model == POWERPC_MMU_SOFT_74xx)) {
+                /* Software TLB search */
+                ret = ppc6xx_tlb_check(env, ctx, eaddr, rw, type);
+            } else {
+                LOG_MMU("0 htab=" TARGET_FMT_plx "/" TARGET_FMT_plx
+                        " vsid=" TARGET_FMT_lx " ptem=" TARGET_FMT_lx
+                        " hash=" TARGET_FMT_plx "\n",
+                        env->htab_base, env->htab_mask, vsid, ctx->ptem,
+                        ctx->hash[0]);
+                /* Primary table lookup */
+                ret = find_pte(env, ctx, 0, rw, type, target_page_bits);
+                if (ret < 0) {
+                    /* Secondary table lookup */
+                    if (eaddr != 0xEFFFFFFF) {
+                        LOG_MMU("1 htab=" TARGET_FMT_plx "/" TARGET_FMT_plx
+                                " vsid=" TARGET_FMT_lx " api=" TARGET_FMT_lx
+                                " hash=" TARGET_FMT_plx "\n", env->htab_base,
+                                env->htab_mask, vsid, ctx->ptem, ctx->hash[1]);
+                    }
+                    ret2 = find_pte(env, ctx, 1, rw, type,
+                                    target_page_bits);
+                    if (ret2 != -1) {
+                        ret = ret2;
+                    }
+                }
+            }
+#if defined(DUMP_PAGE_TABLES)
+            if (qemu_log_enabled()) {
+                target_phys_addr_t curaddr;
+                uint32_t a0, a1, a2, a3;
+
+                qemu_log("Page table: " TARGET_FMT_plx " len " TARGET_FMT_plx
+                         "\n", sdr, mask + 0x80);
+                for (curaddr = sdr; curaddr < (sdr + mask + 0x80);
+                     curaddr += 16) {
+                    a0 = ldl_phys(curaddr);
+                    a1 = ldl_phys(curaddr + 4);
+                    a2 = ldl_phys(curaddr + 8);
+                    a3 = ldl_phys(curaddr + 12);
+                    if (a0 != 0 || a1 != 0 || a2 != 0 || a3 != 0) {
+                        qemu_log(TARGET_FMT_plx ": %08x %08x %08x %08x\n",
+                                 curaddr, a0, a1, a2, a3);
+                    }
+                }
+            }
+#endif
+        } else {
+            LOG_MMU("No access allowed\n");
+            ret = -3;
+        }
+    } else {
+        target_ulong sr;
+
+        LOG_MMU("direct store...\n");
+        /* Direct-store segment : absolutely *BUGGY* for now */
+
+        /* Direct-store implies a 32-bit MMU.
+         * Check the Segment Register's bus unit ID (BUID).
+         */
+        sr = env->sr[eaddr >> 28];
+        if ((sr & 0x1FF00000) >> 20 == 0x07f) {
+            /* Memory-forced I/O controller interface access */
+            /* If T=1 and BUID=x'07F', the 601 performs a memory access
+             * to SR[28-31] LA[4-31], bypassing all protection mechanisms.
+             */
+            ctx->raddr = ((sr & 0xF) << 28) | (eaddr & 0x0FFFFFFF);
+            ctx->prot = PAGE_READ | PAGE_WRITE | PAGE_EXEC;
+            return 0;
+        }
+
+        switch (type) {
+        case ACCESS_INT:
+            /* Integer load/store : only access allowed */
+            break;
+        case ACCESS_CODE:
+            /* No code fetch is allowed in direct-store areas */
+            return -4;
+        case ACCESS_FLOAT:
+            /* Floating point load/store */
+            return -4;
+        case ACCESS_RES:
+            /* lwarx, ldarx or srwcx. */
+            return -4;
+        case ACCESS_CACHE:
+            /* dcba, dcbt, dcbtst, dcbf, dcbi, dcbst, dcbz, or icbi */
+            /* Should make the instruction do no-op.
+             * As it already do no-op, it's quite easy :-)
+             */
+            ctx->raddr = eaddr;
+            return 0;
+        case ACCESS_EXT:
+            /* eciwx or ecowx */
+            return -4;
+        default:
+            qemu_log("ERROR: instruction should not need "
+                        "address translation\n");
+            return -4;
+        }
+        if ((rw == 1 || ctx->key != 1) && (rw == 0 || ctx->key != 0)) {
+            ctx->raddr = eaddr;
+            ret = 2;
+        } else {
+            ret = -2;
+        }
+    }
+
+    return ret;
+}
+
+/* Generic TLB check function for embedded PowerPC implementations */
+int ppcemb_tlb_check(CPUPPCState *env, ppcemb_tlb_t *tlb,
+                     target_phys_addr_t *raddrp,
+                     target_ulong address, uint32_t pid, int ext,
+                     int i)
+{
+    target_ulong mask;
+
+    /* Check valid flag */
+    if (!(tlb->prot & PAGE_VALID)) {
+        return -1;
+    }
+    mask = ~(tlb->size - 1);
+    LOG_SWTLB("%s: TLB %d address " TARGET_FMT_lx " PID %u <=> " TARGET_FMT_lx
+              " " TARGET_FMT_lx " %u %x\n", __func__, i, address, pid, tlb->EPN,
+              mask, (uint32_t)tlb->PID, tlb->prot);
+    /* Check PID */
+    if (tlb->PID != 0 && tlb->PID != pid) {
+        return -1;
+    }
+    /* Check effective address */
+    if ((address & mask) != tlb->EPN) {
+        return -1;
+    }
+    *raddrp = (tlb->RPN & mask) | (address & ~mask);
+#if (TARGET_PHYS_ADDR_BITS >= 36)
+    if (ext) {
+        /* Extend the physical address to 36 bits */
+        *raddrp |= (target_phys_addr_t)(tlb->RPN & 0xF) << 32;
+    }
+#endif
+
+    return 0;
+}
+
+/* Generic TLB search function for PowerPC embedded implementations */
+int ppcemb_tlb_search(CPUPPCState *env, target_ulong address, uint32_t pid)
+{
+    ppcemb_tlb_t *tlb;
+    target_phys_addr_t raddr;
+    int i, ret;
+
+    /* Default return value is no match */
+    ret = -1;
+    for (i = 0; i < env->nb_tlb; i++) {
+        tlb = &env->tlb.tlbe[i];
+        if (ppcemb_tlb_check(env, tlb, &raddr, address, pid, 0, i) == 0) {
+            ret = i;
+            break;
+        }
+    }
+
+    return ret;
+}
+
+/* Helpers specific to PowerPC 40x implementations */
+static inline void ppc4xx_tlb_invalidate_all(CPUPPCState *env)
+{
+    ppcemb_tlb_t *tlb;
+    int i;
+
+    for (i = 0; i < env->nb_tlb; i++) {
+        tlb = &env->tlb.tlbe[i];
+        tlb->prot &= ~PAGE_VALID;
+    }
+    tlb_flush(env, 1);
+}
+
+static inline void ppc4xx_tlb_invalidate_virt(CPUPPCState *env,
+                                              target_ulong eaddr, uint32_t pid)
+{
+#if !defined(FLUSH_ALL_TLBS)
+    ppcemb_tlb_t *tlb;
+    target_phys_addr_t raddr;
+    target_ulong page, end;
+    int i;
+
+    for (i = 0; i < env->nb_tlb; i++) {
+        tlb = &env->tlb.tlbe[i];
+        if (ppcemb_tlb_check(env, tlb, &raddr, eaddr, pid, 0, i) == 0) {
+            end = tlb->EPN + tlb->size;
+            for (page = tlb->EPN; page < end; page += TARGET_PAGE_SIZE) {
+                tlb_flush_page(env, page);
+            }
+            tlb->prot &= ~PAGE_VALID;
+            break;
+        }
+    }
+#else
+    ppc4xx_tlb_invalidate_all(env);
+#endif
+}
+
+static int mmu40x_get_physical_address(CPUPPCState *env, mmu_ctx_t *ctx,
+                                       target_ulong address, int rw,
+                                       int access_type)
+{
+    ppcemb_tlb_t *tlb;
+    target_phys_addr_t raddr;
+    int i, ret, zsel, zpr, pr;
+
+    ret = -1;
+    raddr = (target_phys_addr_t)-1ULL;
+    pr = msr_pr;
+    for (i = 0; i < env->nb_tlb; i++) {
+        tlb = &env->tlb.tlbe[i];
+        if (ppcemb_tlb_check(env, tlb, &raddr, address,
+                             env->spr[SPR_40x_PID], 0, i) < 0) {
+            continue;
+        }
+        zsel = (tlb->attr >> 4) & 0xF;
+        zpr = (env->spr[SPR_40x_ZPR] >> (30 - (2 * zsel))) & 0x3;
+        LOG_SWTLB("%s: TLB %d zsel %d zpr %d rw %d attr %08x\n",
+                    __func__, i, zsel, zpr, rw, tlb->attr);
+        /* Check execute enable bit */
+        switch (zpr) {
+        case 0x2:
+            if (pr != 0) {
+                goto check_perms;
+            }
+            /* No break here */
+        case 0x3:
+            /* All accesses granted */
+            ctx->prot = PAGE_READ | PAGE_WRITE | PAGE_EXEC;
+            ret = 0;
+            break;
+        case 0x0:
+            if (pr != 0) {
+                /* Raise Zone protection fault.  */
+                env->spr[SPR_40x_ESR] = 1 << 22;
+                ctx->prot = 0;
+                ret = -2;
+                break;
+            }
+            /* No break here */
+        case 0x1:
+        check_perms:
+            /* Check from TLB entry */
+            ctx->prot = tlb->prot;
+            ret = check_prot(ctx->prot, rw, access_type);
+            if (ret == -2) {
+                env->spr[SPR_40x_ESR] = 0;
+            }
+            break;
+        }
+        if (ret >= 0) {
+            ctx->raddr = raddr;
+            LOG_SWTLB("%s: access granted " TARGET_FMT_lx " => " TARGET_FMT_plx
+                      " %d %d\n", __func__, address, ctx->raddr, ctx->prot,
+                      ret);
+            return 0;
+        }
+    }
+    LOG_SWTLB("%s: access refused " TARGET_FMT_lx " => " TARGET_FMT_plx
+              " %d %d\n", __func__, address, raddr, ctx->prot, ret);
+
+    return ret;
+}
+
+void store_40x_sler(CPUPPCState *env, uint32_t val)
+{
+    /* XXX: TO BE FIXED */
+    if (val != 0x00000000) {
+        cpu_abort(env, "Little-endian regions are not supported by now\n");
+    }
+    env->spr[SPR_405_SLER] = val;
+}
+
+static inline int mmubooke_check_tlb(CPUPPCState *env, ppcemb_tlb_t *tlb,
+                                     target_phys_addr_t *raddr, int *prot,
+                                     target_ulong address, int rw,
+                                     int access_type, int i)
+{
+    int ret, prot2;
+
+    if (ppcemb_tlb_check(env, tlb, raddr, address,
+                         env->spr[SPR_BOOKE_PID],
+                         !env->nb_pids, i) >= 0) {
+        goto found_tlb;
+    }
+
+    if (env->spr[SPR_BOOKE_PID1] &&
+        ppcemb_tlb_check(env, tlb, raddr, address,
+                         env->spr[SPR_BOOKE_PID1], 0, i) >= 0) {
+        goto found_tlb;
+    }
+
+    if (env->spr[SPR_BOOKE_PID2] &&
+        ppcemb_tlb_check(env, tlb, raddr, address,
+                         env->spr[SPR_BOOKE_PID2], 0, i) >= 0) {
+        goto found_tlb;
+    }
+
+    LOG_SWTLB("%s: TLB entry not found\n", __func__);
+    return -1;
+
+found_tlb:
+
+    if (msr_pr != 0) {
+        prot2 = tlb->prot & 0xF;
+    } else {
+        prot2 = (tlb->prot >> 4) & 0xF;
+    }
+
+    /* Check the address space */
+    if (access_type == ACCESS_CODE) {
+        if (msr_ir != (tlb->attr & 1)) {
+            LOG_SWTLB("%s: AS doesn't match\n", __func__);
+            return -1;
+        }
+
+        *prot = prot2;
+        if (prot2 & PAGE_EXEC) {
+            LOG_SWTLB("%s: good TLB!\n", __func__);
+            return 0;
+        }
+
+        LOG_SWTLB("%s: no PAGE_EXEC: %x\n", __func__, prot2);
+        ret = -3;
+    } else {
+        if (msr_dr != (tlb->attr & 1)) {
+            LOG_SWTLB("%s: AS doesn't match\n", __func__);
+            return -1;
+        }
+
+        *prot = prot2;
+        if ((!rw && prot2 & PAGE_READ) || (rw && (prot2 & PAGE_WRITE))) {
+            LOG_SWTLB("%s: found TLB!\n", __func__);
+            return 0;
+        }
+
+        LOG_SWTLB("%s: PAGE_READ/WRITE doesn't match: %x\n", __func__, prot2);
+        ret = -2;
+    }
+
+    return ret;
+}
+
+static int mmubooke_get_physical_address(CPUPPCState *env, mmu_ctx_t *ctx,
+                                         target_ulong address, int rw,
+                                         int access_type)
+{
+    ppcemb_tlb_t *tlb;
+    target_phys_addr_t raddr;
+    int i, ret;
+
+    ret = -1;
+    raddr = (target_phys_addr_t)-1ULL;
+    for (i = 0; i < env->nb_tlb; i++) {
+        tlb = &env->tlb.tlbe[i];
+        ret = mmubooke_check_tlb(env, tlb, &raddr, &ctx->prot, address, rw,
+                                 access_type, i);
+        if (!ret) {
+            break;
+        }
+    }
+
+    if (ret >= 0) {
+        ctx->raddr = raddr;
+        LOG_SWTLB("%s: access granted " TARGET_FMT_lx " => " TARGET_FMT_plx
+                  " %d %d\n", __func__, address, ctx->raddr, ctx->prot,
+                  ret);
+    } else {
+        LOG_SWTLB("%s: access refused " TARGET_FMT_lx " => " TARGET_FMT_plx
+                  " %d %d\n", __func__, address, raddr, ctx->prot, ret);
+    }
+
+    return ret;
+}
+
+void booke206_flush_tlb(CPUPPCState *env, int flags, const int check_iprot)
+{
+    int tlb_size;
+    int i, j;
+    ppcmas_tlb_t *tlb = env->tlb.tlbm;
+
+    for (i = 0; i < BOOKE206_MAX_TLBN; i++) {
+        if (flags & (1 << i)) {
+            tlb_size = booke206_tlb_size(env, i);
+            for (j = 0; j < tlb_size; j++) {
+                if (!check_iprot || !(tlb[j].mas1 & MAS1_IPROT)) {
+                    tlb[j].mas1 &= ~MAS1_VALID;
+                }
+            }
+        }
+        tlb += booke206_tlb_size(env, i);
+    }
+
+    tlb_flush(env, 1);
+}
+
+target_phys_addr_t booke206_tlb_to_page_size(CPUPPCState *env,
+                                             ppcmas_tlb_t *tlb)
+{
+    int tlbm_size;
+
+    tlbm_size = (tlb->mas1 & MAS1_TSIZE_MASK) >> MAS1_TSIZE_SHIFT;
+
+    return 1024ULL << tlbm_size;
+}
+
+/* TLB check function for MAS based SoftTLBs */
+int ppcmas_tlb_check(CPUPPCState *env, ppcmas_tlb_t *tlb,
+                     target_phys_addr_t *raddrp,
+                     target_ulong address, uint32_t pid)
+{
+    target_ulong mask;
+    uint32_t tlb_pid;
+
+    /* Check valid flag */
+    if (!(tlb->mas1 & MAS1_VALID)) {
+        return -1;
+    }
+
+    mask = ~(booke206_tlb_to_page_size(env, tlb) - 1);
+    LOG_SWTLB("%s: TLB ADDR=0x" TARGET_FMT_lx " PID=0x%x MAS1=0x%x MAS2=0x%"
+              PRIx64 " mask=0x" TARGET_FMT_lx " MAS7_3=0x%" PRIx64 " MAS8=%x\n",
+              __func__, address, pid, tlb->mas1, tlb->mas2, mask, tlb->mas7_3,
+              tlb->mas8);
+
+    /* Check PID */
+    tlb_pid = (tlb->mas1 & MAS1_TID_MASK) >> MAS1_TID_SHIFT;
+    if (tlb_pid != 0 && tlb_pid != pid) {
+        return -1;
+    }
+
+    /* Check effective address */
+    if ((address & mask) != (tlb->mas2 & MAS2_EPN_MASK)) {
+        return -1;
+    }
+
+    if (raddrp) {
+        *raddrp = (tlb->mas7_3 & mask) | (address & ~mask);
+    }
+
+    return 0;
+}
+
+static int mmubooke206_check_tlb(CPUPPCState *env, ppcmas_tlb_t *tlb,
+                                 target_phys_addr_t *raddr, int *prot,
+                                 target_ulong address, int rw,
+                                 int access_type)
+{
+    int ret;
+    int prot2 = 0;
+
+    if (ppcmas_tlb_check(env, tlb, raddr, address,
+                         env->spr[SPR_BOOKE_PID]) >= 0) {
+        goto found_tlb;
+    }
+
+    if (env->spr[SPR_BOOKE_PID1] &&
+        ppcmas_tlb_check(env, tlb, raddr, address,
+                         env->spr[SPR_BOOKE_PID1]) >= 0) {
+        goto found_tlb;
+    }
+
+    if (env->spr[SPR_BOOKE_PID2] &&
+        ppcmas_tlb_check(env, tlb, raddr, address,
+                         env->spr[SPR_BOOKE_PID2]) >= 0) {
+        goto found_tlb;
+    }
+
+    LOG_SWTLB("%s: TLB entry not found\n", __func__);
+    return -1;
+
+found_tlb:
+
+    if (msr_pr != 0) {
+        if (tlb->mas7_3 & MAS3_UR) {
+            prot2 |= PAGE_READ;
+        }
+        if (tlb->mas7_3 & MAS3_UW) {
+            prot2 |= PAGE_WRITE;
+        }
+        if (tlb->mas7_3 & MAS3_UX) {
+            prot2 |= PAGE_EXEC;
+        }
+    } else {
+        if (tlb->mas7_3 & MAS3_SR) {
+            prot2 |= PAGE_READ;
+        }
+        if (tlb->mas7_3 & MAS3_SW) {
+            prot2 |= PAGE_WRITE;
+        }
+        if (tlb->mas7_3 & MAS3_SX) {
+            prot2 |= PAGE_EXEC;
+        }
+    }
+
+    /* Check the address space and permissions */
+    if (access_type == ACCESS_CODE) {
+        if (msr_ir != ((tlb->mas1 & MAS1_TS) >> MAS1_TS_SHIFT)) {
+            LOG_SWTLB("%s: AS doesn't match\n", __func__);
+            return -1;
+        }
+
+        *prot = prot2;
+        if (prot2 & PAGE_EXEC) {
+            LOG_SWTLB("%s: good TLB!\n", __func__);
+            return 0;
+        }
+
+        LOG_SWTLB("%s: no PAGE_EXEC: %x\n", __func__, prot2);
+        ret = -3;
+    } else {
+        if (msr_dr != ((tlb->mas1 & MAS1_TS) >> MAS1_TS_SHIFT)) {
+            LOG_SWTLB("%s: AS doesn't match\n", __func__);
+            return -1;
+        }
+
+        *prot = prot2;
+        if ((!rw && prot2 & PAGE_READ) || (rw && (prot2 & PAGE_WRITE))) {
+            LOG_SWTLB("%s: found TLB!\n", __func__);
+            return 0;
+        }
+
+        LOG_SWTLB("%s: PAGE_READ/WRITE doesn't match: %x\n", __func__, prot2);
+        ret = -2;
+    }
+
+    return ret;
+}
+
+static int mmubooke206_get_physical_address(CPUPPCState *env, mmu_ctx_t *ctx,
+                                            target_ulong address, int rw,
+                                            int access_type)
+{
+    ppcmas_tlb_t *tlb;
+    target_phys_addr_t raddr;
+    int i, j, ret;
+
+    ret = -1;
+    raddr = (target_phys_addr_t)-1ULL;
+
+    for (i = 0; i < BOOKE206_MAX_TLBN; i++) {
+        int ways = booke206_tlb_ways(env, i);
+
+        for (j = 0; j < ways; j++) {
+            tlb = booke206_get_tlbm(env, i, address, j);
+            if (!tlb) {
+                continue;
+            }
+            ret = mmubooke206_check_tlb(env, tlb, &raddr, &ctx->prot, address,
+                                        rw, access_type);
+            if (ret != -1) {
+                goto found_tlb;
+            }
+        }
+    }
+
+found_tlb:
+
+    if (ret >= 0) {
+        ctx->raddr = raddr;
+        LOG_SWTLB("%s: access granted " TARGET_FMT_lx " => " TARGET_FMT_plx
+                  " %d %d\n", __func__, address, ctx->raddr, ctx->prot,
+                  ret);
+    } else {
+        LOG_SWTLB("%s: access refused " TARGET_FMT_lx " => " TARGET_FMT_plx
+                  " %d %d\n", __func__, address, raddr, ctx->prot, ret);
+    }
+
+    return ret;
+}
+
+static const char *book3e_tsize_to_str[32] = {
+    "1K", "2K", "4K", "8K", "16K", "32K", "64K", "128K", "256K", "512K",
+    "1M", "2M", "4M", "8M", "16M", "32M", "64M", "128M", "256M", "512M",
+    "1G", "2G", "4G", "8G", "16G", "32G", "64G", "128G", "256G", "512G",
+    "1T", "2T"
+};
+
+static void mmubooke_dump_mmu(FILE *f, fprintf_function cpu_fprintf,
+                                 CPUPPCState *env)
+{
+    ppcemb_tlb_t *entry;
+    int i;
+
+    if (kvm_enabled() && !env->kvm_sw_tlb) {
+        cpu_fprintf(f, "Cannot access KVM TLB\n");
+        return;
+    }
+
+    cpu_fprintf(f, "\nTLB:\n");
+    cpu_fprintf(f, "Effective          Physical           Size PID   Prot     "
+                "Attr\n");
+
+    entry = &env->tlb.tlbe[0];
+    for (i = 0; i < env->nb_tlb; i++, entry++) {
+        target_phys_addr_t ea, pa;
+        target_ulong mask;
+        uint64_t size = (uint64_t)entry->size;
+        char size_buf[20];
+
+        /* Check valid flag */
+        if (!(entry->prot & PAGE_VALID)) {
+            continue;
+        }
+
+        mask = ~(entry->size - 1);
+        ea = entry->EPN & mask;
+        pa = entry->RPN & mask;
+#if (TARGET_PHYS_ADDR_BITS >= 36)
+        /* Extend the physical address to 36 bits */
+        pa |= (target_phys_addr_t)(entry->RPN & 0xF) << 32;
+#endif
+        size /= 1024;
+        if (size >= 1024) {
+            snprintf(size_buf, sizeof(size_buf), "%3" PRId64 "M", size / 1024);
+        } else {
+            snprintf(size_buf, sizeof(size_buf), "%3" PRId64 "k", size);
+        }
+        cpu_fprintf(f, "0x%016" PRIx64 " 0x%016" PRIx64 " %s %-5u %08x %08x\n",
+                    (uint64_t)ea, (uint64_t)pa, size_buf, (uint32_t)entry->PID,
+                    entry->prot, entry->attr);
+    }
+
+}
+
+static void mmubooke206_dump_one_tlb(FILE *f, fprintf_function cpu_fprintf,
+                                     CPUPPCState *env, int tlbn, int offset,
+                                     int tlbsize)
+{
+    ppcmas_tlb_t *entry;
+    int i;
+
+    cpu_fprintf(f, "\nTLB%d:\n", tlbn);
+    cpu_fprintf(f, "Effective          Physical           Size TID   TS SRWX"
+                " URWX WIMGE U0123\n");
+
+    entry = &env->tlb.tlbm[offset];
+    for (i = 0; i < tlbsize; i++, entry++) {
+        target_phys_addr_t ea, pa, size;
+        int tsize;
+
+        if (!(entry->mas1 & MAS1_VALID)) {
+            continue;
+        }
+
+        tsize = (entry->mas1 & MAS1_TSIZE_MASK) >> MAS1_TSIZE_SHIFT;
+        size = 1024ULL << tsize;
+        ea = entry->mas2 & ~(size - 1);
+        pa = entry->mas7_3 & ~(size - 1);
+
+        cpu_fprintf(f, "0x%016" PRIx64 " 0x%016" PRIx64 " %4s %-5u %1u  S%c%c%c"
+                    "U%c%c%c %c%c%c%c%c U%c%c%c%c\n",
+                    (uint64_t)ea, (uint64_t)pa,
+                    book3e_tsize_to_str[tsize],
+                    (entry->mas1 & MAS1_TID_MASK) >> MAS1_TID_SHIFT,
+                    (entry->mas1 & MAS1_TS) >> MAS1_TS_SHIFT,
+                    entry->mas7_3 & MAS3_SR ? 'R' : '-',
+                    entry->mas7_3 & MAS3_SW ? 'W' : '-',
+                    entry->mas7_3 & MAS3_SX ? 'X' : '-',
+                    entry->mas7_3 & MAS3_UR ? 'R' : '-',
+                    entry->mas7_3 & MAS3_UW ? 'W' : '-',
+                    entry->mas7_3 & MAS3_UX ? 'X' : '-',
+                    entry->mas2 & MAS2_W ? 'W' : '-',
+                    entry->mas2 & MAS2_I ? 'I' : '-',
+                    entry->mas2 & MAS2_M ? 'M' : '-',
+                    entry->mas2 & MAS2_G ? 'G' : '-',
+                    entry->mas2 & MAS2_E ? 'E' : '-',
+                    entry->mas7_3 & MAS3_U0 ? '0' : '-',
+                    entry->mas7_3 & MAS3_U1 ? '1' : '-',
+                    entry->mas7_3 & MAS3_U2 ? '2' : '-',
+                    entry->mas7_3 & MAS3_U3 ? '3' : '-');
+    }
+}
+
+static void mmubooke206_dump_mmu(FILE *f, fprintf_function cpu_fprintf,
+                                 CPUPPCState *env)
+{
+    int offset = 0;
+    int i;
+
+    if (kvm_enabled() && !env->kvm_sw_tlb) {
+        cpu_fprintf(f, "Cannot access KVM TLB\n");
+        return;
+    }
+
+    for (i = 0; i < BOOKE206_MAX_TLBN; i++) {
+        int size = booke206_tlb_size(env, i);
+
+        if (size == 0) {
+            continue;
+        }
+
+        mmubooke206_dump_one_tlb(f, cpu_fprintf, env, i, offset, size);
+        offset += size;
+    }
+}
+
+#if defined(TARGET_PPC64)
+static void mmubooks_dump_mmu(FILE *f, fprintf_function cpu_fprintf,
+                              CPUPPCState *env)
+{
+    int i;
+    uint64_t slbe, slbv;
+
+    cpu_synchronize_state(env);
+
+    cpu_fprintf(f, "SLB\tESID\t\t\tVSID\n");
+    for (i = 0; i < env->slb_nr; i++) {
+        slbe = env->slb[i].esid;
+        slbv = env->slb[i].vsid;
+        if (slbe == 0 && slbv == 0) {
+            continue;
+        }
+        cpu_fprintf(f, "%d\t0x%016" PRIx64 "\t0x%016" PRIx64 "\n",
+                    i, slbe, slbv);
+    }
+}
+#endif
+
+void dump_mmu(FILE *f, fprintf_function cpu_fprintf, CPUPPCState *env)
+{
+    switch (env->mmu_model) {
+    case POWERPC_MMU_BOOKE:
+        mmubooke_dump_mmu(f, cpu_fprintf, env);
+        break;
+    case POWERPC_MMU_BOOKE206:
+        mmubooke206_dump_mmu(f, cpu_fprintf, env);
+        break;
+#if defined(TARGET_PPC64)
+    case POWERPC_MMU_64B:
+    case POWERPC_MMU_2_06:
+        mmubooks_dump_mmu(f, cpu_fprintf, env);
+        break;
+#endif
+    default:
+        qemu_log_mask(LOG_UNIMP, "%s: unimplemented\n", __func__);
+    }
+}
+
+static inline int check_physical(CPUPPCState *env, mmu_ctx_t *ctx,
+                                 target_ulong eaddr, int rw)
+{
+    int in_plb, ret;
+
+    ctx->raddr = eaddr;
+    ctx->prot = PAGE_READ | PAGE_EXEC;
+    ret = 0;
+    switch (env->mmu_model) {
+    case POWERPC_MMU_32B:
+    case POWERPC_MMU_601:
+    case POWERPC_MMU_SOFT_6xx:
+    case POWERPC_MMU_SOFT_74xx:
+    case POWERPC_MMU_SOFT_4xx:
+    case POWERPC_MMU_REAL:
+    case POWERPC_MMU_BOOKE:
+        ctx->prot |= PAGE_WRITE;
+        break;
+#if defined(TARGET_PPC64)
+    case POWERPC_MMU_620:
+    case POWERPC_MMU_64B:
+    case POWERPC_MMU_2_06:
+        /* Real address are 60 bits long */
+        ctx->raddr &= 0x0FFFFFFFFFFFFFFFULL;
+        ctx->prot |= PAGE_WRITE;
+        break;
+#endif
+    case POWERPC_MMU_SOFT_4xx_Z:
+        if (unlikely(msr_pe != 0)) {
+            /* 403 family add some particular protections,
+             * using PBL/PBU registers for accesses with no translation.
+             */
+            in_plb =
+                /* Check PLB validity */
+                (env->pb[0] < env->pb[1] &&
+                 /* and address in plb area */
+                 eaddr >= env->pb[0] && eaddr < env->pb[1]) ||
+                (env->pb[2] < env->pb[3] &&
+                 eaddr >= env->pb[2] && eaddr < env->pb[3]) ? 1 : 0;
+            if (in_plb ^ msr_px) {
+                /* Access in protected area */
+                if (rw == 1) {
+                    /* Access is not allowed */
+                    ret = -2;
+                }
+            } else {
+                /* Read-write access is allowed */
+                ctx->prot |= PAGE_WRITE;
+            }
+        }
+        break;
+    case POWERPC_MMU_MPC8xx:
+        /* XXX: TODO */
+        cpu_abort(env, "MPC8xx MMU model is not implemented\n");
+        break;
+    case POWERPC_MMU_BOOKE206:
+        cpu_abort(env, "BookE 2.06 MMU doesn't have physical real mode\n");
+        break;
+    default:
+        cpu_abort(env, "Unknown or invalid MMU model\n");
+        return -1;
+    }
+
+    return ret;
+}
+
+int get_physical_address(CPUPPCState *env, mmu_ctx_t *ctx, target_ulong eaddr,
+                         int rw, int access_type)
+{
+    int ret;
+
+#if 0
+    qemu_log("%s\n", __func__);
+#endif
+    if ((access_type == ACCESS_CODE && msr_ir == 0) ||
+        (access_type != ACCESS_CODE && msr_dr == 0)) {
+        if (env->mmu_model == POWERPC_MMU_BOOKE) {
+            /* The BookE MMU always performs address translation. The
+               IS and DS bits only affect the address space.  */
+            ret = mmubooke_get_physical_address(env, ctx, eaddr,
+                                                rw, access_type);
+        } else if (env->mmu_model == POWERPC_MMU_BOOKE206) {
+            ret = mmubooke206_get_physical_address(env, ctx, eaddr, rw,
+                                                   access_type);
+        } else {
+            /* No address translation.  */
+            ret = check_physical(env, ctx, eaddr, rw);
+        }
+    } else {
+        ret = -1;
+        switch (env->mmu_model) {
+        case POWERPC_MMU_32B:
+        case POWERPC_MMU_601:
+        case POWERPC_MMU_SOFT_6xx:
+        case POWERPC_MMU_SOFT_74xx:
+            /* Try to find a BAT */
+            if (env->nb_BATs != 0) {
+                ret = get_bat(env, ctx, eaddr, rw, access_type);
+            }
+#if defined(TARGET_PPC64)
+        case POWERPC_MMU_620:
+        case POWERPC_MMU_64B:
+        case POWERPC_MMU_2_06:
+#endif
+            if (ret < 0) {
+                /* We didn't match any BAT entry or don't have BATs */
+                ret = get_segment(env, ctx, eaddr, rw, access_type);
+            }
+            break;
+        case POWERPC_MMU_SOFT_4xx:
+        case POWERPC_MMU_SOFT_4xx_Z:
+            ret = mmu40x_get_physical_address(env, ctx, eaddr,
+                                              rw, access_type);
+            break;
+        case POWERPC_MMU_BOOKE:
+            ret = mmubooke_get_physical_address(env, ctx, eaddr,
+                                                rw, access_type);
+            break;
+        case POWERPC_MMU_BOOKE206:
+            ret = mmubooke206_get_physical_address(env, ctx, eaddr, rw,
+                                               access_type);
+            break;
+        case POWERPC_MMU_MPC8xx:
+            /* XXX: TODO */
+            cpu_abort(env, "MPC8xx MMU model is not implemented\n");
+            break;
+        case POWERPC_MMU_REAL:
+            cpu_abort(env, "PowerPC in real mode do not do any translation\n");
+            return -1;
+        default:
+            cpu_abort(env, "Unknown or invalid MMU model\n");
+            return -1;
+        }
+    }
+#if 0
+    qemu_log("%s address " TARGET_FMT_lx " => %d " TARGET_FMT_plx "\n",
+             __func__, eaddr, ret, ctx->raddr);
+#endif
+
+    return ret;
+}
+
+target_phys_addr_t cpu_get_phys_page_debug(CPUPPCState *env, target_ulong addr)
+{
+    mmu_ctx_t ctx;
+
+    if (unlikely(get_physical_address(env, &ctx, addr, 0, ACCESS_INT) != 0)) {
+        return -1;
+    }
+
+    return ctx.raddr & TARGET_PAGE_MASK;
+}
+
+static void booke206_update_mas_tlb_miss(CPUPPCState *env, target_ulong address,
+                                     int rw)
+{
+    env->spr[SPR_BOOKE_MAS0] = env->spr[SPR_BOOKE_MAS4] & MAS4_TLBSELD_MASK;
+    env->spr[SPR_BOOKE_MAS1] = env->spr[SPR_BOOKE_MAS4] & MAS4_TSIZED_MASK;
+    env->spr[SPR_BOOKE_MAS2] = env->spr[SPR_BOOKE_MAS4] & MAS4_WIMGED_MASK;
+    env->spr[SPR_BOOKE_MAS3] = 0;
+    env->spr[SPR_BOOKE_MAS6] = 0;
+    env->spr[SPR_BOOKE_MAS7] = 0;
+
+    /* AS */
+    if (((rw == 2) && msr_ir) || ((rw != 2) && msr_dr)) {
+        env->spr[SPR_BOOKE_MAS1] |= MAS1_TS;
+        env->spr[SPR_BOOKE_MAS6] |= MAS6_SAS;
+    }
+
+    env->spr[SPR_BOOKE_MAS1] |= MAS1_VALID;
+    env->spr[SPR_BOOKE_MAS2] |= address & MAS2_EPN_MASK;
+
+    switch (env->spr[SPR_BOOKE_MAS4] & MAS4_TIDSELD_PIDZ) {
+    case MAS4_TIDSELD_PID0:
+        env->spr[SPR_BOOKE_MAS1] |= env->spr[SPR_BOOKE_PID] << MAS1_TID_SHIFT;
+        break;
+    case MAS4_TIDSELD_PID1:
+        env->spr[SPR_BOOKE_MAS1] |= env->spr[SPR_BOOKE_PID1] << MAS1_TID_SHIFT;
+        break;
+    case MAS4_TIDSELD_PID2:
+        env->spr[SPR_BOOKE_MAS1] |= env->spr[SPR_BOOKE_PID2] << MAS1_TID_SHIFT;
+        break;
+    }
+
+    env->spr[SPR_BOOKE_MAS6] |= env->spr[SPR_BOOKE_PID] << 16;
+
+    /* next victim logic */
+    env->spr[SPR_BOOKE_MAS0] |= env->last_way << MAS0_ESEL_SHIFT;
+    env->last_way++;
+    env->last_way &= booke206_tlb_ways(env, 0) - 1;
+    env->spr[SPR_BOOKE_MAS0] |= env->last_way << MAS0_NV_SHIFT;
+}
+
+/* Perform address translation */
+int cpu_ppc_handle_mmu_fault(CPUPPCState *env, target_ulong address, int rw,
+                             int mmu_idx)
+{
+    mmu_ctx_t ctx;
+    int access_type;
+    int ret = 0;
+
+    if (rw == 2) {
+        /* code access */
+        rw = 0;
+        access_type = ACCESS_CODE;
+    } else {
+        /* data access */
+        access_type = env->access_type;
+    }
+    ret = get_physical_address(env, &ctx, address, rw, access_type);
+    if (ret == 0) {
+        tlb_set_page(env, address & TARGET_PAGE_MASK,
+                     ctx.raddr & TARGET_PAGE_MASK, ctx.prot,
+                     mmu_idx, TARGET_PAGE_SIZE);
+        ret = 0;
+    } else if (ret < 0) {
+        LOG_MMU_STATE(env);
+        if (access_type == ACCESS_CODE) {
+            switch (ret) {
+            case -1:
+                /* No matches in page tables or TLB */
+                switch (env->mmu_model) {
+                case POWERPC_MMU_SOFT_6xx:
+                    env->exception_index = POWERPC_EXCP_IFTLB;
+                    env->error_code = 1 << 18;
+                    env->spr[SPR_IMISS] = address;
+                    env->spr[SPR_ICMP] = 0x80000000 | ctx.ptem;
+                    goto tlb_miss;
+                case POWERPC_MMU_SOFT_74xx:
+                    env->exception_index = POWERPC_EXCP_IFTLB;
+                    goto tlb_miss_74xx;
+                case POWERPC_MMU_SOFT_4xx:
+                case POWERPC_MMU_SOFT_4xx_Z:
+                    env->exception_index = POWERPC_EXCP_ITLB;
+                    env->error_code = 0;
+                    env->spr[SPR_40x_DEAR] = address;
+                    env->spr[SPR_40x_ESR] = 0x00000000;
+                    break;
+                case POWERPC_MMU_32B:
+                case POWERPC_MMU_601:
+#if defined(TARGET_PPC64)
+                case POWERPC_MMU_620:
+                case POWERPC_MMU_64B:
+                case POWERPC_MMU_2_06:
+#endif
+                    env->exception_index = POWERPC_EXCP_ISI;
+                    env->error_code = 0x40000000;
+                    break;
+                case POWERPC_MMU_BOOKE206:
+                    booke206_update_mas_tlb_miss(env, address, rw);
+                    /* fall through */
+                case POWERPC_MMU_BOOKE:
+                    env->exception_index = POWERPC_EXCP_ITLB;
+                    env->error_code = 0;
+                    env->spr[SPR_BOOKE_DEAR] = address;
+                    return -1;
+                case POWERPC_MMU_MPC8xx:
+                    /* XXX: TODO */
+                    cpu_abort(env, "MPC8xx MMU model is not implemented\n");
+                    break;
+                case POWERPC_MMU_REAL:
+                    cpu_abort(env, "PowerPC in real mode should never raise "
+                              "any MMU exceptions\n");
+                    return -1;
+                default:
+                    cpu_abort(env, "Unknown or invalid MMU model\n");
+                    return -1;
+                }
+                break;
+            case -2:
+                /* Access rights violation */
+                env->exception_index = POWERPC_EXCP_ISI;
+                env->error_code = 0x08000000;
+                break;
+            case -3:
+                /* No execute protection violation */
+                if ((env->mmu_model == POWERPC_MMU_BOOKE) ||
+                    (env->mmu_model == POWERPC_MMU_BOOKE206)) {
+                    env->spr[SPR_BOOKE_ESR] = 0x00000000;
+                }
+                env->exception_index = POWERPC_EXCP_ISI;
+                env->error_code = 0x10000000;
+                break;
+            case -4:
+                /* Direct store exception */
+                /* No code fetch is allowed in direct-store areas */
+                env->exception_index = POWERPC_EXCP_ISI;
+                env->error_code = 0x10000000;
+                break;
+#if defined(TARGET_PPC64)
+            case -5:
+                /* No match in segment table */
+                if (env->mmu_model == POWERPC_MMU_620) {
+                    env->exception_index = POWERPC_EXCP_ISI;
+                    /* XXX: this might be incorrect */
+                    env->error_code = 0x40000000;
+                } else {
+                    env->exception_index = POWERPC_EXCP_ISEG;
+                    env->error_code = 0;
+                }
+                break;
+#endif
+            }
+        } else {
+            switch (ret) {
+            case -1:
+                /* No matches in page tables or TLB */
+                switch (env->mmu_model) {
+                case POWERPC_MMU_SOFT_6xx:
+                    if (rw == 1) {
+                        env->exception_index = POWERPC_EXCP_DSTLB;
+                        env->error_code = 1 << 16;
+                    } else {
+                        env->exception_index = POWERPC_EXCP_DLTLB;
+                        env->error_code = 0;
+                    }
+                    env->spr[SPR_DMISS] = address;
+                    env->spr[SPR_DCMP] = 0x80000000 | ctx.ptem;
+                tlb_miss:
+                    env->error_code |= ctx.key << 19;
+                    env->spr[SPR_HASH1] = env->htab_base +
+                        get_pteg_offset(env, ctx.hash[0], HASH_PTE_SIZE_32);
+                    env->spr[SPR_HASH2] = env->htab_base +
+                        get_pteg_offset(env, ctx.hash[1], HASH_PTE_SIZE_32);
+                    break;
+                case POWERPC_MMU_SOFT_74xx:
+                    if (rw == 1) {
+                        env->exception_index = POWERPC_EXCP_DSTLB;
+                    } else {
+                        env->exception_index = POWERPC_EXCP_DLTLB;
+                    }
+                tlb_miss_74xx:
+                    /* Implement LRU algorithm */
+                    env->error_code = ctx.key << 19;
+                    env->spr[SPR_TLBMISS] = (address & ~((target_ulong)0x3)) |
+                        ((env->last_way + 1) & (env->nb_ways - 1));
+                    env->spr[SPR_PTEHI] = 0x80000000 | ctx.ptem;
+                    break;
+                case POWERPC_MMU_SOFT_4xx:
+                case POWERPC_MMU_SOFT_4xx_Z:
+                    env->exception_index = POWERPC_EXCP_DTLB;
+                    env->error_code = 0;
+                    env->spr[SPR_40x_DEAR] = address;
+                    if (rw) {
+                        env->spr[SPR_40x_ESR] = 0x00800000;
+                    } else {
+                        env->spr[SPR_40x_ESR] = 0x00000000;
+                    }
+                    break;
+                case POWERPC_MMU_32B:
+                case POWERPC_MMU_601:
+#if defined(TARGET_PPC64)
+                case POWERPC_MMU_620:
+                case POWERPC_MMU_64B:
+                case POWERPC_MMU_2_06:
+#endif
+                    env->exception_index = POWERPC_EXCP_DSI;
+                    env->error_code = 0;
+                    env->spr[SPR_DAR] = address;
+                    if (rw == 1) {
+                        env->spr[SPR_DSISR] = 0x42000000;
+                    } else {
+                        env->spr[SPR_DSISR] = 0x40000000;
+                    }
+                    break;
+                case POWERPC_MMU_MPC8xx:
+                    /* XXX: TODO */
+                    cpu_abort(env, "MPC8xx MMU model is not implemented\n");
+                    break;
+                case POWERPC_MMU_BOOKE206:
+                    booke206_update_mas_tlb_miss(env, address, rw);
+                    /* fall through */
+                case POWERPC_MMU_BOOKE:
+                    env->exception_index = POWERPC_EXCP_DTLB;
+                    env->error_code = 0;
+                    env->spr[SPR_BOOKE_DEAR] = address;
+                    env->spr[SPR_BOOKE_ESR] = rw ? ESR_ST : 0;
+                    return -1;
+                case POWERPC_MMU_REAL:
+                    cpu_abort(env, "PowerPC in real mode should never raise "
+                              "any MMU exceptions\n");
+                    return -1;
+                default:
+                    cpu_abort(env, "Unknown or invalid MMU model\n");
+                    return -1;
+                }
+                break;
+            case -2:
+                /* Access rights violation */
+                env->exception_index = POWERPC_EXCP_DSI;
+                env->error_code = 0;
+                if (env->mmu_model == POWERPC_MMU_SOFT_4xx
+                    || env->mmu_model == POWERPC_MMU_SOFT_4xx_Z) {
+                    env->spr[SPR_40x_DEAR] = address;
+                    if (rw) {
+                        env->spr[SPR_40x_ESR] |= 0x00800000;
+                    }
+                } else if ((env->mmu_model == POWERPC_MMU_BOOKE) ||
+                           (env->mmu_model == POWERPC_MMU_BOOKE206)) {
+                    env->spr[SPR_BOOKE_DEAR] = address;
+                    env->spr[SPR_BOOKE_ESR] = rw ? ESR_ST : 0;
+                } else {
+                    env->spr[SPR_DAR] = address;
+                    if (rw == 1) {
+                        env->spr[SPR_DSISR] = 0x0A000000;
+                    } else {
+                        env->spr[SPR_DSISR] = 0x08000000;
+                    }
+                }
+                break;
+            case -4:
+                /* Direct store exception */
+                switch (access_type) {
+                case ACCESS_FLOAT:
+                    /* Floating point load/store */
+                    env->exception_index = POWERPC_EXCP_ALIGN;
+                    env->error_code = POWERPC_EXCP_ALIGN_FP;
+                    env->spr[SPR_DAR] = address;
+                    break;
+                case ACCESS_RES:
+                    /* lwarx, ldarx or stwcx. */
+                    env->exception_index = POWERPC_EXCP_DSI;
+                    env->error_code = 0;
+                    env->spr[SPR_DAR] = address;
+                    if (rw == 1) {
+                        env->spr[SPR_DSISR] = 0x06000000;
+                    } else {
+                        env->spr[SPR_DSISR] = 0x04000000;
+                    }
+                    break;
+                case ACCESS_EXT:
+                    /* eciwx or ecowx */
+                    env->exception_index = POWERPC_EXCP_DSI;
+                    env->error_code = 0;
+                    env->spr[SPR_DAR] = address;
+                    if (rw == 1) {
+                        env->spr[SPR_DSISR] = 0x06100000;
+                    } else {
+                        env->spr[SPR_DSISR] = 0x04100000;
+                    }
+                    break;
+                default:
+                    printf("DSI: invalid exception (%d)\n", ret);
+                    env->exception_index = POWERPC_EXCP_PROGRAM;
+                    env->error_code =
+                        POWERPC_EXCP_INVAL | POWERPC_EXCP_INVAL_INVAL;
+                    env->spr[SPR_DAR] = address;
+                    break;
+                }
+                break;
+#if defined(TARGET_PPC64)
+            case -5:
+                /* No match in segment table */
+                if (env->mmu_model == POWERPC_MMU_620) {
+                    env->exception_index = POWERPC_EXCP_DSI;
+                    env->error_code = 0;
+                    env->spr[SPR_DAR] = address;
+                    /* XXX: this might be incorrect */
+                    if (rw == 1) {
+                        env->spr[SPR_DSISR] = 0x42000000;
+                    } else {
+                        env->spr[SPR_DSISR] = 0x40000000;
+                    }
+                } else {
+                    env->exception_index = POWERPC_EXCP_DSEG;
+                    env->error_code = 0;
+                    env->spr[SPR_DAR] = address;
+                }
+                break;
+#endif
+            }
+        }
+#if 0
+        printf("%s: set exception to %d %02x\n", __func__,
+               env->exception, env->error_code);
+#endif
+        ret = 1;
+    }
+
+    return ret;
+}
+
+/*****************************************************************************/
+/* BATs management */
+#if !defined(FLUSH_ALL_TLBS)
+static inline void do_invalidate_BAT(CPUPPCState *env, target_ulong BATu,
+                                     target_ulong mask)
+{
+    target_ulong base, end, page;
+
+    base = BATu & ~0x0001FFFF;
+    end = base + mask + 0x00020000;
+    LOG_BATS("Flush BAT from " TARGET_FMT_lx " to " TARGET_FMT_lx " ("
+             TARGET_FMT_lx ")\n", base, end, mask);
+    for (page = base; page != end; page += TARGET_PAGE_SIZE) {
+        tlb_flush_page(env, page);
+    }
+    LOG_BATS("Flush done\n");
+}
+#endif
+
+static inline void dump_store_bat(CPUPPCState *env, char ID, int ul, int nr,
+                                  target_ulong value)
+{
+    LOG_BATS("Set %cBAT%d%c to " TARGET_FMT_lx " (" TARGET_FMT_lx ")\n", ID,
+             nr, ul == 0 ? 'u' : 'l', value, env->nip);
+}
+
+void ppc_store_ibatu(CPUPPCState *env, int nr, target_ulong value)
+{
+    target_ulong mask;
+
+    dump_store_bat(env, 'I', 0, nr, value);
+    if (env->IBAT[0][nr] != value) {
+        mask = (value << 15) & 0x0FFE0000UL;
+#if !defined(FLUSH_ALL_TLBS)
+        do_invalidate_BAT(env, env->IBAT[0][nr], mask);
+#endif
+        /* When storing valid upper BAT, mask BEPI and BRPN
+         * and invalidate all TLBs covered by this BAT
+         */
+        mask = (value << 15) & 0x0FFE0000UL;
+        env->IBAT[0][nr] = (value & 0x00001FFFUL) |
+            (value & ~0x0001FFFFUL & ~mask);
+        env->IBAT[1][nr] = (env->IBAT[1][nr] & 0x0000007B) |
+            (env->IBAT[1][nr] & ~0x0001FFFF & ~mask);
+#if !defined(FLUSH_ALL_TLBS)
+        do_invalidate_BAT(env, env->IBAT[0][nr], mask);
+#else
+        tlb_flush(env, 1);
+#endif
+    }
+}
+
+void ppc_store_ibatl(CPUPPCState *env, int nr, target_ulong value)
+{
+    dump_store_bat(env, 'I', 1, nr, value);
+    env->IBAT[1][nr] = value;
+}
+
+void ppc_store_dbatu(CPUPPCState *env, int nr, target_ulong value)
+{
+    target_ulong mask;
+
+    dump_store_bat(env, 'D', 0, nr, value);
+    if (env->DBAT[0][nr] != value) {
+        /* When storing valid upper BAT, mask BEPI and BRPN
+         * and invalidate all TLBs covered by this BAT
+         */
+        mask = (value << 15) & 0x0FFE0000UL;
+#if !defined(FLUSH_ALL_TLBS)
+        do_invalidate_BAT(env, env->DBAT[0][nr], mask);
+#endif
+        mask = (value << 15) & 0x0FFE0000UL;
+        env->DBAT[0][nr] = (value & 0x00001FFFUL) |
+            (value & ~0x0001FFFFUL & ~mask);
+        env->DBAT[1][nr] = (env->DBAT[1][nr] & 0x0000007B) |
+            (env->DBAT[1][nr] & ~0x0001FFFF & ~mask);
+#if !defined(FLUSH_ALL_TLBS)
+        do_invalidate_BAT(env, env->DBAT[0][nr], mask);
+#else
+        tlb_flush(env, 1);
+#endif
+    }
+}
+
+void ppc_store_dbatl(CPUPPCState *env, int nr, target_ulong value)
+{
+    dump_store_bat(env, 'D', 1, nr, value);
+    env->DBAT[1][nr] = value;
+}
+
+void ppc_store_ibatu_601(CPUPPCState *env, int nr, target_ulong value)
+{
+    target_ulong mask;
+#if defined(FLUSH_ALL_TLBS)
+    int do_inval;
+#endif
+
+    dump_store_bat(env, 'I', 0, nr, value);
+    if (env->IBAT[0][nr] != value) {
+#if defined(FLUSH_ALL_TLBS)
+        do_inval = 0;
+#endif
+        mask = (env->IBAT[1][nr] << 17) & 0x0FFE0000UL;
+        if (env->IBAT[1][nr] & 0x40) {
+            /* Invalidate BAT only if it is valid */
+#if !defined(FLUSH_ALL_TLBS)
+            do_invalidate_BAT(env, env->IBAT[0][nr], mask);
+#else
+            do_inval = 1;
+#endif
+        }
+        /* When storing valid upper BAT, mask BEPI and BRPN
+         * and invalidate all TLBs covered by this BAT
+         */
+        env->IBAT[0][nr] = (value & 0x00001FFFUL) |
+            (value & ~0x0001FFFFUL & ~mask);
+        env->DBAT[0][nr] = env->IBAT[0][nr];
+        if (env->IBAT[1][nr] & 0x40) {
+#if !defined(FLUSH_ALL_TLBS)
+            do_invalidate_BAT(env, env->IBAT[0][nr], mask);
+#else
+            do_inval = 1;
+#endif
+        }
+#if defined(FLUSH_ALL_TLBS)
+        if (do_inval) {
+            tlb_flush(env, 1);
+        }
+#endif
+    }
+}
+
+void ppc_store_ibatl_601(CPUPPCState *env, int nr, target_ulong value)
+{
+    target_ulong mask;
+#if defined(FLUSH_ALL_TLBS)
+    int do_inval;
+#endif
+
+    dump_store_bat(env, 'I', 1, nr, value);
+    if (env->IBAT[1][nr] != value) {
+#if defined(FLUSH_ALL_TLBS)
+        do_inval = 0;
+#endif
+        if (env->IBAT[1][nr] & 0x40) {
+#if !defined(FLUSH_ALL_TLBS)
+            mask = (env->IBAT[1][nr] << 17) & 0x0FFE0000UL;
+            do_invalidate_BAT(env, env->IBAT[0][nr], mask);
+#else
+            do_inval = 1;
+#endif
+        }
+        if (value & 0x40) {
+#if !defined(FLUSH_ALL_TLBS)
+            mask = (value << 17) & 0x0FFE0000UL;
+            do_invalidate_BAT(env, env->IBAT[0][nr], mask);
+#else
+            do_inval = 1;
+#endif
+        }
+        env->IBAT[1][nr] = value;
+        env->DBAT[1][nr] = value;
+#if defined(FLUSH_ALL_TLBS)
+        if (do_inval) {
+            tlb_flush(env, 1);
+        }
+#endif
+    }
+}
+
+/*****************************************************************************/
+/* TLB management */
+void ppc_tlb_invalidate_all(CPUPPCState *env)
+{
+    switch (env->mmu_model) {
+    case POWERPC_MMU_SOFT_6xx:
+    case POWERPC_MMU_SOFT_74xx:
+        ppc6xx_tlb_invalidate_all(env);
+        break;
+    case POWERPC_MMU_SOFT_4xx:
+    case POWERPC_MMU_SOFT_4xx_Z:
+        ppc4xx_tlb_invalidate_all(env);
+        break;
+    case POWERPC_MMU_REAL:
+        cpu_abort(env, "No TLB for PowerPC 4xx in real mode\n");
+        break;
+    case POWERPC_MMU_MPC8xx:
+        /* XXX: TODO */
+        cpu_abort(env, "MPC8xx MMU model is not implemented\n");
+        break;
+    case POWERPC_MMU_BOOKE:
+        tlb_flush(env, 1);
+        break;
+    case POWERPC_MMU_BOOKE206:
+        booke206_flush_tlb(env, -1, 0);
+        break;
+    case POWERPC_MMU_32B:
+    case POWERPC_MMU_601:
+#if defined(TARGET_PPC64)
+    case POWERPC_MMU_620:
+    case POWERPC_MMU_64B:
+    case POWERPC_MMU_2_06:
+#endif /* defined(TARGET_PPC64) */
+        tlb_flush(env, 1);
+        break;
+    default:
+        /* XXX: TODO */
+        cpu_abort(env, "Unknown MMU model\n");
+        break;
+    }
+}
+
+void ppc_tlb_invalidate_one(CPUPPCState *env, target_ulong addr)
+{
+#if !defined(FLUSH_ALL_TLBS)
+    addr &= TARGET_PAGE_MASK;
+    switch (env->mmu_model) {
+    case POWERPC_MMU_SOFT_6xx:
+    case POWERPC_MMU_SOFT_74xx:
+        ppc6xx_tlb_invalidate_virt(env, addr, 0);
+        if (env->id_tlbs == 1) {
+            ppc6xx_tlb_invalidate_virt(env, addr, 1);
+        }
+        break;
+    case POWERPC_MMU_SOFT_4xx:
+    case POWERPC_MMU_SOFT_4xx_Z:
+        ppc4xx_tlb_invalidate_virt(env, addr, env->spr[SPR_40x_PID]);
+        break;
+    case POWERPC_MMU_REAL:
+        cpu_abort(env, "No TLB for PowerPC 4xx in real mode\n");
+        break;
+    case POWERPC_MMU_MPC8xx:
+        /* XXX: TODO */
+        cpu_abort(env, "MPC8xx MMU model is not implemented\n");
+        break;
+    case POWERPC_MMU_BOOKE:
+        /* XXX: TODO */
+        cpu_abort(env, "BookE MMU model is not implemented\n");
+        break;
+    case POWERPC_MMU_BOOKE206:
+        /* XXX: TODO */
+        cpu_abort(env, "BookE 2.06 MMU model is not implemented\n");
+        break;
+    case POWERPC_MMU_32B:
+    case POWERPC_MMU_601:
+        /* tlbie invalidate TLBs for all segments */
+        addr &= ~((target_ulong)-1ULL << 28);
+        /* XXX: this case should be optimized,
+         * giving a mask to tlb_flush_page
+         */
+        tlb_flush_page(env, addr | (0x0 << 28));
+        tlb_flush_page(env, addr | (0x1 << 28));
+        tlb_flush_page(env, addr | (0x2 << 28));
+        tlb_flush_page(env, addr | (0x3 << 28));
+        tlb_flush_page(env, addr | (0x4 << 28));
+        tlb_flush_page(env, addr | (0x5 << 28));
+        tlb_flush_page(env, addr | (0x6 << 28));
+        tlb_flush_page(env, addr | (0x7 << 28));
+        tlb_flush_page(env, addr | (0x8 << 28));
+        tlb_flush_page(env, addr | (0x9 << 28));
+        tlb_flush_page(env, addr | (0xA << 28));
+        tlb_flush_page(env, addr | (0xB << 28));
+        tlb_flush_page(env, addr | (0xC << 28));
+        tlb_flush_page(env, addr | (0xD << 28));
+        tlb_flush_page(env, addr | (0xE << 28));
+        tlb_flush_page(env, addr | (0xF << 28));
+        break;
+#if defined(TARGET_PPC64)
+    case POWERPC_MMU_620:
+    case POWERPC_MMU_64B:
+    case POWERPC_MMU_2_06:
+        /* tlbie invalidate TLBs for all segments */
+        /* XXX: given the fact that there are too many segments to invalidate,
+         *      and we still don't have a tlb_flush_mask(env, n, mask) in QEMU,
+         *      we just invalidate all TLBs
+         */
+        tlb_flush(env, 1);
+        break;
+#endif /* defined(TARGET_PPC64) */
+    default:
+        /* XXX: TODO */
+        cpu_abort(env, "Unknown MMU model\n");
+        break;
+    }
+#else
+    ppc_tlb_invalidate_all(env);
+#endif
+}
+
+/*****************************************************************************/
+/* Special registers manipulation */
+#if defined(TARGET_PPC64)
+void ppc_store_asr(CPUPPCState *env, target_ulong value)
+{
+    if (env->asr != value) {
+        env->asr = value;
+        tlb_flush(env, 1);
+    }
+}
+#endif
+
+void ppc_store_sdr1(CPUPPCState *env, target_ulong value)
+{
+    LOG_MMU("%s: " TARGET_FMT_lx "\n", __func__, value);
+    if (env->spr[SPR_SDR1] != value) {
+        env->spr[SPR_SDR1] = value;
+#if defined(TARGET_PPC64)
+        if (env->mmu_model & POWERPC_MMU_64) {
+            target_ulong htabsize = value & SDR_64_HTABSIZE;
+
+            if (htabsize > 28) {
+                fprintf(stderr, "Invalid HTABSIZE 0x" TARGET_FMT_lx
+                        " stored in SDR1\n", htabsize);
+                htabsize = 28;
+            }
+            env->htab_mask = (1ULL << (htabsize + 18)) - 1;
+            env->htab_base = value & SDR_64_HTABORG;
+        } else
+#endif /* defined(TARGET_PPC64) */
+        {
+            /* FIXME: Should check for valid HTABMASK values */
+            env->htab_mask = ((value & SDR_32_HTABMASK) << 16) | 0xFFFF;
+            env->htab_base = value & SDR_32_HTABORG;
+        }
+        tlb_flush(env, 1);
+    }
+}
+
+#if defined(TARGET_PPC64)
+target_ulong ppc_load_sr(CPUPPCState *env, int slb_nr)
+{
+    /* XXX */
+    return 0;
+}
+#endif
+
+void ppc_store_sr(CPUPPCState *env, int srnum, target_ulong value)
+{
+    LOG_MMU("%s: reg=%d " TARGET_FMT_lx " " TARGET_FMT_lx "\n", __func__,
+            srnum, value, env->sr[srnum]);
+#if defined(TARGET_PPC64)
+    if (env->mmu_model & POWERPC_MMU_64) {
+        uint64_t rb = 0, rs = 0;
+
+        /* ESID = srnum */
+        rb |= ((uint32_t)srnum & 0xf) << 28;
+        /* Set the valid bit */
+        rb |= 1 << 27;
+        /* Index = ESID */
+        rb |= (uint32_t)srnum;
+
+        /* VSID = VSID */
+        rs |= (value & 0xfffffff) << 12;
+        /* flags = flags */
+        rs |= ((value >> 27) & 0xf) << 8;
+
+        ppc_store_slb(env, rb, rs);
+    } else
+#endif
+    if (env->sr[srnum] != value) {
+        env->sr[srnum] = value;
+/* Invalidating 256MB of virtual memory in 4kB pages is way longer than
+   flusing the whole TLB. */
+#if !defined(FLUSH_ALL_TLBS) && 0
+        {
+            target_ulong page, end;
+            /* Invalidate 256 MB of virtual memory */
+            page = (16 << 20) * srnum;
+            end = page + (16 << 20);
+            for (; page != end; page += TARGET_PAGE_SIZE) {
+                tlb_flush_page(env, page);
+            }
+        }
+#else
+        tlb_flush(env, 1);
+#endif
+    }
+}
+#endif /* !defined(CONFIG_USER_ONLY) */
+
 /*****************************************************************************/
 /* SPR accesses */
 
commit 4cc2cc085586cdb787a24d78a7ba032fa657275a
Author: Blue Swirl <blauwirbel at gmail.com>
Date:   Wed May 30 04:23:32 2012 +0000

    ppc: Avoid a warning with the next patch
    
    When the code is moved together by the next patch, compiler
    detects a possible uninitialized variable use. Avoid the warning
    by initializing the variables.
    
    Signed-off-by: Blue Swirl <blauwirbel at gmail.com>
    Signed-off-by: Alexander Graf <agraf at suse.de>
    Signed-off-by: Andreas Färber <afaerber at suse.de>
    Signed-off-by: Alexander Graf <agraf at suse.de>

diff --git a/target-ppc/mmu_helper.c b/target-ppc/mmu_helper.c
index 7bd6230..e79b8f2 100644
--- a/target-ppc/mmu_helper.c
+++ b/target-ppc/mmu_helper.c
@@ -89,7 +89,7 @@ void helper_store_slb(CPUPPCState *env, target_ulong rb, target_ulong rs)
 
 target_ulong helper_load_slb_esid(CPUPPCState *env, target_ulong rb)
 {
-    target_ulong rt;
+    target_ulong rt = 0;
 
     if (ppc_load_slb_esid(env, rb, &rt) < 0) {
         helper_raise_exception_err(env, POWERPC_EXCP_PROGRAM,
@@ -100,7 +100,7 @@ target_ulong helper_load_slb_esid(CPUPPCState *env, target_ulong rb)
 
 target_ulong helper_load_slb_vsid(CPUPPCState *env, target_ulong rb)
 {
-    target_ulong rt;
+    target_ulong rt = 0;
 
     if (ppc_load_slb_vsid(env, rb, &rt) < 0) {
         helper_raise_exception_err(env, POWERPC_EXCP_PROGRAM,
commit c6c7cf05e126d4dd1d9bfcb1aaf1b2cc66f5fa9a
Author: Blue Swirl <blauwirbel at gmail.com>
Date:   Wed May 30 04:23:31 2012 +0000

    ppc: Avoid AREG0 for MMU etc. helpers
    
    Add an explicit CPUPPCState parameter instead of relying on AREG0.
    
    Signed-off-by: Blue Swirl <blauwirbel at gmail.com>
    Signed-off-by: Alexander Graf <agraf at suse.de>
    Signed-off-by: Andreas Färber <afaerber at suse.de>
    Signed-off-by: Alexander Graf <agraf at suse.de>

diff --git a/target-ppc/Makefile.objs b/target-ppc/Makefile.objs
index 0f89c2c..71e25b1 100644
--- a/target-ppc/Makefile.objs
+++ b/target-ppc/Makefile.objs
@@ -7,5 +7,4 @@ obj-y += fpu_helper.o
 obj-y += int_helper.o
 obj-y += mmu_helper.o
 
-$(obj)/mmu_helper.o: QEMU_CFLAGS += $(HELPER_CFLAGS)
 $(obj)/op_helper.o: QEMU_CFLAGS += $(HELPER_CFLAGS)
diff --git a/target-ppc/helper.h b/target-ppc/helper.h
index 7074bad..b1f7ba5 100644
--- a/target-ppc/helper.h
+++ b/target-ppc/helper.h
@@ -324,38 +324,38 @@ DEF_HELPER_3(efdcmpgt, i32, env, i64, i64)
 DEF_HELPER_3(efdcmpeq, i32, env, i64, i64)
 
 #if !defined(CONFIG_USER_ONLY)
-DEF_HELPER_1(4xx_tlbre_hi, tl, tl)
-DEF_HELPER_1(4xx_tlbre_lo, tl, tl)
-DEF_HELPER_2(4xx_tlbwe_hi, void, tl, tl)
-DEF_HELPER_2(4xx_tlbwe_lo, void, tl, tl)
-DEF_HELPER_1(4xx_tlbsx, tl, tl)
-DEF_HELPER_2(440_tlbre, tl, i32, tl)
-DEF_HELPER_3(440_tlbwe, void, i32, tl, tl)
-DEF_HELPER_1(440_tlbsx, tl, tl)
-DEF_HELPER_0(booke206_tlbre, void)
-DEF_HELPER_0(booke206_tlbwe, void)
-DEF_HELPER_1(booke206_tlbsx, void, tl)
-DEF_HELPER_1(booke206_tlbivax, void, tl)
-DEF_HELPER_1(booke206_tlbilx0, void, tl)
-DEF_HELPER_1(booke206_tlbilx1, void, tl)
-DEF_HELPER_1(booke206_tlbilx3, void, tl)
-DEF_HELPER_1(booke206_tlbflush, void, i32)
-DEF_HELPER_2(booke_setpid, void, i32, tl)
-DEF_HELPER_1(6xx_tlbd, void, tl)
-DEF_HELPER_1(6xx_tlbi, void, tl)
-DEF_HELPER_1(74xx_tlbd, void, tl)
-DEF_HELPER_1(74xx_tlbi, void, tl)
-DEF_HELPER_FLAGS_0(tlbia, TCG_CALL_CONST, void)
-DEF_HELPER_FLAGS_1(tlbie, TCG_CALL_CONST, void, tl)
+DEF_HELPER_2(4xx_tlbre_hi, tl, env, tl)
+DEF_HELPER_2(4xx_tlbre_lo, tl, env, tl)
+DEF_HELPER_3(4xx_tlbwe_hi, void, env, tl, tl)
+DEF_HELPER_3(4xx_tlbwe_lo, void, env, tl, tl)
+DEF_HELPER_2(4xx_tlbsx, tl, env, tl)
+DEF_HELPER_3(440_tlbre, tl, env, i32, tl)
+DEF_HELPER_4(440_tlbwe, void, env, i32, tl, tl)
+DEF_HELPER_2(440_tlbsx, tl, env, tl)
+DEF_HELPER_1(booke206_tlbre, void, env)
+DEF_HELPER_1(booke206_tlbwe, void, env)
+DEF_HELPER_2(booke206_tlbsx, void, env, tl)
+DEF_HELPER_2(booke206_tlbivax, void, env, tl)
+DEF_HELPER_2(booke206_tlbilx0, void, env, tl)
+DEF_HELPER_2(booke206_tlbilx1, void, env, tl)
+DEF_HELPER_2(booke206_tlbilx3, void, env, tl)
+DEF_HELPER_2(booke206_tlbflush, void, env, i32)
+DEF_HELPER_3(booke_setpid, void, env, i32, tl)
+DEF_HELPER_2(6xx_tlbd, void, env, tl)
+DEF_HELPER_2(6xx_tlbi, void, env, tl)
+DEF_HELPER_2(74xx_tlbd, void, env, tl)
+DEF_HELPER_2(74xx_tlbi, void, env, tl)
+DEF_HELPER_FLAGS_1(tlbia, TCG_CALL_CONST, void, env)
+DEF_HELPER_FLAGS_2(tlbie, TCG_CALL_CONST, void, env, tl)
 #if defined(TARGET_PPC64)
-DEF_HELPER_FLAGS_2(store_slb, TCG_CALL_CONST, void, tl, tl)
-DEF_HELPER_1(load_slb_esid, tl, tl)
-DEF_HELPER_1(load_slb_vsid, tl, tl)
-DEF_HELPER_FLAGS_0(slbia, TCG_CALL_CONST, void)
-DEF_HELPER_FLAGS_1(slbie, TCG_CALL_CONST, void, tl)
+DEF_HELPER_FLAGS_3(store_slb, TCG_CALL_CONST, void, env, tl, tl)
+DEF_HELPER_2(load_slb_esid, tl, env, tl)
+DEF_HELPER_2(load_slb_vsid, tl, env, tl)
+DEF_HELPER_FLAGS_1(slbia, TCG_CALL_CONST, void, env)
+DEF_HELPER_FLAGS_2(slbie, TCG_CALL_CONST, void, env, tl)
 #endif
-DEF_HELPER_FLAGS_1(load_sr, TCG_CALL_CONST, tl, tl);
-DEF_HELPER_FLAGS_2(store_sr, TCG_CALL_CONST, void, tl, tl)
+DEF_HELPER_FLAGS_2(load_sr, TCG_CALL_CONST, tl, env, tl);
+DEF_HELPER_FLAGS_3(store_sr, TCG_CALL_CONST, void, env, tl, tl)
 
 DEF_HELPER_FLAGS_1(602_mfrom, TCG_CALL_CONST | TCG_CALL_PURE, tl, tl)
 DEF_HELPER_1(msgsnd, void, tl)
@@ -365,7 +365,7 @@ DEF_HELPER_2(msgclr, void, env, tl)
 DEF_HELPER_4(dlmzb, tl, env, tl, tl, i32)
 DEF_HELPER_FLAGS_1(clcs, TCG_CALL_CONST | TCG_CALL_PURE, tl, i32)
 #if !defined(CONFIG_USER_ONLY)
-DEF_HELPER_1(rac, tl, tl)
+DEF_HELPER_2(rac, tl, env, tl)
 #endif
 DEF_HELPER_3(div, tl, env, tl, tl)
 DEF_HELPER_3(divo, tl, env, tl, tl)
@@ -405,12 +405,12 @@ DEF_HELPER_1(store_40x_dbcr0, void, tl)
 DEF_HELPER_1(store_40x_sler, void, tl)
 DEF_HELPER_1(store_booke_tcr, void, tl)
 DEF_HELPER_1(store_booke_tsr, void, tl)
-DEF_HELPER_2(store_ibatl, void, i32, tl)
-DEF_HELPER_2(store_ibatu, void, i32, tl)
-DEF_HELPER_2(store_dbatl, void, i32, tl)
-DEF_HELPER_2(store_dbatu, void, i32, tl)
-DEF_HELPER_2(store_601_batl, void, i32, tl)
-DEF_HELPER_2(store_601_batu, void, i32, tl)
+DEF_HELPER_3(store_ibatl, void, env, i32, tl)
+DEF_HELPER_3(store_ibatu, void, env, i32, tl)
+DEF_HELPER_3(store_dbatl, void, env, i32, tl)
+DEF_HELPER_3(store_dbatu, void, env, i32, tl)
+DEF_HELPER_3(store_601_batl, void, env, i32, tl)
+DEF_HELPER_3(store_601_batu, void, env, i32, tl)
 #endif
 
 #include "def-helper.h"
diff --git a/target-ppc/mmu_helper.c b/target-ppc/mmu_helper.c
index 81800b6..7bd6230 100644
--- a/target-ppc/mmu_helper.c
+++ b/target-ppc/mmu_helper.c
@@ -17,7 +17,6 @@
  * License along with this library; if not, see <http://www.gnu.org/licenses/>.
  */
 #include "cpu.h"
-#include "dyngen-exec.h"
 #include "helper.h"
 
 //#define DEBUG_SOFTWARE_TLB
@@ -32,38 +31,38 @@
 /* SPR accesses */
 
 #if !defined(CONFIG_USER_ONLY)
-void helper_store_ibatu(uint32_t nr, target_ulong val)
+void helper_store_ibatu(CPUPPCState *env, uint32_t nr, target_ulong val)
 {
     ppc_store_ibatu(env, nr, val);
 }
 
-void helper_store_ibatl(uint32_t nr, target_ulong val)
+void helper_store_ibatl(CPUPPCState *env, uint32_t nr, target_ulong val)
 {
     ppc_store_ibatl(env, nr, val);
 }
 
-void helper_store_dbatu(uint32_t nr, target_ulong val)
+void helper_store_dbatu(CPUPPCState *env, uint32_t nr, target_ulong val)
 {
     ppc_store_dbatu(env, nr, val);
 }
 
-void helper_store_dbatl(uint32_t nr, target_ulong val)
+void helper_store_dbatl(CPUPPCState *env, uint32_t nr, target_ulong val)
 {
     ppc_store_dbatl(env, nr, val);
 }
 
-void helper_store_601_batl(uint32_t nr, target_ulong val)
+void helper_store_601_batl(CPUPPCState *env, uint32_t nr, target_ulong val)
 {
     ppc_store_ibatl_601(env, nr, val);
 }
 
-void helper_store_601_batu(uint32_t nr, target_ulong val)
+void helper_store_601_batu(CPUPPCState *env, uint32_t nr, target_ulong val)
 {
     ppc_store_ibatu_601(env, nr, val);
 }
 
 /* Segment registers load and store */
-target_ulong helper_load_sr(target_ulong sr_num)
+target_ulong helper_load_sr(CPUPPCState *env, target_ulong sr_num)
 {
 #if defined(TARGET_PPC64)
     if (env->mmu_model & POWERPC_MMU_64) {
@@ -73,14 +72,14 @@ target_ulong helper_load_sr(target_ulong sr_num)
     return env->sr[sr_num];
 }
 
-void helper_store_sr(target_ulong sr_num, target_ulong val)
+void helper_store_sr(CPUPPCState *env, target_ulong sr_num, target_ulong val)
 {
     ppc_store_sr(env, sr_num, val);
 }
 
 /* SLB management */
 #if defined(TARGET_PPC64)
-void helper_store_slb(target_ulong rb, target_ulong rs)
+void helper_store_slb(CPUPPCState *env, target_ulong rb, target_ulong rs)
 {
     if (ppc_store_slb(env, rb, rs) < 0) {
         helper_raise_exception_err(env, POWERPC_EXCP_PROGRAM,
@@ -88,7 +87,7 @@ void helper_store_slb(target_ulong rb, target_ulong rs)
     }
 }
 
-target_ulong helper_load_slb_esid(target_ulong rb)
+target_ulong helper_load_slb_esid(CPUPPCState *env, target_ulong rb)
 {
     target_ulong rt;
 
@@ -99,7 +98,7 @@ target_ulong helper_load_slb_esid(target_ulong rb)
     return rt;
 }
 
-target_ulong helper_load_slb_vsid(target_ulong rb)
+target_ulong helper_load_slb_vsid(CPUPPCState *env, target_ulong rb)
 {
     target_ulong rt;
 
@@ -110,12 +109,12 @@ target_ulong helper_load_slb_vsid(target_ulong rb)
     return rt;
 }
 
-void helper_slbia(void)
+void helper_slbia(CPUPPCState *env)
 {
     ppc_slb_invalidate_all(env);
 }
 
-void helper_slbie(target_ulong addr)
+void helper_slbie(CPUPPCState *env, target_ulong addr)
 {
     ppc_slb_invalidate_one(env, addr);
 }
@@ -123,19 +122,19 @@ void helper_slbie(target_ulong addr)
 #endif /* defined(TARGET_PPC64) */
 
 /* TLB management */
-void helper_tlbia(void)
+void helper_tlbia(CPUPPCState *env)
 {
     ppc_tlb_invalidate_all(env);
 }
 
-void helper_tlbie(target_ulong addr)
+void helper_tlbie(CPUPPCState *env, target_ulong addr)
 {
     ppc_tlb_invalidate_one(env, addr);
 }
 
 /* Software driven TLBs management */
 /* PowerPC 602/603 software TLB load instructions helpers */
-static void do_6xx_tlb(target_ulong new_EPN, int is_code)
+static void do_6xx_tlb(CPUPPCState *env, target_ulong new_EPN, int is_code)
 {
     target_ulong RPN, CMP, EPN;
     int way;
@@ -158,18 +157,18 @@ static void do_6xx_tlb(target_ulong new_EPN, int is_code)
                      way, is_code, CMP, RPN);
 }
 
-void helper_6xx_tlbd(target_ulong EPN)
+void helper_6xx_tlbd(CPUPPCState *env, target_ulong EPN)
 {
-    do_6xx_tlb(EPN, 0);
+    do_6xx_tlb(env, EPN, 0);
 }
 
-void helper_6xx_tlbi(target_ulong EPN)
+void helper_6xx_tlbi(CPUPPCState *env, target_ulong EPN)
 {
-    do_6xx_tlb(EPN, 1);
+    do_6xx_tlb(env, EPN, 1);
 }
 
 /* PowerPC 74xx software TLB load instructions helpers */
-static void do_74xx_tlb(target_ulong new_EPN, int is_code)
+static void do_74xx_tlb(CPUPPCState *env, target_ulong new_EPN, int is_code)
 {
     target_ulong RPN, CMP, EPN;
     int way;
@@ -187,20 +186,20 @@ static void do_74xx_tlb(target_ulong new_EPN, int is_code)
                      way, is_code, CMP, RPN);
 }
 
-void helper_74xx_tlbd(target_ulong EPN)
+void helper_74xx_tlbd(CPUPPCState *env, target_ulong EPN)
 {
-    do_74xx_tlb(EPN, 0);
+    do_74xx_tlb(env, EPN, 0);
 }
 
-void helper_74xx_tlbi(target_ulong EPN)
+void helper_74xx_tlbi(CPUPPCState *env, target_ulong EPN)
 {
-    do_74xx_tlb(EPN, 1);
+    do_74xx_tlb(env, EPN, 1);
 }
 
 /*****************************************************************************/
 /* PowerPC 601 specific instructions (POWER bridge) */
 
-target_ulong helper_rac(target_ulong addr)
+target_ulong helper_rac(CPUPPCState *env, target_ulong addr)
 {
     mmu_ctx_t ctx;
     int nb_BATs;
@@ -303,7 +302,7 @@ static inline int booke_page_size_to_tlb(target_ulong page_size)
 #define PPC4XX_TLBLO_ATTR_MASK      0x000000FF
 #define PPC4XX_TLBLO_RPN_MASK       0xFFFFFC00
 
-target_ulong helper_4xx_tlbre_hi(target_ulong entry)
+target_ulong helper_4xx_tlbre_hi(CPUPPCState *env, target_ulong entry)
 {
     ppcemb_tlb_t *tlb;
     target_ulong ret;
@@ -324,7 +323,7 @@ target_ulong helper_4xx_tlbre_hi(target_ulong entry)
     return ret;
 }
 
-target_ulong helper_4xx_tlbre_lo(target_ulong entry)
+target_ulong helper_4xx_tlbre_lo(CPUPPCState *env, target_ulong entry)
 {
     ppcemb_tlb_t *tlb;
     target_ulong ret;
@@ -341,7 +340,8 @@ target_ulong helper_4xx_tlbre_lo(target_ulong entry)
     return ret;
 }
 
-void helper_4xx_tlbwe_hi(target_ulong entry, target_ulong val)
+void helper_4xx_tlbwe_hi(CPUPPCState *env, target_ulong entry,
+                         target_ulong val)
 {
     ppcemb_tlb_t *tlb;
     target_ulong page, end;
@@ -400,7 +400,8 @@ void helper_4xx_tlbwe_hi(target_ulong entry, target_ulong val)
     }
 }
 
-void helper_4xx_tlbwe_lo(target_ulong entry, target_ulong val)
+void helper_4xx_tlbwe_lo(CPUPPCState *env, target_ulong entry,
+                         target_ulong val)
 {
     ppcemb_tlb_t *tlb;
 
@@ -426,13 +427,14 @@ void helper_4xx_tlbwe_lo(target_ulong entry, target_ulong val)
               tlb->prot & PAGE_VALID ? 'v' : '-', (int)tlb->PID);
 }
 
-target_ulong helper_4xx_tlbsx(target_ulong address)
+target_ulong helper_4xx_tlbsx(CPUPPCState *env, target_ulong address)
 {
     return ppcemb_tlb_search(env, address, env->spr[SPR_40x_PID]);
 }
 
 /* PowerPC 440 TLB management */
-void helper_440_tlbwe(uint32_t word, target_ulong entry, target_ulong value)
+void helper_440_tlbwe(CPUPPCState *env, uint32_t word, target_ulong entry,
+                      target_ulong value)
 {
     ppcemb_tlb_t *tlb;
     target_ulong EPN, RPN, size;
@@ -504,7 +506,8 @@ void helper_440_tlbwe(uint32_t word, target_ulong entry, target_ulong value)
     }
 }
 
-target_ulong helper_440_tlbre(uint32_t word, target_ulong entry)
+target_ulong helper_440_tlbre(CPUPPCState *env, uint32_t word,
+                              target_ulong entry)
 {
     ppcemb_tlb_t *tlb;
     target_ulong ret;
@@ -559,7 +562,7 @@ target_ulong helper_440_tlbre(uint32_t word, target_ulong entry)
     return ret;
 }
 
-target_ulong helper_440_tlbsx(target_ulong address)
+target_ulong helper_440_tlbsx(CPUPPCState *env, target_ulong address)
 {
     return ppcemb_tlb_search(env, address, env->spr[SPR_440_MMUCR] & 0xFF);
 }
@@ -583,14 +586,14 @@ static ppcmas_tlb_t *booke206_cur_tlb(CPUPPCState *env)
     return booke206_get_tlbm(env, tlb, ea, esel);
 }
 
-void helper_booke_setpid(uint32_t pidn, target_ulong pid)
+void helper_booke_setpid(CPUPPCState *env, uint32_t pidn, target_ulong pid)
 {
     env->spr[pidn] = pid;
     /* changing PIDs mean we're in a different address space now */
     tlb_flush(env, 1);
 }
 
-void helper_booke206_tlbwe(void)
+void helper_booke206_tlbwe(CPUPPCState *env)
 {
     uint32_t tlbncfg, tlbn;
     ppcmas_tlb_t *tlb;
@@ -687,7 +690,7 @@ static inline void booke206_tlb_to_mas(CPUPPCState *env, ppcmas_tlb_t *tlb)
     env->spr[SPR_BOOKE_MAS7] = tlb->mas7_3 >> 32;
 }
 
-void helper_booke206_tlbre(void)
+void helper_booke206_tlbre(CPUPPCState *env)
 {
     ppcmas_tlb_t *tlb = NULL;
 
@@ -699,7 +702,7 @@ void helper_booke206_tlbre(void)
     }
 }
 
-void helper_booke206_tlbsx(target_ulong address)
+void helper_booke206_tlbsx(CPUPPCState *env, target_ulong address)
 {
     ppcmas_tlb_t *tlb = NULL;
     int i, j;
@@ -773,7 +776,7 @@ static inline void booke206_invalidate_ea_tlb(CPUPPCState *env, int tlbn,
     }
 }
 
-void helper_booke206_tlbivax(target_ulong address)
+void helper_booke206_tlbivax(CPUPPCState *env, target_ulong address)
 {
     if (address & 0x4) {
         /* flush all entries */
@@ -798,13 +801,13 @@ void helper_booke206_tlbivax(target_ulong address)
     }
 }
 
-void helper_booke206_tlbilx0(target_ulong address)
+void helper_booke206_tlbilx0(CPUPPCState *env, target_ulong address)
 {
     /* XXX missing LPID handling */
     booke206_flush_tlb(env, -1, 1);
 }
 
-void helper_booke206_tlbilx1(target_ulong address)
+void helper_booke206_tlbilx1(CPUPPCState *env, target_ulong address)
 {
     int i, j;
     int tid = (env->spr[SPR_BOOKE_MAS6] & MAS6_SPID);
@@ -825,7 +828,7 @@ void helper_booke206_tlbilx1(target_ulong address)
     tlb_flush(env, 1);
 }
 
-void helper_booke206_tlbilx3(target_ulong address)
+void helper_booke206_tlbilx3(CPUPPCState *env, target_ulong address)
 {
     int i, j;
     ppcmas_tlb_t *tlb;
@@ -865,7 +868,7 @@ void helper_booke206_tlbilx3(target_ulong address)
     tlb_flush(env, 1);
 }
 
-void helper_booke206_tlbflush(uint32_t type)
+void helper_booke206_tlbflush(CPUPPCState *env, uint32_t type)
 {
     int flags = 0;
 
diff --git a/target-ppc/translate.c b/target-ppc/translate.c
index eb3cd5a..446f97e 100644
--- a/target-ppc/translate.c
+++ b/target-ppc/translate.c
@@ -4200,7 +4200,7 @@ static void gen_mfsr(DisasContext *ctx)
         return;
     }
     t0 = tcg_const_tl(SR(ctx->opcode));
-    gen_helper_load_sr(cpu_gpr[rD(ctx->opcode)], t0);
+    gen_helper_load_sr(cpu_gpr[rD(ctx->opcode)], cpu_env, t0);
     tcg_temp_free(t0);
 #endif
 }
@@ -4219,7 +4219,7 @@ static void gen_mfsrin(DisasContext *ctx)
     t0 = tcg_temp_new();
     tcg_gen_shri_tl(t0, cpu_gpr[rB(ctx->opcode)], 28);
     tcg_gen_andi_tl(t0, t0, 0xF);
-    gen_helper_load_sr(cpu_gpr[rD(ctx->opcode)], t0);
+    gen_helper_load_sr(cpu_gpr[rD(ctx->opcode)], cpu_env, t0);
     tcg_temp_free(t0);
 #endif
 }
@@ -4236,7 +4236,7 @@ static void gen_mtsr(DisasContext *ctx)
         return;
     }
     t0 = tcg_const_tl(SR(ctx->opcode));
-    gen_helper_store_sr(t0, cpu_gpr[rS(ctx->opcode)]);
+    gen_helper_store_sr(cpu_env, t0, cpu_gpr[rS(ctx->opcode)]);
     tcg_temp_free(t0);
 #endif
 }
@@ -4255,7 +4255,7 @@ static void gen_mtsrin(DisasContext *ctx)
     t0 = tcg_temp_new();
     tcg_gen_shri_tl(t0, cpu_gpr[rB(ctx->opcode)], 28);
     tcg_gen_andi_tl(t0, t0, 0xF);
-    gen_helper_store_sr(t0, cpu_gpr[rD(ctx->opcode)]);
+    gen_helper_store_sr(cpu_env, t0, cpu_gpr[rD(ctx->opcode)]);
     tcg_temp_free(t0);
 #endif
 }
@@ -4275,7 +4275,7 @@ static void gen_mfsr_64b(DisasContext *ctx)
         return;
     }
     t0 = tcg_const_tl(SR(ctx->opcode));
-    gen_helper_load_sr(cpu_gpr[rD(ctx->opcode)], t0);
+    gen_helper_load_sr(cpu_gpr[rD(ctx->opcode)], cpu_env, t0);
     tcg_temp_free(t0);
 #endif
 }
@@ -4294,7 +4294,7 @@ static void gen_mfsrin_64b(DisasContext *ctx)
     t0 = tcg_temp_new();
     tcg_gen_shri_tl(t0, cpu_gpr[rB(ctx->opcode)], 28);
     tcg_gen_andi_tl(t0, t0, 0xF);
-    gen_helper_load_sr(cpu_gpr[rD(ctx->opcode)], t0);
+    gen_helper_load_sr(cpu_gpr[rD(ctx->opcode)], cpu_env, t0);
     tcg_temp_free(t0);
 #endif
 }
@@ -4311,7 +4311,7 @@ static void gen_mtsr_64b(DisasContext *ctx)
         return;
     }
     t0 = tcg_const_tl(SR(ctx->opcode));
-    gen_helper_store_sr(t0, cpu_gpr[rS(ctx->opcode)]);
+    gen_helper_store_sr(cpu_env, t0, cpu_gpr[rS(ctx->opcode)]);
     tcg_temp_free(t0);
 #endif
 }
@@ -4330,7 +4330,7 @@ static void gen_mtsrin_64b(DisasContext *ctx)
     t0 = tcg_temp_new();
     tcg_gen_shri_tl(t0, cpu_gpr[rB(ctx->opcode)], 28);
     tcg_gen_andi_tl(t0, t0, 0xF);
-    gen_helper_store_sr(t0, cpu_gpr[rS(ctx->opcode)]);
+    gen_helper_store_sr(cpu_env, t0, cpu_gpr[rS(ctx->opcode)]);
     tcg_temp_free(t0);
 #endif
 }
@@ -4345,7 +4345,8 @@ static void gen_slbmte(DisasContext *ctx)
         gen_inval_exception(ctx, POWERPC_EXCP_PRIV_REG);
         return;
     }
-    gen_helper_store_slb(cpu_gpr[rB(ctx->opcode)], cpu_gpr[rS(ctx->opcode)]);
+    gen_helper_store_slb(cpu_env, cpu_gpr[rB(ctx->opcode)],
+                         cpu_gpr[rS(ctx->opcode)]);
 #endif
 }
 
@@ -4358,7 +4359,7 @@ static void gen_slbmfee(DisasContext *ctx)
         gen_inval_exception(ctx, POWERPC_EXCP_PRIV_REG);
         return;
     }
-    gen_helper_load_slb_esid(cpu_gpr[rS(ctx->opcode)],
+    gen_helper_load_slb_esid(cpu_gpr[rS(ctx->opcode)], cpu_env,
                              cpu_gpr[rB(ctx->opcode)]);
 #endif
 }
@@ -4372,7 +4373,7 @@ static void gen_slbmfev(DisasContext *ctx)
         gen_inval_exception(ctx, POWERPC_EXCP_PRIV_REG);
         return;
     }
-    gen_helper_load_slb_vsid(cpu_gpr[rS(ctx->opcode)],
+    gen_helper_load_slb_vsid(cpu_gpr[rS(ctx->opcode)], cpu_env,
                              cpu_gpr[rB(ctx->opcode)]);
 #endif
 }
@@ -4391,7 +4392,7 @@ static void gen_tlbia(DisasContext *ctx)
         gen_inval_exception(ctx, POWERPC_EXCP_PRIV_OPC);
         return;
     }
-    gen_helper_tlbia();
+    gen_helper_tlbia(cpu_env);
 #endif
 }
 
@@ -4405,7 +4406,7 @@ static void gen_tlbiel(DisasContext *ctx)
         gen_inval_exception(ctx, POWERPC_EXCP_PRIV_OPC);
         return;
     }
-    gen_helper_tlbie(cpu_gpr[rB(ctx->opcode)]);
+    gen_helper_tlbie(cpu_env, cpu_gpr[rB(ctx->opcode)]);
 #endif
 }
 
@@ -4423,11 +4424,11 @@ static void gen_tlbie(DisasContext *ctx)
     if (!ctx->sf_mode) {
         TCGv t0 = tcg_temp_new();
         tcg_gen_ext32u_tl(t0, cpu_gpr[rB(ctx->opcode)]);
-        gen_helper_tlbie(t0);
+        gen_helper_tlbie(cpu_env, t0);
         tcg_temp_free(t0);
     } else
 #endif
-        gen_helper_tlbie(cpu_gpr[rB(ctx->opcode)]);
+        gen_helper_tlbie(cpu_env, cpu_gpr[rB(ctx->opcode)]);
 #endif
 }
 
@@ -4459,7 +4460,7 @@ static void gen_slbia(DisasContext *ctx)
         gen_inval_exception(ctx, POWERPC_EXCP_PRIV_OPC);
         return;
     }
-    gen_helper_slbia();
+    gen_helper_slbia(cpu_env);
 #endif
 }
 
@@ -4473,7 +4474,7 @@ static void gen_slbie(DisasContext *ctx)
         gen_inval_exception(ctx, POWERPC_EXCP_PRIV_OPC);
         return;
     }
-    gen_helper_slbie(cpu_gpr[rB(ctx->opcode)]);
+    gen_helper_slbie(cpu_env, cpu_gpr[rB(ctx->opcode)]);
 #endif
 }
 #endif
@@ -5194,7 +5195,7 @@ static void gen_tlbld_6xx(DisasContext *ctx)
         gen_inval_exception(ctx, POWERPC_EXCP_PRIV_OPC);
         return;
     }
-    gen_helper_6xx_tlbd(cpu_gpr[rB(ctx->opcode)]);
+    gen_helper_6xx_tlbd(cpu_env, cpu_gpr[rB(ctx->opcode)]);
 #endif
 }
 
@@ -5208,7 +5209,7 @@ static void gen_tlbli_6xx(DisasContext *ctx)
         gen_inval_exception(ctx, POWERPC_EXCP_PRIV_OPC);
         return;
     }
-    gen_helper_6xx_tlbi(cpu_gpr[rB(ctx->opcode)]);
+    gen_helper_6xx_tlbi(cpu_env, cpu_gpr[rB(ctx->opcode)]);
 #endif
 }
 
@@ -5224,7 +5225,7 @@ static void gen_tlbld_74xx(DisasContext *ctx)
         gen_inval_exception(ctx, POWERPC_EXCP_PRIV_OPC);
         return;
     }
-    gen_helper_74xx_tlbd(cpu_gpr[rB(ctx->opcode)]);
+    gen_helper_74xx_tlbd(cpu_env, cpu_gpr[rB(ctx->opcode)]);
 #endif
 }
 
@@ -5238,7 +5239,7 @@ static void gen_tlbli_74xx(DisasContext *ctx)
         gen_inval_exception(ctx, POWERPC_EXCP_PRIV_OPC);
         return;
     }
-    gen_helper_74xx_tlbi(cpu_gpr[rB(ctx->opcode)]);
+    gen_helper_74xx_tlbi(cpu_env, cpu_gpr[rB(ctx->opcode)]);
 #endif
 }
 
@@ -5286,7 +5287,7 @@ static void gen_mfsri(DisasContext *ctx)
     gen_addr_reg_index(ctx, t0);
     tcg_gen_shri_tl(t0, t0, 28);
     tcg_gen_andi_tl(t0, t0, 0xF);
-    gen_helper_load_sr(cpu_gpr[rd], t0);
+    gen_helper_load_sr(cpu_gpr[rd], cpu_env, t0);
     tcg_temp_free(t0);
     if (ra != 0 && ra != rd)
         tcg_gen_mov_tl(cpu_gpr[ra], cpu_gpr[rd]);
@@ -5305,7 +5306,7 @@ static void gen_rac(DisasContext *ctx)
     }
     t0 = tcg_temp_new();
     gen_addr_reg_index(ctx, t0);
-    gen_helper_rac(cpu_gpr[rD(ctx->opcode)], t0);
+    gen_helper_rac(cpu_gpr[rD(ctx->opcode)], cpu_env, t0);
     tcg_temp_free(t0);
 #endif
 }
@@ -5483,7 +5484,7 @@ static void gen_tlbiva(DisasContext *ctx)
     }
     t0 = tcg_temp_new();
     gen_addr_reg_index(ctx, t0);
-    gen_helper_tlbie(cpu_gpr[rB(ctx->opcode)]);
+    gen_helper_tlbie(cpu_env, cpu_gpr[rB(ctx->opcode)]);
     tcg_temp_free(t0);
 #endif
 }
@@ -5946,10 +5947,12 @@ static void gen_tlbre_40x(DisasContext *ctx)
     }
     switch (rB(ctx->opcode)) {
     case 0:
-        gen_helper_4xx_tlbre_hi(cpu_gpr[rD(ctx->opcode)], cpu_gpr[rA(ctx->opcode)]);
+        gen_helper_4xx_tlbre_hi(cpu_gpr[rD(ctx->opcode)], cpu_env,
+                                cpu_gpr[rA(ctx->opcode)]);
         break;
     case 1:
-        gen_helper_4xx_tlbre_lo(cpu_gpr[rD(ctx->opcode)], cpu_gpr[rA(ctx->opcode)]);
+        gen_helper_4xx_tlbre_lo(cpu_gpr[rD(ctx->opcode)], cpu_env,
+                                cpu_gpr[rA(ctx->opcode)]);
         break;
     default:
         gen_inval_exception(ctx, POWERPC_EXCP_INVAL_INVAL);
@@ -5971,7 +5974,7 @@ static void gen_tlbsx_40x(DisasContext *ctx)
     }
     t0 = tcg_temp_new();
     gen_addr_reg_index(ctx, t0);
-    gen_helper_4xx_tlbsx(cpu_gpr[rD(ctx->opcode)], t0);
+    gen_helper_4xx_tlbsx(cpu_gpr[rD(ctx->opcode)], cpu_env, t0);
     tcg_temp_free(t0);
     if (Rc(ctx->opcode)) {
         int l1 = gen_new_label();
@@ -5997,10 +6000,12 @@ static void gen_tlbwe_40x(DisasContext *ctx)
     }
     switch (rB(ctx->opcode)) {
     case 0:
-        gen_helper_4xx_tlbwe_hi(cpu_gpr[rA(ctx->opcode)], cpu_gpr[rS(ctx->opcode)]);
+        gen_helper_4xx_tlbwe_hi(cpu_env, cpu_gpr[rA(ctx->opcode)],
+                                cpu_gpr[rS(ctx->opcode)]);
         break;
     case 1:
-        gen_helper_4xx_tlbwe_lo(cpu_gpr[rA(ctx->opcode)], cpu_gpr[rS(ctx->opcode)]);
+        gen_helper_4xx_tlbwe_lo(cpu_env, cpu_gpr[rA(ctx->opcode)],
+                                cpu_gpr[rS(ctx->opcode)]);
         break;
     default:
         gen_inval_exception(ctx, POWERPC_EXCP_INVAL_INVAL);
@@ -6027,7 +6032,8 @@ static void gen_tlbre_440(DisasContext *ctx)
     case 2:
         {
             TCGv_i32 t0 = tcg_const_i32(rB(ctx->opcode));
-            gen_helper_440_tlbre(cpu_gpr[rD(ctx->opcode)], t0, cpu_gpr[rA(ctx->opcode)]);
+            gen_helper_440_tlbre(cpu_gpr[rD(ctx->opcode)], cpu_env,
+                                 t0, cpu_gpr[rA(ctx->opcode)]);
             tcg_temp_free_i32(t0);
         }
         break;
@@ -6051,7 +6057,7 @@ static void gen_tlbsx_440(DisasContext *ctx)
     }
     t0 = tcg_temp_new();
     gen_addr_reg_index(ctx, t0);
-    gen_helper_440_tlbsx(cpu_gpr[rD(ctx->opcode)], t0);
+    gen_helper_440_tlbsx(cpu_gpr[rD(ctx->opcode)], cpu_env, t0);
     tcg_temp_free(t0);
     if (Rc(ctx->opcode)) {
         int l1 = gen_new_label();
@@ -6081,7 +6087,8 @@ static void gen_tlbwe_440(DisasContext *ctx)
     case 2:
         {
             TCGv_i32 t0 = tcg_const_i32(rB(ctx->opcode));
-            gen_helper_440_tlbwe(t0, cpu_gpr[rA(ctx->opcode)], cpu_gpr[rS(ctx->opcode)]);
+            gen_helper_440_tlbwe(cpu_env, t0, cpu_gpr[rA(ctx->opcode)],
+                                 cpu_gpr[rS(ctx->opcode)]);
             tcg_temp_free_i32(t0);
         }
         break;
@@ -6105,7 +6112,7 @@ static void gen_tlbre_booke206(DisasContext *ctx)
         return;
     }
 
-    gen_helper_booke206_tlbre();
+    gen_helper_booke206_tlbre(cpu_env);
 #endif
 }
 
@@ -6129,7 +6136,7 @@ static void gen_tlbsx_booke206(DisasContext *ctx)
     }
 
     tcg_gen_add_tl(t0, t0, cpu_gpr[rB(ctx->opcode)]);
-    gen_helper_booke206_tlbsx(t0);
+    gen_helper_booke206_tlbsx(cpu_env, t0);
 #endif
 }
 
@@ -6144,7 +6151,7 @@ static void gen_tlbwe_booke206(DisasContext *ctx)
         return;
     }
     gen_update_nip(ctx, ctx->nip - 4);
-    gen_helper_booke206_tlbwe();
+    gen_helper_booke206_tlbwe(cpu_env);
 #endif
 }
 
@@ -6162,7 +6169,7 @@ static void gen_tlbivax_booke206(DisasContext *ctx)
     t0 = tcg_temp_new();
     gen_addr_reg_index(ctx, t0);
 
-    gen_helper_booke206_tlbivax(t0);
+    gen_helper_booke206_tlbivax(cpu_env, t0);
 #endif
 }
 
@@ -6182,13 +6189,13 @@ static void gen_tlbilx_booke206(DisasContext *ctx)
 
     switch((ctx->opcode >> 21) & 0x3) {
     case 0:
-        gen_helper_booke206_tlbilx0(t0);
+        gen_helper_booke206_tlbilx0(cpu_env, t0);
         break;
     case 1:
-        gen_helper_booke206_tlbilx1(t0);
+        gen_helper_booke206_tlbilx1(cpu_env, t0);
         break;
     case 3:
-        gen_helper_booke206_tlbilx3(t0);
+        gen_helper_booke206_tlbilx3(cpu_env, t0);
         break;
     default:
         gen_inval_exception(ctx, POWERPC_EXCP_INVAL_INVAL);
diff --git a/target-ppc/translate_init.c b/target-ppc/translate_init.c
index 6f61175..1e15fd9 100644
--- a/target-ppc/translate_init.c
+++ b/target-ppc/translate_init.c
@@ -279,28 +279,28 @@ static void spr_read_ibat_h (void *opaque, int gprn, int sprn)
 static void spr_write_ibatu (void *opaque, int sprn, int gprn)
 {
     TCGv_i32 t0 = tcg_const_i32((sprn - SPR_IBAT0U) / 2);
-    gen_helper_store_ibatu(t0, cpu_gpr[gprn]);
+    gen_helper_store_ibatu(cpu_env, t0, cpu_gpr[gprn]);
     tcg_temp_free_i32(t0);
 }
 
 static void spr_write_ibatu_h (void *opaque, int sprn, int gprn)
 {
     TCGv_i32 t0 = tcg_const_i32(((sprn - SPR_IBAT4U) / 2) + 4);
-    gen_helper_store_ibatu(t0, cpu_gpr[gprn]);
+    gen_helper_store_ibatu(cpu_env, t0, cpu_gpr[gprn]);
     tcg_temp_free_i32(t0);
 }
 
 static void spr_write_ibatl (void *opaque, int sprn, int gprn)
 {
     TCGv_i32 t0 = tcg_const_i32((sprn - SPR_IBAT0L) / 2);
-    gen_helper_store_ibatl(t0, cpu_gpr[gprn]);
+    gen_helper_store_ibatl(cpu_env, t0, cpu_gpr[gprn]);
     tcg_temp_free_i32(t0);
 }
 
 static void spr_write_ibatl_h (void *opaque, int sprn, int gprn)
 {
     TCGv_i32 t0 = tcg_const_i32(((sprn - SPR_IBAT4L) / 2) + 4);
-    gen_helper_store_ibatl(t0, cpu_gpr[gprn]);
+    gen_helper_store_ibatl(cpu_env, t0, cpu_gpr[gprn]);
     tcg_temp_free_i32(t0);
 }
 
@@ -319,28 +319,28 @@ static void spr_read_dbat_h (void *opaque, int gprn, int sprn)
 static void spr_write_dbatu (void *opaque, int sprn, int gprn)
 {
     TCGv_i32 t0 = tcg_const_i32((sprn - SPR_DBAT0U) / 2);
-    gen_helper_store_dbatu(t0, cpu_gpr[gprn]);
+    gen_helper_store_dbatu(cpu_env, t0, cpu_gpr[gprn]);
     tcg_temp_free_i32(t0);
 }
 
 static void spr_write_dbatu_h (void *opaque, int sprn, int gprn)
 {
     TCGv_i32 t0 = tcg_const_i32(((sprn - SPR_DBAT4U) / 2) + 4);
-    gen_helper_store_dbatu(t0, cpu_gpr[gprn]);
+    gen_helper_store_dbatu(cpu_env, t0, cpu_gpr[gprn]);
     tcg_temp_free_i32(t0);
 }
 
 static void spr_write_dbatl (void *opaque, int sprn, int gprn)
 {
     TCGv_i32 t0 = tcg_const_i32((sprn - SPR_DBAT0L) / 2);
-    gen_helper_store_dbatl(t0, cpu_gpr[gprn]);
+    gen_helper_store_dbatl(cpu_env, t0, cpu_gpr[gprn]);
     tcg_temp_free_i32(t0);
 }
 
 static void spr_write_dbatl_h (void *opaque, int sprn, int gprn)
 {
     TCGv_i32 t0 = tcg_const_i32(((sprn - SPR_DBAT4L) / 2) + 4);
-    gen_helper_store_dbatl(t0, cpu_gpr[gprn]);
+    gen_helper_store_dbatl(cpu_env, t0, cpu_gpr[gprn]);
     tcg_temp_free_i32(t0);
 }
 
@@ -421,14 +421,14 @@ static void spr_read_601_ubat (void *opaque, int gprn, int sprn)
 static void spr_write_601_ubatu (void *opaque, int sprn, int gprn)
 {
     TCGv_i32 t0 = tcg_const_i32((sprn - SPR_IBAT0U) / 2);
-    gen_helper_store_601_batl(t0, cpu_gpr[gprn]);
+    gen_helper_store_601_batl(cpu_env, t0, cpu_gpr[gprn]);
     tcg_temp_free_i32(t0);
 }
 
 static void spr_write_601_ubatl (void *opaque, int sprn, int gprn)
 {
     TCGv_i32 t0 = tcg_const_i32((sprn - SPR_IBAT0U) / 2);
-    gen_helper_store_601_batu(t0, cpu_gpr[gprn]);
+    gen_helper_store_601_batu(cpu_env, t0, cpu_gpr[gprn]);
     tcg_temp_free_i32(t0);
 }
 #endif
@@ -1371,14 +1371,14 @@ static void spr_write_e500_l1csr0 (void *opaque, int sprn, int gprn)
 static void spr_write_booke206_mmucsr0 (void *opaque, int sprn, int gprn)
 {
     TCGv_i32 t0 = tcg_const_i32(sprn);
-    gen_helper_booke206_tlbflush(t0);
+    gen_helper_booke206_tlbflush(cpu_env, t0);
     tcg_temp_free_i32(t0);
 }
 
 static void spr_write_booke_pid (void *opaque, int sprn, int gprn)
 {
     TCGv_i32 t0 = tcg_const_i32(sprn);
-    gen_helper_booke_setpid(t0, cpu_gpr[gprn]);
+    gen_helper_booke_setpid(cpu_env, t0, cpu_gpr[gprn]);
     tcg_temp_free_i32(t0);
 }
 #endif
commit ec19c4d14643a38890745d46535d3149fec2033f
Author: Blue Swirl <blauwirbel at gmail.com>
Date:   Wed May 30 04:23:30 2012 +0000

    ppc: Split MMU etc. helpers from op_helper.c
    
    Move MMU, TLB, SLB and BAT ops to mmu_helper.c.
    
    Signed-off-by: Blue Swirl <blauwirbel at gmail.com>
    Signed-off-by: Alexander Graf <agraf at suse.de>
    Signed-off-by: Andreas Färber <afaerber at suse.de>
    Signed-off-by: Alexander Graf <agraf at suse.de>

diff --git a/target-ppc/Makefile.objs b/target-ppc/Makefile.objs
index 5d63400..0f89c2c 100644
--- a/target-ppc/Makefile.objs
+++ b/target-ppc/Makefile.objs
@@ -5,5 +5,7 @@ obj-y += op_helper.o helper.o
 obj-y += excp_helper.o
 obj-y += fpu_helper.o
 obj-y += int_helper.o
+obj-y += mmu_helper.o
 
+$(obj)/mmu_helper.o: QEMU_CFLAGS += $(HELPER_CFLAGS)
 $(obj)/op_helper.o: QEMU_CFLAGS += $(HELPER_CFLAGS)
diff --git a/target-ppc/mmu_helper.c b/target-ppc/mmu_helper.c
new file mode 100644
index 0000000..81800b6
--- /dev/null
+++ b/target-ppc/mmu_helper.c
@@ -0,0 +1,882 @@
+/*
+ *  PowerPC MMU, TLB, SLB and BAT emulation helpers for QEMU.
+ *
+ *  Copyright (c) 2003-2007 Jocelyn Mayer
+ *
+ * This library is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Lesser General Public
+ * License as published by the Free Software Foundation; either
+ * version 2 of the License, or (at your option) any later version.
+ *
+ * This library is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
+ * Lesser General Public License for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public
+ * License along with this library; if not, see <http://www.gnu.org/licenses/>.
+ */
+#include "cpu.h"
+#include "dyngen-exec.h"
+#include "helper.h"
+
+//#define DEBUG_SOFTWARE_TLB
+
+#ifdef DEBUG_SOFTWARE_TLB
+#  define LOG_SWTLB(...) qemu_log(__VA_ARGS__)
+#else
+#  define LOG_SWTLB(...) do { } while (0)
+#endif
+
+/*****************************************************************************/
+/* SPR accesses */
+
+#if !defined(CONFIG_USER_ONLY)
+void helper_store_ibatu(uint32_t nr, target_ulong val)
+{
+    ppc_store_ibatu(env, nr, val);
+}
+
+void helper_store_ibatl(uint32_t nr, target_ulong val)
+{
+    ppc_store_ibatl(env, nr, val);
+}
+
+void helper_store_dbatu(uint32_t nr, target_ulong val)
+{
+    ppc_store_dbatu(env, nr, val);
+}
+
+void helper_store_dbatl(uint32_t nr, target_ulong val)
+{
+    ppc_store_dbatl(env, nr, val);
+}
+
+void helper_store_601_batl(uint32_t nr, target_ulong val)
+{
+    ppc_store_ibatl_601(env, nr, val);
+}
+
+void helper_store_601_batu(uint32_t nr, target_ulong val)
+{
+    ppc_store_ibatu_601(env, nr, val);
+}
+
+/* Segment registers load and store */
+target_ulong helper_load_sr(target_ulong sr_num)
+{
+#if defined(TARGET_PPC64)
+    if (env->mmu_model & POWERPC_MMU_64) {
+        return ppc_load_sr(env, sr_num);
+    }
+#endif
+    return env->sr[sr_num];
+}
+
+void helper_store_sr(target_ulong sr_num, target_ulong val)
+{
+    ppc_store_sr(env, sr_num, val);
+}
+
+/* SLB management */
+#if defined(TARGET_PPC64)
+void helper_store_slb(target_ulong rb, target_ulong rs)
+{
+    if (ppc_store_slb(env, rb, rs) < 0) {
+        helper_raise_exception_err(env, POWERPC_EXCP_PROGRAM,
+                                   POWERPC_EXCP_INVAL);
+    }
+}
+
+target_ulong helper_load_slb_esid(target_ulong rb)
+{
+    target_ulong rt;
+
+    if (ppc_load_slb_esid(env, rb, &rt) < 0) {
+        helper_raise_exception_err(env, POWERPC_EXCP_PROGRAM,
+                                   POWERPC_EXCP_INVAL);
+    }
+    return rt;
+}
+
+target_ulong helper_load_slb_vsid(target_ulong rb)
+{
+    target_ulong rt;
+
+    if (ppc_load_slb_vsid(env, rb, &rt) < 0) {
+        helper_raise_exception_err(env, POWERPC_EXCP_PROGRAM,
+                                   POWERPC_EXCP_INVAL);
+    }
+    return rt;
+}
+
+void helper_slbia(void)
+{
+    ppc_slb_invalidate_all(env);
+}
+
+void helper_slbie(target_ulong addr)
+{
+    ppc_slb_invalidate_one(env, addr);
+}
+
+#endif /* defined(TARGET_PPC64) */
+
+/* TLB management */
+void helper_tlbia(void)
+{
+    ppc_tlb_invalidate_all(env);
+}
+
+void helper_tlbie(target_ulong addr)
+{
+    ppc_tlb_invalidate_one(env, addr);
+}
+
+/* Software driven TLBs management */
+/* PowerPC 602/603 software TLB load instructions helpers */
+static void do_6xx_tlb(target_ulong new_EPN, int is_code)
+{
+    target_ulong RPN, CMP, EPN;
+    int way;
+
+    RPN = env->spr[SPR_RPA];
+    if (is_code) {
+        CMP = env->spr[SPR_ICMP];
+        EPN = env->spr[SPR_IMISS];
+    } else {
+        CMP = env->spr[SPR_DCMP];
+        EPN = env->spr[SPR_DMISS];
+    }
+    way = (env->spr[SPR_SRR1] >> 17) & 1;
+    (void)EPN; /* avoid a compiler warning */
+    LOG_SWTLB("%s: EPN " TARGET_FMT_lx " " TARGET_FMT_lx " PTE0 " TARGET_FMT_lx
+              " PTE1 " TARGET_FMT_lx " way %d\n", __func__, new_EPN, EPN, CMP,
+              RPN, way);
+    /* Store this TLB */
+    ppc6xx_tlb_store(env, (uint32_t)(new_EPN & TARGET_PAGE_MASK),
+                     way, is_code, CMP, RPN);
+}
+
+void helper_6xx_tlbd(target_ulong EPN)
+{
+    do_6xx_tlb(EPN, 0);
+}
+
+void helper_6xx_tlbi(target_ulong EPN)
+{
+    do_6xx_tlb(EPN, 1);
+}
+
+/* PowerPC 74xx software TLB load instructions helpers */
+static void do_74xx_tlb(target_ulong new_EPN, int is_code)
+{
+    target_ulong RPN, CMP, EPN;
+    int way;
+
+    RPN = env->spr[SPR_PTELO];
+    CMP = env->spr[SPR_PTEHI];
+    EPN = env->spr[SPR_TLBMISS] & ~0x3;
+    way = env->spr[SPR_TLBMISS] & 0x3;
+    (void)EPN; /* avoid a compiler warning */
+    LOG_SWTLB("%s: EPN " TARGET_FMT_lx " " TARGET_FMT_lx " PTE0 " TARGET_FMT_lx
+              " PTE1 " TARGET_FMT_lx " way %d\n", __func__, new_EPN, EPN, CMP,
+              RPN, way);
+    /* Store this TLB */
+    ppc6xx_tlb_store(env, (uint32_t)(new_EPN & TARGET_PAGE_MASK),
+                     way, is_code, CMP, RPN);
+}
+
+void helper_74xx_tlbd(target_ulong EPN)
+{
+    do_74xx_tlb(EPN, 0);
+}
+
+void helper_74xx_tlbi(target_ulong EPN)
+{
+    do_74xx_tlb(EPN, 1);
+}
+
+/*****************************************************************************/
+/* PowerPC 601 specific instructions (POWER bridge) */
+
+target_ulong helper_rac(target_ulong addr)
+{
+    mmu_ctx_t ctx;
+    int nb_BATs;
+    target_ulong ret = 0;
+
+    /* We don't have to generate many instances of this instruction,
+     * as rac is supervisor only.
+     */
+    /* XXX: FIX THIS: Pretend we have no BAT */
+    nb_BATs = env->nb_BATs;
+    env->nb_BATs = 0;
+    if (get_physical_address(env, &ctx, addr, 0, ACCESS_INT) == 0) {
+        ret = ctx.raddr;
+    }
+    env->nb_BATs = nb_BATs;
+    return ret;
+}
+
+static inline target_ulong booke_tlb_to_page_size(int size)
+{
+    return 1024 << (2 * size);
+}
+
+static inline int booke_page_size_to_tlb(target_ulong page_size)
+{
+    int size;
+
+    switch (page_size) {
+    case 0x00000400UL:
+        size = 0x0;
+        break;
+    case 0x00001000UL:
+        size = 0x1;
+        break;
+    case 0x00004000UL:
+        size = 0x2;
+        break;
+    case 0x00010000UL:
+        size = 0x3;
+        break;
+    case 0x00040000UL:
+        size = 0x4;
+        break;
+    case 0x00100000UL:
+        size = 0x5;
+        break;
+    case 0x00400000UL:
+        size = 0x6;
+        break;
+    case 0x01000000UL:
+        size = 0x7;
+        break;
+    case 0x04000000UL:
+        size = 0x8;
+        break;
+    case 0x10000000UL:
+        size = 0x9;
+        break;
+    case 0x40000000UL:
+        size = 0xA;
+        break;
+#if defined(TARGET_PPC64)
+    case 0x000100000000ULL:
+        size = 0xB;
+        break;
+    case 0x000400000000ULL:
+        size = 0xC;
+        break;
+    case 0x001000000000ULL:
+        size = 0xD;
+        break;
+    case 0x004000000000ULL:
+        size = 0xE;
+        break;
+    case 0x010000000000ULL:
+        size = 0xF;
+        break;
+#endif
+    default:
+        size = -1;
+        break;
+    }
+
+    return size;
+}
+
+/* Helpers for 4xx TLB management */
+#define PPC4XX_TLB_ENTRY_MASK       0x0000003f  /* Mask for 64 TLB entries */
+
+#define PPC4XX_TLBHI_V              0x00000040
+#define PPC4XX_TLBHI_E              0x00000020
+#define PPC4XX_TLBHI_SIZE_MIN       0
+#define PPC4XX_TLBHI_SIZE_MAX       7
+#define PPC4XX_TLBHI_SIZE_DEFAULT   1
+#define PPC4XX_TLBHI_SIZE_SHIFT     7
+#define PPC4XX_TLBHI_SIZE_MASK      0x00000007
+
+#define PPC4XX_TLBLO_EX             0x00000200
+#define PPC4XX_TLBLO_WR             0x00000100
+#define PPC4XX_TLBLO_ATTR_MASK      0x000000FF
+#define PPC4XX_TLBLO_RPN_MASK       0xFFFFFC00
+
+target_ulong helper_4xx_tlbre_hi(target_ulong entry)
+{
+    ppcemb_tlb_t *tlb;
+    target_ulong ret;
+    int size;
+
+    entry &= PPC4XX_TLB_ENTRY_MASK;
+    tlb = &env->tlb.tlbe[entry];
+    ret = tlb->EPN;
+    if (tlb->prot & PAGE_VALID) {
+        ret |= PPC4XX_TLBHI_V;
+    }
+    size = booke_page_size_to_tlb(tlb->size);
+    if (size < PPC4XX_TLBHI_SIZE_MIN || size > PPC4XX_TLBHI_SIZE_MAX) {
+        size = PPC4XX_TLBHI_SIZE_DEFAULT;
+    }
+    ret |= size << PPC4XX_TLBHI_SIZE_SHIFT;
+    env->spr[SPR_40x_PID] = tlb->PID;
+    return ret;
+}
+
+target_ulong helper_4xx_tlbre_lo(target_ulong entry)
+{
+    ppcemb_tlb_t *tlb;
+    target_ulong ret;
+
+    entry &= PPC4XX_TLB_ENTRY_MASK;
+    tlb = &env->tlb.tlbe[entry];
+    ret = tlb->RPN;
+    if (tlb->prot & PAGE_EXEC) {
+        ret |= PPC4XX_TLBLO_EX;
+    }
+    if (tlb->prot & PAGE_WRITE) {
+        ret |= PPC4XX_TLBLO_WR;
+    }
+    return ret;
+}
+
+void helper_4xx_tlbwe_hi(target_ulong entry, target_ulong val)
+{
+    ppcemb_tlb_t *tlb;
+    target_ulong page, end;
+
+    LOG_SWTLB("%s entry %d val " TARGET_FMT_lx "\n", __func__, (int)entry,
+              val);
+    entry &= PPC4XX_TLB_ENTRY_MASK;
+    tlb = &env->tlb.tlbe[entry];
+    /* Invalidate previous TLB (if it's valid) */
+    if (tlb->prot & PAGE_VALID) {
+        end = tlb->EPN + tlb->size;
+        LOG_SWTLB("%s: invalidate old TLB %d start " TARGET_FMT_lx " end "
+                  TARGET_FMT_lx "\n", __func__, (int)entry, tlb->EPN, end);
+        for (page = tlb->EPN; page < end; page += TARGET_PAGE_SIZE) {
+            tlb_flush_page(env, page);
+        }
+    }
+    tlb->size = booke_tlb_to_page_size((val >> PPC4XX_TLBHI_SIZE_SHIFT)
+                                       & PPC4XX_TLBHI_SIZE_MASK);
+    /* We cannot handle TLB size < TARGET_PAGE_SIZE.
+     * If this ever occurs, one should use the ppcemb target instead
+     * of the ppc or ppc64 one
+     */
+    if ((val & PPC4XX_TLBHI_V) && tlb->size < TARGET_PAGE_SIZE) {
+        cpu_abort(env, "TLB size " TARGET_FMT_lu " < %u "
+                  "are not supported (%d)\n",
+                  tlb->size, TARGET_PAGE_SIZE, (int)((val >> 7) & 0x7));
+    }
+    tlb->EPN = val & ~(tlb->size - 1);
+    if (val & PPC4XX_TLBHI_V) {
+        tlb->prot |= PAGE_VALID;
+        if (val & PPC4XX_TLBHI_E) {
+            /* XXX: TO BE FIXED */
+            cpu_abort(env,
+                      "Little-endian TLB entries are not supported by now\n");
+        }
+    } else {
+        tlb->prot &= ~PAGE_VALID;
+    }
+    tlb->PID = env->spr[SPR_40x_PID]; /* PID */
+    LOG_SWTLB("%s: set up TLB %d RPN " TARGET_FMT_plx " EPN " TARGET_FMT_lx
+              " size " TARGET_FMT_lx " prot %c%c%c%c PID %d\n", __func__,
+              (int)entry, tlb->RPN, tlb->EPN, tlb->size,
+              tlb->prot & PAGE_READ ? 'r' : '-',
+              tlb->prot & PAGE_WRITE ? 'w' : '-',
+              tlb->prot & PAGE_EXEC ? 'x' : '-',
+              tlb->prot & PAGE_VALID ? 'v' : '-', (int)tlb->PID);
+    /* Invalidate new TLB (if valid) */
+    if (tlb->prot & PAGE_VALID) {
+        end = tlb->EPN + tlb->size;
+        LOG_SWTLB("%s: invalidate TLB %d start " TARGET_FMT_lx " end "
+                  TARGET_FMT_lx "\n", __func__, (int)entry, tlb->EPN, end);
+        for (page = tlb->EPN; page < end; page += TARGET_PAGE_SIZE) {
+            tlb_flush_page(env, page);
+        }
+    }
+}
+
+void helper_4xx_tlbwe_lo(target_ulong entry, target_ulong val)
+{
+    ppcemb_tlb_t *tlb;
+
+    LOG_SWTLB("%s entry %i val " TARGET_FMT_lx "\n", __func__, (int)entry,
+              val);
+    entry &= PPC4XX_TLB_ENTRY_MASK;
+    tlb = &env->tlb.tlbe[entry];
+    tlb->attr = val & PPC4XX_TLBLO_ATTR_MASK;
+    tlb->RPN = val & PPC4XX_TLBLO_RPN_MASK;
+    tlb->prot = PAGE_READ;
+    if (val & PPC4XX_TLBLO_EX) {
+        tlb->prot |= PAGE_EXEC;
+    }
+    if (val & PPC4XX_TLBLO_WR) {
+        tlb->prot |= PAGE_WRITE;
+    }
+    LOG_SWTLB("%s: set up TLB %d RPN " TARGET_FMT_plx " EPN " TARGET_FMT_lx
+              " size " TARGET_FMT_lx " prot %c%c%c%c PID %d\n", __func__,
+              (int)entry, tlb->RPN, tlb->EPN, tlb->size,
+              tlb->prot & PAGE_READ ? 'r' : '-',
+              tlb->prot & PAGE_WRITE ? 'w' : '-',
+              tlb->prot & PAGE_EXEC ? 'x' : '-',
+              tlb->prot & PAGE_VALID ? 'v' : '-', (int)tlb->PID);
+}
+
+target_ulong helper_4xx_tlbsx(target_ulong address)
+{
+    return ppcemb_tlb_search(env, address, env->spr[SPR_40x_PID]);
+}
+
+/* PowerPC 440 TLB management */
+void helper_440_tlbwe(uint32_t word, target_ulong entry, target_ulong value)
+{
+    ppcemb_tlb_t *tlb;
+    target_ulong EPN, RPN, size;
+    int do_flush_tlbs;
+
+    LOG_SWTLB("%s word %d entry %d value " TARGET_FMT_lx "\n",
+              __func__, word, (int)entry, value);
+    do_flush_tlbs = 0;
+    entry &= 0x3F;
+    tlb = &env->tlb.tlbe[entry];
+    switch (word) {
+    default:
+        /* Just here to please gcc */
+    case 0:
+        EPN = value & 0xFFFFFC00;
+        if ((tlb->prot & PAGE_VALID) && EPN != tlb->EPN) {
+            do_flush_tlbs = 1;
+        }
+        tlb->EPN = EPN;
+        size = booke_tlb_to_page_size((value >> 4) & 0xF);
+        if ((tlb->prot & PAGE_VALID) && tlb->size < size) {
+            do_flush_tlbs = 1;
+        }
+        tlb->size = size;
+        tlb->attr &= ~0x1;
+        tlb->attr |= (value >> 8) & 1;
+        if (value & 0x200) {
+            tlb->prot |= PAGE_VALID;
+        } else {
+            if (tlb->prot & PAGE_VALID) {
+                tlb->prot &= ~PAGE_VALID;
+                do_flush_tlbs = 1;
+            }
+        }
+        tlb->PID = env->spr[SPR_440_MMUCR] & 0x000000FF;
+        if (do_flush_tlbs) {
+            tlb_flush(env, 1);
+        }
+        break;
+    case 1:
+        RPN = value & 0xFFFFFC0F;
+        if ((tlb->prot & PAGE_VALID) && tlb->RPN != RPN) {
+            tlb_flush(env, 1);
+        }
+        tlb->RPN = RPN;
+        break;
+    case 2:
+        tlb->attr = (tlb->attr & 0x1) | (value & 0x0000FF00);
+        tlb->prot = tlb->prot & PAGE_VALID;
+        if (value & 0x1) {
+            tlb->prot |= PAGE_READ << 4;
+        }
+        if (value & 0x2) {
+            tlb->prot |= PAGE_WRITE << 4;
+        }
+        if (value & 0x4) {
+            tlb->prot |= PAGE_EXEC << 4;
+        }
+        if (value & 0x8) {
+            tlb->prot |= PAGE_READ;
+        }
+        if (value & 0x10) {
+            tlb->prot |= PAGE_WRITE;
+        }
+        if (value & 0x20) {
+            tlb->prot |= PAGE_EXEC;
+        }
+        break;
+    }
+}
+
+target_ulong helper_440_tlbre(uint32_t word, target_ulong entry)
+{
+    ppcemb_tlb_t *tlb;
+    target_ulong ret;
+    int size;
+
+    entry &= 0x3F;
+    tlb = &env->tlb.tlbe[entry];
+    switch (word) {
+    default:
+        /* Just here to please gcc */
+    case 0:
+        ret = tlb->EPN;
+        size = booke_page_size_to_tlb(tlb->size);
+        if (size < 0 || size > 0xF) {
+            size = 1;
+        }
+        ret |= size << 4;
+        if (tlb->attr & 0x1) {
+            ret |= 0x100;
+        }
+        if (tlb->prot & PAGE_VALID) {
+            ret |= 0x200;
+        }
+        env->spr[SPR_440_MMUCR] &= ~0x000000FF;
+        env->spr[SPR_440_MMUCR] |= tlb->PID;
+        break;
+    case 1:
+        ret = tlb->RPN;
+        break;
+    case 2:
+        ret = tlb->attr & ~0x1;
+        if (tlb->prot & (PAGE_READ << 4)) {
+            ret |= 0x1;
+        }
+        if (tlb->prot & (PAGE_WRITE << 4)) {
+            ret |= 0x2;
+        }
+        if (tlb->prot & (PAGE_EXEC << 4)) {
+            ret |= 0x4;
+        }
+        if (tlb->prot & PAGE_READ) {
+            ret |= 0x8;
+        }
+        if (tlb->prot & PAGE_WRITE) {
+            ret |= 0x10;
+        }
+        if (tlb->prot & PAGE_EXEC) {
+            ret |= 0x20;
+        }
+        break;
+    }
+    return ret;
+}
+
+target_ulong helper_440_tlbsx(target_ulong address)
+{
+    return ppcemb_tlb_search(env, address, env->spr[SPR_440_MMUCR] & 0xFF);
+}
+
+/* PowerPC BookE 2.06 TLB management */
+
+static ppcmas_tlb_t *booke206_cur_tlb(CPUPPCState *env)
+{
+    uint32_t tlbncfg = 0;
+    int esel = (env->spr[SPR_BOOKE_MAS0] & MAS0_ESEL_MASK) >> MAS0_ESEL_SHIFT;
+    int ea = (env->spr[SPR_BOOKE_MAS2] & MAS2_EPN_MASK);
+    int tlb;
+
+    tlb = (env->spr[SPR_BOOKE_MAS0] & MAS0_TLBSEL_MASK) >> MAS0_TLBSEL_SHIFT;
+    tlbncfg = env->spr[SPR_BOOKE_TLB0CFG + tlb];
+
+    if ((tlbncfg & TLBnCFG_HES) && (env->spr[SPR_BOOKE_MAS0] & MAS0_HES)) {
+        cpu_abort(env, "we don't support HES yet\n");
+    }
+
+    return booke206_get_tlbm(env, tlb, ea, esel);
+}
+
+void helper_booke_setpid(uint32_t pidn, target_ulong pid)
+{
+    env->spr[pidn] = pid;
+    /* changing PIDs mean we're in a different address space now */
+    tlb_flush(env, 1);
+}
+
+void helper_booke206_tlbwe(void)
+{
+    uint32_t tlbncfg, tlbn;
+    ppcmas_tlb_t *tlb;
+    uint32_t size_tlb, size_ps;
+
+    switch (env->spr[SPR_BOOKE_MAS0] & MAS0_WQ_MASK) {
+    case MAS0_WQ_ALWAYS:
+        /* good to go, write that entry */
+        break;
+    case MAS0_WQ_COND:
+        /* XXX check if reserved */
+        if (0) {
+            return;
+        }
+        break;
+    case MAS0_WQ_CLR_RSRV:
+        /* XXX clear entry */
+        return;
+    default:
+        /* no idea what to do */
+        return;
+    }
+
+    if (((env->spr[SPR_BOOKE_MAS0] & MAS0_ATSEL) == MAS0_ATSEL_LRAT) &&
+        !msr_gs) {
+        /* XXX we don't support direct LRAT setting yet */
+        fprintf(stderr, "cpu: don't support LRAT setting yet\n");
+        return;
+    }
+
+    tlbn = (env->spr[SPR_BOOKE_MAS0] & MAS0_TLBSEL_MASK) >> MAS0_TLBSEL_SHIFT;
+    tlbncfg = env->spr[SPR_BOOKE_TLB0CFG + tlbn];
+
+    tlb = booke206_cur_tlb(env);
+
+    if (!tlb) {
+        helper_raise_exception_err(env, POWERPC_EXCP_PROGRAM,
+                                   POWERPC_EXCP_INVAL |
+                                   POWERPC_EXCP_INVAL_INVAL);
+    }
+
+    /* check that we support the targeted size */
+    size_tlb = (env->spr[SPR_BOOKE_MAS1] & MAS1_TSIZE_MASK) >> MAS1_TSIZE_SHIFT;
+    size_ps = booke206_tlbnps(env, tlbn);
+    if ((env->spr[SPR_BOOKE_MAS1] & MAS1_VALID) && (tlbncfg & TLBnCFG_AVAIL) &&
+        !(size_ps & (1 << size_tlb))) {
+        helper_raise_exception_err(env, POWERPC_EXCP_PROGRAM,
+                                   POWERPC_EXCP_INVAL |
+                                   POWERPC_EXCP_INVAL_INVAL);
+    }
+
+    if (msr_gs) {
+        cpu_abort(env, "missing HV implementation\n");
+    }
+    tlb->mas7_3 = ((uint64_t)env->spr[SPR_BOOKE_MAS7] << 32) |
+        env->spr[SPR_BOOKE_MAS3];
+    tlb->mas1 = env->spr[SPR_BOOKE_MAS1];
+
+    /* MAV 1.0 only */
+    if (!(tlbncfg & TLBnCFG_AVAIL)) {
+        /* force !AVAIL TLB entries to correct page size */
+        tlb->mas1 &= ~MAS1_TSIZE_MASK;
+        /* XXX can be configured in MMUCSR0 */
+        tlb->mas1 |= (tlbncfg & TLBnCFG_MINSIZE) >> 12;
+    }
+
+    /* XXX needs to change when supporting 64-bit e500 */
+    tlb->mas2 = env->spr[SPR_BOOKE_MAS2] & 0xffffffff;
+
+    if (!(tlbncfg & TLBnCFG_IPROT)) {
+        /* no IPROT supported by TLB */
+        tlb->mas1 &= ~MAS1_IPROT;
+    }
+
+    if (booke206_tlb_to_page_size(env, tlb) == TARGET_PAGE_SIZE) {
+        tlb_flush_page(env, tlb->mas2 & MAS2_EPN_MASK);
+    } else {
+        tlb_flush(env, 1);
+    }
+}
+
+static inline void booke206_tlb_to_mas(CPUPPCState *env, ppcmas_tlb_t *tlb)
+{
+    int tlbn = booke206_tlbm_to_tlbn(env, tlb);
+    int way = booke206_tlbm_to_way(env, tlb);
+
+    env->spr[SPR_BOOKE_MAS0] = tlbn << MAS0_TLBSEL_SHIFT;
+    env->spr[SPR_BOOKE_MAS0] |= way << MAS0_ESEL_SHIFT;
+    env->spr[SPR_BOOKE_MAS0] |= env->last_way << MAS0_NV_SHIFT;
+
+    env->spr[SPR_BOOKE_MAS1] = tlb->mas1;
+    env->spr[SPR_BOOKE_MAS2] = tlb->mas2;
+    env->spr[SPR_BOOKE_MAS3] = tlb->mas7_3;
+    env->spr[SPR_BOOKE_MAS7] = tlb->mas7_3 >> 32;
+}
+
+void helper_booke206_tlbre(void)
+{
+    ppcmas_tlb_t *tlb = NULL;
+
+    tlb = booke206_cur_tlb(env);
+    if (!tlb) {
+        env->spr[SPR_BOOKE_MAS1] = 0;
+    } else {
+        booke206_tlb_to_mas(env, tlb);
+    }
+}
+
+void helper_booke206_tlbsx(target_ulong address)
+{
+    ppcmas_tlb_t *tlb = NULL;
+    int i, j;
+    target_phys_addr_t raddr;
+    uint32_t spid, sas;
+
+    spid = (env->spr[SPR_BOOKE_MAS6] & MAS6_SPID_MASK) >> MAS6_SPID_SHIFT;
+    sas = env->spr[SPR_BOOKE_MAS6] & MAS6_SAS;
+
+    for (i = 0; i < BOOKE206_MAX_TLBN; i++) {
+        int ways = booke206_tlb_ways(env, i);
+
+        for (j = 0; j < ways; j++) {
+            tlb = booke206_get_tlbm(env, i, address, j);
+
+            if (!tlb) {
+                continue;
+            }
+
+            if (ppcmas_tlb_check(env, tlb, &raddr, address, spid)) {
+                continue;
+            }
+
+            if (sas != ((tlb->mas1 & MAS1_TS) >> MAS1_TS_SHIFT)) {
+                continue;
+            }
+
+            booke206_tlb_to_mas(env, tlb);
+            return;
+        }
+    }
+
+    /* no entry found, fill with defaults */
+    env->spr[SPR_BOOKE_MAS0] = env->spr[SPR_BOOKE_MAS4] & MAS4_TLBSELD_MASK;
+    env->spr[SPR_BOOKE_MAS1] = env->spr[SPR_BOOKE_MAS4] & MAS4_TSIZED_MASK;
+    env->spr[SPR_BOOKE_MAS2] = env->spr[SPR_BOOKE_MAS4] & MAS4_WIMGED_MASK;
+    env->spr[SPR_BOOKE_MAS3] = 0;
+    env->spr[SPR_BOOKE_MAS7] = 0;
+
+    if (env->spr[SPR_BOOKE_MAS6] & MAS6_SAS) {
+        env->spr[SPR_BOOKE_MAS1] |= MAS1_TS;
+    }
+
+    env->spr[SPR_BOOKE_MAS1] |= (env->spr[SPR_BOOKE_MAS6] >> 16)
+        << MAS1_TID_SHIFT;
+
+    /* next victim logic */
+    env->spr[SPR_BOOKE_MAS0] |= env->last_way << MAS0_ESEL_SHIFT;
+    env->last_way++;
+    env->last_way &= booke206_tlb_ways(env, 0) - 1;
+    env->spr[SPR_BOOKE_MAS0] |= env->last_way << MAS0_NV_SHIFT;
+}
+
+static inline void booke206_invalidate_ea_tlb(CPUPPCState *env, int tlbn,
+                                              uint32_t ea)
+{
+    int i;
+    int ways = booke206_tlb_ways(env, tlbn);
+    target_ulong mask;
+
+    for (i = 0; i < ways; i++) {
+        ppcmas_tlb_t *tlb = booke206_get_tlbm(env, tlbn, ea, i);
+        if (!tlb) {
+            continue;
+        }
+        mask = ~(booke206_tlb_to_page_size(env, tlb) - 1);
+        if (((tlb->mas2 & MAS2_EPN_MASK) == (ea & mask)) &&
+            !(tlb->mas1 & MAS1_IPROT)) {
+            tlb->mas1 &= ~MAS1_VALID;
+        }
+    }
+}
+
+void helper_booke206_tlbivax(target_ulong address)
+{
+    if (address & 0x4) {
+        /* flush all entries */
+        if (address & 0x8) {
+            /* flush all of TLB1 */
+            booke206_flush_tlb(env, BOOKE206_FLUSH_TLB1, 1);
+        } else {
+            /* flush all of TLB0 */
+            booke206_flush_tlb(env, BOOKE206_FLUSH_TLB0, 0);
+        }
+        return;
+    }
+
+    if (address & 0x8) {
+        /* flush TLB1 entries */
+        booke206_invalidate_ea_tlb(env, 1, address);
+        tlb_flush(env, 1);
+    } else {
+        /* flush TLB0 entries */
+        booke206_invalidate_ea_tlb(env, 0, address);
+        tlb_flush_page(env, address & MAS2_EPN_MASK);
+    }
+}
+
+void helper_booke206_tlbilx0(target_ulong address)
+{
+    /* XXX missing LPID handling */
+    booke206_flush_tlb(env, -1, 1);
+}
+
+void helper_booke206_tlbilx1(target_ulong address)
+{
+    int i, j;
+    int tid = (env->spr[SPR_BOOKE_MAS6] & MAS6_SPID);
+    ppcmas_tlb_t *tlb = env->tlb.tlbm;
+    int tlb_size;
+
+    /* XXX missing LPID handling */
+    for (i = 0; i < BOOKE206_MAX_TLBN; i++) {
+        tlb_size = booke206_tlb_size(env, i);
+        for (j = 0; j < tlb_size; j++) {
+            if (!(tlb[j].mas1 & MAS1_IPROT) &&
+                ((tlb[j].mas1 & MAS1_TID_MASK) == tid)) {
+                tlb[j].mas1 &= ~MAS1_VALID;
+            }
+        }
+        tlb += booke206_tlb_size(env, i);
+    }
+    tlb_flush(env, 1);
+}
+
+void helper_booke206_tlbilx3(target_ulong address)
+{
+    int i, j;
+    ppcmas_tlb_t *tlb;
+    int tid = (env->spr[SPR_BOOKE_MAS6] & MAS6_SPID);
+    int pid = tid >> MAS6_SPID_SHIFT;
+    int sgs = env->spr[SPR_BOOKE_MAS5] & MAS5_SGS;
+    int ind = (env->spr[SPR_BOOKE_MAS6] & MAS6_SIND) ? MAS1_IND : 0;
+    /* XXX check for unsupported isize and raise an invalid opcode then */
+    int size = env->spr[SPR_BOOKE_MAS6] & MAS6_ISIZE_MASK;
+    /* XXX implement MAV2 handling */
+    bool mav2 = false;
+
+    /* XXX missing LPID handling */
+    /* flush by pid and ea */
+    for (i = 0; i < BOOKE206_MAX_TLBN; i++) {
+        int ways = booke206_tlb_ways(env, i);
+
+        for (j = 0; j < ways; j++) {
+            tlb = booke206_get_tlbm(env, i, address, j);
+            if (!tlb) {
+                continue;
+            }
+            if ((ppcmas_tlb_check(env, tlb, NULL, address, pid) != 0) ||
+                (tlb->mas1 & MAS1_IPROT) ||
+                ((tlb->mas1 & MAS1_IND) != ind) ||
+                ((tlb->mas8 & MAS8_TGS) != sgs)) {
+                continue;
+            }
+            if (mav2 && ((tlb->mas1 & MAS1_TSIZE_MASK) != size)) {
+                /* XXX only check when MMUCFG[TWC] || TLBnCFG[HES] */
+                continue;
+            }
+            /* XXX e500mc doesn't match SAS, but other cores might */
+            tlb->mas1 &= ~MAS1_VALID;
+        }
+    }
+    tlb_flush(env, 1);
+}
+
+void helper_booke206_tlbflush(uint32_t type)
+{
+    int flags = 0;
+
+    if (type & 2) {
+        flags |= BOOKE206_FLUSH_TLB1;
+    }
+
+    if (type & 4) {
+        flags |= BOOKE206_FLUSH_TLB0;
+    }
+
+    booke206_flush_tlb(env, flags, 1);
+}
+#endif
diff --git a/target-ppc/op_helper.c b/target-ppc/op_helper.c
index 55b9e9d..c854c71 100644
--- a/target-ppc/op_helper.c
+++ b/target-ppc/op_helper.c
@@ -29,13 +29,6 @@
 #endif /* !defined(CONFIG_USER_ONLY) */
 
 //#define DEBUG_OP
-//#define DEBUG_SOFTWARE_TLB
-
-#ifdef DEBUG_SOFTWARE_TLB
-#  define LOG_SWTLB(...) qemu_log(__VA_ARGS__)
-#else
-#  define LOG_SWTLB(...) do { } while (0)
-#endif
 
 /*****************************************************************************/
 /* SPR accesses */
@@ -196,36 +189,6 @@ void helper_store_booke_tsr(target_ulong val)
 {
     store_booke_tsr(env, val);
 }
-
-void helper_store_ibatu(uint32_t nr, target_ulong val)
-{
-    ppc_store_ibatu(env, nr, val);
-}
-
-void helper_store_ibatl(uint32_t nr, target_ulong val)
-{
-    ppc_store_ibatl(env, nr, val);
-}
-
-void helper_store_dbatu(uint32_t nr, target_ulong val)
-{
-    ppc_store_dbatu(env, nr, val);
-}
-
-void helper_store_dbatl(uint32_t nr, target_ulong val)
-{
-    ppc_store_dbatl(env, nr, val);
-}
-
-void helper_store_601_batl(uint32_t nr, target_ulong val)
-{
-    ppc_store_ibatl_601(env, nr, val);
-}
-
-void helper_store_601_batu(uint32_t nr, target_ulong val)
-{
-    ppc_store_ibatu_601(env, nr, val);
-}
 #endif
 
 /*****************************************************************************/
@@ -417,27 +380,6 @@ target_ulong helper_clcs(uint32_t arg)
     }
 }
 
-#if !defined(CONFIG_USER_ONLY)
-target_ulong helper_rac(target_ulong addr)
-{
-    mmu_ctx_t ctx;
-    int nb_BATs;
-    target_ulong ret = 0;
-
-    /* We don't have to generate many instances of this instruction,
-     * as rac is supervisor only.
-     */
-    /* XXX: FIX THIS: Pretend we have no BAT */
-    nb_BATs = env->nb_BATs;
-    env->nb_BATs = 0;
-    if (get_physical_address(env, &ctx, addr, 0, ACCESS_INT) == 0) {
-        ret = ctx.raddr;
-    }
-    env->nb_BATs = nb_BATs;
-    return ret;
-}
-#endif
-
 /*****************************************************************************/
 /* Embedded PowerPC specific helpers */
 
@@ -578,800 +520,4 @@ void tlb_fill(CPUPPCState *env1, target_ulong addr, int is_write, int mmu_idx,
     }
     env = saved_env;
 }
-
-/* Segment registers load and store */
-target_ulong helper_load_sr(target_ulong sr_num)
-{
-#if defined(TARGET_PPC64)
-    if (env->mmu_model & POWERPC_MMU_64) {
-        return ppc_load_sr(env, sr_num);
-    }
-#endif
-    return env->sr[sr_num];
-}
-
-void helper_store_sr(target_ulong sr_num, target_ulong val)
-{
-    ppc_store_sr(env, sr_num, val);
-}
-
-/* SLB management */
-#if defined(TARGET_PPC64)
-void helper_store_slb(target_ulong rb, target_ulong rs)
-{
-    if (ppc_store_slb(env, rb, rs) < 0) {
-        helper_raise_exception_err(env, POWERPC_EXCP_PROGRAM,
-                                   POWERPC_EXCP_INVAL);
-    }
-}
-
-target_ulong helper_load_slb_esid(target_ulong rb)
-{
-    target_ulong rt;
-
-    if (ppc_load_slb_esid(env, rb, &rt) < 0) {
-        helper_raise_exception_err(env, POWERPC_EXCP_PROGRAM,
-                                   POWERPC_EXCP_INVAL);
-    }
-    return rt;
-}
-
-target_ulong helper_load_slb_vsid(target_ulong rb)
-{
-    target_ulong rt;
-
-    if (ppc_load_slb_vsid(env, rb, &rt) < 0) {
-        helper_raise_exception_err(env, POWERPC_EXCP_PROGRAM,
-                                   POWERPC_EXCP_INVAL);
-    }
-    return rt;
-}
-
-void helper_slbia(void)
-{
-    ppc_slb_invalidate_all(env);
-}
-
-void helper_slbie(target_ulong addr)
-{
-    ppc_slb_invalidate_one(env, addr);
-}
-
-#endif /* defined(TARGET_PPC64) */
-
-/* TLB management */
-void helper_tlbia(void)
-{
-    ppc_tlb_invalidate_all(env);
-}
-
-void helper_tlbie(target_ulong addr)
-{
-    ppc_tlb_invalidate_one(env, addr);
-}
-
-/* Software driven TLBs management */
-/* PowerPC 602/603 software TLB load instructions helpers */
-static void do_6xx_tlb(target_ulong new_EPN, int is_code)
-{
-    target_ulong RPN, CMP, EPN;
-    int way;
-
-    RPN = env->spr[SPR_RPA];
-    if (is_code) {
-        CMP = env->spr[SPR_ICMP];
-        EPN = env->spr[SPR_IMISS];
-    } else {
-        CMP = env->spr[SPR_DCMP];
-        EPN = env->spr[SPR_DMISS];
-    }
-    way = (env->spr[SPR_SRR1] >> 17) & 1;
-    (void)EPN; /* avoid a compiler warning */
-    LOG_SWTLB("%s: EPN " TARGET_FMT_lx " " TARGET_FMT_lx " PTE0 " TARGET_FMT_lx
-              " PTE1 " TARGET_FMT_lx " way %d\n", __func__, new_EPN, EPN, CMP,
-              RPN, way);
-    /* Store this TLB */
-    ppc6xx_tlb_store(env, (uint32_t)(new_EPN & TARGET_PAGE_MASK),
-                     way, is_code, CMP, RPN);
-}
-
-void helper_6xx_tlbd(target_ulong EPN)
-{
-    do_6xx_tlb(EPN, 0);
-}
-
-void helper_6xx_tlbi(target_ulong EPN)
-{
-    do_6xx_tlb(EPN, 1);
-}
-
-/* PowerPC 74xx software TLB load instructions helpers */
-static void do_74xx_tlb(target_ulong new_EPN, int is_code)
-{
-    target_ulong RPN, CMP, EPN;
-    int way;
-
-    RPN = env->spr[SPR_PTELO];
-    CMP = env->spr[SPR_PTEHI];
-    EPN = env->spr[SPR_TLBMISS] & ~0x3;
-    way = env->spr[SPR_TLBMISS] & 0x3;
-    (void)EPN; /* avoid a compiler warning */
-    LOG_SWTLB("%s: EPN " TARGET_FMT_lx " " TARGET_FMT_lx " PTE0 " TARGET_FMT_lx
-              " PTE1 " TARGET_FMT_lx " way %d\n", __func__, new_EPN, EPN, CMP,
-              RPN, way);
-    /* Store this TLB */
-    ppc6xx_tlb_store(env, (uint32_t)(new_EPN & TARGET_PAGE_MASK),
-                     way, is_code, CMP, RPN);
-}
-
-void helper_74xx_tlbd(target_ulong EPN)
-{
-    do_74xx_tlb(EPN, 0);
-}
-
-void helper_74xx_tlbi(target_ulong EPN)
-{
-    do_74xx_tlb(EPN, 1);
-}
-
-static inline target_ulong booke_tlb_to_page_size(int size)
-{
-    return 1024 << (2 * size);
-}
-
-static inline int booke_page_size_to_tlb(target_ulong page_size)
-{
-    int size;
-
-    switch (page_size) {
-    case 0x00000400UL:
-        size = 0x0;
-        break;
-    case 0x00001000UL:
-        size = 0x1;
-        break;
-    case 0x00004000UL:
-        size = 0x2;
-        break;
-    case 0x00010000UL:
-        size = 0x3;
-        break;
-    case 0x00040000UL:
-        size = 0x4;
-        break;
-    case 0x00100000UL:
-        size = 0x5;
-        break;
-    case 0x00400000UL:
-        size = 0x6;
-        break;
-    case 0x01000000UL:
-        size = 0x7;
-        break;
-    case 0x04000000UL:
-        size = 0x8;
-        break;
-    case 0x10000000UL:
-        size = 0x9;
-        break;
-    case 0x40000000UL:
-        size = 0xA;
-        break;
-#if defined(TARGET_PPC64)
-    case 0x000100000000ULL:
-        size = 0xB;
-        break;
-    case 0x000400000000ULL:
-        size = 0xC;
-        break;
-    case 0x001000000000ULL:
-        size = 0xD;
-        break;
-    case 0x004000000000ULL:
-        size = 0xE;
-        break;
-    case 0x010000000000ULL:
-        size = 0xF;
-        break;
-#endif
-    default:
-        size = -1;
-        break;
-    }
-
-    return size;
-}
-
-/* Helpers for 4xx TLB management */
-#define PPC4XX_TLB_ENTRY_MASK       0x0000003f  /* Mask for 64 TLB entries */
-
-#define PPC4XX_TLBHI_V              0x00000040
-#define PPC4XX_TLBHI_E              0x00000020
-#define PPC4XX_TLBHI_SIZE_MIN       0
-#define PPC4XX_TLBHI_SIZE_MAX       7
-#define PPC4XX_TLBHI_SIZE_DEFAULT   1
-#define PPC4XX_TLBHI_SIZE_SHIFT     7
-#define PPC4XX_TLBHI_SIZE_MASK      0x00000007
-
-#define PPC4XX_TLBLO_EX             0x00000200
-#define PPC4XX_TLBLO_WR             0x00000100
-#define PPC4XX_TLBLO_ATTR_MASK      0x000000FF
-#define PPC4XX_TLBLO_RPN_MASK       0xFFFFFC00
-
-target_ulong helper_4xx_tlbre_hi(target_ulong entry)
-{
-    ppcemb_tlb_t *tlb;
-    target_ulong ret;
-    int size;
-
-    entry &= PPC4XX_TLB_ENTRY_MASK;
-    tlb = &env->tlb.tlbe[entry];
-    ret = tlb->EPN;
-    if (tlb->prot & PAGE_VALID) {
-        ret |= PPC4XX_TLBHI_V;
-    }
-    size = booke_page_size_to_tlb(tlb->size);
-    if (size < PPC4XX_TLBHI_SIZE_MIN || size > PPC4XX_TLBHI_SIZE_MAX) {
-        size = PPC4XX_TLBHI_SIZE_DEFAULT;
-    }
-    ret |= size << PPC4XX_TLBHI_SIZE_SHIFT;
-    env->spr[SPR_40x_PID] = tlb->PID;
-    return ret;
-}
-
-target_ulong helper_4xx_tlbre_lo(target_ulong entry)
-{
-    ppcemb_tlb_t *tlb;
-    target_ulong ret;
-
-    entry &= PPC4XX_TLB_ENTRY_MASK;
-    tlb = &env->tlb.tlbe[entry];
-    ret = tlb->RPN;
-    if (tlb->prot & PAGE_EXEC) {
-        ret |= PPC4XX_TLBLO_EX;
-    }
-    if (tlb->prot & PAGE_WRITE) {
-        ret |= PPC4XX_TLBLO_WR;
-    }
-    return ret;
-}
-
-void helper_4xx_tlbwe_hi(target_ulong entry, target_ulong val)
-{
-    ppcemb_tlb_t *tlb;
-    target_ulong page, end;
-
-    LOG_SWTLB("%s entry %d val " TARGET_FMT_lx "\n", __func__, (int)entry,
-              val);
-    entry &= PPC4XX_TLB_ENTRY_MASK;
-    tlb = &env->tlb.tlbe[entry];
-    /* Invalidate previous TLB (if it's valid) */
-    if (tlb->prot & PAGE_VALID) {
-        end = tlb->EPN + tlb->size;
-        LOG_SWTLB("%s: invalidate old TLB %d start " TARGET_FMT_lx " end "
-                  TARGET_FMT_lx "\n", __func__, (int)entry, tlb->EPN, end);
-        for (page = tlb->EPN; page < end; page += TARGET_PAGE_SIZE) {
-            tlb_flush_page(env, page);
-        }
-    }
-    tlb->size = booke_tlb_to_page_size((val >> PPC4XX_TLBHI_SIZE_SHIFT)
-                                       & PPC4XX_TLBHI_SIZE_MASK);
-    /* We cannot handle TLB size < TARGET_PAGE_SIZE.
-     * If this ever occurs, one should use the ppcemb target instead
-     * of the ppc or ppc64 one
-     */
-    if ((val & PPC4XX_TLBHI_V) && tlb->size < TARGET_PAGE_SIZE) {
-        cpu_abort(env, "TLB size " TARGET_FMT_lu " < %u "
-                  "are not supported (%d)\n",
-                  tlb->size, TARGET_PAGE_SIZE, (int)((val >> 7) & 0x7));
-    }
-    tlb->EPN = val & ~(tlb->size - 1);
-    if (val & PPC4XX_TLBHI_V) {
-        tlb->prot |= PAGE_VALID;
-        if (val & PPC4XX_TLBHI_E) {
-            /* XXX: TO BE FIXED */
-            cpu_abort(env,
-                      "Little-endian TLB entries are not supported by now\n");
-        }
-    } else {
-        tlb->prot &= ~PAGE_VALID;
-    }
-    tlb->PID = env->spr[SPR_40x_PID]; /* PID */
-    LOG_SWTLB("%s: set up TLB %d RPN " TARGET_FMT_plx " EPN " TARGET_FMT_lx
-              " size " TARGET_FMT_lx " prot %c%c%c%c PID %d\n", __func__,
-              (int)entry, tlb->RPN, tlb->EPN, tlb->size,
-              tlb->prot & PAGE_READ ? 'r' : '-',
-              tlb->prot & PAGE_WRITE ? 'w' : '-',
-              tlb->prot & PAGE_EXEC ? 'x' : '-',
-              tlb->prot & PAGE_VALID ? 'v' : '-', (int)tlb->PID);
-    /* Invalidate new TLB (if valid) */
-    if (tlb->prot & PAGE_VALID) {
-        end = tlb->EPN + tlb->size;
-        LOG_SWTLB("%s: invalidate TLB %d start " TARGET_FMT_lx " end "
-                  TARGET_FMT_lx "\n", __func__, (int)entry, tlb->EPN, end);
-        for (page = tlb->EPN; page < end; page += TARGET_PAGE_SIZE) {
-            tlb_flush_page(env, page);
-        }
-    }
-}
-
-void helper_4xx_tlbwe_lo(target_ulong entry, target_ulong val)
-{
-    ppcemb_tlb_t *tlb;
-
-    LOG_SWTLB("%s entry %i val " TARGET_FMT_lx "\n", __func__, (int)entry,
-              val);
-    entry &= PPC4XX_TLB_ENTRY_MASK;
-    tlb = &env->tlb.tlbe[entry];
-    tlb->attr = val & PPC4XX_TLBLO_ATTR_MASK;
-    tlb->RPN = val & PPC4XX_TLBLO_RPN_MASK;
-    tlb->prot = PAGE_READ;
-    if (val & PPC4XX_TLBLO_EX) {
-        tlb->prot |= PAGE_EXEC;
-    }
-    if (val & PPC4XX_TLBLO_WR) {
-        tlb->prot |= PAGE_WRITE;
-    }
-    LOG_SWTLB("%s: set up TLB %d RPN " TARGET_FMT_plx " EPN " TARGET_FMT_lx
-              " size " TARGET_FMT_lx " prot %c%c%c%c PID %d\n", __func__,
-              (int)entry, tlb->RPN, tlb->EPN, tlb->size,
-              tlb->prot & PAGE_READ ? 'r' : '-',
-              tlb->prot & PAGE_WRITE ? 'w' : '-',
-              tlb->prot & PAGE_EXEC ? 'x' : '-',
-              tlb->prot & PAGE_VALID ? 'v' : '-', (int)tlb->PID);
-}
-
-target_ulong helper_4xx_tlbsx(target_ulong address)
-{
-    return ppcemb_tlb_search(env, address, env->spr[SPR_40x_PID]);
-}
-
-/* PowerPC 440 TLB management */
-void helper_440_tlbwe(uint32_t word, target_ulong entry, target_ulong value)
-{
-    ppcemb_tlb_t *tlb;
-    target_ulong EPN, RPN, size;
-    int do_flush_tlbs;
-
-    LOG_SWTLB("%s word %d entry %d value " TARGET_FMT_lx "\n",
-              __func__, word, (int)entry, value);
-    do_flush_tlbs = 0;
-    entry &= 0x3F;
-    tlb = &env->tlb.tlbe[entry];
-    switch (word) {
-    default:
-        /* Just here to please gcc */
-    case 0:
-        EPN = value & 0xFFFFFC00;
-        if ((tlb->prot & PAGE_VALID) && EPN != tlb->EPN) {
-            do_flush_tlbs = 1;
-        }
-        tlb->EPN = EPN;
-        size = booke_tlb_to_page_size((value >> 4) & 0xF);
-        if ((tlb->prot & PAGE_VALID) && tlb->size < size) {
-            do_flush_tlbs = 1;
-        }
-        tlb->size = size;
-        tlb->attr &= ~0x1;
-        tlb->attr |= (value >> 8) & 1;
-        if (value & 0x200) {
-            tlb->prot |= PAGE_VALID;
-        } else {
-            if (tlb->prot & PAGE_VALID) {
-                tlb->prot &= ~PAGE_VALID;
-                do_flush_tlbs = 1;
-            }
-        }
-        tlb->PID = env->spr[SPR_440_MMUCR] & 0x000000FF;
-        if (do_flush_tlbs) {
-            tlb_flush(env, 1);
-        }
-        break;
-    case 1:
-        RPN = value & 0xFFFFFC0F;
-        if ((tlb->prot & PAGE_VALID) && tlb->RPN != RPN) {
-            tlb_flush(env, 1);
-        }
-        tlb->RPN = RPN;
-        break;
-    case 2:
-        tlb->attr = (tlb->attr & 0x1) | (value & 0x0000FF00);
-        tlb->prot = tlb->prot & PAGE_VALID;
-        if (value & 0x1) {
-            tlb->prot |= PAGE_READ << 4;
-        }
-        if (value & 0x2) {
-            tlb->prot |= PAGE_WRITE << 4;
-        }
-        if (value & 0x4) {
-            tlb->prot |= PAGE_EXEC << 4;
-        }
-        if (value & 0x8) {
-            tlb->prot |= PAGE_READ;
-        }
-        if (value & 0x10) {
-            tlb->prot |= PAGE_WRITE;
-        }
-        if (value & 0x20) {
-            tlb->prot |= PAGE_EXEC;
-        }
-        break;
-    }
-}
-
-target_ulong helper_440_tlbre(uint32_t word, target_ulong entry)
-{
-    ppcemb_tlb_t *tlb;
-    target_ulong ret;
-    int size;
-
-    entry &= 0x3F;
-    tlb = &env->tlb.tlbe[entry];
-    switch (word) {
-    default:
-        /* Just here to please gcc */
-    case 0:
-        ret = tlb->EPN;
-        size = booke_page_size_to_tlb(tlb->size);
-        if (size < 0 || size > 0xF) {
-            size = 1;
-        }
-        ret |= size << 4;
-        if (tlb->attr & 0x1) {
-            ret |= 0x100;
-        }
-        if (tlb->prot & PAGE_VALID) {
-            ret |= 0x200;
-        }
-        env->spr[SPR_440_MMUCR] &= ~0x000000FF;
-        env->spr[SPR_440_MMUCR] |= tlb->PID;
-        break;
-    case 1:
-        ret = tlb->RPN;
-        break;
-    case 2:
-        ret = tlb->attr & ~0x1;
-        if (tlb->prot & (PAGE_READ << 4)) {
-            ret |= 0x1;
-        }
-        if (tlb->prot & (PAGE_WRITE << 4)) {
-            ret |= 0x2;
-        }
-        if (tlb->prot & (PAGE_EXEC << 4)) {
-            ret |= 0x4;
-        }
-        if (tlb->prot & PAGE_READ) {
-            ret |= 0x8;
-        }
-        if (tlb->prot & PAGE_WRITE) {
-            ret |= 0x10;
-        }
-        if (tlb->prot & PAGE_EXEC) {
-            ret |= 0x20;
-        }
-        break;
-    }
-    return ret;
-}
-
-target_ulong helper_440_tlbsx(target_ulong address)
-{
-    return ppcemb_tlb_search(env, address, env->spr[SPR_440_MMUCR] & 0xFF);
-}
-
-/* PowerPC BookE 2.06 TLB management */
-
-static ppcmas_tlb_t *booke206_cur_tlb(CPUPPCState *env)
-{
-    uint32_t tlbncfg = 0;
-    int esel = (env->spr[SPR_BOOKE_MAS0] & MAS0_ESEL_MASK) >> MAS0_ESEL_SHIFT;
-    int ea = (env->spr[SPR_BOOKE_MAS2] & MAS2_EPN_MASK);
-    int tlb;
-
-    tlb = (env->spr[SPR_BOOKE_MAS0] & MAS0_TLBSEL_MASK) >> MAS0_TLBSEL_SHIFT;
-    tlbncfg = env->spr[SPR_BOOKE_TLB0CFG + tlb];
-
-    if ((tlbncfg & TLBnCFG_HES) && (env->spr[SPR_BOOKE_MAS0] & MAS0_HES)) {
-        cpu_abort(env, "we don't support HES yet\n");
-    }
-
-    return booke206_get_tlbm(env, tlb, ea, esel);
-}
-
-void helper_booke_setpid(uint32_t pidn, target_ulong pid)
-{
-    env->spr[pidn] = pid;
-    /* changing PIDs mean we're in a different address space now */
-    tlb_flush(env, 1);
-}
-
-void helper_booke206_tlbwe(void)
-{
-    uint32_t tlbncfg, tlbn;
-    ppcmas_tlb_t *tlb;
-    uint32_t size_tlb, size_ps;
-
-    switch (env->spr[SPR_BOOKE_MAS0] & MAS0_WQ_MASK) {
-    case MAS0_WQ_ALWAYS:
-        /* good to go, write that entry */
-        break;
-    case MAS0_WQ_COND:
-        /* XXX check if reserved */
-        if (0) {
-            return;
-        }
-        break;
-    case MAS0_WQ_CLR_RSRV:
-        /* XXX clear entry */
-        return;
-    default:
-        /* no idea what to do */
-        return;
-    }
-
-    if (((env->spr[SPR_BOOKE_MAS0] & MAS0_ATSEL) == MAS0_ATSEL_LRAT) &&
-        !msr_gs) {
-        /* XXX we don't support direct LRAT setting yet */
-        fprintf(stderr, "cpu: don't support LRAT setting yet\n");
-        return;
-    }
-
-    tlbn = (env->spr[SPR_BOOKE_MAS0] & MAS0_TLBSEL_MASK) >> MAS0_TLBSEL_SHIFT;
-    tlbncfg = env->spr[SPR_BOOKE_TLB0CFG + tlbn];
-
-    tlb = booke206_cur_tlb(env);
-
-    if (!tlb) {
-        helper_raise_exception_err(env, POWERPC_EXCP_PROGRAM,
-                                   POWERPC_EXCP_INVAL |
-                                   POWERPC_EXCP_INVAL_INVAL);
-    }
-
-    /* check that we support the targeted size */
-    size_tlb = (env->spr[SPR_BOOKE_MAS1] & MAS1_TSIZE_MASK) >> MAS1_TSIZE_SHIFT;
-    size_ps = booke206_tlbnps(env, tlbn);
-    if ((env->spr[SPR_BOOKE_MAS1] & MAS1_VALID) && (tlbncfg & TLBnCFG_AVAIL) &&
-        !(size_ps & (1 << size_tlb))) {
-        helper_raise_exception_err(env, POWERPC_EXCP_PROGRAM,
-                                   POWERPC_EXCP_INVAL |
-                                   POWERPC_EXCP_INVAL_INVAL);
-    }
-
-    if (msr_gs) {
-        cpu_abort(env, "missing HV implementation\n");
-    }
-    tlb->mas7_3 = ((uint64_t)env->spr[SPR_BOOKE_MAS7] << 32) |
-        env->spr[SPR_BOOKE_MAS3];
-    tlb->mas1 = env->spr[SPR_BOOKE_MAS1];
-
-    /* MAV 1.0 only */
-    if (!(tlbncfg & TLBnCFG_AVAIL)) {
-        /* force !AVAIL TLB entries to correct page size */
-        tlb->mas1 &= ~MAS1_TSIZE_MASK;
-        /* XXX can be configured in MMUCSR0 */
-        tlb->mas1 |= (tlbncfg & TLBnCFG_MINSIZE) >> 12;
-    }
-
-    /* XXX needs to change when supporting 64-bit e500 */
-    tlb->mas2 = env->spr[SPR_BOOKE_MAS2] & 0xffffffff;
-
-    if (!(tlbncfg & TLBnCFG_IPROT)) {
-        /* no IPROT supported by TLB */
-        tlb->mas1 &= ~MAS1_IPROT;
-    }
-
-    if (booke206_tlb_to_page_size(env, tlb) == TARGET_PAGE_SIZE) {
-        tlb_flush_page(env, tlb->mas2 & MAS2_EPN_MASK);
-    } else {
-        tlb_flush(env, 1);
-    }
-}
-
-static inline void booke206_tlb_to_mas(CPUPPCState *env, ppcmas_tlb_t *tlb)
-{
-    int tlbn = booke206_tlbm_to_tlbn(env, tlb);
-    int way = booke206_tlbm_to_way(env, tlb);
-
-    env->spr[SPR_BOOKE_MAS0] = tlbn << MAS0_TLBSEL_SHIFT;
-    env->spr[SPR_BOOKE_MAS0] |= way << MAS0_ESEL_SHIFT;
-    env->spr[SPR_BOOKE_MAS0] |= env->last_way << MAS0_NV_SHIFT;
-
-    env->spr[SPR_BOOKE_MAS1] = tlb->mas1;
-    env->spr[SPR_BOOKE_MAS2] = tlb->mas2;
-    env->spr[SPR_BOOKE_MAS3] = tlb->mas7_3;
-    env->spr[SPR_BOOKE_MAS7] = tlb->mas7_3 >> 32;
-}
-
-void helper_booke206_tlbre(void)
-{
-    ppcmas_tlb_t *tlb = NULL;
-
-    tlb = booke206_cur_tlb(env);
-    if (!tlb) {
-        env->spr[SPR_BOOKE_MAS1] = 0;
-    } else {
-        booke206_tlb_to_mas(env, tlb);
-    }
-}
-
-void helper_booke206_tlbsx(target_ulong address)
-{
-    ppcmas_tlb_t *tlb = NULL;
-    int i, j;
-    target_phys_addr_t raddr;
-    uint32_t spid, sas;
-
-    spid = (env->spr[SPR_BOOKE_MAS6] & MAS6_SPID_MASK) >> MAS6_SPID_SHIFT;
-    sas = env->spr[SPR_BOOKE_MAS6] & MAS6_SAS;
-
-    for (i = 0; i < BOOKE206_MAX_TLBN; i++) {
-        int ways = booke206_tlb_ways(env, i);
-
-        for (j = 0; j < ways; j++) {
-            tlb = booke206_get_tlbm(env, i, address, j);
-
-            if (!tlb) {
-                continue;
-            }
-
-            if (ppcmas_tlb_check(env, tlb, &raddr, address, spid)) {
-                continue;
-            }
-
-            if (sas != ((tlb->mas1 & MAS1_TS) >> MAS1_TS_SHIFT)) {
-                continue;
-            }
-
-            booke206_tlb_to_mas(env, tlb);
-            return;
-        }
-    }
-
-    /* no entry found, fill with defaults */
-    env->spr[SPR_BOOKE_MAS0] = env->spr[SPR_BOOKE_MAS4] & MAS4_TLBSELD_MASK;
-    env->spr[SPR_BOOKE_MAS1] = env->spr[SPR_BOOKE_MAS4] & MAS4_TSIZED_MASK;
-    env->spr[SPR_BOOKE_MAS2] = env->spr[SPR_BOOKE_MAS4] & MAS4_WIMGED_MASK;
-    env->spr[SPR_BOOKE_MAS3] = 0;
-    env->spr[SPR_BOOKE_MAS7] = 0;
-
-    if (env->spr[SPR_BOOKE_MAS6] & MAS6_SAS) {
-        env->spr[SPR_BOOKE_MAS1] |= MAS1_TS;
-    }
-
-    env->spr[SPR_BOOKE_MAS1] |= (env->spr[SPR_BOOKE_MAS6] >> 16)
-        << MAS1_TID_SHIFT;
-
-    /* next victim logic */
-    env->spr[SPR_BOOKE_MAS0] |= env->last_way << MAS0_ESEL_SHIFT;
-    env->last_way++;
-    env->last_way &= booke206_tlb_ways(env, 0) - 1;
-    env->spr[SPR_BOOKE_MAS0] |= env->last_way << MAS0_NV_SHIFT;
-}
-
-static inline void booke206_invalidate_ea_tlb(CPUPPCState *env, int tlbn,
-                                              uint32_t ea)
-{
-    int i;
-    int ways = booke206_tlb_ways(env, tlbn);
-    target_ulong mask;
-
-    for (i = 0; i < ways; i++) {
-        ppcmas_tlb_t *tlb = booke206_get_tlbm(env, tlbn, ea, i);
-        if (!tlb) {
-            continue;
-        }
-        mask = ~(booke206_tlb_to_page_size(env, tlb) - 1);
-        if (((tlb->mas2 & MAS2_EPN_MASK) == (ea & mask)) &&
-            !(tlb->mas1 & MAS1_IPROT)) {
-            tlb->mas1 &= ~MAS1_VALID;
-        }
-    }
-}
-
-void helper_booke206_tlbivax(target_ulong address)
-{
-    if (address & 0x4) {
-        /* flush all entries */
-        if (address & 0x8) {
-            /* flush all of TLB1 */
-            booke206_flush_tlb(env, BOOKE206_FLUSH_TLB1, 1);
-        } else {
-            /* flush all of TLB0 */
-            booke206_flush_tlb(env, BOOKE206_FLUSH_TLB0, 0);
-        }
-        return;
-    }
-
-    if (address & 0x8) {
-        /* flush TLB1 entries */
-        booke206_invalidate_ea_tlb(env, 1, address);
-        tlb_flush(env, 1);
-    } else {
-        /* flush TLB0 entries */
-        booke206_invalidate_ea_tlb(env, 0, address);
-        tlb_flush_page(env, address & MAS2_EPN_MASK);
-    }
-}
-
-void helper_booke206_tlbilx0(target_ulong address)
-{
-    /* XXX missing LPID handling */
-    booke206_flush_tlb(env, -1, 1);
-}
-
-void helper_booke206_tlbilx1(target_ulong address)
-{
-    int i, j;
-    int tid = (env->spr[SPR_BOOKE_MAS6] & MAS6_SPID);
-    ppcmas_tlb_t *tlb = env->tlb.tlbm;
-    int tlb_size;
-
-    /* XXX missing LPID handling */
-    for (i = 0; i < BOOKE206_MAX_TLBN; i++) {
-        tlb_size = booke206_tlb_size(env, i);
-        for (j = 0; j < tlb_size; j++) {
-            if (!(tlb[j].mas1 & MAS1_IPROT) &&
-                ((tlb[j].mas1 & MAS1_TID_MASK) == tid)) {
-                tlb[j].mas1 &= ~MAS1_VALID;
-            }
-        }
-        tlb += booke206_tlb_size(env, i);
-    }
-    tlb_flush(env, 1);
-}
-
-void helper_booke206_tlbilx3(target_ulong address)
-{
-    int i, j;
-    ppcmas_tlb_t *tlb;
-    int tid = (env->spr[SPR_BOOKE_MAS6] & MAS6_SPID);
-    int pid = tid >> MAS6_SPID_SHIFT;
-    int sgs = env->spr[SPR_BOOKE_MAS5] & MAS5_SGS;
-    int ind = (env->spr[SPR_BOOKE_MAS6] & MAS6_SIND) ? MAS1_IND : 0;
-    /* XXX check for unsupported isize and raise an invalid opcode then */
-    int size = env->spr[SPR_BOOKE_MAS6] & MAS6_ISIZE_MASK;
-    /* XXX implement MAV2 handling */
-    bool mav2 = false;
-
-    /* XXX missing LPID handling */
-    /* flush by pid and ea */
-    for (i = 0; i < BOOKE206_MAX_TLBN; i++) {
-        int ways = booke206_tlb_ways(env, i);
-
-        for (j = 0; j < ways; j++) {
-            tlb = booke206_get_tlbm(env, i, address, j);
-            if (!tlb) {
-                continue;
-            }
-            if ((ppcmas_tlb_check(env, tlb, NULL, address, pid) != 0) ||
-                (tlb->mas1 & MAS1_IPROT) ||
-                ((tlb->mas1 & MAS1_IND) != ind) ||
-                ((tlb->mas8 & MAS8_TGS) != sgs)) {
-                continue;
-            }
-            if (mav2 && ((tlb->mas1 & MAS1_TSIZE_MASK) != size)) {
-                /* XXX only check when MMUCFG[TWC] || TLBnCFG[HES] */
-                continue;
-            }
-            /* XXX e500mc doesn't match SAS, but other cores might */
-            tlb->mas1 &= ~MAS1_VALID;
-        }
-    }
-    tlb_flush(env, 1);
-}
-
-void helper_booke206_tlbflush(uint32_t type)
-{
-    int flags = 0;
-
-    if (type & 2) {
-        flags |= BOOKE206_FLUSH_TLB1;
-    }
-
-    if (type & 4) {
-        flags |= BOOKE206_FLUSH_TLB0;
-    }
-
-    booke206_flush_tlb(env, flags, 1);
-}
 #endif /* !CONFIG_USER_ONLY */
commit d15f74fb83fdaa80e8ef85001554d7fba0c1d0a3
Author: Blue Swirl <blauwirbel at gmail.com>
Date:   Wed May 30 04:23:29 2012 +0000

    ppc: Avoid AREG0 for integer and vector helpers
    
    Add an explicit CPUPPCState parameter instead of relying on AREG0.
    
    Signed-off-by: Blue Swirl <blauwirbel at gmail.com>
    Signed-off-by: Alexander Graf <agraf at suse.de>
    Signed-off-by: Andreas Färber <afaerber at suse.de>
    [fix unwanted whitespace line in Makefile.target]
    Signed-off-by: Alexander Graf <agraf at suse.de>

diff --git a/target-ppc/Makefile.objs b/target-ppc/Makefile.objs
index 97e440b..5d63400 100644
--- a/target-ppc/Makefile.objs
+++ b/target-ppc/Makefile.objs
@@ -6,5 +6,4 @@ obj-y += excp_helper.o
 obj-y += fpu_helper.o
 obj-y += int_helper.o
 
-$(obj)/int_helper.o: QEMU_CFLAGS += $(HELPER_CFLAGS)
 $(obj)/op_helper.o: QEMU_CFLAGS += $(HELPER_CFLAGS)
diff --git a/target-ppc/helper.h b/target-ppc/helper.h
index 0aba7f8..7074bad 100644
--- a/target-ppc/helper.h
+++ b/target-ppc/helper.h
@@ -33,17 +33,17 @@ DEF_HELPER_4(lscbx, tl, tl, i32, i32, i32)
 #if defined(TARGET_PPC64)
 DEF_HELPER_FLAGS_2(mulhd, TCG_CALL_CONST | TCG_CALL_PURE, i64, i64, i64)
 DEF_HELPER_FLAGS_2(mulhdu, TCG_CALL_CONST | TCG_CALL_PURE, i64, i64, i64)
-DEF_HELPER_2(mulldo, i64, i64, i64)
+DEF_HELPER_3(mulldo, i64, env, i64, i64)
 #endif
 
 DEF_HELPER_FLAGS_1(cntlzw, TCG_CALL_CONST | TCG_CALL_PURE, tl, tl)
 DEF_HELPER_FLAGS_1(popcntb, TCG_CALL_CONST | TCG_CALL_PURE, tl, tl)
 DEF_HELPER_FLAGS_1(popcntw, TCG_CALL_CONST | TCG_CALL_PURE, tl, tl)
-DEF_HELPER_2(sraw, tl, tl, tl)
+DEF_HELPER_3(sraw, tl, env, tl, tl)
 #if defined(TARGET_PPC64)
 DEF_HELPER_FLAGS_1(cntlzd, TCG_CALL_CONST | TCG_CALL_PURE, tl, tl)
 DEF_HELPER_FLAGS_1(popcntd, TCG_CALL_CONST | TCG_CALL_PURE, tl, tl)
-DEF_HELPER_2(srad, tl, tl, tl)
+DEF_HELPER_3(srad, tl, env, tl, tl)
 #endif
 
 DEF_HELPER_FLAGS_1(cntlsw32, TCG_CALL_CONST | TCG_CALL_PURE, i32, i32)
@@ -120,32 +120,32 @@ DEF_HELPER_3(vminuw, void, avr, avr, avr)
 DEF_HELPER_3(vmaxub, void, avr, avr, avr)
 DEF_HELPER_3(vmaxuh, void, avr, avr, avr)
 DEF_HELPER_3(vmaxuw, void, avr, avr, avr)
-DEF_HELPER_3(vcmpequb, void, avr, avr, avr)
-DEF_HELPER_3(vcmpequh, void, avr, avr, avr)
-DEF_HELPER_3(vcmpequw, void, avr, avr, avr)
-DEF_HELPER_3(vcmpgtub, void, avr, avr, avr)
-DEF_HELPER_3(vcmpgtuh, void, avr, avr, avr)
-DEF_HELPER_3(vcmpgtuw, void, avr, avr, avr)
-DEF_HELPER_3(vcmpgtsb, void, avr, avr, avr)
-DEF_HELPER_3(vcmpgtsh, void, avr, avr, avr)
-DEF_HELPER_3(vcmpgtsw, void, avr, avr, avr)
-DEF_HELPER_3(vcmpeqfp, void, avr, avr, avr)
-DEF_HELPER_3(vcmpgefp, void, avr, avr, avr)
-DEF_HELPER_3(vcmpgtfp, void, avr, avr, avr)
-DEF_HELPER_3(vcmpbfp, void, avr, avr, avr)
-DEF_HELPER_3(vcmpequb_dot, void, avr, avr, avr)
-DEF_HELPER_3(vcmpequh_dot, void, avr, avr, avr)
-DEF_HELPER_3(vcmpequw_dot, void, avr, avr, avr)
-DEF_HELPER_3(vcmpgtub_dot, void, avr, avr, avr)
-DEF_HELPER_3(vcmpgtuh_dot, void, avr, avr, avr)
-DEF_HELPER_3(vcmpgtuw_dot, void, avr, avr, avr)
-DEF_HELPER_3(vcmpgtsb_dot, void, avr, avr, avr)
-DEF_HELPER_3(vcmpgtsh_dot, void, avr, avr, avr)
-DEF_HELPER_3(vcmpgtsw_dot, void, avr, avr, avr)
-DEF_HELPER_3(vcmpeqfp_dot, void, avr, avr, avr)
-DEF_HELPER_3(vcmpgefp_dot, void, avr, avr, avr)
-DEF_HELPER_3(vcmpgtfp_dot, void, avr, avr, avr)
-DEF_HELPER_3(vcmpbfp_dot, void, avr, avr, avr)
+DEF_HELPER_4(vcmpequb, void, env, avr, avr, avr)
+DEF_HELPER_4(vcmpequh, void, env, avr, avr, avr)
+DEF_HELPER_4(vcmpequw, void, env, avr, avr, avr)
+DEF_HELPER_4(vcmpgtub, void, env, avr, avr, avr)
+DEF_HELPER_4(vcmpgtuh, void, env, avr, avr, avr)
+DEF_HELPER_4(vcmpgtuw, void, env, avr, avr, avr)
+DEF_HELPER_4(vcmpgtsb, void, env, avr, avr, avr)
+DEF_HELPER_4(vcmpgtsh, void, env, avr, avr, avr)
+DEF_HELPER_4(vcmpgtsw, void, env, avr, avr, avr)
+DEF_HELPER_4(vcmpeqfp, void, env, avr, avr, avr)
+DEF_HELPER_4(vcmpgefp, void, env, avr, avr, avr)
+DEF_HELPER_4(vcmpgtfp, void, env, avr, avr, avr)
+DEF_HELPER_4(vcmpbfp, void, env, avr, avr, avr)
+DEF_HELPER_4(vcmpequb_dot, void, env, avr, avr, avr)
+DEF_HELPER_4(vcmpequh_dot, void, env, avr, avr, avr)
+DEF_HELPER_4(vcmpequw_dot, void, env, avr, avr, avr)
+DEF_HELPER_4(vcmpgtub_dot, void, env, avr, avr, avr)
+DEF_HELPER_4(vcmpgtuh_dot, void, env, avr, avr, avr)
+DEF_HELPER_4(vcmpgtuw_dot, void, env, avr, avr, avr)
+DEF_HELPER_4(vcmpgtsb_dot, void, env, avr, avr, avr)
+DEF_HELPER_4(vcmpgtsh_dot, void, env, avr, avr, avr)
+DEF_HELPER_4(vcmpgtsw_dot, void, env, avr, avr, avr)
+DEF_HELPER_4(vcmpeqfp_dot, void, env, avr, avr, avr)
+DEF_HELPER_4(vcmpgefp_dot, void, env, avr, avr, avr)
+DEF_HELPER_4(vcmpgtfp_dot, void, env, avr, avr, avr)
+DEF_HELPER_4(vcmpbfp_dot, void, env, avr, avr, avr)
 DEF_HELPER_3(vmrglb, void, avr, avr, avr)
 DEF_HELPER_3(vmrglh, void, avr, avr, avr)
 DEF_HELPER_3(vmrglw, void, avr, avr, avr)
@@ -175,18 +175,18 @@ DEF_HELPER_3(vaddcuw, void, avr, avr, avr)
 DEF_HELPER_3(vsubcuw, void, avr, avr, avr)
 DEF_HELPER_2(lvsl, void, avr, tl);
 DEF_HELPER_2(lvsr, void, avr, tl);
-DEF_HELPER_3(vaddsbs, void, avr, avr, avr)
-DEF_HELPER_3(vaddshs, void, avr, avr, avr)
-DEF_HELPER_3(vaddsws, void, avr, avr, avr)
-DEF_HELPER_3(vsubsbs, void, avr, avr, avr)
-DEF_HELPER_3(vsubshs, void, avr, avr, avr)
-DEF_HELPER_3(vsubsws, void, avr, avr, avr)
-DEF_HELPER_3(vaddubs, void, avr, avr, avr)
-DEF_HELPER_3(vadduhs, void, avr, avr, avr)
-DEF_HELPER_3(vadduws, void, avr, avr, avr)
-DEF_HELPER_3(vsububs, void, avr, avr, avr)
-DEF_HELPER_3(vsubuhs, void, avr, avr, avr)
-DEF_HELPER_3(vsubuws, void, avr, avr, avr)
+DEF_HELPER_4(vaddsbs, void, env, avr, avr, avr)
+DEF_HELPER_4(vaddshs, void, env, avr, avr, avr)
+DEF_HELPER_4(vaddsws, void, env, avr, avr, avr)
+DEF_HELPER_4(vsubsbs, void, env, avr, avr, avr)
+DEF_HELPER_4(vsubshs, void, env, avr, avr, avr)
+DEF_HELPER_4(vsubsws, void, env, avr, avr, avr)
+DEF_HELPER_4(vaddubs, void, env, avr, avr, avr)
+DEF_HELPER_4(vadduhs, void, env, avr, avr, avr)
+DEF_HELPER_4(vadduws, void, env, avr, avr, avr)
+DEF_HELPER_4(vsububs, void, env, avr, avr, avr)
+DEF_HELPER_4(vsubuhs, void, env, avr, avr, avr)
+DEF_HELPER_4(vsubuws, void, env, avr, avr, avr)
 DEF_HELPER_3(vrlb, void, avr, avr, avr)
 DEF_HELPER_3(vrlh, void, avr, avr, avr)
 DEF_HELPER_3(vrlw, void, avr, avr, avr)
@@ -205,56 +205,56 @@ DEF_HELPER_2(vupkhsb, void, avr, avr)
 DEF_HELPER_2(vupkhsh, void, avr, avr)
 DEF_HELPER_2(vupklsb, void, avr, avr)
 DEF_HELPER_2(vupklsh, void, avr, avr)
-DEF_HELPER_4(vmsumubm, void, avr, avr, avr, avr)
-DEF_HELPER_4(vmsummbm, void, avr, avr, avr, avr)
-DEF_HELPER_4(vsel, void, avr, avr, avr, avr)
-DEF_HELPER_4(vperm, void, avr, avr, avr, avr)
-DEF_HELPER_3(vpkshss, void, avr, avr, avr)
-DEF_HELPER_3(vpkshus, void, avr, avr, avr)
-DEF_HELPER_3(vpkswss, void, avr, avr, avr)
-DEF_HELPER_3(vpkswus, void, avr, avr, avr)
-DEF_HELPER_3(vpkuhus, void, avr, avr, avr)
-DEF_HELPER_3(vpkuwus, void, avr, avr, avr)
-DEF_HELPER_3(vpkuhum, void, avr, avr, avr)
-DEF_HELPER_3(vpkuwum, void, avr, avr, avr)
+DEF_HELPER_5(vmsumubm, void, env, avr, avr, avr, avr)
+DEF_HELPER_5(vmsummbm, void, env, avr, avr, avr, avr)
+DEF_HELPER_5(vsel, void, env, avr, avr, avr, avr)
+DEF_HELPER_5(vperm, void, env, avr, avr, avr, avr)
+DEF_HELPER_4(vpkshss, void, env, avr, avr, avr)
+DEF_HELPER_4(vpkshus, void, env, avr, avr, avr)
+DEF_HELPER_4(vpkswss, void, env, avr, avr, avr)
+DEF_HELPER_4(vpkswus, void, env, avr, avr, avr)
+DEF_HELPER_4(vpkuhus, void, env, avr, avr, avr)
+DEF_HELPER_4(vpkuwus, void, env, avr, avr, avr)
+DEF_HELPER_4(vpkuhum, void, env, avr, avr, avr)
+DEF_HELPER_4(vpkuwum, void, env, avr, avr, avr)
 DEF_HELPER_3(vpkpx, void, avr, avr, avr)
-DEF_HELPER_4(vmhaddshs, void, avr, avr, avr, avr)
-DEF_HELPER_4(vmhraddshs, void, avr, avr, avr, avr)
-DEF_HELPER_4(vmsumuhm, void, avr, avr, avr, avr)
-DEF_HELPER_4(vmsumuhs, void, avr, avr, avr, avr)
-DEF_HELPER_4(vmsumshm, void, avr, avr, avr, avr)
-DEF_HELPER_4(vmsumshs, void, avr, avr, avr, avr)
+DEF_HELPER_5(vmhaddshs, void, env, avr, avr, avr, avr)
+DEF_HELPER_5(vmhraddshs, void, env, avr, avr, avr, avr)
+DEF_HELPER_5(vmsumuhm, void, env, avr, avr, avr, avr)
+DEF_HELPER_5(vmsumuhs, void, env, avr, avr, avr, avr)
+DEF_HELPER_5(vmsumshm, void, env, avr, avr, avr, avr)
+DEF_HELPER_5(vmsumshs, void, env, avr, avr, avr, avr)
 DEF_HELPER_4(vmladduhm, void, avr, avr, avr, avr)
-DEF_HELPER_1(mtvscr, void, avr);
+DEF_HELPER_2(mtvscr, void, env, avr);
 DEF_HELPER_2(lvebx, void, avr, tl)
 DEF_HELPER_2(lvehx, void, avr, tl)
 DEF_HELPER_2(lvewx, void, avr, tl)
 DEF_HELPER_2(stvebx, void, avr, tl)
 DEF_HELPER_2(stvehx, void, avr, tl)
 DEF_HELPER_2(stvewx, void, avr, tl)
-DEF_HELPER_3(vsumsws, void, avr, avr, avr)
-DEF_HELPER_3(vsum2sws, void, avr, avr, avr)
-DEF_HELPER_3(vsum4sbs, void, avr, avr, avr)
-DEF_HELPER_3(vsum4shs, void, avr, avr, avr)
-DEF_HELPER_3(vsum4ubs, void, avr, avr, avr)
-DEF_HELPER_3(vaddfp, void, avr, avr, avr)
-DEF_HELPER_3(vsubfp, void, avr, avr, avr)
-DEF_HELPER_3(vmaxfp, void, avr, avr, avr)
-DEF_HELPER_3(vminfp, void, avr, avr, avr)
-DEF_HELPER_2(vrefp, void, avr, avr)
-DEF_HELPER_2(vrsqrtefp, void, avr, avr)
-DEF_HELPER_4(vmaddfp, void, avr, avr, avr, avr)
-DEF_HELPER_4(vnmsubfp, void, avr, avr, avr, avr)
-DEF_HELPER_2(vexptefp, void, avr, avr)
-DEF_HELPER_2(vlogefp, void, avr, avr)
-DEF_HELPER_2(vrfim, void, avr, avr)
-DEF_HELPER_2(vrfin, void, avr, avr)
-DEF_HELPER_2(vrfip, void, avr, avr)
-DEF_HELPER_2(vrfiz, void, avr, avr)
-DEF_HELPER_3(vcfux, void, avr, avr, i32)
-DEF_HELPER_3(vcfsx, void, avr, avr, i32)
-DEF_HELPER_3(vctuxs, void, avr, avr, i32)
-DEF_HELPER_3(vctsxs, void, avr, avr, i32)
+DEF_HELPER_4(vsumsws, void, env, avr, avr, avr)
+DEF_HELPER_4(vsum2sws, void, env, avr, avr, avr)
+DEF_HELPER_4(vsum4sbs, void, env, avr, avr, avr)
+DEF_HELPER_4(vsum4shs, void, env, avr, avr, avr)
+DEF_HELPER_4(vsum4ubs, void, env, avr, avr, avr)
+DEF_HELPER_4(vaddfp, void, env, avr, avr, avr)
+DEF_HELPER_4(vsubfp, void, env, avr, avr, avr)
+DEF_HELPER_4(vmaxfp, void, env, avr, avr, avr)
+DEF_HELPER_4(vminfp, void, env, avr, avr, avr)
+DEF_HELPER_3(vrefp, void, env, avr, avr)
+DEF_HELPER_3(vrsqrtefp, void, env, avr, avr)
+DEF_HELPER_5(vmaddfp, void, env, avr, avr, avr, avr)
+DEF_HELPER_5(vnmsubfp, void, env, avr, avr, avr, avr)
+DEF_HELPER_3(vexptefp, void, env, avr, avr)
+DEF_HELPER_3(vlogefp, void, env, avr, avr)
+DEF_HELPER_3(vrfim, void, env, avr, avr)
+DEF_HELPER_3(vrfin, void, env, avr, avr)
+DEF_HELPER_3(vrfip, void, env, avr, avr)
+DEF_HELPER_3(vrfiz, void, env, avr, avr)
+DEF_HELPER_4(vcfux, void, env, avr, avr, i32)
+DEF_HELPER_4(vcfsx, void, env, avr, avr, i32)
+DEF_HELPER_4(vctuxs, void, env, avr, avr, i32)
+DEF_HELPER_4(vctsxs, void, env, avr, avr, i32)
 
 DEF_HELPER_2(efscfsi, i32, env, i32)
 DEF_HELPER_2(efscfui, i32, env, i32)
@@ -362,15 +362,15 @@ DEF_HELPER_1(msgsnd, void, tl)
 DEF_HELPER_2(msgclr, void, env, tl)
 #endif
 
-DEF_HELPER_3(dlmzb, tl, tl, tl, i32)
+DEF_HELPER_4(dlmzb, tl, env, tl, tl, i32)
 DEF_HELPER_FLAGS_1(clcs, TCG_CALL_CONST | TCG_CALL_PURE, tl, i32)
 #if !defined(CONFIG_USER_ONLY)
 DEF_HELPER_1(rac, tl, tl)
 #endif
-DEF_HELPER_2(div, tl, tl, tl)
-DEF_HELPER_2(divo, tl, tl, tl)
-DEF_HELPER_2(divs, tl, tl, tl)
-DEF_HELPER_2(divso, tl, tl, tl)
+DEF_HELPER_3(div, tl, env, tl, tl)
+DEF_HELPER_3(divo, tl, env, tl, tl)
+DEF_HELPER_3(divs, tl, env, tl, tl)
+DEF_HELPER_3(divso, tl, env, tl, tl)
 
 DEF_HELPER_1(load_dcr, tl, tl);
 DEF_HELPER_2(store_dcr, void, tl, tl)
diff --git a/target-ppc/int_helper.c b/target-ppc/int_helper.c
index 71c7304..3173f11 100644
--- a/target-ppc/int_helper.c
+++ b/target-ppc/int_helper.c
@@ -17,7 +17,6 @@
  * License along with this library; if not, see <http://www.gnu.org/licenses/>.
  */
 #include "cpu.h"
-#include "dyngen-exec.h"
 #include "host-utils.h"
 #include "helper.h"
 
@@ -44,7 +43,7 @@ uint64_t helper_mulhdu(uint64_t arg1, uint64_t arg2)
     return th;
 }
 
-uint64_t helper_mulldo(uint64_t arg1, uint64_t arg2)
+uint64_t helper_mulldo(CPUPPCState *env, uint64_t arg1, uint64_t arg2)
 {
     int64_t th;
     uint64_t tl;
@@ -73,7 +72,8 @@ target_ulong helper_cntlzd(target_ulong t)
 #endif
 
 /* shift right arithmetic helper */
-target_ulong helper_sraw(target_ulong value, target_ulong shift)
+target_ulong helper_sraw(CPUPPCState *env, target_ulong value,
+                         target_ulong shift)
 {
     int32_t ret;
 
@@ -102,7 +102,8 @@ target_ulong helper_sraw(target_ulong value, target_ulong shift)
 }
 
 #if defined(TARGET_PPC64)
-target_ulong helper_srad(target_ulong value, target_ulong shift)
+target_ulong helper_srad(CPUPPCState *env, target_ulong value,
+                         target_ulong shift)
 {
     int64_t ret;
 
@@ -184,7 +185,7 @@ target_ulong helper_popcntw(target_ulong val)
 
 /*****************************************************************************/
 /* PowerPC 601 specific instructions (POWER bridge) */
-target_ulong helper_div(target_ulong arg1, target_ulong arg2)
+target_ulong helper_div(CPUPPCState *env, target_ulong arg1, target_ulong arg2)
 {
     uint64_t tmp = (uint64_t)arg1 << 32 | env->spr[SPR_MQ];
 
@@ -198,7 +199,8 @@ target_ulong helper_div(target_ulong arg1, target_ulong arg2)
     }
 }
 
-target_ulong helper_divo(target_ulong arg1, target_ulong arg2)
+target_ulong helper_divo(CPUPPCState *env, target_ulong arg1,
+                         target_ulong arg2)
 {
     uint64_t tmp = (uint64_t)arg1 << 32 | env->spr[SPR_MQ];
 
@@ -219,7 +221,8 @@ target_ulong helper_divo(target_ulong arg1, target_ulong arg2)
     }
 }
 
-target_ulong helper_divs(target_ulong arg1, target_ulong arg2)
+target_ulong helper_divs(CPUPPCState *env, target_ulong arg1,
+                         target_ulong arg2)
 {
     if (((int32_t)arg1 == INT32_MIN && (int32_t)arg2 == (int32_t)-1) ||
         (int32_t)arg2 == 0) {
@@ -231,7 +234,8 @@ target_ulong helper_divs(target_ulong arg1, target_ulong arg2)
     }
 }
 
-target_ulong helper_divso(target_ulong arg1, target_ulong arg2)
+target_ulong helper_divso(CPUPPCState *env, target_ulong arg1,
+                          target_ulong arg2)
 {
     if (((int32_t)arg1 == INT32_MIN && (int32_t)arg2 == (int32_t)-1) ||
         (int32_t)arg2 == 0) {
@@ -361,7 +365,7 @@ void helper_lvsr(ppc_avr_t *r, target_ulong sh)
     }
 }
 
-void helper_mtvscr(ppc_avr_t *r)
+void helper_mtvscr(CPUPPCState *env, ppc_avr_t *r)
 {
 #if defined(HOST_WORDS_BIGENDIAN)
     env->vscr = r->u32[3];
@@ -399,7 +403,8 @@ VARITH(uwm, u32)
 #undef VARITH
 
 #define VARITHFP(suffix, func)                                          \
-    void helper_v##suffix(ppc_avr_t *r, ppc_avr_t *a, ppc_avr_t *b)     \
+    void helper_v##suffix(CPUPPCState *env, ppc_avr_t *r, ppc_avr_t *a, \
+                          ppc_avr_t *b)                                 \
     {                                                                   \
         int i;                                                          \
                                                                         \
@@ -420,7 +425,8 @@ VARITHFP(subfp, float32_sub)
     }
 
 #define VARITHSAT_DO(name, op, optype, cvt, element)                    \
-    void helper_v##name(ppc_avr_t *r, ppc_avr_t *a, ppc_avr_t *b)       \
+    void helper_v##name(CPUPPCState *env, ppc_avr_t *r, ppc_avr_t *a,   \
+                        ppc_avr_t *b)                                   \
     {                                                                   \
         int sat = 0;                                                    \
         int i;                                                          \
@@ -481,7 +487,8 @@ VAVG(w, s32, int64_t, u32, uint64_t)
 #undef VAVG
 
 #define VCF(suffix, cvt, element)                                       \
-    void helper_vcf##suffix(ppc_avr_t *r, ppc_avr_t *b, uint32_t uim)   \
+    void helper_vcf##suffix(CPUPPCState *env, ppc_avr_t *r,             \
+                            ppc_avr_t *b, uint32_t uim)                 \
     {                                                                   \
         int i;                                                          \
                                                                         \
@@ -495,7 +502,8 @@ VCF(sx, int32_to_float32, s32)
 #undef VCF
 
 #define VCMP_DO(suffix, compare, element, record)                       \
-    void helper_vcmp##suffix(ppc_avr_t *r, ppc_avr_t *a, ppc_avr_t *b)  \
+    void helper_vcmp##suffix(CPUPPCState *env, ppc_avr_t *r,            \
+                             ppc_avr_t *a, ppc_avr_t *b)                \
     {                                                                   \
         uint32_t ones = (uint32_t)-1;                                   \
         uint32_t all = ones;                                            \
@@ -539,7 +547,8 @@ VCMP(gtsw, >, s32)
 #undef VCMP
 
 #define VCMPFP_DO(suffix, compare, order, record)                       \
-    void helper_vcmp##suffix(ppc_avr_t *r, ppc_avr_t *a, ppc_avr_t *b)  \
+    void helper_vcmp##suffix(CPUPPCState *env, ppc_avr_t *r,            \
+                             ppc_avr_t *a, ppc_avr_t *b)                \
     {                                                                   \
         uint32_t ones = (uint32_t)-1;                                   \
         uint32_t all = ones;                                            \
@@ -574,8 +583,8 @@ VCMPFP(gtfp, ==, float_relation_greater)
 #undef VCMPFP_DO
 #undef VCMPFP
 
-static inline void vcmpbfp_internal(ppc_avr_t *r, ppc_avr_t *a, ppc_avr_t *b,
-                                    int record)
+static inline void vcmpbfp_internal(CPUPPCState *env, ppc_avr_t *r,
+                                    ppc_avr_t *a, ppc_avr_t *b, int record)
 {
     int i;
     int all_in = 0;
@@ -600,18 +609,20 @@ static inline void vcmpbfp_internal(ppc_avr_t *r, ppc_avr_t *a, ppc_avr_t *b,
     }
 }
 
-void helper_vcmpbfp(ppc_avr_t *r, ppc_avr_t *a, ppc_avr_t *b)
+void helper_vcmpbfp(CPUPPCState *env, ppc_avr_t *r, ppc_avr_t *a, ppc_avr_t *b)
 {
-    vcmpbfp_internal(r, a, b, 0);
+    vcmpbfp_internal(env, r, a, b, 0);
 }
 
-void helper_vcmpbfp_dot(ppc_avr_t *r, ppc_avr_t *a, ppc_avr_t *b)
+void helper_vcmpbfp_dot(CPUPPCState *env, ppc_avr_t *r, ppc_avr_t *a,
+                        ppc_avr_t *b)
 {
-    vcmpbfp_internal(r, a, b, 1);
+    vcmpbfp_internal(env, r, a, b, 1);
 }
 
 #define VCT(suffix, satcvt, element)                                    \
-    void helper_vct##suffix(ppc_avr_t *r, ppc_avr_t *b, uint32_t uim)   \
+    void helper_vct##suffix(CPUPPCState *env, ppc_avr_t *r,             \
+                            ppc_avr_t *b, uint32_t uim)                 \
     {                                                                   \
         int i;                                                          \
         int sat = 0;                                                    \
@@ -638,7 +649,8 @@ VCT(uxs, cvtsduw, u32)
 VCT(sxs, cvtsdsw, s32)
 #undef VCT
 
-void helper_vmaddfp(ppc_avr_t *r, ppc_avr_t *a, ppc_avr_t *b, ppc_avr_t *c)
+void helper_vmaddfp(CPUPPCState *env, ppc_avr_t *r, ppc_avr_t *a, ppc_avr_t *b,
+                    ppc_avr_t *c)
 {
     int i;
 
@@ -658,7 +670,8 @@ void helper_vmaddfp(ppc_avr_t *r, ppc_avr_t *a, ppc_avr_t *b, ppc_avr_t *c)
     }
 }
 
-void helper_vmhaddshs(ppc_avr_t *r, ppc_avr_t *a, ppc_avr_t *b, ppc_avr_t *c)
+void helper_vmhaddshs(CPUPPCState *env, ppc_avr_t *r, ppc_avr_t *a,
+                      ppc_avr_t *b, ppc_avr_t *c)
 {
     int sat = 0;
     int i;
@@ -675,7 +688,8 @@ void helper_vmhaddshs(ppc_avr_t *r, ppc_avr_t *a, ppc_avr_t *b, ppc_avr_t *c)
     }
 }
 
-void helper_vmhraddshs(ppc_avr_t *r, ppc_avr_t *a, ppc_avr_t *b, ppc_avr_t *c)
+void helper_vmhraddshs(CPUPPCState *env, ppc_avr_t *r, ppc_avr_t *a,
+                       ppc_avr_t *b, ppc_avr_t *c)
 {
     int sat = 0;
     int i;
@@ -717,7 +731,8 @@ VMINMAX(uw, u32)
 #undef VMINMAX
 
 #define VMINMAXFP(suffix, rT, rF)                                       \
-    void helper_v##suffix(ppc_avr_t *r, ppc_avr_t *a, ppc_avr_t *b)     \
+    void helper_v##suffix(CPUPPCState *env, ppc_avr_t *r, ppc_avr_t *a, \
+                          ppc_avr_t *b)                                 \
     {                                                                   \
         int i;                                                          \
                                                                         \
@@ -784,7 +799,8 @@ VMRG(w, u32)
 #undef MRGHI
 #undef MRGLO
 
-void helper_vmsummbm(ppc_avr_t *r, ppc_avr_t *a, ppc_avr_t *b, ppc_avr_t *c)
+void helper_vmsummbm(CPUPPCState *env, ppc_avr_t *r, ppc_avr_t *a,
+                     ppc_avr_t *b, ppc_avr_t *c)
 {
     int32_t prod[16];
     int i;
@@ -799,7 +815,8 @@ void helper_vmsummbm(ppc_avr_t *r, ppc_avr_t *a, ppc_avr_t *b, ppc_avr_t *c)
     }
 }
 
-void helper_vmsumshm(ppc_avr_t *r, ppc_avr_t *a, ppc_avr_t *b, ppc_avr_t *c)
+void helper_vmsumshm(CPUPPCState *env, ppc_avr_t *r, ppc_avr_t *a,
+                     ppc_avr_t *b, ppc_avr_t *c)
 {
     int32_t prod[8];
     int i;
@@ -813,7 +830,8 @@ void helper_vmsumshm(ppc_avr_t *r, ppc_avr_t *a, ppc_avr_t *b, ppc_avr_t *c)
     }
 }
 
-void helper_vmsumshs(ppc_avr_t *r, ppc_avr_t *a, ppc_avr_t *b, ppc_avr_t *c)
+void helper_vmsumshs(CPUPPCState *env, ppc_avr_t *r, ppc_avr_t *a,
+                     ppc_avr_t *b, ppc_avr_t *c)
 {
     int32_t prod[8];
     int i;
@@ -834,7 +852,8 @@ void helper_vmsumshs(ppc_avr_t *r, ppc_avr_t *a, ppc_avr_t *b, ppc_avr_t *c)
     }
 }
 
-void helper_vmsumubm(ppc_avr_t *r, ppc_avr_t *a, ppc_avr_t *b, ppc_avr_t *c)
+void helper_vmsumubm(CPUPPCState *env, ppc_avr_t *r, ppc_avr_t *a,
+                     ppc_avr_t *b, ppc_avr_t *c)
 {
     uint16_t prod[16];
     int i;
@@ -849,7 +868,8 @@ void helper_vmsumubm(ppc_avr_t *r, ppc_avr_t *a, ppc_avr_t *b, ppc_avr_t *c)
     }
 }
 
-void helper_vmsumuhm(ppc_avr_t *r, ppc_avr_t *a, ppc_avr_t *b, ppc_avr_t *c)
+void helper_vmsumuhm(CPUPPCState *env, ppc_avr_t *r, ppc_avr_t *a,
+                     ppc_avr_t *b, ppc_avr_t *c)
 {
     uint32_t prod[8];
     int i;
@@ -863,7 +883,8 @@ void helper_vmsumuhm(ppc_avr_t *r, ppc_avr_t *a, ppc_avr_t *b, ppc_avr_t *c)
     }
 }
 
-void helper_vmsumuhs(ppc_avr_t *r, ppc_avr_t *a, ppc_avr_t *b, ppc_avr_t *c)
+void helper_vmsumuhs(CPUPPCState *env, ppc_avr_t *r, ppc_avr_t *a,
+                     ppc_avr_t *b, ppc_avr_t *c)
 {
     uint32_t prod[8];
     int i;
@@ -909,7 +930,8 @@ VMUL(uh, u16, u32)
 #undef VMUL_DO
 #undef VMUL
 
-void helper_vnmsubfp(ppc_avr_t *r, ppc_avr_t *a, ppc_avr_t *b, ppc_avr_t *c)
+void helper_vnmsubfp(CPUPPCState *env, ppc_avr_t *r, ppc_avr_t *a,
+                     ppc_avr_t *b, ppc_avr_t *c)
 {
     int i;
 
@@ -930,7 +952,8 @@ void helper_vnmsubfp(ppc_avr_t *r, ppc_avr_t *a, ppc_avr_t *b, ppc_avr_t *c)
     }
 }
 
-void helper_vperm(ppc_avr_t *r, ppc_avr_t *a, ppc_avr_t *b, ppc_avr_t *c)
+void helper_vperm(CPUPPCState *env, ppc_avr_t *r, ppc_avr_t *a, ppc_avr_t *b,
+                  ppc_avr_t *c)
 {
     ppc_avr_t result;
     int i;
@@ -980,7 +1003,8 @@ void helper_vpkpx(ppc_avr_t *r, ppc_avr_t *a, ppc_avr_t *b)
 }
 
 #define VPK(suffix, from, to, cvt, dosat)                               \
-    void helper_vpk##suffix(ppc_avr_t *r, ppc_avr_t *a, ppc_avr_t *b)   \
+    void helper_vpk##suffix(CPUPPCState *env, ppc_avr_t *r,             \
+                            ppc_avr_t *a, ppc_avr_t *b)                 \
     {                                                                   \
         int i;                                                          \
         int sat = 0;                                                    \
@@ -1010,7 +1034,7 @@ VPK(uwum, u32, u16, I, 0)
 #undef VPK
 #undef PKBIG
 
-void helper_vrefp(ppc_avr_t *r, ppc_avr_t *b)
+void helper_vrefp(CPUPPCState *env, ppc_avr_t *r, ppc_avr_t *b)
 {
     int i;
 
@@ -1022,7 +1046,8 @@ void helper_vrefp(ppc_avr_t *r, ppc_avr_t *b)
 }
 
 #define VRFI(suffix, rounding)                                  \
-    void helper_vrfi##suffix(ppc_avr_t *r, ppc_avr_t *b)        \
+    void helper_vrfi##suffix(CPUPPCState *env, ppc_avr_t *r,    \
+                             ppc_avr_t *b)                      \
     {                                                           \
         int i;                                                  \
         float_status s = env->vec_status;                       \
@@ -1059,7 +1084,7 @@ VROTATE(h, u16)
 VROTATE(w, u32)
 #undef VROTATE
 
-void helper_vrsqrtefp(ppc_avr_t *r, ppc_avr_t *b)
+void helper_vrsqrtefp(CPUPPCState *env, ppc_avr_t *r, ppc_avr_t *b)
 {
     int i;
 
@@ -1072,13 +1097,14 @@ void helper_vrsqrtefp(ppc_avr_t *r, ppc_avr_t *b)
     }
 }
 
-void helper_vsel(ppc_avr_t *r, ppc_avr_t *a, ppc_avr_t *b, ppc_avr_t *c)
+void helper_vsel(CPUPPCState *env, ppc_avr_t *r, ppc_avr_t *a, ppc_avr_t *b,
+                 ppc_avr_t *c)
 {
     r->u64[0] = (a->u64[0] & ~c->u64[0]) | (b->u64[0] & c->u64[0]);
     r->u64[1] = (a->u64[1] & ~c->u64[1]) | (b->u64[1] & c->u64[1]);
 }
 
-void helper_vexptefp(ppc_avr_t *r, ppc_avr_t *b)
+void helper_vexptefp(CPUPPCState *env, ppc_avr_t *r, ppc_avr_t *b)
 {
     int i;
 
@@ -1089,7 +1115,7 @@ void helper_vexptefp(ppc_avr_t *r, ppc_avr_t *b)
     }
 }
 
-void helper_vlogefp(ppc_avr_t *r, ppc_avr_t *b)
+void helper_vlogefp(CPUPPCState *env, ppc_avr_t *r, ppc_avr_t *b)
 {
     int i;
 
@@ -1286,7 +1312,7 @@ void helper_vsubcuw(ppc_avr_t *r, ppc_avr_t *a, ppc_avr_t *b)
     }
 }
 
-void helper_vsumsws(ppc_avr_t *r, ppc_avr_t *a, ppc_avr_t *b)
+void helper_vsumsws(CPUPPCState *env, ppc_avr_t *r, ppc_avr_t *a, ppc_avr_t *b)
 {
     int64_t t;
     int i, upper;
@@ -1311,7 +1337,7 @@ void helper_vsumsws(ppc_avr_t *r, ppc_avr_t *a, ppc_avr_t *b)
     }
 }
 
-void helper_vsum2sws(ppc_avr_t *r, ppc_avr_t *a, ppc_avr_t *b)
+void helper_vsum2sws(CPUPPCState *env, ppc_avr_t *r, ppc_avr_t *a, ppc_avr_t *b)
 {
     int i, j, upper;
     ppc_avr_t result;
@@ -1338,7 +1364,7 @@ void helper_vsum2sws(ppc_avr_t *r, ppc_avr_t *a, ppc_avr_t *b)
     }
 }
 
-void helper_vsum4sbs(ppc_avr_t *r, ppc_avr_t *a, ppc_avr_t *b)
+void helper_vsum4sbs(CPUPPCState *env, ppc_avr_t *r, ppc_avr_t *a, ppc_avr_t *b)
 {
     int i, j;
     int sat = 0;
@@ -1357,7 +1383,7 @@ void helper_vsum4sbs(ppc_avr_t *r, ppc_avr_t *a, ppc_avr_t *b)
     }
 }
 
-void helper_vsum4shs(ppc_avr_t *r, ppc_avr_t *a, ppc_avr_t *b)
+void helper_vsum4shs(CPUPPCState *env, ppc_avr_t *r, ppc_avr_t *a, ppc_avr_t *b)
 {
     int sat = 0;
     int i;
@@ -1374,7 +1400,7 @@ void helper_vsum4shs(ppc_avr_t *r, ppc_avr_t *a, ppc_avr_t *b)
     }
 }
 
-void helper_vsum4ubs(ppc_avr_t *r, ppc_avr_t *a, ppc_avr_t *b)
+void helper_vsum4ubs(CPUPPCState *env, ppc_avr_t *r, ppc_avr_t *a, ppc_avr_t *b)
 {
     int i, j;
     int sat = 0;
@@ -1501,8 +1527,8 @@ uint32_t helper_cntlzw32(uint32_t val)
 }
 
 /* 440 specific */
-target_ulong helper_dlmzb(target_ulong high, target_ulong low,
-                          uint32_t update_Rc)
+target_ulong helper_dlmzb(CPUPPCState *env, target_ulong high,
+                          target_ulong low, uint32_t update_Rc)
 {
     target_ulong mask;
     int i;
diff --git a/target-ppc/translate.c b/target-ppc/translate.c
index c8b7982..eb3cd5a 100644
--- a/target-ppc/translate.c
+++ b/target-ppc/translate.c
@@ -1181,8 +1181,16 @@ static void gen_mulld(DisasContext *ctx)
     if (unlikely(Rc(ctx->opcode) != 0))
         gen_set_Rc0(ctx, cpu_gpr[rD(ctx->opcode)]);
 }
+
 /* mulldo  mulldo. */
-GEN_INT_ARITH_MUL_HELPER(mulldo, 0x17);
+static void gen_mulldo(DisasContext *ctx)
+{
+    gen_helper_mulldo(cpu_gpr[rD(ctx->opcode)], cpu_env,
+                      cpu_gpr[rA(ctx->opcode)], cpu_gpr[rB(ctx->opcode)]);
+    if (unlikely(Rc(ctx->opcode) != 0)) {
+        gen_set_Rc0(ctx, cpu_gpr[rD(ctx->opcode)]);
+    }
+}
 #endif
 
 /* neg neg. nego nego. */
@@ -1869,7 +1877,7 @@ static void gen_slw(DisasContext *ctx)
 /* sraw & sraw. */
 static void gen_sraw(DisasContext *ctx)
 {
-    gen_helper_sraw(cpu_gpr[rA(ctx->opcode)],
+    gen_helper_sraw(cpu_gpr[rA(ctx->opcode)], cpu_env,
                     cpu_gpr[rS(ctx->opcode)], cpu_gpr[rB(ctx->opcode)]);
     if (unlikely(Rc(ctx->opcode) != 0))
         gen_set_Rc0(ctx, cpu_gpr[rA(ctx->opcode)]);
@@ -1953,7 +1961,7 @@ static void gen_sld(DisasContext *ctx)
 /* srad & srad. */
 static void gen_srad(DisasContext *ctx)
 {
-    gen_helper_srad(cpu_gpr[rA(ctx->opcode)],
+    gen_helper_srad(cpu_gpr[rA(ctx->opcode)], cpu_env,
                     cpu_gpr[rS(ctx->opcode)], cpu_gpr[rB(ctx->opcode)]);
     if (unlikely(Rc(ctx->opcode) != 0))
         gen_set_Rc0(ctx, cpu_gpr[rA(ctx->opcode)]);
@@ -4550,7 +4558,8 @@ static void gen_clcs(DisasContext *ctx)
 /* div - div. */
 static void gen_div(DisasContext *ctx)
 {
-    gen_helper_div(cpu_gpr[rD(ctx->opcode)], cpu_gpr[rA(ctx->opcode)], cpu_gpr[rB(ctx->opcode)]);
+    gen_helper_div(cpu_gpr[rD(ctx->opcode)], cpu_env, cpu_gpr[rA(ctx->opcode)],
+                   cpu_gpr[rB(ctx->opcode)]);
     if (unlikely(Rc(ctx->opcode) != 0))
         gen_set_Rc0(ctx, cpu_gpr[rD(ctx->opcode)]);
 }
@@ -4558,7 +4567,8 @@ static void gen_div(DisasContext *ctx)
 /* divo - divo. */
 static void gen_divo(DisasContext *ctx)
 {
-    gen_helper_divo(cpu_gpr[rD(ctx->opcode)], cpu_gpr[rA(ctx->opcode)], cpu_gpr[rB(ctx->opcode)]);
+    gen_helper_divo(cpu_gpr[rD(ctx->opcode)], cpu_env, cpu_gpr[rA(ctx->opcode)],
+                    cpu_gpr[rB(ctx->opcode)]);
     if (unlikely(Rc(ctx->opcode) != 0))
         gen_set_Rc0(ctx, cpu_gpr[rD(ctx->opcode)]);
 }
@@ -4566,7 +4576,8 @@ static void gen_divo(DisasContext *ctx)
 /* divs - divs. */
 static void gen_divs(DisasContext *ctx)
 {
-    gen_helper_divs(cpu_gpr[rD(ctx->opcode)], cpu_gpr[rA(ctx->opcode)], cpu_gpr[rB(ctx->opcode)]);
+    gen_helper_divs(cpu_gpr[rD(ctx->opcode)], cpu_env, cpu_gpr[rA(ctx->opcode)],
+                    cpu_gpr[rB(ctx->opcode)]);
     if (unlikely(Rc(ctx->opcode) != 0))
         gen_set_Rc0(ctx, cpu_gpr[rD(ctx->opcode)]);
 }
@@ -4574,7 +4585,8 @@ static void gen_divs(DisasContext *ctx)
 /* divso - divso. */
 static void gen_divso(DisasContext *ctx)
 {
-    gen_helper_divso(cpu_gpr[rD(ctx->opcode)], cpu_gpr[rA(ctx->opcode)], cpu_gpr[rB(ctx->opcode)]);
+    gen_helper_divso(cpu_gpr[rD(ctx->opcode)], cpu_env,
+                     cpu_gpr[rA(ctx->opcode)], cpu_gpr[rB(ctx->opcode)]);
     if (unlikely(Rc(ctx->opcode) != 0))
         gen_set_Rc0(ctx, cpu_gpr[rD(ctx->opcode)]);
 }
@@ -6237,8 +6249,8 @@ static void gen_wrteei(DisasContext *ctx)
 static void gen_dlmzb(DisasContext *ctx)
 {
     TCGv_i32 t0 = tcg_const_i32(Rc(ctx->opcode));
-    gen_helper_dlmzb(cpu_gpr[rA(ctx->opcode)], cpu_gpr[rS(ctx->opcode)],
-                     cpu_gpr[rB(ctx->opcode)], t0);
+    gen_helper_dlmzb(cpu_gpr[rA(ctx->opcode)], cpu_env,
+                     cpu_gpr[rS(ctx->opcode)], cpu_gpr[rB(ctx->opcode)], t0);
     tcg_temp_free_i32(t0);
 }
 
@@ -6457,7 +6469,7 @@ static void gen_mtvscr(DisasContext *ctx)
         return;
     }
     p = gen_avr_ptr(rD(ctx->opcode));
-    gen_helper_mtvscr(p);
+    gen_helper_mtvscr(cpu_env, p);
     tcg_temp_free_ptr(p);
 }
 
@@ -6496,6 +6508,23 @@ static void glue(gen_, name)(DisasContext *ctx)
     tcg_temp_free_ptr(rd);                                              \
 }
 
+#define GEN_VXFORM_ENV(name, opc2, opc3)                                \
+static void glue(gen_, name)(DisasContext *ctx)                         \
+{                                                                       \
+    TCGv_ptr ra, rb, rd;                                                \
+    if (unlikely(!ctx->altivec_enabled)) {                              \
+        gen_exception(ctx, POWERPC_EXCP_VPU);                           \
+        return;                                                         \
+    }                                                                   \
+    ra = gen_avr_ptr(rA(ctx->opcode));                                  \
+    rb = gen_avr_ptr(rB(ctx->opcode));                                  \
+    rd = gen_avr_ptr(rD(ctx->opcode));                                  \
+    gen_helper_##name(rd, cpu_env, ra, rb);                             \
+    tcg_temp_free_ptr(ra);                                              \
+    tcg_temp_free_ptr(rb);                                              \
+    tcg_temp_free_ptr(rd);                                              \
+}
+
 GEN_VXFORM(vaddubm, 0, 0);
 GEN_VXFORM(vadduhm, 0, 1);
 GEN_VXFORM(vadduwm, 0, 2);
@@ -6547,41 +6576,41 @@ GEN_VXFORM(vslo, 6, 16);
 GEN_VXFORM(vsro, 6, 17);
 GEN_VXFORM(vaddcuw, 0, 6);
 GEN_VXFORM(vsubcuw, 0, 22);
-GEN_VXFORM(vaddubs, 0, 8);
-GEN_VXFORM(vadduhs, 0, 9);
-GEN_VXFORM(vadduws, 0, 10);
-GEN_VXFORM(vaddsbs, 0, 12);
-GEN_VXFORM(vaddshs, 0, 13);
-GEN_VXFORM(vaddsws, 0, 14);
-GEN_VXFORM(vsububs, 0, 24);
-GEN_VXFORM(vsubuhs, 0, 25);
-GEN_VXFORM(vsubuws, 0, 26);
-GEN_VXFORM(vsubsbs, 0, 28);
-GEN_VXFORM(vsubshs, 0, 29);
-GEN_VXFORM(vsubsws, 0, 30);
+GEN_VXFORM_ENV(vaddubs, 0, 8);
+GEN_VXFORM_ENV(vadduhs, 0, 9);
+GEN_VXFORM_ENV(vadduws, 0, 10);
+GEN_VXFORM_ENV(vaddsbs, 0, 12);
+GEN_VXFORM_ENV(vaddshs, 0, 13);
+GEN_VXFORM_ENV(vaddsws, 0, 14);
+GEN_VXFORM_ENV(vsububs, 0, 24);
+GEN_VXFORM_ENV(vsubuhs, 0, 25);
+GEN_VXFORM_ENV(vsubuws, 0, 26);
+GEN_VXFORM_ENV(vsubsbs, 0, 28);
+GEN_VXFORM_ENV(vsubshs, 0, 29);
+GEN_VXFORM_ENV(vsubsws, 0, 30);
 GEN_VXFORM(vrlb, 2, 0);
 GEN_VXFORM(vrlh, 2, 1);
 GEN_VXFORM(vrlw, 2, 2);
 GEN_VXFORM(vsl, 2, 7);
 GEN_VXFORM(vsr, 2, 11);
-GEN_VXFORM(vpkuhum, 7, 0);
-GEN_VXFORM(vpkuwum, 7, 1);
-GEN_VXFORM(vpkuhus, 7, 2);
-GEN_VXFORM(vpkuwus, 7, 3);
-GEN_VXFORM(vpkshus, 7, 4);
-GEN_VXFORM(vpkswus, 7, 5);
-GEN_VXFORM(vpkshss, 7, 6);
-GEN_VXFORM(vpkswss, 7, 7);
+GEN_VXFORM_ENV(vpkuhum, 7, 0);
+GEN_VXFORM_ENV(vpkuwum, 7, 1);
+GEN_VXFORM_ENV(vpkuhus, 7, 2);
+GEN_VXFORM_ENV(vpkuwus, 7, 3);
+GEN_VXFORM_ENV(vpkshus, 7, 4);
+GEN_VXFORM_ENV(vpkswus, 7, 5);
+GEN_VXFORM_ENV(vpkshss, 7, 6);
+GEN_VXFORM_ENV(vpkswss, 7, 7);
 GEN_VXFORM(vpkpx, 7, 12);
-GEN_VXFORM(vsum4ubs, 4, 24);
-GEN_VXFORM(vsum4sbs, 4, 28);
-GEN_VXFORM(vsum4shs, 4, 25);
-GEN_VXFORM(vsum2sws, 4, 26);
-GEN_VXFORM(vsumsws, 4, 30);
-GEN_VXFORM(vaddfp, 5, 0);
-GEN_VXFORM(vsubfp, 5, 1);
-GEN_VXFORM(vmaxfp, 5, 16);
-GEN_VXFORM(vminfp, 5, 17);
+GEN_VXFORM_ENV(vsum4ubs, 4, 24);
+GEN_VXFORM_ENV(vsum4sbs, 4, 28);
+GEN_VXFORM_ENV(vsum4shs, 4, 25);
+GEN_VXFORM_ENV(vsum2sws, 4, 26);
+GEN_VXFORM_ENV(vsumsws, 4, 30);
+GEN_VXFORM_ENV(vaddfp, 5, 0);
+GEN_VXFORM_ENV(vsubfp, 5, 1);
+GEN_VXFORM_ENV(vmaxfp, 5, 16);
+GEN_VXFORM_ENV(vminfp, 5, 17);
 
 #define GEN_VXRFORM1(opname, name, str, opc2, opc3)                     \
 static void glue(gen_, name)(DisasContext *ctx)                         \
@@ -6594,7 +6623,7 @@ static void glue(gen_, name)(DisasContext *ctx)                         \
         ra = gen_avr_ptr(rA(ctx->opcode));                              \
         rb = gen_avr_ptr(rB(ctx->opcode));                              \
         rd = gen_avr_ptr(rD(ctx->opcode));                              \
-        gen_helper_##opname (rd, ra, rb);                               \
+        gen_helper_##opname(cpu_env, rd, ra, rb);                       \
         tcg_temp_free_ptr(ra);                                          \
         tcg_temp_free_ptr(rb);                                          \
         tcg_temp_free_ptr(rd);                                          \
@@ -6653,20 +6682,36 @@ static void glue(gen_, name)(DisasContext *ctx)
         tcg_temp_free_ptr(rd);                                         \
     }
 
+#define GEN_VXFORM_NOA_ENV(name, opc2, opc3)                            \
+static void glue(gen_, name)(DisasContext *ctx)                         \
+    {                                                                   \
+        TCGv_ptr rb, rd;                                                \
+                                                                        \
+        if (unlikely(!ctx->altivec_enabled)) {                          \
+            gen_exception(ctx, POWERPC_EXCP_VPU);                       \
+            return;                                                     \
+        }                                                               \
+        rb = gen_avr_ptr(rB(ctx->opcode));                              \
+        rd = gen_avr_ptr(rD(ctx->opcode));                              \
+        gen_helper_##name(cpu_env, rd, rb);                             \
+        tcg_temp_free_ptr(rb);                                          \
+        tcg_temp_free_ptr(rd);                                          \
+    }
+
 GEN_VXFORM_NOA(vupkhsb, 7, 8);
 GEN_VXFORM_NOA(vupkhsh, 7, 9);
 GEN_VXFORM_NOA(vupklsb, 7, 10);
 GEN_VXFORM_NOA(vupklsh, 7, 11);
 GEN_VXFORM_NOA(vupkhpx, 7, 13);
 GEN_VXFORM_NOA(vupklpx, 7, 15);
-GEN_VXFORM_NOA(vrefp, 5, 4);
-GEN_VXFORM_NOA(vrsqrtefp, 5, 5);
-GEN_VXFORM_NOA(vexptefp, 5, 6);
-GEN_VXFORM_NOA(vlogefp, 5, 7);
-GEN_VXFORM_NOA(vrfim, 5, 8);
-GEN_VXFORM_NOA(vrfin, 5, 9);
-GEN_VXFORM_NOA(vrfip, 5, 10);
-GEN_VXFORM_NOA(vrfiz, 5, 11);
+GEN_VXFORM_NOA_ENV(vrefp, 5, 4);
+GEN_VXFORM_NOA_ENV(vrsqrtefp, 5, 5);
+GEN_VXFORM_NOA_ENV(vexptefp, 5, 6);
+GEN_VXFORM_NOA_ENV(vlogefp, 5, 7);
+GEN_VXFORM_NOA_ENV(vrfim, 5, 8);
+GEN_VXFORM_NOA_ENV(vrfin, 5, 9);
+GEN_VXFORM_NOA_ENV(vrfip, 5, 10);
+GEN_VXFORM_NOA_ENV(vrfiz, 5, 11);
 
 #define GEN_VXFORM_SIMM(name, opc2, opc3)                               \
 static void glue(gen_, name)(DisasContext *ctx)                                 \
@@ -6702,13 +6747,32 @@ static void glue(gen_, name)(DisasContext *ctx)
         tcg_temp_free_ptr(rd);                                          \
     }
 
+#define GEN_VXFORM_UIMM_ENV(name, opc2, opc3)                           \
+static void glue(gen_, name)(DisasContext *ctx)                         \
+    {                                                                   \
+        TCGv_ptr rb, rd;                                                \
+        TCGv_i32 uimm;                                                  \
+                                                                        \
+        if (unlikely(!ctx->altivec_enabled)) {                          \
+            gen_exception(ctx, POWERPC_EXCP_VPU);                       \
+            return;                                                     \
+        }                                                               \
+        uimm = tcg_const_i32(UIMM5(ctx->opcode));                       \
+        rb = gen_avr_ptr(rB(ctx->opcode));                              \
+        rd = gen_avr_ptr(rD(ctx->opcode));                              \
+        gen_helper_##name(cpu_env, rd, rb, uimm);                       \
+        tcg_temp_free_i32(uimm);                                        \
+        tcg_temp_free_ptr(rb);                                          \
+        tcg_temp_free_ptr(rd);                                          \
+    }
+
 GEN_VXFORM_UIMM(vspltb, 6, 8);
 GEN_VXFORM_UIMM(vsplth, 6, 9);
 GEN_VXFORM_UIMM(vspltw, 6, 10);
-GEN_VXFORM_UIMM(vcfux, 5, 12);
-GEN_VXFORM_UIMM(vcfsx, 5, 13);
-GEN_VXFORM_UIMM(vctuxs, 5, 14);
-GEN_VXFORM_UIMM(vctsxs, 5, 15);
+GEN_VXFORM_UIMM_ENV(vcfux, 5, 12);
+GEN_VXFORM_UIMM_ENV(vcfsx, 5, 13);
+GEN_VXFORM_UIMM_ENV(vctuxs, 5, 14);
+GEN_VXFORM_UIMM_ENV(vctsxs, 5, 15);
 
 static void gen_vsldoi(DisasContext *ctx)
 {
@@ -6730,7 +6794,7 @@ static void gen_vsldoi(DisasContext *ctx)
 }
 
 #define GEN_VAFORM_PAIRED(name0, name1, opc2)                           \
-static void glue(gen_, name0##_##name1)(DisasContext *ctx)                      \
+static void glue(gen_, name0##_##name1)(DisasContext *ctx)              \
     {                                                                   \
         TCGv_ptr ra, rb, rc, rd;                                        \
         if (unlikely(!ctx->altivec_enabled)) {                          \
@@ -6742,9 +6806,9 @@ static void glue(gen_, name0##_##name1)(DisasContext *ctx)
         rc = gen_avr_ptr(rC(ctx->opcode));                              \
         rd = gen_avr_ptr(rD(ctx->opcode));                              \
         if (Rc(ctx->opcode)) {                                          \
-            gen_helper_##name1 (rd, ra, rb, rc);                        \
+            gen_helper_##name1(cpu_env, rd, ra, rb, rc);                \
         } else {                                                        \
-            gen_helper_##name0 (rd, ra, rb, rc);                        \
+            gen_helper_##name0(cpu_env, rd, ra, rb, rc);                \
         }                                                               \
         tcg_temp_free_ptr(ra);                                          \
         tcg_temp_free_ptr(rb);                                          \
commit 64654ded79762878a6207ccb9b299c69e9a90acf
Author: Blue Swirl <blauwirbel at gmail.com>
Date:   Wed May 30 04:23:28 2012 +0000

    ppc: Split integer and vector ops
    
    Move integer and vector ops to int_helper.c.
    
    Signed-off-by: Blue Swirl <blauwirbel at gmail.com>
    Signed-off-by: Alexander Graf <agraf at suse.de>
    Signed-off-by: Andreas Färber <afaerber at suse.de>
    Signed-off-by: Alexander Graf <agraf at suse.de>

diff --git a/target-ppc/Makefile.objs b/target-ppc/Makefile.objs
index 5bea9c3..97e440b 100644
--- a/target-ppc/Makefile.objs
+++ b/target-ppc/Makefile.objs
@@ -4,5 +4,7 @@ obj-$(CONFIG_KVM) += kvm.o kvm_ppc.o
 obj-y += op_helper.o helper.o
 obj-y += excp_helper.o
 obj-y += fpu_helper.o
+obj-y += int_helper.o
 
+$(obj)/int_helper.o: QEMU_CFLAGS += $(HELPER_CFLAGS)
 $(obj)/op_helper.o: QEMU_CFLAGS += $(HELPER_CFLAGS)
diff --git a/target-ppc/int_helper.c b/target-ppc/int_helper.c
new file mode 100644
index 0000000..71c7304
--- /dev/null
+++ b/target-ppc/int_helper.c
@@ -0,0 +1,1538 @@
+/*
+ *  PowerPC integer and vector emulation helpers for QEMU.
+ *
+ *  Copyright (c) 2003-2007 Jocelyn Mayer
+ *
+ * This library is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Lesser General Public
+ * License as published by the Free Software Foundation; either
+ * version 2 of the License, or (at your option) any later version.
+ *
+ * This library is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
+ * Lesser General Public License for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public
+ * License along with this library; if not, see <http://www.gnu.org/licenses/>.
+ */
+#include "cpu.h"
+#include "dyngen-exec.h"
+#include "host-utils.h"
+#include "helper.h"
+
+#include "helper_regs.h"
+/*****************************************************************************/
+/* Fixed point operations helpers */
+#if defined(TARGET_PPC64)
+
+/* multiply high word */
+uint64_t helper_mulhd(uint64_t arg1, uint64_t arg2)
+{
+    uint64_t tl, th;
+
+    muls64(&tl, &th, arg1, arg2);
+    return th;
+}
+
+/* multiply high word unsigned */
+uint64_t helper_mulhdu(uint64_t arg1, uint64_t arg2)
+{
+    uint64_t tl, th;
+
+    mulu64(&tl, &th, arg1, arg2);
+    return th;
+}
+
+uint64_t helper_mulldo(uint64_t arg1, uint64_t arg2)
+{
+    int64_t th;
+    uint64_t tl;
+
+    muls64(&tl, (uint64_t *)&th, arg1, arg2);
+    /* If th != 0 && th != -1, then we had an overflow */
+    if (likely((uint64_t)(th + 1) <= 1)) {
+        env->xer &= ~(1 << XER_OV);
+    } else {
+        env->xer |= (1 << XER_OV) | (1 << XER_SO);
+    }
+    return (int64_t)tl;
+}
+#endif
+
+target_ulong helper_cntlzw(target_ulong t)
+{
+    return clz32(t);
+}
+
+#if defined(TARGET_PPC64)
+target_ulong helper_cntlzd(target_ulong t)
+{
+    return clz64(t);
+}
+#endif
+
+/* shift right arithmetic helper */
+target_ulong helper_sraw(target_ulong value, target_ulong shift)
+{
+    int32_t ret;
+
+    if (likely(!(shift & 0x20))) {
+        if (likely((uint32_t)shift != 0)) {
+            shift &= 0x1f;
+            ret = (int32_t)value >> shift;
+            if (likely(ret >= 0 || (value & ((1 << shift) - 1)) == 0)) {
+                env->xer &= ~(1 << XER_CA);
+            } else {
+                env->xer |= (1 << XER_CA);
+            }
+        } else {
+            ret = (int32_t)value;
+            env->xer &= ~(1 << XER_CA);
+        }
+    } else {
+        ret = (int32_t)value >> 31;
+        if (ret) {
+            env->xer |= (1 << XER_CA);
+        } else {
+            env->xer &= ~(1 << XER_CA);
+        }
+    }
+    return (target_long)ret;
+}
+
+#if defined(TARGET_PPC64)
+target_ulong helper_srad(target_ulong value, target_ulong shift)
+{
+    int64_t ret;
+
+    if (likely(!(shift & 0x40))) {
+        if (likely((uint64_t)shift != 0)) {
+            shift &= 0x3f;
+            ret = (int64_t)value >> shift;
+            if (likely(ret >= 0 || (value & ((1 << shift) - 1)) == 0)) {
+                env->xer &= ~(1 << XER_CA);
+            } else {
+                env->xer |= (1 << XER_CA);
+            }
+        } else {
+            ret = (int64_t)value;
+            env->xer &= ~(1 << XER_CA);
+        }
+    } else {
+        ret = (int64_t)value >> 63;
+        if (ret) {
+            env->xer |= (1 << XER_CA);
+        } else {
+            env->xer &= ~(1 << XER_CA);
+        }
+    }
+    return ret;
+}
+#endif
+
+#if defined(TARGET_PPC64)
+target_ulong helper_popcntb(target_ulong val)
+{
+    val = (val & 0x5555555555555555ULL) + ((val >>  1) &
+                                           0x5555555555555555ULL);
+    val = (val & 0x3333333333333333ULL) + ((val >>  2) &
+                                           0x3333333333333333ULL);
+    val = (val & 0x0f0f0f0f0f0f0f0fULL) + ((val >>  4) &
+                                           0x0f0f0f0f0f0f0f0fULL);
+    return val;
+}
+
+target_ulong helper_popcntw(target_ulong val)
+{
+    val = (val & 0x5555555555555555ULL) + ((val >>  1) &
+                                           0x5555555555555555ULL);
+    val = (val & 0x3333333333333333ULL) + ((val >>  2) &
+                                           0x3333333333333333ULL);
+    val = (val & 0x0f0f0f0f0f0f0f0fULL) + ((val >>  4) &
+                                           0x0f0f0f0f0f0f0f0fULL);
+    val = (val & 0x00ff00ff00ff00ffULL) + ((val >>  8) &
+                                           0x00ff00ff00ff00ffULL);
+    val = (val & 0x0000ffff0000ffffULL) + ((val >> 16) &
+                                           0x0000ffff0000ffffULL);
+    return val;
+}
+
+target_ulong helper_popcntd(target_ulong val)
+{
+    return ctpop64(val);
+}
+#else
+target_ulong helper_popcntb(target_ulong val)
+{
+    val = (val & 0x55555555) + ((val >>  1) & 0x55555555);
+    val = (val & 0x33333333) + ((val >>  2) & 0x33333333);
+    val = (val & 0x0f0f0f0f) + ((val >>  4) & 0x0f0f0f0f);
+    return val;
+}
+
+target_ulong helper_popcntw(target_ulong val)
+{
+    val = (val & 0x55555555) + ((val >>  1) & 0x55555555);
+    val = (val & 0x33333333) + ((val >>  2) & 0x33333333);
+    val = (val & 0x0f0f0f0f) + ((val >>  4) & 0x0f0f0f0f);
+    val = (val & 0x00ff00ff) + ((val >>  8) & 0x00ff00ff);
+    val = (val & 0x0000ffff) + ((val >> 16) & 0x0000ffff);
+    return val;
+}
+#endif
+
+/*****************************************************************************/
+/* PowerPC 601 specific instructions (POWER bridge) */
+target_ulong helper_div(target_ulong arg1, target_ulong arg2)
+{
+    uint64_t tmp = (uint64_t)arg1 << 32 | env->spr[SPR_MQ];
+
+    if (((int32_t)tmp == INT32_MIN && (int32_t)arg2 == (int32_t)-1) ||
+        (int32_t)arg2 == 0) {
+        env->spr[SPR_MQ] = 0;
+        return INT32_MIN;
+    } else {
+        env->spr[SPR_MQ] = tmp % arg2;
+        return  tmp / (int32_t)arg2;
+    }
+}
+
+target_ulong helper_divo(target_ulong arg1, target_ulong arg2)
+{
+    uint64_t tmp = (uint64_t)arg1 << 32 | env->spr[SPR_MQ];
+
+    if (((int32_t)tmp == INT32_MIN && (int32_t)arg2 == (int32_t)-1) ||
+        (int32_t)arg2 == 0) {
+        env->xer |= (1 << XER_OV) | (1 << XER_SO);
+        env->spr[SPR_MQ] = 0;
+        return INT32_MIN;
+    } else {
+        env->spr[SPR_MQ] = tmp % arg2;
+        tmp /= (int32_t)arg2;
+        if ((int32_t)tmp != tmp) {
+            env->xer |= (1 << XER_OV) | (1 << XER_SO);
+        } else {
+            env->xer &= ~(1 << XER_OV);
+        }
+        return tmp;
+    }
+}
+
+target_ulong helper_divs(target_ulong arg1, target_ulong arg2)
+{
+    if (((int32_t)arg1 == INT32_MIN && (int32_t)arg2 == (int32_t)-1) ||
+        (int32_t)arg2 == 0) {
+        env->spr[SPR_MQ] = 0;
+        return INT32_MIN;
+    } else {
+        env->spr[SPR_MQ] = (int32_t)arg1 % (int32_t)arg2;
+        return (int32_t)arg1 / (int32_t)arg2;
+    }
+}
+
+target_ulong helper_divso(target_ulong arg1, target_ulong arg2)
+{
+    if (((int32_t)arg1 == INT32_MIN && (int32_t)arg2 == (int32_t)-1) ||
+        (int32_t)arg2 == 0) {
+        env->xer |= (1 << XER_OV) | (1 << XER_SO);
+        env->spr[SPR_MQ] = 0;
+        return INT32_MIN;
+    } else {
+        env->xer &= ~(1 << XER_OV);
+        env->spr[SPR_MQ] = (int32_t)arg1 % (int32_t)arg2;
+        return (int32_t)arg1 / (int32_t)arg2;
+    }
+}
+
+/*****************************************************************************/
+/* 602 specific instructions */
+/* mfrom is the most crazy instruction ever seen, imho ! */
+/* Real implementation uses a ROM table. Do the same */
+/* Extremely decomposed:
+ *                      -arg / 256
+ * return 256 * log10(10           + 1.0) + 0.5
+ */
+#if !defined(CONFIG_USER_ONLY)
+target_ulong helper_602_mfrom(target_ulong arg)
+{
+    if (likely(arg < 602)) {
+#include "mfrom_table.c"
+        return mfrom_ROM_table[arg];
+    } else {
+        return 0;
+    }
+}
+#endif
+
+/*****************************************************************************/
+/* Altivec extension helpers */
+#if defined(HOST_WORDS_BIGENDIAN)
+#define HI_IDX 0
+#define LO_IDX 1
+#else
+#define HI_IDX 1
+#define LO_IDX 0
+#endif
+
+#if defined(HOST_WORDS_BIGENDIAN)
+#define VECTOR_FOR_INORDER_I(index, element)                    \
+    for (index = 0; index < ARRAY_SIZE(r->element); index++)
+#else
+#define VECTOR_FOR_INORDER_I(index, element)                    \
+    for (index = ARRAY_SIZE(r->element)-1; index >= 0; index--)
+#endif
+
+/* If X is a NaN, store the corresponding QNaN into RESULT.  Otherwise,
+ * execute the following block.  */
+#define DO_HANDLE_NAN(result, x)                        \
+    if (float32_is_any_nan(x)) {                        \
+        CPU_FloatU __f;                                 \
+        __f.f = x;                                      \
+        __f.l = __f.l | (1 << 22);  /* Set QNaN bit. */ \
+        result = __f.f;                                 \
+    } else
+
+#define HANDLE_NAN1(result, x)                  \
+    DO_HANDLE_NAN(result, x)
+#define HANDLE_NAN2(result, x, y)                       \
+    DO_HANDLE_NAN(result, x) DO_HANDLE_NAN(result, y)
+#define HANDLE_NAN3(result, x, y, z)                                    \
+    DO_HANDLE_NAN(result, x) DO_HANDLE_NAN(result, y) DO_HANDLE_NAN(result, z)
+
+/* Saturating arithmetic helpers.  */
+#define SATCVT(from, to, from_type, to_type, min, max)          \
+    static inline to_type cvt##from##to(from_type x, int *sat)  \
+    {                                                           \
+        to_type r;                                              \
+                                                                \
+        if (x < (from_type)min) {                               \
+            r = min;                                            \
+            *sat = 1;                                           \
+        } else if (x > (from_type)max) {                        \
+            r = max;                                            \
+            *sat = 1;                                           \
+        } else {                                                \
+            r = x;                                              \
+        }                                                       \
+        return r;                                               \
+    }
+#define SATCVTU(from, to, from_type, to_type, min, max)         \
+    static inline to_type cvt##from##to(from_type x, int *sat)  \
+    {                                                           \
+        to_type r;                                              \
+                                                                \
+        if (x > (from_type)max) {                               \
+            r = max;                                            \
+            *sat = 1;                                           \
+        } else {                                                \
+            r = x;                                              \
+        }                                                       \
+        return r;                                               \
+    }
+SATCVT(sh, sb, int16_t, int8_t, INT8_MIN, INT8_MAX)
+SATCVT(sw, sh, int32_t, int16_t, INT16_MIN, INT16_MAX)
+SATCVT(sd, sw, int64_t, int32_t, INT32_MIN, INT32_MAX)
+
+SATCVTU(uh, ub, uint16_t, uint8_t, 0, UINT8_MAX)
+SATCVTU(uw, uh, uint32_t, uint16_t, 0, UINT16_MAX)
+SATCVTU(ud, uw, uint64_t, uint32_t, 0, UINT32_MAX)
+SATCVT(sh, ub, int16_t, uint8_t, 0, UINT8_MAX)
+SATCVT(sw, uh, int32_t, uint16_t, 0, UINT16_MAX)
+SATCVT(sd, uw, int64_t, uint32_t, 0, UINT32_MAX)
+#undef SATCVT
+#undef SATCVTU
+
+void helper_lvsl(ppc_avr_t *r, target_ulong sh)
+{
+    int i, j = (sh & 0xf);
+
+    VECTOR_FOR_INORDER_I(i, u8) {
+        r->u8[i] = j++;
+    }
+}
+
+void helper_lvsr(ppc_avr_t *r, target_ulong sh)
+{
+    int i, j = 0x10 - (sh & 0xf);
+
+    VECTOR_FOR_INORDER_I(i, u8) {
+        r->u8[i] = j++;
+    }
+}
+
+void helper_mtvscr(ppc_avr_t *r)
+{
+#if defined(HOST_WORDS_BIGENDIAN)
+    env->vscr = r->u32[3];
+#else
+    env->vscr = r->u32[0];
+#endif
+    set_flush_to_zero(vscr_nj, &env->vec_status);
+}
+
+void helper_vaddcuw(ppc_avr_t *r, ppc_avr_t *a, ppc_avr_t *b)
+{
+    int i;
+
+    for (i = 0; i < ARRAY_SIZE(r->u32); i++) {
+        r->u32[i] = ~a->u32[i] < b->u32[i];
+    }
+}
+
+#define VARITH_DO(name, op, element)                                    \
+    void helper_v##name(ppc_avr_t *r, ppc_avr_t *a, ppc_avr_t *b)       \
+    {                                                                   \
+        int i;                                                          \
+                                                                        \
+        for (i = 0; i < ARRAY_SIZE(r->element); i++) {                  \
+            r->element[i] = a->element[i] op b->element[i];             \
+        }                                                               \
+    }
+#define VARITH(suffix, element)                 \
+    VARITH_DO(add##suffix, +, element)          \
+    VARITH_DO(sub##suffix, -, element)
+VARITH(ubm, u8)
+VARITH(uhm, u16)
+VARITH(uwm, u32)
+#undef VARITH_DO
+#undef VARITH
+
+#define VARITHFP(suffix, func)                                          \
+    void helper_v##suffix(ppc_avr_t *r, ppc_avr_t *a, ppc_avr_t *b)     \
+    {                                                                   \
+        int i;                                                          \
+                                                                        \
+        for (i = 0; i < ARRAY_SIZE(r->f); i++) {                        \
+            HANDLE_NAN2(r->f[i], a->f[i], b->f[i]) {                    \
+                r->f[i] = func(a->f[i], b->f[i], &env->vec_status);     \
+            }                                                           \
+        }                                                               \
+    }
+VARITHFP(addfp, float32_add)
+VARITHFP(subfp, float32_sub)
+#undef VARITHFP
+
+#define VARITHSAT_CASE(type, op, cvt, element)                          \
+    {                                                                   \
+        type result = (type)a->element[i] op (type)b->element[i];       \
+        r->element[i] = cvt(result, &sat);                              \
+    }
+
+#define VARITHSAT_DO(name, op, optype, cvt, element)                    \
+    void helper_v##name(ppc_avr_t *r, ppc_avr_t *a, ppc_avr_t *b)       \
+    {                                                                   \
+        int sat = 0;                                                    \
+        int i;                                                          \
+                                                                        \
+        for (i = 0; i < ARRAY_SIZE(r->element); i++) {                  \
+            switch (sizeof(r->element[0])) {                            \
+            case 1:                                                     \
+                VARITHSAT_CASE(optype, op, cvt, element);               \
+                break;                                                  \
+            case 2:                                                     \
+                VARITHSAT_CASE(optype, op, cvt, element);               \
+                break;                                                  \
+            case 4:                                                     \
+                VARITHSAT_CASE(optype, op, cvt, element);               \
+                break;                                                  \
+            }                                                           \
+        }                                                               \
+        if (sat) {                                                      \
+            env->vscr |= (1 << VSCR_SAT);                               \
+        }                                                               \
+    }
+#define VARITHSAT_SIGNED(suffix, element, optype, cvt)          \
+    VARITHSAT_DO(adds##suffix##s, +, optype, cvt, element)      \
+    VARITHSAT_DO(subs##suffix##s, -, optype, cvt, element)
+#define VARITHSAT_UNSIGNED(suffix, element, optype, cvt)        \
+    VARITHSAT_DO(addu##suffix##s, +, optype, cvt, element)      \
+    VARITHSAT_DO(subu##suffix##s, -, optype, cvt, element)
+VARITHSAT_SIGNED(b, s8, int16_t, cvtshsb)
+VARITHSAT_SIGNED(h, s16, int32_t, cvtswsh)
+VARITHSAT_SIGNED(w, s32, int64_t, cvtsdsw)
+VARITHSAT_UNSIGNED(b, u8, uint16_t, cvtshub)
+VARITHSAT_UNSIGNED(h, u16, uint32_t, cvtswuh)
+VARITHSAT_UNSIGNED(w, u32, uint64_t, cvtsduw)
+#undef VARITHSAT_CASE
+#undef VARITHSAT_DO
+#undef VARITHSAT_SIGNED
+#undef VARITHSAT_UNSIGNED
+
+#define VAVG_DO(name, element, etype)                                   \
+    void helper_v##name(ppc_avr_t *r, ppc_avr_t *a, ppc_avr_t *b)       \
+    {                                                                   \
+        int i;                                                          \
+                                                                        \
+        for (i = 0; i < ARRAY_SIZE(r->element); i++) {                  \
+            etype x = (etype)a->element[i] + (etype)b->element[i] + 1;  \
+            r->element[i] = x >> 1;                                     \
+        }                                                               \
+    }
+
+#define VAVG(type, signed_element, signed_type, unsigned_element,       \
+             unsigned_type)                                             \
+    VAVG_DO(avgs##type, signed_element, signed_type)                    \
+    VAVG_DO(avgu##type, unsigned_element, unsigned_type)
+VAVG(b, s8, int16_t, u8, uint16_t)
+VAVG(h, s16, int32_t, u16, uint32_t)
+VAVG(w, s32, int64_t, u32, uint64_t)
+#undef VAVG_DO
+#undef VAVG
+
+#define VCF(suffix, cvt, element)                                       \
+    void helper_vcf##suffix(ppc_avr_t *r, ppc_avr_t *b, uint32_t uim)   \
+    {                                                                   \
+        int i;                                                          \
+                                                                        \
+        for (i = 0; i < ARRAY_SIZE(r->f); i++) {                        \
+            float32 t = cvt(b->element[i], &env->vec_status);           \
+            r->f[i] = float32_scalbn(t, -uim, &env->vec_status);        \
+        }                                                               \
+    }
+VCF(ux, uint32_to_float32, u32)
+VCF(sx, int32_to_float32, s32)
+#undef VCF
+
+#define VCMP_DO(suffix, compare, element, record)                       \
+    void helper_vcmp##suffix(ppc_avr_t *r, ppc_avr_t *a, ppc_avr_t *b)  \
+    {                                                                   \
+        uint32_t ones = (uint32_t)-1;                                   \
+        uint32_t all = ones;                                            \
+        uint32_t none = 0;                                              \
+        int i;                                                          \
+                                                                        \
+        for (i = 0; i < ARRAY_SIZE(r->element); i++) {                  \
+            uint32_t result = (a->element[i] compare b->element[i] ?    \
+                               ones : 0x0);                             \
+            switch (sizeof(a->element[0])) {                            \
+            case 4:                                                     \
+                r->u32[i] = result;                                     \
+                break;                                                  \
+            case 2:                                                     \
+                r->u16[i] = result;                                     \
+                break;                                                  \
+            case 1:                                                     \
+                r->u8[i] = result;                                      \
+                break;                                                  \
+            }                                                           \
+            all &= result;                                              \
+            none |= result;                                             \
+        }                                                               \
+        if (record) {                                                   \
+            env->crf[6] = ((all != 0) << 3) | ((none == 0) << 1);       \
+        }                                                               \
+    }
+#define VCMP(suffix, compare, element)          \
+    VCMP_DO(suffix, compare, element, 0)        \
+    VCMP_DO(suffix##_dot, compare, element, 1)
+VCMP(equb, ==, u8)
+VCMP(equh, ==, u16)
+VCMP(equw, ==, u32)
+VCMP(gtub, >, u8)
+VCMP(gtuh, >, u16)
+VCMP(gtuw, >, u32)
+VCMP(gtsb, >, s8)
+VCMP(gtsh, >, s16)
+VCMP(gtsw, >, s32)
+#undef VCMP_DO
+#undef VCMP
+
+#define VCMPFP_DO(suffix, compare, order, record)                       \
+    void helper_vcmp##suffix(ppc_avr_t *r, ppc_avr_t *a, ppc_avr_t *b)  \
+    {                                                                   \
+        uint32_t ones = (uint32_t)-1;                                   \
+        uint32_t all = ones;                                            \
+        uint32_t none = 0;                                              \
+        int i;                                                          \
+                                                                        \
+        for (i = 0; i < ARRAY_SIZE(r->f); i++) {                        \
+            uint32_t result;                                            \
+            int rel = float32_compare_quiet(a->f[i], b->f[i],           \
+                                            &env->vec_status);          \
+            if (rel == float_relation_unordered) {                      \
+                result = 0;                                             \
+            } else if (rel compare order) {                             \
+                result = ones;                                          \
+            } else {                                                    \
+                result = 0;                                             \
+            }                                                           \
+            r->u32[i] = result;                                         \
+            all &= result;                                              \
+            none |= result;                                             \
+        }                                                               \
+        if (record) {                                                   \
+            env->crf[6] = ((all != 0) << 3) | ((none == 0) << 1);       \
+        }                                                               \
+    }
+#define VCMPFP(suffix, compare, order)          \
+    VCMPFP_DO(suffix, compare, order, 0)        \
+    VCMPFP_DO(suffix##_dot, compare, order, 1)
+VCMPFP(eqfp, ==, float_relation_equal)
+VCMPFP(gefp, !=, float_relation_less)
+VCMPFP(gtfp, ==, float_relation_greater)
+#undef VCMPFP_DO
+#undef VCMPFP
+
+static inline void vcmpbfp_internal(ppc_avr_t *r, ppc_avr_t *a, ppc_avr_t *b,
+                                    int record)
+{
+    int i;
+    int all_in = 0;
+
+    for (i = 0; i < ARRAY_SIZE(r->f); i++) {
+        int le_rel = float32_compare_quiet(a->f[i], b->f[i], &env->vec_status);
+        if (le_rel == float_relation_unordered) {
+            r->u32[i] = 0xc0000000;
+            /* ALL_IN does not need to be updated here.  */
+        } else {
+            float32 bneg = float32_chs(b->f[i]);
+            int ge_rel = float32_compare_quiet(a->f[i], bneg, &env->vec_status);
+            int le = le_rel != float_relation_greater;
+            int ge = ge_rel != float_relation_less;
+
+            r->u32[i] = ((!le) << 31) | ((!ge) << 30);
+            all_in |= (!le | !ge);
+        }
+    }
+    if (record) {
+        env->crf[6] = (all_in == 0) << 1;
+    }
+}
+
+void helper_vcmpbfp(ppc_avr_t *r, ppc_avr_t *a, ppc_avr_t *b)
+{
+    vcmpbfp_internal(r, a, b, 0);
+}
+
+void helper_vcmpbfp_dot(ppc_avr_t *r, ppc_avr_t *a, ppc_avr_t *b)
+{
+    vcmpbfp_internal(r, a, b, 1);
+}
+
+#define VCT(suffix, satcvt, element)                                    \
+    void helper_vct##suffix(ppc_avr_t *r, ppc_avr_t *b, uint32_t uim)   \
+    {                                                                   \
+        int i;                                                          \
+        int sat = 0;                                                    \
+        float_status s = env->vec_status;                               \
+                                                                        \
+        set_float_rounding_mode(float_round_to_zero, &s);               \
+        for (i = 0; i < ARRAY_SIZE(r->f); i++) {                        \
+            if (float32_is_any_nan(b->f[i])) {                          \
+                r->element[i] = 0;                                      \
+            } else {                                                    \
+                float64 t = float32_to_float64(b->f[i], &s);            \
+                int64_t j;                                              \
+                                                                        \
+                t = float64_scalbn(t, uim, &s);                         \
+                j = float64_to_int64(t, &s);                            \
+                r->element[i] = satcvt(j, &sat);                        \
+            }                                                           \
+        }                                                               \
+        if (sat) {                                                      \
+            env->vscr |= (1 << VSCR_SAT);                               \
+        }                                                               \
+    }
+VCT(uxs, cvtsduw, u32)
+VCT(sxs, cvtsdsw, s32)
+#undef VCT
+
+void helper_vmaddfp(ppc_avr_t *r, ppc_avr_t *a, ppc_avr_t *b, ppc_avr_t *c)
+{
+    int i;
+
+    for (i = 0; i < ARRAY_SIZE(r->f); i++) {
+        HANDLE_NAN3(r->f[i], a->f[i], b->f[i], c->f[i]) {
+            /* Need to do the computation in higher precision and round
+             * once at the end.  */
+            float64 af, bf, cf, t;
+
+            af = float32_to_float64(a->f[i], &env->vec_status);
+            bf = float32_to_float64(b->f[i], &env->vec_status);
+            cf = float32_to_float64(c->f[i], &env->vec_status);
+            t = float64_mul(af, cf, &env->vec_status);
+            t = float64_add(t, bf, &env->vec_status);
+            r->f[i] = float64_to_float32(t, &env->vec_status);
+        }
+    }
+}
+
+void helper_vmhaddshs(ppc_avr_t *r, ppc_avr_t *a, ppc_avr_t *b, ppc_avr_t *c)
+{
+    int sat = 0;
+    int i;
+
+    for (i = 0; i < ARRAY_SIZE(r->s16); i++) {
+        int32_t prod = a->s16[i] * b->s16[i];
+        int32_t t = (int32_t)c->s16[i] + (prod >> 15);
+
+        r->s16[i] = cvtswsh(t, &sat);
+    }
+
+    if (sat) {
+        env->vscr |= (1 << VSCR_SAT);
+    }
+}
+
+void helper_vmhraddshs(ppc_avr_t *r, ppc_avr_t *a, ppc_avr_t *b, ppc_avr_t *c)
+{
+    int sat = 0;
+    int i;
+
+    for (i = 0; i < ARRAY_SIZE(r->s16); i++) {
+        int32_t prod = a->s16[i] * b->s16[i] + 0x00004000;
+        int32_t t = (int32_t)c->s16[i] + (prod >> 15);
+        r->s16[i] = cvtswsh(t, &sat);
+    }
+
+    if (sat) {
+        env->vscr |= (1 << VSCR_SAT);
+    }
+}
+
+#define VMINMAX_DO(name, compare, element)                              \
+    void helper_v##name(ppc_avr_t *r, ppc_avr_t *a, ppc_avr_t *b)       \
+    {                                                                   \
+        int i;                                                          \
+                                                                        \
+        for (i = 0; i < ARRAY_SIZE(r->element); i++) {                  \
+            if (a->element[i] compare b->element[i]) {                  \
+                r->element[i] = b->element[i];                          \
+            } else {                                                    \
+                r->element[i] = a->element[i];                          \
+            }                                                           \
+        }                                                               \
+    }
+#define VMINMAX(suffix, element)                \
+    VMINMAX_DO(min##suffix, >, element)         \
+    VMINMAX_DO(max##suffix, <, element)
+VMINMAX(sb, s8)
+VMINMAX(sh, s16)
+VMINMAX(sw, s32)
+VMINMAX(ub, u8)
+VMINMAX(uh, u16)
+VMINMAX(uw, u32)
+#undef VMINMAX_DO
+#undef VMINMAX
+
+#define VMINMAXFP(suffix, rT, rF)                                       \
+    void helper_v##suffix(ppc_avr_t *r, ppc_avr_t *a, ppc_avr_t *b)     \
+    {                                                                   \
+        int i;                                                          \
+                                                                        \
+        for (i = 0; i < ARRAY_SIZE(r->f); i++) {                        \
+            HANDLE_NAN2(r->f[i], a->f[i], b->f[i]) {                    \
+                if (float32_lt_quiet(a->f[i], b->f[i],                  \
+                                     &env->vec_status)) {               \
+                    r->f[i] = rT->f[i];                                 \
+                } else {                                                \
+                    r->f[i] = rF->f[i];                                 \
+                }                                                       \
+            }                                                           \
+        }                                                               \
+    }
+VMINMAXFP(minfp, a, b)
+VMINMAXFP(maxfp, b, a)
+#undef VMINMAXFP
+
+void helper_vmladduhm(ppc_avr_t *r, ppc_avr_t *a, ppc_avr_t *b, ppc_avr_t *c)
+{
+    int i;
+
+    for (i = 0; i < ARRAY_SIZE(r->s16); i++) {
+        int32_t prod = a->s16[i] * b->s16[i];
+        r->s16[i] = (int16_t) (prod + c->s16[i]);
+    }
+}
+
+#define VMRG_DO(name, element, highp)                                   \
+    void helper_v##name(ppc_avr_t *r, ppc_avr_t *a, ppc_avr_t *b)       \
+    {                                                                   \
+        ppc_avr_t result;                                               \
+        int i;                                                          \
+        size_t n_elems = ARRAY_SIZE(r->element);                        \
+                                                                        \
+        for (i = 0; i < n_elems / 2; i++) {                             \
+            if (highp) {                                                \
+                result.element[i*2+HI_IDX] = a->element[i];             \
+                result.element[i*2+LO_IDX] = b->element[i];             \
+            } else {                                                    \
+                result.element[n_elems - i * 2 - (1 + HI_IDX)] =        \
+                    b->element[n_elems - i - 1];                        \
+                result.element[n_elems - i * 2 - (1 + LO_IDX)] =        \
+                    a->element[n_elems - i - 1];                        \
+            }                                                           \
+        }                                                               \
+        *r = result;                                                    \
+    }
+#if defined(HOST_WORDS_BIGENDIAN)
+#define MRGHI 0
+#define MRGLO 1
+#else
+#define MRGHI 1
+#define MRGLO 0
+#endif
+#define VMRG(suffix, element)                   \
+    VMRG_DO(mrgl##suffix, element, MRGHI)       \
+    VMRG_DO(mrgh##suffix, element, MRGLO)
+VMRG(b, u8)
+VMRG(h, u16)
+VMRG(w, u32)
+#undef VMRG_DO
+#undef VMRG
+#undef MRGHI
+#undef MRGLO
+
+void helper_vmsummbm(ppc_avr_t *r, ppc_avr_t *a, ppc_avr_t *b, ppc_avr_t *c)
+{
+    int32_t prod[16];
+    int i;
+
+    for (i = 0; i < ARRAY_SIZE(r->s8); i++) {
+        prod[i] = (int32_t)a->s8[i] * b->u8[i];
+    }
+
+    VECTOR_FOR_INORDER_I(i, s32) {
+        r->s32[i] = c->s32[i] + prod[4 * i] + prod[4 * i + 1] +
+            prod[4 * i + 2] + prod[4 * i + 3];
+    }
+}
+
+void helper_vmsumshm(ppc_avr_t *r, ppc_avr_t *a, ppc_avr_t *b, ppc_avr_t *c)
+{
+    int32_t prod[8];
+    int i;
+
+    for (i = 0; i < ARRAY_SIZE(r->s16); i++) {
+        prod[i] = a->s16[i] * b->s16[i];
+    }
+
+    VECTOR_FOR_INORDER_I(i, s32) {
+        r->s32[i] = c->s32[i] + prod[2 * i] + prod[2 * i + 1];
+    }
+}
+
+void helper_vmsumshs(ppc_avr_t *r, ppc_avr_t *a, ppc_avr_t *b, ppc_avr_t *c)
+{
+    int32_t prod[8];
+    int i;
+    int sat = 0;
+
+    for (i = 0; i < ARRAY_SIZE(r->s16); i++) {
+        prod[i] = (int32_t)a->s16[i] * b->s16[i];
+    }
+
+    VECTOR_FOR_INORDER_I(i, s32) {
+        int64_t t = (int64_t)c->s32[i] + prod[2 * i] + prod[2 * i + 1];
+
+        r->u32[i] = cvtsdsw(t, &sat);
+    }
+
+    if (sat) {
+        env->vscr |= (1 << VSCR_SAT);
+    }
+}
+
+void helper_vmsumubm(ppc_avr_t *r, ppc_avr_t *a, ppc_avr_t *b, ppc_avr_t *c)
+{
+    uint16_t prod[16];
+    int i;
+
+    for (i = 0; i < ARRAY_SIZE(r->u8); i++) {
+        prod[i] = a->u8[i] * b->u8[i];
+    }
+
+    VECTOR_FOR_INORDER_I(i, u32) {
+        r->u32[i] = c->u32[i] + prod[4 * i] + prod[4 * i + 1] +
+            prod[4 * i + 2] + prod[4 * i + 3];
+    }
+}
+
+void helper_vmsumuhm(ppc_avr_t *r, ppc_avr_t *a, ppc_avr_t *b, ppc_avr_t *c)
+{
+    uint32_t prod[8];
+    int i;
+
+    for (i = 0; i < ARRAY_SIZE(r->u16); i++) {
+        prod[i] = a->u16[i] * b->u16[i];
+    }
+
+    VECTOR_FOR_INORDER_I(i, u32) {
+        r->u32[i] = c->u32[i] + prod[2 * i] + prod[2 * i + 1];
+    }
+}
+
+void helper_vmsumuhs(ppc_avr_t *r, ppc_avr_t *a, ppc_avr_t *b, ppc_avr_t *c)
+{
+    uint32_t prod[8];
+    int i;
+    int sat = 0;
+
+    for (i = 0; i < ARRAY_SIZE(r->u16); i++) {
+        prod[i] = a->u16[i] * b->u16[i];
+    }
+
+    VECTOR_FOR_INORDER_I(i, s32) {
+        uint64_t t = (uint64_t)c->u32[i] + prod[2 * i] + prod[2 * i + 1];
+
+        r->u32[i] = cvtuduw(t, &sat);
+    }
+
+    if (sat) {
+        env->vscr |= (1 << VSCR_SAT);
+    }
+}
+
+#define VMUL_DO(name, mul_element, prod_element, evenp)                 \
+    void helper_v##name(ppc_avr_t *r, ppc_avr_t *a, ppc_avr_t *b)       \
+    {                                                                   \
+        int i;                                                          \
+                                                                        \
+        VECTOR_FOR_INORDER_I(i, prod_element) {                         \
+            if (evenp) {                                                \
+                r->prod_element[i] = a->mul_element[i * 2 + HI_IDX] *   \
+                    b->mul_element[i * 2 + HI_IDX];                     \
+            } else {                                                    \
+                r->prod_element[i] = a->mul_element[i * 2 + LO_IDX] *   \
+                    b->mul_element[i * 2 + LO_IDX];                     \
+            }                                                           \
+        }                                                               \
+    }
+#define VMUL(suffix, mul_element, prod_element)         \
+    VMUL_DO(mule##suffix, mul_element, prod_element, 1) \
+    VMUL_DO(mulo##suffix, mul_element, prod_element, 0)
+VMUL(sb, s8, s16)
+VMUL(sh, s16, s32)
+VMUL(ub, u8, u16)
+VMUL(uh, u16, u32)
+#undef VMUL_DO
+#undef VMUL
+
+void helper_vnmsubfp(ppc_avr_t *r, ppc_avr_t *a, ppc_avr_t *b, ppc_avr_t *c)
+{
+    int i;
+
+    for (i = 0; i < ARRAY_SIZE(r->f); i++) {
+        HANDLE_NAN3(r->f[i], a->f[i], b->f[i], c->f[i]) {
+            /* Need to do the computation is higher precision and round
+             * once at the end.  */
+            float64 af, bf, cf, t;
+
+            af = float32_to_float64(a->f[i], &env->vec_status);
+            bf = float32_to_float64(b->f[i], &env->vec_status);
+            cf = float32_to_float64(c->f[i], &env->vec_status);
+            t = float64_mul(af, cf, &env->vec_status);
+            t = float64_sub(t, bf, &env->vec_status);
+            t = float64_chs(t);
+            r->f[i] = float64_to_float32(t, &env->vec_status);
+        }
+    }
+}
+
+void helper_vperm(ppc_avr_t *r, ppc_avr_t *a, ppc_avr_t *b, ppc_avr_t *c)
+{
+    ppc_avr_t result;
+    int i;
+
+    VECTOR_FOR_INORDER_I(i, u8) {
+        int s = c->u8[i] & 0x1f;
+#if defined(HOST_WORDS_BIGENDIAN)
+        int index = s & 0xf;
+#else
+        int index = 15 - (s & 0xf);
+#endif
+
+        if (s & 0x10) {
+            result.u8[i] = b->u8[index];
+        } else {
+            result.u8[i] = a->u8[index];
+        }
+    }
+    *r = result;
+}
+
+#if defined(HOST_WORDS_BIGENDIAN)
+#define PKBIG 1
+#else
+#define PKBIG 0
+#endif
+void helper_vpkpx(ppc_avr_t *r, ppc_avr_t *a, ppc_avr_t *b)
+{
+    int i, j;
+    ppc_avr_t result;
+#if defined(HOST_WORDS_BIGENDIAN)
+    const ppc_avr_t *x[2] = { a, b };
+#else
+    const ppc_avr_t *x[2] = { b, a };
+#endif
+
+    VECTOR_FOR_INORDER_I(i, u64) {
+        VECTOR_FOR_INORDER_I(j, u32) {
+            uint32_t e = x[i]->u32[j];
+
+            result.u16[4*i+j] = (((e >> 9) & 0xfc00) |
+                                 ((e >> 6) & 0x3e0) |
+                                 ((e >> 3) & 0x1f));
+        }
+    }
+    *r = result;
+}
+
+#define VPK(suffix, from, to, cvt, dosat)                               \
+    void helper_vpk##suffix(ppc_avr_t *r, ppc_avr_t *a, ppc_avr_t *b)   \
+    {                                                                   \
+        int i;                                                          \
+        int sat = 0;                                                    \
+        ppc_avr_t result;                                               \
+        ppc_avr_t *a0 = PKBIG ? a : b;                                  \
+        ppc_avr_t *a1 = PKBIG ? b : a;                                  \
+                                                                        \
+        VECTOR_FOR_INORDER_I(i, from) {                                 \
+            result.to[i] = cvt(a0->from[i], &sat);                      \
+            result.to[i+ARRAY_SIZE(r->from)] = cvt(a1->from[i], &sat);  \
+        }                                                               \
+        *r = result;                                                    \
+        if (dosat && sat) {                                             \
+            env->vscr |= (1 << VSCR_SAT);                               \
+        }                                                               \
+    }
+#define I(x, y) (x)
+VPK(shss, s16, s8, cvtshsb, 1)
+VPK(shus, s16, u8, cvtshub, 1)
+VPK(swss, s32, s16, cvtswsh, 1)
+VPK(swus, s32, u16, cvtswuh, 1)
+VPK(uhus, u16, u8, cvtuhub, 1)
+VPK(uwus, u32, u16, cvtuwuh, 1)
+VPK(uhum, u16, u8, I, 0)
+VPK(uwum, u32, u16, I, 0)
+#undef I
+#undef VPK
+#undef PKBIG
+
+void helper_vrefp(ppc_avr_t *r, ppc_avr_t *b)
+{
+    int i;
+
+    for (i = 0; i < ARRAY_SIZE(r->f); i++) {
+        HANDLE_NAN1(r->f[i], b->f[i]) {
+            r->f[i] = float32_div(float32_one, b->f[i], &env->vec_status);
+        }
+    }
+}
+
+#define VRFI(suffix, rounding)                                  \
+    void helper_vrfi##suffix(ppc_avr_t *r, ppc_avr_t *b)        \
+    {                                                           \
+        int i;                                                  \
+        float_status s = env->vec_status;                       \
+                                                                \
+        set_float_rounding_mode(rounding, &s);                  \
+        for (i = 0; i < ARRAY_SIZE(r->f); i++) {                \
+            HANDLE_NAN1(r->f[i], b->f[i]) {                     \
+                r->f[i] = float32_round_to_int (b->f[i], &s);   \
+            }                                                   \
+        }                                                       \
+    }
+VRFI(n, float_round_nearest_even)
+VRFI(m, float_round_down)
+VRFI(p, float_round_up)
+VRFI(z, float_round_to_zero)
+#undef VRFI
+
+#define VROTATE(suffix, element)                                        \
+    void helper_vrl##suffix(ppc_avr_t *r, ppc_avr_t *a, ppc_avr_t *b)   \
+    {                                                                   \
+        int i;                                                          \
+                                                                        \
+        for (i = 0; i < ARRAY_SIZE(r->element); i++) {                  \
+            unsigned int mask = ((1 <<                                  \
+                                  (3 + (sizeof(a->element[0]) >> 1)))   \
+                                 - 1);                                  \
+            unsigned int shift = b->element[i] & mask;                  \
+            r->element[i] = (a->element[i] << shift) |                  \
+                (a->element[i] >> (sizeof(a->element[0]) * 8 - shift)); \
+        }                                                               \
+    }
+VROTATE(b, u8)
+VROTATE(h, u16)
+VROTATE(w, u32)
+#undef VROTATE
+
+void helper_vrsqrtefp(ppc_avr_t *r, ppc_avr_t *b)
+{
+    int i;
+
+    for (i = 0; i < ARRAY_SIZE(r->f); i++) {
+        HANDLE_NAN1(r->f[i], b->f[i]) {
+            float32 t = float32_sqrt(b->f[i], &env->vec_status);
+
+            r->f[i] = float32_div(float32_one, t, &env->vec_status);
+        }
+    }
+}
+
+void helper_vsel(ppc_avr_t *r, ppc_avr_t *a, ppc_avr_t *b, ppc_avr_t *c)
+{
+    r->u64[0] = (a->u64[0] & ~c->u64[0]) | (b->u64[0] & c->u64[0]);
+    r->u64[1] = (a->u64[1] & ~c->u64[1]) | (b->u64[1] & c->u64[1]);
+}
+
+void helper_vexptefp(ppc_avr_t *r, ppc_avr_t *b)
+{
+    int i;
+
+    for (i = 0; i < ARRAY_SIZE(r->f); i++) {
+        HANDLE_NAN1(r->f[i], b->f[i]) {
+            r->f[i] = float32_exp2(b->f[i], &env->vec_status);
+        }
+    }
+}
+
+void helper_vlogefp(ppc_avr_t *r, ppc_avr_t *b)
+{
+    int i;
+
+    for (i = 0; i < ARRAY_SIZE(r->f); i++) {
+        HANDLE_NAN1(r->f[i], b->f[i]) {
+            r->f[i] = float32_log2(b->f[i], &env->vec_status);
+        }
+    }
+}
+
+#if defined(HOST_WORDS_BIGENDIAN)
+#define LEFT 0
+#define RIGHT 1
+#else
+#define LEFT 1
+#define RIGHT 0
+#endif
+/* The specification says that the results are undefined if all of the
+ * shift counts are not identical.  We check to make sure that they are
+ * to conform to what real hardware appears to do.  */
+#define VSHIFT(suffix, leftp)                                           \
+    void helper_vs##suffix(ppc_avr_t *r, ppc_avr_t *a, ppc_avr_t *b)    \
+    {                                                                   \
+        int shift = b->u8[LO_IDX*15] & 0x7;                             \
+        int doit = 1;                                                   \
+        int i;                                                          \
+                                                                        \
+        for (i = 0; i < ARRAY_SIZE(r->u8); i++) {                       \
+            doit = doit && ((b->u8[i] & 0x7) == shift);                 \
+        }                                                               \
+        if (doit) {                                                     \
+            if (shift == 0) {                                           \
+                *r = *a;                                                \
+            } else if (leftp) {                                         \
+                uint64_t carry = a->u64[LO_IDX] >> (64 - shift);        \
+                                                                        \
+                r->u64[HI_IDX] = (a->u64[HI_IDX] << shift) | carry;     \
+                r->u64[LO_IDX] = a->u64[LO_IDX] << shift;               \
+            } else {                                                    \
+                uint64_t carry = a->u64[HI_IDX] << (64 - shift);        \
+                                                                        \
+                r->u64[LO_IDX] = (a->u64[LO_IDX] >> shift) | carry;     \
+                r->u64[HI_IDX] = a->u64[HI_IDX] >> shift;               \
+            }                                                           \
+        }                                                               \
+    }
+VSHIFT(l, LEFT)
+VSHIFT(r, RIGHT)
+#undef VSHIFT
+#undef LEFT
+#undef RIGHT
+
+#define VSL(suffix, element)                                            \
+    void helper_vsl##suffix(ppc_avr_t *r, ppc_avr_t *a, ppc_avr_t *b)   \
+    {                                                                   \
+        int i;                                                          \
+                                                                        \
+        for (i = 0; i < ARRAY_SIZE(r->element); i++) {                  \
+            unsigned int mask = ((1 <<                                  \
+                                  (3 + (sizeof(a->element[0]) >> 1)))   \
+                                 - 1);                                  \
+            unsigned int shift = b->element[i] & mask;                  \
+                                                                        \
+            r->element[i] = a->element[i] << shift;                     \
+        }                                                               \
+    }
+VSL(b, u8)
+VSL(h, u16)
+VSL(w, u32)
+#undef VSL
+
+void helper_vsldoi(ppc_avr_t *r, ppc_avr_t *a, ppc_avr_t *b, uint32_t shift)
+{
+    int sh = shift & 0xf;
+    int i;
+    ppc_avr_t result;
+
+#if defined(HOST_WORDS_BIGENDIAN)
+    for (i = 0; i < ARRAY_SIZE(r->u8); i++) {
+        int index = sh + i;
+        if (index > 0xf) {
+            result.u8[i] = b->u8[index - 0x10];
+        } else {
+            result.u8[i] = a->u8[index];
+        }
+    }
+#else
+    for (i = 0; i < ARRAY_SIZE(r->u8); i++) {
+        int index = (16 - sh) + i;
+        if (index > 0xf) {
+            result.u8[i] = a->u8[index - 0x10];
+        } else {
+            result.u8[i] = b->u8[index];
+        }
+    }
+#endif
+    *r = result;
+}
+
+void helper_vslo(ppc_avr_t *r, ppc_avr_t *a, ppc_avr_t *b)
+{
+    int sh = (b->u8[LO_IDX*0xf] >> 3) & 0xf;
+
+#if defined(HOST_WORDS_BIGENDIAN)
+    memmove(&r->u8[0], &a->u8[sh], 16 - sh);
+    memset(&r->u8[16-sh], 0, sh);
+#else
+    memmove(&r->u8[sh], &a->u8[0], 16 - sh);
+    memset(&r->u8[0], 0, sh);
+#endif
+}
+
+/* Experimental testing shows that hardware masks the immediate.  */
+#define _SPLAT_MASKED(element) (splat & (ARRAY_SIZE(r->element) - 1))
+#if defined(HOST_WORDS_BIGENDIAN)
+#define SPLAT_ELEMENT(element) _SPLAT_MASKED(element)
+#else
+#define SPLAT_ELEMENT(element)                                  \
+    (ARRAY_SIZE(r->element) - 1 - _SPLAT_MASKED(element))
+#endif
+#define VSPLT(suffix, element)                                          \
+    void helper_vsplt##suffix(ppc_avr_t *r, ppc_avr_t *b, uint32_t splat) \
+    {                                                                   \
+        uint32_t s = b->element[SPLAT_ELEMENT(element)];                \
+        int i;                                                          \
+                                                                        \
+        for (i = 0; i < ARRAY_SIZE(r->element); i++) {                  \
+            r->element[i] = s;                                          \
+        }                                                               \
+    }
+VSPLT(b, u8)
+VSPLT(h, u16)
+VSPLT(w, u32)
+#undef VSPLT
+#undef SPLAT_ELEMENT
+#undef _SPLAT_MASKED
+
+#define VSPLTI(suffix, element, splat_type)                     \
+    void helper_vspltis##suffix(ppc_avr_t *r, uint32_t splat)   \
+    {                                                           \
+        splat_type x = (int8_t)(splat << 3) >> 3;               \
+        int i;                                                  \
+                                                                \
+        for (i = 0; i < ARRAY_SIZE(r->element); i++) {          \
+            r->element[i] = x;                                  \
+        }                                                       \
+    }
+VSPLTI(b, s8, int8_t)
+VSPLTI(h, s16, int16_t)
+VSPLTI(w, s32, int32_t)
+#undef VSPLTI
+
+#define VSR(suffix, element)                                            \
+    void helper_vsr##suffix(ppc_avr_t *r, ppc_avr_t *a, ppc_avr_t *b)   \
+    {                                                                   \
+        int i;                                                          \
+                                                                        \
+        for (i = 0; i < ARRAY_SIZE(r->element); i++) {                  \
+            unsigned int mask = ((1 <<                                  \
+                                  (3 + (sizeof(a->element[0]) >> 1)))   \
+                                 - 1);                                  \
+            unsigned int shift = b->element[i] & mask;                  \
+                                                                        \
+            r->element[i] = a->element[i] >> shift;                     \
+        }                                                               \
+    }
+VSR(ab, s8)
+VSR(ah, s16)
+VSR(aw, s32)
+VSR(b, u8)
+VSR(h, u16)
+VSR(w, u32)
+#undef VSR
+
+void helper_vsro(ppc_avr_t *r, ppc_avr_t *a, ppc_avr_t *b)
+{
+    int sh = (b->u8[LO_IDX * 0xf] >> 3) & 0xf;
+
+#if defined(HOST_WORDS_BIGENDIAN)
+    memmove(&r->u8[sh], &a->u8[0], 16 - sh);
+    memset(&r->u8[0], 0, sh);
+#else
+    memmove(&r->u8[0], &a->u8[sh], 16 - sh);
+    memset(&r->u8[16 - sh], 0, sh);
+#endif
+}
+
+void helper_vsubcuw(ppc_avr_t *r, ppc_avr_t *a, ppc_avr_t *b)
+{
+    int i;
+
+    for (i = 0; i < ARRAY_SIZE(r->u32); i++) {
+        r->u32[i] = a->u32[i] >= b->u32[i];
+    }
+}
+
+void helper_vsumsws(ppc_avr_t *r, ppc_avr_t *a, ppc_avr_t *b)
+{
+    int64_t t;
+    int i, upper;
+    ppc_avr_t result;
+    int sat = 0;
+
+#if defined(HOST_WORDS_BIGENDIAN)
+    upper = ARRAY_SIZE(r->s32)-1;
+#else
+    upper = 0;
+#endif
+    t = (int64_t)b->s32[upper];
+    for (i = 0; i < ARRAY_SIZE(r->s32); i++) {
+        t += a->s32[i];
+        result.s32[i] = 0;
+    }
+    result.s32[upper] = cvtsdsw(t, &sat);
+    *r = result;
+
+    if (sat) {
+        env->vscr |= (1 << VSCR_SAT);
+    }
+}
+
+void helper_vsum2sws(ppc_avr_t *r, ppc_avr_t *a, ppc_avr_t *b)
+{
+    int i, j, upper;
+    ppc_avr_t result;
+    int sat = 0;
+
+#if defined(HOST_WORDS_BIGENDIAN)
+    upper = 1;
+#else
+    upper = 0;
+#endif
+    for (i = 0; i < ARRAY_SIZE(r->u64); i++) {
+        int64_t t = (int64_t)b->s32[upper + i * 2];
+
+        result.u64[i] = 0;
+        for (j = 0; j < ARRAY_SIZE(r->u64); j++) {
+            t += a->s32[2 * i + j];
+        }
+        result.s32[upper + i * 2] = cvtsdsw(t, &sat);
+    }
+
+    *r = result;
+    if (sat) {
+        env->vscr |= (1 << VSCR_SAT);
+    }
+}
+
+void helper_vsum4sbs(ppc_avr_t *r, ppc_avr_t *a, ppc_avr_t *b)
+{
+    int i, j;
+    int sat = 0;
+
+    for (i = 0; i < ARRAY_SIZE(r->s32); i++) {
+        int64_t t = (int64_t)b->s32[i];
+
+        for (j = 0; j < ARRAY_SIZE(r->s32); j++) {
+            t += a->s8[4 * i + j];
+        }
+        r->s32[i] = cvtsdsw(t, &sat);
+    }
+
+    if (sat) {
+        env->vscr |= (1 << VSCR_SAT);
+    }
+}
+
+void helper_vsum4shs(ppc_avr_t *r, ppc_avr_t *a, ppc_avr_t *b)
+{
+    int sat = 0;
+    int i;
+
+    for (i = 0; i < ARRAY_SIZE(r->s32); i++) {
+        int64_t t = (int64_t)b->s32[i];
+
+        t += a->s16[2 * i] + a->s16[2 * i + 1];
+        r->s32[i] = cvtsdsw(t, &sat);
+    }
+
+    if (sat) {
+        env->vscr |= (1 << VSCR_SAT);
+    }
+}
+
+void helper_vsum4ubs(ppc_avr_t *r, ppc_avr_t *a, ppc_avr_t *b)
+{
+    int i, j;
+    int sat = 0;
+
+    for (i = 0; i < ARRAY_SIZE(r->u32); i++) {
+        uint64_t t = (uint64_t)b->u32[i];
+
+        for (j = 0; j < ARRAY_SIZE(r->u32); j++) {
+            t += a->u8[4 * i + j];
+        }
+        r->u32[i] = cvtuduw(t, &sat);
+    }
+
+    if (sat) {
+        env->vscr |= (1 << VSCR_SAT);
+    }
+}
+
+#if defined(HOST_WORDS_BIGENDIAN)
+#define UPKHI 1
+#define UPKLO 0
+#else
+#define UPKHI 0
+#define UPKLO 1
+#endif
+#define VUPKPX(suffix, hi)                                              \
+    void helper_vupk##suffix(ppc_avr_t *r, ppc_avr_t *b)                \
+    {                                                                   \
+        int i;                                                          \
+        ppc_avr_t result;                                               \
+                                                                        \
+        for (i = 0; i < ARRAY_SIZE(r->u32); i++) {                      \
+            uint16_t e = b->u16[hi ? i : i+4];                          \
+            uint8_t a = (e >> 15) ? 0xff : 0;                           \
+            uint8_t r = (e >> 10) & 0x1f;                               \
+            uint8_t g = (e >> 5) & 0x1f;                                \
+            uint8_t b = e & 0x1f;                                       \
+                                                                        \
+            result.u32[i] = (a << 24) | (r << 16) | (g << 8) | b;       \
+        }                                                               \
+        *r = result;                                                    \
+    }
+VUPKPX(lpx, UPKLO)
+VUPKPX(hpx, UPKHI)
+#undef VUPKPX
+
+#define VUPK(suffix, unpacked, packee, hi)                              \
+    void helper_vupk##suffix(ppc_avr_t *r, ppc_avr_t *b)                \
+    {                                                                   \
+        int i;                                                          \
+        ppc_avr_t result;                                               \
+                                                                        \
+        if (hi) {                                                       \
+            for (i = 0; i < ARRAY_SIZE(r->unpacked); i++) {             \
+                result.unpacked[i] = b->packee[i];                      \
+            }                                                           \
+        } else {                                                        \
+            for (i = ARRAY_SIZE(r->unpacked); i < ARRAY_SIZE(r->packee); \
+                 i++) {                                                 \
+                result.unpacked[i - ARRAY_SIZE(r->unpacked)] = b->packee[i]; \
+            }                                                           \
+        }                                                               \
+        *r = result;                                                    \
+    }
+VUPK(hsb, s16, s8, UPKHI)
+VUPK(hsh, s32, s16, UPKHI)
+VUPK(lsb, s16, s8, UPKLO)
+VUPK(lsh, s32, s16, UPKLO)
+#undef VUPK
+#undef UPKHI
+#undef UPKLO
+
+#undef DO_HANDLE_NAN
+#undef HANDLE_NAN1
+#undef HANDLE_NAN2
+#undef HANDLE_NAN3
+#undef VECTOR_FOR_INORDER_I
+#undef HI_IDX
+#undef LO_IDX
+
+/*****************************************************************************/
+/* SPE extension helpers */
+/* Use a table to make this quicker */
+static uint8_t hbrev[16] = {
+    0x0, 0x8, 0x4, 0xC, 0x2, 0xA, 0x6, 0xE,
+    0x1, 0x9, 0x5, 0xD, 0x3, 0xB, 0x7, 0xF,
+};
+
+static inline uint8_t byte_reverse(uint8_t val)
+{
+    return hbrev[val >> 4] | (hbrev[val & 0xF] << 4);
+}
+
+static inline uint32_t word_reverse(uint32_t val)
+{
+    return byte_reverse(val >> 24) | (byte_reverse(val >> 16) << 8) |
+        (byte_reverse(val >> 8) << 16) | (byte_reverse(val) << 24);
+}
+
+#define MASKBITS 16 /* Random value - to be fixed (implementation dependent) */
+target_ulong helper_brinc(target_ulong arg1, target_ulong arg2)
+{
+    uint32_t a, b, d, mask;
+
+    mask = UINT32_MAX >> (32 - MASKBITS);
+    a = arg1 & mask;
+    b = arg2 & mask;
+    d = word_reverse(1 + word_reverse(a | ~b));
+    return (arg1 & ~mask) | (d & b);
+}
+
+uint32_t helper_cntlsw32(uint32_t val)
+{
+    if (val & 0x80000000) {
+        return clz32(~val);
+    } else {
+        return clz32(val);
+    }
+}
+
+uint32_t helper_cntlzw32(uint32_t val)
+{
+    return clz32(val);
+}
+
+/* 440 specific */
+target_ulong helper_dlmzb(target_ulong high, target_ulong low,
+                          uint32_t update_Rc)
+{
+    target_ulong mask;
+    int i;
+
+    i = 1;
+    for (mask = 0xFF000000; mask != 0; mask = mask >> 8) {
+        if ((high & mask) == 0) {
+            if (update_Rc) {
+                env->crf[0] = 0x4;
+            }
+            goto done;
+        }
+        i++;
+    }
+    for (mask = 0xFF000000; mask != 0; mask = mask >> 8) {
+        if ((low & mask) == 0) {
+            if (update_Rc) {
+                env->crf[0] = 0x8;
+            }
+            goto done;
+        }
+        i++;
+    }
+    if (update_Rc) {
+        env->crf[0] = 0x2;
+    }
+ done:
+    env->xer = (env->xer & ~0x7F) | i;
+    if (update_Rc) {
+        env->crf[0] |= xer_so;
+    }
+    return i;
+}
diff --git a/target-ppc/op_helper.c b/target-ppc/op_helper.c
index 3f677f6..55b9e9d 100644
--- a/target-ppc/op_helper.c
+++ b/target-ppc/op_helper.c
@@ -387,166 +387,6 @@ target_ulong helper_lscbx(target_ulong addr, uint32_t reg, uint32_t ra,
 }
 
 /*****************************************************************************/
-/* Fixed point operations helpers */
-#if defined(TARGET_PPC64)
-
-/* multiply high word */
-uint64_t helper_mulhd(uint64_t arg1, uint64_t arg2)
-{
-    uint64_t tl, th;
-
-    muls64(&tl, &th, arg1, arg2);
-    return th;
-}
-
-/* multiply high word unsigned */
-uint64_t helper_mulhdu(uint64_t arg1, uint64_t arg2)
-{
-    uint64_t tl, th;
-
-    mulu64(&tl, &th, arg1, arg2);
-    return th;
-}
-
-uint64_t helper_mulldo(uint64_t arg1, uint64_t arg2)
-{
-    int64_t th;
-    uint64_t tl;
-
-    muls64(&tl, (uint64_t *)&th, arg1, arg2);
-    /* If th != 0 && th != -1, then we had an overflow */
-    if (likely((uint64_t)(th + 1) <= 1)) {
-        env->xer &= ~(1 << XER_OV);
-    } else {
-        env->xer |= (1 << XER_OV) | (1 << XER_SO);
-    }
-    return (int64_t)tl;
-}
-#endif
-
-target_ulong helper_cntlzw(target_ulong t)
-{
-    return clz32(t);
-}
-
-#if defined(TARGET_PPC64)
-target_ulong helper_cntlzd(target_ulong t)
-{
-    return clz64(t);
-}
-#endif
-
-/* shift right arithmetic helper */
-target_ulong helper_sraw(target_ulong value, target_ulong shift)
-{
-    int32_t ret;
-
-    if (likely(!(shift & 0x20))) {
-        if (likely((uint32_t)shift != 0)) {
-            shift &= 0x1f;
-            ret = (int32_t)value >> shift;
-            if (likely(ret >= 0 || (value & ((1 << shift) - 1)) == 0)) {
-                env->xer &= ~(1 << XER_CA);
-            } else {
-                env->xer |= (1 << XER_CA);
-            }
-        } else {
-            ret = (int32_t)value;
-            env->xer &= ~(1 << XER_CA);
-        }
-    } else {
-        ret = (int32_t)value >> 31;
-        if (ret) {
-            env->xer |= (1 << XER_CA);
-        } else {
-            env->xer &= ~(1 << XER_CA);
-        }
-    }
-    return (target_long)ret;
-}
-
-#if defined(TARGET_PPC64)
-target_ulong helper_srad(target_ulong value, target_ulong shift)
-{
-    int64_t ret;
-
-    if (likely(!(shift & 0x40))) {
-        if (likely((uint64_t)shift != 0)) {
-            shift &= 0x3f;
-            ret = (int64_t)value >> shift;
-            if (likely(ret >= 0 || (value & ((1 << shift) - 1)) == 0)) {
-                env->xer &= ~(1 << XER_CA);
-            } else {
-                env->xer |= (1 << XER_CA);
-            }
-        } else {
-            ret = (int64_t)value;
-            env->xer &= ~(1 << XER_CA);
-        }
-    } else {
-        ret = (int64_t)value >> 63;
-        if (ret) {
-            env->xer |= (1 << XER_CA);
-        } else {
-            env->xer &= ~(1 << XER_CA);
-        }
-    }
-    return ret;
-}
-#endif
-
-#if defined(TARGET_PPC64)
-target_ulong helper_popcntb(target_ulong val)
-{
-    val = (val & 0x5555555555555555ULL) + ((val >>  1) &
-                                           0x5555555555555555ULL);
-    val = (val & 0x3333333333333333ULL) + ((val >>  2) &
-                                           0x3333333333333333ULL);
-    val = (val & 0x0f0f0f0f0f0f0f0fULL) + ((val >>  4) &
-                                           0x0f0f0f0f0f0f0f0fULL);
-    return val;
-}
-
-target_ulong helper_popcntw(target_ulong val)
-{
-    val = (val & 0x5555555555555555ULL) + ((val >>  1) &
-                                           0x5555555555555555ULL);
-    val = (val & 0x3333333333333333ULL) + ((val >>  2) &
-                                           0x3333333333333333ULL);
-    val = (val & 0x0f0f0f0f0f0f0f0fULL) + ((val >>  4) &
-                                           0x0f0f0f0f0f0f0f0fULL);
-    val = (val & 0x00ff00ff00ff00ffULL) + ((val >>  8) &
-                                           0x00ff00ff00ff00ffULL);
-    val = (val & 0x0000ffff0000ffffULL) + ((val >> 16) &
-                                           0x0000ffff0000ffffULL);
-    return val;
-}
-
-target_ulong helper_popcntd(target_ulong val)
-{
-    return ctpop64(val);
-}
-#else
-target_ulong helper_popcntb(target_ulong val)
-{
-    val = (val & 0x55555555) + ((val >>  1) & 0x55555555);
-    val = (val & 0x33333333) + ((val >>  2) & 0x33333333);
-    val = (val & 0x0f0f0f0f) + ((val >>  4) & 0x0f0f0f0f);
-    return val;
-}
-
-target_ulong helper_popcntw(target_ulong val)
-{
-    val = (val & 0x55555555) + ((val >>  1) & 0x55555555);
-    val = (val & 0x33333333) + ((val >>  2) & 0x33333333);
-    val = (val & 0x0f0f0f0f) + ((val >>  4) & 0x0f0f0f0f);
-    val = (val & 0x00ff00ff) + ((val >>  8) & 0x00ff00ff);
-    val = (val & 0x0000ffff) + ((val >> 16) & 0x0000ffff);
-    return val;
-}
-#endif
-
-/*****************************************************************************/
 /* PowerPC 601 specific instructions (POWER bridge) */
 
 target_ulong helper_clcs(uint32_t arg)
@@ -577,67 +417,6 @@ target_ulong helper_clcs(uint32_t arg)
     }
 }
 
-target_ulong helper_div(target_ulong arg1, target_ulong arg2)
-{
-    uint64_t tmp = (uint64_t)arg1 << 32 | env->spr[SPR_MQ];
-
-    if (((int32_t)tmp == INT32_MIN && (int32_t)arg2 == (int32_t)-1) ||
-        (int32_t)arg2 == 0) {
-        env->spr[SPR_MQ] = 0;
-        return INT32_MIN;
-    } else {
-        env->spr[SPR_MQ] = tmp % arg2;
-        return  tmp / (int32_t)arg2;
-    }
-}
-
-target_ulong helper_divo(target_ulong arg1, target_ulong arg2)
-{
-    uint64_t tmp = (uint64_t)arg1 << 32 | env->spr[SPR_MQ];
-
-    if (((int32_t)tmp == INT32_MIN && (int32_t)arg2 == (int32_t)-1) ||
-        (int32_t)arg2 == 0) {
-        env->xer |= (1 << XER_OV) | (1 << XER_SO);
-        env->spr[SPR_MQ] = 0;
-        return INT32_MIN;
-    } else {
-        env->spr[SPR_MQ] = tmp % arg2;
-        tmp /= (int32_t)arg2;
-        if ((int32_t)tmp != tmp) {
-            env->xer |= (1 << XER_OV) | (1 << XER_SO);
-        } else {
-            env->xer &= ~(1 << XER_OV);
-        }
-        return tmp;
-    }
-}
-
-target_ulong helper_divs(target_ulong arg1, target_ulong arg2)
-{
-    if (((int32_t)arg1 == INT32_MIN && (int32_t)arg2 == (int32_t)-1) ||
-        (int32_t)arg2 == 0) {
-        env->spr[SPR_MQ] = 0;
-        return INT32_MIN;
-    } else {
-        env->spr[SPR_MQ] = (int32_t)arg1 % (int32_t)arg2;
-        return (int32_t)arg1 / (int32_t)arg2;
-    }
-}
-
-target_ulong helper_divso(target_ulong arg1, target_ulong arg2)
-{
-    if (((int32_t)arg1 == INT32_MIN && (int32_t)arg2 == (int32_t)-1) ||
-        (int32_t)arg2 == 0) {
-        env->xer |= (1 << XER_OV) | (1 << XER_SO);
-        env->spr[SPR_MQ] = 0;
-        return INT32_MIN;
-    } else {
-        env->xer &= ~(1 << XER_OV);
-        env->spr[SPR_MQ] = (int32_t)arg1 % (int32_t)arg2;
-        return (int32_t)arg1 / (int32_t)arg2;
-    }
-}
-
 #if !defined(CONFIG_USER_ONLY)
 target_ulong helper_rac(target_ulong addr)
 {
@@ -660,26 +439,6 @@ target_ulong helper_rac(target_ulong addr)
 #endif
 
 /*****************************************************************************/
-/* 602 specific instructions */
-/* mfrom is the most crazy instruction ever seen, imho ! */
-/* Real implementation uses a ROM table. Do the same */
-/* Extremely decomposed:
- *                      -arg / 256
- * return 256 * log10(10           + 1.0) + 0.5
- */
-#if !defined(CONFIG_USER_ONLY)
-target_ulong helper_602_mfrom(target_ulong arg)
-{
-    if (likely(arg < 602)) {
-#include "mfrom_table.c"
-        return mfrom_ROM_table[arg];
-    } else {
-        return 0;
-    }
-}
-#endif
-
-/*****************************************************************************/
 /* Embedded PowerPC specific helpers */
 
 /* XXX: to be improved to check access rights when in user-mode */
@@ -716,43 +475,6 @@ void helper_store_dcr(target_ulong dcrn, target_ulong val)
     }
 }
 
-/* 440 specific */
-target_ulong helper_dlmzb(target_ulong high, target_ulong low,
-                          uint32_t update_Rc)
-{
-    target_ulong mask;
-    int i;
-
-    i = 1;
-    for (mask = 0xFF000000; mask != 0; mask = mask >> 8) {
-        if ((high & mask) == 0) {
-            if (update_Rc) {
-                env->crf[0] = 0x4;
-            }
-            goto done;
-        }
-        i++;
-    }
-    for (mask = 0xFF000000; mask != 0; mask = mask >> 8) {
-        if ((low & mask) == 0) {
-            if (update_Rc) {
-                env->crf[0] = 0x8;
-            }
-            goto done;
-        }
-        i++;
-    }
-    if (update_Rc) {
-        env->crf[0] = 0x2;
-    }
- done:
-    env->xer = (env->xer & ~0x7F) | i;
-    if (update_Rc) {
-        env->crf[0] |= xer_so;
-    }
-    return i;
-}
-
 /*****************************************************************************/
 /* Altivec extension helpers */
 #if defined(HOST_WORDS_BIGENDIAN)
@@ -763,74 +485,6 @@ target_ulong helper_dlmzb(target_ulong high, target_ulong low,
 #define LO_IDX 0
 #endif
 
-#if defined(HOST_WORDS_BIGENDIAN)
-#define VECTOR_FOR_INORDER_I(index, element)                    \
-    for (index = 0; index < ARRAY_SIZE(r->element); index++)
-#else
-#define VECTOR_FOR_INORDER_I(index, element)                    \
-    for (index = ARRAY_SIZE(r->element)-1; index >= 0; index--)
-#endif
-
-/* If X is a NaN, store the corresponding QNaN into RESULT.  Otherwise,
- * execute the following block.  */
-#define DO_HANDLE_NAN(result, x)                        \
-    if (float32_is_any_nan(x)) {                        \
-        CPU_FloatU __f;                                 \
-        __f.f = x;                                      \
-        __f.l = __f.l | (1 << 22);  /* Set QNaN bit. */ \
-        result = __f.f;                                 \
-    } else
-
-#define HANDLE_NAN1(result, x)                  \
-    DO_HANDLE_NAN(result, x)
-#define HANDLE_NAN2(result, x, y)                       \
-    DO_HANDLE_NAN(result, x) DO_HANDLE_NAN(result, y)
-#define HANDLE_NAN3(result, x, y, z)                                    \
-    DO_HANDLE_NAN(result, x) DO_HANDLE_NAN(result, y) DO_HANDLE_NAN(result, z)
-
-/* Saturating arithmetic helpers.  */
-#define SATCVT(from, to, from_type, to_type, min, max)          \
-    static inline to_type cvt##from##to(from_type x, int *sat)  \
-    {                                                           \
-        to_type r;                                              \
-                                                                \
-        if (x < (from_type)min) {                               \
-            r = min;                                            \
-            *sat = 1;                                           \
-        } else if (x > (from_type)max) {                        \
-            r = max;                                            \
-            *sat = 1;                                           \
-        } else {                                                \
-            r = x;                                              \
-        }                                                       \
-        return r;                                               \
-    }
-#define SATCVTU(from, to, from_type, to_type, min, max)         \
-    static inline to_type cvt##from##to(from_type x, int *sat)  \
-    {                                                           \
-        to_type r;                                              \
-                                                                \
-        if (x > (from_type)max) {                               \
-            r = max;                                            \
-            *sat = 1;                                           \
-        } else {                                                \
-            r = x;                                              \
-        }                                                       \
-        return r;                                               \
-    }
-SATCVT(sh, sb, int16_t, int8_t, INT8_MIN, INT8_MAX)
-SATCVT(sw, sh, int32_t, int16_t, INT16_MIN, INT16_MAX)
-SATCVT(sd, sw, int64_t, int32_t, INT32_MIN, INT32_MAX)
-
-SATCVTU(uh, ub, uint16_t, uint8_t, 0, UINT8_MAX)
-SATCVTU(uw, uh, uint32_t, uint16_t, 0, UINT16_MAX)
-SATCVTU(ud, uw, uint64_t, uint32_t, 0, UINT32_MAX)
-SATCVT(sh, ub, int16_t, uint8_t, 0, UINT8_MAX)
-SATCVT(sw, uh, int32_t, uint16_t, 0, UINT16_MAX)
-SATCVT(sd, uw, int64_t, uint32_t, 0, UINT32_MAX)
-#undef SATCVT
-#undef SATCVTU
-
 #define LVE(name, access, swap, element)                        \
     void helper_##name(ppc_avr_t *r, target_ulong addr)         \
     {                                                           \
@@ -854,24 +508,6 @@ LVE(lvewx, ldl, bswap32, u32)
 #undef I
 #undef LVE
 
-void helper_lvsl(ppc_avr_t *r, target_ulong sh)
-{
-    int i, j = (sh & 0xf);
-
-    VECTOR_FOR_INORDER_I(i, u8) {
-        r->u8[i] = j++;
-    }
-}
-
-void helper_lvsr(ppc_avr_t *r, target_ulong sh)
-{
-    int i, j = 0x10 - (sh & 0xf);
-
-    VECTOR_FOR_INORDER_I(i, u8) {
-        r->u8[i] = j++;
-    }
-}
-
 #define STVE(name, access, swap, element)                               \
     void helper_##name(ppc_avr_t *r, target_ulong addr)                 \
     {                                                                   \
@@ -893,1146 +529,10 @@ STVE(stvewx, stl, bswap32, u32)
 #undef I
 #undef LVE
 
-void helper_mtvscr(ppc_avr_t *r)
-{
-#if defined(HOST_WORDS_BIGENDIAN)
-    env->vscr = r->u32[3];
-#else
-    env->vscr = r->u32[0];
-#endif
-    set_flush_to_zero(vscr_nj, &env->vec_status);
-}
-
-void helper_vaddcuw(ppc_avr_t *r, ppc_avr_t *a, ppc_avr_t *b)
-{
-    int i;
-
-    for (i = 0; i < ARRAY_SIZE(r->u32); i++) {
-        r->u32[i] = ~a->u32[i] < b->u32[i];
-    }
-}
-
-#define VARITH_DO(name, op, element)                                    \
-    void helper_v##name(ppc_avr_t *r, ppc_avr_t *a, ppc_avr_t *b)       \
-    {                                                                   \
-        int i;                                                          \
-                                                                        \
-        for (i = 0; i < ARRAY_SIZE(r->element); i++) {                  \
-            r->element[i] = a->element[i] op b->element[i];             \
-        }                                                               \
-    }
-#define VARITH(suffix, element)                 \
-    VARITH_DO(add##suffix, +, element)          \
-    VARITH_DO(sub##suffix, -, element)
-VARITH(ubm, u8)
-VARITH(uhm, u16)
-VARITH(uwm, u32)
-#undef VARITH_DO
-#undef VARITH
-
-#define VARITHFP(suffix, func)                                          \
-    void helper_v##suffix(ppc_avr_t *r, ppc_avr_t *a, ppc_avr_t *b)     \
-    {                                                                   \
-        int i;                                                          \
-                                                                        \
-        for (i = 0; i < ARRAY_SIZE(r->f); i++) {                        \
-            HANDLE_NAN2(r->f[i], a->f[i], b->f[i]) {                    \
-                r->f[i] = func(a->f[i], b->f[i], &env->vec_status);     \
-            }                                                           \
-        }                                                               \
-    }
-VARITHFP(addfp, float32_add)
-VARITHFP(subfp, float32_sub)
-#undef VARITHFP
-
-#define VARITHSAT_CASE(type, op, cvt, element)                          \
-    {                                                                   \
-        type result = (type)a->element[i] op (type)b->element[i];       \
-        r->element[i] = cvt(result, &sat);                              \
-    }
-
-#define VARITHSAT_DO(name, op, optype, cvt, element)                    \
-    void helper_v##name(ppc_avr_t *r, ppc_avr_t *a, ppc_avr_t *b)       \
-    {                                                                   \
-        int sat = 0;                                                    \
-        int i;                                                          \
-                                                                        \
-        for (i = 0; i < ARRAY_SIZE(r->element); i++) {                  \
-            switch (sizeof(r->element[0])) {                            \
-            case 1:                                                     \
-                VARITHSAT_CASE(optype, op, cvt, element);               \
-                break;                                                  \
-            case 2:                                                     \
-                VARITHSAT_CASE(optype, op, cvt, element);               \
-                break;                                                  \
-            case 4:                                                     \
-                VARITHSAT_CASE(optype, op, cvt, element);               \
-                break;                                                  \
-            }                                                           \
-        }                                                               \
-        if (sat) {                                                      \
-            env->vscr |= (1 << VSCR_SAT);                               \
-        }                                                               \
-    }
-#define VARITHSAT_SIGNED(suffix, element, optype, cvt)          \
-    VARITHSAT_DO(adds##suffix##s, +, optype, cvt, element)      \
-    VARITHSAT_DO(subs##suffix##s, -, optype, cvt, element)
-#define VARITHSAT_UNSIGNED(suffix, element, optype, cvt)        \
-    VARITHSAT_DO(addu##suffix##s, +, optype, cvt, element)      \
-    VARITHSAT_DO(subu##suffix##s, -, optype, cvt, element)
-VARITHSAT_SIGNED(b, s8, int16_t, cvtshsb)
-VARITHSAT_SIGNED(h, s16, int32_t, cvtswsh)
-VARITHSAT_SIGNED(w, s32, int64_t, cvtsdsw)
-VARITHSAT_UNSIGNED(b, u8, uint16_t, cvtshub)
-VARITHSAT_UNSIGNED(h, u16, uint32_t, cvtswuh)
-VARITHSAT_UNSIGNED(w, u32, uint64_t, cvtsduw)
-#undef VARITHSAT_CASE
-#undef VARITHSAT_DO
-#undef VARITHSAT_SIGNED
-#undef VARITHSAT_UNSIGNED
-
-#define VAVG_DO(name, element, etype)                                   \
-    void helper_v##name(ppc_avr_t *r, ppc_avr_t *a, ppc_avr_t *b)       \
-    {                                                                   \
-        int i;                                                          \
-                                                                        \
-        for (i = 0; i < ARRAY_SIZE(r->element); i++) {                  \
-            etype x = (etype)a->element[i] + (etype)b->element[i] + 1;  \
-            r->element[i] = x >> 1;                                     \
-        }                                                               \
-    }
-
-#define VAVG(type, signed_element, signed_type, unsigned_element,       \
-             unsigned_type)                                             \
-    VAVG_DO(avgs##type, signed_element, signed_type)                    \
-    VAVG_DO(avgu##type, unsigned_element, unsigned_type)
-VAVG(b, s8, int16_t, u8, uint16_t)
-VAVG(h, s16, int32_t, u16, uint32_t)
-VAVG(w, s32, int64_t, u32, uint64_t)
-#undef VAVG_DO
-#undef VAVG
-
-#define VCF(suffix, cvt, element)                                       \
-    void helper_vcf##suffix(ppc_avr_t *r, ppc_avr_t *b, uint32_t uim)   \
-    {                                                                   \
-        int i;                                                          \
-                                                                        \
-        for (i = 0; i < ARRAY_SIZE(r->f); i++) {                        \
-            float32 t = cvt(b->element[i], &env->vec_status);           \
-            r->f[i] = float32_scalbn(t, -uim, &env->vec_status);        \
-        }                                                               \
-    }
-VCF(ux, uint32_to_float32, u32)
-VCF(sx, int32_to_float32, s32)
-#undef VCF
-
-#define VCMP_DO(suffix, compare, element, record)                       \
-    void helper_vcmp##suffix(ppc_avr_t *r, ppc_avr_t *a, ppc_avr_t *b)  \
-    {                                                                   \
-        uint32_t ones = (uint32_t)-1;                                   \
-        uint32_t all = ones;                                            \
-        uint32_t none = 0;                                              \
-        int i;                                                          \
-                                                                        \
-        for (i = 0; i < ARRAY_SIZE(r->element); i++) {                  \
-            uint32_t result = (a->element[i] compare b->element[i] ?    \
-                               ones : 0x0);                             \
-            switch (sizeof(a->element[0])) {                            \
-            case 4:                                                     \
-                r->u32[i] = result;                                     \
-                break;                                                  \
-            case 2:                                                     \
-                r->u16[i] = result;                                     \
-                break;                                                  \
-            case 1:                                                     \
-                r->u8[i] = result;                                      \
-                break;                                                  \
-            }                                                           \
-            all &= result;                                              \
-            none |= result;                                             \
-        }                                                               \
-        if (record) {                                                   \
-            env->crf[6] = ((all != 0) << 3) | ((none == 0) << 1);       \
-        }                                                               \
-    }
-#define VCMP(suffix, compare, element)          \
-    VCMP_DO(suffix, compare, element, 0)        \
-    VCMP_DO(suffix##_dot, compare, element, 1)
-VCMP(equb, ==, u8)
-VCMP(equh, ==, u16)
-VCMP(equw, ==, u32)
-VCMP(gtub, >, u8)
-VCMP(gtuh, >, u16)
-VCMP(gtuw, >, u32)
-VCMP(gtsb, >, s8)
-VCMP(gtsh, >, s16)
-VCMP(gtsw, >, s32)
-#undef VCMP_DO
-#undef VCMP
-
-#define VCMPFP_DO(suffix, compare, order, record)                       \
-    void helper_vcmp##suffix(ppc_avr_t *r, ppc_avr_t *a, ppc_avr_t *b)  \
-    {                                                                   \
-        uint32_t ones = (uint32_t)-1;                                   \
-        uint32_t all = ones;                                            \
-        uint32_t none = 0;                                              \
-        int i;                                                          \
-                                                                        \
-        for (i = 0; i < ARRAY_SIZE(r->f); i++) {                        \
-            uint32_t result;                                            \
-            int rel = float32_compare_quiet(a->f[i], b->f[i],           \
-                                            &env->vec_status);          \
-            if (rel == float_relation_unordered) {                      \
-                result = 0;                                             \
-            } else if (rel compare order) {                             \
-                result = ones;                                          \
-            } else {                                                    \
-                result = 0;                                             \
-            }                                                           \
-            r->u32[i] = result;                                         \
-            all &= result;                                              \
-            none |= result;                                             \
-        }                                                               \
-        if (record) {                                                   \
-            env->crf[6] = ((all != 0) << 3) | ((none == 0) << 1);       \
-        }                                                               \
-    }
-#define VCMPFP(suffix, compare, order)          \
-    VCMPFP_DO(suffix, compare, order, 0)        \
-    VCMPFP_DO(suffix##_dot, compare, order, 1)
-VCMPFP(eqfp, ==, float_relation_equal)
-VCMPFP(gefp, !=, float_relation_less)
-VCMPFP(gtfp, ==, float_relation_greater)
-#undef VCMPFP_DO
-#undef VCMPFP
-
-static inline void vcmpbfp_internal(ppc_avr_t *r, ppc_avr_t *a, ppc_avr_t *b,
-                                    int record)
-{
-    int i;
-    int all_in = 0;
-
-    for (i = 0; i < ARRAY_SIZE(r->f); i++) {
-        int le_rel = float32_compare_quiet(a->f[i], b->f[i], &env->vec_status);
-        if (le_rel == float_relation_unordered) {
-            r->u32[i] = 0xc0000000;
-            /* ALL_IN does not need to be updated here.  */
-        } else {
-            float32 bneg = float32_chs(b->f[i]);
-            int ge_rel = float32_compare_quiet(a->f[i], bneg, &env->vec_status);
-            int le = le_rel != float_relation_greater;
-            int ge = ge_rel != float_relation_less;
-
-            r->u32[i] = ((!le) << 31) | ((!ge) << 30);
-            all_in |= (!le | !ge);
-        }
-    }
-    if (record) {
-        env->crf[6] = (all_in == 0) << 1;
-    }
-}
-
-void helper_vcmpbfp(ppc_avr_t *r, ppc_avr_t *a, ppc_avr_t *b)
-{
-    vcmpbfp_internal(r, a, b, 0);
-}
-
-void helper_vcmpbfp_dot(ppc_avr_t *r, ppc_avr_t *a, ppc_avr_t *b)
-{
-    vcmpbfp_internal(r, a, b, 1);
-}
-
-#define VCT(suffix, satcvt, element)                                    \
-    void helper_vct##suffix(ppc_avr_t *r, ppc_avr_t *b, uint32_t uim)   \
-    {                                                                   \
-        int i;                                                          \
-        int sat = 0;                                                    \
-        float_status s = env->vec_status;                               \
-                                                                        \
-        set_float_rounding_mode(float_round_to_zero, &s);               \
-        for (i = 0; i < ARRAY_SIZE(r->f); i++) {                        \
-            if (float32_is_any_nan(b->f[i])) {                          \
-                r->element[i] = 0;                                      \
-            } else {                                                    \
-                float64 t = float32_to_float64(b->f[i], &s);            \
-                int64_t j;                                              \
-                                                                        \
-                t = float64_scalbn(t, uim, &s);                         \
-                j = float64_to_int64(t, &s);                            \
-                r->element[i] = satcvt(j, &sat);                        \
-            }                                                           \
-        }                                                               \
-        if (sat) {                                                      \
-            env->vscr |= (1 << VSCR_SAT);                               \
-        }                                                               \
-    }
-VCT(uxs, cvtsduw, u32)
-VCT(sxs, cvtsdsw, s32)
-#undef VCT
-
-void helper_vmaddfp(ppc_avr_t *r, ppc_avr_t *a, ppc_avr_t *b, ppc_avr_t *c)
-{
-    int i;
-
-    for (i = 0; i < ARRAY_SIZE(r->f); i++) {
-        HANDLE_NAN3(r->f[i], a->f[i], b->f[i], c->f[i]) {
-            /* Need to do the computation in higher precision and round
-             * once at the end.  */
-            float64 af, bf, cf, t;
-
-            af = float32_to_float64(a->f[i], &env->vec_status);
-            bf = float32_to_float64(b->f[i], &env->vec_status);
-            cf = float32_to_float64(c->f[i], &env->vec_status);
-            t = float64_mul(af, cf, &env->vec_status);
-            t = float64_add(t, bf, &env->vec_status);
-            r->f[i] = float64_to_float32(t, &env->vec_status);
-        }
-    }
-}
-
-void helper_vmhaddshs(ppc_avr_t *r, ppc_avr_t *a, ppc_avr_t *b, ppc_avr_t *c)
-{
-    int sat = 0;
-    int i;
-
-    for (i = 0; i < ARRAY_SIZE(r->s16); i++) {
-        int32_t prod = a->s16[i] * b->s16[i];
-        int32_t t = (int32_t)c->s16[i] + (prod >> 15);
-
-        r->s16[i] = cvtswsh(t, &sat);
-    }
-
-    if (sat) {
-        env->vscr |= (1 << VSCR_SAT);
-    }
-}
-
-void helper_vmhraddshs(ppc_avr_t *r, ppc_avr_t *a, ppc_avr_t *b, ppc_avr_t *c)
-{
-    int sat = 0;
-    int i;
-
-    for (i = 0; i < ARRAY_SIZE(r->s16); i++) {
-        int32_t prod = a->s16[i] * b->s16[i] + 0x00004000;
-        int32_t t = (int32_t)c->s16[i] + (prod >> 15);
-        r->s16[i] = cvtswsh(t, &sat);
-    }
-
-    if (sat) {
-        env->vscr |= (1 << VSCR_SAT);
-    }
-}
-
-#define VMINMAX_DO(name, compare, element)                              \
-    void helper_v##name(ppc_avr_t *r, ppc_avr_t *a, ppc_avr_t *b)       \
-    {                                                                   \
-        int i;                                                          \
-                                                                        \
-        for (i = 0; i < ARRAY_SIZE(r->element); i++) {                  \
-            if (a->element[i] compare b->element[i]) {                  \
-                r->element[i] = b->element[i];                          \
-            } else {                                                    \
-                r->element[i] = a->element[i];                          \
-            }                                                           \
-        }                                                               \
-    }
-#define VMINMAX(suffix, element)                \
-    VMINMAX_DO(min##suffix, >, element)         \
-    VMINMAX_DO(max##suffix, <, element)
-VMINMAX(sb, s8)
-VMINMAX(sh, s16)
-VMINMAX(sw, s32)
-VMINMAX(ub, u8)
-VMINMAX(uh, u16)
-VMINMAX(uw, u32)
-#undef VMINMAX_DO
-#undef VMINMAX
-
-#define VMINMAXFP(suffix, rT, rF)                                       \
-    void helper_v##suffix(ppc_avr_t *r, ppc_avr_t *a, ppc_avr_t *b)     \
-    {                                                                   \
-        int i;                                                          \
-                                                                        \
-        for (i = 0; i < ARRAY_SIZE(r->f); i++) {                        \
-            HANDLE_NAN2(r->f[i], a->f[i], b->f[i]) {                    \
-                if (float32_lt_quiet(a->f[i], b->f[i],                  \
-                                     &env->vec_status)) {               \
-                    r->f[i] = rT->f[i];                                 \
-                } else {                                                \
-                    r->f[i] = rF->f[i];                                 \
-                }                                                       \
-            }                                                           \
-        }                                                               \
-    }
-VMINMAXFP(minfp, a, b)
-VMINMAXFP(maxfp, b, a)
-#undef VMINMAXFP
-
-void helper_vmladduhm(ppc_avr_t *r, ppc_avr_t *a, ppc_avr_t *b, ppc_avr_t *c)
-{
-    int i;
-
-    for (i = 0; i < ARRAY_SIZE(r->s16); i++) {
-        int32_t prod = a->s16[i] * b->s16[i];
-        r->s16[i] = (int16_t) (prod + c->s16[i]);
-    }
-}
-
-#define VMRG_DO(name, element, highp)                                   \
-    void helper_v##name(ppc_avr_t *r, ppc_avr_t *a, ppc_avr_t *b)       \
-    {                                                                   \
-        ppc_avr_t result;                                               \
-        int i;                                                          \
-        size_t n_elems = ARRAY_SIZE(r->element);                        \
-                                                                        \
-        for (i = 0; i < n_elems / 2; i++) {                             \
-            if (highp) {                                                \
-                result.element[i*2+HI_IDX] = a->element[i];             \
-                result.element[i*2+LO_IDX] = b->element[i];             \
-            } else {                                                    \
-                result.element[n_elems - i * 2 - (1 + HI_IDX)] =        \
-                    b->element[n_elems - i - 1];                        \
-                result.element[n_elems - i * 2 - (1 + LO_IDX)] =        \
-                    a->element[n_elems - i - 1];                        \
-            }                                                           \
-        }                                                               \
-        *r = result;                                                    \
-    }
-#if defined(HOST_WORDS_BIGENDIAN)
-#define MRGHI 0
-#define MRGLO 1
-#else
-#define MRGHI 1
-#define MRGLO 0
-#endif
-#define VMRG(suffix, element)                   \
-    VMRG_DO(mrgl##suffix, element, MRGHI)       \
-    VMRG_DO(mrgh##suffix, element, MRGLO)
-VMRG(b, u8)
-VMRG(h, u16)
-VMRG(w, u32)
-#undef VMRG_DO
-#undef VMRG
-#undef MRGHI
-#undef MRGLO
-
-void helper_vmsummbm(ppc_avr_t *r, ppc_avr_t *a, ppc_avr_t *b, ppc_avr_t *c)
-{
-    int32_t prod[16];
-    int i;
-
-    for (i = 0; i < ARRAY_SIZE(r->s8); i++) {
-        prod[i] = (int32_t)a->s8[i] * b->u8[i];
-    }
-
-    VECTOR_FOR_INORDER_I(i, s32) {
-        r->s32[i] = c->s32[i] + prod[4 * i] + prod[4 * i + 1] +
-            prod[4 * i + 2] + prod[4 * i + 3];
-    }
-}
-
-void helper_vmsumshm(ppc_avr_t *r, ppc_avr_t *a, ppc_avr_t *b, ppc_avr_t *c)
-{
-    int32_t prod[8];
-    int i;
-
-    for (i = 0; i < ARRAY_SIZE(r->s16); i++) {
-        prod[i] = a->s16[i] * b->s16[i];
-    }
-
-    VECTOR_FOR_INORDER_I(i, s32) {
-        r->s32[i] = c->s32[i] + prod[2 * i] + prod[2 * i + 1];
-    }
-}
-
-void helper_vmsumshs(ppc_avr_t *r, ppc_avr_t *a, ppc_avr_t *b, ppc_avr_t *c)
-{
-    int32_t prod[8];
-    int i;
-    int sat = 0;
-
-    for (i = 0; i < ARRAY_SIZE(r->s16); i++) {
-        prod[i] = (int32_t)a->s16[i] * b->s16[i];
-    }
-
-    VECTOR_FOR_INORDER_I(i, s32) {
-        int64_t t = (int64_t)c->s32[i] + prod[2 * i] + prod[2 * i + 1];
-
-        r->u32[i] = cvtsdsw(t, &sat);
-    }
-
-    if (sat) {
-        env->vscr |= (1 << VSCR_SAT);
-    }
-}
-
-void helper_vmsumubm(ppc_avr_t *r, ppc_avr_t *a, ppc_avr_t *b, ppc_avr_t *c)
-{
-    uint16_t prod[16];
-    int i;
-
-    for (i = 0; i < ARRAY_SIZE(r->u8); i++) {
-        prod[i] = a->u8[i] * b->u8[i];
-    }
-
-    VECTOR_FOR_INORDER_I(i, u32) {
-        r->u32[i] = c->u32[i] + prod[4 * i] + prod[4 * i + 1] +
-            prod[4 * i + 2] + prod[4 * i + 3];
-    }
-}
-
-void helper_vmsumuhm(ppc_avr_t *r, ppc_avr_t *a, ppc_avr_t *b, ppc_avr_t *c)
-{
-    uint32_t prod[8];
-    int i;
-
-    for (i = 0; i < ARRAY_SIZE(r->u16); i++) {
-        prod[i] = a->u16[i] * b->u16[i];
-    }
-
-    VECTOR_FOR_INORDER_I(i, u32) {
-        r->u32[i] = c->u32[i] + prod[2 * i] + prod[2 * i + 1];
-    }
-}
-
-void helper_vmsumuhs(ppc_avr_t *r, ppc_avr_t *a, ppc_avr_t *b, ppc_avr_t *c)
-{
-    uint32_t prod[8];
-    int i;
-    int sat = 0;
-
-    for (i = 0; i < ARRAY_SIZE(r->u16); i++) {
-        prod[i] = a->u16[i] * b->u16[i];
-    }
-
-    VECTOR_FOR_INORDER_I(i, s32) {
-        uint64_t t = (uint64_t)c->u32[i] + prod[2 * i] + prod[2 * i + 1];
-
-        r->u32[i] = cvtuduw(t, &sat);
-    }
-
-    if (sat) {
-        env->vscr |= (1 << VSCR_SAT);
-    }
-}
-
-#define VMUL_DO(name, mul_element, prod_element, evenp)                 \
-    void helper_v##name(ppc_avr_t *r, ppc_avr_t *a, ppc_avr_t *b)       \
-    {                                                                   \
-        int i;                                                          \
-                                                                        \
-        VECTOR_FOR_INORDER_I(i, prod_element) {                         \
-            if (evenp) {                                                \
-                r->prod_element[i] = a->mul_element[i * 2 + HI_IDX] *   \
-                    b->mul_element[i * 2 + HI_IDX];                     \
-            } else {                                                    \
-                r->prod_element[i] = a->mul_element[i * 2 + LO_IDX] *   \
-                    b->mul_element[i * 2 + LO_IDX];                     \
-            }                                                           \
-        }                                                               \
-    }
-#define VMUL(suffix, mul_element, prod_element)         \
-    VMUL_DO(mule##suffix, mul_element, prod_element, 1) \
-    VMUL_DO(mulo##suffix, mul_element, prod_element, 0)
-VMUL(sb, s8, s16)
-VMUL(sh, s16, s32)
-VMUL(ub, u8, u16)
-VMUL(uh, u16, u32)
-#undef VMUL_DO
-#undef VMUL
-
-void helper_vnmsubfp(ppc_avr_t *r, ppc_avr_t *a, ppc_avr_t *b, ppc_avr_t *c)
-{
-    int i;
-
-    for (i = 0; i < ARRAY_SIZE(r->f); i++) {
-        HANDLE_NAN3(r->f[i], a->f[i], b->f[i], c->f[i]) {
-            /* Need to do the computation is higher precision and round
-             * once at the end.  */
-            float64 af, bf, cf, t;
-
-            af = float32_to_float64(a->f[i], &env->vec_status);
-            bf = float32_to_float64(b->f[i], &env->vec_status);
-            cf = float32_to_float64(c->f[i], &env->vec_status);
-            t = float64_mul(af, cf, &env->vec_status);
-            t = float64_sub(t, bf, &env->vec_status);
-            t = float64_chs(t);
-            r->f[i] = float64_to_float32(t, &env->vec_status);
-        }
-    }
-}
-
-void helper_vperm(ppc_avr_t *r, ppc_avr_t *a, ppc_avr_t *b, ppc_avr_t *c)
-{
-    ppc_avr_t result;
-    int i;
-
-    VECTOR_FOR_INORDER_I(i, u8) {
-        int s = c->u8[i] & 0x1f;
-#if defined(HOST_WORDS_BIGENDIAN)
-        int index = s & 0xf;
-#else
-        int index = 15 - (s & 0xf);
-#endif
-
-        if (s & 0x10) {
-            result.u8[i] = b->u8[index];
-        } else {
-            result.u8[i] = a->u8[index];
-        }
-    }
-    *r = result;
-}
-
-#if defined(HOST_WORDS_BIGENDIAN)
-#define PKBIG 1
-#else
-#define PKBIG 0
-#endif
-void helper_vpkpx(ppc_avr_t *r, ppc_avr_t *a, ppc_avr_t *b)
-{
-    int i, j;
-    ppc_avr_t result;
-#if defined(HOST_WORDS_BIGENDIAN)
-    const ppc_avr_t *x[2] = { a, b };
-#else
-    const ppc_avr_t *x[2] = { b, a };
-#endif
-
-    VECTOR_FOR_INORDER_I(i, u64) {
-        VECTOR_FOR_INORDER_I(j, u32) {
-            uint32_t e = x[i]->u32[j];
-
-            result.u16[4*i+j] = (((e >> 9) & 0xfc00) |
-                                 ((e >> 6) & 0x3e0) |
-                                 ((e >> 3) & 0x1f));
-        }
-    }
-    *r = result;
-}
-
-#define VPK(suffix, from, to, cvt, dosat)                               \
-    void helper_vpk##suffix(ppc_avr_t *r, ppc_avr_t *a, ppc_avr_t *b)   \
-    {                                                                   \
-        int i;                                                          \
-        int sat = 0;                                                    \
-        ppc_avr_t result;                                               \
-        ppc_avr_t *a0 = PKBIG ? a : b;                                  \
-        ppc_avr_t *a1 = PKBIG ? b : a;                                  \
-                                                                        \
-        VECTOR_FOR_INORDER_I(i, from) {                                 \
-            result.to[i] = cvt(a0->from[i], &sat);                      \
-            result.to[i+ARRAY_SIZE(r->from)] = cvt(a1->from[i], &sat);  \
-        }                                                               \
-        *r = result;                                                    \
-        if (dosat && sat) {                                             \
-            env->vscr |= (1 << VSCR_SAT);                               \
-        }                                                               \
-    }
-#define I(x, y) (x)
-VPK(shss, s16, s8, cvtshsb, 1)
-VPK(shus, s16, u8, cvtshub, 1)
-VPK(swss, s32, s16, cvtswsh, 1)
-VPK(swus, s32, u16, cvtswuh, 1)
-VPK(uhus, u16, u8, cvtuhub, 1)
-VPK(uwus, u32, u16, cvtuwuh, 1)
-VPK(uhum, u16, u8, I, 0)
-VPK(uwum, u32, u16, I, 0)
-#undef I
-#undef VPK
-#undef PKBIG
-
-void helper_vrefp(ppc_avr_t *r, ppc_avr_t *b)
-{
-    int i;
-
-    for (i = 0; i < ARRAY_SIZE(r->f); i++) {
-        HANDLE_NAN1(r->f[i], b->f[i]) {
-            r->f[i] = float32_div(float32_one, b->f[i], &env->vec_status);
-        }
-    }
-}
-
-#define VRFI(suffix, rounding)                                  \
-    void helper_vrfi##suffix(ppc_avr_t *r, ppc_avr_t *b)        \
-    {                                                           \
-        int i;                                                  \
-        float_status s = env->vec_status;                       \
-                                                                \
-        set_float_rounding_mode(rounding, &s);                  \
-        for (i = 0; i < ARRAY_SIZE(r->f); i++) {                \
-            HANDLE_NAN1(r->f[i], b->f[i]) {                     \
-                r->f[i] = float32_round_to_int (b->f[i], &s);   \
-            }                                                   \
-        }                                                       \
-    }
-VRFI(n, float_round_nearest_even)
-VRFI(m, float_round_down)
-VRFI(p, float_round_up)
-VRFI(z, float_round_to_zero)
-#undef VRFI
-
-#define VROTATE(suffix, element)                                        \
-    void helper_vrl##suffix(ppc_avr_t *r, ppc_avr_t *a, ppc_avr_t *b)   \
-    {                                                                   \
-        int i;                                                          \
-                                                                        \
-        for (i = 0; i < ARRAY_SIZE(r->element); i++) {                  \
-            unsigned int mask = ((1 <<                                  \
-                                  (3 + (sizeof(a->element[0]) >> 1)))   \
-                                 - 1);                                  \
-            unsigned int shift = b->element[i] & mask;                  \
-            r->element[i] = (a->element[i] << shift) |                  \
-                (a->element[i] >> (sizeof(a->element[0]) * 8 - shift)); \
-        }                                                               \
-    }
-VROTATE(b, u8)
-VROTATE(h, u16)
-VROTATE(w, u32)
-#undef VROTATE
-
-void helper_vrsqrtefp(ppc_avr_t *r, ppc_avr_t *b)
-{
-    int i;
-
-    for (i = 0; i < ARRAY_SIZE(r->f); i++) {
-        HANDLE_NAN1(r->f[i], b->f[i]) {
-            float32 t = float32_sqrt(b->f[i], &env->vec_status);
-
-            r->f[i] = float32_div(float32_one, t, &env->vec_status);
-        }
-    }
-}
-
-void helper_vsel(ppc_avr_t *r, ppc_avr_t *a, ppc_avr_t *b, ppc_avr_t *c)
-{
-    r->u64[0] = (a->u64[0] & ~c->u64[0]) | (b->u64[0] & c->u64[0]);
-    r->u64[1] = (a->u64[1] & ~c->u64[1]) | (b->u64[1] & c->u64[1]);
-}
-
-void helper_vexptefp(ppc_avr_t *r, ppc_avr_t *b)
-{
-    int i;
-
-    for (i = 0; i < ARRAY_SIZE(r->f); i++) {
-        HANDLE_NAN1(r->f[i], b->f[i]) {
-            r->f[i] = float32_exp2(b->f[i], &env->vec_status);
-        }
-    }
-}
-
-void helper_vlogefp(ppc_avr_t *r, ppc_avr_t *b)
-{
-    int i;
-
-    for (i = 0; i < ARRAY_SIZE(r->f); i++) {
-        HANDLE_NAN1(r->f[i], b->f[i]) {
-            r->f[i] = float32_log2(b->f[i], &env->vec_status);
-        }
-    }
-}
-
-#if defined(HOST_WORDS_BIGENDIAN)
-#define LEFT 0
-#define RIGHT 1
-#else
-#define LEFT 1
-#define RIGHT 0
-#endif
-/* The specification says that the results are undefined if all of the
- * shift counts are not identical.  We check to make sure that they are
- * to conform to what real hardware appears to do.  */
-#define VSHIFT(suffix, leftp)                                           \
-    void helper_vs##suffix(ppc_avr_t *r, ppc_avr_t *a, ppc_avr_t *b)    \
-    {                                                                   \
-        int shift = b->u8[LO_IDX*15] & 0x7;                             \
-        int doit = 1;                                                   \
-        int i;                                                          \
-                                                                        \
-        for (i = 0; i < ARRAY_SIZE(r->u8); i++) {                       \
-            doit = doit && ((b->u8[i] & 0x7) == shift);                 \
-        }                                                               \
-        if (doit) {                                                     \
-            if (shift == 0) {                                           \
-                *r = *a;                                                \
-            } else if (leftp) {                                         \
-                uint64_t carry = a->u64[LO_IDX] >> (64 - shift);        \
-                                                                        \
-                r->u64[HI_IDX] = (a->u64[HI_IDX] << shift) | carry;     \
-                r->u64[LO_IDX] = a->u64[LO_IDX] << shift;               \
-            } else {                                                    \
-                uint64_t carry = a->u64[HI_IDX] << (64 - shift);        \
-                                                                        \
-                r->u64[LO_IDX] = (a->u64[LO_IDX] >> shift) | carry;     \
-                r->u64[HI_IDX] = a->u64[HI_IDX] >> shift;               \
-            }                                                           \
-        }                                                               \
-    }
-VSHIFT(l, LEFT)
-VSHIFT(r, RIGHT)
-#undef VSHIFT
-#undef LEFT
-#undef RIGHT
-
-#define VSL(suffix, element)                                            \
-    void helper_vsl##suffix(ppc_avr_t *r, ppc_avr_t *a, ppc_avr_t *b)   \
-    {                                                                   \
-        int i;                                                          \
-                                                                        \
-        for (i = 0; i < ARRAY_SIZE(r->element); i++) {                  \
-            unsigned int mask = ((1 <<                                  \
-                                  (3 + (sizeof(a->element[0]) >> 1)))   \
-                                 - 1);                                  \
-            unsigned int shift = b->element[i] & mask;                  \
-                                                                        \
-            r->element[i] = a->element[i] << shift;                     \
-        }                                                               \
-    }
-VSL(b, u8)
-VSL(h, u16)
-VSL(w, u32)
-#undef VSL
-
-void helper_vsldoi(ppc_avr_t *r, ppc_avr_t *a, ppc_avr_t *b, uint32_t shift)
-{
-    int sh = shift & 0xf;
-    int i;
-    ppc_avr_t result;
-
-#if defined(HOST_WORDS_BIGENDIAN)
-    for (i = 0; i < ARRAY_SIZE(r->u8); i++) {
-        int index = sh + i;
-        if (index > 0xf) {
-            result.u8[i] = b->u8[index - 0x10];
-        } else {
-            result.u8[i] = a->u8[index];
-        }
-    }
-#else
-    for (i = 0; i < ARRAY_SIZE(r->u8); i++) {
-        int index = (16 - sh) + i;
-        if (index > 0xf) {
-            result.u8[i] = a->u8[index - 0x10];
-        } else {
-            result.u8[i] = b->u8[index];
-        }
-    }
-#endif
-    *r = result;
-}
-
-void helper_vslo(ppc_avr_t *r, ppc_avr_t *a, ppc_avr_t *b)
-{
-    int sh = (b->u8[LO_IDX*0xf] >> 3) & 0xf;
-
-#if defined(HOST_WORDS_BIGENDIAN)
-    memmove(&r->u8[0], &a->u8[sh], 16 - sh);
-    memset(&r->u8[16-sh], 0, sh);
-#else
-    memmove(&r->u8[sh], &a->u8[0], 16 - sh);
-    memset(&r->u8[0], 0, sh);
-#endif
-}
-
-/* Experimental testing shows that hardware masks the immediate.  */
-#define _SPLAT_MASKED(element) (splat & (ARRAY_SIZE(r->element) - 1))
-#if defined(HOST_WORDS_BIGENDIAN)
-#define SPLAT_ELEMENT(element) _SPLAT_MASKED(element)
-#else
-#define SPLAT_ELEMENT(element)                                  \
-    (ARRAY_SIZE(r->element) - 1 - _SPLAT_MASKED(element))
-#endif
-#define VSPLT(suffix, element)                                          \
-    void helper_vsplt##suffix(ppc_avr_t *r, ppc_avr_t *b, uint32_t splat) \
-    {                                                                   \
-        uint32_t s = b->element[SPLAT_ELEMENT(element)];                \
-        int i;                                                          \
-                                                                        \
-        for (i = 0; i < ARRAY_SIZE(r->element); i++) {                  \
-            r->element[i] = s;                                          \
-        }                                                               \
-    }
-VSPLT(b, u8)
-VSPLT(h, u16)
-VSPLT(w, u32)
-#undef VSPLT
-#undef SPLAT_ELEMENT
-#undef _SPLAT_MASKED
-
-#define VSPLTI(suffix, element, splat_type)                     \
-    void helper_vspltis##suffix(ppc_avr_t *r, uint32_t splat)   \
-    {                                                           \
-        splat_type x = (int8_t)(splat << 3) >> 3;               \
-        int i;                                                  \
-                                                                \
-        for (i = 0; i < ARRAY_SIZE(r->element); i++) {          \
-            r->element[i] = x;                                  \
-        }                                                       \
-    }
-VSPLTI(b, s8, int8_t)
-VSPLTI(h, s16, int16_t)
-VSPLTI(w, s32, int32_t)
-#undef VSPLTI
-
-#define VSR(suffix, element)                                            \
-    void helper_vsr##suffix(ppc_avr_t *r, ppc_avr_t *a, ppc_avr_t *b)   \
-    {                                                                   \
-        int i;                                                          \
-                                                                        \
-        for (i = 0; i < ARRAY_SIZE(r->element); i++) {                  \
-            unsigned int mask = ((1 <<                                  \
-                                  (3 + (sizeof(a->element[0]) >> 1)))   \
-                                 - 1);                                  \
-            unsigned int shift = b->element[i] & mask;                  \
-                                                                        \
-            r->element[i] = a->element[i] >> shift;                     \
-        }                                                               \
-    }
-VSR(ab, s8)
-VSR(ah, s16)
-VSR(aw, s32)
-VSR(b, u8)
-VSR(h, u16)
-VSR(w, u32)
-#undef VSR
-
-void helper_vsro(ppc_avr_t *r, ppc_avr_t *a, ppc_avr_t *b)
-{
-    int sh = (b->u8[LO_IDX * 0xf] >> 3) & 0xf;
-
-#if defined(HOST_WORDS_BIGENDIAN)
-    memmove(&r->u8[sh], &a->u8[0], 16 - sh);
-    memset(&r->u8[0], 0, sh);
-#else
-    memmove(&r->u8[0], &a->u8[sh], 16 - sh);
-    memset(&r->u8[16 - sh], 0, sh);
-#endif
-}
-
-void helper_vsubcuw(ppc_avr_t *r, ppc_avr_t *a, ppc_avr_t *b)
-{
-    int i;
-
-    for (i = 0; i < ARRAY_SIZE(r->u32); i++) {
-        r->u32[i] = a->u32[i] >= b->u32[i];
-    }
-}
-
-void helper_vsumsws(ppc_avr_t *r, ppc_avr_t *a, ppc_avr_t *b)
-{
-    int64_t t;
-    int i, upper;
-    ppc_avr_t result;
-    int sat = 0;
-
-#if defined(HOST_WORDS_BIGENDIAN)
-    upper = ARRAY_SIZE(r->s32)-1;
-#else
-    upper = 0;
-#endif
-    t = (int64_t)b->s32[upper];
-    for (i = 0; i < ARRAY_SIZE(r->s32); i++) {
-        t += a->s32[i];
-        result.s32[i] = 0;
-    }
-    result.s32[upper] = cvtsdsw(t, &sat);
-    *r = result;
-
-    if (sat) {
-        env->vscr |= (1 << VSCR_SAT);
-    }
-}
-
-void helper_vsum2sws(ppc_avr_t *r, ppc_avr_t *a, ppc_avr_t *b)
-{
-    int i, j, upper;
-    ppc_avr_t result;
-    int sat = 0;
-
-#if defined(HOST_WORDS_BIGENDIAN)
-    upper = 1;
-#else
-    upper = 0;
-#endif
-    for (i = 0; i < ARRAY_SIZE(r->u64); i++) {
-        int64_t t = (int64_t)b->s32[upper + i * 2];
-
-        result.u64[i] = 0;
-        for (j = 0; j < ARRAY_SIZE(r->u64); j++) {
-            t += a->s32[2 * i + j];
-        }
-        result.s32[upper + i * 2] = cvtsdsw(t, &sat);
-    }
-
-    *r = result;
-    if (sat) {
-        env->vscr |= (1 << VSCR_SAT);
-    }
-}
-
-void helper_vsum4sbs(ppc_avr_t *r, ppc_avr_t *a, ppc_avr_t *b)
-{
-    int i, j;
-    int sat = 0;
-
-    for (i = 0; i < ARRAY_SIZE(r->s32); i++) {
-        int64_t t = (int64_t)b->s32[i];
-
-        for (j = 0; j < ARRAY_SIZE(r->s32); j++) {
-            t += a->s8[4 * i + j];
-        }
-        r->s32[i] = cvtsdsw(t, &sat);
-    }
-
-    if (sat) {
-        env->vscr |= (1 << VSCR_SAT);
-    }
-}
-
-void helper_vsum4shs(ppc_avr_t *r, ppc_avr_t *a, ppc_avr_t *b)
-{
-    int sat = 0;
-    int i;
-
-    for (i = 0; i < ARRAY_SIZE(r->s32); i++) {
-        int64_t t = (int64_t)b->s32[i];
-
-        t += a->s16[2 * i] + a->s16[2 * i + 1];
-        r->s32[i] = cvtsdsw(t, &sat);
-    }
-
-    if (sat) {
-        env->vscr |= (1 << VSCR_SAT);
-    }
-}
-
-void helper_vsum4ubs(ppc_avr_t *r, ppc_avr_t *a, ppc_avr_t *b)
-{
-    int i, j;
-    int sat = 0;
-
-    for (i = 0; i < ARRAY_SIZE(r->u32); i++) {
-        uint64_t t = (uint64_t)b->u32[i];
-
-        for (j = 0; j < ARRAY_SIZE(r->u32); j++) {
-            t += a->u8[4 * i + j];
-        }
-        r->u32[i] = cvtuduw(t, &sat);
-    }
-
-    if (sat) {
-        env->vscr |= (1 << VSCR_SAT);
-    }
-}
-
-#if defined(HOST_WORDS_BIGENDIAN)
-#define UPKHI 1
-#define UPKLO 0
-#else
-#define UPKHI 0
-#define UPKLO 1
-#endif
-#define VUPKPX(suffix, hi)                                              \
-    void helper_vupk##suffix(ppc_avr_t *r, ppc_avr_t *b)                \
-    {                                                                   \
-        int i;                                                          \
-        ppc_avr_t result;                                               \
-                                                                        \
-        for (i = 0; i < ARRAY_SIZE(r->u32); i++) {                      \
-            uint16_t e = b->u16[hi ? i : i+4];                          \
-            uint8_t a = (e >> 15) ? 0xff : 0;                           \
-            uint8_t r = (e >> 10) & 0x1f;                               \
-            uint8_t g = (e >> 5) & 0x1f;                                \
-            uint8_t b = e & 0x1f;                                       \
-                                                                        \
-            result.u32[i] = (a << 24) | (r << 16) | (g << 8) | b;       \
-        }                                                               \
-        *r = result;                                                    \
-    }
-VUPKPX(lpx, UPKLO)
-VUPKPX(hpx, UPKHI)
-#undef VUPKPX
-
-#define VUPK(suffix, unpacked, packee, hi)                              \
-    void helper_vupk##suffix(ppc_avr_t *r, ppc_avr_t *b)                \
-    {                                                                   \
-        int i;                                                          \
-        ppc_avr_t result;                                               \
-                                                                        \
-        if (hi) {                                                       \
-            for (i = 0; i < ARRAY_SIZE(r->unpacked); i++) {             \
-                result.unpacked[i] = b->packee[i];                      \
-            }                                                           \
-        } else {                                                        \
-            for (i = ARRAY_SIZE(r->unpacked); i < ARRAY_SIZE(r->packee); \
-                 i++) {                                                 \
-                result.unpacked[i - ARRAY_SIZE(r->unpacked)] = b->packee[i]; \
-            }                                                           \
-        }                                                               \
-        *r = result;                                                    \
-    }
-VUPK(hsb, s16, s8, UPKHI)
-VUPK(hsh, s32, s16, UPKHI)
-VUPK(lsb, s16, s8, UPKLO)
-VUPK(lsh, s32, s16, UPKLO)
-#undef VUPK
-#undef UPKHI
-#undef UPKLO
-
-#undef DO_HANDLE_NAN
-#undef HANDLE_NAN1
-#undef HANDLE_NAN2
-#undef HANDLE_NAN3
-#undef VECTOR_FOR_INORDER_I
 #undef HI_IDX
 #undef LO_IDX
 
 /*****************************************************************************/
-/* SPE extension helpers */
-/* Use a table to make this quicker */
-static uint8_t hbrev[16] = {
-    0x0, 0x8, 0x4, 0xC, 0x2, 0xA, 0x6, 0xE,
-    0x1, 0x9, 0x5, 0xD, 0x3, 0xB, 0x7, 0xF,
-};
-
-static inline uint8_t byte_reverse(uint8_t val)
-{
-    return hbrev[val >> 4] | (hbrev[val & 0xF] << 4);
-}
-
-static inline uint32_t word_reverse(uint32_t val)
-{
-    return byte_reverse(val >> 24) | (byte_reverse(val >> 16) << 8) |
-        (byte_reverse(val >> 8) << 16) | (byte_reverse(val) << 24);
-}
-
-#define MASKBITS 16 /* Random value - to be fixed (implementation dependent) */
-target_ulong helper_brinc(target_ulong arg1, target_ulong arg2)
-{
-    uint32_t a, b, d, mask;
-
-    mask = UINT32_MAX >> (32 - MASKBITS);
-    a = arg1 & mask;
-    b = arg2 & mask;
-    d = word_reverse(1 + word_reverse(a | ~b));
-    return (arg1 & ~mask) | (d & b);
-}
-
-uint32_t helper_cntlsw32(uint32_t val)
-{
-    if (val & 0x80000000) {
-        return clz32(~val);
-    } else {
-        return clz32(val);
-    }
-}
-
-uint32_t helper_cntlzw32(uint32_t val)
-{
-    return clz32(val);
-}
-
-/*****************************************************************************/
 /* Softmmu support */
 #if !defined(CONFIG_USER_ONLY)
 
commit 8e70394950ed55dd7f0a5f9b5f831cf70089d0df
Author: Blue Swirl <blauwirbel at gmail.com>
Date:   Wed May 30 04:23:27 2012 +0000

    ppc: Avoid AREG0 for FPU and SPE helpers
    
    Add an explicit CPUPPCState parameter instead of relying on AREG0.
    
    Signed-off-by: Blue Swirl <blauwirbel at gmail.com>
    Signed-off-by: Alexander Graf <agraf at suse.de>
    Signed-off-by: Andreas Färber <afaerber at suse.de>
    Signed-off-by: Alexander Graf <agraf at suse.de>

diff --git a/target-ppc/Makefile.objs b/target-ppc/Makefile.objs
index dde916c..5bea9c3 100644
--- a/target-ppc/Makefile.objs
+++ b/target-ppc/Makefile.objs
@@ -5,5 +5,4 @@ obj-y += op_helper.o helper.o
 obj-y += excp_helper.o
 obj-y += fpu_helper.o
 
-$(obj)/fpu_helper.o: QEMU_CFLAGS += $(HELPER_CFLAGS)
 $(obj)/op_helper.o: QEMU_CFLAGS += $(HELPER_CFLAGS)
diff --git a/target-ppc/fpu_helper.c b/target-ppc/fpu_helper.c
index be965d1..d90636f 100644
--- a/target-ppc/fpu_helper.c
+++ b/target-ppc/fpu_helper.c
@@ -17,12 +17,11 @@
  * License along with this library; if not, see <http://www.gnu.org/licenses/>.
  */
 #include "cpu.h"
-#include "dyngen-exec.h"
 #include "helper.h"
 
 /*****************************************************************************/
 /* Floating point operations helpers */
-uint64_t helper_float32_to_float64(uint32_t arg)
+uint64_t helper_float32_to_float64(CPUPPCState *env, uint32_t arg)
 {
     CPU_FloatU f;
     CPU_DoubleU d;
@@ -32,7 +31,7 @@ uint64_t helper_float32_to_float64(uint32_t arg)
     return d.ll;
 }
 
-uint32_t helper_float64_to_float32(uint64_t arg)
+uint32_t helper_float64_to_float32(CPUPPCState *env, uint64_t arg)
 {
     CPU_FloatU f;
     CPU_DoubleU d;
@@ -51,7 +50,7 @@ static inline int isden(float64 d)
     return ((u.ll >> 52) & 0x7FF) == 0;
 }
 
-uint32_t helper_compute_fprf(uint64_t arg, uint32_t set_fprf)
+uint32_t helper_compute_fprf(CPUPPCState *env, uint64_t arg, uint32_t set_fprf)
 {
     CPU_DoubleU farg;
     int isneg;
@@ -107,7 +106,7 @@ uint32_t helper_compute_fprf(uint64_t arg, uint32_t set_fprf)
 }
 
 /* Floating-point invalid operations exception */
-static inline uint64_t fload_invalid_op_excp(int op)
+static inline uint64_t fload_invalid_op_excp(CPUPPCState *env, int op)
 {
     uint64_t ret = 0;
     int ve;
@@ -190,7 +189,7 @@ static inline uint64_t fload_invalid_op_excp(int op)
     return ret;
 }
 
-static inline void float_zero_divide_excp(void)
+static inline void float_zero_divide_excp(CPUPPCState *env)
 {
     env->fpscr |= 1 << FPSCR_ZX;
     env->fpscr &= ~((1 << FPSCR_FR) | (1 << FPSCR_FI));
@@ -206,7 +205,7 @@ static inline void float_zero_divide_excp(void)
     }
 }
 
-static inline void float_overflow_excp(void)
+static inline void float_overflow_excp(CPUPPCState *env)
 {
     env->fpscr |= 1 << FPSCR_OX;
     /* Update the floating-point exception summary */
@@ -224,7 +223,7 @@ static inline void float_overflow_excp(void)
     }
 }
 
-static inline void float_underflow_excp(void)
+static inline void float_underflow_excp(CPUPPCState *env)
 {
     env->fpscr |= 1 << FPSCR_UX;
     /* Update the floating-point exception summary */
@@ -239,7 +238,7 @@ static inline void float_underflow_excp(void)
     }
 }
 
-static inline void float_inexact_excp(void)
+static inline void float_inexact_excp(CPUPPCState *env)
 {
     env->fpscr |= 1 << FPSCR_XX;
     /* Update the floating-point exception summary */
@@ -253,7 +252,7 @@ static inline void float_inexact_excp(void)
     }
 }
 
-static inline void fpscr_set_rounding_mode(void)
+static inline void fpscr_set_rounding_mode(CPUPPCState *env)
 {
     int rnd_type;
 
@@ -280,7 +279,7 @@ static inline void fpscr_set_rounding_mode(void)
     set_float_rounding_mode(rnd_type, &env->fp_status);
 }
 
-void helper_fpscr_clrbit(uint32_t bit)
+void helper_fpscr_clrbit(CPUPPCState *env, uint32_t bit)
 {
     int prev;
 
@@ -290,7 +289,7 @@ void helper_fpscr_clrbit(uint32_t bit)
         switch (bit) {
         case FPSCR_RN1:
         case FPSCR_RN:
-            fpscr_set_rounding_mode();
+            fpscr_set_rounding_mode(env);
             break;
         default:
             break;
@@ -298,7 +297,7 @@ void helper_fpscr_clrbit(uint32_t bit)
     }
 }
 
-void helper_fpscr_setbit(uint32_t bit)
+void helper_fpscr_setbit(CPUPPCState *env, uint32_t bit)
 {
     int prev;
 
@@ -414,7 +413,7 @@ void helper_fpscr_setbit(uint32_t bit)
             break;
         case FPSCR_RN1:
         case FPSCR_RN:
-            fpscr_set_rounding_mode();
+            fpscr_set_rounding_mode(env);
             break;
         default:
             break;
@@ -428,7 +427,7 @@ void helper_fpscr_setbit(uint32_t bit)
     }
 }
 
-void helper_store_fpscr(uint64_t arg, uint32_t mask)
+void helper_store_fpscr(CPUPPCState *env, uint64_t arg, uint32_t mask)
 {
     /*
      * We use only the 32 LSB of the incoming fpr
@@ -460,10 +459,10 @@ void helper_store_fpscr(uint64_t arg, uint32_t mask)
     } else {
         env->fpscr &= ~(1 << FPSCR_FEX);
     }
-    fpscr_set_rounding_mode();
+    fpscr_set_rounding_mode(env);
 }
 
-void helper_float_check_status(void)
+void helper_float_check_status(CPUPPCState *env)
 {
     if (env->exception_index == POWERPC_EXCP_PROGRAM &&
         (env->error_code & POWERPC_EXCP_FP)) {
@@ -475,24 +474,24 @@ void helper_float_check_status(void)
     } else {
         int status = get_float_exception_flags(&env->fp_status);
         if (status & float_flag_divbyzero) {
-            float_zero_divide_excp();
+            float_zero_divide_excp(env);
         } else if (status & float_flag_overflow) {
-            float_overflow_excp();
+            float_overflow_excp(env);
         } else if (status & float_flag_underflow) {
-            float_underflow_excp();
+            float_underflow_excp(env);
         } else if (status & float_flag_inexact) {
-            float_inexact_excp();
+            float_inexact_excp(env);
         }
     }
 }
 
-void helper_reset_fpstatus(void)
+void helper_reset_fpstatus(CPUPPCState *env)
 {
     set_float_exception_flags(0, &env->fp_status);
 }
 
 /* fadd - fadd. */
-uint64_t helper_fadd(uint64_t arg1, uint64_t arg2)
+uint64_t helper_fadd(CPUPPCState *env, uint64_t arg1, uint64_t arg2)
 {
     CPU_DoubleU farg1, farg2;
 
@@ -502,12 +501,12 @@ uint64_t helper_fadd(uint64_t arg1, uint64_t arg2)
     if (unlikely(float64_is_infinity(farg1.d) && float64_is_infinity(farg2.d) &&
                  float64_is_neg(farg1.d) != float64_is_neg(farg2.d))) {
         /* Magnitude subtraction of infinities */
-        farg1.ll = fload_invalid_op_excp(POWERPC_EXCP_FP_VXISI);
+        farg1.ll = fload_invalid_op_excp(env, POWERPC_EXCP_FP_VXISI);
     } else {
         if (unlikely(float64_is_signaling_nan(farg1.d) ||
                      float64_is_signaling_nan(farg2.d))) {
             /* sNaN addition */
-            fload_invalid_op_excp(POWERPC_EXCP_FP_VXSNAN);
+            fload_invalid_op_excp(env, POWERPC_EXCP_FP_VXSNAN);
         }
         farg1.d = float64_add(farg1.d, farg2.d, &env->fp_status);
     }
@@ -516,7 +515,7 @@ uint64_t helper_fadd(uint64_t arg1, uint64_t arg2)
 }
 
 /* fsub - fsub. */
-uint64_t helper_fsub(uint64_t arg1, uint64_t arg2)
+uint64_t helper_fsub(CPUPPCState *env, uint64_t arg1, uint64_t arg2)
 {
     CPU_DoubleU farg1, farg2;
 
@@ -526,12 +525,12 @@ uint64_t helper_fsub(uint64_t arg1, uint64_t arg2)
     if (unlikely(float64_is_infinity(farg1.d) && float64_is_infinity(farg2.d) &&
                  float64_is_neg(farg1.d) == float64_is_neg(farg2.d))) {
         /* Magnitude subtraction of infinities */
-        farg1.ll = fload_invalid_op_excp(POWERPC_EXCP_FP_VXISI);
+        farg1.ll = fload_invalid_op_excp(env, POWERPC_EXCP_FP_VXISI);
     } else {
         if (unlikely(float64_is_signaling_nan(farg1.d) ||
                      float64_is_signaling_nan(farg2.d))) {
             /* sNaN subtraction */
-            fload_invalid_op_excp(POWERPC_EXCP_FP_VXSNAN);
+            fload_invalid_op_excp(env, POWERPC_EXCP_FP_VXSNAN);
         }
         farg1.d = float64_sub(farg1.d, farg2.d, &env->fp_status);
     }
@@ -540,7 +539,7 @@ uint64_t helper_fsub(uint64_t arg1, uint64_t arg2)
 }
 
 /* fmul - fmul. */
-uint64_t helper_fmul(uint64_t arg1, uint64_t arg2)
+uint64_t helper_fmul(CPUPPCState *env, uint64_t arg1, uint64_t arg2)
 {
     CPU_DoubleU farg1, farg2;
 
@@ -550,12 +549,12 @@ uint64_t helper_fmul(uint64_t arg1, uint64_t arg2)
     if (unlikely((float64_is_infinity(farg1.d) && float64_is_zero(farg2.d)) ||
                  (float64_is_zero(farg1.d) && float64_is_infinity(farg2.d)))) {
         /* Multiplication of zero by infinity */
-        farg1.ll = fload_invalid_op_excp(POWERPC_EXCP_FP_VXIMZ);
+        farg1.ll = fload_invalid_op_excp(env, POWERPC_EXCP_FP_VXIMZ);
     } else {
         if (unlikely(float64_is_signaling_nan(farg1.d) ||
                      float64_is_signaling_nan(farg2.d))) {
             /* sNaN multiplication */
-            fload_invalid_op_excp(POWERPC_EXCP_FP_VXSNAN);
+            fload_invalid_op_excp(env, POWERPC_EXCP_FP_VXSNAN);
         }
         farg1.d = float64_mul(farg1.d, farg2.d, &env->fp_status);
     }
@@ -564,7 +563,7 @@ uint64_t helper_fmul(uint64_t arg1, uint64_t arg2)
 }
 
 /* fdiv - fdiv. */
-uint64_t helper_fdiv(uint64_t arg1, uint64_t arg2)
+uint64_t helper_fdiv(CPUPPCState *env, uint64_t arg1, uint64_t arg2)
 {
     CPU_DoubleU farg1, farg2;
 
@@ -574,15 +573,15 @@ uint64_t helper_fdiv(uint64_t arg1, uint64_t arg2)
     if (unlikely(float64_is_infinity(farg1.d) &&
                  float64_is_infinity(farg2.d))) {
         /* Division of infinity by infinity */
-        farg1.ll = fload_invalid_op_excp(POWERPC_EXCP_FP_VXIDI);
+        farg1.ll = fload_invalid_op_excp(env, POWERPC_EXCP_FP_VXIDI);
     } else if (unlikely(float64_is_zero(farg1.d) && float64_is_zero(farg2.d))) {
         /* Division of zero by zero */
-        farg1.ll = fload_invalid_op_excp(POWERPC_EXCP_FP_VXZDZ);
+        farg1.ll = fload_invalid_op_excp(env, POWERPC_EXCP_FP_VXZDZ);
     } else {
         if (unlikely(float64_is_signaling_nan(farg1.d) ||
                      float64_is_signaling_nan(farg2.d))) {
             /* sNaN division */
-            fload_invalid_op_excp(POWERPC_EXCP_FP_VXSNAN);
+            fload_invalid_op_excp(env, POWERPC_EXCP_FP_VXSNAN);
         }
         farg1.d = float64_div(farg1.d, farg2.d, &env->fp_status);
     }
@@ -591,7 +590,7 @@ uint64_t helper_fdiv(uint64_t arg1, uint64_t arg2)
 }
 
 /* fabs */
-uint64_t helper_fabs(uint64_t arg)
+uint64_t helper_fabs(CPUPPCState *env, uint64_t arg)
 {
     CPU_DoubleU farg;
 
@@ -601,7 +600,7 @@ uint64_t helper_fabs(uint64_t arg)
 }
 
 /* fnabs */
-uint64_t helper_fnabs(uint64_t arg)
+uint64_t helper_fnabs(CPUPPCState *env, uint64_t arg)
 {
     CPU_DoubleU farg;
 
@@ -612,7 +611,7 @@ uint64_t helper_fnabs(uint64_t arg)
 }
 
 /* fneg */
-uint64_t helper_fneg(uint64_t arg)
+uint64_t helper_fneg(CPUPPCState *env, uint64_t arg)
 {
     CPU_DoubleU farg;
 
@@ -622,7 +621,7 @@ uint64_t helper_fneg(uint64_t arg)
 }
 
 /* fctiw - fctiw. */
-uint64_t helper_fctiw(uint64_t arg)
+uint64_t helper_fctiw(CPUPPCState *env, uint64_t arg)
 {
     CPU_DoubleU farg;
 
@@ -630,12 +629,12 @@ uint64_t helper_fctiw(uint64_t arg)
 
     if (unlikely(float64_is_signaling_nan(farg.d))) {
         /* sNaN conversion */
-        farg.ll = fload_invalid_op_excp(POWERPC_EXCP_FP_VXSNAN |
+        farg.ll = fload_invalid_op_excp(env, POWERPC_EXCP_FP_VXSNAN |
                                         POWERPC_EXCP_FP_VXCVI);
     } else if (unlikely(float64_is_quiet_nan(farg.d) ||
                         float64_is_infinity(farg.d))) {
         /* qNan / infinity conversion */
-        farg.ll = fload_invalid_op_excp(POWERPC_EXCP_FP_VXCVI);
+        farg.ll = fload_invalid_op_excp(env, POWERPC_EXCP_FP_VXCVI);
     } else {
         farg.ll = float64_to_int32(farg.d, &env->fp_status);
         /* XXX: higher bits are not supposed to be significant.
@@ -647,7 +646,7 @@ uint64_t helper_fctiw(uint64_t arg)
 }
 
 /* fctiwz - fctiwz. */
-uint64_t helper_fctiwz(uint64_t arg)
+uint64_t helper_fctiwz(CPUPPCState *env, uint64_t arg)
 {
     CPU_DoubleU farg;
 
@@ -655,12 +654,12 @@ uint64_t helper_fctiwz(uint64_t arg)
 
     if (unlikely(float64_is_signaling_nan(farg.d))) {
         /* sNaN conversion */
-        farg.ll = fload_invalid_op_excp(POWERPC_EXCP_FP_VXSNAN |
+        farg.ll = fload_invalid_op_excp(env, POWERPC_EXCP_FP_VXSNAN |
                                         POWERPC_EXCP_FP_VXCVI);
     } else if (unlikely(float64_is_quiet_nan(farg.d) ||
                         float64_is_infinity(farg.d))) {
         /* qNan / infinity conversion */
-        farg.ll = fload_invalid_op_excp(POWERPC_EXCP_FP_VXCVI);
+        farg.ll = fload_invalid_op_excp(env, POWERPC_EXCP_FP_VXCVI);
     } else {
         farg.ll = float64_to_int32_round_to_zero(farg.d, &env->fp_status);
         /* XXX: higher bits are not supposed to be significant.
@@ -673,7 +672,7 @@ uint64_t helper_fctiwz(uint64_t arg)
 
 #if defined(TARGET_PPC64)
 /* fcfid - fcfid. */
-uint64_t helper_fcfid(uint64_t arg)
+uint64_t helper_fcfid(CPUPPCState *env, uint64_t arg)
 {
     CPU_DoubleU farg;
 
@@ -682,7 +681,7 @@ uint64_t helper_fcfid(uint64_t arg)
 }
 
 /* fctid - fctid. */
-uint64_t helper_fctid(uint64_t arg)
+uint64_t helper_fctid(CPUPPCState *env, uint64_t arg)
 {
     CPU_DoubleU farg;
 
@@ -690,12 +689,12 @@ uint64_t helper_fctid(uint64_t arg)
 
     if (unlikely(float64_is_signaling_nan(farg.d))) {
         /* sNaN conversion */
-        farg.ll = fload_invalid_op_excp(POWERPC_EXCP_FP_VXSNAN |
+        farg.ll = fload_invalid_op_excp(env, POWERPC_EXCP_FP_VXSNAN |
                                         POWERPC_EXCP_FP_VXCVI);
     } else if (unlikely(float64_is_quiet_nan(farg.d) ||
                         float64_is_infinity(farg.d))) {
         /* qNan / infinity conversion */
-        farg.ll = fload_invalid_op_excp(POWERPC_EXCP_FP_VXCVI);
+        farg.ll = fload_invalid_op_excp(env, POWERPC_EXCP_FP_VXCVI);
     } else {
         farg.ll = float64_to_int64(farg.d, &env->fp_status);
     }
@@ -703,7 +702,7 @@ uint64_t helper_fctid(uint64_t arg)
 }
 
 /* fctidz - fctidz. */
-uint64_t helper_fctidz(uint64_t arg)
+uint64_t helper_fctidz(CPUPPCState *env, uint64_t arg)
 {
     CPU_DoubleU farg;
 
@@ -711,12 +710,12 @@ uint64_t helper_fctidz(uint64_t arg)
 
     if (unlikely(float64_is_signaling_nan(farg.d))) {
         /* sNaN conversion */
-        farg.ll = fload_invalid_op_excp(POWERPC_EXCP_FP_VXSNAN |
+        farg.ll = fload_invalid_op_excp(env, POWERPC_EXCP_FP_VXSNAN |
                                         POWERPC_EXCP_FP_VXCVI);
     } else if (unlikely(float64_is_quiet_nan(farg.d) ||
                         float64_is_infinity(farg.d))) {
         /* qNan / infinity conversion */
-        farg.ll = fload_invalid_op_excp(POWERPC_EXCP_FP_VXCVI);
+        farg.ll = fload_invalid_op_excp(env, POWERPC_EXCP_FP_VXCVI);
     } else {
         farg.ll = float64_to_int64_round_to_zero(farg.d, &env->fp_status);
     }
@@ -725,7 +724,8 @@ uint64_t helper_fctidz(uint64_t arg)
 
 #endif
 
-static inline uint64_t do_fri(uint64_t arg, int rounding_mode)
+static inline uint64_t do_fri(CPUPPCState *env, uint64_t arg,
+                              int rounding_mode)
 {
     CPU_DoubleU farg;
 
@@ -733,43 +733,44 @@ static inline uint64_t do_fri(uint64_t arg, int rounding_mode)
 
     if (unlikely(float64_is_signaling_nan(farg.d))) {
         /* sNaN round */
-        farg.ll = fload_invalid_op_excp(POWERPC_EXCP_FP_VXSNAN |
+        farg.ll = fload_invalid_op_excp(env, POWERPC_EXCP_FP_VXSNAN |
                                         POWERPC_EXCP_FP_VXCVI);
     } else if (unlikely(float64_is_quiet_nan(farg.d) ||
                         float64_is_infinity(farg.d))) {
         /* qNan / infinity round */
-        farg.ll = fload_invalid_op_excp(POWERPC_EXCP_FP_VXCVI);
+        farg.ll = fload_invalid_op_excp(env, POWERPC_EXCP_FP_VXCVI);
     } else {
         set_float_rounding_mode(rounding_mode, &env->fp_status);
         farg.ll = float64_round_to_int(farg.d, &env->fp_status);
         /* Restore rounding mode from FPSCR */
-        fpscr_set_rounding_mode();
+        fpscr_set_rounding_mode(env);
     }
     return farg.ll;
 }
 
-uint64_t helper_frin(uint64_t arg)
+uint64_t helper_frin(CPUPPCState *env, uint64_t arg)
 {
-    return do_fri(arg, float_round_nearest_even);
+    return do_fri(env, arg, float_round_nearest_even);
 }
 
-uint64_t helper_friz(uint64_t arg)
+uint64_t helper_friz(CPUPPCState *env, uint64_t arg)
 {
-    return do_fri(arg, float_round_to_zero);
+    return do_fri(env, arg, float_round_to_zero);
 }
 
-uint64_t helper_frip(uint64_t arg)
+uint64_t helper_frip(CPUPPCState *env, uint64_t arg)
 {
-    return do_fri(arg, float_round_up);
+    return do_fri(env, arg, float_round_up);
 }
 
-uint64_t helper_frim(uint64_t arg)
+uint64_t helper_frim(CPUPPCState *env, uint64_t arg)
 {
-    return do_fri(arg, float_round_down);
+    return do_fri(env, arg, float_round_down);
 }
 
 /* fmadd - fmadd. */
-uint64_t helper_fmadd(uint64_t arg1, uint64_t arg2, uint64_t arg3)
+uint64_t helper_fmadd(CPUPPCState *env, uint64_t arg1, uint64_t arg2,
+                      uint64_t arg3)
 {
     CPU_DoubleU farg1, farg2, farg3;
 
@@ -780,13 +781,13 @@ uint64_t helper_fmadd(uint64_t arg1, uint64_t arg2, uint64_t arg3)
     if (unlikely((float64_is_infinity(farg1.d) && float64_is_zero(farg2.d)) ||
                  (float64_is_zero(farg1.d) && float64_is_infinity(farg2.d)))) {
         /* Multiplication of zero by infinity */
-        farg1.ll = fload_invalid_op_excp(POWERPC_EXCP_FP_VXIMZ);
+        farg1.ll = fload_invalid_op_excp(env, POWERPC_EXCP_FP_VXIMZ);
     } else {
         if (unlikely(float64_is_signaling_nan(farg1.d) ||
                      float64_is_signaling_nan(farg2.d) ||
                      float64_is_signaling_nan(farg3.d))) {
             /* sNaN operation */
-            fload_invalid_op_excp(POWERPC_EXCP_FP_VXSNAN);
+            fload_invalid_op_excp(env, POWERPC_EXCP_FP_VXSNAN);
         }
         /* This is the way the PowerPC specification defines it */
         float128 ft0_128, ft1_128;
@@ -798,7 +799,7 @@ uint64_t helper_fmadd(uint64_t arg1, uint64_t arg2, uint64_t arg3)
                      float64_is_infinity(farg3.d) &&
                      float128_is_neg(ft0_128) != float64_is_neg(farg3.d))) {
             /* Magnitude subtraction of infinities */
-            farg1.ll = fload_invalid_op_excp(POWERPC_EXCP_FP_VXISI);
+            farg1.ll = fload_invalid_op_excp(env, POWERPC_EXCP_FP_VXISI);
         } else {
             ft1_128 = float64_to_float128(farg3.d, &env->fp_status);
             ft0_128 = float128_add(ft0_128, ft1_128, &env->fp_status);
@@ -810,7 +811,8 @@ uint64_t helper_fmadd(uint64_t arg1, uint64_t arg2, uint64_t arg3)
 }
 
 /* fmsub - fmsub. */
-uint64_t helper_fmsub(uint64_t arg1, uint64_t arg2, uint64_t arg3)
+uint64_t helper_fmsub(CPUPPCState *env, uint64_t arg1, uint64_t arg2,
+                      uint64_t arg3)
 {
     CPU_DoubleU farg1, farg2, farg3;
 
@@ -822,13 +824,13 @@ uint64_t helper_fmsub(uint64_t arg1, uint64_t arg2, uint64_t arg3)
                  (float64_is_zero(farg1.d) &&
                   float64_is_infinity(farg2.d)))) {
         /* Multiplication of zero by infinity */
-        farg1.ll = fload_invalid_op_excp(POWERPC_EXCP_FP_VXIMZ);
+        farg1.ll = fload_invalid_op_excp(env, POWERPC_EXCP_FP_VXIMZ);
     } else {
         if (unlikely(float64_is_signaling_nan(farg1.d) ||
                      float64_is_signaling_nan(farg2.d) ||
                      float64_is_signaling_nan(farg3.d))) {
             /* sNaN operation */
-            fload_invalid_op_excp(POWERPC_EXCP_FP_VXSNAN);
+            fload_invalid_op_excp(env, POWERPC_EXCP_FP_VXSNAN);
         }
         /* This is the way the PowerPC specification defines it */
         float128 ft0_128, ft1_128;
@@ -840,7 +842,7 @@ uint64_t helper_fmsub(uint64_t arg1, uint64_t arg2, uint64_t arg3)
                      float64_is_infinity(farg3.d) &&
                      float128_is_neg(ft0_128) == float64_is_neg(farg3.d))) {
             /* Magnitude subtraction of infinities */
-            farg1.ll = fload_invalid_op_excp(POWERPC_EXCP_FP_VXISI);
+            farg1.ll = fload_invalid_op_excp(env, POWERPC_EXCP_FP_VXISI);
         } else {
             ft1_128 = float64_to_float128(farg3.d, &env->fp_status);
             ft0_128 = float128_sub(ft0_128, ft1_128, &env->fp_status);
@@ -851,7 +853,8 @@ uint64_t helper_fmsub(uint64_t arg1, uint64_t arg2, uint64_t arg3)
 }
 
 /* fnmadd - fnmadd. */
-uint64_t helper_fnmadd(uint64_t arg1, uint64_t arg2, uint64_t arg3)
+uint64_t helper_fnmadd(CPUPPCState *env, uint64_t arg1, uint64_t arg2,
+                       uint64_t arg3)
 {
     CPU_DoubleU farg1, farg2, farg3;
 
@@ -862,13 +865,13 @@ uint64_t helper_fnmadd(uint64_t arg1, uint64_t arg2, uint64_t arg3)
     if (unlikely((float64_is_infinity(farg1.d) && float64_is_zero(farg2.d)) ||
                  (float64_is_zero(farg1.d) && float64_is_infinity(farg2.d)))) {
         /* Multiplication of zero by infinity */
-        farg1.ll = fload_invalid_op_excp(POWERPC_EXCP_FP_VXIMZ);
+        farg1.ll = fload_invalid_op_excp(env, POWERPC_EXCP_FP_VXIMZ);
     } else {
         if (unlikely(float64_is_signaling_nan(farg1.d) ||
                      float64_is_signaling_nan(farg2.d) ||
                      float64_is_signaling_nan(farg3.d))) {
             /* sNaN operation */
-            fload_invalid_op_excp(POWERPC_EXCP_FP_VXSNAN);
+            fload_invalid_op_excp(env, POWERPC_EXCP_FP_VXSNAN);
         }
         /* This is the way the PowerPC specification defines it */
         float128 ft0_128, ft1_128;
@@ -880,7 +883,7 @@ uint64_t helper_fnmadd(uint64_t arg1, uint64_t arg2, uint64_t arg3)
                      float64_is_infinity(farg3.d) &&
                      float128_is_neg(ft0_128) != float64_is_neg(farg3.d))) {
             /* Magnitude subtraction of infinities */
-            farg1.ll = fload_invalid_op_excp(POWERPC_EXCP_FP_VXISI);
+            farg1.ll = fload_invalid_op_excp(env, POWERPC_EXCP_FP_VXISI);
         } else {
             ft1_128 = float64_to_float128(farg3.d, &env->fp_status);
             ft0_128 = float128_add(ft0_128, ft1_128, &env->fp_status);
@@ -894,7 +897,8 @@ uint64_t helper_fnmadd(uint64_t arg1, uint64_t arg2, uint64_t arg3)
 }
 
 /* fnmsub - fnmsub. */
-uint64_t helper_fnmsub(uint64_t arg1, uint64_t arg2, uint64_t arg3)
+uint64_t helper_fnmsub(CPUPPCState *env, uint64_t arg1, uint64_t arg2,
+                       uint64_t arg3)
 {
     CPU_DoubleU farg1, farg2, farg3;
 
@@ -906,13 +910,13 @@ uint64_t helper_fnmsub(uint64_t arg1, uint64_t arg2, uint64_t arg3)
                  (float64_is_zero(farg1.d) &&
                   float64_is_infinity(farg2.d)))) {
         /* Multiplication of zero by infinity */
-        farg1.ll = fload_invalid_op_excp(POWERPC_EXCP_FP_VXIMZ);
+        farg1.ll = fload_invalid_op_excp(env, POWERPC_EXCP_FP_VXIMZ);
     } else {
         if (unlikely(float64_is_signaling_nan(farg1.d) ||
                      float64_is_signaling_nan(farg2.d) ||
                      float64_is_signaling_nan(farg3.d))) {
             /* sNaN operation */
-            fload_invalid_op_excp(POWERPC_EXCP_FP_VXSNAN);
+            fload_invalid_op_excp(env, POWERPC_EXCP_FP_VXSNAN);
         }
         /* This is the way the PowerPC specification defines it */
         float128 ft0_128, ft1_128;
@@ -924,7 +928,7 @@ uint64_t helper_fnmsub(uint64_t arg1, uint64_t arg2, uint64_t arg3)
                      float64_is_infinity(farg3.d) &&
                      float128_is_neg(ft0_128) == float64_is_neg(farg3.d))) {
             /* Magnitude subtraction of infinities */
-            farg1.ll = fload_invalid_op_excp(POWERPC_EXCP_FP_VXISI);
+            farg1.ll = fload_invalid_op_excp(env, POWERPC_EXCP_FP_VXISI);
         } else {
             ft1_128 = float64_to_float128(farg3.d, &env->fp_status);
             ft0_128 = float128_sub(ft0_128, ft1_128, &env->fp_status);
@@ -938,7 +942,7 @@ uint64_t helper_fnmsub(uint64_t arg1, uint64_t arg2, uint64_t arg3)
 }
 
 /* frsp - frsp. */
-uint64_t helper_frsp(uint64_t arg)
+uint64_t helper_frsp(CPUPPCState *env, uint64_t arg)
 {
     CPU_DoubleU farg;
     float32 f32;
@@ -947,7 +951,7 @@ uint64_t helper_frsp(uint64_t arg)
 
     if (unlikely(float64_is_signaling_nan(farg.d))) {
         /* sNaN square root */
-        fload_invalid_op_excp(POWERPC_EXCP_FP_VXSNAN);
+        fload_invalid_op_excp(env, POWERPC_EXCP_FP_VXSNAN);
     }
     f32 = float64_to_float32(farg.d, &env->fp_status);
     farg.d = float32_to_float64(f32, &env->fp_status);
@@ -956,7 +960,7 @@ uint64_t helper_frsp(uint64_t arg)
 }
 
 /* fsqrt - fsqrt. */
-uint64_t helper_fsqrt(uint64_t arg)
+uint64_t helper_fsqrt(CPUPPCState *env, uint64_t arg)
 {
     CPU_DoubleU farg;
 
@@ -964,11 +968,11 @@ uint64_t helper_fsqrt(uint64_t arg)
 
     if (unlikely(float64_is_neg(farg.d) && !float64_is_zero(farg.d))) {
         /* Square root of a negative nonzero number */
-        farg.ll = fload_invalid_op_excp(POWERPC_EXCP_FP_VXSQRT);
+        farg.ll = fload_invalid_op_excp(env, POWERPC_EXCP_FP_VXSQRT);
     } else {
         if (unlikely(float64_is_signaling_nan(farg.d))) {
             /* sNaN square root */
-            fload_invalid_op_excp(POWERPC_EXCP_FP_VXSNAN);
+            fload_invalid_op_excp(env, POWERPC_EXCP_FP_VXSNAN);
         }
         farg.d = float64_sqrt(farg.d, &env->fp_status);
     }
@@ -976,7 +980,7 @@ uint64_t helper_fsqrt(uint64_t arg)
 }
 
 /* fre - fre. */
-uint64_t helper_fre(uint64_t arg)
+uint64_t helper_fre(CPUPPCState *env, uint64_t arg)
 {
     CPU_DoubleU farg;
 
@@ -984,14 +988,14 @@ uint64_t helper_fre(uint64_t arg)
 
     if (unlikely(float64_is_signaling_nan(farg.d))) {
         /* sNaN reciprocal */
-        fload_invalid_op_excp(POWERPC_EXCP_FP_VXSNAN);
+        fload_invalid_op_excp(env, POWERPC_EXCP_FP_VXSNAN);
     }
     farg.d = float64_div(float64_one, farg.d, &env->fp_status);
     return farg.d;
 }
 
 /* fres - fres. */
-uint64_t helper_fres(uint64_t arg)
+uint64_t helper_fres(CPUPPCState *env, uint64_t arg)
 {
     CPU_DoubleU farg;
     float32 f32;
@@ -1000,7 +1004,7 @@ uint64_t helper_fres(uint64_t arg)
 
     if (unlikely(float64_is_signaling_nan(farg.d))) {
         /* sNaN reciprocal */
-        fload_invalid_op_excp(POWERPC_EXCP_FP_VXSNAN);
+        fload_invalid_op_excp(env, POWERPC_EXCP_FP_VXSNAN);
     }
     farg.d = float64_div(float64_one, farg.d, &env->fp_status);
     f32 = float64_to_float32(farg.d, &env->fp_status);
@@ -1010,7 +1014,7 @@ uint64_t helper_fres(uint64_t arg)
 }
 
 /* frsqrte  - frsqrte. */
-uint64_t helper_frsqrte(uint64_t arg)
+uint64_t helper_frsqrte(CPUPPCState *env, uint64_t arg)
 {
     CPU_DoubleU farg;
     float32 f32;
@@ -1019,11 +1023,11 @@ uint64_t helper_frsqrte(uint64_t arg)
 
     if (unlikely(float64_is_neg(farg.d) && !float64_is_zero(farg.d))) {
         /* Reciprocal square root of a negative nonzero number */
-        farg.ll = fload_invalid_op_excp(POWERPC_EXCP_FP_VXSQRT);
+        farg.ll = fload_invalid_op_excp(env, POWERPC_EXCP_FP_VXSQRT);
     } else {
         if (unlikely(float64_is_signaling_nan(farg.d))) {
             /* sNaN reciprocal square root */
-            fload_invalid_op_excp(POWERPC_EXCP_FP_VXSNAN);
+            fload_invalid_op_excp(env, POWERPC_EXCP_FP_VXSNAN);
         }
         farg.d = float64_sqrt(farg.d, &env->fp_status);
         farg.d = float64_div(float64_one, farg.d, &env->fp_status);
@@ -1034,7 +1038,8 @@ uint64_t helper_frsqrte(uint64_t arg)
 }
 
 /* fsel - fsel. */
-uint64_t helper_fsel(uint64_t arg1, uint64_t arg2, uint64_t arg3)
+uint64_t helper_fsel(CPUPPCState *env, uint64_t arg1, uint64_t arg2,
+                     uint64_t arg3)
 {
     CPU_DoubleU farg1;
 
@@ -1048,7 +1053,8 @@ uint64_t helper_fsel(uint64_t arg1, uint64_t arg2, uint64_t arg3)
     }
 }
 
-void helper_fcmpu(uint64_t arg1, uint64_t arg2, uint32_t crfD)
+void helper_fcmpu(CPUPPCState *env, uint64_t arg1, uint64_t arg2,
+                  uint32_t crfD)
 {
     CPU_DoubleU farg1, farg2;
     uint32_t ret = 0;
@@ -1074,11 +1080,12 @@ void helper_fcmpu(uint64_t arg1, uint64_t arg2, uint32_t crfD)
                  && (float64_is_signaling_nan(farg1.d) ||
                      float64_is_signaling_nan(farg2.d)))) {
         /* sNaN comparison */
-        fload_invalid_op_excp(POWERPC_EXCP_FP_VXSNAN);
+        fload_invalid_op_excp(env, POWERPC_EXCP_FP_VXSNAN);
     }
 }
 
-void helper_fcmpo(uint64_t arg1, uint64_t arg2, uint32_t crfD)
+void helper_fcmpo(CPUPPCState *env, uint64_t arg1, uint64_t arg2,
+                  uint32_t crfD)
 {
     CPU_DoubleU farg1, farg2;
     uint32_t ret = 0;
@@ -1104,17 +1111,17 @@ void helper_fcmpo(uint64_t arg1, uint64_t arg2, uint32_t crfD)
         if (float64_is_signaling_nan(farg1.d) ||
             float64_is_signaling_nan(farg2.d)) {
             /* sNaN comparison */
-            fload_invalid_op_excp(POWERPC_EXCP_FP_VXSNAN |
+            fload_invalid_op_excp(env, POWERPC_EXCP_FP_VXSNAN |
                                   POWERPC_EXCP_FP_VXVC);
         } else {
             /* qNaN comparison */
-            fload_invalid_op_excp(POWERPC_EXCP_FP_VXVC);
+            fload_invalid_op_excp(env, POWERPC_EXCP_FP_VXVC);
         }
     }
 }
 
 /* Single-precision floating-point conversions */
-static inline uint32_t efscfsi(uint32_t val)
+static inline uint32_t efscfsi(CPUPPCState *env, uint32_t val)
 {
     CPU_FloatU u;
 
@@ -1123,7 +1130,7 @@ static inline uint32_t efscfsi(uint32_t val)
     return u.l;
 }
 
-static inline uint32_t efscfui(uint32_t val)
+static inline uint32_t efscfui(CPUPPCState *env, uint32_t val)
 {
     CPU_FloatU u;
 
@@ -1132,7 +1139,7 @@ static inline uint32_t efscfui(uint32_t val)
     return u.l;
 }
 
-static inline int32_t efsctsi(uint32_t val)
+static inline int32_t efsctsi(CPUPPCState *env, uint32_t val)
 {
     CPU_FloatU u;
 
@@ -1145,7 +1152,7 @@ static inline int32_t efsctsi(uint32_t val)
     return float32_to_int32(u.f, &env->vec_status);
 }
 
-static inline uint32_t efsctui(uint32_t val)
+static inline uint32_t efsctui(CPUPPCState *env, uint32_t val)
 {
     CPU_FloatU u;
 
@@ -1158,7 +1165,7 @@ static inline uint32_t efsctui(uint32_t val)
     return float32_to_uint32(u.f, &env->vec_status);
 }
 
-static inline uint32_t efsctsiz(uint32_t val)
+static inline uint32_t efsctsiz(CPUPPCState *env, uint32_t val)
 {
     CPU_FloatU u;
 
@@ -1171,7 +1178,7 @@ static inline uint32_t efsctsiz(uint32_t val)
     return float32_to_int32_round_to_zero(u.f, &env->vec_status);
 }
 
-static inline uint32_t efsctuiz(uint32_t val)
+static inline uint32_t efsctuiz(CPUPPCState *env, uint32_t val)
 {
     CPU_FloatU u;
 
@@ -1184,7 +1191,7 @@ static inline uint32_t efsctuiz(uint32_t val)
     return float32_to_uint32_round_to_zero(u.f, &env->vec_status);
 }
 
-static inline uint32_t efscfsf(uint32_t val)
+static inline uint32_t efscfsf(CPUPPCState *env, uint32_t val)
 {
     CPU_FloatU u;
     float32 tmp;
@@ -1196,7 +1203,7 @@ static inline uint32_t efscfsf(uint32_t val)
     return u.l;
 }
 
-static inline uint32_t efscfuf(uint32_t val)
+static inline uint32_t efscfuf(CPUPPCState *env, uint32_t val)
 {
     CPU_FloatU u;
     float32 tmp;
@@ -1208,7 +1215,7 @@ static inline uint32_t efscfuf(uint32_t val)
     return u.l;
 }
 
-static inline uint32_t efsctsf(uint32_t val)
+static inline uint32_t efsctsf(CPUPPCState *env, uint32_t val)
 {
     CPU_FloatU u;
     float32 tmp;
@@ -1224,7 +1231,7 @@ static inline uint32_t efsctsf(uint32_t val)
     return float32_to_int32(u.f, &env->vec_status);
 }
 
-static inline uint32_t efsctuf(uint32_t val)
+static inline uint32_t efsctuf(CPUPPCState *env, uint32_t val)
 {
     CPU_FloatU u;
     float32 tmp;
@@ -1240,10 +1247,10 @@ static inline uint32_t efsctuf(uint32_t val)
     return float32_to_uint32(u.f, &env->vec_status);
 }
 
-#define HELPER_SPE_SINGLE_CONV(name)            \
-    uint32_t helper_e##name(uint32_t val)       \
-    {                                           \
-        return e##name(val);                    \
+#define HELPER_SPE_SINGLE_CONV(name)                              \
+    uint32_t helper_e##name(CPUPPCState *env, uint32_t val)       \
+    {                                                             \
+        return e##name(env, val);                                 \
     }
 /* efscfsi */
 HELPER_SPE_SINGLE_CONV(fscfsi);
@@ -1266,11 +1273,11 @@ HELPER_SPE_SINGLE_CONV(fsctsf);
 /* efsctuf */
 HELPER_SPE_SINGLE_CONV(fsctuf);
 
-#define HELPER_SPE_VECTOR_CONV(name)                    \
-    uint64_t helper_ev##name(uint64_t val)              \
-    {                                                   \
-        return ((uint64_t)e##name(val >> 32) << 32) |   \
-            (uint64_t)e##name(val);                     \
+#define HELPER_SPE_VECTOR_CONV(name)                            \
+    uint64_t helper_ev##name(CPUPPCState *env, uint64_t val)    \
+    {                                                           \
+        return ((uint64_t)e##name(env, val >> 32) << 32) |      \
+            (uint64_t)e##name(env, val);                        \
     }
 /* evfscfsi */
 HELPER_SPE_VECTOR_CONV(fscfsi);
@@ -1294,7 +1301,7 @@ HELPER_SPE_VECTOR_CONV(fsctsf);
 HELPER_SPE_VECTOR_CONV(fsctuf);
 
 /* Single-precision floating-point arithmetic */
-static inline uint32_t efsadd(uint32_t op1, uint32_t op2)
+static inline uint32_t efsadd(CPUPPCState *env, uint32_t op1, uint32_t op2)
 {
     CPU_FloatU u1, u2;
 
@@ -1304,7 +1311,7 @@ static inline uint32_t efsadd(uint32_t op1, uint32_t op2)
     return u1.l;
 }
 
-static inline uint32_t efssub(uint32_t op1, uint32_t op2)
+static inline uint32_t efssub(CPUPPCState *env, uint32_t op1, uint32_t op2)
 {
     CPU_FloatU u1, u2;
 
@@ -1314,7 +1321,7 @@ static inline uint32_t efssub(uint32_t op1, uint32_t op2)
     return u1.l;
 }
 
-static inline uint32_t efsmul(uint32_t op1, uint32_t op2)
+static inline uint32_t efsmul(CPUPPCState *env, uint32_t op1, uint32_t op2)
 {
     CPU_FloatU u1, u2;
 
@@ -1324,7 +1331,7 @@ static inline uint32_t efsmul(uint32_t op1, uint32_t op2)
     return u1.l;
 }
 
-static inline uint32_t efsdiv(uint32_t op1, uint32_t op2)
+static inline uint32_t efsdiv(CPUPPCState *env, uint32_t op1, uint32_t op2)
 {
     CPU_FloatU u1, u2;
 
@@ -1334,10 +1341,10 @@ static inline uint32_t efsdiv(uint32_t op1, uint32_t op2)
     return u1.l;
 }
 
-#define HELPER_SPE_SINGLE_ARITH(name)                   \
-    uint32_t helper_e##name(uint32_t op1, uint32_t op2) \
-    {                                                   \
-        return e##name(op1, op2);                       \
+#define HELPER_SPE_SINGLE_ARITH(name)                                   \
+    uint32_t helper_e##name(CPUPPCState *env, uint32_t op1, uint32_t op2) \
+    {                                                                   \
+        return e##name(env, op1, op2);                                  \
     }
 /* efsadd */
 HELPER_SPE_SINGLE_ARITH(fsadd);
@@ -1349,10 +1356,10 @@ HELPER_SPE_SINGLE_ARITH(fsmul);
 HELPER_SPE_SINGLE_ARITH(fsdiv);
 
 #define HELPER_SPE_VECTOR_ARITH(name)                                   \
-    uint64_t helper_ev##name(uint64_t op1, uint64_t op2)                \
+    uint64_t helper_ev##name(CPUPPCState *env, uint64_t op1, uint64_t op2) \
     {                                                                   \
-        return ((uint64_t)e##name(op1 >> 32, op2 >> 32) << 32) |        \
-            (uint64_t)e##name(op1, op2);                                \
+        return ((uint64_t)e##name(env, op1 >> 32, op2 >> 32) << 32) |   \
+            (uint64_t)e##name(env, op1, op2);                           \
     }
 /* evfsadd */
 HELPER_SPE_VECTOR_ARITH(fsadd);
@@ -1364,7 +1371,7 @@ HELPER_SPE_VECTOR_ARITH(fsmul);
 HELPER_SPE_VECTOR_ARITH(fsdiv);
 
 /* Single-precision floating-point comparisons */
-static inline uint32_t efscmplt(uint32_t op1, uint32_t op2)
+static inline uint32_t efscmplt(CPUPPCState *env, uint32_t op1, uint32_t op2)
 {
     CPU_FloatU u1, u2;
 
@@ -1373,7 +1380,7 @@ static inline uint32_t efscmplt(uint32_t op1, uint32_t op2)
     return float32_lt(u1.f, u2.f, &env->vec_status) ? 4 : 0;
 }
 
-static inline uint32_t efscmpgt(uint32_t op1, uint32_t op2)
+static inline uint32_t efscmpgt(CPUPPCState *env, uint32_t op1, uint32_t op2)
 {
     CPU_FloatU u1, u2;
 
@@ -1382,7 +1389,7 @@ static inline uint32_t efscmpgt(uint32_t op1, uint32_t op2)
     return float32_le(u1.f, u2.f, &env->vec_status) ? 0 : 4;
 }
 
-static inline uint32_t efscmpeq(uint32_t op1, uint32_t op2)
+static inline uint32_t efscmpeq(CPUPPCState *env, uint32_t op1, uint32_t op2)
 {
     CPU_FloatU u1, u2;
 
@@ -1391,28 +1398,28 @@ static inline uint32_t efscmpeq(uint32_t op1, uint32_t op2)
     return float32_eq(u1.f, u2.f, &env->vec_status) ? 4 : 0;
 }
 
-static inline uint32_t efststlt(uint32_t op1, uint32_t op2)
+static inline uint32_t efststlt(CPUPPCState *env, uint32_t op1, uint32_t op2)
 {
     /* XXX: TODO: ignore special values (NaN, infinites, ...) */
-    return efscmplt(op1, op2);
+    return efscmplt(env, op1, op2);
 }
 
-static inline uint32_t efststgt(uint32_t op1, uint32_t op2)
+static inline uint32_t efststgt(CPUPPCState *env, uint32_t op1, uint32_t op2)
 {
     /* XXX: TODO: ignore special values (NaN, infinites, ...) */
-    return efscmpgt(op1, op2);
+    return efscmpgt(env, op1, op2);
 }
 
-static inline uint32_t efststeq(uint32_t op1, uint32_t op2)
+static inline uint32_t efststeq(CPUPPCState *env, uint32_t op1, uint32_t op2)
 {
     /* XXX: TODO: ignore special values (NaN, infinites, ...) */
-    return efscmpeq(op1, op2);
+    return efscmpeq(env, op1, op2);
 }
 
-#define HELPER_SINGLE_SPE_CMP(name)                     \
-    uint32_t helper_e##name(uint32_t op1, uint32_t op2) \
-    {                                                   \
-        return e##name(op1, op2) << 2;                  \
+#define HELPER_SINGLE_SPE_CMP(name)                                     \
+    uint32_t helper_e##name(CPUPPCState *env, uint32_t op1, uint32_t op2) \
+    {                                                                   \
+        return e##name(env, op1, op2) << 2;                             \
     }
 /* efststlt */
 HELPER_SINGLE_SPE_CMP(fststlt);
@@ -1433,9 +1440,10 @@ static inline uint32_t evcmp_merge(int t0, int t1)
 }
 
 #define HELPER_VECTOR_SPE_CMP(name)                                     \
-    uint32_t helper_ev##name(uint64_t op1, uint64_t op2)                \
+    uint32_t helper_ev##name(CPUPPCState *env, uint64_t op1, uint64_t op2) \
     {                                                                   \
-        return evcmp_merge(e##name(op1 >> 32, op2 >> 32), e##name(op1, op2)); \
+        return evcmp_merge(e##name(env, op1 >> 32, op2 >> 32),          \
+                           e##name(env, op1, op2));                     \
     }
 /* evfststlt */
 HELPER_VECTOR_SPE_CMP(fststlt);
@@ -1451,7 +1459,7 @@ HELPER_VECTOR_SPE_CMP(fscmpgt);
 HELPER_VECTOR_SPE_CMP(fscmpeq);
 
 /* Double-precision floating-point conversion */
-uint64_t helper_efdcfsi(uint32_t val)
+uint64_t helper_efdcfsi(CPUPPCState *env, uint32_t val)
 {
     CPU_DoubleU u;
 
@@ -1460,7 +1468,7 @@ uint64_t helper_efdcfsi(uint32_t val)
     return u.ll;
 }
 
-uint64_t helper_efdcfsid(uint64_t val)
+uint64_t helper_efdcfsid(CPUPPCState *env, uint64_t val)
 {
     CPU_DoubleU u;
 
@@ -1469,7 +1477,7 @@ uint64_t helper_efdcfsid(uint64_t val)
     return u.ll;
 }
 
-uint64_t helper_efdcfui(uint32_t val)
+uint64_t helper_efdcfui(CPUPPCState *env, uint32_t val)
 {
     CPU_DoubleU u;
 
@@ -1478,7 +1486,7 @@ uint64_t helper_efdcfui(uint32_t val)
     return u.ll;
 }
 
-uint64_t helper_efdcfuid(uint64_t val)
+uint64_t helper_efdcfuid(CPUPPCState *env, uint64_t val)
 {
     CPU_DoubleU u;
 
@@ -1487,7 +1495,7 @@ uint64_t helper_efdcfuid(uint64_t val)
     return u.ll;
 }
 
-uint32_t helper_efdctsi(uint64_t val)
+uint32_t helper_efdctsi(CPUPPCState *env, uint64_t val)
 {
     CPU_DoubleU u;
 
@@ -1500,7 +1508,7 @@ uint32_t helper_efdctsi(uint64_t val)
     return float64_to_int32(u.d, &env->vec_status);
 }
 
-uint32_t helper_efdctui(uint64_t val)
+uint32_t helper_efdctui(CPUPPCState *env, uint64_t val)
 {
     CPU_DoubleU u;
 
@@ -1513,7 +1521,7 @@ uint32_t helper_efdctui(uint64_t val)
     return float64_to_uint32(u.d, &env->vec_status);
 }
 
-uint32_t helper_efdctsiz(uint64_t val)
+uint32_t helper_efdctsiz(CPUPPCState *env, uint64_t val)
 {
     CPU_DoubleU u;
 
@@ -1526,7 +1534,7 @@ uint32_t helper_efdctsiz(uint64_t val)
     return float64_to_int32_round_to_zero(u.d, &env->vec_status);
 }
 
-uint64_t helper_efdctsidz(uint64_t val)
+uint64_t helper_efdctsidz(CPUPPCState *env, uint64_t val)
 {
     CPU_DoubleU u;
 
@@ -1539,7 +1547,7 @@ uint64_t helper_efdctsidz(uint64_t val)
     return float64_to_int64_round_to_zero(u.d, &env->vec_status);
 }
 
-uint32_t helper_efdctuiz(uint64_t val)
+uint32_t helper_efdctuiz(CPUPPCState *env, uint64_t val)
 {
     CPU_DoubleU u;
 
@@ -1552,7 +1560,7 @@ uint32_t helper_efdctuiz(uint64_t val)
     return float64_to_uint32_round_to_zero(u.d, &env->vec_status);
 }
 
-uint64_t helper_efdctuidz(uint64_t val)
+uint64_t helper_efdctuidz(CPUPPCState *env, uint64_t val)
 {
     CPU_DoubleU u;
 
@@ -1565,7 +1573,7 @@ uint64_t helper_efdctuidz(uint64_t val)
     return float64_to_uint64_round_to_zero(u.d, &env->vec_status);
 }
 
-uint64_t helper_efdcfsf(uint32_t val)
+uint64_t helper_efdcfsf(CPUPPCState *env, uint32_t val)
 {
     CPU_DoubleU u;
     float64 tmp;
@@ -1577,7 +1585,7 @@ uint64_t helper_efdcfsf(uint32_t val)
     return u.ll;
 }
 
-uint64_t helper_efdcfuf(uint32_t val)
+uint64_t helper_efdcfuf(CPUPPCState *env, uint32_t val)
 {
     CPU_DoubleU u;
     float64 tmp;
@@ -1589,7 +1597,7 @@ uint64_t helper_efdcfuf(uint32_t val)
     return u.ll;
 }
 
-uint32_t helper_efdctsf(uint64_t val)
+uint32_t helper_efdctsf(CPUPPCState *env, uint64_t val)
 {
     CPU_DoubleU u;
     float64 tmp;
@@ -1605,7 +1613,7 @@ uint32_t helper_efdctsf(uint64_t val)
     return float64_to_int32(u.d, &env->vec_status);
 }
 
-uint32_t helper_efdctuf(uint64_t val)
+uint32_t helper_efdctuf(CPUPPCState *env, uint64_t val)
 {
     CPU_DoubleU u;
     float64 tmp;
@@ -1621,7 +1629,7 @@ uint32_t helper_efdctuf(uint64_t val)
     return float64_to_uint32(u.d, &env->vec_status);
 }
 
-uint32_t helper_efscfd(uint64_t val)
+uint32_t helper_efscfd(CPUPPCState *env, uint64_t val)
 {
     CPU_DoubleU u1;
     CPU_FloatU u2;
@@ -1632,7 +1640,7 @@ uint32_t helper_efscfd(uint64_t val)
     return u2.l;
 }
 
-uint64_t helper_efdcfs(uint32_t val)
+uint64_t helper_efdcfs(CPUPPCState *env, uint32_t val)
 {
     CPU_DoubleU u2;
     CPU_FloatU u1;
@@ -1644,7 +1652,7 @@ uint64_t helper_efdcfs(uint32_t val)
 }
 
 /* Double precision fixed-point arithmetic */
-uint64_t helper_efdadd(uint64_t op1, uint64_t op2)
+uint64_t helper_efdadd(CPUPPCState *env, uint64_t op1, uint64_t op2)
 {
     CPU_DoubleU u1, u2;
 
@@ -1654,7 +1662,7 @@ uint64_t helper_efdadd(uint64_t op1, uint64_t op2)
     return u1.ll;
 }
 
-uint64_t helper_efdsub(uint64_t op1, uint64_t op2)
+uint64_t helper_efdsub(CPUPPCState *env, uint64_t op1, uint64_t op2)
 {
     CPU_DoubleU u1, u2;
 
@@ -1664,7 +1672,7 @@ uint64_t helper_efdsub(uint64_t op1, uint64_t op2)
     return u1.ll;
 }
 
-uint64_t helper_efdmul(uint64_t op1, uint64_t op2)
+uint64_t helper_efdmul(CPUPPCState *env, uint64_t op1, uint64_t op2)
 {
     CPU_DoubleU u1, u2;
 
@@ -1674,7 +1682,7 @@ uint64_t helper_efdmul(uint64_t op1, uint64_t op2)
     return u1.ll;
 }
 
-uint64_t helper_efddiv(uint64_t op1, uint64_t op2)
+uint64_t helper_efddiv(CPUPPCState *env, uint64_t op1, uint64_t op2)
 {
     CPU_DoubleU u1, u2;
 
@@ -1685,7 +1693,7 @@ uint64_t helper_efddiv(uint64_t op1, uint64_t op2)
 }
 
 /* Double precision floating point helpers */
-uint32_t helper_efdtstlt(uint64_t op1, uint64_t op2)
+uint32_t helper_efdtstlt(CPUPPCState *env, uint64_t op1, uint64_t op2)
 {
     CPU_DoubleU u1, u2;
 
@@ -1694,7 +1702,7 @@ uint32_t helper_efdtstlt(uint64_t op1, uint64_t op2)
     return float64_lt(u1.d, u2.d, &env->vec_status) ? 4 : 0;
 }
 
-uint32_t helper_efdtstgt(uint64_t op1, uint64_t op2)
+uint32_t helper_efdtstgt(CPUPPCState *env, uint64_t op1, uint64_t op2)
 {
     CPU_DoubleU u1, u2;
 
@@ -1703,7 +1711,7 @@ uint32_t helper_efdtstgt(uint64_t op1, uint64_t op2)
     return float64_le(u1.d, u2.d, &env->vec_status) ? 0 : 4;
 }
 
-uint32_t helper_efdtsteq(uint64_t op1, uint64_t op2)
+uint32_t helper_efdtsteq(CPUPPCState *env, uint64_t op1, uint64_t op2)
 {
     CPU_DoubleU u1, u2;
 
@@ -1712,20 +1720,20 @@ uint32_t helper_efdtsteq(uint64_t op1, uint64_t op2)
     return float64_eq_quiet(u1.d, u2.d, &env->vec_status) ? 4 : 0;
 }
 
-uint32_t helper_efdcmplt(uint64_t op1, uint64_t op2)
+uint32_t helper_efdcmplt(CPUPPCState *env, uint64_t op1, uint64_t op2)
 {
     /* XXX: TODO: test special values (NaN, infinites, ...) */
-    return helper_efdtstlt(op1, op2);
+    return helper_efdtstlt(env, op1, op2);
 }
 
-uint32_t helper_efdcmpgt(uint64_t op1, uint64_t op2)
+uint32_t helper_efdcmpgt(CPUPPCState *env, uint64_t op1, uint64_t op2)
 {
     /* XXX: TODO: test special values (NaN, infinites, ...) */
-    return helper_efdtstgt(op1, op2);
+    return helper_efdtstgt(env, op1, op2);
 }
 
-uint32_t helper_efdcmpeq(uint64_t op1, uint64_t op2)
+uint32_t helper_efdcmpeq(CPUPPCState *env, uint64_t op1, uint64_t op2)
 {
     /* XXX: TODO: test special values (NaN, infinites, ...) */
-    return helper_efdtsteq(op1, op2);
+    return helper_efdtsteq(env, op1, op2);
 }
diff --git a/target-ppc/helper.h b/target-ppc/helper.h
index a4562ae..0aba7f8 100644
--- a/target-ppc/helper.h
+++ b/target-ppc/helper.h
@@ -50,47 +50,47 @@ DEF_HELPER_FLAGS_1(cntlsw32, TCG_CALL_CONST | TCG_CALL_PURE, i32, i32)
 DEF_HELPER_FLAGS_1(cntlzw32, TCG_CALL_CONST | TCG_CALL_PURE, i32, i32)
 DEF_HELPER_FLAGS_2(brinc, TCG_CALL_CONST | TCG_CALL_PURE, tl, tl, tl)
 
-DEF_HELPER_0(float_check_status, void)
-DEF_HELPER_0(reset_fpstatus, void)
-DEF_HELPER_2(compute_fprf, i32, i64, i32)
-DEF_HELPER_2(store_fpscr, void, i64, i32)
-DEF_HELPER_1(fpscr_clrbit, void, i32)
-DEF_HELPER_1(fpscr_setbit, void, i32)
-DEF_HELPER_1(float64_to_float32, i32, i64)
-DEF_HELPER_1(float32_to_float64, i64, i32)
+DEF_HELPER_1(float_check_status, void, env)
+DEF_HELPER_1(reset_fpstatus, void, env)
+DEF_HELPER_3(compute_fprf, i32, env, i64, i32)
+DEF_HELPER_3(store_fpscr, void, env, i64, i32)
+DEF_HELPER_2(fpscr_clrbit, void, env, i32)
+DEF_HELPER_2(fpscr_setbit, void, env, i32)
+DEF_HELPER_2(float64_to_float32, i32, env, i64)
+DEF_HELPER_2(float32_to_float64, i64, env, i32)
 
-DEF_HELPER_3(fcmpo, void, i64, i64, i32)
-DEF_HELPER_3(fcmpu, void, i64, i64, i32)
+DEF_HELPER_4(fcmpo, void, env, i64, i64, i32)
+DEF_HELPER_4(fcmpu, void, env, i64, i64, i32)
 
-DEF_HELPER_1(fctiw, i64, i64)
-DEF_HELPER_1(fctiwz, i64, i64)
+DEF_HELPER_2(fctiw, i64, env, i64)
+DEF_HELPER_2(fctiwz, i64, env, i64)
 #if defined(TARGET_PPC64)
-DEF_HELPER_1(fcfid, i64, i64)
-DEF_HELPER_1(fctid, i64, i64)
-DEF_HELPER_1(fctidz, i64, i64)
+DEF_HELPER_2(fcfid, i64, env, i64)
+DEF_HELPER_2(fctid, i64, env, i64)
+DEF_HELPER_2(fctidz, i64, env, i64)
 #endif
-DEF_HELPER_1(frsp, i64, i64)
-DEF_HELPER_1(frin, i64, i64)
-DEF_HELPER_1(friz, i64, i64)
-DEF_HELPER_1(frip, i64, i64)
-DEF_HELPER_1(frim, i64, i64)
+DEF_HELPER_2(frsp, i64, env, i64)
+DEF_HELPER_2(frin, i64, env, i64)
+DEF_HELPER_2(friz, i64, env, i64)
+DEF_HELPER_2(frip, i64, env, i64)
+DEF_HELPER_2(frim, i64, env, i64)
 
-DEF_HELPER_2(fadd, i64, i64, i64)
-DEF_HELPER_2(fsub, i64, i64, i64)
-DEF_HELPER_2(fmul, i64, i64, i64)
-DEF_HELPER_2(fdiv, i64, i64, i64)
-DEF_HELPER_3(fmadd, i64, i64, i64, i64)
-DEF_HELPER_3(fmsub, i64, i64, i64, i64)
-DEF_HELPER_3(fnmadd, i64, i64, i64, i64)
-DEF_HELPER_3(fnmsub, i64, i64, i64, i64)
-DEF_HELPER_1(fabs, i64, i64)
-DEF_HELPER_1(fnabs, i64, i64)
-DEF_HELPER_1(fneg, i64, i64)
-DEF_HELPER_1(fsqrt, i64, i64)
-DEF_HELPER_1(fre, i64, i64)
-DEF_HELPER_1(fres, i64, i64)
-DEF_HELPER_1(frsqrte, i64, i64)
-DEF_HELPER_3(fsel, i64, i64, i64, i64)
+DEF_HELPER_3(fadd, i64, env, i64, i64)
+DEF_HELPER_3(fsub, i64, env, i64, i64)
+DEF_HELPER_3(fmul, i64, env, i64, i64)
+DEF_HELPER_3(fdiv, i64, env, i64, i64)
+DEF_HELPER_4(fmadd, i64, env, i64, i64, i64)
+DEF_HELPER_4(fmsub, i64, env, i64, i64, i64)
+DEF_HELPER_4(fnmadd, i64, env, i64, i64, i64)
+DEF_HELPER_4(fnmsub, i64, env, i64, i64, i64)
+DEF_HELPER_2(fabs, i64, env, i64)
+DEF_HELPER_2(fnabs, i64, env, i64)
+DEF_HELPER_2(fneg, i64, env, i64)
+DEF_HELPER_2(fsqrt, i64, env, i64)
+DEF_HELPER_2(fre, i64, env, i64)
+DEF_HELPER_2(fres, i64, env, i64)
+DEF_HELPER_2(frsqrte, i64, env, i64)
+DEF_HELPER_4(fsel, i64, env, i64, i64, i64)
 
 #define dh_alias_avr ptr
 #define dh_ctype_avr ppc_avr_t *
@@ -256,72 +256,72 @@ DEF_HELPER_3(vcfsx, void, avr, avr, i32)
 DEF_HELPER_3(vctuxs, void, avr, avr, i32)
 DEF_HELPER_3(vctsxs, void, avr, avr, i32)
 
-DEF_HELPER_1(efscfsi, i32, i32)
-DEF_HELPER_1(efscfui, i32, i32)
-DEF_HELPER_1(efscfuf, i32, i32)
-DEF_HELPER_1(efscfsf, i32, i32)
-DEF_HELPER_1(efsctsi, i32, i32)
-DEF_HELPER_1(efsctui, i32, i32)
-DEF_HELPER_1(efsctsiz, i32, i32)
-DEF_HELPER_1(efsctuiz, i32, i32)
-DEF_HELPER_1(efsctsf, i32, i32)
-DEF_HELPER_1(efsctuf, i32, i32)
-DEF_HELPER_1(evfscfsi, i64, i64)
-DEF_HELPER_1(evfscfui, i64, i64)
-DEF_HELPER_1(evfscfuf, i64, i64)
-DEF_HELPER_1(evfscfsf, i64, i64)
-DEF_HELPER_1(evfsctsi, i64, i64)
-DEF_HELPER_1(evfsctui, i64, i64)
-DEF_HELPER_1(evfsctsiz, i64, i64)
-DEF_HELPER_1(evfsctuiz, i64, i64)
-DEF_HELPER_1(evfsctsf, i64, i64)
-DEF_HELPER_1(evfsctuf, i64, i64)
-DEF_HELPER_2(efsadd, i32, i32, i32)
-DEF_HELPER_2(efssub, i32, i32, i32)
-DEF_HELPER_2(efsmul, i32, i32, i32)
-DEF_HELPER_2(efsdiv, i32, i32, i32)
-DEF_HELPER_2(evfsadd, i64, i64, i64)
-DEF_HELPER_2(evfssub, i64, i64, i64)
-DEF_HELPER_2(evfsmul, i64, i64, i64)
-DEF_HELPER_2(evfsdiv, i64, i64, i64)
-DEF_HELPER_2(efststlt, i32, i32, i32)
-DEF_HELPER_2(efststgt, i32, i32, i32)
-DEF_HELPER_2(efststeq, i32, i32, i32)
-DEF_HELPER_2(efscmplt, i32, i32, i32)
-DEF_HELPER_2(efscmpgt, i32, i32, i32)
-DEF_HELPER_2(efscmpeq, i32, i32, i32)
-DEF_HELPER_2(evfststlt, i32, i64, i64)
-DEF_HELPER_2(evfststgt, i32, i64, i64)
-DEF_HELPER_2(evfststeq, i32, i64, i64)
-DEF_HELPER_2(evfscmplt, i32, i64, i64)
-DEF_HELPER_2(evfscmpgt, i32, i64, i64)
-DEF_HELPER_2(evfscmpeq, i32, i64, i64)
-DEF_HELPER_1(efdcfsi, i64, i32)
-DEF_HELPER_1(efdcfsid, i64, i64)
-DEF_HELPER_1(efdcfui, i64, i32)
-DEF_HELPER_1(efdcfuid, i64, i64)
-DEF_HELPER_1(efdctsi, i32, i64)
-DEF_HELPER_1(efdctui, i32, i64)
-DEF_HELPER_1(efdctsiz, i32, i64)
-DEF_HELPER_1(efdctsidz, i64, i64)
-DEF_HELPER_1(efdctuiz, i32, i64)
-DEF_HELPER_1(efdctuidz, i64, i64)
-DEF_HELPER_1(efdcfsf, i64, i32)
-DEF_HELPER_1(efdcfuf, i64, i32)
-DEF_HELPER_1(efdctsf, i32, i64)
-DEF_HELPER_1(efdctuf, i32, i64)
-DEF_HELPER_1(efscfd, i32, i64)
-DEF_HELPER_1(efdcfs, i64, i32)
-DEF_HELPER_2(efdadd, i64, i64, i64)
-DEF_HELPER_2(efdsub, i64, i64, i64)
-DEF_HELPER_2(efdmul, i64, i64, i64)
-DEF_HELPER_2(efddiv, i64, i64, i64)
-DEF_HELPER_2(efdtstlt, i32, i64, i64)
-DEF_HELPER_2(efdtstgt, i32, i64, i64)
-DEF_HELPER_2(efdtsteq, i32, i64, i64)
-DEF_HELPER_2(efdcmplt, i32, i64, i64)
-DEF_HELPER_2(efdcmpgt, i32, i64, i64)
-DEF_HELPER_2(efdcmpeq, i32, i64, i64)
+DEF_HELPER_2(efscfsi, i32, env, i32)
+DEF_HELPER_2(efscfui, i32, env, i32)
+DEF_HELPER_2(efscfuf, i32, env, i32)
+DEF_HELPER_2(efscfsf, i32, env, i32)
+DEF_HELPER_2(efsctsi, i32, env, i32)
+DEF_HELPER_2(efsctui, i32, env, i32)
+DEF_HELPER_2(efsctsiz, i32, env, i32)
+DEF_HELPER_2(efsctuiz, i32, env, i32)
+DEF_HELPER_2(efsctsf, i32, env, i32)
+DEF_HELPER_2(efsctuf, i32, env, i32)
+DEF_HELPER_2(evfscfsi, i64, env, i64)
+DEF_HELPER_2(evfscfui, i64, env, i64)
+DEF_HELPER_2(evfscfuf, i64, env, i64)
+DEF_HELPER_2(evfscfsf, i64, env, i64)
+DEF_HELPER_2(evfsctsi, i64, env, i64)
+DEF_HELPER_2(evfsctui, i64, env, i64)
+DEF_HELPER_2(evfsctsiz, i64, env, i64)
+DEF_HELPER_2(evfsctuiz, i64, env, i64)
+DEF_HELPER_2(evfsctsf, i64, env, i64)
+DEF_HELPER_2(evfsctuf, i64, env, i64)
+DEF_HELPER_3(efsadd, i32, env, i32, i32)
+DEF_HELPER_3(efssub, i32, env, i32, i32)
+DEF_HELPER_3(efsmul, i32, env, i32, i32)
+DEF_HELPER_3(efsdiv, i32, env, i32, i32)
+DEF_HELPER_3(evfsadd, i64, env, i64, i64)
+DEF_HELPER_3(evfssub, i64, env, i64, i64)
+DEF_HELPER_3(evfsmul, i64, env, i64, i64)
+DEF_HELPER_3(evfsdiv, i64, env, i64, i64)
+DEF_HELPER_3(efststlt, i32, env, i32, i32)
+DEF_HELPER_3(efststgt, i32, env, i32, i32)
+DEF_HELPER_3(efststeq, i32, env, i32, i32)
+DEF_HELPER_3(efscmplt, i32, env, i32, i32)
+DEF_HELPER_3(efscmpgt, i32, env, i32, i32)
+DEF_HELPER_3(efscmpeq, i32, env, i32, i32)
+DEF_HELPER_3(evfststlt, i32, env, i64, i64)
+DEF_HELPER_3(evfststgt, i32, env, i64, i64)
+DEF_HELPER_3(evfststeq, i32, env, i64, i64)
+DEF_HELPER_3(evfscmplt, i32, env, i64, i64)
+DEF_HELPER_3(evfscmpgt, i32, env, i64, i64)
+DEF_HELPER_3(evfscmpeq, i32, env, i64, i64)
+DEF_HELPER_2(efdcfsi, i64, env, i32)
+DEF_HELPER_2(efdcfsid, i64, env, i64)
+DEF_HELPER_2(efdcfui, i64, env, i32)
+DEF_HELPER_2(efdcfuid, i64, env, i64)
+DEF_HELPER_2(efdctsi, i32, env, i64)
+DEF_HELPER_2(efdctui, i32, env, i64)
+DEF_HELPER_2(efdctsiz, i32, env, i64)
+DEF_HELPER_2(efdctsidz, i64, env, i64)
+DEF_HELPER_2(efdctuiz, i32, env, i64)
+DEF_HELPER_2(efdctuidz, i64, env, i64)
+DEF_HELPER_2(efdcfsf, i64, env, i32)
+DEF_HELPER_2(efdcfuf, i64, env, i32)
+DEF_HELPER_2(efdctsf, i32, env, i64)
+DEF_HELPER_2(efdctuf, i32, env, i64)
+DEF_HELPER_2(efscfd, i32, env, i64)
+DEF_HELPER_2(efdcfs, i64, env, i32)
+DEF_HELPER_3(efdadd, i64, env, i64, i64)
+DEF_HELPER_3(efdsub, i64, env, i64, i64)
+DEF_HELPER_3(efdmul, i64, env, i64, i64)
+DEF_HELPER_3(efddiv, i64, env, i64, i64)
+DEF_HELPER_3(efdtstlt, i32, env, i64, i64)
+DEF_HELPER_3(efdtstgt, i32, env, i64, i64)
+DEF_HELPER_3(efdtsteq, i32, env, i64, i64)
+DEF_HELPER_3(efdcmplt, i32, env, i64, i64)
+DEF_HELPER_3(efdcmpgt, i32, env, i64, i64)
+DEF_HELPER_3(efdcmpeq, i32, env, i64, i64)
 
 #if !defined(CONFIG_USER_ONLY)
 DEF_HELPER_1(4xx_tlbre_hi, tl, tl)
diff --git a/target-ppc/translate.c b/target-ppc/translate.c
index 02626ae..c8b7982 100644
--- a/target-ppc/translate.c
+++ b/target-ppc/translate.c
@@ -219,7 +219,7 @@ struct opc_handler_t {
 
 static inline void gen_reset_fpstatus(void)
 {
-    gen_helper_reset_fpstatus();
+    gen_helper_reset_fpstatus(cpu_env);
 }
 
 static inline void gen_compute_fprf(TCGv_i64 arg, int set_fprf, int set_rc)
@@ -229,15 +229,15 @@ static inline void gen_compute_fprf(TCGv_i64 arg, int set_fprf, int set_rc)
     if (set_fprf != 0) {
         /* This case might be optimized later */
         tcg_gen_movi_i32(t0, 1);
-        gen_helper_compute_fprf(t0, arg, t0);
+        gen_helper_compute_fprf(t0, cpu_env, arg, t0);
         if (unlikely(set_rc)) {
             tcg_gen_mov_i32(cpu_crf[1], t0);
         }
-        gen_helper_float_check_status();
+        gen_helper_float_check_status(cpu_env);
     } else if (unlikely(set_rc)) {
         /* We always need to compute fpcc */
         tcg_gen_movi_i32(t0, 0);
-        gen_helper_compute_fprf(t0, arg, t0);
+        gen_helper_compute_fprf(t0, cpu_env, arg, t0);
         tcg_gen_mov_i32(cpu_crf[1], t0);
     }
 
@@ -2027,10 +2027,12 @@ static void gen_f##name(DisasContext *ctx)                                    \
     /* NIP cannot be restored if the memory exception comes from an helper */ \
     gen_update_nip(ctx, ctx->nip - 4);                                        \
     gen_reset_fpstatus();                                                     \
-    gen_helper_f##op(cpu_fpr[rD(ctx->opcode)], cpu_fpr[rA(ctx->opcode)],      \
+    gen_helper_f##op(cpu_fpr[rD(ctx->opcode)], cpu_env,                       \
+                     cpu_fpr[rA(ctx->opcode)],                                \
                      cpu_fpr[rC(ctx->opcode)], cpu_fpr[rB(ctx->opcode)]);     \
     if (isfloat) {                                                            \
-        gen_helper_frsp(cpu_fpr[rD(ctx->opcode)], cpu_fpr[rD(ctx->opcode)]);  \
+        gen_helper_frsp(cpu_fpr[rD(ctx->opcode)], cpu_env,                    \
+                        cpu_fpr[rD(ctx->opcode)]);                            \
     }                                                                         \
     gen_compute_fprf(cpu_fpr[rD(ctx->opcode)], set_fprf,                      \
                      Rc(ctx->opcode) != 0);                                   \
@@ -2050,10 +2052,12 @@ static void gen_f##name(DisasContext *ctx)                                    \
     /* NIP cannot be restored if the memory exception comes from an helper */ \
     gen_update_nip(ctx, ctx->nip - 4);                                        \
     gen_reset_fpstatus();                                                     \
-    gen_helper_f##op(cpu_fpr[rD(ctx->opcode)], cpu_fpr[rA(ctx->opcode)],      \
+    gen_helper_f##op(cpu_fpr[rD(ctx->opcode)], cpu_env,                       \
+                     cpu_fpr[rA(ctx->opcode)],                                \
                      cpu_fpr[rB(ctx->opcode)]);                               \
     if (isfloat) {                                                            \
-        gen_helper_frsp(cpu_fpr[rD(ctx->opcode)], cpu_fpr[rD(ctx->opcode)]);  \
+        gen_helper_frsp(cpu_fpr[rD(ctx->opcode)], cpu_env,                    \
+                        cpu_fpr[rD(ctx->opcode)]);                            \
     }                                                                         \
     gen_compute_fprf(cpu_fpr[rD(ctx->opcode)],                                \
                      set_fprf, Rc(ctx->opcode) != 0);                         \
@@ -2072,10 +2076,12 @@ static void gen_f##name(DisasContext *ctx)                                    \
     /* NIP cannot be restored if the memory exception comes from an helper */ \
     gen_update_nip(ctx, ctx->nip - 4);                                        \
     gen_reset_fpstatus();                                                     \
-    gen_helper_f##op(cpu_fpr[rD(ctx->opcode)], cpu_fpr[rA(ctx->opcode)],      \
-                       cpu_fpr[rC(ctx->opcode)]);                             \
+    gen_helper_f##op(cpu_fpr[rD(ctx->opcode)], cpu_env,                       \
+                     cpu_fpr[rA(ctx->opcode)],                                \
+                     cpu_fpr[rC(ctx->opcode)]);                               \
     if (isfloat) {                                                            \
-        gen_helper_frsp(cpu_fpr[rD(ctx->opcode)], cpu_fpr[rD(ctx->opcode)]);  \
+        gen_helper_frsp(cpu_fpr[rD(ctx->opcode)], cpu_env,                    \
+                        cpu_fpr[rD(ctx->opcode)]);                            \
     }                                                                         \
     gen_compute_fprf(cpu_fpr[rD(ctx->opcode)],                                \
                      set_fprf, Rc(ctx->opcode) != 0);                         \
@@ -2094,7 +2100,8 @@ static void gen_f##name(DisasContext *ctx)                                    \
     /* NIP cannot be restored if the memory exception comes from an helper */ \
     gen_update_nip(ctx, ctx->nip - 4);                                        \
     gen_reset_fpstatus();                                                     \
-    gen_helper_f##name(cpu_fpr[rD(ctx->opcode)], cpu_fpr[rB(ctx->opcode)]);   \
+    gen_helper_f##name(cpu_fpr[rD(ctx->opcode)], cpu_env,                     \
+                       cpu_fpr[rB(ctx->opcode)]);                             \
     gen_compute_fprf(cpu_fpr[rD(ctx->opcode)],                                \
                      set_fprf, Rc(ctx->opcode) != 0);                         \
 }
@@ -2109,7 +2116,8 @@ static void gen_f##name(DisasContext *ctx)                                    \
     /* NIP cannot be restored if the memory exception comes from an helper */ \
     gen_update_nip(ctx, ctx->nip - 4);                                        \
     gen_reset_fpstatus();                                                     \
-    gen_helper_f##name(cpu_fpr[rD(ctx->opcode)], cpu_fpr[rB(ctx->opcode)]);   \
+    gen_helper_f##name(cpu_fpr[rD(ctx->opcode)], cpu_env,                     \
+                       cpu_fpr[rB(ctx->opcode)]);                             \
     gen_compute_fprf(cpu_fpr[rD(ctx->opcode)],                                \
                      set_fprf, Rc(ctx->opcode) != 0);                         \
 }
@@ -2140,8 +2148,10 @@ static void gen_frsqrtes(DisasContext *ctx)
     /* NIP cannot be restored if the memory exception comes from an helper */
     gen_update_nip(ctx, ctx->nip - 4);
     gen_reset_fpstatus();
-    gen_helper_frsqrte(cpu_fpr[rD(ctx->opcode)], cpu_fpr[rB(ctx->opcode)]);
-    gen_helper_frsp(cpu_fpr[rD(ctx->opcode)], cpu_fpr[rD(ctx->opcode)]);
+    gen_helper_frsqrte(cpu_fpr[rD(ctx->opcode)], cpu_env,
+                       cpu_fpr[rB(ctx->opcode)]);
+    gen_helper_frsp(cpu_fpr[rD(ctx->opcode)], cpu_env,
+                    cpu_fpr[rD(ctx->opcode)]);
     gen_compute_fprf(cpu_fpr[rD(ctx->opcode)], 1, Rc(ctx->opcode) != 0);
 }
 
@@ -2161,7 +2171,8 @@ static void gen_fsqrt(DisasContext *ctx)
     /* NIP cannot be restored if the memory exception comes from an helper */
     gen_update_nip(ctx, ctx->nip - 4);
     gen_reset_fpstatus();
-    gen_helper_fsqrt(cpu_fpr[rD(ctx->opcode)], cpu_fpr[rB(ctx->opcode)]);
+    gen_helper_fsqrt(cpu_fpr[rD(ctx->opcode)], cpu_env,
+                     cpu_fpr[rB(ctx->opcode)]);
     gen_compute_fprf(cpu_fpr[rD(ctx->opcode)], 1, Rc(ctx->opcode) != 0);
 }
 
@@ -2174,8 +2185,10 @@ static void gen_fsqrts(DisasContext *ctx)
     /* NIP cannot be restored if the memory exception comes from an helper */
     gen_update_nip(ctx, ctx->nip - 4);
     gen_reset_fpstatus();
-    gen_helper_fsqrt(cpu_fpr[rD(ctx->opcode)], cpu_fpr[rB(ctx->opcode)]);
-    gen_helper_frsp(cpu_fpr[rD(ctx->opcode)], cpu_fpr[rD(ctx->opcode)]);
+    gen_helper_fsqrt(cpu_fpr[rD(ctx->opcode)], cpu_env,
+                     cpu_fpr[rB(ctx->opcode)]);
+    gen_helper_frsp(cpu_fpr[rD(ctx->opcode)], cpu_env,
+                    cpu_fpr[rD(ctx->opcode)]);
     gen_compute_fprf(cpu_fpr[rD(ctx->opcode)], 1, Rc(ctx->opcode) != 0);
 }
 
@@ -2228,9 +2241,10 @@ static void gen_fcmpo(DisasContext *ctx)
     gen_update_nip(ctx, ctx->nip - 4);
     gen_reset_fpstatus();
     crf = tcg_const_i32(crfD(ctx->opcode));
-    gen_helper_fcmpo(cpu_fpr[rA(ctx->opcode)], cpu_fpr[rB(ctx->opcode)], crf);
+    gen_helper_fcmpo(cpu_env, cpu_fpr[rA(ctx->opcode)],
+                     cpu_fpr[rB(ctx->opcode)], crf);
     tcg_temp_free_i32(crf);
-    gen_helper_float_check_status();
+    gen_helper_float_check_status(cpu_env);
 }
 
 /* fcmpu */
@@ -2245,9 +2259,10 @@ static void gen_fcmpu(DisasContext *ctx)
     gen_update_nip(ctx, ctx->nip - 4);
     gen_reset_fpstatus();
     crf = tcg_const_i32(crfD(ctx->opcode));
-    gen_helper_fcmpu(cpu_fpr[rA(ctx->opcode)], cpu_fpr[rB(ctx->opcode)], crf);
+    gen_helper_fcmpu(cpu_env, cpu_fpr[rA(ctx->opcode)],
+                     cpu_fpr[rB(ctx->opcode)], crf);
     tcg_temp_free_i32(crf);
-    gen_helper_float_check_status();
+    gen_helper_float_check_status(cpu_env);
 }
 
 /***                         Floating-point move                           ***/
@@ -2319,7 +2334,7 @@ static void gen_mtfsb0(DisasContext *ctx)
         /* NIP cannot be restored if the memory exception comes from an helper */
         gen_update_nip(ctx, ctx->nip - 4);
         t0 = tcg_const_i32(crb);
-        gen_helper_fpscr_clrbit(t0);
+        gen_helper_fpscr_clrbit(cpu_env, t0);
         tcg_temp_free_i32(t0);
     }
     if (unlikely(Rc(ctx->opcode) != 0)) {
@@ -2344,14 +2359,14 @@ static void gen_mtfsb1(DisasContext *ctx)
         /* NIP cannot be restored if the memory exception comes from an helper */
         gen_update_nip(ctx, ctx->nip - 4);
         t0 = tcg_const_i32(crb);
-        gen_helper_fpscr_setbit(t0);
+        gen_helper_fpscr_setbit(cpu_env, t0);
         tcg_temp_free_i32(t0);
     }
     if (unlikely(Rc(ctx->opcode) != 0)) {
         tcg_gen_shri_i32(cpu_crf[1], cpu_fpscr, FPSCR_OX);
     }
     /* We can raise a differed exception */
-    gen_helper_float_check_status();
+    gen_helper_float_check_status(cpu_env);
 }
 
 /* mtfsf */
@@ -2371,13 +2386,13 @@ static void gen_mtfsf(DisasContext *ctx)
         t0 = tcg_const_i32(0xff);
     else
         t0 = tcg_const_i32(FM(ctx->opcode));
-    gen_helper_store_fpscr(cpu_fpr[rB(ctx->opcode)], t0);
+    gen_helper_store_fpscr(cpu_env, cpu_fpr[rB(ctx->opcode)], t0);
     tcg_temp_free_i32(t0);
     if (unlikely(Rc(ctx->opcode) != 0)) {
         tcg_gen_shri_i32(cpu_crf[1], cpu_fpscr, FPSCR_OX);
     }
     /* We can raise a differed exception */
-    gen_helper_float_check_status();
+    gen_helper_float_check_status(cpu_env);
 }
 
 /* mtfsfi */
@@ -2398,14 +2413,14 @@ static void gen_mtfsfi(DisasContext *ctx)
     gen_reset_fpstatus();
     t0 = tcg_const_i64(FPIMM(ctx->opcode) << (4 * sh));
     t1 = tcg_const_i32(1 << sh);
-    gen_helper_store_fpscr(t0, t1);
+    gen_helper_store_fpscr(cpu_env, t0, t1);
     tcg_temp_free_i64(t0);
     tcg_temp_free_i32(t1);
     if (unlikely(Rc(ctx->opcode) != 0)) {
         tcg_gen_shri_i32(cpu_crf[1], cpu_fpscr, FPSCR_OX);
     }
     /* We can raise a differed exception */
-    gen_helper_float_check_status();
+    gen_helper_float_check_status(cpu_env);
 }
 
 /***                           Addressing modes                            ***/
@@ -3303,7 +3318,7 @@ static inline void gen_qemu_ld32fs(DisasContext *ctx, TCGv_i64 arg1, TCGv arg2)
     gen_qemu_ld32u(ctx, t0, arg2);
     tcg_gen_trunc_tl_i32(t1, t0);
     tcg_temp_free(t0);
-    gen_helper_float32_to_float64(arg1, t1);
+    gen_helper_float32_to_float64(arg1, cpu_env, t1);
     tcg_temp_free_i32(t1);
 }
 
@@ -3393,7 +3408,7 @@ static inline void gen_qemu_st32fs(DisasContext *ctx, TCGv_i64 arg1, TCGv arg2)
 {
     TCGv_i32 t0 = tcg_temp_new_i32();
     TCGv t1 = tcg_temp_new();
-    gen_helper_float64_to_float32(t0, arg1);
+    gen_helper_float64_to_float32(t0, cpu_env, arg1);
     tcg_gen_extu_i32_tl(t1, t0);
     tcg_temp_free_i32(t0);
     gen_qemu_st32(ctx, t1, arg2);
@@ -8010,7 +8025,7 @@ static inline void gen_##name(DisasContext *ctx)                              \
     TCGv t1;                                                                  \
     t0 = tcg_temp_new_i32();                                                  \
     tcg_gen_trunc_tl_i32(t0, cpu_gpr[rB(ctx->opcode)]);                       \
-    gen_helper_##name(t0, t0);                                                \
+    gen_helper_##name(t0, cpu_env, t0);                                       \
     t1 = tcg_temp_new();                                                      \
     tcg_gen_extu_i32_tl(t1, t0);                                              \
     tcg_temp_free_i32(t0);                                                    \
@@ -8025,7 +8040,7 @@ static inline void gen_##name(DisasContext *ctx)                              \
     TCGv_i32 t0;                                                              \
     TCGv t1;                                                                  \
     t0 = tcg_temp_new_i32();                                                  \
-    gen_helper_##name(t0, cpu_gpr[rB(ctx->opcode)]);                          \
+    gen_helper_##name(t0, cpu_env, cpu_gpr[rB(ctx->opcode)]);                 \
     t1 = tcg_temp_new();                                                      \
     tcg_gen_extu_i32_tl(t1, t0);                                              \
     tcg_temp_free_i32(t0);                                                    \
@@ -8039,13 +8054,14 @@ static inline void gen_##name(DisasContext *ctx)                              \
 {                                                                             \
     TCGv_i32 t0 = tcg_temp_new_i32();                                         \
     tcg_gen_trunc_tl_i32(t0, cpu_gpr[rB(ctx->opcode)]);                       \
-    gen_helper_##name(cpu_gpr[rD(ctx->opcode)], t0);                          \
+    gen_helper_##name(cpu_gpr[rD(ctx->opcode)], cpu_env, t0);                 \
     tcg_temp_free_i32(t0);                                                    \
 }
 #define GEN_SPEFPUOP_CONV_64_64(name)                                         \
 static inline void gen_##name(DisasContext *ctx)                              \
 {                                                                             \
-    gen_helper_##name(cpu_gpr[rD(ctx->opcode)], cpu_gpr[rB(ctx->opcode)]);    \
+    gen_helper_##name(cpu_gpr[rD(ctx->opcode)], cpu_env,                      \
+                      cpu_gpr[rB(ctx->opcode)]);                              \
 }
 #define GEN_SPEFPUOP_ARITH2_32_32(name)                                       \
 static inline void gen_##name(DisasContext *ctx)                              \
@@ -8060,7 +8076,7 @@ static inline void gen_##name(DisasContext *ctx)                              \
     t1 = tcg_temp_new_i32();                                                  \
     tcg_gen_trunc_tl_i32(t0, cpu_gpr[rA(ctx->opcode)]);                       \
     tcg_gen_trunc_tl_i32(t1, cpu_gpr[rB(ctx->opcode)]);                       \
-    gen_helper_##name(t0, t0, t1);                                            \
+    gen_helper_##name(t0, cpu_env, t0, t1);                                   \
     tcg_temp_free_i32(t1);                                                    \
     t2 = tcg_temp_new();                                                      \
     tcg_gen_extu_i32_tl(t2, t0);                                              \
@@ -8077,8 +8093,8 @@ static inline void gen_##name(DisasContext *ctx)                              \
         gen_exception(ctx, POWERPC_EXCP_SPEU);                                \
         return;                                                               \
     }                                                                         \
-    gen_helper_##name(cpu_gpr[rD(ctx->opcode)], cpu_gpr[rA(ctx->opcode)],     \
-                      cpu_gpr[rB(ctx->opcode)]);                              \
+    gen_helper_##name(cpu_gpr[rD(ctx->opcode)], cpu_env,                      \
+                      cpu_gpr[rA(ctx->opcode)], cpu_gpr[rB(ctx->opcode)]);    \
 }
 #define GEN_SPEFPUOP_COMP_32(name)                                            \
 static inline void gen_##name(DisasContext *ctx)                              \
@@ -8092,7 +8108,7 @@ static inline void gen_##name(DisasContext *ctx)                              \
     t1 = tcg_temp_new_i32();                                                  \
     tcg_gen_trunc_tl_i32(t0, cpu_gpr[rA(ctx->opcode)]);                       \
     tcg_gen_trunc_tl_i32(t1, cpu_gpr[rB(ctx->opcode)]);                       \
-    gen_helper_##name(cpu_crf[crfD(ctx->opcode)], t0, t1);                    \
+    gen_helper_##name(cpu_crf[crfD(ctx->opcode)], cpu_env, t0, t1);           \
     tcg_temp_free_i32(t0);                                                    \
     tcg_temp_free_i32(t1);                                                    \
 }
@@ -8103,28 +8119,29 @@ static inline void gen_##name(DisasContext *ctx)                              \
         gen_exception(ctx, POWERPC_EXCP_SPEU);                                \
         return;                                                               \
     }                                                                         \
-    gen_helper_##name(cpu_crf[crfD(ctx->opcode)],                             \
+    gen_helper_##name(cpu_crf[crfD(ctx->opcode)], cpu_env,                    \
                       cpu_gpr[rA(ctx->opcode)], cpu_gpr[rB(ctx->opcode)]);    \
 }
 #else
 #define GEN_SPEFPUOP_CONV_32_32(name)                                         \
 static inline void gen_##name(DisasContext *ctx)                              \
 {                                                                             \
-    gen_helper_##name(cpu_gpr[rD(ctx->opcode)], cpu_gpr[rB(ctx->opcode)]);    \
+    gen_helper_##name(cpu_gpr[rD(ctx->opcode)], cpu_env,                      \
+                      cpu_gpr[rB(ctx->opcode)]);                              \
 }
 #define GEN_SPEFPUOP_CONV_32_64(name)                                         \
 static inline void gen_##name(DisasContext *ctx)                              \
 {                                                                             \
     TCGv_i64 t0 = tcg_temp_new_i64();                                         \
     gen_load_gpr64(t0, rB(ctx->opcode));                                      \
-    gen_helper_##name(cpu_gpr[rD(ctx->opcode)], t0);                          \
+    gen_helper_##name(cpu_gpr[rD(ctx->opcode)], cpu_env, t0);                 \
     tcg_temp_free_i64(t0);                                                    \
 }
 #define GEN_SPEFPUOP_CONV_64_32(name)                                         \
 static inline void gen_##name(DisasContext *ctx)                              \
 {                                                                             \
     TCGv_i64 t0 = tcg_temp_new_i64();                                         \
-    gen_helper_##name(t0, cpu_gpr[rB(ctx->opcode)]);                          \
+    gen_helper_##name(t0, cpu_env, cpu_gpr[rB(ctx->opcode)]);                 \
     gen_store_gpr64(rD(ctx->opcode), t0);                                     \
     tcg_temp_free_i64(t0);                                                    \
 }
@@ -8133,7 +8150,7 @@ static inline void gen_##name(DisasContext *ctx)                              \
 {                                                                             \
     TCGv_i64 t0 = tcg_temp_new_i64();                                         \
     gen_load_gpr64(t0, rB(ctx->opcode));                                      \
-    gen_helper_##name(t0, t0);                                                \
+    gen_helper_##name(t0, cpu_env, t0);                                       \
     gen_store_gpr64(rD(ctx->opcode), t0);                                     \
     tcg_temp_free_i64(t0);                                                    \
 }
@@ -8144,7 +8161,7 @@ static inline void gen_##name(DisasContext *ctx)                              \
         gen_exception(ctx, POWERPC_EXCP_SPEU);                                \
         return;                                                               \
     }                                                                         \
-    gen_helper_##name(cpu_gpr[rD(ctx->opcode)],                               \
+    gen_helper_##name(cpu_gpr[rD(ctx->opcode)], cpu_env,                      \
                       cpu_gpr[rA(ctx->opcode)], cpu_gpr[rB(ctx->opcode)]);    \
 }
 #define GEN_SPEFPUOP_ARITH2_64_64(name)                                       \
@@ -8159,7 +8176,7 @@ static inline void gen_##name(DisasContext *ctx)                              \
     t1 = tcg_temp_new_i64();                                                  \
     gen_load_gpr64(t0, rA(ctx->opcode));                                      \
     gen_load_gpr64(t1, rB(ctx->opcode));                                      \
-    gen_helper_##name(t0, t0, t1);                                            \
+    gen_helper_##name(t0, cpu_env, t0, t1);                                   \
     gen_store_gpr64(rD(ctx->opcode), t0);                                     \
     tcg_temp_free_i64(t0);                                                    \
     tcg_temp_free_i64(t1);                                                    \
@@ -8171,7 +8188,7 @@ static inline void gen_##name(DisasContext *ctx)                              \
         gen_exception(ctx, POWERPC_EXCP_SPEU);                                \
         return;                                                               \
     }                                                                         \
-    gen_helper_##name(cpu_crf[crfD(ctx->opcode)],                             \
+    gen_helper_##name(cpu_crf[crfD(ctx->opcode)], cpu_env,                    \
                       cpu_gpr[rA(ctx->opcode)], cpu_gpr[rB(ctx->opcode)]);    \
 }
 #define GEN_SPEFPUOP_COMP_64(name)                                            \
@@ -8186,7 +8203,7 @@ static inline void gen_##name(DisasContext *ctx)                              \
     t1 = tcg_temp_new_i64();                                                  \
     gen_load_gpr64(t0, rA(ctx->opcode));                                      \
     gen_load_gpr64(t1, rB(ctx->opcode));                                      \
-    gen_helper_##name(cpu_crf[crfD(ctx->opcode)], t0, t1);                    \
+    gen_helper_##name(cpu_crf[crfD(ctx->opcode)], cpu_env, t0, t1);           \
     tcg_temp_free_i64(t0);                                                    \
     tcg_temp_free_i64(t1);                                                    \
 }
commit bd23cd45ea533580da410eed9c31692abf7584e6
Author: Blue Swirl <blauwirbel at gmail.com>
Date:   Wed May 30 04:23:26 2012 +0000

    ppc: Split FPU and SPE ops
    
    Move FPU and SPE helpers from op_helper.c to fpu_helper.c.
    
    Signed-off-by: Blue Swirl <blauwirbel at gmail.com>
    Signed-off-by: Alexander Graf <agraf at suse.de>
    Signed-off-by: Andreas Färber <afaerber at suse.de>
    Signed-off-by: Alexander Graf <agraf at suse.de>

diff --git a/target-ppc/Makefile.objs b/target-ppc/Makefile.objs
index a02b7bc..dde916c 100644
--- a/target-ppc/Makefile.objs
+++ b/target-ppc/Makefile.objs
@@ -3,5 +3,7 @@ obj-$(CONFIG_SOFTMMU) += machine.o
 obj-$(CONFIG_KVM) += kvm.o kvm_ppc.o
 obj-y += op_helper.o helper.o
 obj-y += excp_helper.o
+obj-y += fpu_helper.o
 
+$(obj)/fpu_helper.o: QEMU_CFLAGS += $(HELPER_CFLAGS)
 $(obj)/op_helper.o: QEMU_CFLAGS += $(HELPER_CFLAGS)
diff --git a/target-ppc/fpu_helper.c b/target-ppc/fpu_helper.c
new file mode 100644
index 0000000..be965d1
--- /dev/null
+++ b/target-ppc/fpu_helper.c
@@ -0,0 +1,1731 @@
+/*
+ *  PowerPC floating point and SPE emulation helpers for QEMU.
+ *
+ *  Copyright (c) 2003-2007 Jocelyn Mayer
+ *
+ * This library is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Lesser General Public
+ * License as published by the Free Software Foundation; either
+ * version 2 of the License, or (at your option) any later version.
+ *
+ * This library is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
+ * Lesser General Public License for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public
+ * License along with this library; if not, see <http://www.gnu.org/licenses/>.
+ */
+#include "cpu.h"
+#include "dyngen-exec.h"
+#include "helper.h"
+
+/*****************************************************************************/
+/* Floating point operations helpers */
+uint64_t helper_float32_to_float64(uint32_t arg)
+{
+    CPU_FloatU f;
+    CPU_DoubleU d;
+
+    f.l = arg;
+    d.d = float32_to_float64(f.f, &env->fp_status);
+    return d.ll;
+}
+
+uint32_t helper_float64_to_float32(uint64_t arg)
+{
+    CPU_FloatU f;
+    CPU_DoubleU d;
+
+    d.ll = arg;
+    f.f = float64_to_float32(d.d, &env->fp_status);
+    return f.l;
+}
+
+static inline int isden(float64 d)
+{
+    CPU_DoubleU u;
+
+    u.d = d;
+
+    return ((u.ll >> 52) & 0x7FF) == 0;
+}
+
+uint32_t helper_compute_fprf(uint64_t arg, uint32_t set_fprf)
+{
+    CPU_DoubleU farg;
+    int isneg;
+    int ret;
+
+    farg.ll = arg;
+    isneg = float64_is_neg(farg.d);
+    if (unlikely(float64_is_any_nan(farg.d))) {
+        if (float64_is_signaling_nan(farg.d)) {
+            /* Signaling NaN: flags are undefined */
+            ret = 0x00;
+        } else {
+            /* Quiet NaN */
+            ret = 0x11;
+        }
+    } else if (unlikely(float64_is_infinity(farg.d))) {
+        /* +/- infinity */
+        if (isneg) {
+            ret = 0x09;
+        } else {
+            ret = 0x05;
+        }
+    } else {
+        if (float64_is_zero(farg.d)) {
+            /* +/- zero */
+            if (isneg) {
+                ret = 0x12;
+            } else {
+                ret = 0x02;
+            }
+        } else {
+            if (isden(farg.d)) {
+                /* Denormalized numbers */
+                ret = 0x10;
+            } else {
+                /* Normalized numbers */
+                ret = 0x00;
+            }
+            if (isneg) {
+                ret |= 0x08;
+            } else {
+                ret |= 0x04;
+            }
+        }
+    }
+    if (set_fprf) {
+        /* We update FPSCR_FPRF */
+        env->fpscr &= ~(0x1F << FPSCR_FPRF);
+        env->fpscr |= ret << FPSCR_FPRF;
+    }
+    /* We just need fpcc to update Rc1 */
+    return ret & 0xF;
+}
+
+/* Floating-point invalid operations exception */
+static inline uint64_t fload_invalid_op_excp(int op)
+{
+    uint64_t ret = 0;
+    int ve;
+
+    ve = fpscr_ve;
+    switch (op) {
+    case POWERPC_EXCP_FP_VXSNAN:
+        env->fpscr |= 1 << FPSCR_VXSNAN;
+        break;
+    case POWERPC_EXCP_FP_VXSOFT:
+        env->fpscr |= 1 << FPSCR_VXSOFT;
+        break;
+    case POWERPC_EXCP_FP_VXISI:
+        /* Magnitude subtraction of infinities */
+        env->fpscr |= 1 << FPSCR_VXISI;
+        goto update_arith;
+    case POWERPC_EXCP_FP_VXIDI:
+        /* Division of infinity by infinity */
+        env->fpscr |= 1 << FPSCR_VXIDI;
+        goto update_arith;
+    case POWERPC_EXCP_FP_VXZDZ:
+        /* Division of zero by zero */
+        env->fpscr |= 1 << FPSCR_VXZDZ;
+        goto update_arith;
+    case POWERPC_EXCP_FP_VXIMZ:
+        /* Multiplication of zero by infinity */
+        env->fpscr |= 1 << FPSCR_VXIMZ;
+        goto update_arith;
+    case POWERPC_EXCP_FP_VXVC:
+        /* Ordered comparison of NaN */
+        env->fpscr |= 1 << FPSCR_VXVC;
+        env->fpscr &= ~(0xF << FPSCR_FPCC);
+        env->fpscr |= 0x11 << FPSCR_FPCC;
+        /* We must update the target FPR before raising the exception */
+        if (ve != 0) {
+            env->exception_index = POWERPC_EXCP_PROGRAM;
+            env->error_code = POWERPC_EXCP_FP | POWERPC_EXCP_FP_VXVC;
+            /* Update the floating-point enabled exception summary */
+            env->fpscr |= 1 << FPSCR_FEX;
+            /* Exception is differed */
+            ve = 0;
+        }
+        break;
+    case POWERPC_EXCP_FP_VXSQRT:
+        /* Square root of a negative number */
+        env->fpscr |= 1 << FPSCR_VXSQRT;
+    update_arith:
+        env->fpscr &= ~((1 << FPSCR_FR) | (1 << FPSCR_FI));
+        if (ve == 0) {
+            /* Set the result to quiet NaN */
+            ret = 0x7FF8000000000000ULL;
+            env->fpscr &= ~(0xF << FPSCR_FPCC);
+            env->fpscr |= 0x11 << FPSCR_FPCC;
+        }
+        break;
+    case POWERPC_EXCP_FP_VXCVI:
+        /* Invalid conversion */
+        env->fpscr |= 1 << FPSCR_VXCVI;
+        env->fpscr &= ~((1 << FPSCR_FR) | (1 << FPSCR_FI));
+        if (ve == 0) {
+            /* Set the result to quiet NaN */
+            ret = 0x7FF8000000000000ULL;
+            env->fpscr &= ~(0xF << FPSCR_FPCC);
+            env->fpscr |= 0x11 << FPSCR_FPCC;
+        }
+        break;
+    }
+    /* Update the floating-point invalid operation summary */
+    env->fpscr |= 1 << FPSCR_VX;
+    /* Update the floating-point exception summary */
+    env->fpscr |= 1 << FPSCR_FX;
+    if (ve != 0) {
+        /* Update the floating-point enabled exception summary */
+        env->fpscr |= 1 << FPSCR_FEX;
+        if (msr_fe0 != 0 || msr_fe1 != 0) {
+            helper_raise_exception_err(env, POWERPC_EXCP_PROGRAM,
+                                       POWERPC_EXCP_FP | op);
+        }
+    }
+    return ret;
+}
+
+static inline void float_zero_divide_excp(void)
+{
+    env->fpscr |= 1 << FPSCR_ZX;
+    env->fpscr &= ~((1 << FPSCR_FR) | (1 << FPSCR_FI));
+    /* Update the floating-point exception summary */
+    env->fpscr |= 1 << FPSCR_FX;
+    if (fpscr_ze != 0) {
+        /* Update the floating-point enabled exception summary */
+        env->fpscr |= 1 << FPSCR_FEX;
+        if (msr_fe0 != 0 || msr_fe1 != 0) {
+            helper_raise_exception_err(env, POWERPC_EXCP_PROGRAM,
+                                       POWERPC_EXCP_FP | POWERPC_EXCP_FP_ZX);
+        }
+    }
+}
+
+static inline void float_overflow_excp(void)
+{
+    env->fpscr |= 1 << FPSCR_OX;
+    /* Update the floating-point exception summary */
+    env->fpscr |= 1 << FPSCR_FX;
+    if (fpscr_oe != 0) {
+        /* XXX: should adjust the result */
+        /* Update the floating-point enabled exception summary */
+        env->fpscr |= 1 << FPSCR_FEX;
+        /* We must update the target FPR before raising the exception */
+        env->exception_index = POWERPC_EXCP_PROGRAM;
+        env->error_code = POWERPC_EXCP_FP | POWERPC_EXCP_FP_OX;
+    } else {
+        env->fpscr |= 1 << FPSCR_XX;
+        env->fpscr |= 1 << FPSCR_FI;
+    }
+}
+
+static inline void float_underflow_excp(void)
+{
+    env->fpscr |= 1 << FPSCR_UX;
+    /* Update the floating-point exception summary */
+    env->fpscr |= 1 << FPSCR_FX;
+    if (fpscr_ue != 0) {
+        /* XXX: should adjust the result */
+        /* Update the floating-point enabled exception summary */
+        env->fpscr |= 1 << FPSCR_FEX;
+        /* We must update the target FPR before raising the exception */
+        env->exception_index = POWERPC_EXCP_PROGRAM;
+        env->error_code = POWERPC_EXCP_FP | POWERPC_EXCP_FP_UX;
+    }
+}
+
+static inline void float_inexact_excp(void)
+{
+    env->fpscr |= 1 << FPSCR_XX;
+    /* Update the floating-point exception summary */
+    env->fpscr |= 1 << FPSCR_FX;
+    if (fpscr_xe != 0) {
+        /* Update the floating-point enabled exception summary */
+        env->fpscr |= 1 << FPSCR_FEX;
+        /* We must update the target FPR before raising the exception */
+        env->exception_index = POWERPC_EXCP_PROGRAM;
+        env->error_code = POWERPC_EXCP_FP | POWERPC_EXCP_FP_XX;
+    }
+}
+
+static inline void fpscr_set_rounding_mode(void)
+{
+    int rnd_type;
+
+    /* Set rounding mode */
+    switch (fpscr_rn) {
+    case 0:
+        /* Best approximation (round to nearest) */
+        rnd_type = float_round_nearest_even;
+        break;
+    case 1:
+        /* Smaller magnitude (round toward zero) */
+        rnd_type = float_round_to_zero;
+        break;
+    case 2:
+        /* Round toward +infinite */
+        rnd_type = float_round_up;
+        break;
+    default:
+    case 3:
+        /* Round toward -infinite */
+        rnd_type = float_round_down;
+        break;
+    }
+    set_float_rounding_mode(rnd_type, &env->fp_status);
+}
+
+void helper_fpscr_clrbit(uint32_t bit)
+{
+    int prev;
+
+    prev = (env->fpscr >> bit) & 1;
+    env->fpscr &= ~(1 << bit);
+    if (prev == 1) {
+        switch (bit) {
+        case FPSCR_RN1:
+        case FPSCR_RN:
+            fpscr_set_rounding_mode();
+            break;
+        default:
+            break;
+        }
+    }
+}
+
+void helper_fpscr_setbit(uint32_t bit)
+{
+    int prev;
+
+    prev = (env->fpscr >> bit) & 1;
+    env->fpscr |= 1 << bit;
+    if (prev == 0) {
+        switch (bit) {
+        case FPSCR_VX:
+            env->fpscr |= 1 << FPSCR_FX;
+            if (fpscr_ve) {
+                goto raise_ve;
+            }
+        case FPSCR_OX:
+            env->fpscr |= 1 << FPSCR_FX;
+            if (fpscr_oe) {
+                goto raise_oe;
+            }
+            break;
+        case FPSCR_UX:
+            env->fpscr |= 1 << FPSCR_FX;
+            if (fpscr_ue) {
+                goto raise_ue;
+            }
+            break;
+        case FPSCR_ZX:
+            env->fpscr |= 1 << FPSCR_FX;
+            if (fpscr_ze) {
+                goto raise_ze;
+            }
+            break;
+        case FPSCR_XX:
+            env->fpscr |= 1 << FPSCR_FX;
+            if (fpscr_xe) {
+                goto raise_xe;
+            }
+            break;
+        case FPSCR_VXSNAN:
+        case FPSCR_VXISI:
+        case FPSCR_VXIDI:
+        case FPSCR_VXZDZ:
+        case FPSCR_VXIMZ:
+        case FPSCR_VXVC:
+        case FPSCR_VXSOFT:
+        case FPSCR_VXSQRT:
+        case FPSCR_VXCVI:
+            env->fpscr |= 1 << FPSCR_VX;
+            env->fpscr |= 1 << FPSCR_FX;
+            if (fpscr_ve != 0) {
+                goto raise_ve;
+            }
+            break;
+        case FPSCR_VE:
+            if (fpscr_vx != 0) {
+            raise_ve:
+                env->error_code = POWERPC_EXCP_FP;
+                if (fpscr_vxsnan) {
+                    env->error_code |= POWERPC_EXCP_FP_VXSNAN;
+                }
+                if (fpscr_vxisi) {
+                    env->error_code |= POWERPC_EXCP_FP_VXISI;
+                }
+                if (fpscr_vxidi) {
+                    env->error_code |= POWERPC_EXCP_FP_VXIDI;
+                }
+                if (fpscr_vxzdz) {
+                    env->error_code |= POWERPC_EXCP_FP_VXZDZ;
+                }
+                if (fpscr_vximz) {
+                    env->error_code |= POWERPC_EXCP_FP_VXIMZ;
+                }
+                if (fpscr_vxvc) {
+                    env->error_code |= POWERPC_EXCP_FP_VXVC;
+                }
+                if (fpscr_vxsoft) {
+                    env->error_code |= POWERPC_EXCP_FP_VXSOFT;
+                }
+                if (fpscr_vxsqrt) {
+                    env->error_code |= POWERPC_EXCP_FP_VXSQRT;
+                }
+                if (fpscr_vxcvi) {
+                    env->error_code |= POWERPC_EXCP_FP_VXCVI;
+                }
+                goto raise_excp;
+            }
+            break;
+        case FPSCR_OE:
+            if (fpscr_ox != 0) {
+            raise_oe:
+                env->error_code = POWERPC_EXCP_FP | POWERPC_EXCP_FP_OX;
+                goto raise_excp;
+            }
+            break;
+        case FPSCR_UE:
+            if (fpscr_ux != 0) {
+            raise_ue:
+                env->error_code = POWERPC_EXCP_FP | POWERPC_EXCP_FP_UX;
+                goto raise_excp;
+            }
+            break;
+        case FPSCR_ZE:
+            if (fpscr_zx != 0) {
+            raise_ze:
+                env->error_code = POWERPC_EXCP_FP | POWERPC_EXCP_FP_ZX;
+                goto raise_excp;
+            }
+            break;
+        case FPSCR_XE:
+            if (fpscr_xx != 0) {
+            raise_xe:
+                env->error_code = POWERPC_EXCP_FP | POWERPC_EXCP_FP_XX;
+                goto raise_excp;
+            }
+            break;
+        case FPSCR_RN1:
+        case FPSCR_RN:
+            fpscr_set_rounding_mode();
+            break;
+        default:
+            break;
+        raise_excp:
+            /* Update the floating-point enabled exception summary */
+            env->fpscr |= 1 << FPSCR_FEX;
+            /* We have to update Rc1 before raising the exception */
+            env->exception_index = POWERPC_EXCP_PROGRAM;
+            break;
+        }
+    }
+}
+
+void helper_store_fpscr(uint64_t arg, uint32_t mask)
+{
+    /*
+     * We use only the 32 LSB of the incoming fpr
+     */
+    uint32_t prev, new;
+    int i;
+
+    prev = env->fpscr;
+    new = (uint32_t)arg;
+    new &= ~0x60000000;
+    new |= prev & 0x60000000;
+    for (i = 0; i < 8; i++) {
+        if (mask & (1 << i)) {
+            env->fpscr &= ~(0xF << (4 * i));
+            env->fpscr |= new & (0xF << (4 * i));
+        }
+    }
+    /* Update VX and FEX */
+    if (fpscr_ix != 0) {
+        env->fpscr |= 1 << FPSCR_VX;
+    } else {
+        env->fpscr &= ~(1 << FPSCR_VX);
+    }
+    if ((fpscr_ex & fpscr_eex) != 0) {
+        env->fpscr |= 1 << FPSCR_FEX;
+        env->exception_index = POWERPC_EXCP_PROGRAM;
+        /* XXX: we should compute it properly */
+        env->error_code = POWERPC_EXCP_FP;
+    } else {
+        env->fpscr &= ~(1 << FPSCR_FEX);
+    }
+    fpscr_set_rounding_mode();
+}
+
+void helper_float_check_status(void)
+{
+    if (env->exception_index == POWERPC_EXCP_PROGRAM &&
+        (env->error_code & POWERPC_EXCP_FP)) {
+        /* Differred floating-point exception after target FPR update */
+        if (msr_fe0 != 0 || msr_fe1 != 0) {
+            helper_raise_exception_err(env, env->exception_index,
+                                       env->error_code);
+        }
+    } else {
+        int status = get_float_exception_flags(&env->fp_status);
+        if (status & float_flag_divbyzero) {
+            float_zero_divide_excp();
+        } else if (status & float_flag_overflow) {
+            float_overflow_excp();
+        } else if (status & float_flag_underflow) {
+            float_underflow_excp();
+        } else if (status & float_flag_inexact) {
+            float_inexact_excp();
+        }
+    }
+}
+
+void helper_reset_fpstatus(void)
+{
+    set_float_exception_flags(0, &env->fp_status);
+}
+
+/* fadd - fadd. */
+uint64_t helper_fadd(uint64_t arg1, uint64_t arg2)
+{
+    CPU_DoubleU farg1, farg2;
+
+    farg1.ll = arg1;
+    farg2.ll = arg2;
+
+    if (unlikely(float64_is_infinity(farg1.d) && float64_is_infinity(farg2.d) &&
+                 float64_is_neg(farg1.d) != float64_is_neg(farg2.d))) {
+        /* Magnitude subtraction of infinities */
+        farg1.ll = fload_invalid_op_excp(POWERPC_EXCP_FP_VXISI);
+    } else {
+        if (unlikely(float64_is_signaling_nan(farg1.d) ||
+                     float64_is_signaling_nan(farg2.d))) {
+            /* sNaN addition */
+            fload_invalid_op_excp(POWERPC_EXCP_FP_VXSNAN);
+        }
+        farg1.d = float64_add(farg1.d, farg2.d, &env->fp_status);
+    }
+
+    return farg1.ll;
+}
+
+/* fsub - fsub. */
+uint64_t helper_fsub(uint64_t arg1, uint64_t arg2)
+{
+    CPU_DoubleU farg1, farg2;
+
+    farg1.ll = arg1;
+    farg2.ll = arg2;
+
+    if (unlikely(float64_is_infinity(farg1.d) && float64_is_infinity(farg2.d) &&
+                 float64_is_neg(farg1.d) == float64_is_neg(farg2.d))) {
+        /* Magnitude subtraction of infinities */
+        farg1.ll = fload_invalid_op_excp(POWERPC_EXCP_FP_VXISI);
+    } else {
+        if (unlikely(float64_is_signaling_nan(farg1.d) ||
+                     float64_is_signaling_nan(farg2.d))) {
+            /* sNaN subtraction */
+            fload_invalid_op_excp(POWERPC_EXCP_FP_VXSNAN);
+        }
+        farg1.d = float64_sub(farg1.d, farg2.d, &env->fp_status);
+    }
+
+    return farg1.ll;
+}
+
+/* fmul - fmul. */
+uint64_t helper_fmul(uint64_t arg1, uint64_t arg2)
+{
+    CPU_DoubleU farg1, farg2;
+
+    farg1.ll = arg1;
+    farg2.ll = arg2;
+
+    if (unlikely((float64_is_infinity(farg1.d) && float64_is_zero(farg2.d)) ||
+                 (float64_is_zero(farg1.d) && float64_is_infinity(farg2.d)))) {
+        /* Multiplication of zero by infinity */
+        farg1.ll = fload_invalid_op_excp(POWERPC_EXCP_FP_VXIMZ);
+    } else {
+        if (unlikely(float64_is_signaling_nan(farg1.d) ||
+                     float64_is_signaling_nan(farg2.d))) {
+            /* sNaN multiplication */
+            fload_invalid_op_excp(POWERPC_EXCP_FP_VXSNAN);
+        }
+        farg1.d = float64_mul(farg1.d, farg2.d, &env->fp_status);
+    }
+
+    return farg1.ll;
+}
+
+/* fdiv - fdiv. */
+uint64_t helper_fdiv(uint64_t arg1, uint64_t arg2)
+{
+    CPU_DoubleU farg1, farg2;
+
+    farg1.ll = arg1;
+    farg2.ll = arg2;
+
+    if (unlikely(float64_is_infinity(farg1.d) &&
+                 float64_is_infinity(farg2.d))) {
+        /* Division of infinity by infinity */
+        farg1.ll = fload_invalid_op_excp(POWERPC_EXCP_FP_VXIDI);
+    } else if (unlikely(float64_is_zero(farg1.d) && float64_is_zero(farg2.d))) {
+        /* Division of zero by zero */
+        farg1.ll = fload_invalid_op_excp(POWERPC_EXCP_FP_VXZDZ);
+    } else {
+        if (unlikely(float64_is_signaling_nan(farg1.d) ||
+                     float64_is_signaling_nan(farg2.d))) {
+            /* sNaN division */
+            fload_invalid_op_excp(POWERPC_EXCP_FP_VXSNAN);
+        }
+        farg1.d = float64_div(farg1.d, farg2.d, &env->fp_status);
+    }
+
+    return farg1.ll;
+}
+
+/* fabs */
+uint64_t helper_fabs(uint64_t arg)
+{
+    CPU_DoubleU farg;
+
+    farg.ll = arg;
+    farg.d = float64_abs(farg.d);
+    return farg.ll;
+}
+
+/* fnabs */
+uint64_t helper_fnabs(uint64_t arg)
+{
+    CPU_DoubleU farg;
+
+    farg.ll = arg;
+    farg.d = float64_abs(farg.d);
+    farg.d = float64_chs(farg.d);
+    return farg.ll;
+}
+
+/* fneg */
+uint64_t helper_fneg(uint64_t arg)
+{
+    CPU_DoubleU farg;
+
+    farg.ll = arg;
+    farg.d = float64_chs(farg.d);
+    return farg.ll;
+}
+
+/* fctiw - fctiw. */
+uint64_t helper_fctiw(uint64_t arg)
+{
+    CPU_DoubleU farg;
+
+    farg.ll = arg;
+
+    if (unlikely(float64_is_signaling_nan(farg.d))) {
+        /* sNaN conversion */
+        farg.ll = fload_invalid_op_excp(POWERPC_EXCP_FP_VXSNAN |
+                                        POWERPC_EXCP_FP_VXCVI);
+    } else if (unlikely(float64_is_quiet_nan(farg.d) ||
+                        float64_is_infinity(farg.d))) {
+        /* qNan / infinity conversion */
+        farg.ll = fload_invalid_op_excp(POWERPC_EXCP_FP_VXCVI);
+    } else {
+        farg.ll = float64_to_int32(farg.d, &env->fp_status);
+        /* XXX: higher bits are not supposed to be significant.
+         *     to make tests easier, return the same as a real PowerPC 750
+         */
+        farg.ll |= 0xFFF80000ULL << 32;
+    }
+    return farg.ll;
+}
+
+/* fctiwz - fctiwz. */
+uint64_t helper_fctiwz(uint64_t arg)
+{
+    CPU_DoubleU farg;
+
+    farg.ll = arg;
+
+    if (unlikely(float64_is_signaling_nan(farg.d))) {
+        /* sNaN conversion */
+        farg.ll = fload_invalid_op_excp(POWERPC_EXCP_FP_VXSNAN |
+                                        POWERPC_EXCP_FP_VXCVI);
+    } else if (unlikely(float64_is_quiet_nan(farg.d) ||
+                        float64_is_infinity(farg.d))) {
+        /* qNan / infinity conversion */
+        farg.ll = fload_invalid_op_excp(POWERPC_EXCP_FP_VXCVI);
+    } else {
+        farg.ll = float64_to_int32_round_to_zero(farg.d, &env->fp_status);
+        /* XXX: higher bits are not supposed to be significant.
+         *     to make tests easier, return the same as a real PowerPC 750
+         */
+        farg.ll |= 0xFFF80000ULL << 32;
+    }
+    return farg.ll;
+}
+
+#if defined(TARGET_PPC64)
+/* fcfid - fcfid. */
+uint64_t helper_fcfid(uint64_t arg)
+{
+    CPU_DoubleU farg;
+
+    farg.d = int64_to_float64(arg, &env->fp_status);
+    return farg.ll;
+}
+
+/* fctid - fctid. */
+uint64_t helper_fctid(uint64_t arg)
+{
+    CPU_DoubleU farg;
+
+    farg.ll = arg;
+
+    if (unlikely(float64_is_signaling_nan(farg.d))) {
+        /* sNaN conversion */
+        farg.ll = fload_invalid_op_excp(POWERPC_EXCP_FP_VXSNAN |
+                                        POWERPC_EXCP_FP_VXCVI);
+    } else if (unlikely(float64_is_quiet_nan(farg.d) ||
+                        float64_is_infinity(farg.d))) {
+        /* qNan / infinity conversion */
+        farg.ll = fload_invalid_op_excp(POWERPC_EXCP_FP_VXCVI);
+    } else {
+        farg.ll = float64_to_int64(farg.d, &env->fp_status);
+    }
+    return farg.ll;
+}
+
+/* fctidz - fctidz. */
+uint64_t helper_fctidz(uint64_t arg)
+{
+    CPU_DoubleU farg;
+
+    farg.ll = arg;
+
+    if (unlikely(float64_is_signaling_nan(farg.d))) {
+        /* sNaN conversion */
+        farg.ll = fload_invalid_op_excp(POWERPC_EXCP_FP_VXSNAN |
+                                        POWERPC_EXCP_FP_VXCVI);
+    } else if (unlikely(float64_is_quiet_nan(farg.d) ||
+                        float64_is_infinity(farg.d))) {
+        /* qNan / infinity conversion */
+        farg.ll = fload_invalid_op_excp(POWERPC_EXCP_FP_VXCVI);
+    } else {
+        farg.ll = float64_to_int64_round_to_zero(farg.d, &env->fp_status);
+    }
+    return farg.ll;
+}
+
+#endif
+
+static inline uint64_t do_fri(uint64_t arg, int rounding_mode)
+{
+    CPU_DoubleU farg;
+
+    farg.ll = arg;
+
+    if (unlikely(float64_is_signaling_nan(farg.d))) {
+        /* sNaN round */
+        farg.ll = fload_invalid_op_excp(POWERPC_EXCP_FP_VXSNAN |
+                                        POWERPC_EXCP_FP_VXCVI);
+    } else if (unlikely(float64_is_quiet_nan(farg.d) ||
+                        float64_is_infinity(farg.d))) {
+        /* qNan / infinity round */
+        farg.ll = fload_invalid_op_excp(POWERPC_EXCP_FP_VXCVI);
+    } else {
+        set_float_rounding_mode(rounding_mode, &env->fp_status);
+        farg.ll = float64_round_to_int(farg.d, &env->fp_status);
+        /* Restore rounding mode from FPSCR */
+        fpscr_set_rounding_mode();
+    }
+    return farg.ll;
+}
+
+uint64_t helper_frin(uint64_t arg)
+{
+    return do_fri(arg, float_round_nearest_even);
+}
+
+uint64_t helper_friz(uint64_t arg)
+{
+    return do_fri(arg, float_round_to_zero);
+}
+
+uint64_t helper_frip(uint64_t arg)
+{
+    return do_fri(arg, float_round_up);
+}
+
+uint64_t helper_frim(uint64_t arg)
+{
+    return do_fri(arg, float_round_down);
+}
+
+/* fmadd - fmadd. */
+uint64_t helper_fmadd(uint64_t arg1, uint64_t arg2, uint64_t arg3)
+{
+    CPU_DoubleU farg1, farg2, farg3;
+
+    farg1.ll = arg1;
+    farg2.ll = arg2;
+    farg3.ll = arg3;
+
+    if (unlikely((float64_is_infinity(farg1.d) && float64_is_zero(farg2.d)) ||
+                 (float64_is_zero(farg1.d) && float64_is_infinity(farg2.d)))) {
+        /* Multiplication of zero by infinity */
+        farg1.ll = fload_invalid_op_excp(POWERPC_EXCP_FP_VXIMZ);
+    } else {
+        if (unlikely(float64_is_signaling_nan(farg1.d) ||
+                     float64_is_signaling_nan(farg2.d) ||
+                     float64_is_signaling_nan(farg3.d))) {
+            /* sNaN operation */
+            fload_invalid_op_excp(POWERPC_EXCP_FP_VXSNAN);
+        }
+        /* This is the way the PowerPC specification defines it */
+        float128 ft0_128, ft1_128;
+
+        ft0_128 = float64_to_float128(farg1.d, &env->fp_status);
+        ft1_128 = float64_to_float128(farg2.d, &env->fp_status);
+        ft0_128 = float128_mul(ft0_128, ft1_128, &env->fp_status);
+        if (unlikely(float128_is_infinity(ft0_128) &&
+                     float64_is_infinity(farg3.d) &&
+                     float128_is_neg(ft0_128) != float64_is_neg(farg3.d))) {
+            /* Magnitude subtraction of infinities */
+            farg1.ll = fload_invalid_op_excp(POWERPC_EXCP_FP_VXISI);
+        } else {
+            ft1_128 = float64_to_float128(farg3.d, &env->fp_status);
+            ft0_128 = float128_add(ft0_128, ft1_128, &env->fp_status);
+            farg1.d = float128_to_float64(ft0_128, &env->fp_status);
+        }
+    }
+
+    return farg1.ll;
+}
+
+/* fmsub - fmsub. */
+uint64_t helper_fmsub(uint64_t arg1, uint64_t arg2, uint64_t arg3)
+{
+    CPU_DoubleU farg1, farg2, farg3;
+
+    farg1.ll = arg1;
+    farg2.ll = arg2;
+    farg3.ll = arg3;
+
+    if (unlikely((float64_is_infinity(farg1.d) && float64_is_zero(farg2.d)) ||
+                 (float64_is_zero(farg1.d) &&
+                  float64_is_infinity(farg2.d)))) {
+        /* Multiplication of zero by infinity */
+        farg1.ll = fload_invalid_op_excp(POWERPC_EXCP_FP_VXIMZ);
+    } else {
+        if (unlikely(float64_is_signaling_nan(farg1.d) ||
+                     float64_is_signaling_nan(farg2.d) ||
+                     float64_is_signaling_nan(farg3.d))) {
+            /* sNaN operation */
+            fload_invalid_op_excp(POWERPC_EXCP_FP_VXSNAN);
+        }
+        /* This is the way the PowerPC specification defines it */
+        float128 ft0_128, ft1_128;
+
+        ft0_128 = float64_to_float128(farg1.d, &env->fp_status);
+        ft1_128 = float64_to_float128(farg2.d, &env->fp_status);
+        ft0_128 = float128_mul(ft0_128, ft1_128, &env->fp_status);
+        if (unlikely(float128_is_infinity(ft0_128) &&
+                     float64_is_infinity(farg3.d) &&
+                     float128_is_neg(ft0_128) == float64_is_neg(farg3.d))) {
+            /* Magnitude subtraction of infinities */
+            farg1.ll = fload_invalid_op_excp(POWERPC_EXCP_FP_VXISI);
+        } else {
+            ft1_128 = float64_to_float128(farg3.d, &env->fp_status);
+            ft0_128 = float128_sub(ft0_128, ft1_128, &env->fp_status);
+            farg1.d = float128_to_float64(ft0_128, &env->fp_status);
+        }
+    }
+    return farg1.ll;
+}
+
+/* fnmadd - fnmadd. */
+uint64_t helper_fnmadd(uint64_t arg1, uint64_t arg2, uint64_t arg3)
+{
+    CPU_DoubleU farg1, farg2, farg3;
+
+    farg1.ll = arg1;
+    farg2.ll = arg2;
+    farg3.ll = arg3;
+
+    if (unlikely((float64_is_infinity(farg1.d) && float64_is_zero(farg2.d)) ||
+                 (float64_is_zero(farg1.d) && float64_is_infinity(farg2.d)))) {
+        /* Multiplication of zero by infinity */
+        farg1.ll = fload_invalid_op_excp(POWERPC_EXCP_FP_VXIMZ);
+    } else {
+        if (unlikely(float64_is_signaling_nan(farg1.d) ||
+                     float64_is_signaling_nan(farg2.d) ||
+                     float64_is_signaling_nan(farg3.d))) {
+            /* sNaN operation */
+            fload_invalid_op_excp(POWERPC_EXCP_FP_VXSNAN);
+        }
+        /* This is the way the PowerPC specification defines it */
+        float128 ft0_128, ft1_128;
+
+        ft0_128 = float64_to_float128(farg1.d, &env->fp_status);
+        ft1_128 = float64_to_float128(farg2.d, &env->fp_status);
+        ft0_128 = float128_mul(ft0_128, ft1_128, &env->fp_status);
+        if (unlikely(float128_is_infinity(ft0_128) &&
+                     float64_is_infinity(farg3.d) &&
+                     float128_is_neg(ft0_128) != float64_is_neg(farg3.d))) {
+            /* Magnitude subtraction of infinities */
+            farg1.ll = fload_invalid_op_excp(POWERPC_EXCP_FP_VXISI);
+        } else {
+            ft1_128 = float64_to_float128(farg3.d, &env->fp_status);
+            ft0_128 = float128_add(ft0_128, ft1_128, &env->fp_status);
+            farg1.d = float128_to_float64(ft0_128, &env->fp_status);
+        }
+        if (likely(!float64_is_any_nan(farg1.d))) {
+            farg1.d = float64_chs(farg1.d);
+        }
+    }
+    return farg1.ll;
+}
+
+/* fnmsub - fnmsub. */
+uint64_t helper_fnmsub(uint64_t arg1, uint64_t arg2, uint64_t arg3)
+{
+    CPU_DoubleU farg1, farg2, farg3;
+
+    farg1.ll = arg1;
+    farg2.ll = arg2;
+    farg3.ll = arg3;
+
+    if (unlikely((float64_is_infinity(farg1.d) && float64_is_zero(farg2.d)) ||
+                 (float64_is_zero(farg1.d) &&
+                  float64_is_infinity(farg2.d)))) {
+        /* Multiplication of zero by infinity */
+        farg1.ll = fload_invalid_op_excp(POWERPC_EXCP_FP_VXIMZ);
+    } else {
+        if (unlikely(float64_is_signaling_nan(farg1.d) ||
+                     float64_is_signaling_nan(farg2.d) ||
+                     float64_is_signaling_nan(farg3.d))) {
+            /* sNaN operation */
+            fload_invalid_op_excp(POWERPC_EXCP_FP_VXSNAN);
+        }
+        /* This is the way the PowerPC specification defines it */
+        float128 ft0_128, ft1_128;
+
+        ft0_128 = float64_to_float128(farg1.d, &env->fp_status);
+        ft1_128 = float64_to_float128(farg2.d, &env->fp_status);
+        ft0_128 = float128_mul(ft0_128, ft1_128, &env->fp_status);
+        if (unlikely(float128_is_infinity(ft0_128) &&
+                     float64_is_infinity(farg3.d) &&
+                     float128_is_neg(ft0_128) == float64_is_neg(farg3.d))) {
+            /* Magnitude subtraction of infinities */
+            farg1.ll = fload_invalid_op_excp(POWERPC_EXCP_FP_VXISI);
+        } else {
+            ft1_128 = float64_to_float128(farg3.d, &env->fp_status);
+            ft0_128 = float128_sub(ft0_128, ft1_128, &env->fp_status);
+            farg1.d = float128_to_float64(ft0_128, &env->fp_status);
+        }
+        if (likely(!float64_is_any_nan(farg1.d))) {
+            farg1.d = float64_chs(farg1.d);
+        }
+    }
+    return farg1.ll;
+}
+
+/* frsp - frsp. */
+uint64_t helper_frsp(uint64_t arg)
+{
+    CPU_DoubleU farg;
+    float32 f32;
+
+    farg.ll = arg;
+
+    if (unlikely(float64_is_signaling_nan(farg.d))) {
+        /* sNaN square root */
+        fload_invalid_op_excp(POWERPC_EXCP_FP_VXSNAN);
+    }
+    f32 = float64_to_float32(farg.d, &env->fp_status);
+    farg.d = float32_to_float64(f32, &env->fp_status);
+
+    return farg.ll;
+}
+
+/* fsqrt - fsqrt. */
+uint64_t helper_fsqrt(uint64_t arg)
+{
+    CPU_DoubleU farg;
+
+    farg.ll = arg;
+
+    if (unlikely(float64_is_neg(farg.d) && !float64_is_zero(farg.d))) {
+        /* Square root of a negative nonzero number */
+        farg.ll = fload_invalid_op_excp(POWERPC_EXCP_FP_VXSQRT);
+    } else {
+        if (unlikely(float64_is_signaling_nan(farg.d))) {
+            /* sNaN square root */
+            fload_invalid_op_excp(POWERPC_EXCP_FP_VXSNAN);
+        }
+        farg.d = float64_sqrt(farg.d, &env->fp_status);
+    }
+    return farg.ll;
+}
+
+/* fre - fre. */
+uint64_t helper_fre(uint64_t arg)
+{
+    CPU_DoubleU farg;
+
+    farg.ll = arg;
+
+    if (unlikely(float64_is_signaling_nan(farg.d))) {
+        /* sNaN reciprocal */
+        fload_invalid_op_excp(POWERPC_EXCP_FP_VXSNAN);
+    }
+    farg.d = float64_div(float64_one, farg.d, &env->fp_status);
+    return farg.d;
+}
+
+/* fres - fres. */
+uint64_t helper_fres(uint64_t arg)
+{
+    CPU_DoubleU farg;
+    float32 f32;
+
+    farg.ll = arg;
+
+    if (unlikely(float64_is_signaling_nan(farg.d))) {
+        /* sNaN reciprocal */
+        fload_invalid_op_excp(POWERPC_EXCP_FP_VXSNAN);
+    }
+    farg.d = float64_div(float64_one, farg.d, &env->fp_status);
+    f32 = float64_to_float32(farg.d, &env->fp_status);
+    farg.d = float32_to_float64(f32, &env->fp_status);
+
+    return farg.ll;
+}
+
+/* frsqrte  - frsqrte. */
+uint64_t helper_frsqrte(uint64_t arg)
+{
+    CPU_DoubleU farg;
+    float32 f32;
+
+    farg.ll = arg;
+
+    if (unlikely(float64_is_neg(farg.d) && !float64_is_zero(farg.d))) {
+        /* Reciprocal square root of a negative nonzero number */
+        farg.ll = fload_invalid_op_excp(POWERPC_EXCP_FP_VXSQRT);
+    } else {
+        if (unlikely(float64_is_signaling_nan(farg.d))) {
+            /* sNaN reciprocal square root */
+            fload_invalid_op_excp(POWERPC_EXCP_FP_VXSNAN);
+        }
+        farg.d = float64_sqrt(farg.d, &env->fp_status);
+        farg.d = float64_div(float64_one, farg.d, &env->fp_status);
+        f32 = float64_to_float32(farg.d, &env->fp_status);
+        farg.d = float32_to_float64(f32, &env->fp_status);
+    }
+    return farg.ll;
+}
+
+/* fsel - fsel. */
+uint64_t helper_fsel(uint64_t arg1, uint64_t arg2, uint64_t arg3)
+{
+    CPU_DoubleU farg1;
+
+    farg1.ll = arg1;
+
+    if ((!float64_is_neg(farg1.d) || float64_is_zero(farg1.d)) &&
+        !float64_is_any_nan(farg1.d)) {
+        return arg2;
+    } else {
+        return arg3;
+    }
+}
+
+void helper_fcmpu(uint64_t arg1, uint64_t arg2, uint32_t crfD)
+{
+    CPU_DoubleU farg1, farg2;
+    uint32_t ret = 0;
+
+    farg1.ll = arg1;
+    farg2.ll = arg2;
+
+    if (unlikely(float64_is_any_nan(farg1.d) ||
+                 float64_is_any_nan(farg2.d))) {
+        ret = 0x01UL;
+    } else if (float64_lt(farg1.d, farg2.d, &env->fp_status)) {
+        ret = 0x08UL;
+    } else if (!float64_le(farg1.d, farg2.d, &env->fp_status)) {
+        ret = 0x04UL;
+    } else {
+        ret = 0x02UL;
+    }
+
+    env->fpscr &= ~(0x0F << FPSCR_FPRF);
+    env->fpscr |= ret << FPSCR_FPRF;
+    env->crf[crfD] = ret;
+    if (unlikely(ret == 0x01UL
+                 && (float64_is_signaling_nan(farg1.d) ||
+                     float64_is_signaling_nan(farg2.d)))) {
+        /* sNaN comparison */
+        fload_invalid_op_excp(POWERPC_EXCP_FP_VXSNAN);
+    }
+}
+
+void helper_fcmpo(uint64_t arg1, uint64_t arg2, uint32_t crfD)
+{
+    CPU_DoubleU farg1, farg2;
+    uint32_t ret = 0;
+
+    farg1.ll = arg1;
+    farg2.ll = arg2;
+
+    if (unlikely(float64_is_any_nan(farg1.d) ||
+                 float64_is_any_nan(farg2.d))) {
+        ret = 0x01UL;
+    } else if (float64_lt(farg1.d, farg2.d, &env->fp_status)) {
+        ret = 0x08UL;
+    } else if (!float64_le(farg1.d, farg2.d, &env->fp_status)) {
+        ret = 0x04UL;
+    } else {
+        ret = 0x02UL;
+    }
+
+    env->fpscr &= ~(0x0F << FPSCR_FPRF);
+    env->fpscr |= ret << FPSCR_FPRF;
+    env->crf[crfD] = ret;
+    if (unlikely(ret == 0x01UL)) {
+        if (float64_is_signaling_nan(farg1.d) ||
+            float64_is_signaling_nan(farg2.d)) {
+            /* sNaN comparison */
+            fload_invalid_op_excp(POWERPC_EXCP_FP_VXSNAN |
+                                  POWERPC_EXCP_FP_VXVC);
+        } else {
+            /* qNaN comparison */
+            fload_invalid_op_excp(POWERPC_EXCP_FP_VXVC);
+        }
+    }
+}
+
+/* Single-precision floating-point conversions */
+static inline uint32_t efscfsi(uint32_t val)
+{
+    CPU_FloatU u;
+
+    u.f = int32_to_float32(val, &env->vec_status);
+
+    return u.l;
+}
+
+static inline uint32_t efscfui(uint32_t val)
+{
+    CPU_FloatU u;
+
+    u.f = uint32_to_float32(val, &env->vec_status);
+
+    return u.l;
+}
+
+static inline int32_t efsctsi(uint32_t val)
+{
+    CPU_FloatU u;
+
+    u.l = val;
+    /* NaN are not treated the same way IEEE 754 does */
+    if (unlikely(float32_is_quiet_nan(u.f))) {
+        return 0;
+    }
+
+    return float32_to_int32(u.f, &env->vec_status);
+}
+
+static inline uint32_t efsctui(uint32_t val)
+{
+    CPU_FloatU u;
+
+    u.l = val;
+    /* NaN are not treated the same way IEEE 754 does */
+    if (unlikely(float32_is_quiet_nan(u.f))) {
+        return 0;
+    }
+
+    return float32_to_uint32(u.f, &env->vec_status);
+}
+
+static inline uint32_t efsctsiz(uint32_t val)
+{
+    CPU_FloatU u;
+
+    u.l = val;
+    /* NaN are not treated the same way IEEE 754 does */
+    if (unlikely(float32_is_quiet_nan(u.f))) {
+        return 0;
+    }
+
+    return float32_to_int32_round_to_zero(u.f, &env->vec_status);
+}
+
+static inline uint32_t efsctuiz(uint32_t val)
+{
+    CPU_FloatU u;
+
+    u.l = val;
+    /* NaN are not treated the same way IEEE 754 does */
+    if (unlikely(float32_is_quiet_nan(u.f))) {
+        return 0;
+    }
+
+    return float32_to_uint32_round_to_zero(u.f, &env->vec_status);
+}
+
+static inline uint32_t efscfsf(uint32_t val)
+{
+    CPU_FloatU u;
+    float32 tmp;
+
+    u.f = int32_to_float32(val, &env->vec_status);
+    tmp = int64_to_float32(1ULL << 32, &env->vec_status);
+    u.f = float32_div(u.f, tmp, &env->vec_status);
+
+    return u.l;
+}
+
+static inline uint32_t efscfuf(uint32_t val)
+{
+    CPU_FloatU u;
+    float32 tmp;
+
+    u.f = uint32_to_float32(val, &env->vec_status);
+    tmp = uint64_to_float32(1ULL << 32, &env->vec_status);
+    u.f = float32_div(u.f, tmp, &env->vec_status);
+
+    return u.l;
+}
+
+static inline uint32_t efsctsf(uint32_t val)
+{
+    CPU_FloatU u;
+    float32 tmp;
+
+    u.l = val;
+    /* NaN are not treated the same way IEEE 754 does */
+    if (unlikely(float32_is_quiet_nan(u.f))) {
+        return 0;
+    }
+    tmp = uint64_to_float32(1ULL << 32, &env->vec_status);
+    u.f = float32_mul(u.f, tmp, &env->vec_status);
+
+    return float32_to_int32(u.f, &env->vec_status);
+}
+
+static inline uint32_t efsctuf(uint32_t val)
+{
+    CPU_FloatU u;
+    float32 tmp;
+
+    u.l = val;
+    /* NaN are not treated the same way IEEE 754 does */
+    if (unlikely(float32_is_quiet_nan(u.f))) {
+        return 0;
+    }
+    tmp = uint64_to_float32(1ULL << 32, &env->vec_status);
+    u.f = float32_mul(u.f, tmp, &env->vec_status);
+
+    return float32_to_uint32(u.f, &env->vec_status);
+}
+
+#define HELPER_SPE_SINGLE_CONV(name)            \
+    uint32_t helper_e##name(uint32_t val)       \
+    {                                           \
+        return e##name(val);                    \
+    }
+/* efscfsi */
+HELPER_SPE_SINGLE_CONV(fscfsi);
+/* efscfui */
+HELPER_SPE_SINGLE_CONV(fscfui);
+/* efscfuf */
+HELPER_SPE_SINGLE_CONV(fscfuf);
+/* efscfsf */
+HELPER_SPE_SINGLE_CONV(fscfsf);
+/* efsctsi */
+HELPER_SPE_SINGLE_CONV(fsctsi);
+/* efsctui */
+HELPER_SPE_SINGLE_CONV(fsctui);
+/* efsctsiz */
+HELPER_SPE_SINGLE_CONV(fsctsiz);
+/* efsctuiz */
+HELPER_SPE_SINGLE_CONV(fsctuiz);
+/* efsctsf */
+HELPER_SPE_SINGLE_CONV(fsctsf);
+/* efsctuf */
+HELPER_SPE_SINGLE_CONV(fsctuf);
+
+#define HELPER_SPE_VECTOR_CONV(name)                    \
+    uint64_t helper_ev##name(uint64_t val)              \
+    {                                                   \
+        return ((uint64_t)e##name(val >> 32) << 32) |   \
+            (uint64_t)e##name(val);                     \
+    }
+/* evfscfsi */
+HELPER_SPE_VECTOR_CONV(fscfsi);
+/* evfscfui */
+HELPER_SPE_VECTOR_CONV(fscfui);
+/* evfscfuf */
+HELPER_SPE_VECTOR_CONV(fscfuf);
+/* evfscfsf */
+HELPER_SPE_VECTOR_CONV(fscfsf);
+/* evfsctsi */
+HELPER_SPE_VECTOR_CONV(fsctsi);
+/* evfsctui */
+HELPER_SPE_VECTOR_CONV(fsctui);
+/* evfsctsiz */
+HELPER_SPE_VECTOR_CONV(fsctsiz);
+/* evfsctuiz */
+HELPER_SPE_VECTOR_CONV(fsctuiz);
+/* evfsctsf */
+HELPER_SPE_VECTOR_CONV(fsctsf);
+/* evfsctuf */
+HELPER_SPE_VECTOR_CONV(fsctuf);
+
+/* Single-precision floating-point arithmetic */
+static inline uint32_t efsadd(uint32_t op1, uint32_t op2)
+{
+    CPU_FloatU u1, u2;
+
+    u1.l = op1;
+    u2.l = op2;
+    u1.f = float32_add(u1.f, u2.f, &env->vec_status);
+    return u1.l;
+}
+
+static inline uint32_t efssub(uint32_t op1, uint32_t op2)
+{
+    CPU_FloatU u1, u2;
+
+    u1.l = op1;
+    u2.l = op2;
+    u1.f = float32_sub(u1.f, u2.f, &env->vec_status);
+    return u1.l;
+}
+
+static inline uint32_t efsmul(uint32_t op1, uint32_t op2)
+{
+    CPU_FloatU u1, u2;
+
+    u1.l = op1;
+    u2.l = op2;
+    u1.f = float32_mul(u1.f, u2.f, &env->vec_status);
+    return u1.l;
+}
+
+static inline uint32_t efsdiv(uint32_t op1, uint32_t op2)
+{
+    CPU_FloatU u1, u2;
+
+    u1.l = op1;
+    u2.l = op2;
+    u1.f = float32_div(u1.f, u2.f, &env->vec_status);
+    return u1.l;
+}
+
+#define HELPER_SPE_SINGLE_ARITH(name)                   \
+    uint32_t helper_e##name(uint32_t op1, uint32_t op2) \
+    {                                                   \
+        return e##name(op1, op2);                       \
+    }
+/* efsadd */
+HELPER_SPE_SINGLE_ARITH(fsadd);
+/* efssub */
+HELPER_SPE_SINGLE_ARITH(fssub);
+/* efsmul */
+HELPER_SPE_SINGLE_ARITH(fsmul);
+/* efsdiv */
+HELPER_SPE_SINGLE_ARITH(fsdiv);
+
+#define HELPER_SPE_VECTOR_ARITH(name)                                   \
+    uint64_t helper_ev##name(uint64_t op1, uint64_t op2)                \
+    {                                                                   \
+        return ((uint64_t)e##name(op1 >> 32, op2 >> 32) << 32) |        \
+            (uint64_t)e##name(op1, op2);                                \
+    }
+/* evfsadd */
+HELPER_SPE_VECTOR_ARITH(fsadd);
+/* evfssub */
+HELPER_SPE_VECTOR_ARITH(fssub);
+/* evfsmul */
+HELPER_SPE_VECTOR_ARITH(fsmul);
+/* evfsdiv */
+HELPER_SPE_VECTOR_ARITH(fsdiv);
+
+/* Single-precision floating-point comparisons */
+static inline uint32_t efscmplt(uint32_t op1, uint32_t op2)
+{
+    CPU_FloatU u1, u2;
+
+    u1.l = op1;
+    u2.l = op2;
+    return float32_lt(u1.f, u2.f, &env->vec_status) ? 4 : 0;
+}
+
+static inline uint32_t efscmpgt(uint32_t op1, uint32_t op2)
+{
+    CPU_FloatU u1, u2;
+
+    u1.l = op1;
+    u2.l = op2;
+    return float32_le(u1.f, u2.f, &env->vec_status) ? 0 : 4;
+}
+
+static inline uint32_t efscmpeq(uint32_t op1, uint32_t op2)
+{
+    CPU_FloatU u1, u2;
+
+    u1.l = op1;
+    u2.l = op2;
+    return float32_eq(u1.f, u2.f, &env->vec_status) ? 4 : 0;
+}
+
+static inline uint32_t efststlt(uint32_t op1, uint32_t op2)
+{
+    /* XXX: TODO: ignore special values (NaN, infinites, ...) */
+    return efscmplt(op1, op2);
+}
+
+static inline uint32_t efststgt(uint32_t op1, uint32_t op2)
+{
+    /* XXX: TODO: ignore special values (NaN, infinites, ...) */
+    return efscmpgt(op1, op2);
+}
+
+static inline uint32_t efststeq(uint32_t op1, uint32_t op2)
+{
+    /* XXX: TODO: ignore special values (NaN, infinites, ...) */
+    return efscmpeq(op1, op2);
+}
+
+#define HELPER_SINGLE_SPE_CMP(name)                     \
+    uint32_t helper_e##name(uint32_t op1, uint32_t op2) \
+    {                                                   \
+        return e##name(op1, op2) << 2;                  \
+    }
+/* efststlt */
+HELPER_SINGLE_SPE_CMP(fststlt);
+/* efststgt */
+HELPER_SINGLE_SPE_CMP(fststgt);
+/* efststeq */
+HELPER_SINGLE_SPE_CMP(fststeq);
+/* efscmplt */
+HELPER_SINGLE_SPE_CMP(fscmplt);
+/* efscmpgt */
+HELPER_SINGLE_SPE_CMP(fscmpgt);
+/* efscmpeq */
+HELPER_SINGLE_SPE_CMP(fscmpeq);
+
+static inline uint32_t evcmp_merge(int t0, int t1)
+{
+    return (t0 << 3) | (t1 << 2) | ((t0 | t1) << 1) | (t0 & t1);
+}
+
+#define HELPER_VECTOR_SPE_CMP(name)                                     \
+    uint32_t helper_ev##name(uint64_t op1, uint64_t op2)                \
+    {                                                                   \
+        return evcmp_merge(e##name(op1 >> 32, op2 >> 32), e##name(op1, op2)); \
+    }
+/* evfststlt */
+HELPER_VECTOR_SPE_CMP(fststlt);
+/* evfststgt */
+HELPER_VECTOR_SPE_CMP(fststgt);
+/* evfststeq */
+HELPER_VECTOR_SPE_CMP(fststeq);
+/* evfscmplt */
+HELPER_VECTOR_SPE_CMP(fscmplt);
+/* evfscmpgt */
+HELPER_VECTOR_SPE_CMP(fscmpgt);
+/* evfscmpeq */
+HELPER_VECTOR_SPE_CMP(fscmpeq);
+
+/* Double-precision floating-point conversion */
+uint64_t helper_efdcfsi(uint32_t val)
+{
+    CPU_DoubleU u;
+
+    u.d = int32_to_float64(val, &env->vec_status);
+
+    return u.ll;
+}
+
+uint64_t helper_efdcfsid(uint64_t val)
+{
+    CPU_DoubleU u;
+
+    u.d = int64_to_float64(val, &env->vec_status);
+
+    return u.ll;
+}
+
+uint64_t helper_efdcfui(uint32_t val)
+{
+    CPU_DoubleU u;
+
+    u.d = uint32_to_float64(val, &env->vec_status);
+
+    return u.ll;
+}
+
+uint64_t helper_efdcfuid(uint64_t val)
+{
+    CPU_DoubleU u;
+
+    u.d = uint64_to_float64(val, &env->vec_status);
+
+    return u.ll;
+}
+
+uint32_t helper_efdctsi(uint64_t val)
+{
+    CPU_DoubleU u;
+
+    u.ll = val;
+    /* NaN are not treated the same way IEEE 754 does */
+    if (unlikely(float64_is_any_nan(u.d))) {
+        return 0;
+    }
+
+    return float64_to_int32(u.d, &env->vec_status);
+}
+
+uint32_t helper_efdctui(uint64_t val)
+{
+    CPU_DoubleU u;
+
+    u.ll = val;
+    /* NaN are not treated the same way IEEE 754 does */
+    if (unlikely(float64_is_any_nan(u.d))) {
+        return 0;
+    }
+
+    return float64_to_uint32(u.d, &env->vec_status);
+}
+
+uint32_t helper_efdctsiz(uint64_t val)
+{
+    CPU_DoubleU u;
+
+    u.ll = val;
+    /* NaN are not treated the same way IEEE 754 does */
+    if (unlikely(float64_is_any_nan(u.d))) {
+        return 0;
+    }
+
+    return float64_to_int32_round_to_zero(u.d, &env->vec_status);
+}
+
+uint64_t helper_efdctsidz(uint64_t val)
+{
+    CPU_DoubleU u;
+
+    u.ll = val;
+    /* NaN are not treated the same way IEEE 754 does */
+    if (unlikely(float64_is_any_nan(u.d))) {
+        return 0;
+    }
+
+    return float64_to_int64_round_to_zero(u.d, &env->vec_status);
+}
+
+uint32_t helper_efdctuiz(uint64_t val)
+{
+    CPU_DoubleU u;
+
+    u.ll = val;
+    /* NaN are not treated the same way IEEE 754 does */
+    if (unlikely(float64_is_any_nan(u.d))) {
+        return 0;
+    }
+
+    return float64_to_uint32_round_to_zero(u.d, &env->vec_status);
+}
+
+uint64_t helper_efdctuidz(uint64_t val)
+{
+    CPU_DoubleU u;
+
+    u.ll = val;
+    /* NaN are not treated the same way IEEE 754 does */
+    if (unlikely(float64_is_any_nan(u.d))) {
+        return 0;
+    }
+
+    return float64_to_uint64_round_to_zero(u.d, &env->vec_status);
+}
+
+uint64_t helper_efdcfsf(uint32_t val)
+{
+    CPU_DoubleU u;
+    float64 tmp;
+
+    u.d = int32_to_float64(val, &env->vec_status);
+    tmp = int64_to_float64(1ULL << 32, &env->vec_status);
+    u.d = float64_div(u.d, tmp, &env->vec_status);
+
+    return u.ll;
+}
+
+uint64_t helper_efdcfuf(uint32_t val)
+{
+    CPU_DoubleU u;
+    float64 tmp;
+
+    u.d = uint32_to_float64(val, &env->vec_status);
+    tmp = int64_to_float64(1ULL << 32, &env->vec_status);
+    u.d = float64_div(u.d, tmp, &env->vec_status);
+
+    return u.ll;
+}
+
+uint32_t helper_efdctsf(uint64_t val)
+{
+    CPU_DoubleU u;
+    float64 tmp;
+
+    u.ll = val;
+    /* NaN are not treated the same way IEEE 754 does */
+    if (unlikely(float64_is_any_nan(u.d))) {
+        return 0;
+    }
+    tmp = uint64_to_float64(1ULL << 32, &env->vec_status);
+    u.d = float64_mul(u.d, tmp, &env->vec_status);
+
+    return float64_to_int32(u.d, &env->vec_status);
+}
+
+uint32_t helper_efdctuf(uint64_t val)
+{
+    CPU_DoubleU u;
+    float64 tmp;
+
+    u.ll = val;
+    /* NaN are not treated the same way IEEE 754 does */
+    if (unlikely(float64_is_any_nan(u.d))) {
+        return 0;
+    }
+    tmp = uint64_to_float64(1ULL << 32, &env->vec_status);
+    u.d = float64_mul(u.d, tmp, &env->vec_status);
+
+    return float64_to_uint32(u.d, &env->vec_status);
+}
+
+uint32_t helper_efscfd(uint64_t val)
+{
+    CPU_DoubleU u1;
+    CPU_FloatU u2;
+
+    u1.ll = val;
+    u2.f = float64_to_float32(u1.d, &env->vec_status);
+
+    return u2.l;
+}
+
+uint64_t helper_efdcfs(uint32_t val)
+{
+    CPU_DoubleU u2;
+    CPU_FloatU u1;
+
+    u1.l = val;
+    u2.d = float32_to_float64(u1.f, &env->vec_status);
+
+    return u2.ll;
+}
+
+/* Double precision fixed-point arithmetic */
+uint64_t helper_efdadd(uint64_t op1, uint64_t op2)
+{
+    CPU_DoubleU u1, u2;
+
+    u1.ll = op1;
+    u2.ll = op2;
+    u1.d = float64_add(u1.d, u2.d, &env->vec_status);
+    return u1.ll;
+}
+
+uint64_t helper_efdsub(uint64_t op1, uint64_t op2)
+{
+    CPU_DoubleU u1, u2;
+
+    u1.ll = op1;
+    u2.ll = op2;
+    u1.d = float64_sub(u1.d, u2.d, &env->vec_status);
+    return u1.ll;
+}
+
+uint64_t helper_efdmul(uint64_t op1, uint64_t op2)
+{
+    CPU_DoubleU u1, u2;
+
+    u1.ll = op1;
+    u2.ll = op2;
+    u1.d = float64_mul(u1.d, u2.d, &env->vec_status);
+    return u1.ll;
+}
+
+uint64_t helper_efddiv(uint64_t op1, uint64_t op2)
+{
+    CPU_DoubleU u1, u2;
+
+    u1.ll = op1;
+    u2.ll = op2;
+    u1.d = float64_div(u1.d, u2.d, &env->vec_status);
+    return u1.ll;
+}
+
+/* Double precision floating point helpers */
+uint32_t helper_efdtstlt(uint64_t op1, uint64_t op2)
+{
+    CPU_DoubleU u1, u2;
+
+    u1.ll = op1;
+    u2.ll = op2;
+    return float64_lt(u1.d, u2.d, &env->vec_status) ? 4 : 0;
+}
+
+uint32_t helper_efdtstgt(uint64_t op1, uint64_t op2)
+{
+    CPU_DoubleU u1, u2;
+
+    u1.ll = op1;
+    u2.ll = op2;
+    return float64_le(u1.d, u2.d, &env->vec_status) ? 0 : 4;
+}
+
+uint32_t helper_efdtsteq(uint64_t op1, uint64_t op2)
+{
+    CPU_DoubleU u1, u2;
+
+    u1.ll = op1;
+    u2.ll = op2;
+    return float64_eq_quiet(u1.d, u2.d, &env->vec_status) ? 4 : 0;
+}
+
+uint32_t helper_efdcmplt(uint64_t op1, uint64_t op2)
+{
+    /* XXX: TODO: test special values (NaN, infinites, ...) */
+    return helper_efdtstlt(op1, op2);
+}
+
+uint32_t helper_efdcmpgt(uint64_t op1, uint64_t op2)
+{
+    /* XXX: TODO: test special values (NaN, infinites, ...) */
+    return helper_efdtstgt(op1, op2);
+}
+
+uint32_t helper_efdcmpeq(uint64_t op1, uint64_t op2)
+{
+    /* XXX: TODO: test special values (NaN, infinites, ...) */
+    return helper_efdtsteq(op1, op2);
+}
diff --git a/target-ppc/op_helper.c b/target-ppc/op_helper.c
index eedbb42..3f677f6 100644
--- a/target-ppc/op_helper.c
+++ b/target-ppc/op_helper.c
@@ -547,1099 +547,6 @@ target_ulong helper_popcntw(target_ulong val)
 #endif
 
 /*****************************************************************************/
-/* Floating point operations helpers */
-uint64_t helper_float32_to_float64(uint32_t arg)
-{
-    CPU_FloatU f;
-    CPU_DoubleU d;
-
-    f.l = arg;
-    d.d = float32_to_float64(f.f, &env->fp_status);
-    return d.ll;
-}
-
-uint32_t helper_float64_to_float32(uint64_t arg)
-{
-    CPU_FloatU f;
-    CPU_DoubleU d;
-
-    d.ll = arg;
-    f.f = float64_to_float32(d.d, &env->fp_status);
-    return f.l;
-}
-
-static inline int isden(float64 d)
-{
-    CPU_DoubleU u;
-
-    u.d = d;
-
-    return ((u.ll >> 52) & 0x7FF) == 0;
-}
-
-uint32_t helper_compute_fprf(uint64_t arg, uint32_t set_fprf)
-{
-    CPU_DoubleU farg;
-    int isneg;
-    int ret;
-
-    farg.ll = arg;
-    isneg = float64_is_neg(farg.d);
-    if (unlikely(float64_is_any_nan(farg.d))) {
-        if (float64_is_signaling_nan(farg.d)) {
-            /* Signaling NaN: flags are undefined */
-            ret = 0x00;
-        } else {
-            /* Quiet NaN */
-            ret = 0x11;
-        }
-    } else if (unlikely(float64_is_infinity(farg.d))) {
-        /* +/- infinity */
-        if (isneg) {
-            ret = 0x09;
-        } else {
-            ret = 0x05;
-        }
-    } else {
-        if (float64_is_zero(farg.d)) {
-            /* +/- zero */
-            if (isneg) {
-                ret = 0x12;
-            } else {
-                ret = 0x02;
-            }
-        } else {
-            if (isden(farg.d)) {
-                /* Denormalized numbers */
-                ret = 0x10;
-            } else {
-                /* Normalized numbers */
-                ret = 0x00;
-            }
-            if (isneg) {
-                ret |= 0x08;
-            } else {
-                ret |= 0x04;
-            }
-        }
-    }
-    if (set_fprf) {
-        /* We update FPSCR_FPRF */
-        env->fpscr &= ~(0x1F << FPSCR_FPRF);
-        env->fpscr |= ret << FPSCR_FPRF;
-    }
-    /* We just need fpcc to update Rc1 */
-    return ret & 0xF;
-}
-
-/* Floating-point invalid operations exception */
-static inline uint64_t fload_invalid_op_excp(int op)
-{
-    uint64_t ret = 0;
-    int ve;
-
-    ve = fpscr_ve;
-    switch (op) {
-    case POWERPC_EXCP_FP_VXSNAN:
-        env->fpscr |= 1 << FPSCR_VXSNAN;
-        break;
-    case POWERPC_EXCP_FP_VXSOFT:
-        env->fpscr |= 1 << FPSCR_VXSOFT;
-        break;
-    case POWERPC_EXCP_FP_VXISI:
-        /* Magnitude subtraction of infinities */
-        env->fpscr |= 1 << FPSCR_VXISI;
-        goto update_arith;
-    case POWERPC_EXCP_FP_VXIDI:
-        /* Division of infinity by infinity */
-        env->fpscr |= 1 << FPSCR_VXIDI;
-        goto update_arith;
-    case POWERPC_EXCP_FP_VXZDZ:
-        /* Division of zero by zero */
-        env->fpscr |= 1 << FPSCR_VXZDZ;
-        goto update_arith;
-    case POWERPC_EXCP_FP_VXIMZ:
-        /* Multiplication of zero by infinity */
-        env->fpscr |= 1 << FPSCR_VXIMZ;
-        goto update_arith;
-    case POWERPC_EXCP_FP_VXVC:
-        /* Ordered comparison of NaN */
-        env->fpscr |= 1 << FPSCR_VXVC;
-        env->fpscr &= ~(0xF << FPSCR_FPCC);
-        env->fpscr |= 0x11 << FPSCR_FPCC;
-        /* We must update the target FPR before raising the exception */
-        if (ve != 0) {
-            env->exception_index = POWERPC_EXCP_PROGRAM;
-            env->error_code = POWERPC_EXCP_FP | POWERPC_EXCP_FP_VXVC;
-            /* Update the floating-point enabled exception summary */
-            env->fpscr |= 1 << FPSCR_FEX;
-            /* Exception is differed */
-            ve = 0;
-        }
-        break;
-    case POWERPC_EXCP_FP_VXSQRT:
-        /* Square root of a negative number */
-        env->fpscr |= 1 << FPSCR_VXSQRT;
-    update_arith:
-        env->fpscr &= ~((1 << FPSCR_FR) | (1 << FPSCR_FI));
-        if (ve == 0) {
-            /* Set the result to quiet NaN */
-            ret = 0x7FF8000000000000ULL;
-            env->fpscr &= ~(0xF << FPSCR_FPCC);
-            env->fpscr |= 0x11 << FPSCR_FPCC;
-        }
-        break;
-    case POWERPC_EXCP_FP_VXCVI:
-        /* Invalid conversion */
-        env->fpscr |= 1 << FPSCR_VXCVI;
-        env->fpscr &= ~((1 << FPSCR_FR) | (1 << FPSCR_FI));
-        if (ve == 0) {
-            /* Set the result to quiet NaN */
-            ret = 0x7FF8000000000000ULL;
-            env->fpscr &= ~(0xF << FPSCR_FPCC);
-            env->fpscr |= 0x11 << FPSCR_FPCC;
-        }
-        break;
-    }
-    /* Update the floating-point invalid operation summary */
-    env->fpscr |= 1 << FPSCR_VX;
-    /* Update the floating-point exception summary */
-    env->fpscr |= 1 << FPSCR_FX;
-    if (ve != 0) {
-        /* Update the floating-point enabled exception summary */
-        env->fpscr |= 1 << FPSCR_FEX;
-        if (msr_fe0 != 0 || msr_fe1 != 0) {
-            helper_raise_exception_err(env, POWERPC_EXCP_PROGRAM,
-                                       POWERPC_EXCP_FP | op);
-        }
-    }
-    return ret;
-}
-
-static inline void float_zero_divide_excp(void)
-{
-    env->fpscr |= 1 << FPSCR_ZX;
-    env->fpscr &= ~((1 << FPSCR_FR) | (1 << FPSCR_FI));
-    /* Update the floating-point exception summary */
-    env->fpscr |= 1 << FPSCR_FX;
-    if (fpscr_ze != 0) {
-        /* Update the floating-point enabled exception summary */
-        env->fpscr |= 1 << FPSCR_FEX;
-        if (msr_fe0 != 0 || msr_fe1 != 0) {
-            helper_raise_exception_err(env, POWERPC_EXCP_PROGRAM,
-                                       POWERPC_EXCP_FP | POWERPC_EXCP_FP_ZX);
-        }
-    }
-}
-
-static inline void float_overflow_excp(void)
-{
-    env->fpscr |= 1 << FPSCR_OX;
-    /* Update the floating-point exception summary */
-    env->fpscr |= 1 << FPSCR_FX;
-    if (fpscr_oe != 0) {
-        /* XXX: should adjust the result */
-        /* Update the floating-point enabled exception summary */
-        env->fpscr |= 1 << FPSCR_FEX;
-        /* We must update the target FPR before raising the exception */
-        env->exception_index = POWERPC_EXCP_PROGRAM;
-        env->error_code = POWERPC_EXCP_FP | POWERPC_EXCP_FP_OX;
-    } else {
-        env->fpscr |= 1 << FPSCR_XX;
-        env->fpscr |= 1 << FPSCR_FI;
-    }
-}
-
-static inline void float_underflow_excp(void)
-{
-    env->fpscr |= 1 << FPSCR_UX;
-    /* Update the floating-point exception summary */
-    env->fpscr |= 1 << FPSCR_FX;
-    if (fpscr_ue != 0) {
-        /* XXX: should adjust the result */
-        /* Update the floating-point enabled exception summary */
-        env->fpscr |= 1 << FPSCR_FEX;
-        /* We must update the target FPR before raising the exception */
-        env->exception_index = POWERPC_EXCP_PROGRAM;
-        env->error_code = POWERPC_EXCP_FP | POWERPC_EXCP_FP_UX;
-    }
-}
-
-static inline void float_inexact_excp(void)
-{
-    env->fpscr |= 1 << FPSCR_XX;
-    /* Update the floating-point exception summary */
-    env->fpscr |= 1 << FPSCR_FX;
-    if (fpscr_xe != 0) {
-        /* Update the floating-point enabled exception summary */
-        env->fpscr |= 1 << FPSCR_FEX;
-        /* We must update the target FPR before raising the exception */
-        env->exception_index = POWERPC_EXCP_PROGRAM;
-        env->error_code = POWERPC_EXCP_FP | POWERPC_EXCP_FP_XX;
-    }
-}
-
-static inline void fpscr_set_rounding_mode(void)
-{
-    int rnd_type;
-
-    /* Set rounding mode */
-    switch (fpscr_rn) {
-    case 0:
-        /* Best approximation (round to nearest) */
-        rnd_type = float_round_nearest_even;
-        break;
-    case 1:
-        /* Smaller magnitude (round toward zero) */
-        rnd_type = float_round_to_zero;
-        break;
-    case 2:
-        /* Round toward +infinite */
-        rnd_type = float_round_up;
-        break;
-    default:
-    case 3:
-        /* Round toward -infinite */
-        rnd_type = float_round_down;
-        break;
-    }
-    set_float_rounding_mode(rnd_type, &env->fp_status);
-}
-
-void helper_fpscr_clrbit(uint32_t bit)
-{
-    int prev;
-
-    prev = (env->fpscr >> bit) & 1;
-    env->fpscr &= ~(1 << bit);
-    if (prev == 1) {
-        switch (bit) {
-        case FPSCR_RN1:
-        case FPSCR_RN:
-            fpscr_set_rounding_mode();
-            break;
-        default:
-            break;
-        }
-    }
-}
-
-void helper_fpscr_setbit(uint32_t bit)
-{
-    int prev;
-
-    prev = (env->fpscr >> bit) & 1;
-    env->fpscr |= 1 << bit;
-    if (prev == 0) {
-        switch (bit) {
-        case FPSCR_VX:
-            env->fpscr |= 1 << FPSCR_FX;
-            if (fpscr_ve) {
-                goto raise_ve;
-            }
-        case FPSCR_OX:
-            env->fpscr |= 1 << FPSCR_FX;
-            if (fpscr_oe) {
-                goto raise_oe;
-            }
-            break;
-        case FPSCR_UX:
-            env->fpscr |= 1 << FPSCR_FX;
-            if (fpscr_ue) {
-                goto raise_ue;
-            }
-            break;
-        case FPSCR_ZX:
-            env->fpscr |= 1 << FPSCR_FX;
-            if (fpscr_ze) {
-                goto raise_ze;
-            }
-            break;
-        case FPSCR_XX:
-            env->fpscr |= 1 << FPSCR_FX;
-            if (fpscr_xe) {
-                goto raise_xe;
-            }
-            break;
-        case FPSCR_VXSNAN:
-        case FPSCR_VXISI:
-        case FPSCR_VXIDI:
-        case FPSCR_VXZDZ:
-        case FPSCR_VXIMZ:
-        case FPSCR_VXVC:
-        case FPSCR_VXSOFT:
-        case FPSCR_VXSQRT:
-        case FPSCR_VXCVI:
-            env->fpscr |= 1 << FPSCR_VX;
-            env->fpscr |= 1 << FPSCR_FX;
-            if (fpscr_ve != 0) {
-                goto raise_ve;
-            }
-            break;
-        case FPSCR_VE:
-            if (fpscr_vx != 0) {
-            raise_ve:
-                env->error_code = POWERPC_EXCP_FP;
-                if (fpscr_vxsnan) {
-                    env->error_code |= POWERPC_EXCP_FP_VXSNAN;
-                }
-                if (fpscr_vxisi) {
-                    env->error_code |= POWERPC_EXCP_FP_VXISI;
-                }
-                if (fpscr_vxidi) {
-                    env->error_code |= POWERPC_EXCP_FP_VXIDI;
-                }
-                if (fpscr_vxzdz) {
-                    env->error_code |= POWERPC_EXCP_FP_VXZDZ;
-                }
-                if (fpscr_vximz) {
-                    env->error_code |= POWERPC_EXCP_FP_VXIMZ;
-                }
-                if (fpscr_vxvc) {
-                    env->error_code |= POWERPC_EXCP_FP_VXVC;
-                }
-                if (fpscr_vxsoft) {
-                    env->error_code |= POWERPC_EXCP_FP_VXSOFT;
-                }
-                if (fpscr_vxsqrt) {
-                    env->error_code |= POWERPC_EXCP_FP_VXSQRT;
-                }
-                if (fpscr_vxcvi) {
-                    env->error_code |= POWERPC_EXCP_FP_VXCVI;
-                }
-                goto raise_excp;
-            }
-            break;
-        case FPSCR_OE:
-            if (fpscr_ox != 0) {
-            raise_oe:
-                env->error_code = POWERPC_EXCP_FP | POWERPC_EXCP_FP_OX;
-                goto raise_excp;
-            }
-            break;
-        case FPSCR_UE:
-            if (fpscr_ux != 0) {
-            raise_ue:
-                env->error_code = POWERPC_EXCP_FP | POWERPC_EXCP_FP_UX;
-                goto raise_excp;
-            }
-            break;
-        case FPSCR_ZE:
-            if (fpscr_zx != 0) {
-            raise_ze:
-                env->error_code = POWERPC_EXCP_FP | POWERPC_EXCP_FP_ZX;
-                goto raise_excp;
-            }
-            break;
-        case FPSCR_XE:
-            if (fpscr_xx != 0) {
-            raise_xe:
-                env->error_code = POWERPC_EXCP_FP | POWERPC_EXCP_FP_XX;
-                goto raise_excp;
-            }
-            break;
-        case FPSCR_RN1:
-        case FPSCR_RN:
-            fpscr_set_rounding_mode();
-            break;
-        default:
-            break;
-        raise_excp:
-            /* Update the floating-point enabled exception summary */
-            env->fpscr |= 1 << FPSCR_FEX;
-            /* We have to update Rc1 before raising the exception */
-            env->exception_index = POWERPC_EXCP_PROGRAM;
-            break;
-        }
-    }
-}
-
-void helper_store_fpscr(uint64_t arg, uint32_t mask)
-{
-    /*
-     * We use only the 32 LSB of the incoming fpr
-     */
-    uint32_t prev, new;
-    int i;
-
-    prev = env->fpscr;
-    new = (uint32_t)arg;
-    new &= ~0x60000000;
-    new |= prev & 0x60000000;
-    for (i = 0; i < 8; i++) {
-        if (mask & (1 << i)) {
-            env->fpscr &= ~(0xF << (4 * i));
-            env->fpscr |= new & (0xF << (4 * i));
-        }
-    }
-    /* Update VX and FEX */
-    if (fpscr_ix != 0) {
-        env->fpscr |= 1 << FPSCR_VX;
-    } else {
-        env->fpscr &= ~(1 << FPSCR_VX);
-    }
-    if ((fpscr_ex & fpscr_eex) != 0) {
-        env->fpscr |= 1 << FPSCR_FEX;
-        env->exception_index = POWERPC_EXCP_PROGRAM;
-        /* XXX: we should compute it properly */
-        env->error_code = POWERPC_EXCP_FP;
-    } else {
-        env->fpscr &= ~(1 << FPSCR_FEX);
-    }
-    fpscr_set_rounding_mode();
-}
-
-void helper_float_check_status(void)
-{
-    if (env->exception_index == POWERPC_EXCP_PROGRAM &&
-        (env->error_code & POWERPC_EXCP_FP)) {
-        /* Differred floating-point exception after target FPR update */
-        if (msr_fe0 != 0 || msr_fe1 != 0) {
-            helper_raise_exception_err(env, env->exception_index,
-                                       env->error_code);
-        }
-    } else {
-        int status = get_float_exception_flags(&env->fp_status);
-        if (status & float_flag_divbyzero) {
-            float_zero_divide_excp();
-        } else if (status & float_flag_overflow) {
-            float_overflow_excp();
-        } else if (status & float_flag_underflow) {
-            float_underflow_excp();
-        } else if (status & float_flag_inexact) {
-            float_inexact_excp();
-        }
-    }
-}
-
-void helper_reset_fpstatus(void)
-{
-    set_float_exception_flags(0, &env->fp_status);
-}
-
-/* fadd - fadd. */
-uint64_t helper_fadd(uint64_t arg1, uint64_t arg2)
-{
-    CPU_DoubleU farg1, farg2;
-
-    farg1.ll = arg1;
-    farg2.ll = arg2;
-
-    if (unlikely(float64_is_infinity(farg1.d) && float64_is_infinity(farg2.d) &&
-                 float64_is_neg(farg1.d) != float64_is_neg(farg2.d))) {
-        /* Magnitude subtraction of infinities */
-        farg1.ll = fload_invalid_op_excp(POWERPC_EXCP_FP_VXISI);
-    } else {
-        if (unlikely(float64_is_signaling_nan(farg1.d) ||
-                     float64_is_signaling_nan(farg2.d))) {
-            /* sNaN addition */
-            fload_invalid_op_excp(POWERPC_EXCP_FP_VXSNAN);
-        }
-        farg1.d = float64_add(farg1.d, farg2.d, &env->fp_status);
-    }
-
-    return farg1.ll;
-}
-
-/* fsub - fsub. */
-uint64_t helper_fsub(uint64_t arg1, uint64_t arg2)
-{
-    CPU_DoubleU farg1, farg2;
-
-    farg1.ll = arg1;
-    farg2.ll = arg2;
-
-    if (unlikely(float64_is_infinity(farg1.d) && float64_is_infinity(farg2.d) &&
-                 float64_is_neg(farg1.d) == float64_is_neg(farg2.d))) {
-        /* Magnitude subtraction of infinities */
-        farg1.ll = fload_invalid_op_excp(POWERPC_EXCP_FP_VXISI);
-    } else {
-        if (unlikely(float64_is_signaling_nan(farg1.d) ||
-                     float64_is_signaling_nan(farg2.d))) {
-            /* sNaN subtraction */
-            fload_invalid_op_excp(POWERPC_EXCP_FP_VXSNAN);
-        }
-        farg1.d = float64_sub(farg1.d, farg2.d, &env->fp_status);
-    }
-
-    return farg1.ll;
-}
-
-/* fmul - fmul. */
-uint64_t helper_fmul(uint64_t arg1, uint64_t arg2)
-{
-    CPU_DoubleU farg1, farg2;
-
-    farg1.ll = arg1;
-    farg2.ll = arg2;
-
-    if (unlikely((float64_is_infinity(farg1.d) && float64_is_zero(farg2.d)) ||
-                 (float64_is_zero(farg1.d) && float64_is_infinity(farg2.d)))) {
-        /* Multiplication of zero by infinity */
-        farg1.ll = fload_invalid_op_excp(POWERPC_EXCP_FP_VXIMZ);
-    } else {
-        if (unlikely(float64_is_signaling_nan(farg1.d) ||
-                     float64_is_signaling_nan(farg2.d))) {
-            /* sNaN multiplication */
-            fload_invalid_op_excp(POWERPC_EXCP_FP_VXSNAN);
-        }
-        farg1.d = float64_mul(farg1.d, farg2.d, &env->fp_status);
-    }
-
-    return farg1.ll;
-}
-
-/* fdiv - fdiv. */
-uint64_t helper_fdiv(uint64_t arg1, uint64_t arg2)
-{
-    CPU_DoubleU farg1, farg2;
-
-    farg1.ll = arg1;
-    farg2.ll = arg2;
-
-    if (unlikely(float64_is_infinity(farg1.d) &&
-                 float64_is_infinity(farg2.d))) {
-        /* Division of infinity by infinity */
-        farg1.ll = fload_invalid_op_excp(POWERPC_EXCP_FP_VXIDI);
-    } else if (unlikely(float64_is_zero(farg1.d) && float64_is_zero(farg2.d))) {
-        /* Division of zero by zero */
-        farg1.ll = fload_invalid_op_excp(POWERPC_EXCP_FP_VXZDZ);
-    } else {
-        if (unlikely(float64_is_signaling_nan(farg1.d) ||
-                     float64_is_signaling_nan(farg2.d))) {
-            /* sNaN division */
-            fload_invalid_op_excp(POWERPC_EXCP_FP_VXSNAN);
-        }
-        farg1.d = float64_div(farg1.d, farg2.d, &env->fp_status);
-    }
-
-    return farg1.ll;
-}
-
-/* fabs */
-uint64_t helper_fabs(uint64_t arg)
-{
-    CPU_DoubleU farg;
-
-    farg.ll = arg;
-    farg.d = float64_abs(farg.d);
-    return farg.ll;
-}
-
-/* fnabs */
-uint64_t helper_fnabs(uint64_t arg)
-{
-    CPU_DoubleU farg;
-
-    farg.ll = arg;
-    farg.d = float64_abs(farg.d);
-    farg.d = float64_chs(farg.d);
-    return farg.ll;
-}
-
-/* fneg */
-uint64_t helper_fneg(uint64_t arg)
-{
-    CPU_DoubleU farg;
-
-    farg.ll = arg;
-    farg.d = float64_chs(farg.d);
-    return farg.ll;
-}
-
-/* fctiw - fctiw. */
-uint64_t helper_fctiw(uint64_t arg)
-{
-    CPU_DoubleU farg;
-
-    farg.ll = arg;
-
-    if (unlikely(float64_is_signaling_nan(farg.d))) {
-        /* sNaN conversion */
-        farg.ll = fload_invalid_op_excp(POWERPC_EXCP_FP_VXSNAN |
-                                        POWERPC_EXCP_FP_VXCVI);
-    } else if (unlikely(float64_is_quiet_nan(farg.d) ||
-                        float64_is_infinity(farg.d))) {
-        /* qNan / infinity conversion */
-        farg.ll = fload_invalid_op_excp(POWERPC_EXCP_FP_VXCVI);
-    } else {
-        farg.ll = float64_to_int32(farg.d, &env->fp_status);
-        /* XXX: higher bits are not supposed to be significant.
-         *     to make tests easier, return the same as a real PowerPC 750
-         */
-        farg.ll |= 0xFFF80000ULL << 32;
-    }
-    return farg.ll;
-}
-
-/* fctiwz - fctiwz. */
-uint64_t helper_fctiwz(uint64_t arg)
-{
-    CPU_DoubleU farg;
-
-    farg.ll = arg;
-
-    if (unlikely(float64_is_signaling_nan(farg.d))) {
-        /* sNaN conversion */
-        farg.ll = fload_invalid_op_excp(POWERPC_EXCP_FP_VXSNAN |
-                                        POWERPC_EXCP_FP_VXCVI);
-    } else if (unlikely(float64_is_quiet_nan(farg.d) ||
-                        float64_is_infinity(farg.d))) {
-        /* qNan / infinity conversion */
-        farg.ll = fload_invalid_op_excp(POWERPC_EXCP_FP_VXCVI);
-    } else {
-        farg.ll = float64_to_int32_round_to_zero(farg.d, &env->fp_status);
-        /* XXX: higher bits are not supposed to be significant.
-         *     to make tests easier, return the same as a real PowerPC 750
-         */
-        farg.ll |= 0xFFF80000ULL << 32;
-    }
-    return farg.ll;
-}
-
-#if defined(TARGET_PPC64)
-/* fcfid - fcfid. */
-uint64_t helper_fcfid(uint64_t arg)
-{
-    CPU_DoubleU farg;
-
-    farg.d = int64_to_float64(arg, &env->fp_status);
-    return farg.ll;
-}
-
-/* fctid - fctid. */
-uint64_t helper_fctid(uint64_t arg)
-{
-    CPU_DoubleU farg;
-
-    farg.ll = arg;
-
-    if (unlikely(float64_is_signaling_nan(farg.d))) {
-        /* sNaN conversion */
-        farg.ll = fload_invalid_op_excp(POWERPC_EXCP_FP_VXSNAN |
-                                        POWERPC_EXCP_FP_VXCVI);
-    } else if (unlikely(float64_is_quiet_nan(farg.d) ||
-                        float64_is_infinity(farg.d))) {
-        /* qNan / infinity conversion */
-        farg.ll = fload_invalid_op_excp(POWERPC_EXCP_FP_VXCVI);
-    } else {
-        farg.ll = float64_to_int64(farg.d, &env->fp_status);
-    }
-    return farg.ll;
-}
-
-/* fctidz - fctidz. */
-uint64_t helper_fctidz(uint64_t arg)
-{
-    CPU_DoubleU farg;
-
-    farg.ll = arg;
-
-    if (unlikely(float64_is_signaling_nan(farg.d))) {
-        /* sNaN conversion */
-        farg.ll = fload_invalid_op_excp(POWERPC_EXCP_FP_VXSNAN |
-                                        POWERPC_EXCP_FP_VXCVI);
-    } else if (unlikely(float64_is_quiet_nan(farg.d) ||
-                        float64_is_infinity(farg.d))) {
-        /* qNan / infinity conversion */
-        farg.ll = fload_invalid_op_excp(POWERPC_EXCP_FP_VXCVI);
-    } else {
-        farg.ll = float64_to_int64_round_to_zero(farg.d, &env->fp_status);
-    }
-    return farg.ll;
-}
-
-#endif
-
-static inline uint64_t do_fri(uint64_t arg, int rounding_mode)
-{
-    CPU_DoubleU farg;
-
-    farg.ll = arg;
-
-    if (unlikely(float64_is_signaling_nan(farg.d))) {
-        /* sNaN round */
-        farg.ll = fload_invalid_op_excp(POWERPC_EXCP_FP_VXSNAN |
-                                        POWERPC_EXCP_FP_VXCVI);
-    } else if (unlikely(float64_is_quiet_nan(farg.d) ||
-                        float64_is_infinity(farg.d))) {
-        /* qNan / infinity round */
-        farg.ll = fload_invalid_op_excp(POWERPC_EXCP_FP_VXCVI);
-    } else {
-        set_float_rounding_mode(rounding_mode, &env->fp_status);
-        farg.ll = float64_round_to_int(farg.d, &env->fp_status);
-        /* Restore rounding mode from FPSCR */
-        fpscr_set_rounding_mode();
-    }
-    return farg.ll;
-}
-
-uint64_t helper_frin(uint64_t arg)
-{
-    return do_fri(arg, float_round_nearest_even);
-}
-
-uint64_t helper_friz(uint64_t arg)
-{
-    return do_fri(arg, float_round_to_zero);
-}
-
-uint64_t helper_frip(uint64_t arg)
-{
-    return do_fri(arg, float_round_up);
-}
-
-uint64_t helper_frim(uint64_t arg)
-{
-    return do_fri(arg, float_round_down);
-}
-
-/* fmadd - fmadd. */
-uint64_t helper_fmadd(uint64_t arg1, uint64_t arg2, uint64_t arg3)
-{
-    CPU_DoubleU farg1, farg2, farg3;
-
-    farg1.ll = arg1;
-    farg2.ll = arg2;
-    farg3.ll = arg3;
-
-    if (unlikely((float64_is_infinity(farg1.d) && float64_is_zero(farg2.d)) ||
-                 (float64_is_zero(farg1.d) && float64_is_infinity(farg2.d)))) {
-        /* Multiplication of zero by infinity */
-        farg1.ll = fload_invalid_op_excp(POWERPC_EXCP_FP_VXIMZ);
-    } else {
-        if (unlikely(float64_is_signaling_nan(farg1.d) ||
-                     float64_is_signaling_nan(farg2.d) ||
-                     float64_is_signaling_nan(farg3.d))) {
-            /* sNaN operation */
-            fload_invalid_op_excp(POWERPC_EXCP_FP_VXSNAN);
-        }
-        /* This is the way the PowerPC specification defines it */
-        float128 ft0_128, ft1_128;
-
-        ft0_128 = float64_to_float128(farg1.d, &env->fp_status);
-        ft1_128 = float64_to_float128(farg2.d, &env->fp_status);
-        ft0_128 = float128_mul(ft0_128, ft1_128, &env->fp_status);
-        if (unlikely(float128_is_infinity(ft0_128) &&
-                     float64_is_infinity(farg3.d) &&
-                     float128_is_neg(ft0_128) != float64_is_neg(farg3.d))) {
-            /* Magnitude subtraction of infinities */
-            farg1.ll = fload_invalid_op_excp(POWERPC_EXCP_FP_VXISI);
-        } else {
-            ft1_128 = float64_to_float128(farg3.d, &env->fp_status);
-            ft0_128 = float128_add(ft0_128, ft1_128, &env->fp_status);
-            farg1.d = float128_to_float64(ft0_128, &env->fp_status);
-        }
-    }
-
-    return farg1.ll;
-}
-
-/* fmsub - fmsub. */
-uint64_t helper_fmsub(uint64_t arg1, uint64_t arg2, uint64_t arg3)
-{
-    CPU_DoubleU farg1, farg2, farg3;
-
-    farg1.ll = arg1;
-    farg2.ll = arg2;
-    farg3.ll = arg3;
-
-    if (unlikely((float64_is_infinity(farg1.d) && float64_is_zero(farg2.d)) ||
-                 (float64_is_zero(farg1.d) &&
-                  float64_is_infinity(farg2.d)))) {
-        /* Multiplication of zero by infinity */
-        farg1.ll = fload_invalid_op_excp(POWERPC_EXCP_FP_VXIMZ);
-    } else {
-        if (unlikely(float64_is_signaling_nan(farg1.d) ||
-                     float64_is_signaling_nan(farg2.d) ||
-                     float64_is_signaling_nan(farg3.d))) {
-            /* sNaN operation */
-            fload_invalid_op_excp(POWERPC_EXCP_FP_VXSNAN);
-        }
-        /* This is the way the PowerPC specification defines it */
-        float128 ft0_128, ft1_128;
-
-        ft0_128 = float64_to_float128(farg1.d, &env->fp_status);
-        ft1_128 = float64_to_float128(farg2.d, &env->fp_status);
-        ft0_128 = float128_mul(ft0_128, ft1_128, &env->fp_status);
-        if (unlikely(float128_is_infinity(ft0_128) &&
-                     float64_is_infinity(farg3.d) &&
-                     float128_is_neg(ft0_128) == float64_is_neg(farg3.d))) {
-            /* Magnitude subtraction of infinities */
-            farg1.ll = fload_invalid_op_excp(POWERPC_EXCP_FP_VXISI);
-        } else {
-            ft1_128 = float64_to_float128(farg3.d, &env->fp_status);
-            ft0_128 = float128_sub(ft0_128, ft1_128, &env->fp_status);
-            farg1.d = float128_to_float64(ft0_128, &env->fp_status);
-        }
-    }
-    return farg1.ll;
-}
-
-/* fnmadd - fnmadd. */
-uint64_t helper_fnmadd(uint64_t arg1, uint64_t arg2, uint64_t arg3)
-{
-    CPU_DoubleU farg1, farg2, farg3;
-
-    farg1.ll = arg1;
-    farg2.ll = arg2;
-    farg3.ll = arg3;
-
-    if (unlikely((float64_is_infinity(farg1.d) && float64_is_zero(farg2.d)) ||
-                 (float64_is_zero(farg1.d) && float64_is_infinity(farg2.d)))) {
-        /* Multiplication of zero by infinity */
-        farg1.ll = fload_invalid_op_excp(POWERPC_EXCP_FP_VXIMZ);
-    } else {
-        if (unlikely(float64_is_signaling_nan(farg1.d) ||
-                     float64_is_signaling_nan(farg2.d) ||
-                     float64_is_signaling_nan(farg3.d))) {
-            /* sNaN operation */
-            fload_invalid_op_excp(POWERPC_EXCP_FP_VXSNAN);
-        }
-        /* This is the way the PowerPC specification defines it */
-        float128 ft0_128, ft1_128;
-
-        ft0_128 = float64_to_float128(farg1.d, &env->fp_status);
-        ft1_128 = float64_to_float128(farg2.d, &env->fp_status);
-        ft0_128 = float128_mul(ft0_128, ft1_128, &env->fp_status);
-        if (unlikely(float128_is_infinity(ft0_128) &&
-                     float64_is_infinity(farg3.d) &&
-                     float128_is_neg(ft0_128) != float64_is_neg(farg3.d))) {
-            /* Magnitude subtraction of infinities */
-            farg1.ll = fload_invalid_op_excp(POWERPC_EXCP_FP_VXISI);
-        } else {
-            ft1_128 = float64_to_float128(farg3.d, &env->fp_status);
-            ft0_128 = float128_add(ft0_128, ft1_128, &env->fp_status);
-            farg1.d = float128_to_float64(ft0_128, &env->fp_status);
-        }
-        if (likely(!float64_is_any_nan(farg1.d))) {
-            farg1.d = float64_chs(farg1.d);
-        }
-    }
-    return farg1.ll;
-}
-
-/* fnmsub - fnmsub. */
-uint64_t helper_fnmsub(uint64_t arg1, uint64_t arg2, uint64_t arg3)
-{
-    CPU_DoubleU farg1, farg2, farg3;
-
-    farg1.ll = arg1;
-    farg2.ll = arg2;
-    farg3.ll = arg3;
-
-    if (unlikely((float64_is_infinity(farg1.d) && float64_is_zero(farg2.d)) ||
-                 (float64_is_zero(farg1.d) &&
-                  float64_is_infinity(farg2.d)))) {
-        /* Multiplication of zero by infinity */
-        farg1.ll = fload_invalid_op_excp(POWERPC_EXCP_FP_VXIMZ);
-    } else {
-        if (unlikely(float64_is_signaling_nan(farg1.d) ||
-                     float64_is_signaling_nan(farg2.d) ||
-                     float64_is_signaling_nan(farg3.d))) {
-            /* sNaN operation */
-            fload_invalid_op_excp(POWERPC_EXCP_FP_VXSNAN);
-        }
-        /* This is the way the PowerPC specification defines it */
-        float128 ft0_128, ft1_128;
-
-        ft0_128 = float64_to_float128(farg1.d, &env->fp_status);
-        ft1_128 = float64_to_float128(farg2.d, &env->fp_status);
-        ft0_128 = float128_mul(ft0_128, ft1_128, &env->fp_status);
-        if (unlikely(float128_is_infinity(ft0_128) &&
-                     float64_is_infinity(farg3.d) &&
-                     float128_is_neg(ft0_128) == float64_is_neg(farg3.d))) {
-            /* Magnitude subtraction of infinities */
-            farg1.ll = fload_invalid_op_excp(POWERPC_EXCP_FP_VXISI);
-        } else {
-            ft1_128 = float64_to_float128(farg3.d, &env->fp_status);
-            ft0_128 = float128_sub(ft0_128, ft1_128, &env->fp_status);
-            farg1.d = float128_to_float64(ft0_128, &env->fp_status);
-        }
-        if (likely(!float64_is_any_nan(farg1.d))) {
-            farg1.d = float64_chs(farg1.d);
-        }
-    }
-    return farg1.ll;
-}
-
-/* frsp - frsp. */
-uint64_t helper_frsp(uint64_t arg)
-{
-    CPU_DoubleU farg;
-    float32 f32;
-
-    farg.ll = arg;
-
-    if (unlikely(float64_is_signaling_nan(farg.d))) {
-        /* sNaN square root */
-        fload_invalid_op_excp(POWERPC_EXCP_FP_VXSNAN);
-    }
-    f32 = float64_to_float32(farg.d, &env->fp_status);
-    farg.d = float32_to_float64(f32, &env->fp_status);
-
-    return farg.ll;
-}
-
-/* fsqrt - fsqrt. */
-uint64_t helper_fsqrt(uint64_t arg)
-{
-    CPU_DoubleU farg;
-
-    farg.ll = arg;
-
-    if (unlikely(float64_is_neg(farg.d) && !float64_is_zero(farg.d))) {
-        /* Square root of a negative nonzero number */
-        farg.ll = fload_invalid_op_excp(POWERPC_EXCP_FP_VXSQRT);
-    } else {
-        if (unlikely(float64_is_signaling_nan(farg.d))) {
-            /* sNaN square root */
-            fload_invalid_op_excp(POWERPC_EXCP_FP_VXSNAN);
-        }
-        farg.d = float64_sqrt(farg.d, &env->fp_status);
-    }
-    return farg.ll;
-}
-
-/* fre - fre. */
-uint64_t helper_fre(uint64_t arg)
-{
-    CPU_DoubleU farg;
-
-    farg.ll = arg;
-
-    if (unlikely(float64_is_signaling_nan(farg.d))) {
-        /* sNaN reciprocal */
-        fload_invalid_op_excp(POWERPC_EXCP_FP_VXSNAN);
-    }
-    farg.d = float64_div(float64_one, farg.d, &env->fp_status);
-    return farg.d;
-}
-
-/* fres - fres. */
-uint64_t helper_fres(uint64_t arg)
-{
-    CPU_DoubleU farg;
-    float32 f32;
-
-    farg.ll = arg;
-
-    if (unlikely(float64_is_signaling_nan(farg.d))) {
-        /* sNaN reciprocal */
-        fload_invalid_op_excp(POWERPC_EXCP_FP_VXSNAN);
-    }
-    farg.d = float64_div(float64_one, farg.d, &env->fp_status);
-    f32 = float64_to_float32(farg.d, &env->fp_status);
-    farg.d = float32_to_float64(f32, &env->fp_status);
-
-    return farg.ll;
-}
-
-/* frsqrte  - frsqrte. */
-uint64_t helper_frsqrte(uint64_t arg)
-{
-    CPU_DoubleU farg;
-    float32 f32;
-
-    farg.ll = arg;
-
-    if (unlikely(float64_is_neg(farg.d) && !float64_is_zero(farg.d))) {
-        /* Reciprocal square root of a negative nonzero number */
-        farg.ll = fload_invalid_op_excp(POWERPC_EXCP_FP_VXSQRT);
-    } else {
-        if (unlikely(float64_is_signaling_nan(farg.d))) {
-            /* sNaN reciprocal square root */
-            fload_invalid_op_excp(POWERPC_EXCP_FP_VXSNAN);
-        }
-        farg.d = float64_sqrt(farg.d, &env->fp_status);
-        farg.d = float64_div(float64_one, farg.d, &env->fp_status);
-        f32 = float64_to_float32(farg.d, &env->fp_status);
-        farg.d = float32_to_float64(f32, &env->fp_status);
-    }
-    return farg.ll;
-}
-
-/* fsel - fsel. */
-uint64_t helper_fsel(uint64_t arg1, uint64_t arg2, uint64_t arg3)
-{
-    CPU_DoubleU farg1;
-
-    farg1.ll = arg1;
-
-    if ((!float64_is_neg(farg1.d) || float64_is_zero(farg1.d)) &&
-        !float64_is_any_nan(farg1.d)) {
-        return arg2;
-    } else {
-        return arg3;
-    }
-}
-
-void helper_fcmpu(uint64_t arg1, uint64_t arg2, uint32_t crfD)
-{
-    CPU_DoubleU farg1, farg2;
-    uint32_t ret = 0;
-
-    farg1.ll = arg1;
-    farg2.ll = arg2;
-
-    if (unlikely(float64_is_any_nan(farg1.d) ||
-                 float64_is_any_nan(farg2.d))) {
-        ret = 0x01UL;
-    } else if (float64_lt(farg1.d, farg2.d, &env->fp_status)) {
-        ret = 0x08UL;
-    } else if (!float64_le(farg1.d, farg2.d, &env->fp_status)) {
-        ret = 0x04UL;
-    } else {
-        ret = 0x02UL;
-    }
-
-    env->fpscr &= ~(0x0F << FPSCR_FPRF);
-    env->fpscr |= ret << FPSCR_FPRF;
-    env->crf[crfD] = ret;
-    if (unlikely(ret == 0x01UL
-                 && (float64_is_signaling_nan(farg1.d) ||
-                     float64_is_signaling_nan(farg2.d)))) {
-        /* sNaN comparison */
-        fload_invalid_op_excp(POWERPC_EXCP_FP_VXSNAN);
-    }
-}
-
-void helper_fcmpo(uint64_t arg1, uint64_t arg2, uint32_t crfD)
-{
-    CPU_DoubleU farg1, farg2;
-    uint32_t ret = 0;
-
-    farg1.ll = arg1;
-    farg2.ll = arg2;
-
-    if (unlikely(float64_is_any_nan(farg1.d) ||
-                 float64_is_any_nan(farg2.d))) {
-        ret = 0x01UL;
-    } else if (float64_lt(farg1.d, farg2.d, &env->fp_status)) {
-        ret = 0x08UL;
-    } else if (!float64_le(farg1.d, farg2.d, &env->fp_status)) {
-        ret = 0x04UL;
-    } else {
-        ret = 0x02UL;
-    }
-
-    env->fpscr &= ~(0x0F << FPSCR_FPRF);
-    env->fpscr |= ret << FPSCR_FPRF;
-    env->crf[crfD] = ret;
-    if (unlikely(ret == 0x01UL)) {
-        if (float64_is_signaling_nan(farg1.d) ||
-            float64_is_signaling_nan(farg2.d)) {
-            /* sNaN comparison */
-            fload_invalid_op_excp(POWERPC_EXCP_FP_VXSNAN |
-                                  POWERPC_EXCP_FP_VXVC);
-        } else {
-            /* qNaN comparison */
-            fload_invalid_op_excp(POWERPC_EXCP_FP_VXVC);
-        }
-    }
-}
-
-/*****************************************************************************/
 /* PowerPC 601 specific instructions (POWER bridge) */
 
 target_ulong helper_clcs(uint32_t arg)
@@ -3125,623 +2032,6 @@ uint32_t helper_cntlzw32(uint32_t val)
     return clz32(val);
 }
 
-/* Single-precision floating-point conversions */
-static inline uint32_t efscfsi(uint32_t val)
-{
-    CPU_FloatU u;
-
-    u.f = int32_to_float32(val, &env->vec_status);
-
-    return u.l;
-}
-
-static inline uint32_t efscfui(uint32_t val)
-{
-    CPU_FloatU u;
-
-    u.f = uint32_to_float32(val, &env->vec_status);
-
-    return u.l;
-}
-
-static inline int32_t efsctsi(uint32_t val)
-{
-    CPU_FloatU u;
-
-    u.l = val;
-    /* NaN are not treated the same way IEEE 754 does */
-    if (unlikely(float32_is_quiet_nan(u.f))) {
-        return 0;
-    }
-
-    return float32_to_int32(u.f, &env->vec_status);
-}
-
-static inline uint32_t efsctui(uint32_t val)
-{
-    CPU_FloatU u;
-
-    u.l = val;
-    /* NaN are not treated the same way IEEE 754 does */
-    if (unlikely(float32_is_quiet_nan(u.f))) {
-        return 0;
-    }
-
-    return float32_to_uint32(u.f, &env->vec_status);
-}
-
-static inline uint32_t efsctsiz(uint32_t val)
-{
-    CPU_FloatU u;
-
-    u.l = val;
-    /* NaN are not treated the same way IEEE 754 does */
-    if (unlikely(float32_is_quiet_nan(u.f))) {
-        return 0;
-    }
-
-    return float32_to_int32_round_to_zero(u.f, &env->vec_status);
-}
-
-static inline uint32_t efsctuiz(uint32_t val)
-{
-    CPU_FloatU u;
-
-    u.l = val;
-    /* NaN are not treated the same way IEEE 754 does */
-    if (unlikely(float32_is_quiet_nan(u.f))) {
-        return 0;
-    }
-
-    return float32_to_uint32_round_to_zero(u.f, &env->vec_status);
-}
-
-static inline uint32_t efscfsf(uint32_t val)
-{
-    CPU_FloatU u;
-    float32 tmp;
-
-    u.f = int32_to_float32(val, &env->vec_status);
-    tmp = int64_to_float32(1ULL << 32, &env->vec_status);
-    u.f = float32_div(u.f, tmp, &env->vec_status);
-
-    return u.l;
-}
-
-static inline uint32_t efscfuf(uint32_t val)
-{
-    CPU_FloatU u;
-    float32 tmp;
-
-    u.f = uint32_to_float32(val, &env->vec_status);
-    tmp = uint64_to_float32(1ULL << 32, &env->vec_status);
-    u.f = float32_div(u.f, tmp, &env->vec_status);
-
-    return u.l;
-}
-
-static inline uint32_t efsctsf(uint32_t val)
-{
-    CPU_FloatU u;
-    float32 tmp;
-
-    u.l = val;
-    /* NaN are not treated the same way IEEE 754 does */
-    if (unlikely(float32_is_quiet_nan(u.f))) {
-        return 0;
-    }
-    tmp = uint64_to_float32(1ULL << 32, &env->vec_status);
-    u.f = float32_mul(u.f, tmp, &env->vec_status);
-
-    return float32_to_int32(u.f, &env->vec_status);
-}
-
-static inline uint32_t efsctuf(uint32_t val)
-{
-    CPU_FloatU u;
-    float32 tmp;
-
-    u.l = val;
-    /* NaN are not treated the same way IEEE 754 does */
-    if (unlikely(float32_is_quiet_nan(u.f))) {
-        return 0;
-    }
-    tmp = uint64_to_float32(1ULL << 32, &env->vec_status);
-    u.f = float32_mul(u.f, tmp, &env->vec_status);
-
-    return float32_to_uint32(u.f, &env->vec_status);
-}
-
-#define HELPER_SPE_SINGLE_CONV(name)            \
-    uint32_t helper_e##name(uint32_t val)       \
-    {                                           \
-        return e##name(val);                    \
-    }
-/* efscfsi */
-HELPER_SPE_SINGLE_CONV(fscfsi);
-/* efscfui */
-HELPER_SPE_SINGLE_CONV(fscfui);
-/* efscfuf */
-HELPER_SPE_SINGLE_CONV(fscfuf);
-/* efscfsf */
-HELPER_SPE_SINGLE_CONV(fscfsf);
-/* efsctsi */
-HELPER_SPE_SINGLE_CONV(fsctsi);
-/* efsctui */
-HELPER_SPE_SINGLE_CONV(fsctui);
-/* efsctsiz */
-HELPER_SPE_SINGLE_CONV(fsctsiz);
-/* efsctuiz */
-HELPER_SPE_SINGLE_CONV(fsctuiz);
-/* efsctsf */
-HELPER_SPE_SINGLE_CONV(fsctsf);
-/* efsctuf */
-HELPER_SPE_SINGLE_CONV(fsctuf);
-
-#define HELPER_SPE_VECTOR_CONV(name)                    \
-    uint64_t helper_ev##name(uint64_t val)              \
-    {                                                   \
-        return ((uint64_t)e##name(val >> 32) << 32) |   \
-            (uint64_t)e##name(val);                     \
-    }
-/* evfscfsi */
-HELPER_SPE_VECTOR_CONV(fscfsi);
-/* evfscfui */
-HELPER_SPE_VECTOR_CONV(fscfui);
-/* evfscfuf */
-HELPER_SPE_VECTOR_CONV(fscfuf);
-/* evfscfsf */
-HELPER_SPE_VECTOR_CONV(fscfsf);
-/* evfsctsi */
-HELPER_SPE_VECTOR_CONV(fsctsi);
-/* evfsctui */
-HELPER_SPE_VECTOR_CONV(fsctui);
-/* evfsctsiz */
-HELPER_SPE_VECTOR_CONV(fsctsiz);
-/* evfsctuiz */
-HELPER_SPE_VECTOR_CONV(fsctuiz);
-/* evfsctsf */
-HELPER_SPE_VECTOR_CONV(fsctsf);
-/* evfsctuf */
-HELPER_SPE_VECTOR_CONV(fsctuf);
-
-/* Single-precision floating-point arithmetic */
-static inline uint32_t efsadd(uint32_t op1, uint32_t op2)
-{
-    CPU_FloatU u1, u2;
-
-    u1.l = op1;
-    u2.l = op2;
-    u1.f = float32_add(u1.f, u2.f, &env->vec_status);
-    return u1.l;
-}
-
-static inline uint32_t efssub(uint32_t op1, uint32_t op2)
-{
-    CPU_FloatU u1, u2;
-
-    u1.l = op1;
-    u2.l = op2;
-    u1.f = float32_sub(u1.f, u2.f, &env->vec_status);
-    return u1.l;
-}
-
-static inline uint32_t efsmul(uint32_t op1, uint32_t op2)
-{
-    CPU_FloatU u1, u2;
-
-    u1.l = op1;
-    u2.l = op2;
-    u1.f = float32_mul(u1.f, u2.f, &env->vec_status);
-    return u1.l;
-}
-
-static inline uint32_t efsdiv(uint32_t op1, uint32_t op2)
-{
-    CPU_FloatU u1, u2;
-
-    u1.l = op1;
-    u2.l = op2;
-    u1.f = float32_div(u1.f, u2.f, &env->vec_status);
-    return u1.l;
-}
-
-#define HELPER_SPE_SINGLE_ARITH(name)                   \
-    uint32_t helper_e##name(uint32_t op1, uint32_t op2) \
-    {                                                   \
-        return e##name(op1, op2);                       \
-    }
-/* efsadd */
-HELPER_SPE_SINGLE_ARITH(fsadd);
-/* efssub */
-HELPER_SPE_SINGLE_ARITH(fssub);
-/* efsmul */
-HELPER_SPE_SINGLE_ARITH(fsmul);
-/* efsdiv */
-HELPER_SPE_SINGLE_ARITH(fsdiv);
-
-#define HELPER_SPE_VECTOR_ARITH(name)                                   \
-    uint64_t helper_ev##name(uint64_t op1, uint64_t op2)                \
-    {                                                                   \
-        return ((uint64_t)e##name(op1 >> 32, op2 >> 32) << 32) |        \
-            (uint64_t)e##name(op1, op2);                                \
-    }
-/* evfsadd */
-HELPER_SPE_VECTOR_ARITH(fsadd);
-/* evfssub */
-HELPER_SPE_VECTOR_ARITH(fssub);
-/* evfsmul */
-HELPER_SPE_VECTOR_ARITH(fsmul);
-/* evfsdiv */
-HELPER_SPE_VECTOR_ARITH(fsdiv);
-
-/* Single-precision floating-point comparisons */
-static inline uint32_t efscmplt(uint32_t op1, uint32_t op2)
-{
-    CPU_FloatU u1, u2;
-
-    u1.l = op1;
-    u2.l = op2;
-    return float32_lt(u1.f, u2.f, &env->vec_status) ? 4 : 0;
-}
-
-static inline uint32_t efscmpgt(uint32_t op1, uint32_t op2)
-{
-    CPU_FloatU u1, u2;
-
-    u1.l = op1;
-    u2.l = op2;
-    return float32_le(u1.f, u2.f, &env->vec_status) ? 0 : 4;
-}
-
-static inline uint32_t efscmpeq(uint32_t op1, uint32_t op2)
-{
-    CPU_FloatU u1, u2;
-
-    u1.l = op1;
-    u2.l = op2;
-    return float32_eq(u1.f, u2.f, &env->vec_status) ? 4 : 0;
-}
-
-static inline uint32_t efststlt(uint32_t op1, uint32_t op2)
-{
-    /* XXX: TODO: ignore special values (NaN, infinites, ...) */
-    return efscmplt(op1, op2);
-}
-
-static inline uint32_t efststgt(uint32_t op1, uint32_t op2)
-{
-    /* XXX: TODO: ignore special values (NaN, infinites, ...) */
-    return efscmpgt(op1, op2);
-}
-
-static inline uint32_t efststeq(uint32_t op1, uint32_t op2)
-{
-    /* XXX: TODO: ignore special values (NaN, infinites, ...) */
-    return efscmpeq(op1, op2);
-}
-
-#define HELPER_SINGLE_SPE_CMP(name)                     \
-    uint32_t helper_e##name(uint32_t op1, uint32_t op2) \
-    {                                                   \
-        return e##name(op1, op2) << 2;                  \
-    }
-/* efststlt */
-HELPER_SINGLE_SPE_CMP(fststlt);
-/* efststgt */
-HELPER_SINGLE_SPE_CMP(fststgt);
-/* efststeq */
-HELPER_SINGLE_SPE_CMP(fststeq);
-/* efscmplt */
-HELPER_SINGLE_SPE_CMP(fscmplt);
-/* efscmpgt */
-HELPER_SINGLE_SPE_CMP(fscmpgt);
-/* efscmpeq */
-HELPER_SINGLE_SPE_CMP(fscmpeq);
-
-static inline uint32_t evcmp_merge(int t0, int t1)
-{
-    return (t0 << 3) | (t1 << 2) | ((t0 | t1) << 1) | (t0 & t1);
-}
-
-#define HELPER_VECTOR_SPE_CMP(name)                                     \
-    uint32_t helper_ev##name(uint64_t op1, uint64_t op2)                \
-    {                                                                   \
-        return evcmp_merge(e##name(op1 >> 32, op2 >> 32), e##name(op1, op2)); \
-    }
-/* evfststlt */
-HELPER_VECTOR_SPE_CMP(fststlt);
-/* evfststgt */
-HELPER_VECTOR_SPE_CMP(fststgt);
-/* evfststeq */
-HELPER_VECTOR_SPE_CMP(fststeq);
-/* evfscmplt */
-HELPER_VECTOR_SPE_CMP(fscmplt);
-/* evfscmpgt */
-HELPER_VECTOR_SPE_CMP(fscmpgt);
-/* evfscmpeq */
-HELPER_VECTOR_SPE_CMP(fscmpeq);
-
-/* Double-precision floating-point conversion */
-uint64_t helper_efdcfsi(uint32_t val)
-{
-    CPU_DoubleU u;
-
-    u.d = int32_to_float64(val, &env->vec_status);
-
-    return u.ll;
-}
-
-uint64_t helper_efdcfsid(uint64_t val)
-{
-    CPU_DoubleU u;
-
-    u.d = int64_to_float64(val, &env->vec_status);
-
-    return u.ll;
-}
-
-uint64_t helper_efdcfui(uint32_t val)
-{
-    CPU_DoubleU u;
-
-    u.d = uint32_to_float64(val, &env->vec_status);
-
-    return u.ll;
-}
-
-uint64_t helper_efdcfuid(uint64_t val)
-{
-    CPU_DoubleU u;
-
-    u.d = uint64_to_float64(val, &env->vec_status);
-
-    return u.ll;
-}
-
-uint32_t helper_efdctsi(uint64_t val)
-{
-    CPU_DoubleU u;
-
-    u.ll = val;
-    /* NaN are not treated the same way IEEE 754 does */
-    if (unlikely(float64_is_any_nan(u.d))) {
-        return 0;
-    }
-
-    return float64_to_int32(u.d, &env->vec_status);
-}
-
-uint32_t helper_efdctui(uint64_t val)
-{
-    CPU_DoubleU u;
-
-    u.ll = val;
-    /* NaN are not treated the same way IEEE 754 does */
-    if (unlikely(float64_is_any_nan(u.d))) {
-        return 0;
-    }
-
-    return float64_to_uint32(u.d, &env->vec_status);
-}
-
-uint32_t helper_efdctsiz(uint64_t val)
-{
-    CPU_DoubleU u;
-
-    u.ll = val;
-    /* NaN are not treated the same way IEEE 754 does */
-    if (unlikely(float64_is_any_nan(u.d))) {
-        return 0;
-    }
-
-    return float64_to_int32_round_to_zero(u.d, &env->vec_status);
-}
-
-uint64_t helper_efdctsidz(uint64_t val)
-{
-    CPU_DoubleU u;
-
-    u.ll = val;
-    /* NaN are not treated the same way IEEE 754 does */
-    if (unlikely(float64_is_any_nan(u.d))) {
-        return 0;
-    }
-
-    return float64_to_int64_round_to_zero(u.d, &env->vec_status);
-}
-
-uint32_t helper_efdctuiz(uint64_t val)
-{
-    CPU_DoubleU u;
-
-    u.ll = val;
-    /* NaN are not treated the same way IEEE 754 does */
-    if (unlikely(float64_is_any_nan(u.d))) {
-        return 0;
-    }
-
-    return float64_to_uint32_round_to_zero(u.d, &env->vec_status);
-}
-
-uint64_t helper_efdctuidz(uint64_t val)
-{
-    CPU_DoubleU u;
-
-    u.ll = val;
-    /* NaN are not treated the same way IEEE 754 does */
-    if (unlikely(float64_is_any_nan(u.d))) {
-        return 0;
-    }
-
-    return float64_to_uint64_round_to_zero(u.d, &env->vec_status);
-}
-
-uint64_t helper_efdcfsf(uint32_t val)
-{
-    CPU_DoubleU u;
-    float64 tmp;
-
-    u.d = int32_to_float64(val, &env->vec_status);
-    tmp = int64_to_float64(1ULL << 32, &env->vec_status);
-    u.d = float64_div(u.d, tmp, &env->vec_status);
-
-    return u.ll;
-}
-
-uint64_t helper_efdcfuf(uint32_t val)
-{
-    CPU_DoubleU u;
-    float64 tmp;
-
-    u.d = uint32_to_float64(val, &env->vec_status);
-    tmp = int64_to_float64(1ULL << 32, &env->vec_status);
-    u.d = float64_div(u.d, tmp, &env->vec_status);
-
-    return u.ll;
-}
-
-uint32_t helper_efdctsf(uint64_t val)
-{
-    CPU_DoubleU u;
-    float64 tmp;
-
-    u.ll = val;
-    /* NaN are not treated the same way IEEE 754 does */
-    if (unlikely(float64_is_any_nan(u.d))) {
-        return 0;
-    }
-    tmp = uint64_to_float64(1ULL << 32, &env->vec_status);
-    u.d = float64_mul(u.d, tmp, &env->vec_status);
-
-    return float64_to_int32(u.d, &env->vec_status);
-}
-
-uint32_t helper_efdctuf(uint64_t val)
-{
-    CPU_DoubleU u;
-    float64 tmp;
-
-    u.ll = val;
-    /* NaN are not treated the same way IEEE 754 does */
-    if (unlikely(float64_is_any_nan(u.d))) {
-        return 0;
-    }
-    tmp = uint64_to_float64(1ULL << 32, &env->vec_status);
-    u.d = float64_mul(u.d, tmp, &env->vec_status);
-
-    return float64_to_uint32(u.d, &env->vec_status);
-}
-
-uint32_t helper_efscfd(uint64_t val)
-{
-    CPU_DoubleU u1;
-    CPU_FloatU u2;
-
-    u1.ll = val;
-    u2.f = float64_to_float32(u1.d, &env->vec_status);
-
-    return u2.l;
-}
-
-uint64_t helper_efdcfs(uint32_t val)
-{
-    CPU_DoubleU u2;
-    CPU_FloatU u1;
-
-    u1.l = val;
-    u2.d = float32_to_float64(u1.f, &env->vec_status);
-
-    return u2.ll;
-}
-
-/* Double precision fixed-point arithmetic */
-uint64_t helper_efdadd(uint64_t op1, uint64_t op2)
-{
-    CPU_DoubleU u1, u2;
-
-    u1.ll = op1;
-    u2.ll = op2;
-    u1.d = float64_add(u1.d, u2.d, &env->vec_status);
-    return u1.ll;
-}
-
-uint64_t helper_efdsub(uint64_t op1, uint64_t op2)
-{
-    CPU_DoubleU u1, u2;
-
-    u1.ll = op1;
-    u2.ll = op2;
-    u1.d = float64_sub(u1.d, u2.d, &env->vec_status);
-    return u1.ll;
-}
-
-uint64_t helper_efdmul(uint64_t op1, uint64_t op2)
-{
-    CPU_DoubleU u1, u2;
-
-    u1.ll = op1;
-    u2.ll = op2;
-    u1.d = float64_mul(u1.d, u2.d, &env->vec_status);
-    return u1.ll;
-}
-
-uint64_t helper_efddiv(uint64_t op1, uint64_t op2)
-{
-    CPU_DoubleU u1, u2;
-
-    u1.ll = op1;
-    u2.ll = op2;
-    u1.d = float64_div(u1.d, u2.d, &env->vec_status);
-    return u1.ll;
-}
-
-/* Double precision floating point helpers */
-uint32_t helper_efdtstlt(uint64_t op1, uint64_t op2)
-{
-    CPU_DoubleU u1, u2;
-
-    u1.ll = op1;
-    u2.ll = op2;
-    return float64_lt(u1.d, u2.d, &env->vec_status) ? 4 : 0;
-}
-
-uint32_t helper_efdtstgt(uint64_t op1, uint64_t op2)
-{
-    CPU_DoubleU u1, u2;
-
-    u1.ll = op1;
-    u2.ll = op2;
-    return float64_le(u1.d, u2.d, &env->vec_status) ? 0 : 4;
-}
-
-uint32_t helper_efdtsteq(uint64_t op1, uint64_t op2)
-{
-    CPU_DoubleU u1, u2;
-
-    u1.ll = op1;
-    u2.ll = op2;
-    return float64_eq_quiet(u1.d, u2.d, &env->vec_status) ? 4 : 0;
-}
-
-uint32_t helper_efdcmplt(uint64_t op1, uint64_t op2)
-{
-    /* XXX: TODO: test special values (NaN, infinites, ...) */
-    return helper_efdtstlt(op1, op2);
-}
-
-uint32_t helper_efdcmpgt(uint64_t op1, uint64_t op2)
-{
-    /* XXX: TODO: test special values (NaN, infinites, ...) */
-    return helper_efdtstgt(op1, op2);
-}
-
-uint32_t helper_efdcmpeq(uint64_t op1, uint64_t op2)
-{
-    /* XXX: TODO: test special values (NaN, infinites, ...) */
-    return helper_efdtsteq(op1, op2);
-}
-
 /*****************************************************************************/
 /* Softmmu support */
 #if !defined(CONFIG_USER_ONLY)
commit c79c73f6a9e989f9e0ae4323dcc2fad30897acce
Author: Blue Swirl <blauwirbel at gmail.com>
Date:   Wed May 30 04:23:25 2012 +0000

    ppc: Move exception helpers from helper.c to excp_helper.c
    
    Move exception helpers from helper.c to excp_helper.c and
    make cpu_dump_rfi() static.
    
    Signed-off-by: Blue Swirl <blauwirbel at gmail.com>
    Signed-off-by: Alexander Graf <agraf at suse.de>
    Signed-off-by: Andreas Färber <afaerber at suse.de>
    Signed-off-by: Alexander Graf <agraf at suse.de>

diff --git a/target-ppc/cpu.h b/target-ppc/cpu.h
index 77a2858..32cfcef 100644
--- a/target-ppc/cpu.h
+++ b/target-ppc/cpu.h
@@ -1117,8 +1117,6 @@ int get_physical_address (CPUPPCState *env, mmu_ctx_t *ctx, target_ulong vaddr,
 void do_interrupt (CPUPPCState *env);
 void ppc_hw_interrupt (CPUPPCState *env);
 
-void cpu_dump_rfi (target_ulong RA, target_ulong msr);
-
 #if !defined(CONFIG_USER_ONLY)
 void ppc6xx_tlb_store (CPUPPCState *env, target_ulong EPN, int way, int is_code,
                        target_ulong pte0, target_ulong pte1);
diff --git a/target-ppc/excp_helper.c b/target-ppc/excp_helper.c
index c153f4a..7fa7a59 100644
--- a/target-ppc/excp_helper.c
+++ b/target-ppc/excp_helper.c
@@ -24,6 +24,751 @@
 //#define DEBUG_OP
 //#define DEBUG_EXCEPTIONS
 
+#ifdef DEBUG_EXCEPTIONS
+#  define LOG_EXCP(...) qemu_log(__VA_ARGS__)
+#else
+#  define LOG_EXCP(...) do { } while (0)
+#endif
+
+/*****************************************************************************/
+/* PowerPC Hypercall emulation */
+
+void (*cpu_ppc_hypercall)(CPUPPCState *);
+
+/*****************************************************************************/
+/* Exception processing */
+#if defined(CONFIG_USER_ONLY)
+void do_interrupt(CPUPPCState *env)
+{
+    env->exception_index = POWERPC_EXCP_NONE;
+    env->error_code = 0;
+}
+
+void ppc_hw_interrupt(CPUPPCState *env)
+{
+    env->exception_index = POWERPC_EXCP_NONE;
+    env->error_code = 0;
+}
+#else /* defined(CONFIG_USER_ONLY) */
+static inline void dump_syscall(CPUPPCState *env)
+{
+    qemu_log_mask(CPU_LOG_INT, "syscall r0=%016" PRIx64 " r3=%016" PRIx64
+                  " r4=%016" PRIx64 " r5=%016" PRIx64 " r6=%016" PRIx64
+                  " nip=" TARGET_FMT_lx "\n",
+                  ppc_dump_gpr(env, 0), ppc_dump_gpr(env, 3),
+                  ppc_dump_gpr(env, 4), ppc_dump_gpr(env, 5),
+                  ppc_dump_gpr(env, 6), env->nip);
+}
+
+/* Note that this function should be greatly optimized
+ * when called with a constant excp, from ppc_hw_interrupt
+ */
+static inline void powerpc_excp(CPUPPCState *env, int excp_model, int excp)
+{
+    target_ulong msr, new_msr, vector;
+    int srr0, srr1, asrr0, asrr1;
+    int lpes0, lpes1, lev;
+
+    if (0) {
+        /* XXX: find a suitable condition to enable the hypervisor mode */
+        lpes0 = (env->spr[SPR_LPCR] >> 1) & 1;
+        lpes1 = (env->spr[SPR_LPCR] >> 2) & 1;
+    } else {
+        /* Those values ensure we won't enter the hypervisor mode */
+        lpes0 = 0;
+        lpes1 = 1;
+    }
+
+    qemu_log_mask(CPU_LOG_INT, "Raise exception at " TARGET_FMT_lx
+                  " => %08x (%02x)\n", env->nip, excp, env->error_code);
+
+    /* new srr1 value excluding must-be-zero bits */
+    msr = env->msr & ~0x783f0000ULL;
+
+    /* new interrupt handler msr */
+    new_msr = env->msr & ((target_ulong)1 << MSR_ME);
+
+    /* target registers */
+    srr0 = SPR_SRR0;
+    srr1 = SPR_SRR1;
+    asrr0 = -1;
+    asrr1 = -1;
+
+    switch (excp) {
+    case POWERPC_EXCP_NONE:
+        /* Should never happen */
+        return;
+    case POWERPC_EXCP_CRITICAL:    /* Critical input                         */
+        switch (excp_model) {
+        case POWERPC_EXCP_40x:
+            srr0 = SPR_40x_SRR2;
+            srr1 = SPR_40x_SRR3;
+            break;
+        case POWERPC_EXCP_BOOKE:
+            srr0 = SPR_BOOKE_CSRR0;
+            srr1 = SPR_BOOKE_CSRR1;
+            break;
+        case POWERPC_EXCP_G2:
+            break;
+        default:
+            goto excp_invalid;
+        }
+        goto store_next;
+    case POWERPC_EXCP_MCHECK:    /* Machine check exception                  */
+        if (msr_me == 0) {
+            /* Machine check exception is not enabled.
+             * Enter checkstop state.
+             */
+            if (qemu_log_enabled()) {
+                qemu_log("Machine check while not allowed. "
+                        "Entering checkstop state\n");
+            } else {
+                fprintf(stderr, "Machine check while not allowed. "
+                        "Entering checkstop state\n");
+            }
+            env->halted = 1;
+            env->interrupt_request |= CPU_INTERRUPT_EXITTB;
+        }
+        if (0) {
+            /* XXX: find a suitable condition to enable the hypervisor mode */
+            new_msr |= (target_ulong)MSR_HVB;
+        }
+
+        /* machine check exceptions don't have ME set */
+        new_msr &= ~((target_ulong)1 << MSR_ME);
+
+        /* XXX: should also have something loaded in DAR / DSISR */
+        switch (excp_model) {
+        case POWERPC_EXCP_40x:
+            srr0 = SPR_40x_SRR2;
+            srr1 = SPR_40x_SRR3;
+            break;
+        case POWERPC_EXCP_BOOKE:
+            srr0 = SPR_BOOKE_MCSRR0;
+            srr1 = SPR_BOOKE_MCSRR1;
+            asrr0 = SPR_BOOKE_CSRR0;
+            asrr1 = SPR_BOOKE_CSRR1;
+            break;
+        default:
+            break;
+        }
+        goto store_next;
+    case POWERPC_EXCP_DSI:       /* Data storage exception                   */
+        LOG_EXCP("DSI exception: DSISR=" TARGET_FMT_lx" DAR=" TARGET_FMT_lx
+                 "\n", env->spr[SPR_DSISR], env->spr[SPR_DAR]);
+        if (lpes1 == 0) {
+            new_msr |= (target_ulong)MSR_HVB;
+        }
+        goto store_next;
+    case POWERPC_EXCP_ISI:       /* Instruction storage exception            */
+        LOG_EXCP("ISI exception: msr=" TARGET_FMT_lx ", nip=" TARGET_FMT_lx
+                 "\n", msr, env->nip);
+        if (lpes1 == 0) {
+            new_msr |= (target_ulong)MSR_HVB;
+        }
+        msr |= env->error_code;
+        goto store_next;
+    case POWERPC_EXCP_EXTERNAL:  /* External input                           */
+        if (lpes0 == 1) {
+            new_msr |= (target_ulong)MSR_HVB;
+        }
+        goto store_next;
+    case POWERPC_EXCP_ALIGN:     /* Alignment exception                      */
+        if (lpes1 == 0) {
+            new_msr |= (target_ulong)MSR_HVB;
+        }
+        /* XXX: this is false */
+        /* Get rS/rD and rA from faulting opcode */
+        env->spr[SPR_DSISR] |= (ldl_code((env->nip - 4)) & 0x03FF0000) >> 16;
+        goto store_current;
+    case POWERPC_EXCP_PROGRAM:   /* Program exception                        */
+        switch (env->error_code & ~0xF) {
+        case POWERPC_EXCP_FP:
+            if ((msr_fe0 == 0 && msr_fe1 == 0) || msr_fp == 0) {
+                LOG_EXCP("Ignore floating point exception\n");
+                env->exception_index = POWERPC_EXCP_NONE;
+                env->error_code = 0;
+                return;
+            }
+            if (lpes1 == 0) {
+                new_msr |= (target_ulong)MSR_HVB;
+            }
+            msr |= 0x00100000;
+            if (msr_fe0 == msr_fe1) {
+                goto store_next;
+            }
+            msr |= 0x00010000;
+            break;
+        case POWERPC_EXCP_INVAL:
+            LOG_EXCP("Invalid instruction at " TARGET_FMT_lx "\n", env->nip);
+            if (lpes1 == 0) {
+                new_msr |= (target_ulong)MSR_HVB;
+            }
+            msr |= 0x00080000;
+            env->spr[SPR_BOOKE_ESR] = ESR_PIL;
+            break;
+        case POWERPC_EXCP_PRIV:
+            if (lpes1 == 0) {
+                new_msr |= (target_ulong)MSR_HVB;
+            }
+            msr |= 0x00040000;
+            env->spr[SPR_BOOKE_ESR] = ESR_PPR;
+            break;
+        case POWERPC_EXCP_TRAP:
+            if (lpes1 == 0) {
+                new_msr |= (target_ulong)MSR_HVB;
+            }
+            msr |= 0x00020000;
+            env->spr[SPR_BOOKE_ESR] = ESR_PTR;
+            break;
+        default:
+            /* Should never occur */
+            cpu_abort(env, "Invalid program exception %d. Aborting\n",
+                      env->error_code);
+            break;
+        }
+        goto store_current;
+    case POWERPC_EXCP_FPU:       /* Floating-point unavailable exception     */
+        if (lpes1 == 0) {
+            new_msr |= (target_ulong)MSR_HVB;
+        }
+        goto store_current;
+    case POWERPC_EXCP_SYSCALL:   /* System call exception                    */
+        dump_syscall(env);
+        lev = env->error_code;
+        if ((lev == 1) && cpu_ppc_hypercall) {
+            cpu_ppc_hypercall(env);
+            return;
+        }
+        if (lev == 1 || (lpes0 == 0 && lpes1 == 0)) {
+            new_msr |= (target_ulong)MSR_HVB;
+        }
+        goto store_next;
+    case POWERPC_EXCP_APU:       /* Auxiliary processor unavailable          */
+        goto store_current;
+    case POWERPC_EXCP_DECR:      /* Decrementer exception                    */
+        if (lpes1 == 0) {
+            new_msr |= (target_ulong)MSR_HVB;
+        }
+        goto store_next;
+    case POWERPC_EXCP_FIT:       /* Fixed-interval timer interrupt           */
+        /* FIT on 4xx */
+        LOG_EXCP("FIT exception\n");
+        goto store_next;
+    case POWERPC_EXCP_WDT:       /* Watchdog timer interrupt                 */
+        LOG_EXCP("WDT exception\n");
+        switch (excp_model) {
+        case POWERPC_EXCP_BOOKE:
+            srr0 = SPR_BOOKE_CSRR0;
+            srr1 = SPR_BOOKE_CSRR1;
+            break;
+        default:
+            break;
+        }
+        goto store_next;
+    case POWERPC_EXCP_DTLB:      /* Data TLB error                           */
+        goto store_next;
+    case POWERPC_EXCP_ITLB:      /* Instruction TLB error                    */
+        goto store_next;
+    case POWERPC_EXCP_DEBUG:     /* Debug interrupt                          */
+        switch (excp_model) {
+        case POWERPC_EXCP_BOOKE:
+            srr0 = SPR_BOOKE_DSRR0;
+            srr1 = SPR_BOOKE_DSRR1;
+            asrr0 = SPR_BOOKE_CSRR0;
+            asrr1 = SPR_BOOKE_CSRR1;
+            break;
+        default:
+            break;
+        }
+        /* XXX: TODO */
+        cpu_abort(env, "Debug exception is not implemented yet !\n");
+        goto store_next;
+    case POWERPC_EXCP_SPEU:      /* SPE/embedded floating-point unavailable  */
+        env->spr[SPR_BOOKE_ESR] = ESR_SPV;
+        goto store_current;
+    case POWERPC_EXCP_EFPDI:     /* Embedded floating-point data interrupt   */
+        /* XXX: TODO */
+        cpu_abort(env, "Embedded floating point data exception "
+                  "is not implemented yet !\n");
+        env->spr[SPR_BOOKE_ESR] = ESR_SPV;
+        goto store_next;
+    case POWERPC_EXCP_EFPRI:     /* Embedded floating-point round interrupt  */
+        /* XXX: TODO */
+        cpu_abort(env, "Embedded floating point round exception "
+                  "is not implemented yet !\n");
+        env->spr[SPR_BOOKE_ESR] = ESR_SPV;
+        goto store_next;
+    case POWERPC_EXCP_EPERFM:    /* Embedded performance monitor interrupt   */
+        /* XXX: TODO */
+        cpu_abort(env,
+                  "Performance counter exception is not implemented yet !\n");
+        goto store_next;
+    case POWERPC_EXCP_DOORI:     /* Embedded doorbell interrupt              */
+        goto store_next;
+    case POWERPC_EXCP_DOORCI:    /* Embedded doorbell critical interrupt     */
+        srr0 = SPR_BOOKE_CSRR0;
+        srr1 = SPR_BOOKE_CSRR1;
+        goto store_next;
+    case POWERPC_EXCP_RESET:     /* System reset exception                   */
+        if (msr_pow) {
+            /* indicate that we resumed from power save mode */
+            msr |= 0x10000;
+        } else {
+            new_msr &= ~((target_ulong)1 << MSR_ME);
+        }
+
+        if (0) {
+            /* XXX: find a suitable condition to enable the hypervisor mode */
+            new_msr |= (target_ulong)MSR_HVB;
+        }
+        goto store_next;
+    case POWERPC_EXCP_DSEG:      /* Data segment exception                   */
+        if (lpes1 == 0) {
+            new_msr |= (target_ulong)MSR_HVB;
+        }
+        goto store_next;
+    case POWERPC_EXCP_ISEG:      /* Instruction segment exception            */
+        if (lpes1 == 0) {
+            new_msr |= (target_ulong)MSR_HVB;
+        }
+        goto store_next;
+    case POWERPC_EXCP_HDECR:     /* Hypervisor decrementer exception         */
+        srr0 = SPR_HSRR0;
+        srr1 = SPR_HSRR1;
+        new_msr |= (target_ulong)MSR_HVB;
+        new_msr |= env->msr & ((target_ulong)1 << MSR_RI);
+        goto store_next;
+    case POWERPC_EXCP_TRACE:     /* Trace exception                          */
+        if (lpes1 == 0) {
+            new_msr |= (target_ulong)MSR_HVB;
+        }
+        goto store_next;
+    case POWERPC_EXCP_HDSI:      /* Hypervisor data storage exception        */
+        srr0 = SPR_HSRR0;
+        srr1 = SPR_HSRR1;
+        new_msr |= (target_ulong)MSR_HVB;
+        new_msr |= env->msr & ((target_ulong)1 << MSR_RI);
+        goto store_next;
+    case POWERPC_EXCP_HISI:      /* Hypervisor instruction storage exception */
+        srr0 = SPR_HSRR0;
+        srr1 = SPR_HSRR1;
+        new_msr |= (target_ulong)MSR_HVB;
+        new_msr |= env->msr & ((target_ulong)1 << MSR_RI);
+        goto store_next;
+    case POWERPC_EXCP_HDSEG:     /* Hypervisor data segment exception        */
+        srr0 = SPR_HSRR0;
+        srr1 = SPR_HSRR1;
+        new_msr |= (target_ulong)MSR_HVB;
+        new_msr |= env->msr & ((target_ulong)1 << MSR_RI);
+        goto store_next;
+    case POWERPC_EXCP_HISEG:     /* Hypervisor instruction segment exception */
+        srr0 = SPR_HSRR0;
+        srr1 = SPR_HSRR1;
+        new_msr |= (target_ulong)MSR_HVB;
+        new_msr |= env->msr & ((target_ulong)1 << MSR_RI);
+        goto store_next;
+    case POWERPC_EXCP_VPU:       /* Vector unavailable exception             */
+        if (lpes1 == 0) {
+            new_msr |= (target_ulong)MSR_HVB;
+        }
+        goto store_current;
+    case POWERPC_EXCP_PIT:       /* Programmable interval timer interrupt    */
+        LOG_EXCP("PIT exception\n");
+        goto store_next;
+    case POWERPC_EXCP_IO:        /* IO error exception                       */
+        /* XXX: TODO */
+        cpu_abort(env, "601 IO error exception is not implemented yet !\n");
+        goto store_next;
+    case POWERPC_EXCP_RUNM:      /* Run mode exception                       */
+        /* XXX: TODO */
+        cpu_abort(env, "601 run mode exception is not implemented yet !\n");
+        goto store_next;
+    case POWERPC_EXCP_EMUL:      /* Emulation trap exception                 */
+        /* XXX: TODO */
+        cpu_abort(env, "602 emulation trap exception "
+                  "is not implemented yet !\n");
+        goto store_next;
+    case POWERPC_EXCP_IFTLB:     /* Instruction fetch TLB error              */
+        if (lpes1 == 0) { /* XXX: check this */
+            new_msr |= (target_ulong)MSR_HVB;
+        }
+        switch (excp_model) {
+        case POWERPC_EXCP_602:
+        case POWERPC_EXCP_603:
+        case POWERPC_EXCP_603E:
+        case POWERPC_EXCP_G2:
+            goto tlb_miss_tgpr;
+        case POWERPC_EXCP_7x5:
+            goto tlb_miss;
+        case POWERPC_EXCP_74xx:
+            goto tlb_miss_74xx;
+        default:
+            cpu_abort(env, "Invalid instruction TLB miss exception\n");
+            break;
+        }
+        break;
+    case POWERPC_EXCP_DLTLB:     /* Data load TLB miss                       */
+        if (lpes1 == 0) { /* XXX: check this */
+            new_msr |= (target_ulong)MSR_HVB;
+        }
+        switch (excp_model) {
+        case POWERPC_EXCP_602:
+        case POWERPC_EXCP_603:
+        case POWERPC_EXCP_603E:
+        case POWERPC_EXCP_G2:
+            goto tlb_miss_tgpr;
+        case POWERPC_EXCP_7x5:
+            goto tlb_miss;
+        case POWERPC_EXCP_74xx:
+            goto tlb_miss_74xx;
+        default:
+            cpu_abort(env, "Invalid data load TLB miss exception\n");
+            break;
+        }
+        break;
+    case POWERPC_EXCP_DSTLB:     /* Data store TLB miss                      */
+        if (lpes1 == 0) { /* XXX: check this */
+            new_msr |= (target_ulong)MSR_HVB;
+        }
+        switch (excp_model) {
+        case POWERPC_EXCP_602:
+        case POWERPC_EXCP_603:
+        case POWERPC_EXCP_603E:
+        case POWERPC_EXCP_G2:
+        tlb_miss_tgpr:
+            /* Swap temporary saved registers with GPRs */
+            if (!(new_msr & ((target_ulong)1 << MSR_TGPR))) {
+                new_msr |= (target_ulong)1 << MSR_TGPR;
+                hreg_swap_gpr_tgpr(env);
+            }
+            goto tlb_miss;
+        case POWERPC_EXCP_7x5:
+        tlb_miss:
+#if defined(DEBUG_SOFTWARE_TLB)
+            if (qemu_log_enabled()) {
+                const char *es;
+                target_ulong *miss, *cmp;
+                int en;
+
+                if (excp == POWERPC_EXCP_IFTLB) {
+                    es = "I";
+                    en = 'I';
+                    miss = &env->spr[SPR_IMISS];
+                    cmp = &env->spr[SPR_ICMP];
+                } else {
+                    if (excp == POWERPC_EXCP_DLTLB) {
+                        es = "DL";
+                    } else {
+                        es = "DS";
+                    }
+                    en = 'D';
+                    miss = &env->spr[SPR_DMISS];
+                    cmp = &env->spr[SPR_DCMP];
+                }
+                qemu_log("6xx %sTLB miss: %cM " TARGET_FMT_lx " %cC "
+                         TARGET_FMT_lx " H1 " TARGET_FMT_lx " H2 "
+                         TARGET_FMT_lx " %08x\n", es, en, *miss, en, *cmp,
+                         env->spr[SPR_HASH1], env->spr[SPR_HASH2],
+                         env->error_code);
+            }
+#endif
+            msr |= env->crf[0] << 28;
+            msr |= env->error_code; /* key, D/I, S/L bits */
+            /* Set way using a LRU mechanism */
+            msr |= ((env->last_way + 1) & (env->nb_ways - 1)) << 17;
+            break;
+        case POWERPC_EXCP_74xx:
+        tlb_miss_74xx:
+#if defined(DEBUG_SOFTWARE_TLB)
+            if (qemu_log_enabled()) {
+                const char *es;
+                target_ulong *miss, *cmp;
+                int en;
+
+                if (excp == POWERPC_EXCP_IFTLB) {
+                    es = "I";
+                    en = 'I';
+                    miss = &env->spr[SPR_TLBMISS];
+                    cmp = &env->spr[SPR_PTEHI];
+                } else {
+                    if (excp == POWERPC_EXCP_DLTLB) {
+                        es = "DL";
+                    } else {
+                        es = "DS";
+                    }
+                    en = 'D';
+                    miss = &env->spr[SPR_TLBMISS];
+                    cmp = &env->spr[SPR_PTEHI];
+                }
+                qemu_log("74xx %sTLB miss: %cM " TARGET_FMT_lx " %cC "
+                         TARGET_FMT_lx " %08x\n", es, en, *miss, en, *cmp,
+                         env->error_code);
+            }
+#endif
+            msr |= env->error_code; /* key bit */
+            break;
+        default:
+            cpu_abort(env, "Invalid data store TLB miss exception\n");
+            break;
+        }
+        goto store_next;
+    case POWERPC_EXCP_FPA:       /* Floating-point assist exception          */
+        /* XXX: TODO */
+        cpu_abort(env, "Floating point assist exception "
+                  "is not implemented yet !\n");
+        goto store_next;
+    case POWERPC_EXCP_DABR:      /* Data address breakpoint                  */
+        /* XXX: TODO */
+        cpu_abort(env, "DABR exception is not implemented yet !\n");
+        goto store_next;
+    case POWERPC_EXCP_IABR:      /* Instruction address breakpoint           */
+        /* XXX: TODO */
+        cpu_abort(env, "IABR exception is not implemented yet !\n");
+        goto store_next;
+    case POWERPC_EXCP_SMI:       /* System management interrupt              */
+        /* XXX: TODO */
+        cpu_abort(env, "SMI exception is not implemented yet !\n");
+        goto store_next;
+    case POWERPC_EXCP_THERM:     /* Thermal interrupt                        */
+        /* XXX: TODO */
+        cpu_abort(env, "Thermal management exception "
+                  "is not implemented yet !\n");
+        goto store_next;
+    case POWERPC_EXCP_PERFM:     /* Embedded performance monitor interrupt   */
+        if (lpes1 == 0) {
+            new_msr |= (target_ulong)MSR_HVB;
+        }
+        /* XXX: TODO */
+        cpu_abort(env,
+                  "Performance counter exception is not implemented yet !\n");
+        goto store_next;
+    case POWERPC_EXCP_VPUA:      /* Vector assist exception                  */
+        /* XXX: TODO */
+        cpu_abort(env, "VPU assist exception is not implemented yet !\n");
+        goto store_next;
+    case POWERPC_EXCP_SOFTP:     /* Soft patch exception                     */
+        /* XXX: TODO */
+        cpu_abort(env,
+                  "970 soft-patch exception is not implemented yet !\n");
+        goto store_next;
+    case POWERPC_EXCP_MAINT:     /* Maintenance exception                    */
+        /* XXX: TODO */
+        cpu_abort(env,
+                  "970 maintenance exception is not implemented yet !\n");
+        goto store_next;
+    case POWERPC_EXCP_MEXTBR:    /* Maskable external breakpoint             */
+        /* XXX: TODO */
+        cpu_abort(env, "Maskable external exception "
+                  "is not implemented yet !\n");
+        goto store_next;
+    case POWERPC_EXCP_NMEXTBR:   /* Non maskable external breakpoint         */
+        /* XXX: TODO */
+        cpu_abort(env, "Non maskable external exception "
+                  "is not implemented yet !\n");
+        goto store_next;
+    default:
+    excp_invalid:
+        cpu_abort(env, "Invalid PowerPC exception %d. Aborting\n", excp);
+        break;
+    store_current:
+        /* save current instruction location */
+        env->spr[srr0] = env->nip - 4;
+        break;
+    store_next:
+        /* save next instruction location */
+        env->spr[srr0] = env->nip;
+        break;
+    }
+    /* Save MSR */
+    env->spr[srr1] = msr;
+    /* If any alternate SRR register are defined, duplicate saved values */
+    if (asrr0 != -1) {
+        env->spr[asrr0] = env->spr[srr0];
+    }
+    if (asrr1 != -1) {
+        env->spr[asrr1] = env->spr[srr1];
+    }
+    /* If we disactivated any translation, flush TLBs */
+    if (msr & ((1 << MSR_IR) | (1 << MSR_DR))) {
+        tlb_flush(env, 1);
+    }
+
+    if (msr_ile) {
+        new_msr |= (target_ulong)1 << MSR_LE;
+    }
+
+    /* Jump to handler */
+    vector = env->excp_vectors[excp];
+    if (vector == (target_ulong)-1ULL) {
+        cpu_abort(env, "Raised an exception without defined vector %d\n",
+                  excp);
+    }
+    vector |= env->excp_prefix;
+#if defined(TARGET_PPC64)
+    if (excp_model == POWERPC_EXCP_BOOKE) {
+        if (!msr_icm) {
+            vector = (uint32_t)vector;
+        } else {
+            new_msr |= (target_ulong)1 << MSR_CM;
+        }
+    } else {
+        if (!msr_isf && !(env->mmu_model & POWERPC_MMU_64)) {
+            vector = (uint32_t)vector;
+        } else {
+            new_msr |= (target_ulong)1 << MSR_SF;
+        }
+    }
+#endif
+    /* XXX: we don't use hreg_store_msr here as already have treated
+     *      any special case that could occur. Just store MSR and update hflags
+     */
+    env->msr = new_msr & env->msr_mask;
+    hreg_compute_hflags(env);
+    env->nip = vector;
+    /* Reset exception state */
+    env->exception_index = POWERPC_EXCP_NONE;
+    env->error_code = 0;
+
+    if ((env->mmu_model == POWERPC_MMU_BOOKE) ||
+        (env->mmu_model == POWERPC_MMU_BOOKE206)) {
+        /* XXX: The BookE changes address space when switching modes,
+                we should probably implement that as different MMU indexes,
+                but for the moment we do it the slow way and flush all.  */
+        tlb_flush(env, 1);
+    }
+}
+
+void do_interrupt(CPUPPCState *env)
+{
+    powerpc_excp(env, env->excp_model, env->exception_index);
+}
+
+void ppc_hw_interrupt(CPUPPCState *env)
+{
+    int hdice;
+
+#if 0
+    qemu_log_mask(CPU_LOG_INT, "%s: %p pending %08x req %08x me %d ee %d\n",
+                __func__, env, env->pending_interrupts,
+                env->interrupt_request, (int)msr_me, (int)msr_ee);
+#endif
+    /* External reset */
+    if (env->pending_interrupts & (1 << PPC_INTERRUPT_RESET)) {
+        env->pending_interrupts &= ~(1 << PPC_INTERRUPT_RESET);
+        powerpc_excp(env, env->excp_model, POWERPC_EXCP_RESET);
+        return;
+    }
+    /* Machine check exception */
+    if (env->pending_interrupts & (1 << PPC_INTERRUPT_MCK)) {
+        env->pending_interrupts &= ~(1 << PPC_INTERRUPT_MCK);
+        powerpc_excp(env, env->excp_model, POWERPC_EXCP_MCHECK);
+        return;
+    }
+#if 0 /* TODO */
+    /* External debug exception */
+    if (env->pending_interrupts & (1 << PPC_INTERRUPT_DEBUG)) {
+        env->pending_interrupts &= ~(1 << PPC_INTERRUPT_DEBUG);
+        powerpc_excp(env, env->excp_model, POWERPC_EXCP_DEBUG);
+        return;
+    }
+#endif
+    if (0) {
+        /* XXX: find a suitable condition to enable the hypervisor mode */
+        hdice = env->spr[SPR_LPCR] & 1;
+    } else {
+        hdice = 0;
+    }
+    if ((msr_ee != 0 || msr_hv == 0 || msr_pr != 0) && hdice != 0) {
+        /* Hypervisor decrementer exception */
+        if (env->pending_interrupts & (1 << PPC_INTERRUPT_HDECR)) {
+            env->pending_interrupts &= ~(1 << PPC_INTERRUPT_HDECR);
+            powerpc_excp(env, env->excp_model, POWERPC_EXCP_HDECR);
+            return;
+        }
+    }
+    if (msr_ce != 0) {
+        /* External critical interrupt */
+        if (env->pending_interrupts & (1 << PPC_INTERRUPT_CEXT)) {
+            /* Taking a critical external interrupt does not clear the external
+             * critical interrupt status
+             */
+#if 0
+            env->pending_interrupts &= ~(1 << PPC_INTERRUPT_CEXT);
+#endif
+            powerpc_excp(env, env->excp_model, POWERPC_EXCP_CRITICAL);
+            return;
+        }
+    }
+    if (msr_ee != 0) {
+        /* Watchdog timer on embedded PowerPC */
+        if (env->pending_interrupts & (1 << PPC_INTERRUPT_WDT)) {
+            env->pending_interrupts &= ~(1 << PPC_INTERRUPT_WDT);
+            powerpc_excp(env, env->excp_model, POWERPC_EXCP_WDT);
+            return;
+        }
+        if (env->pending_interrupts & (1 << PPC_INTERRUPT_CDOORBELL)) {
+            env->pending_interrupts &= ~(1 << PPC_INTERRUPT_CDOORBELL);
+            powerpc_excp(env, env->excp_model, POWERPC_EXCP_DOORCI);
+            return;
+        }
+        /* Fixed interval timer on embedded PowerPC */
+        if (env->pending_interrupts & (1 << PPC_INTERRUPT_FIT)) {
+            env->pending_interrupts &= ~(1 << PPC_INTERRUPT_FIT);
+            powerpc_excp(env, env->excp_model, POWERPC_EXCP_FIT);
+            return;
+        }
+        /* Programmable interval timer on embedded PowerPC */
+        if (env->pending_interrupts & (1 << PPC_INTERRUPT_PIT)) {
+            env->pending_interrupts &= ~(1 << PPC_INTERRUPT_PIT);
+            powerpc_excp(env, env->excp_model, POWERPC_EXCP_PIT);
+            return;
+        }
+        /* Decrementer exception */
+        if (env->pending_interrupts & (1 << PPC_INTERRUPT_DECR)) {
+            env->pending_interrupts &= ~(1 << PPC_INTERRUPT_DECR);
+            powerpc_excp(env, env->excp_model, POWERPC_EXCP_DECR);
+            return;
+        }
+        /* External interrupt */
+        if (env->pending_interrupts & (1 << PPC_INTERRUPT_EXT)) {
+            /* Taking an external interrupt does not clear the external
+             * interrupt status
+             */
+#if 0
+            env->pending_interrupts &= ~(1 << PPC_INTERRUPT_EXT);
+#endif
+            powerpc_excp(env, env->excp_model, POWERPC_EXCP_EXTERNAL);
+            return;
+        }
+        if (env->pending_interrupts & (1 << PPC_INTERRUPT_DOORBELL)) {
+            env->pending_interrupts &= ~(1 << PPC_INTERRUPT_DOORBELL);
+            powerpc_excp(env, env->excp_model, POWERPC_EXCP_DOORI);
+            return;
+        }
+        if (env->pending_interrupts & (1 << PPC_INTERRUPT_PERFM)) {
+            env->pending_interrupts &= ~(1 << PPC_INTERRUPT_PERFM);
+            powerpc_excp(env, env->excp_model, POWERPC_EXCP_PERFM);
+            return;
+        }
+        /* Thermal interrupt */
+        if (env->pending_interrupts & (1 << PPC_INTERRUPT_THERM)) {
+            env->pending_interrupts &= ~(1 << PPC_INTERRUPT_THERM);
+            powerpc_excp(env, env->excp_model, POWERPC_EXCP_THERM);
+            return;
+        }
+    }
+}
+#endif /* !CONFIG_USER_ONLY */
+
+#if defined(DEBUG_OP)
+static void cpu_dump_rfi(target_ulong RA, target_ulong msr)
+{
+    qemu_log("Return from exception at " TARGET_FMT_lx " with flags "
+             TARGET_FMT_lx "\n", RA, msr);
+}
+#endif
+
 /*****************************************************************************/
 /* Exceptions processing helpers */
 
diff --git a/target-ppc/helper.c b/target-ppc/helper.c
index 44f1cdd..17e72a9 100644
--- a/target-ppc/helper.c
+++ b/target-ppc/helper.c
@@ -28,7 +28,6 @@
 //#define DEBUG_SLB
 //#define DEBUG_SOFTWARE_TLB
 //#define DUMP_PAGE_TABLES
-//#define DEBUG_EXCEPTIONS
 //#define FLUSH_ALL_TLBS
 
 #ifdef DEBUG_MMU
@@ -58,17 +57,6 @@
 #  define LOG_SLB(...) do { } while (0)
 #endif
 
-#ifdef DEBUG_EXCEPTIONS
-#  define LOG_EXCP(...) qemu_log(__VA_ARGS__)
-#else
-#  define LOG_EXCP(...) do { } while (0)
-#endif
-
-/*****************************************************************************/
-/* PowerPC Hypercall emulation */
-
-void (*cpu_ppc_hypercall)(CPUPPCState *);
-
 /*****************************************************************************/
 /* PowerPC MMU emulation */
 
@@ -2519,738 +2507,6 @@ void ppc_store_msr(CPUPPCState *env, target_ulong value)
     hreg_store_msr(env, value, 0);
 }
 
-/*****************************************************************************/
-/* Exception processing */
-#if defined(CONFIG_USER_ONLY)
-void do_interrupt(CPUPPCState *env)
-{
-    env->exception_index = POWERPC_EXCP_NONE;
-    env->error_code = 0;
-}
-
-void ppc_hw_interrupt(CPUPPCState *env)
-{
-    env->exception_index = POWERPC_EXCP_NONE;
-    env->error_code = 0;
-}
-#else /* defined(CONFIG_USER_ONLY) */
-static inline void dump_syscall(CPUPPCState *env)
-{
-    qemu_log_mask(CPU_LOG_INT, "syscall r0=%016" PRIx64 " r3=%016" PRIx64
-                  " r4=%016" PRIx64 " r5=%016" PRIx64 " r6=%016" PRIx64
-                  " nip=" TARGET_FMT_lx "\n",
-                  ppc_dump_gpr(env, 0), ppc_dump_gpr(env, 3),
-                  ppc_dump_gpr(env, 4), ppc_dump_gpr(env, 5),
-                  ppc_dump_gpr(env, 6), env->nip);
-}
-
-/* Note that this function should be greatly optimized
- * when called with a constant excp, from ppc_hw_interrupt
- */
-static inline void powerpc_excp(CPUPPCState *env, int excp_model, int excp)
-{
-    target_ulong msr, new_msr, vector;
-    int srr0, srr1, asrr0, asrr1;
-    int lpes0, lpes1, lev;
-
-    if (0) {
-        /* XXX: find a suitable condition to enable the hypervisor mode */
-        lpes0 = (env->spr[SPR_LPCR] >> 1) & 1;
-        lpes1 = (env->spr[SPR_LPCR] >> 2) & 1;
-    } else {
-        /* Those values ensure we won't enter the hypervisor mode */
-        lpes0 = 0;
-        lpes1 = 1;
-    }
-
-    qemu_log_mask(CPU_LOG_INT, "Raise exception at " TARGET_FMT_lx
-                  " => %08x (%02x)\n", env->nip, excp, env->error_code);
-
-    /* new srr1 value excluding must-be-zero bits */
-    msr = env->msr & ~0x783f0000ULL;
-
-    /* new interrupt handler msr */
-    new_msr = env->msr & ((target_ulong)1 << MSR_ME);
-
-    /* target registers */
-    srr0 = SPR_SRR0;
-    srr1 = SPR_SRR1;
-    asrr0 = -1;
-    asrr1 = -1;
-
-    switch (excp) {
-    case POWERPC_EXCP_NONE:
-        /* Should never happen */
-        return;
-    case POWERPC_EXCP_CRITICAL:    /* Critical input                         */
-        switch (excp_model) {
-        case POWERPC_EXCP_40x:
-            srr0 = SPR_40x_SRR2;
-            srr1 = SPR_40x_SRR3;
-            break;
-        case POWERPC_EXCP_BOOKE:
-            srr0 = SPR_BOOKE_CSRR0;
-            srr1 = SPR_BOOKE_CSRR1;
-            break;
-        case POWERPC_EXCP_G2:
-            break;
-        default:
-            goto excp_invalid;
-        }
-        goto store_next;
-    case POWERPC_EXCP_MCHECK:    /* Machine check exception                  */
-        if (msr_me == 0) {
-            /* Machine check exception is not enabled.
-             * Enter checkstop state.
-             */
-            if (qemu_log_enabled()) {
-                qemu_log("Machine check while not allowed. "
-                        "Entering checkstop state\n");
-            } else {
-                fprintf(stderr, "Machine check while not allowed. "
-                        "Entering checkstop state\n");
-            }
-            env->halted = 1;
-            env->interrupt_request |= CPU_INTERRUPT_EXITTB;
-        }
-        if (0) {
-            /* XXX: find a suitable condition to enable the hypervisor mode */
-            new_msr |= (target_ulong)MSR_HVB;
-        }
-
-        /* machine check exceptions don't have ME set */
-        new_msr &= ~((target_ulong)1 << MSR_ME);
-
-        /* XXX: should also have something loaded in DAR / DSISR */
-        switch (excp_model) {
-        case POWERPC_EXCP_40x:
-            srr0 = SPR_40x_SRR2;
-            srr1 = SPR_40x_SRR3;
-            break;
-        case POWERPC_EXCP_BOOKE:
-            srr0 = SPR_BOOKE_MCSRR0;
-            srr1 = SPR_BOOKE_MCSRR1;
-            asrr0 = SPR_BOOKE_CSRR0;
-            asrr1 = SPR_BOOKE_CSRR1;
-            break;
-        default:
-            break;
-        }
-        goto store_next;
-    case POWERPC_EXCP_DSI:       /* Data storage exception                   */
-        LOG_EXCP("DSI exception: DSISR=" TARGET_FMT_lx" DAR=" TARGET_FMT_lx
-                 "\n", env->spr[SPR_DSISR], env->spr[SPR_DAR]);
-        if (lpes1 == 0) {
-            new_msr |= (target_ulong)MSR_HVB;
-        }
-        goto store_next;
-    case POWERPC_EXCP_ISI:       /* Instruction storage exception            */
-        LOG_EXCP("ISI exception: msr=" TARGET_FMT_lx ", nip=" TARGET_FMT_lx
-                 "\n", msr, env->nip);
-        if (lpes1 == 0) {
-            new_msr |= (target_ulong)MSR_HVB;
-        }
-        msr |= env->error_code;
-        goto store_next;
-    case POWERPC_EXCP_EXTERNAL:  /* External input                           */
-        if (lpes0 == 1) {
-            new_msr |= (target_ulong)MSR_HVB;
-        }
-        goto store_next;
-    case POWERPC_EXCP_ALIGN:     /* Alignment exception                      */
-        if (lpes1 == 0) {
-            new_msr |= (target_ulong)MSR_HVB;
-        }
-        /* XXX: this is false */
-        /* Get rS/rD and rA from faulting opcode */
-        env->spr[SPR_DSISR] |= (ldl_code((env->nip - 4)) & 0x03FF0000) >> 16;
-        goto store_current;
-    case POWERPC_EXCP_PROGRAM:   /* Program exception                        */
-        switch (env->error_code & ~0xF) {
-        case POWERPC_EXCP_FP:
-            if ((msr_fe0 == 0 && msr_fe1 == 0) || msr_fp == 0) {
-                LOG_EXCP("Ignore floating point exception\n");
-                env->exception_index = POWERPC_EXCP_NONE;
-                env->error_code = 0;
-                return;
-            }
-            if (lpes1 == 0) {
-                new_msr |= (target_ulong)MSR_HVB;
-            }
-            msr |= 0x00100000;
-            if (msr_fe0 == msr_fe1) {
-                goto store_next;
-            }
-            msr |= 0x00010000;
-            break;
-        case POWERPC_EXCP_INVAL:
-            LOG_EXCP("Invalid instruction at " TARGET_FMT_lx "\n", env->nip);
-            if (lpes1 == 0) {
-                new_msr |= (target_ulong)MSR_HVB;
-            }
-            msr |= 0x00080000;
-            env->spr[SPR_BOOKE_ESR] = ESR_PIL;
-            break;
-        case POWERPC_EXCP_PRIV:
-            if (lpes1 == 0) {
-                new_msr |= (target_ulong)MSR_HVB;
-            }
-            msr |= 0x00040000;
-            env->spr[SPR_BOOKE_ESR] = ESR_PPR;
-            break;
-        case POWERPC_EXCP_TRAP:
-            if (lpes1 == 0) {
-                new_msr |= (target_ulong)MSR_HVB;
-            }
-            msr |= 0x00020000;
-            env->spr[SPR_BOOKE_ESR] = ESR_PTR;
-            break;
-        default:
-            /* Should never occur */
-            cpu_abort(env, "Invalid program exception %d. Aborting\n",
-                      env->error_code);
-            break;
-        }
-        goto store_current;
-    case POWERPC_EXCP_FPU:       /* Floating-point unavailable exception     */
-        if (lpes1 == 0) {
-            new_msr |= (target_ulong)MSR_HVB;
-        }
-        goto store_current;
-    case POWERPC_EXCP_SYSCALL:   /* System call exception                    */
-        dump_syscall(env);
-        lev = env->error_code;
-        if ((lev == 1) && cpu_ppc_hypercall) {
-            cpu_ppc_hypercall(env);
-            return;
-        }
-        if (lev == 1 || (lpes0 == 0 && lpes1 == 0)) {
-            new_msr |= (target_ulong)MSR_HVB;
-        }
-        goto store_next;
-    case POWERPC_EXCP_APU:       /* Auxiliary processor unavailable          */
-        goto store_current;
-    case POWERPC_EXCP_DECR:      /* Decrementer exception                    */
-        if (lpes1 == 0) {
-            new_msr |= (target_ulong)MSR_HVB;
-        }
-        goto store_next;
-    case POWERPC_EXCP_FIT:       /* Fixed-interval timer interrupt           */
-        /* FIT on 4xx */
-        LOG_EXCP("FIT exception\n");
-        goto store_next;
-    case POWERPC_EXCP_WDT:       /* Watchdog timer interrupt                 */
-        LOG_EXCP("WDT exception\n");
-        switch (excp_model) {
-        case POWERPC_EXCP_BOOKE:
-            srr0 = SPR_BOOKE_CSRR0;
-            srr1 = SPR_BOOKE_CSRR1;
-            break;
-        default:
-            break;
-        }
-        goto store_next;
-    case POWERPC_EXCP_DTLB:      /* Data TLB error                           */
-        goto store_next;
-    case POWERPC_EXCP_ITLB:      /* Instruction TLB error                    */
-        goto store_next;
-    case POWERPC_EXCP_DEBUG:     /* Debug interrupt                          */
-        switch (excp_model) {
-        case POWERPC_EXCP_BOOKE:
-            srr0 = SPR_BOOKE_DSRR0;
-            srr1 = SPR_BOOKE_DSRR1;
-            asrr0 = SPR_BOOKE_CSRR0;
-            asrr1 = SPR_BOOKE_CSRR1;
-            break;
-        default:
-            break;
-        }
-        /* XXX: TODO */
-        cpu_abort(env, "Debug exception is not implemented yet !\n");
-        goto store_next;
-    case POWERPC_EXCP_SPEU:      /* SPE/embedded floating-point unavailable  */
-        env->spr[SPR_BOOKE_ESR] = ESR_SPV;
-        goto store_current;
-    case POWERPC_EXCP_EFPDI:     /* Embedded floating-point data interrupt   */
-        /* XXX: TODO */
-        cpu_abort(env, "Embedded floating point data exception "
-                  "is not implemented yet !\n");
-        env->spr[SPR_BOOKE_ESR] = ESR_SPV;
-        goto store_next;
-    case POWERPC_EXCP_EFPRI:     /* Embedded floating-point round interrupt  */
-        /* XXX: TODO */
-        cpu_abort(env, "Embedded floating point round exception "
-                  "is not implemented yet !\n");
-        env->spr[SPR_BOOKE_ESR] = ESR_SPV;
-        goto store_next;
-    case POWERPC_EXCP_EPERFM:    /* Embedded performance monitor interrupt   */
-        /* XXX: TODO */
-        cpu_abort(env,
-                  "Performance counter exception is not implemented yet !\n");
-        goto store_next;
-    case POWERPC_EXCP_DOORI:     /* Embedded doorbell interrupt              */
-        goto store_next;
-    case POWERPC_EXCP_DOORCI:    /* Embedded doorbell critical interrupt     */
-        srr0 = SPR_BOOKE_CSRR0;
-        srr1 = SPR_BOOKE_CSRR1;
-        goto store_next;
-    case POWERPC_EXCP_RESET:     /* System reset exception                   */
-        if (msr_pow) {
-            /* indicate that we resumed from power save mode */
-            msr |= 0x10000;
-        } else {
-            new_msr &= ~((target_ulong)1 << MSR_ME);
-        }
-
-        if (0) {
-            /* XXX: find a suitable condition to enable the hypervisor mode */
-            new_msr |= (target_ulong)MSR_HVB;
-        }
-        goto store_next;
-    case POWERPC_EXCP_DSEG:      /* Data segment exception                   */
-        if (lpes1 == 0) {
-            new_msr |= (target_ulong)MSR_HVB;
-        }
-        goto store_next;
-    case POWERPC_EXCP_ISEG:      /* Instruction segment exception            */
-        if (lpes1 == 0) {
-            new_msr |= (target_ulong)MSR_HVB;
-        }
-        goto store_next;
-    case POWERPC_EXCP_HDECR:     /* Hypervisor decrementer exception         */
-        srr0 = SPR_HSRR0;
-        srr1 = SPR_HSRR1;
-        new_msr |= (target_ulong)MSR_HVB;
-        new_msr |= env->msr & ((target_ulong)1 << MSR_RI);
-        goto store_next;
-    case POWERPC_EXCP_TRACE:     /* Trace exception                          */
-        if (lpes1 == 0) {
-            new_msr |= (target_ulong)MSR_HVB;
-        }
-        goto store_next;
-    case POWERPC_EXCP_HDSI:      /* Hypervisor data storage exception        */
-        srr0 = SPR_HSRR0;
-        srr1 = SPR_HSRR1;
-        new_msr |= (target_ulong)MSR_HVB;
-        new_msr |= env->msr & ((target_ulong)1 << MSR_RI);
-        goto store_next;
-    case POWERPC_EXCP_HISI:      /* Hypervisor instruction storage exception */
-        srr0 = SPR_HSRR0;
-        srr1 = SPR_HSRR1;
-        new_msr |= (target_ulong)MSR_HVB;
-        new_msr |= env->msr & ((target_ulong)1 << MSR_RI);
-        goto store_next;
-    case POWERPC_EXCP_HDSEG:     /* Hypervisor data segment exception        */
-        srr0 = SPR_HSRR0;
-        srr1 = SPR_HSRR1;
-        new_msr |= (target_ulong)MSR_HVB;
-        new_msr |= env->msr & ((target_ulong)1 << MSR_RI);
-        goto store_next;
-    case POWERPC_EXCP_HISEG:     /* Hypervisor instruction segment exception */
-        srr0 = SPR_HSRR0;
-        srr1 = SPR_HSRR1;
-        new_msr |= (target_ulong)MSR_HVB;
-        new_msr |= env->msr & ((target_ulong)1 << MSR_RI);
-        goto store_next;
-    case POWERPC_EXCP_VPU:       /* Vector unavailable exception             */
-        if (lpes1 == 0) {
-            new_msr |= (target_ulong)MSR_HVB;
-        }
-        goto store_current;
-    case POWERPC_EXCP_PIT:       /* Programmable interval timer interrupt    */
-        LOG_EXCP("PIT exception\n");
-        goto store_next;
-    case POWERPC_EXCP_IO:        /* IO error exception                       */
-        /* XXX: TODO */
-        cpu_abort(env, "601 IO error exception is not implemented yet !\n");
-        goto store_next;
-    case POWERPC_EXCP_RUNM:      /* Run mode exception                       */
-        /* XXX: TODO */
-        cpu_abort(env, "601 run mode exception is not implemented yet !\n");
-        goto store_next;
-    case POWERPC_EXCP_EMUL:      /* Emulation trap exception                 */
-        /* XXX: TODO */
-        cpu_abort(env, "602 emulation trap exception "
-                  "is not implemented yet !\n");
-        goto store_next;
-    case POWERPC_EXCP_IFTLB:     /* Instruction fetch TLB error              */
-        if (lpes1 == 0) { /* XXX: check this */
-            new_msr |= (target_ulong)MSR_HVB;
-        }
-        switch (excp_model) {
-        case POWERPC_EXCP_602:
-        case POWERPC_EXCP_603:
-        case POWERPC_EXCP_603E:
-        case POWERPC_EXCP_G2:
-            goto tlb_miss_tgpr;
-        case POWERPC_EXCP_7x5:
-            goto tlb_miss;
-        case POWERPC_EXCP_74xx:
-            goto tlb_miss_74xx;
-        default:
-            cpu_abort(env, "Invalid instruction TLB miss exception\n");
-            break;
-        }
-        break;
-    case POWERPC_EXCP_DLTLB:     /* Data load TLB miss                       */
-        if (lpes1 == 0) { /* XXX: check this */
-            new_msr |= (target_ulong)MSR_HVB;
-        }
-        switch (excp_model) {
-        case POWERPC_EXCP_602:
-        case POWERPC_EXCP_603:
-        case POWERPC_EXCP_603E:
-        case POWERPC_EXCP_G2:
-            goto tlb_miss_tgpr;
-        case POWERPC_EXCP_7x5:
-            goto tlb_miss;
-        case POWERPC_EXCP_74xx:
-            goto tlb_miss_74xx;
-        default:
-            cpu_abort(env, "Invalid data load TLB miss exception\n");
-            break;
-        }
-        break;
-    case POWERPC_EXCP_DSTLB:     /* Data store TLB miss                      */
-        if (lpes1 == 0) { /* XXX: check this */
-            new_msr |= (target_ulong)MSR_HVB;
-        }
-        switch (excp_model) {
-        case POWERPC_EXCP_602:
-        case POWERPC_EXCP_603:
-        case POWERPC_EXCP_603E:
-        case POWERPC_EXCP_G2:
-        tlb_miss_tgpr:
-            /* Swap temporary saved registers with GPRs */
-            if (!(new_msr & ((target_ulong)1 << MSR_TGPR))) {
-                new_msr |= (target_ulong)1 << MSR_TGPR;
-                hreg_swap_gpr_tgpr(env);
-            }
-            goto tlb_miss;
-        case POWERPC_EXCP_7x5:
-        tlb_miss:
-#if defined(DEBUG_SOFTWARE_TLB)
-            if (qemu_log_enabled()) {
-                const char *es;
-                target_ulong *miss, *cmp;
-                int en;
-
-                if (excp == POWERPC_EXCP_IFTLB) {
-                    es = "I";
-                    en = 'I';
-                    miss = &env->spr[SPR_IMISS];
-                    cmp = &env->spr[SPR_ICMP];
-                } else {
-                    if (excp == POWERPC_EXCP_DLTLB) {
-                        es = "DL";
-                    } else {
-                        es = "DS";
-                    }
-                    en = 'D';
-                    miss = &env->spr[SPR_DMISS];
-                    cmp = &env->spr[SPR_DCMP];
-                }
-                qemu_log("6xx %sTLB miss: %cM " TARGET_FMT_lx " %cC "
-                         TARGET_FMT_lx " H1 " TARGET_FMT_lx " H2 "
-                         TARGET_FMT_lx " %08x\n", es, en, *miss, en, *cmp,
-                         env->spr[SPR_HASH1], env->spr[SPR_HASH2],
-                         env->error_code);
-            }
-#endif
-            msr |= env->crf[0] << 28;
-            msr |= env->error_code; /* key, D/I, S/L bits */
-            /* Set way using a LRU mechanism */
-            msr |= ((env->last_way + 1) & (env->nb_ways - 1)) << 17;
-            break;
-        case POWERPC_EXCP_74xx:
-        tlb_miss_74xx:
-#if defined(DEBUG_SOFTWARE_TLB)
-            if (qemu_log_enabled()) {
-                const char *es;
-                target_ulong *miss, *cmp;
-                int en;
-
-                if (excp == POWERPC_EXCP_IFTLB) {
-                    es = "I";
-                    en = 'I';
-                    miss = &env->spr[SPR_TLBMISS];
-                    cmp = &env->spr[SPR_PTEHI];
-                } else {
-                    if (excp == POWERPC_EXCP_DLTLB) {
-                        es = "DL";
-                    } else {
-                        es = "DS";
-                    }
-                    en = 'D';
-                    miss = &env->spr[SPR_TLBMISS];
-                    cmp = &env->spr[SPR_PTEHI];
-                }
-                qemu_log("74xx %sTLB miss: %cM " TARGET_FMT_lx " %cC "
-                         TARGET_FMT_lx " %08x\n", es, en, *miss, en, *cmp,
-                         env->error_code);
-            }
-#endif
-            msr |= env->error_code; /* key bit */
-            break;
-        default:
-            cpu_abort(env, "Invalid data store TLB miss exception\n");
-            break;
-        }
-        goto store_next;
-    case POWERPC_EXCP_FPA:       /* Floating-point assist exception          */
-        /* XXX: TODO */
-        cpu_abort(env, "Floating point assist exception "
-                  "is not implemented yet !\n");
-        goto store_next;
-    case POWERPC_EXCP_DABR:      /* Data address breakpoint                  */
-        /* XXX: TODO */
-        cpu_abort(env, "DABR exception is not implemented yet !\n");
-        goto store_next;
-    case POWERPC_EXCP_IABR:      /* Instruction address breakpoint           */
-        /* XXX: TODO */
-        cpu_abort(env, "IABR exception is not implemented yet !\n");
-        goto store_next;
-    case POWERPC_EXCP_SMI:       /* System management interrupt              */
-        /* XXX: TODO */
-        cpu_abort(env, "SMI exception is not implemented yet !\n");
-        goto store_next;
-    case POWERPC_EXCP_THERM:     /* Thermal interrupt                        */
-        /* XXX: TODO */
-        cpu_abort(env, "Thermal management exception "
-                  "is not implemented yet !\n");
-        goto store_next;
-    case POWERPC_EXCP_PERFM:     /* Embedded performance monitor interrupt   */
-        if (lpes1 == 0) {
-            new_msr |= (target_ulong)MSR_HVB;
-        }
-        /* XXX: TODO */
-        cpu_abort(env,
-                  "Performance counter exception is not implemented yet !\n");
-        goto store_next;
-    case POWERPC_EXCP_VPUA:      /* Vector assist exception                  */
-        /* XXX: TODO */
-        cpu_abort(env, "VPU assist exception is not implemented yet !\n");
-        goto store_next;
-    case POWERPC_EXCP_SOFTP:     /* Soft patch exception                     */
-        /* XXX: TODO */
-        cpu_abort(env,
-                  "970 soft-patch exception is not implemented yet !\n");
-        goto store_next;
-    case POWERPC_EXCP_MAINT:     /* Maintenance exception                    */
-        /* XXX: TODO */
-        cpu_abort(env,
-                  "970 maintenance exception is not implemented yet !\n");
-        goto store_next;
-    case POWERPC_EXCP_MEXTBR:    /* Maskable external breakpoint             */
-        /* XXX: TODO */
-        cpu_abort(env, "Maskable external exception "
-                  "is not implemented yet !\n");
-        goto store_next;
-    case POWERPC_EXCP_NMEXTBR:   /* Non maskable external breakpoint         */
-        /* XXX: TODO */
-        cpu_abort(env, "Non maskable external exception "
-                  "is not implemented yet !\n");
-        goto store_next;
-    default:
-    excp_invalid:
-        cpu_abort(env, "Invalid PowerPC exception %d. Aborting\n", excp);
-        break;
-    store_current:
-        /* save current instruction location */
-        env->spr[srr0] = env->nip - 4;
-        break;
-    store_next:
-        /* save next instruction location */
-        env->spr[srr0] = env->nip;
-        break;
-    }
-    /* Save MSR */
-    env->spr[srr1] = msr;
-    /* If any alternate SRR register are defined, duplicate saved values */
-    if (asrr0 != -1) {
-        env->spr[asrr0] = env->spr[srr0];
-    }
-    if (asrr1 != -1) {
-        env->spr[asrr1] = env->spr[srr1];
-    }
-    /* If we disactivated any translation, flush TLBs */
-    if (msr & ((1 << MSR_IR) | (1 << MSR_DR))) {
-        tlb_flush(env, 1);
-    }
-
-    if (msr_ile) {
-        new_msr |= (target_ulong)1 << MSR_LE;
-    }
-
-    /* Jump to handler */
-    vector = env->excp_vectors[excp];
-    if (vector == (target_ulong)-1ULL) {
-        cpu_abort(env, "Raised an exception without defined vector %d\n",
-                  excp);
-    }
-    vector |= env->excp_prefix;
-#if defined(TARGET_PPC64)
-    if (excp_model == POWERPC_EXCP_BOOKE) {
-        if (!msr_icm) {
-            vector = (uint32_t)vector;
-        } else {
-            new_msr |= (target_ulong)1 << MSR_CM;
-        }
-    } else {
-        if (!msr_isf && !(env->mmu_model & POWERPC_MMU_64)) {
-            vector = (uint32_t)vector;
-        } else {
-            new_msr |= (target_ulong)1 << MSR_SF;
-        }
-    }
-#endif
-    /* XXX: we don't use hreg_store_msr here as already have treated
-     *      any special case that could occur. Just store MSR and update hflags
-     */
-    env->msr = new_msr & env->msr_mask;
-    hreg_compute_hflags(env);
-    env->nip = vector;
-    /* Reset exception state */
-    env->exception_index = POWERPC_EXCP_NONE;
-    env->error_code = 0;
-
-    if ((env->mmu_model == POWERPC_MMU_BOOKE) ||
-        (env->mmu_model == POWERPC_MMU_BOOKE206)) {
-        /* XXX: The BookE changes address space when switching modes,
-                we should probably implement that as different MMU indexes,
-                but for the moment we do it the slow way and flush all.  */
-        tlb_flush(env, 1);
-    }
-}
-
-void do_interrupt(CPUPPCState *env)
-{
-    powerpc_excp(env, env->excp_model, env->exception_index);
-}
-
-void ppc_hw_interrupt(CPUPPCState *env)
-{
-    int hdice;
-
-#if 0
-    qemu_log_mask(CPU_LOG_INT, "%s: %p pending %08x req %08x me %d ee %d\n",
-                __func__, env, env->pending_interrupts,
-                env->interrupt_request, (int)msr_me, (int)msr_ee);
-#endif
-    /* External reset */
-    if (env->pending_interrupts & (1 << PPC_INTERRUPT_RESET)) {
-        env->pending_interrupts &= ~(1 << PPC_INTERRUPT_RESET);
-        powerpc_excp(env, env->excp_model, POWERPC_EXCP_RESET);
-        return;
-    }
-    /* Machine check exception */
-    if (env->pending_interrupts & (1 << PPC_INTERRUPT_MCK)) {
-        env->pending_interrupts &= ~(1 << PPC_INTERRUPT_MCK);
-        powerpc_excp(env, env->excp_model, POWERPC_EXCP_MCHECK);
-        return;
-    }
-#if 0 /* TODO */
-    /* External debug exception */
-    if (env->pending_interrupts & (1 << PPC_INTERRUPT_DEBUG)) {
-        env->pending_interrupts &= ~(1 << PPC_INTERRUPT_DEBUG);
-        powerpc_excp(env, env->excp_model, POWERPC_EXCP_DEBUG);
-        return;
-    }
-#endif
-    if (0) {
-        /* XXX: find a suitable condition to enable the hypervisor mode */
-        hdice = env->spr[SPR_LPCR] & 1;
-    } else {
-        hdice = 0;
-    }
-    if ((msr_ee != 0 || msr_hv == 0 || msr_pr != 0) && hdice != 0) {
-        /* Hypervisor decrementer exception */
-        if (env->pending_interrupts & (1 << PPC_INTERRUPT_HDECR)) {
-            env->pending_interrupts &= ~(1 << PPC_INTERRUPT_HDECR);
-            powerpc_excp(env, env->excp_model, POWERPC_EXCP_HDECR);
-            return;
-        }
-    }
-    if (msr_ce != 0) {
-        /* External critical interrupt */
-        if (env->pending_interrupts & (1 << PPC_INTERRUPT_CEXT)) {
-            /* Taking a critical external interrupt does not clear the external
-             * critical interrupt status
-             */
-#if 0
-            env->pending_interrupts &= ~(1 << PPC_INTERRUPT_CEXT);
-#endif
-            powerpc_excp(env, env->excp_model, POWERPC_EXCP_CRITICAL);
-            return;
-        }
-    }
-    if (msr_ee != 0) {
-        /* Watchdog timer on embedded PowerPC */
-        if (env->pending_interrupts & (1 << PPC_INTERRUPT_WDT)) {
-            env->pending_interrupts &= ~(1 << PPC_INTERRUPT_WDT);
-            powerpc_excp(env, env->excp_model, POWERPC_EXCP_WDT);
-            return;
-        }
-        if (env->pending_interrupts & (1 << PPC_INTERRUPT_CDOORBELL)) {
-            env->pending_interrupts &= ~(1 << PPC_INTERRUPT_CDOORBELL);
-            powerpc_excp(env, env->excp_model, POWERPC_EXCP_DOORCI);
-            return;
-        }
-        /* Fixed interval timer on embedded PowerPC */
-        if (env->pending_interrupts & (1 << PPC_INTERRUPT_FIT)) {
-            env->pending_interrupts &= ~(1 << PPC_INTERRUPT_FIT);
-            powerpc_excp(env, env->excp_model, POWERPC_EXCP_FIT);
-            return;
-        }
-        /* Programmable interval timer on embedded PowerPC */
-        if (env->pending_interrupts & (1 << PPC_INTERRUPT_PIT)) {
-            env->pending_interrupts &= ~(1 << PPC_INTERRUPT_PIT);
-            powerpc_excp(env, env->excp_model, POWERPC_EXCP_PIT);
-            return;
-        }
-        /* Decrementer exception */
-        if (env->pending_interrupts & (1 << PPC_INTERRUPT_DECR)) {
-            env->pending_interrupts &= ~(1 << PPC_INTERRUPT_DECR);
-            powerpc_excp(env, env->excp_model, POWERPC_EXCP_DECR);
-            return;
-        }
-        /* External interrupt */
-        if (env->pending_interrupts & (1 << PPC_INTERRUPT_EXT)) {
-            /* Taking an external interrupt does not clear the external
-             * interrupt status
-             */
-#if 0
-            env->pending_interrupts &= ~(1 << PPC_INTERRUPT_EXT);
-#endif
-            powerpc_excp(env, env->excp_model, POWERPC_EXCP_EXTERNAL);
-            return;
-        }
-        if (env->pending_interrupts & (1 << PPC_INTERRUPT_DOORBELL)) {
-            env->pending_interrupts &= ~(1 << PPC_INTERRUPT_DOORBELL);
-            powerpc_excp(env, env->excp_model, POWERPC_EXCP_DOORI);
-            return;
-        }
-        if (env->pending_interrupts & (1 << PPC_INTERRUPT_PERFM)) {
-            env->pending_interrupts &= ~(1 << PPC_INTERRUPT_PERFM);
-            powerpc_excp(env, env->excp_model, POWERPC_EXCP_PERFM);
-            return;
-        }
-        /* Thermal interrupt */
-        if (env->pending_interrupts & (1 << PPC_INTERRUPT_THERM)) {
-            env->pending_interrupts &= ~(1 << PPC_INTERRUPT_THERM);
-            powerpc_excp(env, env->excp_model, POWERPC_EXCP_THERM);
-            return;
-        }
-    }
-}
-#endif /* !CONFIG_USER_ONLY */
-
-void cpu_dump_rfi(target_ulong RA, target_ulong msr)
-{
-    qemu_log("Return from exception at " TARGET_FMT_lx " with flags "
-             TARGET_FMT_lx "\n", RA, msr);
-}
-
 PowerPCCPU *cpu_ppc_init(const char *cpu_model)
 {
     PowerPCCPU *cpu;
commit 4d5ea5e5236331b89adcacd2d68b40a849d3c9f8
Author: Blue Swirl <blauwirbel at gmail.com>
Date:   Wed May 30 04:23:24 2012 +0000

    ppc: Fix coding style in helper.c
    
    helper.c will be spilt by the next patches, fix
    style issues before that.
    
    Signed-off-by: Blue Swirl <blauwirbel at gmail.com>
    Signed-off-by: Alexander Graf <agraf at suse.de>
    Signed-off-by: Andreas Färber <afaerber at suse.de>
    Signed-off-by: Alexander Graf <agraf at suse.de>

diff --git a/target-ppc/helper.c b/target-ppc/helper.c
index 3f7d8a4..44f1cdd 100644
--- a/target-ppc/helper.c
+++ b/target-ppc/helper.c
@@ -1,5 +1,5 @@
 /*
- *  PowerPC emulation helpers for qemu.
+ *  PowerPC emulation helpers for QEMU.
  *
  *  Copyright (c) 2003-2007 Jocelyn Mayer
  *
@@ -73,8 +73,8 @@ void (*cpu_ppc_hypercall)(CPUPPCState *);
 /* PowerPC MMU emulation */
 
 #if defined(CONFIG_USER_ONLY)
-int cpu_ppc_handle_mmu_fault (CPUPPCState *env, target_ulong address, int rw,
-                              int mmu_idx)
+int cpu_ppc_handle_mmu_fault(CPUPPCState *env, target_ulong address, int rw,
+                             int mmu_idx)
 {
     int exception, error_code;
 
@@ -84,8 +84,9 @@ int cpu_ppc_handle_mmu_fault (CPUPPCState *env, target_ulong address, int rw,
     } else {
         exception = POWERPC_EXCP_DSI;
         error_code = 0x40000000;
-        if (rw)
+        if (rw) {
             error_code |= 0x02000000;
+        }
         env->spr[SPR_DAR] = address;
         env->spr[SPR_DSISR] = error_code;
     }
@@ -160,8 +161,9 @@ static inline int pp_check(int key, int pp, int nx)
             break;
         }
     }
-    if (nx == 0)
+    if (nx == 0) {
         access |= PAGE_EXEC;
+    }
 
     return access;
 }
@@ -171,27 +173,30 @@ static inline int check_prot(int prot, int rw, int access_type)
     int ret;
 
     if (access_type == ACCESS_CODE) {
-        if (prot & PAGE_EXEC)
+        if (prot & PAGE_EXEC) {
             ret = 0;
-        else
+        } else {
             ret = -2;
+        }
     } else if (rw) {
-        if (prot & PAGE_WRITE)
+        if (prot & PAGE_WRITE) {
             ret = 0;
-        else
+        } else {
             ret = -2;
+        }
     } else {
-        if (prot & PAGE_READ)
+        if (prot & PAGE_READ) {
             ret = 0;
-        else
+        } else {
             ret = -2;
+        }
     }
 
     return ret;
 }
 
-static inline int _pte_check(mmu_ctx_t *ctx, int is_64b, target_ulong pte0,
-                             target_ulong pte1, int h, int rw, int type)
+static inline int pte_check(mmu_ctx_t *ctx, int is_64b, target_ulong pte0,
+                            target_ulong pte1, int h, int rw, int type)
 {
     target_ulong ptem, mmask;
     int access, ret, pteh, ptev, pp;
@@ -254,14 +259,14 @@ static inline int _pte_check(mmu_ctx_t *ctx, int is_64b, target_ulong pte0,
 static inline int pte32_check(mmu_ctx_t *ctx, target_ulong pte0,
                               target_ulong pte1, int h, int rw, int type)
 {
-    return _pte_check(ctx, 0, pte0, pte1, h, rw, type);
+    return pte_check(ctx, 0, pte0, pte1, h, rw, type);
 }
 
 #if defined(TARGET_PPC64)
 static inline int pte64_check(mmu_ctx_t *ctx, target_ulong pte0,
                               target_ulong pte1, int h, int rw, int type)
 {
-    return _pte_check(ctx, 1, pte0, pte1, h, rw, type);
+    return pte_check(ctx, 1, pte0, pte1, h, rw, type);
 }
 #endif
 
@@ -291,8 +296,8 @@ static inline int pte_update_flags(mmu_ctx_t *ctx, target_ulong *pte1p,
 }
 
 /* Software driven TLB helpers */
-static inline int ppc6xx_tlb_getnum(CPUPPCState *env, target_ulong eaddr, int way,
-                                    int is_code)
+static inline int ppc6xx_tlb_getnum(CPUPPCState *env, target_ulong eaddr,
+                                    int way, int is_code)
 {
     int nr;
 
@@ -301,8 +306,9 @@ static inline int ppc6xx_tlb_getnum(CPUPPCState *env, target_ulong eaddr, int wa
     /* Select TLB way */
     nr += env->tlb_per_way * way;
     /* 6xx have separate TLBs for instructions and data */
-    if (is_code && env->id_tlbs == 1)
+    if (is_code && env->id_tlbs == 1) {
         nr += env->nb_tlb;
+    }
 
     return nr;
 }
@@ -312,11 +318,12 @@ static inline void ppc6xx_tlb_invalidate_all(CPUPPCState *env)
     ppc6xx_tlb_t *tlb;
     int nr, max;
 
-    //LOG_SWTLB("Invalidate all TLBs\n");
+    /* LOG_SWTLB("Invalidate all TLBs\n"); */
     /* Invalidate all defined software TLB */
     max = env->nb_tlb;
-    if (env->id_tlbs == 1)
+    if (env->id_tlbs == 1) {
         max *= 2;
+    }
     for (nr = 0; nr < max; nr++) {
         tlb = &env->tlb.tlb6[nr];
         pte_invalidate(&tlb->pte0);
@@ -324,9 +331,9 @@ static inline void ppc6xx_tlb_invalidate_all(CPUPPCState *env)
     tlb_flush(env, 1);
 }
 
-static inline void __ppc6xx_tlb_invalidate_virt(CPUPPCState *env,
-                                                target_ulong eaddr,
-                                                int is_code, int match_epn)
+static inline void ppc6xx_tlb_invalidate_virt2(CPUPPCState *env,
+                                               target_ulong eaddr,
+                                               int is_code, int match_epn)
 {
 #if !defined(FLUSH_ALL_TLBS)
     ppc6xx_tlb_t *tlb;
@@ -352,11 +359,11 @@ static inline void __ppc6xx_tlb_invalidate_virt(CPUPPCState *env,
 static inline void ppc6xx_tlb_invalidate_virt(CPUPPCState *env,
                                               target_ulong eaddr, int is_code)
 {
-    __ppc6xx_tlb_invalidate_virt(env, eaddr, is_code, 0);
+    ppc6xx_tlb_invalidate_virt2(env, eaddr, is_code, 0);
 }
 
-void ppc6xx_tlb_store (CPUPPCState *env, target_ulong EPN, int way, int is_code,
-                       target_ulong pte0, target_ulong pte1)
+void ppc6xx_tlb_store(CPUPPCState *env, target_ulong EPN, int way, int is_code,
+                      target_ulong pte0, target_ulong pte1)
 {
     ppc6xx_tlb_t *tlb;
     int nr;
@@ -366,7 +373,7 @@ void ppc6xx_tlb_store (CPUPPCState *env, target_ulong EPN, int way, int is_code,
     LOG_SWTLB("Set TLB %d/%d EPN " TARGET_FMT_lx " PTE0 " TARGET_FMT_lx
               " PTE1 " TARGET_FMT_lx "\n", nr, env->nb_tlb, EPN, pte0, pte1);
     /* Invalidate any pending reference in QEMU for this virtual address */
-    __ppc6xx_tlb_invalidate_virt(env, EPN, is_code, 1);
+    ppc6xx_tlb_invalidate_virt2(env, EPN, is_code, 1);
     tlb->pte0 = pte0;
     tlb->pte1 = pte1;
     tlb->EPN = EPN;
@@ -436,8 +443,8 @@ static inline int ppc6xx_tlb_check(CPUPPCState *env, mmu_ctx_t *ctx,
 }
 
 /* Perform BAT hit & translation */
-static inline void bat_size_prot(CPUPPCState *env, target_ulong *blp, int *validp,
-                                 int *protp, target_ulong *BATu,
+static inline void bat_size_prot(CPUPPCState *env, target_ulong *blp,
+                                 int *validp, int *protp, target_ulong *BATu,
                                  target_ulong *BATl)
 {
     target_ulong bl;
@@ -452,8 +459,9 @@ static inline void bat_size_prot(CPUPPCState *env, target_ulong *blp, int *valid
         pp = *BATl & 0x00000003;
         if (pp != 0) {
             prot = PAGE_READ | PAGE_EXEC;
-            if (pp == 0x2)
+            if (pp == 0x2) {
                 prot |= PAGE_WRITE;
+            }
         }
     }
     *blp = bl;
@@ -475,10 +483,11 @@ static inline void bat_601_size_prot(CPUPPCState *env, target_ulong *blp,
     valid = (*BATl >> 6) & 1;
     if (valid) {
         pp = *BATu & 0x00000003;
-        if (msr_pr == 0)
+        if (msr_pr == 0) {
             key = (*BATu >> 3) & 1;
-        else
+        } else {
             key = (*BATu >> 2) & 1;
+        }
         prot = pp_check(key, pp, 0);
     }
     *blp = bl;
@@ -486,8 +495,8 @@ static inline void bat_601_size_prot(CPUPPCState *env, target_ulong *blp,
     *protp = prot;
 }
 
-static inline int get_bat(CPUPPCState *env, mmu_ctx_t *ctx, target_ulong virtual,
-                          int rw, int type)
+static inline int get_bat(CPUPPCState *env, mmu_ctx_t *ctx,
+                          target_ulong virtual, int rw, int type)
 {
     target_ulong *BATlt, *BATut, *BATu, *BATl;
     target_ulong BEPIl, BEPIu, bl;
@@ -530,10 +539,11 @@ static inline int get_bat(CPUPPCState *env, mmu_ctx_t *ctx, target_ulong virtual
                 /* Compute access rights */
                 ctx->prot = prot;
                 ret = check_prot(ctx->prot, rw, type);
-                if (ret == 0)
+                if (ret == 0) {
                     LOG_BATS("BAT %d match: r " TARGET_FMT_plx " prot=%c%c\n",
                              i, ctx->raddr, ctx->prot & PAGE_READ ? 'R' : '-',
                              ctx->prot & PAGE_WRITE ? 'W' : '-');
+                }
                 break;
             }
         }
@@ -569,7 +579,7 @@ static inline target_phys_addr_t get_pteg_offset(CPUPPCState *env,
 }
 
 /* PTE table lookup */
-static inline int _find_pte(CPUPPCState *env, mmu_ctx_t *ctx, int is_64b, int h,
+static inline int find_pte2(CPUPPCState *env, mmu_ctx_t *ctx, int is_64b, int h,
                             int rw, int type, int target_page_bits)
 {
     target_phys_addr_t pteg_off;
@@ -679,11 +689,12 @@ static inline int find_pte(CPUPPCState *env, mmu_ctx_t *ctx, int h, int rw,
                            int type, int target_page_bits)
 {
 #if defined(TARGET_PPC64)
-    if (env->mmu_model & POWERPC_MMU_64)
-        return _find_pte(env, ctx, 1, h, rw, type, target_page_bits);
+    if (env->mmu_model & POWERPC_MMU_64) {
+        return find_pte2(env, ctx, 1, h, rw, type, target_page_bits);
+    }
 #endif
 
-    return _find_pte(env, ctx, 0, h, rw, type, target_page_bits);
+    return find_pte2(env, ctx, 0, h, rw, type, target_page_bits);
 }
 
 #if defined(TARGET_PPC64)
@@ -716,7 +727,7 @@ static inline ppc_slb_t *slb_lookup(CPUPPCState *env, target_ulong eaddr)
     return NULL;
 }
 
-void ppc_slb_invalidate_all (CPUPPCState *env)
+void ppc_slb_invalidate_all(CPUPPCState *env)
 {
     int n, do_invalidate;
 
@@ -734,11 +745,12 @@ void ppc_slb_invalidate_all (CPUPPCState *env)
             do_invalidate = 1;
         }
     }
-    if (do_invalidate)
+    if (do_invalidate) {
         tlb_flush(env, 1);
+    }
 }
 
-void ppc_slb_invalidate_one (CPUPPCState *env, uint64_t T0)
+void ppc_slb_invalidate_one(CPUPPCState *env, uint64_t T0)
 {
     ppc_slb_t *slb;
 
@@ -758,7 +770,7 @@ void ppc_slb_invalidate_one (CPUPPCState *env, uint64_t T0)
     }
 }
 
-int ppc_store_slb (CPUPPCState *env, target_ulong rb, target_ulong rs)
+int ppc_store_slb(CPUPPCState *env, target_ulong rb, target_ulong rs)
 {
     int slot = rb & 0xfff;
     ppc_slb_t *slb = &env->slb[slot];
@@ -784,7 +796,7 @@ int ppc_store_slb (CPUPPCState *env, target_ulong rb, target_ulong rs)
     return 0;
 }
 
-int ppc_load_slb_esid (CPUPPCState *env, target_ulong rb, target_ulong *rt)
+int ppc_load_slb_esid(CPUPPCState *env, target_ulong rb, target_ulong *rt)
 {
     int slot = rb & 0xfff;
     ppc_slb_t *slb = &env->slb[slot];
@@ -797,7 +809,7 @@ int ppc_load_slb_esid (CPUPPCState *env, target_ulong rb, target_ulong *rt)
     return 0;
 }
 
-int ppc_load_slb_vsid (CPUPPCState *env, target_ulong rb, target_ulong *rt)
+int ppc_load_slb_vsid(CPUPPCState *env, target_ulong rb, target_ulong *rt)
 {
     int slot = rb & 0xfff;
     ppc_slb_t *slb = &env->slb[slot];
@@ -909,21 +921,24 @@ static inline int get_segment(CPUPPCState *env, mmu_ctx_t *ctx,
                 ret = find_pte(env, ctx, 0, rw, type, target_page_bits);
                 if (ret < 0) {
                     /* Secondary table lookup */
-                    if (eaddr != 0xEFFFFFFF)
+                    if (eaddr != 0xEFFFFFFF) {
                         LOG_MMU("1 htab=" TARGET_FMT_plx "/" TARGET_FMT_plx
                                 " vsid=" TARGET_FMT_lx " api=" TARGET_FMT_lx
                                 " hash=" TARGET_FMT_plx "\n", env->htab_base,
                                 env->htab_mask, vsid, ctx->ptem, ctx->hash[1]);
+                    }
                     ret2 = find_pte(env, ctx, 1, rw, type,
                                     target_page_bits);
-                    if (ret2 != -1)
+                    if (ret2 != -1) {
                         ret = ret2;
+                    }
                 }
             }
-#if defined (DUMP_PAGE_TABLES)
+#if defined(DUMP_PAGE_TABLES)
             if (qemu_log_enabled()) {
                 target_phys_addr_t curaddr;
                 uint32_t a0, a1, a2, a3;
+
                 qemu_log("Page table: " TARGET_FMT_plx " len " TARGET_FMT_plx
                          "\n", sdr, mask + 0x80);
                 for (curaddr = sdr; curaddr < (sdr + mask + 0x80);
@@ -945,6 +960,7 @@ static inline int get_segment(CPUPPCState *env, mmu_ctx_t *ctx,
         }
     } else {
         target_ulong sr;
+
         LOG_MMU("direct store...\n");
         /* Direct-store segment : absolutely *BUGGY* for now */
 
@@ -1018,11 +1034,13 @@ int ppcemb_tlb_check(CPUPPCState *env, ppcemb_tlb_t *tlb,
               " " TARGET_FMT_lx " %u %x\n", __func__, i, address, pid, tlb->EPN,
               mask, (uint32_t)tlb->PID, tlb->prot);
     /* Check PID */
-    if (tlb->PID != 0 && tlb->PID != pid)
+    if (tlb->PID != 0 && tlb->PID != pid) {
         return -1;
+    }
     /* Check effective address */
-    if ((address & mask) != tlb->EPN)
+    if ((address & mask) != tlb->EPN) {
         return -1;
+    }
     *raddrp = (tlb->RPN & mask) | (address & ~mask);
 #if (TARGET_PHYS_ADDR_BITS >= 36)
     if (ext) {
@@ -1035,7 +1053,7 @@ int ppcemb_tlb_check(CPUPPCState *env, ppcemb_tlb_t *tlb,
 }
 
 /* Generic TLB search function for PowerPC embedded implementations */
-int ppcemb_tlb_search (CPUPPCState *env, target_ulong address, uint32_t pid)
+int ppcemb_tlb_search(CPUPPCState *env, target_ulong address, uint32_t pid)
 {
     ppcemb_tlb_t *tlb;
     target_phys_addr_t raddr;
@@ -1080,8 +1098,9 @@ static inline void ppc4xx_tlb_invalidate_virt(CPUPPCState *env,
         tlb = &env->tlb.tlbe[i];
         if (ppcemb_tlb_check(env, tlb, &raddr, eaddr, pid, 0, i) == 0) {
             end = tlb->EPN + tlb->size;
-            for (page = tlb->EPN; page < end; page += TARGET_PAGE_SIZE)
+            for (page = tlb->EPN; page < end; page += TARGET_PAGE_SIZE) {
                 tlb_flush_page(env, page);
+            }
             tlb->prot &= ~PAGE_VALID;
             break;
         }
@@ -1091,8 +1110,9 @@ static inline void ppc4xx_tlb_invalidate_virt(CPUPPCState *env,
 #endif
 }
 
-static int mmu40x_get_physical_address (CPUPPCState *env, mmu_ctx_t *ctx,
-                                 target_ulong address, int rw, int access_type)
+static int mmu40x_get_physical_address(CPUPPCState *env, mmu_ctx_t *ctx,
+                                       target_ulong address, int rw,
+                                       int access_type)
 {
     ppcemb_tlb_t *tlb;
     target_phys_addr_t raddr;
@@ -1104,8 +1124,9 @@ static int mmu40x_get_physical_address (CPUPPCState *env, mmu_ctx_t *ctx,
     for (i = 0; i < env->nb_tlb; i++) {
         tlb = &env->tlb.tlbe[i];
         if (ppcemb_tlb_check(env, tlb, &raddr, address,
-                             env->spr[SPR_40x_PID], 0, i) < 0)
+                             env->spr[SPR_40x_PID], 0, i) < 0) {
             continue;
+        }
         zsel = (tlb->attr >> 4) & 0xF;
         zpr = (env->spr[SPR_40x_ZPR] >> (30 - (2 * zsel))) & 0x3;
         LOG_SWTLB("%s: TLB %d zsel %d zpr %d rw %d attr %08x\n",
@@ -1113,8 +1134,9 @@ static int mmu40x_get_physical_address (CPUPPCState *env, mmu_ctx_t *ctx,
         /* Check execute enable bit */
         switch (zpr) {
         case 0x2:
-            if (pr != 0)
+            if (pr != 0) {
                 goto check_perms;
+            }
             /* No break here */
         case 0x3:
             /* All accesses granted */
@@ -1135,8 +1157,9 @@ static int mmu40x_get_physical_address (CPUPPCState *env, mmu_ctx_t *ctx,
             /* Check from TLB entry */
             ctx->prot = tlb->prot;
             ret = check_prot(ctx->prot, rw, access_type);
-            if (ret == -2)
+            if (ret == -2) {
                 env->spr[SPR_40x_ESR] = 0;
+            }
             break;
         }
         if (ret >= 0) {
@@ -1153,7 +1176,7 @@ static int mmu40x_get_physical_address (CPUPPCState *env, mmu_ctx_t *ctx,
     return ret;
 }
 
-void store_40x_sler (CPUPPCState *env, uint32_t val)
+void store_40x_sler(CPUPPCState *env, uint32_t val)
 {
     /* XXX: TO BE FIXED */
     if (val != 0x00000000) {
@@ -1162,12 +1185,12 @@ void store_40x_sler (CPUPPCState *env, uint32_t val)
     env->spr[SPR_405_SLER] = val;
 }
 
-static inline int mmubooke_check_tlb (CPUPPCState *env, ppcemb_tlb_t *tlb,
-                                      target_phys_addr_t *raddr, int *prot,
-                                      target_ulong address, int rw,
-                                      int access_type, int i)
+static inline int mmubooke_check_tlb(CPUPPCState *env, ppcemb_tlb_t *tlb,
+                                     target_phys_addr_t *raddr, int *prot,
+                                     target_ulong address, int rw,
+                                     int access_type, int i)
 {
-    int ret, _prot;
+    int ret, prot2;
 
     if (ppcemb_tlb_check(env, tlb, raddr, address,
                          env->spr[SPR_BOOKE_PID],
@@ -1193,9 +1216,9 @@ static inline int mmubooke_check_tlb (CPUPPCState *env, ppcemb_tlb_t *tlb,
 found_tlb:
 
     if (msr_pr != 0) {
-        _prot = tlb->prot & 0xF;
+        prot2 = tlb->prot & 0xF;
     } else {
-        _prot = (tlb->prot >> 4) & 0xF;
+        prot2 = (tlb->prot >> 4) & 0xF;
     }
 
     /* Check the address space */
@@ -1205,13 +1228,13 @@ found_tlb:
             return -1;
         }
 
-        *prot = _prot;
-        if (_prot & PAGE_EXEC) {
+        *prot = prot2;
+        if (prot2 & PAGE_EXEC) {
             LOG_SWTLB("%s: good TLB!\n", __func__);
             return 0;
         }
 
-        LOG_SWTLB("%s: no PAGE_EXEC: %x\n", __func__, _prot);
+        LOG_SWTLB("%s: no PAGE_EXEC: %x\n", __func__, prot2);
         ret = -3;
     } else {
         if (msr_dr != (tlb->attr & 1)) {
@@ -1219,22 +1242,22 @@ found_tlb:
             return -1;
         }
 
-        *prot = _prot;
-        if ((!rw && _prot & PAGE_READ) || (rw && (_prot & PAGE_WRITE))) {
+        *prot = prot2;
+        if ((!rw && prot2 & PAGE_READ) || (rw && (prot2 & PAGE_WRITE))) {
             LOG_SWTLB("%s: found TLB!\n", __func__);
             return 0;
         }
 
-        LOG_SWTLB("%s: PAGE_READ/WRITE doesn't match: %x\n", __func__, _prot);
+        LOG_SWTLB("%s: PAGE_READ/WRITE doesn't match: %x\n", __func__, prot2);
         ret = -2;
     }
 
     return ret;
 }
 
-static int mmubooke_get_physical_address (CPUPPCState *env, mmu_ctx_t *ctx,
-                                          target_ulong address, int rw,
-                                          int access_type)
+static int mmubooke_get_physical_address(CPUPPCState *env, mmu_ctx_t *ctx,
+                                         target_ulong address, int rw,
+                                         int access_type)
 {
     ppcemb_tlb_t *tlb;
     target_phys_addr_t raddr;
@@ -1285,7 +1308,8 @@ void booke206_flush_tlb(CPUPPCState *env, int flags, const int check_iprot)
     tlb_flush(env, 1);
 }
 
-target_phys_addr_t booke206_tlb_to_page_size(CPUPPCState *env, ppcmas_tlb_t *tlb)
+target_phys_addr_t booke206_tlb_to_page_size(CPUPPCState *env,
+                                             ppcmas_tlb_t *tlb)
 {
     int tlbm_size;
 
@@ -1337,7 +1361,7 @@ static int mmubooke206_check_tlb(CPUPPCState *env, ppcmas_tlb_t *tlb,
                                  int access_type)
 {
     int ret;
-    int _prot = 0;
+    int prot2 = 0;
 
     if (ppcmas_tlb_check(env, tlb, raddr, address,
                          env->spr[SPR_BOOKE_PID]) >= 0) {
@@ -1363,23 +1387,23 @@ found_tlb:
 
     if (msr_pr != 0) {
         if (tlb->mas7_3 & MAS3_UR) {
-            _prot |= PAGE_READ;
+            prot2 |= PAGE_READ;
         }
         if (tlb->mas7_3 & MAS3_UW) {
-            _prot |= PAGE_WRITE;
+            prot2 |= PAGE_WRITE;
         }
         if (tlb->mas7_3 & MAS3_UX) {
-            _prot |= PAGE_EXEC;
+            prot2 |= PAGE_EXEC;
         }
     } else {
         if (tlb->mas7_3 & MAS3_SR) {
-            _prot |= PAGE_READ;
+            prot2 |= PAGE_READ;
         }
         if (tlb->mas7_3 & MAS3_SW) {
-            _prot |= PAGE_WRITE;
+            prot2 |= PAGE_WRITE;
         }
         if (tlb->mas7_3 & MAS3_SX) {
-            _prot |= PAGE_EXEC;
+            prot2 |= PAGE_EXEC;
         }
     }
 
@@ -1390,13 +1414,13 @@ found_tlb:
             return -1;
         }
 
-        *prot = _prot;
-        if (_prot & PAGE_EXEC) {
+        *prot = prot2;
+        if (prot2 & PAGE_EXEC) {
             LOG_SWTLB("%s: good TLB!\n", __func__);
             return 0;
         }
 
-        LOG_SWTLB("%s: no PAGE_EXEC: %x\n", __func__, _prot);
+        LOG_SWTLB("%s: no PAGE_EXEC: %x\n", __func__, prot2);
         ret = -3;
     } else {
         if (msr_dr != ((tlb->mas1 & MAS1_TS) >> MAS1_TS_SHIFT)) {
@@ -1404,13 +1428,13 @@ found_tlb:
             return -1;
         }
 
-        *prot = _prot;
-        if ((!rw && _prot & PAGE_READ) || (rw && (_prot & PAGE_WRITE))) {
+        *prot = prot2;
+        if ((!rw && prot2 & PAGE_READ) || (rw && (prot2 & PAGE_WRITE))) {
             LOG_SWTLB("%s: found TLB!\n", __func__);
             return 0;
         }
 
-        LOG_SWTLB("%s: PAGE_READ/WRITE doesn't match: %x\n", __func__, _prot);
+        LOG_SWTLB("%s: PAGE_READ/WRITE doesn't match: %x\n", __func__, prot2);
         ret = -2;
     }
 
@@ -1521,7 +1545,8 @@ static void mmubooke206_dump_one_tlb(FILE *f, fprintf_function cpu_fprintf,
     int i;
 
     cpu_fprintf(f, "\nTLB%d:\n", tlbn);
-    cpu_fprintf(f, "Effective          Physical           Size TID   TS SRWX URWX WIMGE U0123\n");
+    cpu_fprintf(f, "Effective          Physical           Size TID   TS SRWX"
+                " URWX WIMGE U0123\n");
 
     entry = &env->tlb.tlbm[offset];
     for (i = 0; i < tlbsize; i++, entry++) {
@@ -1537,7 +1562,8 @@ static void mmubooke206_dump_one_tlb(FILE *f, fprintf_function cpu_fprintf,
         ea = entry->mas2 & ~(size - 1);
         pa = entry->mas7_3 & ~(size - 1);
 
-        cpu_fprintf(f, "0x%016" PRIx64 " 0x%016" PRIx64 " %4s %-5u %1u  S%c%c%c U%c%c%c %c%c%c%c%c U%c%c%c%c\n",
+        cpu_fprintf(f, "0x%016" PRIx64 " 0x%016" PRIx64 " %4s %-5u %1u  S%c%c%c"
+                    "U%c%c%c %c%c%c%c%c U%c%c%c%c\n",
                     (uint64_t)ea, (uint64_t)pa,
                     book3e_tsize_to_str[tsize],
                     (entry->mas1 & MAS1_TID_MASK) >> MAS1_TID_SHIFT,
@@ -1691,8 +1717,8 @@ static inline int check_physical(CPUPPCState *env, mmu_ctx_t *ctx,
     return ret;
 }
 
-int get_physical_address (CPUPPCState *env, mmu_ctx_t *ctx, target_ulong eaddr,
-                          int rw, int access_type)
+int get_physical_address(CPUPPCState *env, mmu_ctx_t *ctx, target_ulong eaddr,
+                         int rw, int access_type)
 {
     int ret;
 
@@ -1721,8 +1747,9 @@ int get_physical_address (CPUPPCState *env, mmu_ctx_t *ctx, target_ulong eaddr,
         case POWERPC_MMU_SOFT_6xx:
         case POWERPC_MMU_SOFT_74xx:
             /* Try to find a BAT */
-            if (env->nb_BATs != 0)
+            if (env->nb_BATs != 0) {
                 ret = get_bat(env, ctx, eaddr, rw, access_type);
+            }
 #if defined(TARGET_PPC64)
         case POWERPC_MMU_620:
         case POWERPC_MMU_64B:
@@ -1766,12 +1793,13 @@ int get_physical_address (CPUPPCState *env, mmu_ctx_t *ctx, target_ulong eaddr,
     return ret;
 }
 
-target_phys_addr_t cpu_get_phys_page_debug (CPUPPCState *env, target_ulong addr)
+target_phys_addr_t cpu_get_phys_page_debug(CPUPPCState *env, target_ulong addr)
 {
     mmu_ctx_t ctx;
 
-    if (unlikely(get_physical_address(env, &ctx, addr, 0, ACCESS_INT) != 0))
+    if (unlikely(get_physical_address(env, &ctx, addr, 0, ACCESS_INT) != 0)) {
         return -1;
+    }
 
     return ctx.raddr & TARGET_PAGE_MASK;
 }
@@ -1817,8 +1845,8 @@ static void booke206_update_mas_tlb_miss(CPUPPCState *env, target_ulong address,
 }
 
 /* Perform address translation */
-int cpu_ppc_handle_mmu_fault (CPUPPCState *env, target_ulong address, int rw,
-                              int mmu_idx)
+int cpu_ppc_handle_mmu_fault(CPUPPCState *env, target_ulong address, int rw,
+                             int mmu_idx)
 {
     mmu_ctx_t ctx;
     int access_type;
@@ -1966,10 +1994,11 @@ int cpu_ppc_handle_mmu_fault (CPUPPCState *env, target_ulong address, int rw,
                     env->exception_index = POWERPC_EXCP_DTLB;
                     env->error_code = 0;
                     env->spr[SPR_40x_DEAR] = address;
-                    if (rw)
+                    if (rw) {
                         env->spr[SPR_40x_ESR] = 0x00800000;
-                    else
+                    } else {
                         env->spr[SPR_40x_ESR] = 0x00000000;
+                    }
                     break;
                 case POWERPC_MMU_32B:
                 case POWERPC_MMU_601:
@@ -1981,10 +2010,11 @@ int cpu_ppc_handle_mmu_fault (CPUPPCState *env, target_ulong address, int rw,
                     env->exception_index = POWERPC_EXCP_DSI;
                     env->error_code = 0;
                     env->spr[SPR_DAR] = address;
-                    if (rw == 1)
+                    if (rw == 1) {
                         env->spr[SPR_DSISR] = 0x42000000;
-                    else
+                    } else {
                         env->spr[SPR_DSISR] = 0x40000000;
+                    }
                     break;
                 case POWERPC_MMU_MPC8xx:
                     /* XXX: TODO */
@@ -2045,20 +2075,22 @@ int cpu_ppc_handle_mmu_fault (CPUPPCState *env, target_ulong address, int rw,
                     env->exception_index = POWERPC_EXCP_DSI;
                     env->error_code = 0;
                     env->spr[SPR_DAR] = address;
-                    if (rw == 1)
+                    if (rw == 1) {
                         env->spr[SPR_DSISR] = 0x06000000;
-                    else
+                    } else {
                         env->spr[SPR_DSISR] = 0x04000000;
+                    }
                     break;
                 case ACCESS_EXT:
                     /* eciwx or ecowx */
                     env->exception_index = POWERPC_EXCP_DSI;
                     env->error_code = 0;
                     env->spr[SPR_DAR] = address;
-                    if (rw == 1)
+                    if (rw == 1) {
                         env->spr[SPR_DSISR] = 0x06100000;
-                    else
+                    } else {
                         env->spr[SPR_DSISR] = 0x04100000;
+                    }
                     break;
                 default:
                     printf("DSI: invalid exception (%d)\n", ret);
@@ -2077,10 +2109,11 @@ int cpu_ppc_handle_mmu_fault (CPUPPCState *env, target_ulong address, int rw,
                     env->error_code = 0;
                     env->spr[SPR_DAR] = address;
                     /* XXX: this might be incorrect */
-                    if (rw == 1)
+                    if (rw == 1) {
                         env->spr[SPR_DSISR] = 0x42000000;
-                    else
+                    } else {
                         env->spr[SPR_DSISR] = 0x40000000;
+                    }
                 } else {
                     env->exception_index = POWERPC_EXCP_DSEG;
                     env->error_code = 0;
@@ -2112,8 +2145,9 @@ static inline void do_invalidate_BAT(CPUPPCState *env, target_ulong BATu,
     end = base + mask + 0x00020000;
     LOG_BATS("Flush BAT from " TARGET_FMT_lx " to " TARGET_FMT_lx " ("
              TARGET_FMT_lx ")\n", base, end, mask);
-    for (page = base; page != end; page += TARGET_PAGE_SIZE)
+    for (page = base; page != end; page += TARGET_PAGE_SIZE) {
         tlb_flush_page(env, page);
+    }
     LOG_BATS("Flush done\n");
 }
 #endif
@@ -2125,7 +2159,7 @@ static inline void dump_store_bat(CPUPPCState *env, char ID, int ul, int nr,
              nr, ul == 0 ? 'u' : 'l', value, env->nip);
 }
 
-void ppc_store_ibatu (CPUPPCState *env, int nr, target_ulong value)
+void ppc_store_ibatu(CPUPPCState *env, int nr, target_ulong value)
 {
     target_ulong mask;
 
@@ -2151,13 +2185,13 @@ void ppc_store_ibatu (CPUPPCState *env, int nr, target_ulong value)
     }
 }
 
-void ppc_store_ibatl (CPUPPCState *env, int nr, target_ulong value)
+void ppc_store_ibatl(CPUPPCState *env, int nr, target_ulong value)
 {
     dump_store_bat(env, 'I', 1, nr, value);
     env->IBAT[1][nr] = value;
 }
 
-void ppc_store_dbatu (CPUPPCState *env, int nr, target_ulong value)
+void ppc_store_dbatu(CPUPPCState *env, int nr, target_ulong value)
 {
     target_ulong mask;
 
@@ -2183,13 +2217,13 @@ void ppc_store_dbatu (CPUPPCState *env, int nr, target_ulong value)
     }
 }
 
-void ppc_store_dbatl (CPUPPCState *env, int nr, target_ulong value)
+void ppc_store_dbatl(CPUPPCState *env, int nr, target_ulong value)
 {
     dump_store_bat(env, 'D', 1, nr, value);
     env->DBAT[1][nr] = value;
 }
 
-void ppc_store_ibatu_601 (CPUPPCState *env, int nr, target_ulong value)
+void ppc_store_ibatu_601(CPUPPCState *env, int nr, target_ulong value)
 {
     target_ulong mask;
 #if defined(FLUSH_ALL_TLBS)
@@ -2224,13 +2258,14 @@ void ppc_store_ibatu_601 (CPUPPCState *env, int nr, target_ulong value)
 #endif
         }
 #if defined(FLUSH_ALL_TLBS)
-        if (do_inval)
+        if (do_inval) {
             tlb_flush(env, 1);
+        }
 #endif
     }
 }
 
-void ppc_store_ibatl_601 (CPUPPCState *env, int nr, target_ulong value)
+void ppc_store_ibatl_601(CPUPPCState *env, int nr, target_ulong value)
 {
     target_ulong mask;
 #if defined(FLUSH_ALL_TLBS)
@@ -2261,15 +2296,16 @@ void ppc_store_ibatl_601 (CPUPPCState *env, int nr, target_ulong value)
         env->IBAT[1][nr] = value;
         env->DBAT[1][nr] = value;
 #if defined(FLUSH_ALL_TLBS)
-        if (do_inval)
+        if (do_inval) {
             tlb_flush(env, 1);
+        }
 #endif
     }
 }
 
 /*****************************************************************************/
 /* TLB management */
-void ppc_tlb_invalidate_all (CPUPPCState *env)
+void ppc_tlb_invalidate_all(CPUPPCState *env)
 {
     switch (env->mmu_model) {
     case POWERPC_MMU_SOFT_6xx:
@@ -2309,7 +2345,7 @@ void ppc_tlb_invalidate_all (CPUPPCState *env)
     }
 }
 
-void ppc_tlb_invalidate_one (CPUPPCState *env, target_ulong addr)
+void ppc_tlb_invalidate_one(CPUPPCState *env, target_ulong addr)
 {
 #if !defined(FLUSH_ALL_TLBS)
     addr &= TARGET_PAGE_MASK;
@@ -2317,8 +2353,9 @@ void ppc_tlb_invalidate_one (CPUPPCState *env, target_ulong addr)
     case POWERPC_MMU_SOFT_6xx:
     case POWERPC_MMU_SOFT_74xx:
         ppc6xx_tlb_invalidate_virt(env, addr, 0);
-        if (env->id_tlbs == 1)
+        if (env->id_tlbs == 1) {
             ppc6xx_tlb_invalidate_virt(env, addr, 1);
+        }
         break;
     case POWERPC_MMU_SOFT_4xx:
     case POWERPC_MMU_SOFT_4xx_Z:
@@ -2388,7 +2425,7 @@ void ppc_tlb_invalidate_one (CPUPPCState *env, target_ulong addr)
 /*****************************************************************************/
 /* Special registers manipulation */
 #if defined(TARGET_PPC64)
-void ppc_store_asr (CPUPPCState *env, target_ulong value)
+void ppc_store_asr(CPUPPCState *env, target_ulong value)
 {
     if (env->asr != value) {
         env->asr = value;
@@ -2397,7 +2434,7 @@ void ppc_store_asr (CPUPPCState *env, target_ulong value)
 }
 #endif
 
-void ppc_store_sdr1 (CPUPPCState *env, target_ulong value)
+void ppc_store_sdr1(CPUPPCState *env, target_ulong value)
 {
     LOG_MMU("%s: " TARGET_FMT_lx "\n", __func__, value);
     if (env->spr[SPR_SDR1] != value) {
@@ -2425,14 +2462,14 @@ void ppc_store_sdr1 (CPUPPCState *env, target_ulong value)
 }
 
 #if defined(TARGET_PPC64)
-target_ulong ppc_load_sr (CPUPPCState *env, int slb_nr)
+target_ulong ppc_load_sr(CPUPPCState *env, int slb_nr)
 {
-    // XXX
+    /* XXX */
     return 0;
 }
 #endif
 
-void ppc_store_sr (CPUPPCState *env, int srnum, target_ulong value)
+void ppc_store_sr(CPUPPCState *env, int srnum, target_ulong value)
 {
     LOG_MMU("%s: reg=%d " TARGET_FMT_lx " " TARGET_FMT_lx "\n", __func__,
             srnum, value, env->sr[srnum]);
@@ -2465,37 +2502,38 @@ void ppc_store_sr (CPUPPCState *env, int srnum, target_ulong value)
             /* Invalidate 256 MB of virtual memory */
             page = (16 << 20) * srnum;
             end = page + (16 << 20);
-            for (; page != end; page += TARGET_PAGE_SIZE)
+            for (; page != end; page += TARGET_PAGE_SIZE) {
                 tlb_flush_page(env, page);
+            }
         }
 #else
         tlb_flush(env, 1);
 #endif
     }
 }
-#endif /* !defined (CONFIG_USER_ONLY) */
+#endif /* !defined(CONFIG_USER_ONLY) */
 
 /* GDBstub can read and write MSR... */
-void ppc_store_msr (CPUPPCState *env, target_ulong value)
+void ppc_store_msr(CPUPPCState *env, target_ulong value)
 {
     hreg_store_msr(env, value, 0);
 }
 
 /*****************************************************************************/
 /* Exception processing */
-#if defined (CONFIG_USER_ONLY)
-void do_interrupt (CPUPPCState *env)
+#if defined(CONFIG_USER_ONLY)
+void do_interrupt(CPUPPCState *env)
 {
     env->exception_index = POWERPC_EXCP_NONE;
     env->error_code = 0;
 }
 
-void ppc_hw_interrupt (CPUPPCState *env)
+void ppc_hw_interrupt(CPUPPCState *env)
 {
     env->exception_index = POWERPC_EXCP_NONE;
     env->error_code = 0;
 }
-#else /* defined (CONFIG_USER_ONLY) */
+#else /* defined(CONFIG_USER_ONLY) */
 static inline void dump_syscall(CPUPPCState *env)
 {
     qemu_log_mask(CPU_LOG_INT, "syscall r0=%016" PRIx64 " r3=%016" PRIx64
@@ -2602,23 +2640,27 @@ static inline void powerpc_excp(CPUPPCState *env, int excp_model, int excp)
     case POWERPC_EXCP_DSI:       /* Data storage exception                   */
         LOG_EXCP("DSI exception: DSISR=" TARGET_FMT_lx" DAR=" TARGET_FMT_lx
                  "\n", env->spr[SPR_DSISR], env->spr[SPR_DAR]);
-        if (lpes1 == 0)
+        if (lpes1 == 0) {
             new_msr |= (target_ulong)MSR_HVB;
+        }
         goto store_next;
     case POWERPC_EXCP_ISI:       /* Instruction storage exception            */
         LOG_EXCP("ISI exception: msr=" TARGET_FMT_lx ", nip=" TARGET_FMT_lx
                  "\n", msr, env->nip);
-        if (lpes1 == 0)
+        if (lpes1 == 0) {
             new_msr |= (target_ulong)MSR_HVB;
+        }
         msr |= env->error_code;
         goto store_next;
     case POWERPC_EXCP_EXTERNAL:  /* External input                           */
-        if (lpes0 == 1)
+        if (lpes0 == 1) {
             new_msr |= (target_ulong)MSR_HVB;
+        }
         goto store_next;
     case POWERPC_EXCP_ALIGN:     /* Alignment exception                      */
-        if (lpes1 == 0)
+        if (lpes1 == 0) {
             new_msr |= (target_ulong)MSR_HVB;
+        }
         /* XXX: this is false */
         /* Get rS/rD and rA from faulting opcode */
         env->spr[SPR_DSISR] |= (ldl_code((env->nip - 4)) & 0x03FF0000) >> 16;
@@ -2632,29 +2674,34 @@ static inline void powerpc_excp(CPUPPCState *env, int excp_model, int excp)
                 env->error_code = 0;
                 return;
             }
-            if (lpes1 == 0)
+            if (lpes1 == 0) {
                 new_msr |= (target_ulong)MSR_HVB;
+            }
             msr |= 0x00100000;
-            if (msr_fe0 == msr_fe1)
+            if (msr_fe0 == msr_fe1) {
                 goto store_next;
+            }
             msr |= 0x00010000;
             break;
         case POWERPC_EXCP_INVAL:
             LOG_EXCP("Invalid instruction at " TARGET_FMT_lx "\n", env->nip);
-            if (lpes1 == 0)
+            if (lpes1 == 0) {
                 new_msr |= (target_ulong)MSR_HVB;
+            }
             msr |= 0x00080000;
             env->spr[SPR_BOOKE_ESR] = ESR_PIL;
             break;
         case POWERPC_EXCP_PRIV:
-            if (lpes1 == 0)
+            if (lpes1 == 0) {
                 new_msr |= (target_ulong)MSR_HVB;
+            }
             msr |= 0x00040000;
             env->spr[SPR_BOOKE_ESR] = ESR_PPR;
             break;
         case POWERPC_EXCP_TRAP:
-            if (lpes1 == 0)
+            if (lpes1 == 0) {
                 new_msr |= (target_ulong)MSR_HVB;
+            }
             msr |= 0x00020000;
             env->spr[SPR_BOOKE_ESR] = ESR_PTR;
             break;
@@ -2666,8 +2713,9 @@ static inline void powerpc_excp(CPUPPCState *env, int excp_model, int excp)
         }
         goto store_current;
     case POWERPC_EXCP_FPU:       /* Floating-point unavailable exception     */
-        if (lpes1 == 0)
+        if (lpes1 == 0) {
             new_msr |= (target_ulong)MSR_HVB;
+        }
         goto store_current;
     case POWERPC_EXCP_SYSCALL:   /* System call exception                    */
         dump_syscall(env);
@@ -2676,14 +2724,16 @@ static inline void powerpc_excp(CPUPPCState *env, int excp_model, int excp)
             cpu_ppc_hypercall(env);
             return;
         }
-        if (lev == 1 || (lpes0 == 0 && lpes1 == 0))
+        if (lev == 1 || (lpes0 == 0 && lpes1 == 0)) {
             new_msr |= (target_ulong)MSR_HVB;
+        }
         goto store_next;
     case POWERPC_EXCP_APU:       /* Auxiliary processor unavailable          */
         goto store_current;
     case POWERPC_EXCP_DECR:      /* Decrementer exception                    */
-        if (lpes1 == 0)
+        if (lpes1 == 0) {
             new_msr |= (target_ulong)MSR_HVB;
+        }
         goto store_next;
     case POWERPC_EXCP_FIT:       /* Fixed-interval timer interrupt           */
         /* FIT on 4xx */
@@ -2758,12 +2808,14 @@ static inline void powerpc_excp(CPUPPCState *env, int excp_model, int excp)
         }
         goto store_next;
     case POWERPC_EXCP_DSEG:      /* Data segment exception                   */
-        if (lpes1 == 0)
+        if (lpes1 == 0) {
             new_msr |= (target_ulong)MSR_HVB;
+        }
         goto store_next;
     case POWERPC_EXCP_ISEG:      /* Instruction segment exception            */
-        if (lpes1 == 0)
+        if (lpes1 == 0) {
             new_msr |= (target_ulong)MSR_HVB;
+        }
         goto store_next;
     case POWERPC_EXCP_HDECR:     /* Hypervisor decrementer exception         */
         srr0 = SPR_HSRR0;
@@ -2772,8 +2824,9 @@ static inline void powerpc_excp(CPUPPCState *env, int excp_model, int excp)
         new_msr |= env->msr & ((target_ulong)1 << MSR_RI);
         goto store_next;
     case POWERPC_EXCP_TRACE:     /* Trace exception                          */
-        if (lpes1 == 0)
+        if (lpes1 == 0) {
             new_msr |= (target_ulong)MSR_HVB;
+        }
         goto store_next;
     case POWERPC_EXCP_HDSI:      /* Hypervisor data storage exception        */
         srr0 = SPR_HSRR0;
@@ -2800,8 +2853,9 @@ static inline void powerpc_excp(CPUPPCState *env, int excp_model, int excp)
         new_msr |= env->msr & ((target_ulong)1 << MSR_RI);
         goto store_next;
     case POWERPC_EXCP_VPU:       /* Vector unavailable exception             */
-        if (lpes1 == 0)
+        if (lpes1 == 0) {
             new_msr |= (target_ulong)MSR_HVB;
+        }
         goto store_current;
     case POWERPC_EXCP_PIT:       /* Programmable interval timer interrupt    */
         LOG_EXCP("PIT exception\n");
@@ -2820,8 +2874,9 @@ static inline void powerpc_excp(CPUPPCState *env, int excp_model, int excp)
                   "is not implemented yet !\n");
         goto store_next;
     case POWERPC_EXCP_IFTLB:     /* Instruction fetch TLB error              */
-        if (lpes1 == 0) /* XXX: check this */
+        if (lpes1 == 0) { /* XXX: check this */
             new_msr |= (target_ulong)MSR_HVB;
+        }
         switch (excp_model) {
         case POWERPC_EXCP_602:
         case POWERPC_EXCP_603:
@@ -2838,8 +2893,9 @@ static inline void powerpc_excp(CPUPPCState *env, int excp_model, int excp)
         }
         break;
     case POWERPC_EXCP_DLTLB:     /* Data load TLB miss                       */
-        if (lpes1 == 0) /* XXX: check this */
+        if (lpes1 == 0) { /* XXX: check this */
             new_msr |= (target_ulong)MSR_HVB;
+        }
         switch (excp_model) {
         case POWERPC_EXCP_602:
         case POWERPC_EXCP_603:
@@ -2856,8 +2912,9 @@ static inline void powerpc_excp(CPUPPCState *env, int excp_model, int excp)
         }
         break;
     case POWERPC_EXCP_DSTLB:     /* Data store TLB miss                      */
-        if (lpes1 == 0) /* XXX: check this */
+        if (lpes1 == 0) { /* XXX: check this */
             new_msr |= (target_ulong)MSR_HVB;
+        }
         switch (excp_model) {
         case POWERPC_EXCP_602:
         case POWERPC_EXCP_603:
@@ -2872,21 +2929,23 @@ static inline void powerpc_excp(CPUPPCState *env, int excp_model, int excp)
             goto tlb_miss;
         case POWERPC_EXCP_7x5:
         tlb_miss:
-#if defined (DEBUG_SOFTWARE_TLB)
+#if defined(DEBUG_SOFTWARE_TLB)
             if (qemu_log_enabled()) {
                 const char *es;
                 target_ulong *miss, *cmp;
                 int en;
+
                 if (excp == POWERPC_EXCP_IFTLB) {
                     es = "I";
                     en = 'I';
                     miss = &env->spr[SPR_IMISS];
                     cmp = &env->spr[SPR_ICMP];
                 } else {
-                    if (excp == POWERPC_EXCP_DLTLB)
+                    if (excp == POWERPC_EXCP_DLTLB) {
                         es = "DL";
-                    else
+                    } else {
                         es = "DS";
+                    }
                     en = 'D';
                     miss = &env->spr[SPR_DMISS];
                     cmp = &env->spr[SPR_DCMP];
@@ -2905,21 +2964,23 @@ static inline void powerpc_excp(CPUPPCState *env, int excp_model, int excp)
             break;
         case POWERPC_EXCP_74xx:
         tlb_miss_74xx:
-#if defined (DEBUG_SOFTWARE_TLB)
+#if defined(DEBUG_SOFTWARE_TLB)
             if (qemu_log_enabled()) {
                 const char *es;
                 target_ulong *miss, *cmp;
                 int en;
+
                 if (excp == POWERPC_EXCP_IFTLB) {
                     es = "I";
                     en = 'I';
                     miss = &env->spr[SPR_TLBMISS];
                     cmp = &env->spr[SPR_PTEHI];
                 } else {
-                    if (excp == POWERPC_EXCP_DLTLB)
+                    if (excp == POWERPC_EXCP_DLTLB) {
                         es = "DL";
-                    else
+                    } else {
                         es = "DS";
+                    }
                     en = 'D';
                     miss = &env->spr[SPR_TLBMISS];
                     cmp = &env->spr[SPR_PTEHI];
@@ -2959,8 +3020,9 @@ static inline void powerpc_excp(CPUPPCState *env, int excp_model, int excp)
                   "is not implemented yet !\n");
         goto store_next;
     case POWERPC_EXCP_PERFM:     /* Embedded performance monitor interrupt   */
-        if (lpes1 == 0)
+        if (lpes1 == 0) {
             new_msr |= (target_ulong)MSR_HVB;
+        }
         /* XXX: TODO */
         cpu_abort(env,
                   "Performance counter exception is not implemented yet !\n");
@@ -3005,13 +3067,16 @@ static inline void powerpc_excp(CPUPPCState *env, int excp_model, int excp)
     /* Save MSR */
     env->spr[srr1] = msr;
     /* If any alternate SRR register are defined, duplicate saved values */
-    if (asrr0 != -1)
+    if (asrr0 != -1) {
         env->spr[asrr0] = env->spr[srr0];
-    if (asrr1 != -1)
+    }
+    if (asrr1 != -1) {
         env->spr[asrr1] = env->spr[srr1];
+    }
     /* If we disactivated any translation, flush TLBs */
-    if (msr & ((1 << MSR_IR) | (1 << MSR_DR)))
+    if (msr & ((1 << MSR_IR) | (1 << MSR_DR))) {
         tlb_flush(env, 1);
+    }
 
     if (msr_ile) {
         new_msr |= (target_ulong)1 << MSR_LE;
@@ -3058,12 +3123,12 @@ static inline void powerpc_excp(CPUPPCState *env, int excp_model, int excp)
     }
 }
 
-void do_interrupt (CPUPPCState *env)
+void do_interrupt(CPUPPCState *env)
 {
     powerpc_excp(env, env->excp_model, env->exception_index);
 }
 
-void ppc_hw_interrupt (CPUPPCState *env)
+void ppc_hw_interrupt(CPUPPCState *env)
 {
     int hdice;
 
@@ -3180,7 +3245,7 @@ void ppc_hw_interrupt (CPUPPCState *env)
 }
 #endif /* !CONFIG_USER_ONLY */
 
-void cpu_dump_rfi (target_ulong RA, target_ulong msr)
+void cpu_dump_rfi(target_ulong RA, target_ulong msr)
 {
     qemu_log("Return from exception at " TARGET_FMT_lx " with flags "
              TARGET_FMT_lx "\n", RA, msr);
@@ -3193,8 +3258,9 @@ PowerPCCPU *cpu_ppc_init(const char *cpu_model)
     const ppc_def_t *def;
 
     def = cpu_ppc_find_by_name(cpu_model);
-    if (!def)
+    if (!def) {
         return NULL;
+    }
 
     cpu = POWERPC_CPU(object_new(TYPE_POWERPC_CPU));
     env = &cpu->env;
commit e5f17ac633fa7ac7a0936846c505a3c2d2b5687c
Author: Blue Swirl <blauwirbel at gmail.com>
Date:   Wed May 30 04:23:23 2012 +0000

    ppc: Avoid AREG0 for exception helpers
    
    Add an explicit CPUPPCState parameter instead of relying on AREG0.
    
    Signed-off-by: Blue Swirl <blauwirbel at gmail.com>
    Signed-off-by: Alexander Graf <agraf at suse.de>
    Signed-off-by: Andreas Färber <afaerber at suse.de>
    Signed-off-by: Alexander Graf <agraf at suse.de>

diff --git a/target-ppc/Makefile.objs b/target-ppc/Makefile.objs
index c0f7e76..a02b7bc 100644
--- a/target-ppc/Makefile.objs
+++ b/target-ppc/Makefile.objs
@@ -4,5 +4,4 @@ obj-$(CONFIG_KVM) += kvm.o kvm_ppc.o
 obj-y += op_helper.o helper.o
 obj-y += excp_helper.o
 
-$(obj)/excp_helper.o: QEMU_CFLAGS += $(HELPER_CFLAGS)
 $(obj)/op_helper.o: QEMU_CFLAGS += $(HELPER_CFLAGS)
diff --git a/target-ppc/excp_helper.c b/target-ppc/excp_helper.c
index f03f738..c153f4a 100644
--- a/target-ppc/excp_helper.c
+++ b/target-ppc/excp_helper.c
@@ -17,7 +17,6 @@
  * License along with this library; if not, see <http://www.gnu.org/licenses/>.
  */
 #include "cpu.h"
-#include "dyngen-exec.h"
 #include "helper.h"
 
 #include "helper_regs.h"
@@ -28,7 +27,8 @@
 /*****************************************************************************/
 /* Exceptions processing helpers */
 
-void helper_raise_exception_err(uint32_t exception, uint32_t error_code)
+void helper_raise_exception_err(CPUPPCState *env, uint32_t exception,
+                                uint32_t error_code)
 {
 #if 0
     printf("Raise exception %3x code : %d\n", exception, error_code);
@@ -38,22 +38,22 @@ void helper_raise_exception_err(uint32_t exception, uint32_t error_code)
     cpu_loop_exit(env);
 }
 
-void helper_raise_exception(uint32_t exception)
+void helper_raise_exception(CPUPPCState *env, uint32_t exception)
 {
-    helper_raise_exception_err(exception, 0);
+    helper_raise_exception_err(env, exception, 0);
 }
 
 #if !defined(CONFIG_USER_ONLY)
-void helper_store_msr(target_ulong val)
+void helper_store_msr(CPUPPCState *env, target_ulong val)
 {
     val = hreg_store_msr(env, val, 0);
     if (val != 0) {
         env->interrupt_request |= CPU_INTERRUPT_EXITTB;
-        helper_raise_exception(val);
+        helper_raise_exception(env, val);
     }
 }
 
-static inline void do_rfi(target_ulong nip, target_ulong msr,
+static inline void do_rfi(CPUPPCState *env, target_ulong nip, target_ulong msr,
                           target_ulong msrm, int keep_msrh)
 {
 #if defined(TARGET_PPC64)
@@ -83,73 +83,77 @@ static inline void do_rfi(target_ulong nip, target_ulong msr,
     env->interrupt_request |= CPU_INTERRUPT_EXITTB;
 }
 
-void helper_rfi(void)
+void helper_rfi(CPUPPCState *env)
 {
-    do_rfi(env->spr[SPR_SRR0], env->spr[SPR_SRR1],
+    do_rfi(env, env->spr[SPR_SRR0], env->spr[SPR_SRR1],
            ~((target_ulong)0x783F0000), 1);
 }
 
 #if defined(TARGET_PPC64)
-void helper_rfid(void)
+void helper_rfid(CPUPPCState *env)
 {
-    do_rfi(env->spr[SPR_SRR0], env->spr[SPR_SRR1],
+    do_rfi(env, env->spr[SPR_SRR0], env->spr[SPR_SRR1],
            ~((target_ulong)0x783F0000), 0);
 }
 
-void helper_hrfid(void)
+void helper_hrfid(CPUPPCState *env)
 {
-    do_rfi(env->spr[SPR_HSRR0], env->spr[SPR_HSRR1],
+    do_rfi(env, env->spr[SPR_HSRR0], env->spr[SPR_HSRR1],
            ~((target_ulong)0x783F0000), 0);
 }
 #endif
 
 /*****************************************************************************/
 /* Embedded PowerPC specific helpers */
-void helper_40x_rfci(void)
+void helper_40x_rfci(CPUPPCState *env)
 {
-    do_rfi(env->spr[SPR_40x_SRR2], env->spr[SPR_40x_SRR3],
+    do_rfi(env, env->spr[SPR_40x_SRR2], env->spr[SPR_40x_SRR3],
            ~((target_ulong)0xFFFF0000), 0);
 }
 
-void helper_rfci(void)
+void helper_rfci(CPUPPCState *env)
 {
-    do_rfi(env->spr[SPR_BOOKE_CSRR0], SPR_BOOKE_CSRR1,
+    do_rfi(env, env->spr[SPR_BOOKE_CSRR0], SPR_BOOKE_CSRR1,
            ~((target_ulong)0x3FFF0000), 0);
 }
 
-void helper_rfdi(void)
+void helper_rfdi(CPUPPCState *env)
 {
-    do_rfi(env->spr[SPR_BOOKE_DSRR0], SPR_BOOKE_DSRR1,
+    do_rfi(env, env->spr[SPR_BOOKE_DSRR0], SPR_BOOKE_DSRR1,
            ~((target_ulong)0x3FFF0000), 0);
 }
 
-void helper_rfmci(void)
+void helper_rfmci(CPUPPCState *env)
 {
-    do_rfi(env->spr[SPR_BOOKE_MCSRR0], SPR_BOOKE_MCSRR1,
+    do_rfi(env, env->spr[SPR_BOOKE_MCSRR0], SPR_BOOKE_MCSRR1,
            ~((target_ulong)0x3FFF0000), 0);
 }
 #endif
 
-void helper_tw(target_ulong arg1, target_ulong arg2, uint32_t flags)
+void helper_tw(CPUPPCState *env, target_ulong arg1, target_ulong arg2,
+               uint32_t flags)
 {
     if (!likely(!(((int32_t)arg1 < (int32_t)arg2 && (flags & 0x10)) ||
                   ((int32_t)arg1 > (int32_t)arg2 && (flags & 0x08)) ||
                   ((int32_t)arg1 == (int32_t)arg2 && (flags & 0x04)) ||
                   ((uint32_t)arg1 < (uint32_t)arg2 && (flags & 0x02)) ||
                   ((uint32_t)arg1 > (uint32_t)arg2 && (flags & 0x01))))) {
-        helper_raise_exception_err(POWERPC_EXCP_PROGRAM, POWERPC_EXCP_TRAP);
+        helper_raise_exception_err(env, POWERPC_EXCP_PROGRAM,
+                                   POWERPC_EXCP_TRAP);
     }
 }
 
 #if defined(TARGET_PPC64)
-void helper_td(target_ulong arg1, target_ulong arg2, uint32_t flags)
+void helper_td(CPUPPCState *env, target_ulong arg1, target_ulong arg2,
+               uint32_t flags)
 {
     if (!likely(!(((int64_t)arg1 < (int64_t)arg2 && (flags & 0x10)) ||
                   ((int64_t)arg1 > (int64_t)arg2 && (flags & 0x08)) ||
                   ((int64_t)arg1 == (int64_t)arg2 && (flags & 0x04)) ||
                   ((uint64_t)arg1 < (uint64_t)arg2 && (flags & 0x02)) ||
                   ((uint64_t)arg1 > (uint64_t)arg2 && (flags & 0x01))))) {
-        helper_raise_exception_err(POWERPC_EXCP_PROGRAM, POWERPC_EXCP_TRAP);
+        helper_raise_exception_err(env, POWERPC_EXCP_PROGRAM,
+                                   POWERPC_EXCP_TRAP);
     }
 }
 #endif
@@ -158,9 +162,9 @@ void helper_td(target_ulong arg1, target_ulong arg2, uint32_t flags)
 /*****************************************************************************/
 /* PowerPC 601 specific instructions (POWER bridge) */
 
-void helper_rfsvc(void)
+void helper_rfsvc(CPUPPCState *env)
 {
-    do_rfi(env->lr, env->ctr, 0x0000FFFF, 0);
+    do_rfi(env, env->lr, env->ctr, 0x0000FFFF, 0);
 }
 
 /* Embedded.Processor Control */
@@ -187,7 +191,7 @@ static int dbell2irq(target_ulong rb)
     return irq;
 }
 
-void helper_msgclr(target_ulong rb)
+void helper_msgclr(CPUPPCState *env, target_ulong rb)
 {
     int irq = dbell2irq(rb);
 
diff --git a/target-ppc/helper.h b/target-ppc/helper.h
index 148543a..a4562ae 100644
--- a/target-ppc/helper.h
+++ b/target-ppc/helper.h
@@ -1,22 +1,22 @@
 #include "def-helper.h"
 
-DEF_HELPER_2(raise_exception_err, void, i32, i32)
-DEF_HELPER_1(raise_exception, void, i32)
-DEF_HELPER_3(tw, void, tl, tl, i32)
+DEF_HELPER_3(raise_exception_err, void, env, i32, i32)
+DEF_HELPER_2(raise_exception, void, env, i32)
+DEF_HELPER_4(tw, void, env, tl, tl, i32)
 #if defined(TARGET_PPC64)
-DEF_HELPER_3(td, void, tl, tl, i32)
+DEF_HELPER_4(td, void, env, tl, tl, i32)
 #endif
 #if !defined(CONFIG_USER_ONLY)
-DEF_HELPER_1(store_msr, void, tl)
-DEF_HELPER_0(rfi, void)
-DEF_HELPER_0(rfsvc, void)
-DEF_HELPER_0(40x_rfci, void)
-DEF_HELPER_0(rfci, void)
-DEF_HELPER_0(rfdi, void)
-DEF_HELPER_0(rfmci, void)
+DEF_HELPER_2(store_msr, void, env, tl)
+DEF_HELPER_1(rfi, void, env)
+DEF_HELPER_1(rfsvc, void, env)
+DEF_HELPER_1(40x_rfci, void, env)
+DEF_HELPER_1(rfci, void, env)
+DEF_HELPER_1(rfdi, void, env)
+DEF_HELPER_1(rfmci, void, env)
 #if defined(TARGET_PPC64)
-DEF_HELPER_0(rfid, void)
-DEF_HELPER_0(hrfid, void)
+DEF_HELPER_1(rfid, void, env)
+DEF_HELPER_1(hrfid, void, env)
 #endif
 #endif
 
@@ -359,7 +359,7 @@ DEF_HELPER_FLAGS_2(store_sr, TCG_CALL_CONST, void, tl, tl)
 
 DEF_HELPER_FLAGS_1(602_mfrom, TCG_CALL_CONST | TCG_CALL_PURE, tl, tl)
 DEF_HELPER_1(msgsnd, void, tl)
-DEF_HELPER_1(msgclr, void, tl)
+DEF_HELPER_2(msgclr, void, env, tl)
 #endif
 
 DEF_HELPER_3(dlmzb, tl, tl, tl, i32)
diff --git a/target-ppc/op_helper.c b/target-ppc/op_helper.c
index 2e87860..eedbb42 100644
--- a/target-ppc/op_helper.c
+++ b/target-ppc/op_helper.c
@@ -294,7 +294,7 @@ void helper_lswx(target_ulong addr, uint32_t reg, uint32_t ra, uint32_t rb)
     if (likely(xer_bc != 0)) {
         if (unlikely((ra != 0 && reg < ra && (reg + xer_bc) > ra) ||
                      (reg < rb && (reg + xer_bc) > rb))) {
-            helper_raise_exception_err(POWERPC_EXCP_PROGRAM,
+            helper_raise_exception_err(env, POWERPC_EXCP_PROGRAM,
                                        POWERPC_EXCP_INVAL |
                                        POWERPC_EXCP_INVAL_LSWX);
         } else {
@@ -709,7 +709,7 @@ static inline uint64_t fload_invalid_op_excp(int op)
         /* Update the floating-point enabled exception summary */
         env->fpscr |= 1 << FPSCR_FEX;
         if (msr_fe0 != 0 || msr_fe1 != 0) {
-            helper_raise_exception_err(POWERPC_EXCP_PROGRAM,
+            helper_raise_exception_err(env, POWERPC_EXCP_PROGRAM,
                                        POWERPC_EXCP_FP | op);
         }
     }
@@ -726,7 +726,7 @@ static inline void float_zero_divide_excp(void)
         /* Update the floating-point enabled exception summary */
         env->fpscr |= 1 << FPSCR_FEX;
         if (msr_fe0 != 0 || msr_fe1 != 0) {
-            helper_raise_exception_err(POWERPC_EXCP_PROGRAM,
+            helper_raise_exception_err(env, POWERPC_EXCP_PROGRAM,
                                        POWERPC_EXCP_FP | POWERPC_EXCP_FP_ZX);
         }
     }
@@ -995,7 +995,8 @@ void helper_float_check_status(void)
         (env->error_code & POWERPC_EXCP_FP)) {
         /* Differred floating-point exception after target FPR update */
         if (msr_fe0 != 0 || msr_fe1 != 0) {
-            helper_raise_exception_err(env->exception_index, env->error_code);
+            helper_raise_exception_err(env, env->exception_index,
+                                       env->error_code);
         }
     } else {
         int status = get_float_exception_flags(&env->fp_status);
@@ -1781,13 +1782,13 @@ target_ulong helper_load_dcr(target_ulong dcrn)
 
     if (unlikely(env->dcr_env == NULL)) {
         qemu_log("No DCR environment\n");
-        helper_raise_exception_err(POWERPC_EXCP_PROGRAM,
+        helper_raise_exception_err(env, POWERPC_EXCP_PROGRAM,
                                    POWERPC_EXCP_INVAL |
                                    POWERPC_EXCP_INVAL_INVAL);
     } else if (unlikely(ppc_dcr_read(env->dcr_env,
                                      (uint32_t)dcrn, &val) != 0)) {
         qemu_log("DCR read error %d %03x\n", (uint32_t)dcrn, (uint32_t)dcrn);
-        helper_raise_exception_err(POWERPC_EXCP_PROGRAM,
+        helper_raise_exception_err(env, POWERPC_EXCP_PROGRAM,
                                    POWERPC_EXCP_INVAL | POWERPC_EXCP_PRIV_REG);
     }
     return val;
@@ -1797,13 +1798,13 @@ void helper_store_dcr(target_ulong dcrn, target_ulong val)
 {
     if (unlikely(env->dcr_env == NULL)) {
         qemu_log("No DCR environment\n");
-        helper_raise_exception_err(POWERPC_EXCP_PROGRAM,
+        helper_raise_exception_err(env, POWERPC_EXCP_PROGRAM,
                                    POWERPC_EXCP_INVAL |
                                    POWERPC_EXCP_INVAL_INVAL);
     } else if (unlikely(ppc_dcr_write(env->dcr_env, (uint32_t)dcrn,
                                       (uint32_t)val) != 0)) {
         qemu_log("DCR write error %d %03x\n", (uint32_t)dcrn, (uint32_t)dcrn);
-        helper_raise_exception_err(POWERPC_EXCP_PROGRAM,
+        helper_raise_exception_err(env, POWERPC_EXCP_PROGRAM,
                                    POWERPC_EXCP_INVAL | POWERPC_EXCP_PRIV_REG);
     }
 }
@@ -3783,7 +3784,7 @@ void tlb_fill(CPUPPCState *env1, target_ulong addr, int is_write, int mmu_idx,
                 cpu_restore_state(tb, env, retaddr);
             }
         }
-        helper_raise_exception_err(env->exception_index, env->error_code);
+        helper_raise_exception_err(env, env->exception_index, env->error_code);
     }
     env = saved_env;
 }
@@ -3809,7 +3810,8 @@ void helper_store_sr(target_ulong sr_num, target_ulong val)
 void helper_store_slb(target_ulong rb, target_ulong rs)
 {
     if (ppc_store_slb(env, rb, rs) < 0) {
-        helper_raise_exception_err(POWERPC_EXCP_PROGRAM, POWERPC_EXCP_INVAL);
+        helper_raise_exception_err(env, POWERPC_EXCP_PROGRAM,
+                                   POWERPC_EXCP_INVAL);
     }
 }
 
@@ -3818,7 +3820,8 @@ target_ulong helper_load_slb_esid(target_ulong rb)
     target_ulong rt;
 
     if (ppc_load_slb_esid(env, rb, &rt) < 0) {
-        helper_raise_exception_err(POWERPC_EXCP_PROGRAM, POWERPC_EXCP_INVAL);
+        helper_raise_exception_err(env, POWERPC_EXCP_PROGRAM,
+                                   POWERPC_EXCP_INVAL);
     }
     return rt;
 }
@@ -3828,7 +3831,8 @@ target_ulong helper_load_slb_vsid(target_ulong rb)
     target_ulong rt;
 
     if (ppc_load_slb_vsid(env, rb, &rt) < 0) {
-        helper_raise_exception_err(POWERPC_EXCP_PROGRAM, POWERPC_EXCP_INVAL);
+        helper_raise_exception_err(env, POWERPC_EXCP_PROGRAM,
+                                   POWERPC_EXCP_INVAL);
     }
     return rt;
 }
@@ -4328,7 +4332,7 @@ void helper_booke206_tlbwe(void)
     tlb = booke206_cur_tlb(env);
 
     if (!tlb) {
-        helper_raise_exception_err(POWERPC_EXCP_PROGRAM,
+        helper_raise_exception_err(env, POWERPC_EXCP_PROGRAM,
                                    POWERPC_EXCP_INVAL |
                                    POWERPC_EXCP_INVAL_INVAL);
     }
@@ -4338,7 +4342,7 @@ void helper_booke206_tlbwe(void)
     size_ps = booke206_tlbnps(env, tlbn);
     if ((env->spr[SPR_BOOKE_MAS1] & MAS1_VALID) && (tlbncfg & TLBnCFG_AVAIL) &&
         !(size_ps & (1 << size_tlb))) {
-        helper_raise_exception_err(POWERPC_EXCP_PROGRAM,
+        helper_raise_exception_err(env, POWERPC_EXCP_PROGRAM,
                                    POWERPC_EXCP_INVAL |
                                    POWERPC_EXCP_INVAL_INVAL);
     }
diff --git a/target-ppc/translate.c b/target-ppc/translate.c
index cf59765..02626ae 100644
--- a/target-ppc/translate.c
+++ b/target-ppc/translate.c
@@ -270,7 +270,7 @@ static inline void gen_exception_err(DisasContext *ctx, uint32_t excp, uint32_t
     }
     t0 = tcg_const_i32(excp);
     t1 = tcg_const_i32(error);
-    gen_helper_raise_exception_err(t0, t1);
+    gen_helper_raise_exception_err(cpu_env, t0, t1);
     tcg_temp_free_i32(t0);
     tcg_temp_free_i32(t1);
     ctx->exception = (excp);
@@ -283,7 +283,7 @@ static inline void gen_exception(DisasContext *ctx, uint32_t excp)
         gen_update_nip(ctx, ctx->nip);
     }
     t0 = tcg_const_i32(excp);
-    gen_helper_raise_exception(t0);
+    gen_helper_raise_exception(cpu_env, t0);
     tcg_temp_free_i32(t0);
     ctx->exception = (excp);
 }
@@ -297,7 +297,7 @@ static inline void gen_debug_exception(DisasContext *ctx)
         gen_update_nip(ctx, ctx->nip);
     }
     t0 = tcg_const_i32(EXCP_DEBUG);
-    gen_helper_raise_exception(t0);
+    gen_helper_raise_exception(cpu_env, t0);
     tcg_temp_free_i32(t0);
 }
 
@@ -2495,7 +2495,7 @@ static inline void gen_check_align(DisasContext *ctx, TCGv EA, int mask)
     tcg_gen_brcondi_tl(TCG_COND_EQ, t0, 0, l1);
     t1 = tcg_const_i32(POWERPC_EXCP_ALIGN);
     t2 = tcg_const_i32(0);
-    gen_helper_raise_exception_err(t1, t2);
+    gen_helper_raise_exception_err(cpu_env, t1, t2);
     tcg_temp_free_i32(t1);
     tcg_temp_free_i32(t2);
     gen_set_label(l1);
@@ -3662,7 +3662,7 @@ static void gen_rfi(DisasContext *ctx)
         return;
     }
     gen_update_cfar(ctx, ctx->nip);
-    gen_helper_rfi();
+    gen_helper_rfi(cpu_env);
     gen_sync_exception(ctx);
 #endif
 }
@@ -3679,7 +3679,7 @@ static void gen_rfid(DisasContext *ctx)
         return;
     }
     gen_update_cfar(ctx, ctx->nip);
-    gen_helper_rfid();
+    gen_helper_rfid(cpu_env);
     gen_sync_exception(ctx);
 #endif
 }
@@ -3694,7 +3694,7 @@ static void gen_hrfid(DisasContext *ctx)
         gen_inval_exception(ctx, POWERPC_EXCP_PRIV_OPC);
         return;
     }
-    gen_helper_hrfid();
+    gen_helper_hrfid(cpu_env);
     gen_sync_exception(ctx);
 #endif
 }
@@ -3722,7 +3722,8 @@ static void gen_tw(DisasContext *ctx)
     TCGv_i32 t0 = tcg_const_i32(TO(ctx->opcode));
     /* Update the nip since this might generate a trap exception */
     gen_update_nip(ctx, ctx->nip);
-    gen_helper_tw(cpu_gpr[rA(ctx->opcode)], cpu_gpr[rB(ctx->opcode)], t0);
+    gen_helper_tw(cpu_env, cpu_gpr[rA(ctx->opcode)], cpu_gpr[rB(ctx->opcode)],
+                  t0);
     tcg_temp_free_i32(t0);
 }
 
@@ -3733,7 +3734,7 @@ static void gen_twi(DisasContext *ctx)
     TCGv_i32 t1 = tcg_const_i32(TO(ctx->opcode));
     /* Update the nip since this might generate a trap exception */
     gen_update_nip(ctx, ctx->nip);
-    gen_helper_tw(cpu_gpr[rA(ctx->opcode)], t0, t1);
+    gen_helper_tw(cpu_env, cpu_gpr[rA(ctx->opcode)], t0, t1);
     tcg_temp_free(t0);
     tcg_temp_free_i32(t1);
 }
@@ -3745,7 +3746,8 @@ static void gen_td(DisasContext *ctx)
     TCGv_i32 t0 = tcg_const_i32(TO(ctx->opcode));
     /* Update the nip since this might generate a trap exception */
     gen_update_nip(ctx, ctx->nip);
-    gen_helper_td(cpu_gpr[rA(ctx->opcode)], cpu_gpr[rB(ctx->opcode)], t0);
+    gen_helper_td(cpu_env, cpu_gpr[rA(ctx->opcode)], cpu_gpr[rB(ctx->opcode)],
+                  t0);
     tcg_temp_free_i32(t0);
 }
 
@@ -3756,7 +3758,7 @@ static void gen_tdi(DisasContext *ctx)
     TCGv_i32 t1 = tcg_const_i32(TO(ctx->opcode));
     /* Update the nip since this might generate a trap exception */
     gen_update_nip(ctx, ctx->nip);
-    gen_helper_td(cpu_gpr[rA(ctx->opcode)], t0, t1);
+    gen_helper_td(cpu_env, cpu_gpr[rA(ctx->opcode)], t0, t1);
     tcg_temp_free(t0);
     tcg_temp_free_i32(t1);
 }
@@ -3934,7 +3936,7 @@ static void gen_mtmsrd(DisasContext *ctx)
          *      directly from ppc_store_msr
          */
         gen_update_nip(ctx, ctx->nip);
-        gen_helper_store_msr(cpu_gpr[rS(ctx->opcode)]);
+        gen_helper_store_msr(cpu_env, cpu_gpr[rS(ctx->opcode)]);
         /* Must stop the translation as machine state (may have) changed */
         /* Note that mtmsr is not always defined as context-synchronizing */
         gen_stop_exception(ctx);
@@ -3972,7 +3974,7 @@ static void gen_mtmsr(DisasContext *ctx)
 #else
         tcg_gen_mov_tl(msr, cpu_gpr[rS(ctx->opcode)]);
 #endif
-        gen_helper_store_msr(msr);
+        gen_helper_store_msr(cpu_env, msr);
         /* Must stop the translation as machine state (may have) changed */
         /* Note that mtmsr is not always defined as context-synchronizing */
         gen_stop_exception(ctx);
@@ -5290,7 +5292,7 @@ static void gen_rfsvc(DisasContext *ctx)
         gen_inval_exception(ctx, POWERPC_EXCP_PRIV_OPC);
         return;
     }
-    gen_helper_rfsvc();
+    gen_helper_rfsvc(cpu_env);
     gen_sync_exception(ctx);
 #endif
 }
@@ -5849,7 +5851,7 @@ static void gen_rfci_40x(DisasContext *ctx)
         return;
     }
     /* Restore CPU state */
-    gen_helper_40x_rfci();
+    gen_helper_40x_rfci(cpu_env);
     gen_sync_exception(ctx);
 #endif
 }
@@ -5864,7 +5866,7 @@ static void gen_rfci(DisasContext *ctx)
         return;
     }
     /* Restore CPU state */
-    gen_helper_rfci();
+    gen_helper_rfci(cpu_env);
     gen_sync_exception(ctx);
 #endif
 }
@@ -5882,7 +5884,7 @@ static void gen_rfdi(DisasContext *ctx)
         return;
     }
     /* Restore CPU state */
-    gen_helper_rfdi();
+    gen_helper_rfdi(cpu_env);
     gen_sync_exception(ctx);
 #endif
 }
@@ -5898,7 +5900,7 @@ static void gen_rfmci(DisasContext *ctx)
         return;
     }
     /* Restore CPU state */
-    gen_helper_rfmci();
+    gen_helper_rfmci(cpu_env);
     gen_sync_exception(ctx);
 #endif
 }
@@ -6258,7 +6260,7 @@ static void gen_msgclr(DisasContext *ctx)
         return;
     }
 
-    gen_helper_msgclr(cpu_gpr[rB(ctx->opcode)]);
+    gen_helper_msgclr(cpu_env, cpu_gpr[rB(ctx->opcode)]);
 #endif
 }
 
commit ad71ed68117c2a740f82ab297581d7dd8fa21aef
Author: Blue Swirl <blauwirbel at gmail.com>
Date:   Wed May 30 04:23:22 2012 +0000

    ppc: Split exception helpers
    
    Move exception helpers from op_helper.c to excp_helper.c.
    
    Signed-off-by: Blue Swirl <blauwirbel at gmail.com>
    Signed-off-by: Alexander Graf <agraf at suse.de>
    Signed-off-by: Andreas Färber <afaerber at suse.de>
    Signed-off-by: Alexander Graf <agraf at suse.de>

diff --git a/target-ppc/Makefile.objs b/target-ppc/Makefile.objs
index f781610..c0f7e76 100644
--- a/target-ppc/Makefile.objs
+++ b/target-ppc/Makefile.objs
@@ -2,5 +2,7 @@ obj-y += translate.o op_helper.o helper.o
 obj-$(CONFIG_SOFTMMU) += machine.o
 obj-$(CONFIG_KVM) += kvm.o kvm_ppc.o
 obj-y += op_helper.o helper.o
+obj-y += excp_helper.o
 
+$(obj)/excp_helper.o: QEMU_CFLAGS += $(HELPER_CFLAGS)
 $(obj)/op_helper.o: QEMU_CFLAGS += $(HELPER_CFLAGS)
diff --git a/target-ppc/excp_helper.c b/target-ppc/excp_helper.c
new file mode 100644
index 0000000..f03f738
--- /dev/null
+++ b/target-ppc/excp_helper.c
@@ -0,0 +1,218 @@
+/*
+ *  PowerPC exception emulation helpers for QEMU.
+ *
+ *  Copyright (c) 2003-2007 Jocelyn Mayer
+ *
+ * This library is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Lesser General Public
+ * License as published by the Free Software Foundation; either
+ * version 2 of the License, or (at your option) any later version.
+ *
+ * This library is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
+ * Lesser General Public License for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public
+ * License along with this library; if not, see <http://www.gnu.org/licenses/>.
+ */
+#include "cpu.h"
+#include "dyngen-exec.h"
+#include "helper.h"
+
+#include "helper_regs.h"
+
+//#define DEBUG_OP
+//#define DEBUG_EXCEPTIONS
+
+/*****************************************************************************/
+/* Exceptions processing helpers */
+
+void helper_raise_exception_err(uint32_t exception, uint32_t error_code)
+{
+#if 0
+    printf("Raise exception %3x code : %d\n", exception, error_code);
+#endif
+    env->exception_index = exception;
+    env->error_code = error_code;
+    cpu_loop_exit(env);
+}
+
+void helper_raise_exception(uint32_t exception)
+{
+    helper_raise_exception_err(exception, 0);
+}
+
+#if !defined(CONFIG_USER_ONLY)
+void helper_store_msr(target_ulong val)
+{
+    val = hreg_store_msr(env, val, 0);
+    if (val != 0) {
+        env->interrupt_request |= CPU_INTERRUPT_EXITTB;
+        helper_raise_exception(val);
+    }
+}
+
+static inline void do_rfi(target_ulong nip, target_ulong msr,
+                          target_ulong msrm, int keep_msrh)
+{
+#if defined(TARGET_PPC64)
+    if (msr & (1ULL << MSR_SF)) {
+        nip = (uint64_t)nip;
+        msr &= (uint64_t)msrm;
+    } else {
+        nip = (uint32_t)nip;
+        msr = (uint32_t)(msr & msrm);
+        if (keep_msrh) {
+            msr |= env->msr & ~((uint64_t)0xFFFFFFFF);
+        }
+    }
+#else
+    nip = (uint32_t)nip;
+    msr &= (uint32_t)msrm;
+#endif
+    /* XXX: beware: this is false if VLE is supported */
+    env->nip = nip & ~((target_ulong)0x00000003);
+    hreg_store_msr(env, msr, 1);
+#if defined(DEBUG_OP)
+    cpu_dump_rfi(env->nip, env->msr);
+#endif
+    /* No need to raise an exception here,
+     * as rfi is always the last insn of a TB
+     */
+    env->interrupt_request |= CPU_INTERRUPT_EXITTB;
+}
+
+void helper_rfi(void)
+{
+    do_rfi(env->spr[SPR_SRR0], env->spr[SPR_SRR1],
+           ~((target_ulong)0x783F0000), 1);
+}
+
+#if defined(TARGET_PPC64)
+void helper_rfid(void)
+{
+    do_rfi(env->spr[SPR_SRR0], env->spr[SPR_SRR1],
+           ~((target_ulong)0x783F0000), 0);
+}
+
+void helper_hrfid(void)
+{
+    do_rfi(env->spr[SPR_HSRR0], env->spr[SPR_HSRR1],
+           ~((target_ulong)0x783F0000), 0);
+}
+#endif
+
+/*****************************************************************************/
+/* Embedded PowerPC specific helpers */
+void helper_40x_rfci(void)
+{
+    do_rfi(env->spr[SPR_40x_SRR2], env->spr[SPR_40x_SRR3],
+           ~((target_ulong)0xFFFF0000), 0);
+}
+
+void helper_rfci(void)
+{
+    do_rfi(env->spr[SPR_BOOKE_CSRR0], SPR_BOOKE_CSRR1,
+           ~((target_ulong)0x3FFF0000), 0);
+}
+
+void helper_rfdi(void)
+{
+    do_rfi(env->spr[SPR_BOOKE_DSRR0], SPR_BOOKE_DSRR1,
+           ~((target_ulong)0x3FFF0000), 0);
+}
+
+void helper_rfmci(void)
+{
+    do_rfi(env->spr[SPR_BOOKE_MCSRR0], SPR_BOOKE_MCSRR1,
+           ~((target_ulong)0x3FFF0000), 0);
+}
+#endif
+
+void helper_tw(target_ulong arg1, target_ulong arg2, uint32_t flags)
+{
+    if (!likely(!(((int32_t)arg1 < (int32_t)arg2 && (flags & 0x10)) ||
+                  ((int32_t)arg1 > (int32_t)arg2 && (flags & 0x08)) ||
+                  ((int32_t)arg1 == (int32_t)arg2 && (flags & 0x04)) ||
+                  ((uint32_t)arg1 < (uint32_t)arg2 && (flags & 0x02)) ||
+                  ((uint32_t)arg1 > (uint32_t)arg2 && (flags & 0x01))))) {
+        helper_raise_exception_err(POWERPC_EXCP_PROGRAM, POWERPC_EXCP_TRAP);
+    }
+}
+
+#if defined(TARGET_PPC64)
+void helper_td(target_ulong arg1, target_ulong arg2, uint32_t flags)
+{
+    if (!likely(!(((int64_t)arg1 < (int64_t)arg2 && (flags & 0x10)) ||
+                  ((int64_t)arg1 > (int64_t)arg2 && (flags & 0x08)) ||
+                  ((int64_t)arg1 == (int64_t)arg2 && (flags & 0x04)) ||
+                  ((uint64_t)arg1 < (uint64_t)arg2 && (flags & 0x02)) ||
+                  ((uint64_t)arg1 > (uint64_t)arg2 && (flags & 0x01))))) {
+        helper_raise_exception_err(POWERPC_EXCP_PROGRAM, POWERPC_EXCP_TRAP);
+    }
+}
+#endif
+
+#if !defined(CONFIG_USER_ONLY)
+/*****************************************************************************/
+/* PowerPC 601 specific instructions (POWER bridge) */
+
+void helper_rfsvc(void)
+{
+    do_rfi(env->lr, env->ctr, 0x0000FFFF, 0);
+}
+
+/* Embedded.Processor Control */
+static int dbell2irq(target_ulong rb)
+{
+    int msg = rb & DBELL_TYPE_MASK;
+    int irq = -1;
+
+    switch (msg) {
+    case DBELL_TYPE_DBELL:
+        irq = PPC_INTERRUPT_DOORBELL;
+        break;
+    case DBELL_TYPE_DBELL_CRIT:
+        irq = PPC_INTERRUPT_CDOORBELL;
+        break;
+    case DBELL_TYPE_G_DBELL:
+    case DBELL_TYPE_G_DBELL_CRIT:
+    case DBELL_TYPE_G_DBELL_MC:
+        /* XXX implement */
+    default:
+        break;
+    }
+
+    return irq;
+}
+
+void helper_msgclr(target_ulong rb)
+{
+    int irq = dbell2irq(rb);
+
+    if (irq < 0) {
+        return;
+    }
+
+    env->pending_interrupts &= ~(1 << irq);
+}
+
+void helper_msgsnd(target_ulong rb)
+{
+    int irq = dbell2irq(rb);
+    int pir = rb & DBELL_PIRTAG_MASK;
+    CPUPPCState *cenv;
+
+    if (irq < 0) {
+        return;
+    }
+
+    for (cenv = first_cpu; cenv != NULL; cenv = cenv->next_cpu) {
+        if ((rb & DBELL_BRDCAST) || (cenv->spr[SPR_BOOKE_PIR] == pir)) {
+            cenv->pending_interrupts |= 1 << irq;
+            cpu_interrupt(cenv, CPU_INTERRUPT_HARD);
+        }
+    }
+}
+#endif
diff --git a/target-ppc/op_helper.c b/target-ppc/op_helper.c
index d9f7a8b..2e87860 100644
--- a/target-ppc/op_helper.c
+++ b/target-ppc/op_helper.c
@@ -29,7 +29,6 @@
 #endif /* !defined(CONFIG_USER_ONLY) */
 
 //#define DEBUG_OP
-//#define DEBUG_EXCEPTIONS
 //#define DEBUG_SOFTWARE_TLB
 
 #ifdef DEBUG_SOFTWARE_TLB
@@ -38,25 +37,6 @@
 #  define LOG_SWTLB(...) do { } while (0)
 #endif
 
-
-/*****************************************************************************/
-/* Exceptions processing helpers */
-
-void helper_raise_exception_err(uint32_t exception, uint32_t error_code)
-{
-#if 0
-    printf("Raise exception %3x code : %d\n", exception, error_code);
-#endif
-    env->exception_index = exception;
-    env->error_code = error_code;
-    cpu_loop_exit(env);
-}
-
-void helper_raise_exception(uint32_t exception)
-{
-    helper_raise_exception_err(exception, 0);
-}
-
 /*****************************************************************************/
 /* SPR accesses */
 void helper_load_dump_spr(uint32_t sprn)
@@ -1658,91 +1638,6 @@ void helper_fcmpo(uint64_t arg1, uint64_t arg2, uint32_t crfD)
     }
 }
 
-#if !defined(CONFIG_USER_ONLY)
-void helper_store_msr(target_ulong val)
-{
-    val = hreg_store_msr(env, val, 0);
-    if (val != 0) {
-        env->interrupt_request |= CPU_INTERRUPT_EXITTB;
-        helper_raise_exception(val);
-    }
-}
-
-static inline void do_rfi(target_ulong nip, target_ulong msr,
-                          target_ulong msrm, int keep_msrh)
-{
-#if defined(TARGET_PPC64)
-    if (msr & (1ULL << MSR_SF)) {
-        nip = (uint64_t)nip;
-        msr &= (uint64_t)msrm;
-    } else {
-        nip = (uint32_t)nip;
-        msr = (uint32_t)(msr & msrm);
-        if (keep_msrh) {
-            msr |= env->msr & ~((uint64_t)0xFFFFFFFF);
-        }
-    }
-#else
-    nip = (uint32_t)nip;
-    msr &= (uint32_t)msrm;
-#endif
-    /* XXX: beware: this is false if VLE is supported */
-    env->nip = nip & ~((target_ulong)0x00000003);
-    hreg_store_msr(env, msr, 1);
-#if defined(DEBUG_OP)
-    cpu_dump_rfi(env->nip, env->msr);
-#endif
-    /* No need to raise an exception here,
-     * as rfi is always the last insn of a TB
-     */
-    env->interrupt_request |= CPU_INTERRUPT_EXITTB;
-}
-
-void helper_rfi(void)
-{
-    do_rfi(env->spr[SPR_SRR0], env->spr[SPR_SRR1],
-           ~((target_ulong)0x783F0000), 1);
-}
-
-#if defined(TARGET_PPC64)
-void helper_rfid(void)
-{
-    do_rfi(env->spr[SPR_SRR0], env->spr[SPR_SRR1],
-           ~((target_ulong)0x783F0000), 0);
-}
-
-void helper_hrfid(void)
-{
-    do_rfi(env->spr[SPR_HSRR0], env->spr[SPR_HSRR1],
-           ~((target_ulong)0x783F0000), 0);
-}
-#endif
-#endif
-
-void helper_tw(target_ulong arg1, target_ulong arg2, uint32_t flags)
-{
-    if (!likely(!(((int32_t)arg1 < (int32_t)arg2 && (flags & 0x10)) ||
-                  ((int32_t)arg1 > (int32_t)arg2 && (flags & 0x08)) ||
-                  ((int32_t)arg1 == (int32_t)arg2 && (flags & 0x04)) ||
-                  ((uint32_t)arg1 < (uint32_t)arg2 && (flags & 0x02)) ||
-                  ((uint32_t)arg1 > (uint32_t)arg2 && (flags & 0x01))))) {
-        helper_raise_exception_err(POWERPC_EXCP_PROGRAM, POWERPC_EXCP_TRAP);
-    }
-}
-
-#if defined(TARGET_PPC64)
-void helper_td(target_ulong arg1, target_ulong arg2, uint32_t flags)
-{
-    if (!likely(!(((int64_t)arg1 < (int64_t)arg2 && (flags & 0x10)) ||
-                  ((int64_t)arg1 > (int64_t)arg2 && (flags & 0x08)) ||
-                  ((int64_t)arg1 == (int64_t)arg2 && (flags & 0x04)) ||
-                  ((uint64_t)arg1 < (uint64_t)arg2 && (flags & 0x02)) ||
-                  ((uint64_t)arg1 > (uint64_t)arg2 && (flags & 0x01))))) {
-        helper_raise_exception_err(POWERPC_EXCP_PROGRAM, POWERPC_EXCP_TRAP);
-    }
-}
-#endif
-
 /*****************************************************************************/
 /* PowerPC 601 specific instructions (POWER bridge) */
 
@@ -1854,11 +1749,6 @@ target_ulong helper_rac(target_ulong addr)
     env->nb_BATs = nb_BATs;
     return ret;
 }
-
-void helper_rfsvc(void)
-{
-    do_rfi(env->lr, env->ctr, 0x0000FFFF, 0);
-}
 #endif
 
 /*****************************************************************************/
@@ -1918,32 +1808,6 @@ void helper_store_dcr(target_ulong dcrn, target_ulong val)
     }
 }
 
-#if !defined(CONFIG_USER_ONLY)
-void helper_40x_rfci(void)
-{
-    do_rfi(env->spr[SPR_40x_SRR2], env->spr[SPR_40x_SRR3],
-           ~((target_ulong)0xFFFF0000), 0);
-}
-
-void helper_rfci(void)
-{
-    do_rfi(env->spr[SPR_BOOKE_CSRR0], SPR_BOOKE_CSRR1,
-           ~((target_ulong)0x3FFF0000), 0);
-}
-
-void helper_rfdi(void)
-{
-    do_rfi(env->spr[SPR_BOOKE_DSRR0], SPR_BOOKE_DSRR1,
-           ~((target_ulong)0x3FFF0000), 0);
-}
-
-void helper_rfmci(void)
-{
-    do_rfi(env->spr[SPR_BOOKE_MCSRR0], SPR_BOOKE_MCSRR1,
-           ~((target_ulong)0x3FFF0000), 0);
-}
-#endif
-
 /* 440 specific */
 target_ulong helper_dlmzb(target_ulong high, target_ulong low,
                           uint32_t update_Rc)
@@ -4716,58 +4580,4 @@ void helper_booke206_tlbflush(uint32_t type)
 
     booke206_flush_tlb(env, flags, 1);
 }
-
-/* Embedded.Processor Control */
-static int dbell2irq(target_ulong rb)
-{
-    int msg = rb & DBELL_TYPE_MASK;
-    int irq = -1;
-
-    switch (msg) {
-    case DBELL_TYPE_DBELL:
-        irq = PPC_INTERRUPT_DOORBELL;
-        break;
-    case DBELL_TYPE_DBELL_CRIT:
-        irq = PPC_INTERRUPT_CDOORBELL;
-        break;
-    case DBELL_TYPE_G_DBELL:
-    case DBELL_TYPE_G_DBELL_CRIT:
-    case DBELL_TYPE_G_DBELL_MC:
-        /* XXX implement */
-    default:
-        break;
-    }
-
-    return irq;
-}
-
-void helper_msgclr(target_ulong rb)
-{
-    int irq = dbell2irq(rb);
-
-    if (irq < 0) {
-        return;
-    }
-
-    env->pending_interrupts &= ~(1 << irq);
-}
-
-void helper_msgsnd(target_ulong rb)
-{
-    int irq = dbell2irq(rb);
-    int pir = rb & DBELL_PIRTAG_MASK;
-    CPUPPCState *cenv;
-
-    if (irq < 0) {
-        return;
-    }
-
-    for (cenv = first_cpu; cenv != NULL; cenv = cenv->next_cpu) {
-        if ((rb & DBELL_BRDCAST) || (cenv->spr[SPR_BOOKE_PIR] == pir)) {
-            cenv->pending_interrupts |= 1 << irq;
-            cpu_interrupt(cenv, CPU_INTERRUPT_HARD);
-        }
-    }
-}
-
 #endif /* !CONFIG_USER_ONLY */
commit b327c654e5c11dac8a8dff3cc379b2599a288eca
Author: Blue Swirl <blauwirbel at gmail.com>
Date:   Wed May 30 04:23:21 2012 +0000

    ppc: Fix coding style in op_helper.c
    
    op_helper.c will be split by the next patches, fix
    style issues before that.
    
    Signed-off-by: Blue Swirl <blauwirbel at gmail.com>
    Signed-off-by: Alexander Graf <agraf at suse.de>
    Signed-off-by: Andreas Färber <afaerber at suse.de>
    Signed-off-by: Alexander Graf <agraf at suse.de>

diff --git a/target-ppc/op_helper.c b/target-ppc/op_helper.c
index 4ef2332..d9f7a8b 100644
--- a/target-ppc/op_helper.c
+++ b/target-ppc/op_helper.c
@@ -1,5 +1,5 @@
 /*
- *  PowerPC emulation helpers for qemu.
+ *  PowerPC emulation helpers for QEMU.
  *
  *  Copyright (c) 2003-2007 Jocelyn Mayer
  *
@@ -42,7 +42,7 @@
 /*****************************************************************************/
 /* Exceptions processing helpers */
 
-void helper_raise_exception_err (uint32_t exception, uint32_t error_code)
+void helper_raise_exception_err(uint32_t exception, uint32_t error_code)
 {
 #if 0
     printf("Raise exception %3x code : %d\n", exception, error_code);
@@ -52,116 +52,116 @@ void helper_raise_exception_err (uint32_t exception, uint32_t error_code)
     cpu_loop_exit(env);
 }
 
-void helper_raise_exception (uint32_t exception)
+void helper_raise_exception(uint32_t exception)
 {
     helper_raise_exception_err(exception, 0);
 }
 
 /*****************************************************************************/
 /* SPR accesses */
-void helper_load_dump_spr (uint32_t sprn)
+void helper_load_dump_spr(uint32_t sprn)
 {
     qemu_log("Read SPR %d %03x => " TARGET_FMT_lx "\n", sprn, sprn,
              env->spr[sprn]);
 }
 
-void helper_store_dump_spr (uint32_t sprn)
+void helper_store_dump_spr(uint32_t sprn)
 {
     qemu_log("Write SPR %d %03x <= " TARGET_FMT_lx "\n", sprn, sprn,
              env->spr[sprn]);
 }
 
-target_ulong helper_load_tbl (void)
+target_ulong helper_load_tbl(void)
 {
     return (target_ulong)cpu_ppc_load_tbl(env);
 }
 
-target_ulong helper_load_tbu (void)
+target_ulong helper_load_tbu(void)
 {
     return cpu_ppc_load_tbu(env);
 }
 
-target_ulong helper_load_atbl (void)
+target_ulong helper_load_atbl(void)
 {
     return (target_ulong)cpu_ppc_load_atbl(env);
 }
 
-target_ulong helper_load_atbu (void)
+target_ulong helper_load_atbu(void)
 {
     return cpu_ppc_load_atbu(env);
 }
 
 #if defined(TARGET_PPC64) && !defined(CONFIG_USER_ONLY)
-target_ulong helper_load_purr (void)
+target_ulong helper_load_purr(void)
 {
     return (target_ulong)cpu_ppc_load_purr(env);
 }
 #endif
 
-target_ulong helper_load_601_rtcl (void)
+target_ulong helper_load_601_rtcl(void)
 {
     return cpu_ppc601_load_rtcl(env);
 }
 
-target_ulong helper_load_601_rtcu (void)
+target_ulong helper_load_601_rtcu(void)
 {
     return cpu_ppc601_load_rtcu(env);
 }
 
 #if !defined(CONFIG_USER_ONLY)
-#if defined (TARGET_PPC64)
-void helper_store_asr (target_ulong val)
+#if defined(TARGET_PPC64)
+void helper_store_asr(target_ulong val)
 {
     ppc_store_asr(env, val);
 }
 #endif
 
-void helper_store_sdr1 (target_ulong val)
+void helper_store_sdr1(target_ulong val)
 {
     ppc_store_sdr1(env, val);
 }
 
-void helper_store_tbl (target_ulong val)
+void helper_store_tbl(target_ulong val)
 {
     cpu_ppc_store_tbl(env, val);
 }
 
-void helper_store_tbu (target_ulong val)
+void helper_store_tbu(target_ulong val)
 {
     cpu_ppc_store_tbu(env, val);
 }
 
-void helper_store_atbl (target_ulong val)
+void helper_store_atbl(target_ulong val)
 {
     cpu_ppc_store_atbl(env, val);
 }
 
-void helper_store_atbu (target_ulong val)
+void helper_store_atbu(target_ulong val)
 {
     cpu_ppc_store_atbu(env, val);
 }
 
-void helper_store_601_rtcl (target_ulong val)
+void helper_store_601_rtcl(target_ulong val)
 {
     cpu_ppc601_store_rtcl(env, val);
 }
 
-void helper_store_601_rtcu (target_ulong val)
+void helper_store_601_rtcu(target_ulong val)
 {
     cpu_ppc601_store_rtcu(env, val);
 }
 
-target_ulong helper_load_decr (void)
+target_ulong helper_load_decr(void)
 {
     return cpu_ppc_load_decr(env);
 }
 
-void helper_store_decr (target_ulong val)
+void helper_store_decr(target_ulong val)
 {
     cpu_ppc_store_decr(env, val);
 }
 
-void helper_store_hid0_601 (target_ulong val)
+void helper_store_hid0_601(target_ulong val)
 {
     target_ulong hid0;
 
@@ -178,7 +178,7 @@ void helper_store_hid0_601 (target_ulong val)
     env->spr[SPR_HID0] = (uint32_t)val;
 }
 
-void helper_store_403_pbr (uint32_t num, target_ulong value)
+void helper_store_403_pbr(uint32_t num, target_ulong value)
 {
     if (likely(env->pb[num] != value)) {
         env->pb[num] = value;
@@ -187,62 +187,62 @@ void helper_store_403_pbr (uint32_t num, target_ulong value)
     }
 }
 
-target_ulong helper_load_40x_pit (void)
+target_ulong helper_load_40x_pit(void)
 {
     return load_40x_pit(env);
 }
 
-void helper_store_40x_pit (target_ulong val)
+void helper_store_40x_pit(target_ulong val)
 {
     store_40x_pit(env, val);
 }
 
-void helper_store_40x_dbcr0 (target_ulong val)
+void helper_store_40x_dbcr0(target_ulong val)
 {
     store_40x_dbcr0(env, val);
 }
 
-void helper_store_40x_sler (target_ulong val)
+void helper_store_40x_sler(target_ulong val)
 {
     store_40x_sler(env, val);
 }
 
-void helper_store_booke_tcr (target_ulong val)
+void helper_store_booke_tcr(target_ulong val)
 {
     store_booke_tcr(env, val);
 }
 
-void helper_store_booke_tsr (target_ulong val)
+void helper_store_booke_tsr(target_ulong val)
 {
     store_booke_tsr(env, val);
 }
 
-void helper_store_ibatu (uint32_t nr, target_ulong val)
+void helper_store_ibatu(uint32_t nr, target_ulong val)
 {
     ppc_store_ibatu(env, nr, val);
 }
 
-void helper_store_ibatl (uint32_t nr, target_ulong val)
+void helper_store_ibatl(uint32_t nr, target_ulong val)
 {
     ppc_store_ibatl(env, nr, val);
 }
 
-void helper_store_dbatu (uint32_t nr, target_ulong val)
+void helper_store_dbatu(uint32_t nr, target_ulong val)
 {
     ppc_store_dbatu(env, nr, val);
 }
 
-void helper_store_dbatl (uint32_t nr, target_ulong val)
+void helper_store_dbatl(uint32_t nr, target_ulong val)
 {
     ppc_store_dbatl(env, nr, val);
 }
 
-void helper_store_601_batl (uint32_t nr, target_ulong val)
+void helper_store_601_batl(uint32_t nr, target_ulong val)
 {
     ppc_store_ibatl_601(env, nr, val);
 }
 
-void helper_store_601_batu (uint32_t nr, target_ulong val)
+void helper_store_601_batu(uint32_t nr, target_ulong val)
 {
     ppc_store_ibatu_601(env, nr, val);
 }
@@ -254,48 +254,53 @@ void helper_store_601_batu (uint32_t nr, target_ulong val)
 static inline target_ulong addr_add(target_ulong addr, target_long arg)
 {
 #if defined(TARGET_PPC64)
-        if (!msr_sf)
-            return (uint32_t)(addr + arg);
-        else
+    if (!msr_sf) {
+        return (uint32_t)(addr + arg);
+    } else
 #endif
-            return addr + arg;
+    {
+        return addr + arg;
+    }
 }
 
-void helper_lmw (target_ulong addr, uint32_t reg)
+void helper_lmw(target_ulong addr, uint32_t reg)
 {
     for (; reg < 32; reg++) {
-        if (msr_le)
+        if (msr_le) {
             env->gpr[reg] = bswap32(ldl(addr));
-        else
+        } else {
             env->gpr[reg] = ldl(addr);
-	addr = addr_add(addr, 4);
+        }
+        addr = addr_add(addr, 4);
     }
 }
 
-void helper_stmw (target_ulong addr, uint32_t reg)
+void helper_stmw(target_ulong addr, uint32_t reg)
 {
     for (; reg < 32; reg++) {
-        if (msr_le)
+        if (msr_le) {
             stl(addr, bswap32((uint32_t)env->gpr[reg]));
-        else
+        } else {
             stl(addr, (uint32_t)env->gpr[reg]);
-	addr = addr_add(addr, 4);
+        }
+        addr = addr_add(addr, 4);
     }
 }
 
 void helper_lsw(target_ulong addr, uint32_t nb, uint32_t reg)
 {
     int sh;
+
     for (; nb > 3; nb -= 4) {
         env->gpr[reg] = ldl(addr);
         reg = (reg + 1) % 32;
-	addr = addr_add(addr, 4);
+        addr = addr_add(addr, 4);
     }
     if (unlikely(nb > 0)) {
         env->gpr[reg] = 0;
         for (sh = 24; nb > 0; nb--, sh -= 8) {
             env->gpr[reg] |= ldub(addr) << sh;
-	    addr = addr_add(addr, 1);
+            addr = addr_add(addr, 1);
         }
     }
 }
@@ -321,10 +326,11 @@ void helper_lswx(target_ulong addr, uint32_t reg, uint32_t ra, uint32_t rb)
 void helper_stsw(target_ulong addr, uint32_t nb, uint32_t reg)
 {
     int sh;
+
     for (; nb > 3; nb -= 4) {
         stl(addr, env->gpr[reg]);
         reg = (reg + 1) % 32;
-	addr = addr_add(addr, 4);
+        addr = addr_add(addr, 4);
     }
     if (unlikely(nb > 0)) {
         for (sh = 24; nb > 0; nb--, sh -= 8) {
@@ -336,13 +342,15 @@ void helper_stsw(target_ulong addr, uint32_t nb, uint32_t reg)
 
 static void do_dcbz(target_ulong addr, int dcache_line_size)
 {
-    addr &= ~(dcache_line_size - 1);
     int i;
-    for (i = 0 ; i < dcache_line_size ; i += 4) {
-        stl(addr + i , 0);
+
+    addr &= ~(dcache_line_size - 1);
+    for (i = 0; i < dcache_line_size; i += 4) {
+        stl(addr + i, 0);
     }
-    if (env->reserve_addr == addr)
+    if (env->reserve_addr == addr) {
         env->reserve_addr = (target_ulong)-1ULL;
+    }
 }
 
 void helper_dcbz(target_ulong addr)
@@ -352,10 +360,11 @@ void helper_dcbz(target_ulong addr)
 
 void helper_dcbz_970(target_ulong addr)
 {
-    if (((env->spr[SPR_970_HID5] >> 7) & 0x3) == 1)
+    if (((env->spr[SPR_970_HID5] >> 7) & 0x3) == 1) {
         do_dcbz(addr, 32);
-    else
+    } else {
         do_dcbz(addr, env->dcache_line_size);
+    }
 }
 
 void helper_icbi(target_ulong addr)
@@ -369,20 +378,23 @@ void helper_icbi(target_ulong addr)
     ldl(addr);
 }
 
-// XXX: to be tested
-target_ulong helper_lscbx (target_ulong addr, uint32_t reg, uint32_t ra, uint32_t rb)
+/* XXX: to be tested */
+target_ulong helper_lscbx(target_ulong addr, uint32_t reg, uint32_t ra,
+                          uint32_t rb)
 {
     int i, c, d;
+
     d = 24;
     for (i = 0; i < xer_bc; i++) {
         c = ldub(addr);
-	addr = addr_add(addr, 1);
+        addr = addr_add(addr, 1);
         /* ra (if not 0) and rb are never modified */
         if (likely(reg != rb && (ra == 0 || reg != ra))) {
             env->gpr[reg] = (env->gpr[reg] & ~(0xFF << d)) | (c << d);
         }
-        if (unlikely(c == xer_cmp))
+        if (unlikely(c == xer_cmp)) {
             break;
+        }
         if (likely(d != 0)) {
             d -= 8;
         } else {
@@ -399,7 +411,7 @@ target_ulong helper_lscbx (target_ulong addr, uint32_t reg, uint32_t ra, uint32_
 #if defined(TARGET_PPC64)
 
 /* multiply high word */
-uint64_t helper_mulhd (uint64_t arg1, uint64_t arg2)
+uint64_t helper_mulhd(uint64_t arg1, uint64_t arg2)
 {
     uint64_t tl, th;
 
@@ -408,7 +420,7 @@ uint64_t helper_mulhd (uint64_t arg1, uint64_t arg2)
 }
 
 /* multiply high word unsigned */
-uint64_t helper_mulhdu (uint64_t arg1, uint64_t arg2)
+uint64_t helper_mulhdu(uint64_t arg1, uint64_t arg2)
 {
     uint64_t tl, th;
 
@@ -416,7 +428,7 @@ uint64_t helper_mulhdu (uint64_t arg1, uint64_t arg2)
     return th;
 }
 
-uint64_t helper_mulldo (uint64_t arg1, uint64_t arg2)
+uint64_t helper_mulldo(uint64_t arg1, uint64_t arg2)
 {
     int64_t th;
     uint64_t tl;
@@ -432,20 +444,20 @@ uint64_t helper_mulldo (uint64_t arg1, uint64_t arg2)
 }
 #endif
 
-target_ulong helper_cntlzw (target_ulong t)
+target_ulong helper_cntlzw(target_ulong t)
 {
     return clz32(t);
 }
 
 #if defined(TARGET_PPC64)
-target_ulong helper_cntlzd (target_ulong t)
+target_ulong helper_cntlzd(target_ulong t)
 {
     return clz64(t);
 }
 #endif
 
 /* shift right arithmetic helper */
-target_ulong helper_sraw (target_ulong value, target_ulong shift)
+target_ulong helper_sraw(target_ulong value, target_ulong shift)
 {
     int32_t ret;
 
@@ -474,7 +486,7 @@ target_ulong helper_sraw (target_ulong value, target_ulong shift)
 }
 
 #if defined(TARGET_PPC64)
-target_ulong helper_srad (target_ulong value, target_ulong shift)
+target_ulong helper_srad(target_ulong value, target_ulong shift)
 {
     int64_t ret;
 
@@ -504,7 +516,7 @@ target_ulong helper_srad (target_ulong value, target_ulong shift)
 #endif
 
 #if defined(TARGET_PPC64)
-target_ulong helper_popcntb (target_ulong val)
+target_ulong helper_popcntb(target_ulong val)
 {
     val = (val & 0x5555555555555555ULL) + ((val >>  1) &
                                            0x5555555555555555ULL);
@@ -515,7 +527,7 @@ target_ulong helper_popcntb (target_ulong val)
     return val;
 }
 
-target_ulong helper_popcntw (target_ulong val)
+target_ulong helper_popcntw(target_ulong val)
 {
     val = (val & 0x5555555555555555ULL) + ((val >>  1) &
                                            0x5555555555555555ULL);
@@ -530,12 +542,12 @@ target_ulong helper_popcntw (target_ulong val)
     return val;
 }
 
-target_ulong helper_popcntd (target_ulong val)
+target_ulong helper_popcntd(target_ulong val)
 {
     return ctpop64(val);
 }
 #else
-target_ulong helper_popcntb (target_ulong val)
+target_ulong helper_popcntb(target_ulong val)
 {
     val = (val & 0x55555555) + ((val >>  1) & 0x55555555);
     val = (val & 0x33333333) + ((val >>  2) & 0x33333333);
@@ -543,7 +555,7 @@ target_ulong helper_popcntb (target_ulong val)
     return val;
 }
 
-target_ulong helper_popcntw (target_ulong val)
+target_ulong helper_popcntw(target_ulong val)
 {
     val = (val & 0x55555555) + ((val >>  1) & 0x55555555);
     val = (val & 0x33333333) + ((val >>  2) & 0x33333333);
@@ -560,6 +572,7 @@ uint64_t helper_float32_to_float64(uint32_t arg)
 {
     CPU_FloatU f;
     CPU_DoubleU d;
+
     f.l = arg;
     d.d = float32_to_float64(f.f, &env->fp_status);
     return d.ll;
@@ -569,6 +582,7 @@ uint32_t helper_float64_to_float32(uint64_t arg)
 {
     CPU_FloatU f;
     CPU_DoubleU d;
+
     d.ll = arg;
     f.f = float64_to_float32(d.d, &env->fp_status);
     return f.l;
@@ -583,11 +597,12 @@ static inline int isden(float64 d)
     return ((u.ll >> 52) & 0x7FF) == 0;
 }
 
-uint32_t helper_compute_fprf (uint64_t arg, uint32_t set_fprf)
+uint32_t helper_compute_fprf(uint64_t arg, uint32_t set_fprf)
 {
     CPU_DoubleU farg;
     int isneg;
     int ret;
+
     farg.ll = arg;
     isneg = float64_is_neg(farg.d);
     if (unlikely(float64_is_any_nan(farg.d))) {
@@ -600,17 +615,19 @@ uint32_t helper_compute_fprf (uint64_t arg, uint32_t set_fprf)
         }
     } else if (unlikely(float64_is_infinity(farg.d))) {
         /* +/- infinity */
-        if (isneg)
+        if (isneg) {
             ret = 0x09;
-        else
+        } else {
             ret = 0x05;
+        }
     } else {
         if (float64_is_zero(farg.d)) {
             /* +/- zero */
-            if (isneg)
+            if (isneg) {
                 ret = 0x12;
-            else
+            } else {
                 ret = 0x02;
+            }
         } else {
             if (isden(farg.d)) {
                 /* Denormalized numbers */
@@ -645,10 +662,10 @@ static inline uint64_t fload_invalid_op_excp(int op)
     switch (op) {
     case POWERPC_EXCP_FP_VXSNAN:
         env->fpscr |= 1 << FPSCR_VXSNAN;
-	break;
+        break;
     case POWERPC_EXCP_FP_VXSOFT:
         env->fpscr |= 1 << FPSCR_VXSOFT;
-	break;
+        break;
     case POWERPC_EXCP_FP_VXISI:
         /* Magnitude subtraction of infinities */
         env->fpscr |= 1 << FPSCR_VXISI;
@@ -711,8 +728,10 @@ static inline uint64_t fload_invalid_op_excp(int op)
     if (ve != 0) {
         /* Update the floating-point enabled exception summary */
         env->fpscr |= 1 << FPSCR_FEX;
-        if (msr_fe0 != 0 || msr_fe1 != 0)
-            helper_raise_exception_err(POWERPC_EXCP_PROGRAM, POWERPC_EXCP_FP | op);
+        if (msr_fe0 != 0 || msr_fe1 != 0) {
+            helper_raise_exception_err(POWERPC_EXCP_PROGRAM,
+                                       POWERPC_EXCP_FP | op);
+        }
     }
     return ret;
 }
@@ -807,7 +826,7 @@ static inline void fpscr_set_rounding_mode(void)
     set_float_rounding_mode(rnd_type, &env->fp_status);
 }
 
-void helper_fpscr_clrbit (uint32_t bit)
+void helper_fpscr_clrbit(uint32_t bit)
 {
     int prev;
 
@@ -825,7 +844,7 @@ void helper_fpscr_clrbit (uint32_t bit)
     }
 }
 
-void helper_fpscr_setbit (uint32_t bit)
+void helper_fpscr_setbit(uint32_t bit)
 {
     int prev;
 
@@ -835,27 +854,32 @@ void helper_fpscr_setbit (uint32_t bit)
         switch (bit) {
         case FPSCR_VX:
             env->fpscr |= 1 << FPSCR_FX;
-            if (fpscr_ve)
+            if (fpscr_ve) {
                 goto raise_ve;
+            }
         case FPSCR_OX:
             env->fpscr |= 1 << FPSCR_FX;
-            if (fpscr_oe)
+            if (fpscr_oe) {
                 goto raise_oe;
+            }
             break;
         case FPSCR_UX:
             env->fpscr |= 1 << FPSCR_FX;
-            if (fpscr_ue)
+            if (fpscr_ue) {
                 goto raise_ue;
+            }
             break;
         case FPSCR_ZX:
             env->fpscr |= 1 << FPSCR_FX;
-            if (fpscr_ze)
+            if (fpscr_ze) {
                 goto raise_ze;
+            }
             break;
         case FPSCR_XX:
             env->fpscr |= 1 << FPSCR_FX;
-            if (fpscr_xe)
+            if (fpscr_xe) {
                 goto raise_xe;
+            }
             break;
         case FPSCR_VXSNAN:
         case FPSCR_VXISI:
@@ -868,31 +892,41 @@ void helper_fpscr_setbit (uint32_t bit)
         case FPSCR_VXCVI:
             env->fpscr |= 1 << FPSCR_VX;
             env->fpscr |= 1 << FPSCR_FX;
-            if (fpscr_ve != 0)
+            if (fpscr_ve != 0) {
                 goto raise_ve;
+            }
             break;
         case FPSCR_VE:
             if (fpscr_vx != 0) {
             raise_ve:
                 env->error_code = POWERPC_EXCP_FP;
-                if (fpscr_vxsnan)
+                if (fpscr_vxsnan) {
                     env->error_code |= POWERPC_EXCP_FP_VXSNAN;
-                if (fpscr_vxisi)
+                }
+                if (fpscr_vxisi) {
                     env->error_code |= POWERPC_EXCP_FP_VXISI;
-                if (fpscr_vxidi)
+                }
+                if (fpscr_vxidi) {
                     env->error_code |= POWERPC_EXCP_FP_VXIDI;
-                if (fpscr_vxzdz)
+                }
+                if (fpscr_vxzdz) {
                     env->error_code |= POWERPC_EXCP_FP_VXZDZ;
-                if (fpscr_vximz)
+                }
+                if (fpscr_vximz) {
                     env->error_code |= POWERPC_EXCP_FP_VXIMZ;
-                if (fpscr_vxvc)
+                }
+                if (fpscr_vxvc) {
                     env->error_code |= POWERPC_EXCP_FP_VXVC;
-                if (fpscr_vxsoft)
+                }
+                if (fpscr_vxsoft) {
                     env->error_code |= POWERPC_EXCP_FP_VXSOFT;
-                if (fpscr_vxsqrt)
+                }
+                if (fpscr_vxsqrt) {
                     env->error_code |= POWERPC_EXCP_FP_VXSQRT;
-                if (fpscr_vxcvi)
+                }
+                if (fpscr_vxcvi) {
                     env->error_code |= POWERPC_EXCP_FP_VXCVI;
+                }
                 goto raise_excp;
             }
             break;
@@ -933,14 +967,14 @@ void helper_fpscr_setbit (uint32_t bit)
         raise_excp:
             /* Update the floating-point enabled exception summary */
             env->fpscr |= 1 << FPSCR_FEX;
-                /* We have to update Rc1 before raising the exception */
+            /* We have to update Rc1 before raising the exception */
             env->exception_index = POWERPC_EXCP_PROGRAM;
             break;
         }
     }
 }
 
-void helper_store_fpscr (uint64_t arg, uint32_t mask)
+void helper_store_fpscr(uint64_t arg, uint32_t mask)
 {
     /*
      * We use only the 32 LSB of the incoming fpr
@@ -959,28 +993,30 @@ void helper_store_fpscr (uint64_t arg, uint32_t mask)
         }
     }
     /* Update VX and FEX */
-    if (fpscr_ix != 0)
+    if (fpscr_ix != 0) {
         env->fpscr |= 1 << FPSCR_VX;
-    else
+    } else {
         env->fpscr &= ~(1 << FPSCR_VX);
+    }
     if ((fpscr_ex & fpscr_eex) != 0) {
         env->fpscr |= 1 << FPSCR_FEX;
         env->exception_index = POWERPC_EXCP_PROGRAM;
         /* XXX: we should compute it properly */
         env->error_code = POWERPC_EXCP_FP;
-    }
-    else
+    } else {
         env->fpscr &= ~(1 << FPSCR_FEX);
+    }
     fpscr_set_rounding_mode();
 }
 
-void helper_float_check_status (void)
+void helper_float_check_status(void)
 {
     if (env->exception_index == POWERPC_EXCP_PROGRAM &&
         (env->error_code & POWERPC_EXCP_FP)) {
         /* Differred floating-point exception after target FPR update */
-        if (msr_fe0 != 0 || msr_fe1 != 0)
+        if (msr_fe0 != 0 || msr_fe1 != 0) {
             helper_raise_exception_err(env->exception_index, env->error_code);
+        }
     } else {
         int status = get_float_exception_flags(&env->fp_status);
         if (status & float_flag_divbyzero) {
@@ -995,13 +1031,13 @@ void helper_float_check_status (void)
     }
 }
 
-void helper_reset_fpstatus (void)
+void helper_reset_fpstatus(void)
 {
     set_float_exception_flags(0, &env->fp_status);
 }
 
 /* fadd - fadd. */
-uint64_t helper_fadd (uint64_t arg1, uint64_t arg2)
+uint64_t helper_fadd(uint64_t arg1, uint64_t arg2)
 {
     CPU_DoubleU farg1, farg2;
 
@@ -1025,7 +1061,7 @@ uint64_t helper_fadd (uint64_t arg1, uint64_t arg2)
 }
 
 /* fsub - fsub. */
-uint64_t helper_fsub (uint64_t arg1, uint64_t arg2)
+uint64_t helper_fsub(uint64_t arg1, uint64_t arg2)
 {
     CPU_DoubleU farg1, farg2;
 
@@ -1049,7 +1085,7 @@ uint64_t helper_fsub (uint64_t arg1, uint64_t arg2)
 }
 
 /* fmul - fmul. */
-uint64_t helper_fmul (uint64_t arg1, uint64_t arg2)
+uint64_t helper_fmul(uint64_t arg1, uint64_t arg2)
 {
     CPU_DoubleU farg1, farg2;
 
@@ -1073,14 +1109,15 @@ uint64_t helper_fmul (uint64_t arg1, uint64_t arg2)
 }
 
 /* fdiv - fdiv. */
-uint64_t helper_fdiv (uint64_t arg1, uint64_t arg2)
+uint64_t helper_fdiv(uint64_t arg1, uint64_t arg2)
 {
     CPU_DoubleU farg1, farg2;
 
     farg1.ll = arg1;
     farg2.ll = arg2;
 
-    if (unlikely(float64_is_infinity(farg1.d) && float64_is_infinity(farg2.d))) {
+    if (unlikely(float64_is_infinity(farg1.d) &&
+                 float64_is_infinity(farg2.d))) {
         /* Division of infinity by infinity */
         farg1.ll = fload_invalid_op_excp(POWERPC_EXCP_FP_VXIDI);
     } else if (unlikely(float64_is_zero(farg1.d) && float64_is_zero(farg2.d))) {
@@ -1099,7 +1136,7 @@ uint64_t helper_fdiv (uint64_t arg1, uint64_t arg2)
 }
 
 /* fabs */
-uint64_t helper_fabs (uint64_t arg)
+uint64_t helper_fabs(uint64_t arg)
 {
     CPU_DoubleU farg;
 
@@ -1109,7 +1146,7 @@ uint64_t helper_fabs (uint64_t arg)
 }
 
 /* fnabs */
-uint64_t helper_fnabs (uint64_t arg)
+uint64_t helper_fnabs(uint64_t arg)
 {
     CPU_DoubleU farg;
 
@@ -1120,7 +1157,7 @@ uint64_t helper_fnabs (uint64_t arg)
 }
 
 /* fneg */
-uint64_t helper_fneg (uint64_t arg)
+uint64_t helper_fneg(uint64_t arg)
 {
     CPU_DoubleU farg;
 
@@ -1130,15 +1167,18 @@ uint64_t helper_fneg (uint64_t arg)
 }
 
 /* fctiw - fctiw. */
-uint64_t helper_fctiw (uint64_t arg)
+uint64_t helper_fctiw(uint64_t arg)
 {
     CPU_DoubleU farg;
+
     farg.ll = arg;
 
     if (unlikely(float64_is_signaling_nan(farg.d))) {
         /* sNaN conversion */
-        farg.ll = fload_invalid_op_excp(POWERPC_EXCP_FP_VXSNAN | POWERPC_EXCP_FP_VXCVI);
-    } else if (unlikely(float64_is_quiet_nan(farg.d) || float64_is_infinity(farg.d))) {
+        farg.ll = fload_invalid_op_excp(POWERPC_EXCP_FP_VXSNAN |
+                                        POWERPC_EXCP_FP_VXCVI);
+    } else if (unlikely(float64_is_quiet_nan(farg.d) ||
+                        float64_is_infinity(farg.d))) {
         /* qNan / infinity conversion */
         farg.ll = fload_invalid_op_excp(POWERPC_EXCP_FP_VXCVI);
     } else {
@@ -1152,15 +1192,18 @@ uint64_t helper_fctiw (uint64_t arg)
 }
 
 /* fctiwz - fctiwz. */
-uint64_t helper_fctiwz (uint64_t arg)
+uint64_t helper_fctiwz(uint64_t arg)
 {
     CPU_DoubleU farg;
+
     farg.ll = arg;
 
     if (unlikely(float64_is_signaling_nan(farg.d))) {
         /* sNaN conversion */
-        farg.ll = fload_invalid_op_excp(POWERPC_EXCP_FP_VXSNAN | POWERPC_EXCP_FP_VXCVI);
-    } else if (unlikely(float64_is_quiet_nan(farg.d) || float64_is_infinity(farg.d))) {
+        farg.ll = fload_invalid_op_excp(POWERPC_EXCP_FP_VXSNAN |
+                                        POWERPC_EXCP_FP_VXCVI);
+    } else if (unlikely(float64_is_quiet_nan(farg.d) ||
+                        float64_is_infinity(farg.d))) {
         /* qNan / infinity conversion */
         farg.ll = fload_invalid_op_excp(POWERPC_EXCP_FP_VXCVI);
     } else {
@@ -1175,23 +1218,27 @@ uint64_t helper_fctiwz (uint64_t arg)
 
 #if defined(TARGET_PPC64)
 /* fcfid - fcfid. */
-uint64_t helper_fcfid (uint64_t arg)
+uint64_t helper_fcfid(uint64_t arg)
 {
     CPU_DoubleU farg;
+
     farg.d = int64_to_float64(arg, &env->fp_status);
     return farg.ll;
 }
 
 /* fctid - fctid. */
-uint64_t helper_fctid (uint64_t arg)
+uint64_t helper_fctid(uint64_t arg)
 {
     CPU_DoubleU farg;
+
     farg.ll = arg;
 
     if (unlikely(float64_is_signaling_nan(farg.d))) {
         /* sNaN conversion */
-        farg.ll = fload_invalid_op_excp(POWERPC_EXCP_FP_VXSNAN | POWERPC_EXCP_FP_VXCVI);
-    } else if (unlikely(float64_is_quiet_nan(farg.d) || float64_is_infinity(farg.d))) {
+        farg.ll = fload_invalid_op_excp(POWERPC_EXCP_FP_VXSNAN |
+                                        POWERPC_EXCP_FP_VXCVI);
+    } else if (unlikely(float64_is_quiet_nan(farg.d) ||
+                        float64_is_infinity(farg.d))) {
         /* qNan / infinity conversion */
         farg.ll = fload_invalid_op_excp(POWERPC_EXCP_FP_VXCVI);
     } else {
@@ -1201,15 +1248,18 @@ uint64_t helper_fctid (uint64_t arg)
 }
 
 /* fctidz - fctidz. */
-uint64_t helper_fctidz (uint64_t arg)
+uint64_t helper_fctidz(uint64_t arg)
 {
     CPU_DoubleU farg;
+
     farg.ll = arg;
 
     if (unlikely(float64_is_signaling_nan(farg.d))) {
         /* sNaN conversion */
-        farg.ll = fload_invalid_op_excp(POWERPC_EXCP_FP_VXSNAN | POWERPC_EXCP_FP_VXCVI);
-    } else if (unlikely(float64_is_quiet_nan(farg.d) || float64_is_infinity(farg.d))) {
+        farg.ll = fload_invalid_op_excp(POWERPC_EXCP_FP_VXSNAN |
+                                        POWERPC_EXCP_FP_VXCVI);
+    } else if (unlikely(float64_is_quiet_nan(farg.d) ||
+                        float64_is_infinity(farg.d))) {
         /* qNan / infinity conversion */
         farg.ll = fload_invalid_op_excp(POWERPC_EXCP_FP_VXCVI);
     } else {
@@ -1223,12 +1273,15 @@ uint64_t helper_fctidz (uint64_t arg)
 static inline uint64_t do_fri(uint64_t arg, int rounding_mode)
 {
     CPU_DoubleU farg;
+
     farg.ll = arg;
 
     if (unlikely(float64_is_signaling_nan(farg.d))) {
         /* sNaN round */
-        farg.ll = fload_invalid_op_excp(POWERPC_EXCP_FP_VXSNAN | POWERPC_EXCP_FP_VXCVI);
-    } else if (unlikely(float64_is_quiet_nan(farg.d) || float64_is_infinity(farg.d))) {
+        farg.ll = fload_invalid_op_excp(POWERPC_EXCP_FP_VXSNAN |
+                                        POWERPC_EXCP_FP_VXCVI);
+    } else if (unlikely(float64_is_quiet_nan(farg.d) ||
+                        float64_is_infinity(farg.d))) {
         /* qNan / infinity round */
         farg.ll = fload_invalid_op_excp(POWERPC_EXCP_FP_VXCVI);
     } else {
@@ -1240,28 +1293,28 @@ static inline uint64_t do_fri(uint64_t arg, int rounding_mode)
     return farg.ll;
 }
 
-uint64_t helper_frin (uint64_t arg)
+uint64_t helper_frin(uint64_t arg)
 {
     return do_fri(arg, float_round_nearest_even);
 }
 
-uint64_t helper_friz (uint64_t arg)
+uint64_t helper_friz(uint64_t arg)
 {
     return do_fri(arg, float_round_to_zero);
 }
 
-uint64_t helper_frip (uint64_t arg)
+uint64_t helper_frip(uint64_t arg)
 {
     return do_fri(arg, float_round_up);
 }
 
-uint64_t helper_frim (uint64_t arg)
+uint64_t helper_frim(uint64_t arg)
 {
     return do_fri(arg, float_round_down);
 }
 
 /* fmadd - fmadd. */
-uint64_t helper_fmadd (uint64_t arg1, uint64_t arg2, uint64_t arg3)
+uint64_t helper_fmadd(uint64_t arg1, uint64_t arg2, uint64_t arg3)
 {
     CPU_DoubleU farg1, farg2, farg3;
 
@@ -1286,7 +1339,8 @@ uint64_t helper_fmadd (uint64_t arg1, uint64_t arg2, uint64_t arg3)
         ft0_128 = float64_to_float128(farg1.d, &env->fp_status);
         ft1_128 = float64_to_float128(farg2.d, &env->fp_status);
         ft0_128 = float128_mul(ft0_128, ft1_128, &env->fp_status);
-        if (unlikely(float128_is_infinity(ft0_128) && float64_is_infinity(farg3.d) &&
+        if (unlikely(float128_is_infinity(ft0_128) &&
+                     float64_is_infinity(farg3.d) &&
                      float128_is_neg(ft0_128) != float64_is_neg(farg3.d))) {
             /* Magnitude subtraction of infinities */
             farg1.ll = fload_invalid_op_excp(POWERPC_EXCP_FP_VXISI);
@@ -1301,7 +1355,7 @@ uint64_t helper_fmadd (uint64_t arg1, uint64_t arg2, uint64_t arg3)
 }
 
 /* fmsub - fmsub. */
-uint64_t helper_fmsub (uint64_t arg1, uint64_t arg2, uint64_t arg3)
+uint64_t helper_fmsub(uint64_t arg1, uint64_t arg2, uint64_t arg3)
 {
     CPU_DoubleU farg1, farg2, farg3;
 
@@ -1310,7 +1364,8 @@ uint64_t helper_fmsub (uint64_t arg1, uint64_t arg2, uint64_t arg3)
     farg3.ll = arg3;
 
     if (unlikely((float64_is_infinity(farg1.d) && float64_is_zero(farg2.d)) ||
-                        (float64_is_zero(farg1.d) && float64_is_infinity(farg2.d)))) {
+                 (float64_is_zero(farg1.d) &&
+                  float64_is_infinity(farg2.d)))) {
         /* Multiplication of zero by infinity */
         farg1.ll = fload_invalid_op_excp(POWERPC_EXCP_FP_VXIMZ);
     } else {
@@ -1326,7 +1381,8 @@ uint64_t helper_fmsub (uint64_t arg1, uint64_t arg2, uint64_t arg3)
         ft0_128 = float64_to_float128(farg1.d, &env->fp_status);
         ft1_128 = float64_to_float128(farg2.d, &env->fp_status);
         ft0_128 = float128_mul(ft0_128, ft1_128, &env->fp_status);
-        if (unlikely(float128_is_infinity(ft0_128) && float64_is_infinity(farg3.d) &&
+        if (unlikely(float128_is_infinity(ft0_128) &&
+                     float64_is_infinity(farg3.d) &&
                      float128_is_neg(ft0_128) == float64_is_neg(farg3.d))) {
             /* Magnitude subtraction of infinities */
             farg1.ll = fload_invalid_op_excp(POWERPC_EXCP_FP_VXISI);
@@ -1340,7 +1396,7 @@ uint64_t helper_fmsub (uint64_t arg1, uint64_t arg2, uint64_t arg3)
 }
 
 /* fnmadd - fnmadd. */
-uint64_t helper_fnmadd (uint64_t arg1, uint64_t arg2, uint64_t arg3)
+uint64_t helper_fnmadd(uint64_t arg1, uint64_t arg2, uint64_t arg3)
 {
     CPU_DoubleU farg1, farg2, farg3;
 
@@ -1365,7 +1421,8 @@ uint64_t helper_fnmadd (uint64_t arg1, uint64_t arg2, uint64_t arg3)
         ft0_128 = float64_to_float128(farg1.d, &env->fp_status);
         ft1_128 = float64_to_float128(farg2.d, &env->fp_status);
         ft0_128 = float128_mul(ft0_128, ft1_128, &env->fp_status);
-        if (unlikely(float128_is_infinity(ft0_128) && float64_is_infinity(farg3.d) &&
+        if (unlikely(float128_is_infinity(ft0_128) &&
+                     float64_is_infinity(farg3.d) &&
                      float128_is_neg(ft0_128) != float64_is_neg(farg3.d))) {
             /* Magnitude subtraction of infinities */
             farg1.ll = fload_invalid_op_excp(POWERPC_EXCP_FP_VXISI);
@@ -1382,7 +1439,7 @@ uint64_t helper_fnmadd (uint64_t arg1, uint64_t arg2, uint64_t arg3)
 }
 
 /* fnmsub - fnmsub. */
-uint64_t helper_fnmsub (uint64_t arg1, uint64_t arg2, uint64_t arg3)
+uint64_t helper_fnmsub(uint64_t arg1, uint64_t arg2, uint64_t arg3)
 {
     CPU_DoubleU farg1, farg2, farg3;
 
@@ -1391,7 +1448,8 @@ uint64_t helper_fnmsub (uint64_t arg1, uint64_t arg2, uint64_t arg3)
     farg3.ll = arg3;
 
     if (unlikely((float64_is_infinity(farg1.d) && float64_is_zero(farg2.d)) ||
-                        (float64_is_zero(farg1.d) && float64_is_infinity(farg2.d)))) {
+                 (float64_is_zero(farg1.d) &&
+                  float64_is_infinity(farg2.d)))) {
         /* Multiplication of zero by infinity */
         farg1.ll = fload_invalid_op_excp(POWERPC_EXCP_FP_VXIMZ);
     } else {
@@ -1407,7 +1465,8 @@ uint64_t helper_fnmsub (uint64_t arg1, uint64_t arg2, uint64_t arg3)
         ft0_128 = float64_to_float128(farg1.d, &env->fp_status);
         ft1_128 = float64_to_float128(farg2.d, &env->fp_status);
         ft0_128 = float128_mul(ft0_128, ft1_128, &env->fp_status);
-        if (unlikely(float128_is_infinity(ft0_128) && float64_is_infinity(farg3.d) &&
+        if (unlikely(float128_is_infinity(ft0_128) &&
+                     float64_is_infinity(farg3.d) &&
                      float128_is_neg(ft0_128) == float64_is_neg(farg3.d))) {
             /* Magnitude subtraction of infinities */
             farg1.ll = fload_invalid_op_excp(POWERPC_EXCP_FP_VXISI);
@@ -1424,15 +1483,16 @@ uint64_t helper_fnmsub (uint64_t arg1, uint64_t arg2, uint64_t arg3)
 }
 
 /* frsp - frsp. */
-uint64_t helper_frsp (uint64_t arg)
+uint64_t helper_frsp(uint64_t arg)
 {
     CPU_DoubleU farg;
     float32 f32;
+
     farg.ll = arg;
 
     if (unlikely(float64_is_signaling_nan(farg.d))) {
         /* sNaN square root */
-       fload_invalid_op_excp(POWERPC_EXCP_FP_VXSNAN);
+        fload_invalid_op_excp(POWERPC_EXCP_FP_VXSNAN);
     }
     f32 = float64_to_float32(farg.d, &env->fp_status);
     farg.d = float32_to_float64(f32, &env->fp_status);
@@ -1441,9 +1501,10 @@ uint64_t helper_frsp (uint64_t arg)
 }
 
 /* fsqrt - fsqrt. */
-uint64_t helper_fsqrt (uint64_t arg)
+uint64_t helper_fsqrt(uint64_t arg)
 {
     CPU_DoubleU farg;
+
     farg.ll = arg;
 
     if (unlikely(float64_is_neg(farg.d) && !float64_is_zero(farg.d))) {
@@ -1460,9 +1521,10 @@ uint64_t helper_fsqrt (uint64_t arg)
 }
 
 /* fre - fre. */
-uint64_t helper_fre (uint64_t arg)
+uint64_t helper_fre(uint64_t arg)
 {
     CPU_DoubleU farg;
+
     farg.ll = arg;
 
     if (unlikely(float64_is_signaling_nan(farg.d))) {
@@ -1474,10 +1536,11 @@ uint64_t helper_fre (uint64_t arg)
 }
 
 /* fres - fres. */
-uint64_t helper_fres (uint64_t arg)
+uint64_t helper_fres(uint64_t arg)
 {
     CPU_DoubleU farg;
     float32 f32;
+
     farg.ll = arg;
 
     if (unlikely(float64_is_signaling_nan(farg.d))) {
@@ -1492,10 +1555,11 @@ uint64_t helper_fres (uint64_t arg)
 }
 
 /* frsqrte  - frsqrte. */
-uint64_t helper_frsqrte (uint64_t arg)
+uint64_t helper_frsqrte(uint64_t arg)
 {
     CPU_DoubleU farg;
     float32 f32;
+
     farg.ll = arg;
 
     if (unlikely(float64_is_neg(farg.d) && !float64_is_zero(farg.d))) {
@@ -1515,23 +1579,25 @@ uint64_t helper_frsqrte (uint64_t arg)
 }
 
 /* fsel - fsel. */
-uint64_t helper_fsel (uint64_t arg1, uint64_t arg2, uint64_t arg3)
+uint64_t helper_fsel(uint64_t arg1, uint64_t arg2, uint64_t arg3)
 {
     CPU_DoubleU farg1;
 
     farg1.ll = arg1;
 
-    if ((!float64_is_neg(farg1.d) || float64_is_zero(farg1.d)) && !float64_is_any_nan(farg1.d)) {
+    if ((!float64_is_neg(farg1.d) || float64_is_zero(farg1.d)) &&
+        !float64_is_any_nan(farg1.d)) {
         return arg2;
     } else {
         return arg3;
     }
 }
 
-void helper_fcmpu (uint64_t arg1, uint64_t arg2, uint32_t crfD)
+void helper_fcmpu(uint64_t arg1, uint64_t arg2, uint32_t crfD)
 {
     CPU_DoubleU farg1, farg2;
     uint32_t ret = 0;
+
     farg1.ll = arg1;
     farg2.ll = arg2;
 
@@ -1557,10 +1623,11 @@ void helper_fcmpu (uint64_t arg1, uint64_t arg2, uint32_t crfD)
     }
 }
 
-void helper_fcmpo (uint64_t arg1, uint64_t arg2, uint32_t crfD)
+void helper_fcmpo(uint64_t arg1, uint64_t arg2, uint32_t crfD)
 {
     CPU_DoubleU farg1, farg2;
     uint32_t ret = 0;
+
     farg1.ll = arg1;
     farg2.ll = arg2;
 
@@ -1578,7 +1645,7 @@ void helper_fcmpo (uint64_t arg1, uint64_t arg2, uint32_t crfD)
     env->fpscr &= ~(0x0F << FPSCR_FPRF);
     env->fpscr |= ret << FPSCR_FPRF;
     env->crf[crfD] = ret;
-    if (unlikely (ret == 0x01UL)) {
+    if (unlikely(ret == 0x01UL)) {
         if (float64_is_signaling_nan(farg1.d) ||
             float64_is_signaling_nan(farg2.d)) {
             /* sNaN comparison */
@@ -1591,8 +1658,8 @@ void helper_fcmpo (uint64_t arg1, uint64_t arg2, uint32_t crfD)
     }
 }
 
-#if !defined (CONFIG_USER_ONLY)
-void helper_store_msr (target_ulong val)
+#if !defined(CONFIG_USER_ONLY)
+void helper_store_msr(target_ulong val)
 {
     val = hreg_store_msr(env, val, 0);
     if (val != 0) {
@@ -1611,8 +1678,9 @@ static inline void do_rfi(target_ulong nip, target_ulong msr,
     } else {
         nip = (uint32_t)nip;
         msr = (uint32_t)(msr & msrm);
-        if (keep_msrh)
+        if (keep_msrh) {
             msr |= env->msr & ~((uint64_t)0xFFFFFFFF);
+        }
     }
 #else
     nip = (uint32_t)nip;
@@ -1621,7 +1689,7 @@ static inline void do_rfi(target_ulong nip, target_ulong msr,
     /* XXX: beware: this is false if VLE is supported */
     env->nip = nip & ~((target_ulong)0x00000003);
     hreg_store_msr(env, msr, 1);
-#if defined (DEBUG_OP)
+#if defined(DEBUG_OP)
     cpu_dump_rfi(env->nip, env->msr);
 #endif
     /* No need to raise an exception here,
@@ -1630,20 +1698,20 @@ static inline void do_rfi(target_ulong nip, target_ulong msr,
     env->interrupt_request |= CPU_INTERRUPT_EXITTB;
 }
 
-void helper_rfi (void)
+void helper_rfi(void)
 {
     do_rfi(env->spr[SPR_SRR0], env->spr[SPR_SRR1],
            ~((target_ulong)0x783F0000), 1);
 }
 
 #if defined(TARGET_PPC64)
-void helper_rfid (void)
+void helper_rfid(void)
 {
     do_rfi(env->spr[SPR_SRR0], env->spr[SPR_SRR1],
            ~((target_ulong)0x783F0000), 0);
 }
 
-void helper_hrfid (void)
+void helper_hrfid(void)
 {
     do_rfi(env->spr[SPR_HSRR0], env->spr[SPR_HSRR1],
            ~((target_ulong)0x783F0000), 0);
@@ -1651,7 +1719,7 @@ void helper_hrfid (void)
 #endif
 #endif
 
-void helper_tw (target_ulong arg1, target_ulong arg2, uint32_t flags)
+void helper_tw(target_ulong arg1, target_ulong arg2, uint32_t flags)
 {
     if (!likely(!(((int32_t)arg1 < (int32_t)arg2 && (flags & 0x10)) ||
                   ((int32_t)arg1 > (int32_t)arg2 && (flags & 0x08)) ||
@@ -1663,21 +1731,22 @@ void helper_tw (target_ulong arg1, target_ulong arg2, uint32_t flags)
 }
 
 #if defined(TARGET_PPC64)
-void helper_td (target_ulong arg1, target_ulong arg2, uint32_t flags)
+void helper_td(target_ulong arg1, target_ulong arg2, uint32_t flags)
 {
     if (!likely(!(((int64_t)arg1 < (int64_t)arg2 && (flags & 0x10)) ||
                   ((int64_t)arg1 > (int64_t)arg2 && (flags & 0x08)) ||
                   ((int64_t)arg1 == (int64_t)arg2 && (flags & 0x04)) ||
                   ((uint64_t)arg1 < (uint64_t)arg2 && (flags & 0x02)) ||
-                  ((uint64_t)arg1 > (uint64_t)arg2 && (flags & 0x01)))))
+                  ((uint64_t)arg1 > (uint64_t)arg2 && (flags & 0x01))))) {
         helper_raise_exception_err(POWERPC_EXCP_PROGRAM, POWERPC_EXCP_TRAP);
+    }
 }
 #endif
 
 /*****************************************************************************/
 /* PowerPC 601 specific instructions (POWER bridge) */
 
-target_ulong helper_clcs (uint32_t arg)
+target_ulong helper_clcs(uint32_t arg)
 {
     switch (arg) {
     case 0x0CUL:
@@ -1691,12 +1760,12 @@ target_ulong helper_clcs (uint32_t arg)
     case 0x0EUL:
         /* Minimum cache line size */
         return (env->icache_line_size < env->dcache_line_size) ?
-                env->icache_line_size : env->dcache_line_size;
+            env->icache_line_size : env->dcache_line_size;
         break;
     case 0x0FUL:
         /* Maximum cache line size */
         return (env->icache_line_size > env->dcache_line_size) ?
-                env->icache_line_size : env->dcache_line_size;
+            env->icache_line_size : env->dcache_line_size;
         break;
     default:
         /* Undefined */
@@ -1705,7 +1774,7 @@ target_ulong helper_clcs (uint32_t arg)
     }
 }
 
-target_ulong helper_div (target_ulong arg1, target_ulong arg2)
+target_ulong helper_div(target_ulong arg1, target_ulong arg2)
 {
     uint64_t tmp = (uint64_t)arg1 << 32 | env->spr[SPR_MQ];
 
@@ -1719,7 +1788,7 @@ target_ulong helper_div (target_ulong arg1, target_ulong arg2)
     }
 }
 
-target_ulong helper_divo (target_ulong arg1, target_ulong arg2)
+target_ulong helper_divo(target_ulong arg1, target_ulong arg2)
 {
     uint64_t tmp = (uint64_t)arg1 << 32 | env->spr[SPR_MQ];
 
@@ -1731,7 +1800,7 @@ target_ulong helper_divo (target_ulong arg1, target_ulong arg2)
     } else {
         env->spr[SPR_MQ] = tmp % arg2;
         tmp /= (int32_t)arg2;
-	if ((int32_t)tmp != tmp) {
+        if ((int32_t)tmp != tmp) {
             env->xer |= (1 << XER_OV) | (1 << XER_SO);
         } else {
             env->xer &= ~(1 << XER_OV);
@@ -1740,7 +1809,7 @@ target_ulong helper_divo (target_ulong arg1, target_ulong arg2)
     }
 }
 
-target_ulong helper_divs (target_ulong arg1, target_ulong arg2)
+target_ulong helper_divs(target_ulong arg1, target_ulong arg2)
 {
     if (((int32_t)arg1 == INT32_MIN && (int32_t)arg2 == (int32_t)-1) ||
         (int32_t)arg2 == 0) {
@@ -1752,7 +1821,7 @@ target_ulong helper_divs (target_ulong arg1, target_ulong arg2)
     }
 }
 
-target_ulong helper_divso (target_ulong arg1, target_ulong arg2)
+target_ulong helper_divso(target_ulong arg1, target_ulong arg2)
 {
     if (((int32_t)arg1 == INT32_MIN && (int32_t)arg2 == (int32_t)-1) ||
         (int32_t)arg2 == 0) {
@@ -1766,8 +1835,8 @@ target_ulong helper_divso (target_ulong arg1, target_ulong arg2)
     }
 }
 
-#if !defined (CONFIG_USER_ONLY)
-target_ulong helper_rac (target_ulong addr)
+#if !defined(CONFIG_USER_ONLY)
+target_ulong helper_rac(target_ulong addr)
 {
     mmu_ctx_t ctx;
     int nb_BATs;
@@ -1779,13 +1848,14 @@ target_ulong helper_rac (target_ulong addr)
     /* XXX: FIX THIS: Pretend we have no BAT */
     nb_BATs = env->nb_BATs;
     env->nb_BATs = 0;
-    if (get_physical_address(env, &ctx, addr, 0, ACCESS_INT) == 0)
+    if (get_physical_address(env, &ctx, addr, 0, ACCESS_INT) == 0) {
         ret = ctx.raddr;
+    }
     env->nb_BATs = nb_BATs;
     return ret;
 }
 
-void helper_rfsvc (void)
+void helper_rfsvc(void)
 {
     do_rfi(env->lr, env->ctr, 0x0000FFFF, 0);
 }
@@ -1799,8 +1869,8 @@ void helper_rfsvc (void)
  *                      -arg / 256
  * return 256 * log10(10           + 1.0) + 0.5
  */
-#if !defined (CONFIG_USER_ONLY)
-target_ulong helper_602_mfrom (target_ulong arg)
+#if !defined(CONFIG_USER_ONLY)
+target_ulong helper_602_mfrom(target_ulong arg)
 {
     if (likely(arg < 602)) {
 #include "mfrom_table.c"
@@ -1815,15 +1885,17 @@ target_ulong helper_602_mfrom (target_ulong arg)
 /* Embedded PowerPC specific helpers */
 
 /* XXX: to be improved to check access rights when in user-mode */
-target_ulong helper_load_dcr (target_ulong dcrn)
+target_ulong helper_load_dcr(target_ulong dcrn)
 {
     uint32_t val = 0;
 
     if (unlikely(env->dcr_env == NULL)) {
         qemu_log("No DCR environment\n");
         helper_raise_exception_err(POWERPC_EXCP_PROGRAM,
-                                   POWERPC_EXCP_INVAL | POWERPC_EXCP_INVAL_INVAL);
-    } else if (unlikely(ppc_dcr_read(env->dcr_env, (uint32_t)dcrn, &val) != 0)) {
+                                   POWERPC_EXCP_INVAL |
+                                   POWERPC_EXCP_INVAL_INVAL);
+    } else if (unlikely(ppc_dcr_read(env->dcr_env,
+                                     (uint32_t)dcrn, &val) != 0)) {
         qemu_log("DCR read error %d %03x\n", (uint32_t)dcrn, (uint32_t)dcrn);
         helper_raise_exception_err(POWERPC_EXCP_PROGRAM,
                                    POWERPC_EXCP_INVAL | POWERPC_EXCP_PRIV_REG);
@@ -1831,13 +1903,15 @@ target_ulong helper_load_dcr (target_ulong dcrn)
     return val;
 }
 
-void helper_store_dcr (target_ulong dcrn, target_ulong val)
+void helper_store_dcr(target_ulong dcrn, target_ulong val)
 {
     if (unlikely(env->dcr_env == NULL)) {
         qemu_log("No DCR environment\n");
         helper_raise_exception_err(POWERPC_EXCP_PROGRAM,
-                                   POWERPC_EXCP_INVAL | POWERPC_EXCP_INVAL_INVAL);
-    } else if (unlikely(ppc_dcr_write(env->dcr_env, (uint32_t)dcrn, (uint32_t)val) != 0)) {
+                                   POWERPC_EXCP_INVAL |
+                                   POWERPC_EXCP_INVAL_INVAL);
+    } else if (unlikely(ppc_dcr_write(env->dcr_env, (uint32_t)dcrn,
+                                      (uint32_t)val) != 0)) {
         qemu_log("DCR write error %d %03x\n", (uint32_t)dcrn, (uint32_t)dcrn);
         helper_raise_exception_err(POWERPC_EXCP_PROGRAM,
                                    POWERPC_EXCP_INVAL | POWERPC_EXCP_PRIV_REG);
@@ -1845,25 +1919,25 @@ void helper_store_dcr (target_ulong dcrn, target_ulong val)
 }
 
 #if !defined(CONFIG_USER_ONLY)
-void helper_40x_rfci (void)
+void helper_40x_rfci(void)
 {
     do_rfi(env->spr[SPR_40x_SRR2], env->spr[SPR_40x_SRR3],
            ~((target_ulong)0xFFFF0000), 0);
 }
 
-void helper_rfci (void)
+void helper_rfci(void)
 {
     do_rfi(env->spr[SPR_BOOKE_CSRR0], SPR_BOOKE_CSRR1,
            ~((target_ulong)0x3FFF0000), 0);
 }
 
-void helper_rfdi (void)
+void helper_rfdi(void)
 {
     do_rfi(env->spr[SPR_BOOKE_DSRR0], SPR_BOOKE_DSRR1,
            ~((target_ulong)0x3FFF0000), 0);
 }
 
-void helper_rfmci (void)
+void helper_rfmci(void)
 {
     do_rfi(env->spr[SPR_BOOKE_MCSRR0], SPR_BOOKE_MCSRR1,
            ~((target_ulong)0x3FFF0000), 0);
@@ -1871,7 +1945,8 @@ void helper_rfmci (void)
 #endif
 
 /* 440 specific */
-target_ulong helper_dlmzb (target_ulong high, target_ulong low, uint32_t update_Rc)
+target_ulong helper_dlmzb(target_ulong high, target_ulong low,
+                          uint32_t update_Rc)
 {
     target_ulong mask;
     int i;
@@ -1917,57 +1992,59 @@ target_ulong helper_dlmzb (target_ulong high, target_ulong low, uint32_t update_
 #endif
 
 #if defined(HOST_WORDS_BIGENDIAN)
-#define VECTOR_FOR_INORDER_I(index, element)            \
+#define VECTOR_FOR_INORDER_I(index, element)                    \
     for (index = 0; index < ARRAY_SIZE(r->element); index++)
 #else
-#define VECTOR_FOR_INORDER_I(index, element)            \
-  for (index = ARRAY_SIZE(r->element)-1; index >= 0; index--)
+#define VECTOR_FOR_INORDER_I(index, element)                    \
+    for (index = ARRAY_SIZE(r->element)-1; index >= 0; index--)
 #endif
 
 /* If X is a NaN, store the corresponding QNaN into RESULT.  Otherwise,
  * execute the following block.  */
-#define DO_HANDLE_NAN(result, x)                \
-    if (float32_is_any_nan(x)) {                                \
-        CPU_FloatU __f;                                         \
-        __f.f = x;                                              \
-        __f.l = __f.l | (1 << 22);  /* Set QNaN bit. */         \
-        result = __f.f;                                         \
+#define DO_HANDLE_NAN(result, x)                        \
+    if (float32_is_any_nan(x)) {                        \
+        CPU_FloatU __f;                                 \
+        __f.f = x;                                      \
+        __f.l = __f.l | (1 << 22);  /* Set QNaN bit. */ \
+        result = __f.f;                                 \
     } else
 
 #define HANDLE_NAN1(result, x)                  \
     DO_HANDLE_NAN(result, x)
-#define HANDLE_NAN2(result, x, y)               \
+#define HANDLE_NAN2(result, x, y)                       \
     DO_HANDLE_NAN(result, x) DO_HANDLE_NAN(result, y)
-#define HANDLE_NAN3(result, x, y, z)            \
+#define HANDLE_NAN3(result, x, y, z)                                    \
     DO_HANDLE_NAN(result, x) DO_HANDLE_NAN(result, y) DO_HANDLE_NAN(result, z)
 
 /* Saturating arithmetic helpers.  */
-#define SATCVT(from, to, from_type, to_type, min, max)                  \
-    static inline to_type cvt##from##to(from_type x, int *sat)          \
-    {                                                                   \
-        to_type r;                                                      \
-        if (x < (from_type)min) {                                       \
-            r = min;                                                    \
-            *sat = 1;                                                   \
-        } else if (x > (from_type)max) {                                \
-            r = max;                                                    \
-            *sat = 1;                                                   \
-        } else {                                                        \
-            r = x;                                                      \
-        }                                                               \
-        return r;                                                       \
+#define SATCVT(from, to, from_type, to_type, min, max)          \
+    static inline to_type cvt##from##to(from_type x, int *sat)  \
+    {                                                           \
+        to_type r;                                              \
+                                                                \
+        if (x < (from_type)min) {                               \
+            r = min;                                            \
+            *sat = 1;                                           \
+        } else if (x > (from_type)max) {                        \
+            r = max;                                            \
+            *sat = 1;                                           \
+        } else {                                                \
+            r = x;                                              \
+        }                                                       \
+        return r;                                               \
     }
-#define SATCVTU(from, to, from_type, to_type, min, max)                 \
-    static inline to_type cvt##from##to(from_type x, int *sat)          \
-    {                                                                   \
-        to_type r;                                                      \
-        if (x > (from_type)max) {                                       \
-            r = max;                                                    \
-            *sat = 1;                                                   \
-        } else {                                                        \
-            r = x;                                                      \
-        }                                                               \
-        return r;                                                       \
+#define SATCVTU(from, to, from_type, to_type, min, max)         \
+    static inline to_type cvt##from##to(from_type x, int *sat)  \
+    {                                                           \
+        to_type r;                                              \
+                                                                \
+        if (x > (from_type)max) {                               \
+            r = max;                                            \
+            *sat = 1;                                           \
+        } else {                                                \
+            r = x;                                              \
+        }                                                       \
+        return r;                                               \
     }
 SATCVT(sh, sb, int16_t, int8_t, INT8_MIN, INT8_MAX)
 SATCVT(sw, sh, int32_t, int16_t, INT16_MIN, INT16_MAX)
@@ -1983,17 +2060,20 @@ SATCVT(sd, uw, int64_t, uint32_t, 0, UINT32_MAX)
 #undef SATCVTU
 
 #define LVE(name, access, swap, element)                        \
-    void helper_##name (ppc_avr_t *r, target_ulong addr)        \
+    void helper_##name(ppc_avr_t *r, target_ulong addr)         \
     {                                                           \
         size_t n_elems = ARRAY_SIZE(r->element);                \
-        int adjust = HI_IDX*(n_elems-1);                        \
+        int adjust = HI_IDX*(n_elems - 1);                      \
         int sh = sizeof(r->element[0]) >> 1;                    \
         int index = (addr & 0xf) >> sh;                         \
-        if(msr_le) {                                            \
-            r->element[LO_IDX ? index : (adjust - index)] = swap(access(addr)); \
-        } else {                                                        \
-            r->element[LO_IDX ? index : (adjust - index)] = access(addr); \
-        }                                                               \
+                                                                \
+        if (msr_le) {                                           \
+            r->element[LO_IDX ? index : (adjust - index)] =     \
+                swap(access(addr));                             \
+        } else {                                                \
+            r->element[LO_IDX ? index : (adjust - index)] =     \
+                access(addr);                                   \
+        }                                                       \
     }
 #define I(x) (x)
 LVE(lvebx, ldub, I, u8)
@@ -2002,32 +2082,33 @@ LVE(lvewx, ldl, bswap32, u32)
 #undef I
 #undef LVE
 
-void helper_lvsl (ppc_avr_t *r, target_ulong sh)
+void helper_lvsl(ppc_avr_t *r, target_ulong sh)
 {
     int i, j = (sh & 0xf);
 
-    VECTOR_FOR_INORDER_I (i, u8) {
+    VECTOR_FOR_INORDER_I(i, u8) {
         r->u8[i] = j++;
     }
 }
 
-void helper_lvsr (ppc_avr_t *r, target_ulong sh)
+void helper_lvsr(ppc_avr_t *r, target_ulong sh)
 {
     int i, j = 0x10 - (sh & 0xf);
 
-    VECTOR_FOR_INORDER_I (i, u8) {
+    VECTOR_FOR_INORDER_I(i, u8) {
         r->u8[i] = j++;
     }
 }
 
-#define STVE(name, access, swap, element)                       \
-    void helper_##name (ppc_avr_t *r, target_ulong addr)        \
-    {                                                           \
-        size_t n_elems = ARRAY_SIZE(r->element);                \
-        int adjust = HI_IDX*(n_elems-1);                        \
-        int sh = sizeof(r->element[0]) >> 1;                    \
-        int index = (addr & 0xf) >> sh;                         \
-        if(msr_le) {                                            \
+#define STVE(name, access, swap, element)                               \
+    void helper_##name(ppc_avr_t *r, target_ulong addr)                 \
+    {                                                                   \
+        size_t n_elems = ARRAY_SIZE(r->element);                        \
+        int adjust = HI_IDX * (n_elems - 1);                            \
+        int sh = sizeof(r->element[0]) >> 1;                            \
+        int index = (addr & 0xf) >> sh;                                 \
+                                                                        \
+        if (msr_le) {                                                   \
             access(addr, swap(r->element[LO_IDX ? index : (adjust - index)])); \
         } else {                                                        \
             access(addr, r->element[LO_IDX ? index : (adjust - index)]); \
@@ -2040,7 +2121,7 @@ STVE(stvewx, stl, bswap32, u32)
 #undef I
 #undef LVE
 
-void helper_mtvscr (ppc_avr_t *r)
+void helper_mtvscr(ppc_avr_t *r)
 {
 #if defined(HOST_WORDS_BIGENDIAN)
     env->vscr = r->u32[3];
@@ -2050,25 +2131,27 @@ void helper_mtvscr (ppc_avr_t *r)
     set_flush_to_zero(vscr_nj, &env->vec_status);
 }
 
-void helper_vaddcuw (ppc_avr_t *r, ppc_avr_t *a, ppc_avr_t *b)
+void helper_vaddcuw(ppc_avr_t *r, ppc_avr_t *a, ppc_avr_t *b)
 {
     int i;
+
     for (i = 0; i < ARRAY_SIZE(r->u32); i++) {
         r->u32[i] = ~a->u32[i] < b->u32[i];
     }
 }
 
-#define VARITH_DO(name, op, element)        \
-void helper_v##name (ppc_avr_t *r, ppc_avr_t *a, ppc_avr_t *b)          \
-{                                                                       \
-    int i;                                                              \
-    for (i = 0; i < ARRAY_SIZE(r->element); i++) {                      \
-        r->element[i] = a->element[i] op b->element[i];                 \
-    }                                                                   \
-}
-#define VARITH(suffix, element)                  \
-  VARITH_DO(add##suffix, +, element)             \
-  VARITH_DO(sub##suffix, -, element)
+#define VARITH_DO(name, op, element)                                    \
+    void helper_v##name(ppc_avr_t *r, ppc_avr_t *a, ppc_avr_t *b)       \
+    {                                                                   \
+        int i;                                                          \
+                                                                        \
+        for (i = 0; i < ARRAY_SIZE(r->element); i++) {                  \
+            r->element[i] = a->element[i] op b->element[i];             \
+        }                                                               \
+    }
+#define VARITH(suffix, element)                 \
+    VARITH_DO(add##suffix, +, element)          \
+    VARITH_DO(sub##suffix, -, element)
 VARITH(ubm, u8)
 VARITH(uhm, u16)
 VARITH(uwm, u32)
@@ -2076,9 +2159,10 @@ VARITH(uwm, u32)
 #undef VARITH
 
 #define VARITHFP(suffix, func)                                          \
-    void helper_v##suffix (ppc_avr_t *r, ppc_avr_t *a, ppc_avr_t *b)    \
+    void helper_v##suffix(ppc_avr_t *r, ppc_avr_t *a, ppc_avr_t *b)     \
     {                                                                   \
         int i;                                                          \
+                                                                        \
         for (i = 0; i < ARRAY_SIZE(r->f); i++) {                        \
             HANDLE_NAN2(r->f[i], a->f[i], b->f[i]) {                    \
                 r->f[i] = func(a->f[i], b->f[i], &env->vec_status);     \
@@ -2096,26 +2180,33 @@ VARITHFP(subfp, float32_sub)
     }
 
 #define VARITHSAT_DO(name, op, optype, cvt, element)                    \
-    void helper_v##name (ppc_avr_t *r, ppc_avr_t *a, ppc_avr_t *b)      \
+    void helper_v##name(ppc_avr_t *r, ppc_avr_t *a, ppc_avr_t *b)       \
     {                                                                   \
         int sat = 0;                                                    \
         int i;                                                          \
+                                                                        \
         for (i = 0; i < ARRAY_SIZE(r->element); i++) {                  \
             switch (sizeof(r->element[0])) {                            \
-            case 1: VARITHSAT_CASE(optype, op, cvt, element); break;    \
-            case 2: VARITHSAT_CASE(optype, op, cvt, element); break;    \
-            case 4: VARITHSAT_CASE(optype, op, cvt, element); break;    \
+            case 1:                                                     \
+                VARITHSAT_CASE(optype, op, cvt, element);               \
+                break;                                                  \
+            case 2:                                                     \
+                VARITHSAT_CASE(optype, op, cvt, element);               \
+                break;                                                  \
+            case 4:                                                     \
+                VARITHSAT_CASE(optype, op, cvt, element);               \
+                break;                                                  \
             }                                                           \
         }                                                               \
         if (sat) {                                                      \
             env->vscr |= (1 << VSCR_SAT);                               \
         }                                                               \
     }
-#define VARITHSAT_SIGNED(suffix, element, optype, cvt)        \
-    VARITHSAT_DO(adds##suffix##s, +, optype, cvt, element)    \
+#define VARITHSAT_SIGNED(suffix, element, optype, cvt)          \
+    VARITHSAT_DO(adds##suffix##s, +, optype, cvt, element)      \
     VARITHSAT_DO(subs##suffix##s, -, optype, cvt, element)
-#define VARITHSAT_UNSIGNED(suffix, element, optype, cvt)       \
-    VARITHSAT_DO(addu##suffix##s, +, optype, cvt, element)     \
+#define VARITHSAT_UNSIGNED(suffix, element, optype, cvt)        \
+    VARITHSAT_DO(addu##suffix##s, +, optype, cvt, element)      \
     VARITHSAT_DO(subu##suffix##s, -, optype, cvt, element)
 VARITHSAT_SIGNED(b, s8, int16_t, cvtshsb)
 VARITHSAT_SIGNED(h, s16, int32_t, cvtswsh)
@@ -2129,16 +2220,18 @@ VARITHSAT_UNSIGNED(w, u32, uint64_t, cvtsduw)
 #undef VARITHSAT_UNSIGNED
 
 #define VAVG_DO(name, element, etype)                                   \
-    void helper_v##name (ppc_avr_t *r, ppc_avr_t *a, ppc_avr_t *b)      \
+    void helper_v##name(ppc_avr_t *r, ppc_avr_t *a, ppc_avr_t *b)       \
     {                                                                   \
         int i;                                                          \
+                                                                        \
         for (i = 0; i < ARRAY_SIZE(r->element); i++) {                  \
             etype x = (etype)a->element[i] + (etype)b->element[i] + 1;  \
             r->element[i] = x >> 1;                                     \
         }                                                               \
     }
 
-#define VAVG(type, signed_element, signed_type, unsigned_element, unsigned_type) \
+#define VAVG(type, signed_element, signed_type, unsigned_element,       \
+             unsigned_type)                                             \
     VAVG_DO(avgs##type, signed_element, signed_type)                    \
     VAVG_DO(avgu##type, unsigned_element, unsigned_type)
 VAVG(b, s8, int16_t, u8, uint16_t)
@@ -2148,12 +2241,13 @@ VAVG(w, s32, int64_t, u32, uint64_t)
 #undef VAVG
 
 #define VCF(suffix, cvt, element)                                       \
-    void helper_vcf##suffix (ppc_avr_t *r, ppc_avr_t *b, uint32_t uim)  \
+    void helper_vcf##suffix(ppc_avr_t *r, ppc_avr_t *b, uint32_t uim)   \
     {                                                                   \
         int i;                                                          \
+                                                                        \
         for (i = 0; i < ARRAY_SIZE(r->f); i++) {                        \
             float32 t = cvt(b->element[i], &env->vec_status);           \
-            r->f[i] = float32_scalbn (t, -uim, &env->vec_status);       \
+            r->f[i] = float32_scalbn(t, -uim, &env->vec_status);        \
         }                                                               \
     }
 VCF(ux, uint32_to_float32, u32)
@@ -2161,18 +2255,26 @@ VCF(sx, int32_to_float32, s32)
 #undef VCF
 
 #define VCMP_DO(suffix, compare, element, record)                       \
-    void helper_vcmp##suffix (ppc_avr_t *r, ppc_avr_t *a, ppc_avr_t *b) \
+    void helper_vcmp##suffix(ppc_avr_t *r, ppc_avr_t *a, ppc_avr_t *b)  \
     {                                                                   \
         uint32_t ones = (uint32_t)-1;                                   \
         uint32_t all = ones;                                            \
         uint32_t none = 0;                                              \
         int i;                                                          \
+                                                                        \
         for (i = 0; i < ARRAY_SIZE(r->element); i++) {                  \
-            uint32_t result = (a->element[i] compare b->element[i] ? ones : 0x0); \
-            switch (sizeof (a->element[0])) {                           \
-            case 4: r->u32[i] = result; break;                          \
-            case 2: r->u16[i] = result; break;                          \
-            case 1: r->u8[i] = result; break;                           \
+            uint32_t result = (a->element[i] compare b->element[i] ?    \
+                               ones : 0x0);                             \
+            switch (sizeof(a->element[0])) {                            \
+            case 4:                                                     \
+                r->u32[i] = result;                                     \
+                break;                                                  \
+            case 2:                                                     \
+                r->u16[i] = result;                                     \
+                break;                                                  \
+            case 1:                                                     \
+                r->u8[i] = result;                                      \
+                break;                                                  \
             }                                                           \
             all &= result;                                              \
             none |= result;                                             \
@@ -2197,15 +2299,17 @@ VCMP(gtsw, >, s32)
 #undef VCMP
 
 #define VCMPFP_DO(suffix, compare, order, record)                       \
-    void helper_vcmp##suffix (ppc_avr_t *r, ppc_avr_t *a, ppc_avr_t *b) \
+    void helper_vcmp##suffix(ppc_avr_t *r, ppc_avr_t *a, ppc_avr_t *b)  \
     {                                                                   \
         uint32_t ones = (uint32_t)-1;                                   \
         uint32_t all = ones;                                            \
         uint32_t none = 0;                                              \
         int i;                                                          \
+                                                                        \
         for (i = 0; i < ARRAY_SIZE(r->f); i++) {                        \
             uint32_t result;                                            \
-            int rel = float32_compare_quiet(a->f[i], b->f[i], &env->vec_status); \
+            int rel = float32_compare_quiet(a->f[i], b->f[i],           \
+                                            &env->vec_status);          \
             if (rel == float_relation_unordered) {                      \
                 result = 0;                                             \
             } else if (rel compare order) {                             \
@@ -2221,8 +2325,8 @@ VCMP(gtsw, >, s32)
             env->crf[6] = ((all != 0) << 3) | ((none == 0) << 1);       \
         }                                                               \
     }
-#define VCMPFP(suffix, compare, order)           \
-    VCMPFP_DO(suffix, compare, order, 0)         \
+#define VCMPFP(suffix, compare, order)          \
+    VCMPFP_DO(suffix, compare, order, 0)        \
     VCMPFP_DO(suffix##_dot, compare, order, 1)
 VCMPFP(eqfp, ==, float_relation_equal)
 VCMPFP(gefp, !=, float_relation_less)
@@ -2235,6 +2339,7 @@ static inline void vcmpbfp_internal(ppc_avr_t *r, ppc_avr_t *a, ppc_avr_t *b,
 {
     int i;
     int all_in = 0;
+
     for (i = 0; i < ARRAY_SIZE(r->f); i++) {
         int le_rel = float32_compare_quiet(a->f[i], b->f[i], &env->vec_status);
         if (le_rel == float_relation_unordered) {
@@ -2245,6 +2350,7 @@ static inline void vcmpbfp_internal(ppc_avr_t *r, ppc_avr_t *a, ppc_avr_t *b,
             int ge_rel = float32_compare_quiet(a->f[i], bneg, &env->vec_status);
             int le = le_rel != float_relation_greater;
             int ge = ge_rel != float_relation_less;
+
             r->u32[i] = ((!le) << 31) | ((!ge) << 30);
             all_in |= (!le | !ge);
         }
@@ -2254,22 +2360,23 @@ static inline void vcmpbfp_internal(ppc_avr_t *r, ppc_avr_t *a, ppc_avr_t *b,
     }
 }
 
-void helper_vcmpbfp (ppc_avr_t *r, ppc_avr_t *a, ppc_avr_t *b)
+void helper_vcmpbfp(ppc_avr_t *r, ppc_avr_t *a, ppc_avr_t *b)
 {
     vcmpbfp_internal(r, a, b, 0);
 }
 
-void helper_vcmpbfp_dot (ppc_avr_t *r, ppc_avr_t *a, ppc_avr_t *b)
+void helper_vcmpbfp_dot(ppc_avr_t *r, ppc_avr_t *a, ppc_avr_t *b)
 {
     vcmpbfp_internal(r, a, b, 1);
 }
 
 #define VCT(suffix, satcvt, element)                                    \
-    void helper_vct##suffix (ppc_avr_t *r, ppc_avr_t *b, uint32_t uim)  \
+    void helper_vct##suffix(ppc_avr_t *r, ppc_avr_t *b, uint32_t uim)   \
     {                                                                   \
         int i;                                                          \
         int sat = 0;                                                    \
         float_status s = env->vec_status;                               \
+                                                                        \
         set_float_rounding_mode(float_round_to_zero, &s);               \
         for (i = 0; i < ARRAY_SIZE(r->f); i++) {                        \
             if (float32_is_any_nan(b->f[i])) {                          \
@@ -2277,6 +2384,7 @@ void helper_vcmpbfp_dot (ppc_avr_t *r, ppc_avr_t *a, ppc_avr_t *b)
             } else {                                                    \
                 float64 t = float32_to_float64(b->f[i], &s);            \
                 int64_t j;                                              \
+                                                                        \
                 t = float64_scalbn(t, uim, &s);                         \
                 j = float64_to_int64(t, &s);                            \
                 r->element[i] = satcvt(j, &sat);                        \
@@ -2290,14 +2398,16 @@ VCT(uxs, cvtsduw, u32)
 VCT(sxs, cvtsdsw, s32)
 #undef VCT
 
-void helper_vmaddfp (ppc_avr_t *r, ppc_avr_t *a, ppc_avr_t *b, ppc_avr_t *c)
+void helper_vmaddfp(ppc_avr_t *r, ppc_avr_t *a, ppc_avr_t *b, ppc_avr_t *c)
 {
     int i;
+
     for (i = 0; i < ARRAY_SIZE(r->f); i++) {
         HANDLE_NAN3(r->f[i], a->f[i], b->f[i], c->f[i]) {
             /* Need to do the computation in higher precision and round
              * once at the end.  */
             float64 af, bf, cf, t;
+
             af = float32_to_float64(a->f[i], &env->vec_status);
             bf = float32_to_float64(b->f[i], &env->vec_status);
             cf = float32_to_float64(c->f[i], &env->vec_status);
@@ -2308,7 +2418,7 @@ void helper_vmaddfp (ppc_avr_t *r, ppc_avr_t *a, ppc_avr_t *b, ppc_avr_t *c)
     }
 }
 
-void helper_vmhaddshs (ppc_avr_t *r, ppc_avr_t *a, ppc_avr_t *b, ppc_avr_t *c)
+void helper_vmhaddshs(ppc_avr_t *r, ppc_avr_t *a, ppc_avr_t *b, ppc_avr_t *c)
 {
     int sat = 0;
     int i;
@@ -2316,7 +2426,8 @@ void helper_vmhaddshs (ppc_avr_t *r, ppc_avr_t *a, ppc_avr_t *b, ppc_avr_t *c)
     for (i = 0; i < ARRAY_SIZE(r->s16); i++) {
         int32_t prod = a->s16[i] * b->s16[i];
         int32_t t = (int32_t)c->s16[i] + (prod >> 15);
-        r->s16[i] = cvtswsh (t, &sat);
+
+        r->s16[i] = cvtswsh(t, &sat);
     }
 
     if (sat) {
@@ -2324,7 +2435,7 @@ void helper_vmhaddshs (ppc_avr_t *r, ppc_avr_t *a, ppc_avr_t *b, ppc_avr_t *c)
     }
 }
 
-void helper_vmhraddshs (ppc_avr_t *r, ppc_avr_t *a, ppc_avr_t *b, ppc_avr_t *c)
+void helper_vmhraddshs(ppc_avr_t *r, ppc_avr_t *a, ppc_avr_t *b, ppc_avr_t *c)
 {
     int sat = 0;
     int i;
@@ -2332,7 +2443,7 @@ void helper_vmhraddshs (ppc_avr_t *r, ppc_avr_t *a, ppc_avr_t *b, ppc_avr_t *c)
     for (i = 0; i < ARRAY_SIZE(r->s16); i++) {
         int32_t prod = a->s16[i] * b->s16[i] + 0x00004000;
         int32_t t = (int32_t)c->s16[i] + (prod >> 15);
-        r->s16[i] = cvtswsh (t, &sat);
+        r->s16[i] = cvtswsh(t, &sat);
     }
 
     if (sat) {
@@ -2341,9 +2452,10 @@ void helper_vmhraddshs (ppc_avr_t *r, ppc_avr_t *a, ppc_avr_t *b, ppc_avr_t *c)
 }
 
 #define VMINMAX_DO(name, compare, element)                              \
-    void helper_v##name (ppc_avr_t *r, ppc_avr_t *a, ppc_avr_t *b)      \
+    void helper_v##name(ppc_avr_t *r, ppc_avr_t *a, ppc_avr_t *b)       \
     {                                                                   \
         int i;                                                          \
+                                                                        \
         for (i = 0; i < ARRAY_SIZE(r->element); i++) {                  \
             if (a->element[i] compare b->element[i]) {                  \
                 r->element[i] = b->element[i];                          \
@@ -2353,8 +2465,8 @@ void helper_vmhraddshs (ppc_avr_t *r, ppc_avr_t *a, ppc_avr_t *b, ppc_avr_t *c)
         }                                                               \
     }
 #define VMINMAX(suffix, element)                \
-  VMINMAX_DO(min##suffix, >, element)           \
-  VMINMAX_DO(max##suffix, <, element)
+    VMINMAX_DO(min##suffix, >, element)         \
+    VMINMAX_DO(max##suffix, <, element)
 VMINMAX(sb, s8)
 VMINMAX(sh, s16)
 VMINMAX(sw, s32)
@@ -2365,12 +2477,14 @@ VMINMAX(uw, u32)
 #undef VMINMAX
 
 #define VMINMAXFP(suffix, rT, rF)                                       \
-    void helper_v##suffix (ppc_avr_t *r, ppc_avr_t *a, ppc_avr_t *b)    \
+    void helper_v##suffix(ppc_avr_t *r, ppc_avr_t *a, ppc_avr_t *b)     \
     {                                                                   \
         int i;                                                          \
+                                                                        \
         for (i = 0; i < ARRAY_SIZE(r->f); i++) {                        \
             HANDLE_NAN2(r->f[i], a->f[i], b->f[i]) {                    \
-                if (float32_lt_quiet(a->f[i], b->f[i], &env->vec_status)) { \
+                if (float32_lt_quiet(a->f[i], b->f[i],                  \
+                                     &env->vec_status)) {               \
                     r->f[i] = rT->f[i];                                 \
                 } else {                                                \
                     r->f[i] = rF->f[i];                                 \
@@ -2382,9 +2496,10 @@ VMINMAXFP(minfp, a, b)
 VMINMAXFP(maxfp, b, a)
 #undef VMINMAXFP
 
-void helper_vmladduhm (ppc_avr_t *r, ppc_avr_t *a, ppc_avr_t *b, ppc_avr_t *c)
+void helper_vmladduhm(ppc_avr_t *r, ppc_avr_t *a, ppc_avr_t *b, ppc_avr_t *c)
 {
     int i;
+
     for (i = 0; i < ARRAY_SIZE(r->s16); i++) {
         int32_t prod = a->s16[i] * b->s16[i];
         r->s16[i] = (int16_t) (prod + c->s16[i]);
@@ -2392,18 +2507,21 @@ void helper_vmladduhm (ppc_avr_t *r, ppc_avr_t *a, ppc_avr_t *b, ppc_avr_t *c)
 }
 
 #define VMRG_DO(name, element, highp)                                   \
-    void helper_v##name (ppc_avr_t *r, ppc_avr_t *a, ppc_avr_t *b)      \
+    void helper_v##name(ppc_avr_t *r, ppc_avr_t *a, ppc_avr_t *b)       \
     {                                                                   \
         ppc_avr_t result;                                               \
         int i;                                                          \
         size_t n_elems = ARRAY_SIZE(r->element);                        \
-        for (i = 0; i < n_elems/2; i++) {                               \
+                                                                        \
+        for (i = 0; i < n_elems / 2; i++) {                             \
             if (highp) {                                                \
                 result.element[i*2+HI_IDX] = a->element[i];             \
                 result.element[i*2+LO_IDX] = b->element[i];             \
             } else {                                                    \
-                result.element[n_elems - i*2 - (1+HI_IDX)] = b->element[n_elems - i - 1]; \
-                result.element[n_elems - i*2 - (1+LO_IDX)] = a->element[n_elems - i - 1]; \
+                result.element[n_elems - i * 2 - (1 + HI_IDX)] =        \
+                    b->element[n_elems - i - 1];                        \
+                result.element[n_elems - i * 2 - (1 + LO_IDX)] =        \
+                    a->element[n_elems - i - 1];                        \
             }                                                           \
         }                                                               \
         *r = result;                                                    \
@@ -2416,8 +2534,8 @@ void helper_vmladduhm (ppc_avr_t *r, ppc_avr_t *a, ppc_avr_t *b, ppc_avr_t *c)
 #define MRGLO 0
 #endif
 #define VMRG(suffix, element)                   \
-  VMRG_DO(mrgl##suffix, element, MRGHI)         \
-  VMRG_DO(mrgh##suffix, element, MRGLO)
+    VMRG_DO(mrgl##suffix, element, MRGHI)       \
+    VMRG_DO(mrgh##suffix, element, MRGLO)
 VMRG(b, u8)
 VMRG(h, u16)
 VMRG(w, u32)
@@ -2426,7 +2544,7 @@ VMRG(w, u32)
 #undef MRGHI
 #undef MRGLO
 
-void helper_vmsummbm (ppc_avr_t *r, ppc_avr_t *a, ppc_avr_t *b, ppc_avr_t *c)
+void helper_vmsummbm(ppc_avr_t *r, ppc_avr_t *a, ppc_avr_t *b, ppc_avr_t *c)
 {
     int32_t prod[16];
     int i;
@@ -2436,11 +2554,12 @@ void helper_vmsummbm (ppc_avr_t *r, ppc_avr_t *a, ppc_avr_t *b, ppc_avr_t *c)
     }
 
     VECTOR_FOR_INORDER_I(i, s32) {
-        r->s32[i] = c->s32[i] + prod[4*i] + prod[4*i+1] + prod[4*i+2] + prod[4*i+3];
+        r->s32[i] = c->s32[i] + prod[4 * i] + prod[4 * i + 1] +
+            prod[4 * i + 2] + prod[4 * i + 3];
     }
 }
 
-void helper_vmsumshm (ppc_avr_t *r, ppc_avr_t *a, ppc_avr_t *b, ppc_avr_t *c)
+void helper_vmsumshm(ppc_avr_t *r, ppc_avr_t *a, ppc_avr_t *b, ppc_avr_t *c)
 {
     int32_t prod[8];
     int i;
@@ -2450,11 +2569,11 @@ void helper_vmsumshm (ppc_avr_t *r, ppc_avr_t *a, ppc_avr_t *b, ppc_avr_t *c)
     }
 
     VECTOR_FOR_INORDER_I(i, s32) {
-        r->s32[i] = c->s32[i] + prod[2*i] + prod[2*i+1];
+        r->s32[i] = c->s32[i] + prod[2 * i] + prod[2 * i + 1];
     }
 }
 
-void helper_vmsumshs (ppc_avr_t *r, ppc_avr_t *a, ppc_avr_t *b, ppc_avr_t *c)
+void helper_vmsumshs(ppc_avr_t *r, ppc_avr_t *a, ppc_avr_t *b, ppc_avr_t *c)
 {
     int32_t prod[8];
     int i;
@@ -2464,8 +2583,9 @@ void helper_vmsumshs (ppc_avr_t *r, ppc_avr_t *a, ppc_avr_t *b, ppc_avr_t *c)
         prod[i] = (int32_t)a->s16[i] * b->s16[i];
     }
 
-    VECTOR_FOR_INORDER_I (i, s32) {
-        int64_t t = (int64_t)c->s32[i] + prod[2*i] + prod[2*i+1];
+    VECTOR_FOR_INORDER_I(i, s32) {
+        int64_t t = (int64_t)c->s32[i] + prod[2 * i] + prod[2 * i + 1];
+
         r->u32[i] = cvtsdsw(t, &sat);
     }
 
@@ -2474,7 +2594,7 @@ void helper_vmsumshs (ppc_avr_t *r, ppc_avr_t *a, ppc_avr_t *b, ppc_avr_t *c)
     }
 }
 
-void helper_vmsumubm (ppc_avr_t *r, ppc_avr_t *a, ppc_avr_t *b, ppc_avr_t *c)
+void helper_vmsumubm(ppc_avr_t *r, ppc_avr_t *a, ppc_avr_t *b, ppc_avr_t *c)
 {
     uint16_t prod[16];
     int i;
@@ -2484,11 +2604,12 @@ void helper_vmsumubm (ppc_avr_t *r, ppc_avr_t *a, ppc_avr_t *b, ppc_avr_t *c)
     }
 
     VECTOR_FOR_INORDER_I(i, u32) {
-        r->u32[i] = c->u32[i] + prod[4*i] + prod[4*i+1] + prod[4*i+2] + prod[4*i+3];
+        r->u32[i] = c->u32[i] + prod[4 * i] + prod[4 * i + 1] +
+            prod[4 * i + 2] + prod[4 * i + 3];
     }
 }
 
-void helper_vmsumuhm (ppc_avr_t *r, ppc_avr_t *a, ppc_avr_t *b, ppc_avr_t *c)
+void helper_vmsumuhm(ppc_avr_t *r, ppc_avr_t *a, ppc_avr_t *b, ppc_avr_t *c)
 {
     uint32_t prod[8];
     int i;
@@ -2498,11 +2619,11 @@ void helper_vmsumuhm (ppc_avr_t *r, ppc_avr_t *a, ppc_avr_t *b, ppc_avr_t *c)
     }
 
     VECTOR_FOR_INORDER_I(i, u32) {
-        r->u32[i] = c->u32[i] + prod[2*i] + prod[2*i+1];
+        r->u32[i] = c->u32[i] + prod[2 * i] + prod[2 * i + 1];
     }
 }
 
-void helper_vmsumuhs (ppc_avr_t *r, ppc_avr_t *a, ppc_avr_t *b, ppc_avr_t *c)
+void helper_vmsumuhs(ppc_avr_t *r, ppc_avr_t *a, ppc_avr_t *b, ppc_avr_t *c)
 {
     uint32_t prod[8];
     int i;
@@ -2512,8 +2633,9 @@ void helper_vmsumuhs (ppc_avr_t *r, ppc_avr_t *a, ppc_avr_t *b, ppc_avr_t *c)
         prod[i] = a->u16[i] * b->u16[i];
     }
 
-    VECTOR_FOR_INORDER_I (i, s32) {
-        uint64_t t = (uint64_t)c->u32[i] + prod[2*i] + prod[2*i+1];
+    VECTOR_FOR_INORDER_I(i, s32) {
+        uint64_t t = (uint64_t)c->u32[i] + prod[2 * i] + prod[2 * i + 1];
+
         r->u32[i] = cvtuduw(t, &sat);
     }
 
@@ -2523,20 +2645,23 @@ void helper_vmsumuhs (ppc_avr_t *r, ppc_avr_t *a, ppc_avr_t *b, ppc_avr_t *c)
 }
 
 #define VMUL_DO(name, mul_element, prod_element, evenp)                 \
-    void helper_v##name (ppc_avr_t *r, ppc_avr_t *a, ppc_avr_t *b)      \
+    void helper_v##name(ppc_avr_t *r, ppc_avr_t *a, ppc_avr_t *b)       \
     {                                                                   \
         int i;                                                          \
+                                                                        \
         VECTOR_FOR_INORDER_I(i, prod_element) {                         \
             if (evenp) {                                                \
-                r->prod_element[i] = a->mul_element[i*2+HI_IDX] * b->mul_element[i*2+HI_IDX]; \
+                r->prod_element[i] = a->mul_element[i * 2 + HI_IDX] *   \
+                    b->mul_element[i * 2 + HI_IDX];                     \
             } else {                                                    \
-                r->prod_element[i] = a->mul_element[i*2+LO_IDX] * b->mul_element[i*2+LO_IDX]; \
+                r->prod_element[i] = a->mul_element[i * 2 + LO_IDX] *   \
+                    b->mul_element[i * 2 + LO_IDX];                     \
             }                                                           \
         }                                                               \
     }
-#define VMUL(suffix, mul_element, prod_element) \
-  VMUL_DO(mule##suffix, mul_element, prod_element, 1) \
-  VMUL_DO(mulo##suffix, mul_element, prod_element, 0)
+#define VMUL(suffix, mul_element, prod_element)         \
+    VMUL_DO(mule##suffix, mul_element, prod_element, 1) \
+    VMUL_DO(mulo##suffix, mul_element, prod_element, 0)
 VMUL(sb, s8, s16)
 VMUL(sh, s16, s32)
 VMUL(ub, u8, u16)
@@ -2544,14 +2669,16 @@ VMUL(uh, u16, u32)
 #undef VMUL_DO
 #undef VMUL
 
-void helper_vnmsubfp (ppc_avr_t *r, ppc_avr_t *a, ppc_avr_t *b, ppc_avr_t *c)
+void helper_vnmsubfp(ppc_avr_t *r, ppc_avr_t *a, ppc_avr_t *b, ppc_avr_t *c)
 {
     int i;
+
     for (i = 0; i < ARRAY_SIZE(r->f); i++) {
         HANDLE_NAN3(r->f[i], a->f[i], b->f[i], c->f[i]) {
             /* Need to do the computation is higher precision and round
              * once at the end.  */
             float64 af, bf, cf, t;
+
             af = float32_to_float64(a->f[i], &env->vec_status);
             bf = float32_to_float64(b->f[i], &env->vec_status);
             cf = float32_to_float64(c->f[i], &env->vec_status);
@@ -2563,17 +2690,19 @@ void helper_vnmsubfp (ppc_avr_t *r, ppc_avr_t *a, ppc_avr_t *b, ppc_avr_t *c)
     }
 }
 
-void helper_vperm (ppc_avr_t *r, ppc_avr_t *a, ppc_avr_t *b, ppc_avr_t *c)
+void helper_vperm(ppc_avr_t *r, ppc_avr_t *a, ppc_avr_t *b, ppc_avr_t *c)
 {
     ppc_avr_t result;
     int i;
-    VECTOR_FOR_INORDER_I (i, u8) {
+
+    VECTOR_FOR_INORDER_I(i, u8) {
         int s = c->u8[i] & 0x1f;
 #if defined(HOST_WORDS_BIGENDIAN)
         int index = s & 0xf;
 #else
         int index = 15 - (s & 0xf);
 #endif
+
         if (s & 0x10) {
             result.u8[i] = b->u8[index];
         } else {
@@ -2588,7 +2717,7 @@ void helper_vperm (ppc_avr_t *r, ppc_avr_t *a, ppc_avr_t *b, ppc_avr_t *c)
 #else
 #define PKBIG 0
 #endif
-void helper_vpkpx (ppc_avr_t *r, ppc_avr_t *a, ppc_avr_t *b)
+void helper_vpkpx(ppc_avr_t *r, ppc_avr_t *a, ppc_avr_t *b)
 {
     int i, j;
     ppc_avr_t result;
@@ -2598,9 +2727,10 @@ void helper_vpkpx (ppc_avr_t *r, ppc_avr_t *a, ppc_avr_t *b)
     const ppc_avr_t *x[2] = { b, a };
 #endif
 
-    VECTOR_FOR_INORDER_I (i, u64) {
-        VECTOR_FOR_INORDER_I (j, u32){
+    VECTOR_FOR_INORDER_I(i, u64) {
+        VECTOR_FOR_INORDER_I(j, u32) {
             uint32_t e = x[i]->u32[j];
+
             result.u16[4*i+j] = (((e >> 9) & 0xfc00) |
                                  ((e >> 6) & 0x3e0) |
                                  ((e >> 3) & 0x1f));
@@ -2609,15 +2739,16 @@ void helper_vpkpx (ppc_avr_t *r, ppc_avr_t *a, ppc_avr_t *b)
     *r = result;
 }
 
-#define VPK(suffix, from, to, cvt, dosat)       \
-    void helper_vpk##suffix (ppc_avr_t *r, ppc_avr_t *a, ppc_avr_t *b)  \
+#define VPK(suffix, from, to, cvt, dosat)                               \
+    void helper_vpk##suffix(ppc_avr_t *r, ppc_avr_t *a, ppc_avr_t *b)   \
     {                                                                   \
         int i;                                                          \
         int sat = 0;                                                    \
         ppc_avr_t result;                                               \
         ppc_avr_t *a0 = PKBIG ? a : b;                                  \
         ppc_avr_t *a1 = PKBIG ? b : a;                                  \
-        VECTOR_FOR_INORDER_I (i, from) {                                \
+                                                                        \
+        VECTOR_FOR_INORDER_I(i, from) {                                 \
             result.to[i] = cvt(a0->from[i], &sat);                      \
             result.to[i+ARRAY_SIZE(r->from)] = cvt(a1->from[i], &sat);  \
         }                                                               \
@@ -2639,9 +2770,10 @@ VPK(uwum, u32, u16, I, 0)
 #undef VPK
 #undef PKBIG
 
-void helper_vrefp (ppc_avr_t *r, ppc_avr_t *b)
+void helper_vrefp(ppc_avr_t *r, ppc_avr_t *b)
 {
     int i;
+
     for (i = 0; i < ARRAY_SIZE(r->f); i++) {
         HANDLE_NAN1(r->f[i], b->f[i]) {
             r->f[i] = float32_div(float32_one, b->f[i], &env->vec_status);
@@ -2649,17 +2781,18 @@ void helper_vrefp (ppc_avr_t *r, ppc_avr_t *b)
     }
 }
 
-#define VRFI(suffix, rounding)                                          \
-    void helper_vrfi##suffix (ppc_avr_t *r, ppc_avr_t *b)               \
-    {                                                                   \
-        int i;                                                          \
-        float_status s = env->vec_status;                               \
-        set_float_rounding_mode(rounding, &s);                          \
-        for (i = 0; i < ARRAY_SIZE(r->f); i++) {                        \
-            HANDLE_NAN1(r->f[i], b->f[i]) {                             \
-                r->f[i] = float32_round_to_int (b->f[i], &s);           \
-            }                                                           \
-        }                                                               \
+#define VRFI(suffix, rounding)                                  \
+    void helper_vrfi##suffix(ppc_avr_t *r, ppc_avr_t *b)        \
+    {                                                           \
+        int i;                                                  \
+        float_status s = env->vec_status;                       \
+                                                                \
+        set_float_rounding_mode(rounding, &s);                  \
+        for (i = 0; i < ARRAY_SIZE(r->f); i++) {                \
+            HANDLE_NAN1(r->f[i], b->f[i]) {                     \
+                r->f[i] = float32_round_to_int (b->f[i], &s);   \
+            }                                                   \
+        }                                                       \
     }
 VRFI(n, float_round_nearest_even)
 VRFI(m, float_round_down)
@@ -2668,13 +2801,17 @@ VRFI(z, float_round_to_zero)
 #undef VRFI
 
 #define VROTATE(suffix, element)                                        \
-    void helper_vrl##suffix (ppc_avr_t *r, ppc_avr_t *a, ppc_avr_t *b)  \
+    void helper_vrl##suffix(ppc_avr_t *r, ppc_avr_t *a, ppc_avr_t *b)   \
     {                                                                   \
         int i;                                                          \
+                                                                        \
         for (i = 0; i < ARRAY_SIZE(r->element); i++) {                  \
-            unsigned int mask = ((1 << (3 + (sizeof (a->element[0]) >> 1))) - 1); \
+            unsigned int mask = ((1 <<                                  \
+                                  (3 + (sizeof(a->element[0]) >> 1)))   \
+                                 - 1);                                  \
             unsigned int shift = b->element[i] & mask;                  \
-            r->element[i] = (a->element[i] << shift) | (a->element[i] >> (sizeof(a->element[0]) * 8 - shift)); \
+            r->element[i] = (a->element[i] << shift) |                  \
+                (a->element[i] >> (sizeof(a->element[0]) * 8 - shift)); \
         }                                                               \
     }
 VROTATE(b, u8)
@@ -2682,26 +2819,29 @@ VROTATE(h, u16)
 VROTATE(w, u32)
 #undef VROTATE
 
-void helper_vrsqrtefp (ppc_avr_t *r, ppc_avr_t *b)
+void helper_vrsqrtefp(ppc_avr_t *r, ppc_avr_t *b)
 {
     int i;
+
     for (i = 0; i < ARRAY_SIZE(r->f); i++) {
         HANDLE_NAN1(r->f[i], b->f[i]) {
             float32 t = float32_sqrt(b->f[i], &env->vec_status);
+
             r->f[i] = float32_div(float32_one, t, &env->vec_status);
         }
     }
 }
 
-void helper_vsel (ppc_avr_t *r, ppc_avr_t *a, ppc_avr_t *b, ppc_avr_t *c)
+void helper_vsel(ppc_avr_t *r, ppc_avr_t *a, ppc_avr_t *b, ppc_avr_t *c)
 {
     r->u64[0] = (a->u64[0] & ~c->u64[0]) | (b->u64[0] & c->u64[0]);
     r->u64[1] = (a->u64[1] & ~c->u64[1]) | (b->u64[1] & c->u64[1]);
 }
 
-void helper_vexptefp (ppc_avr_t *r, ppc_avr_t *b)
+void helper_vexptefp(ppc_avr_t *r, ppc_avr_t *b)
 {
     int i;
+
     for (i = 0; i < ARRAY_SIZE(r->f); i++) {
         HANDLE_NAN1(r->f[i], b->f[i]) {
             r->f[i] = float32_exp2(b->f[i], &env->vec_status);
@@ -2709,9 +2849,10 @@ void helper_vexptefp (ppc_avr_t *r, ppc_avr_t *b)
     }
 }
 
-void helper_vlogefp (ppc_avr_t *r, ppc_avr_t *b)
+void helper_vlogefp(ppc_avr_t *r, ppc_avr_t *b)
 {
     int i;
+
     for (i = 0; i < ARRAY_SIZE(r->f); i++) {
         HANDLE_NAN1(r->f[i], b->f[i]) {
             r->f[i] = float32_log2(b->f[i], &env->vec_status);
@@ -2730,11 +2871,12 @@ void helper_vlogefp (ppc_avr_t *r, ppc_avr_t *b)
  * shift counts are not identical.  We check to make sure that they are
  * to conform to what real hardware appears to do.  */
 #define VSHIFT(suffix, leftp)                                           \
-    void helper_vs##suffix (ppc_avr_t *r, ppc_avr_t *a, ppc_avr_t *b)   \
+    void helper_vs##suffix(ppc_avr_t *r, ppc_avr_t *a, ppc_avr_t *b)    \
     {                                                                   \
         int shift = b->u8[LO_IDX*15] & 0x7;                             \
         int doit = 1;                                                   \
         int i;                                                          \
+                                                                        \
         for (i = 0; i < ARRAY_SIZE(r->u8); i++) {                       \
             doit = doit && ((b->u8[i] & 0x7) == shift);                 \
         }                                                               \
@@ -2743,10 +2885,12 @@ void helper_vlogefp (ppc_avr_t *r, ppc_avr_t *b)
                 *r = *a;                                                \
             } else if (leftp) {                                         \
                 uint64_t carry = a->u64[LO_IDX] >> (64 - shift);        \
+                                                                        \
                 r->u64[HI_IDX] = (a->u64[HI_IDX] << shift) | carry;     \
                 r->u64[LO_IDX] = a->u64[LO_IDX] << shift;               \
             } else {                                                    \
                 uint64_t carry = a->u64[HI_IDX] << (64 - shift);        \
+                                                                        \
                 r->u64[LO_IDX] = (a->u64[LO_IDX] >> shift) | carry;     \
                 r->u64[HI_IDX] = a->u64[HI_IDX] >> shift;               \
             }                                                           \
@@ -2759,12 +2903,16 @@ VSHIFT(r, RIGHT)
 #undef RIGHT
 
 #define VSL(suffix, element)                                            \
-    void helper_vsl##suffix (ppc_avr_t *r, ppc_avr_t *a, ppc_avr_t *b)  \
+    void helper_vsl##suffix(ppc_avr_t *r, ppc_avr_t *a, ppc_avr_t *b)   \
     {                                                                   \
         int i;                                                          \
+                                                                        \
         for (i = 0; i < ARRAY_SIZE(r->element); i++) {                  \
-            unsigned int mask = ((1 << (3 + (sizeof (a->element[0]) >> 1))) - 1); \
+            unsigned int mask = ((1 <<                                  \
+                                  (3 + (sizeof(a->element[0]) >> 1)))   \
+                                 - 1);                                  \
             unsigned int shift = b->element[i] & mask;                  \
+                                                                        \
             r->element[i] = a->element[i] << shift;                     \
         }                                                               \
     }
@@ -2773,7 +2921,7 @@ VSL(h, u16)
 VSL(w, u32)
 #undef VSL
 
-void helper_vsldoi (ppc_avr_t *r, ppc_avr_t *a, ppc_avr_t *b, uint32_t shift)
+void helper_vsldoi(ppc_avr_t *r, ppc_avr_t *a, ppc_avr_t *b, uint32_t shift)
 {
     int sh = shift & 0xf;
     int i;
@@ -2783,7 +2931,7 @@ void helper_vsldoi (ppc_avr_t *r, ppc_avr_t *a, ppc_avr_t *b, uint32_t shift)
     for (i = 0; i < ARRAY_SIZE(r->u8); i++) {
         int index = sh + i;
         if (index > 0xf) {
-            result.u8[i] = b->u8[index-0x10];
+            result.u8[i] = b->u8[index - 0x10];
         } else {
             result.u8[i] = a->u8[index];
         }
@@ -2792,7 +2940,7 @@ void helper_vsldoi (ppc_avr_t *r, ppc_avr_t *a, ppc_avr_t *b, uint32_t shift)
     for (i = 0; i < ARRAY_SIZE(r->u8); i++) {
         int index = (16 - sh) + i;
         if (index > 0xf) {
-            result.u8[i] = a->u8[index-0x10];
+            result.u8[i] = a->u8[index - 0x10];
         } else {
             result.u8[i] = b->u8[index];
         }
@@ -2801,16 +2949,16 @@ void helper_vsldoi (ppc_avr_t *r, ppc_avr_t *a, ppc_avr_t *b, uint32_t shift)
     *r = result;
 }
 
-void helper_vslo (ppc_avr_t *r, ppc_avr_t *a, ppc_avr_t *b)
+void helper_vslo(ppc_avr_t *r, ppc_avr_t *a, ppc_avr_t *b)
 {
-  int sh = (b->u8[LO_IDX*0xf] >> 3) & 0xf;
+    int sh = (b->u8[LO_IDX*0xf] >> 3) & 0xf;
 
-#if defined (HOST_WORDS_BIGENDIAN)
-  memmove (&r->u8[0], &a->u8[sh], 16-sh);
-  memset (&r->u8[16-sh], 0, sh);
+#if defined(HOST_WORDS_BIGENDIAN)
+    memmove(&r->u8[0], &a->u8[sh], 16 - sh);
+    memset(&r->u8[16-sh], 0, sh);
 #else
-  memmove (&r->u8[sh], &a->u8[0], 16-sh);
-  memset (&r->u8[0], 0, sh);
+    memmove(&r->u8[sh], &a->u8[0], 16 - sh);
+    memset(&r->u8[0], 0, sh);
 #endif
 }
 
@@ -2819,13 +2967,15 @@ void helper_vslo (ppc_avr_t *r, ppc_avr_t *a, ppc_avr_t *b)
 #if defined(HOST_WORDS_BIGENDIAN)
 #define SPLAT_ELEMENT(element) _SPLAT_MASKED(element)
 #else
-#define SPLAT_ELEMENT(element) (ARRAY_SIZE(r->element)-1 - _SPLAT_MASKED(element))
+#define SPLAT_ELEMENT(element)                                  \
+    (ARRAY_SIZE(r->element) - 1 - _SPLAT_MASKED(element))
 #endif
 #define VSPLT(suffix, element)                                          \
-    void helper_vsplt##suffix (ppc_avr_t *r, ppc_avr_t *b, uint32_t splat) \
+    void helper_vsplt##suffix(ppc_avr_t *r, ppc_avr_t *b, uint32_t splat) \
     {                                                                   \
         uint32_t s = b->element[SPLAT_ELEMENT(element)];                \
         int i;                                                          \
+                                                                        \
         for (i = 0; i < ARRAY_SIZE(r->element); i++) {                  \
             r->element[i] = s;                                          \
         }                                                               \
@@ -2838,10 +2988,11 @@ VSPLT(w, u32)
 #undef _SPLAT_MASKED
 
 #define VSPLTI(suffix, element, splat_type)                     \
-    void helper_vspltis##suffix (ppc_avr_t *r, uint32_t splat)  \
+    void helper_vspltis##suffix(ppc_avr_t *r, uint32_t splat)   \
     {                                                           \
         splat_type x = (int8_t)(splat << 3) >> 3;               \
         int i;                                                  \
+                                                                \
         for (i = 0; i < ARRAY_SIZE(r->element); i++) {          \
             r->element[i] = x;                                  \
         }                                                       \
@@ -2852,12 +3003,16 @@ VSPLTI(w, s32, int32_t)
 #undef VSPLTI
 
 #define VSR(suffix, element)                                            \
-    void helper_vsr##suffix (ppc_avr_t *r, ppc_avr_t *a, ppc_avr_t *b)  \
+    void helper_vsr##suffix(ppc_avr_t *r, ppc_avr_t *a, ppc_avr_t *b)   \
     {                                                                   \
         int i;                                                          \
+                                                                        \
         for (i = 0; i < ARRAY_SIZE(r->element); i++) {                  \
-            unsigned int mask = ((1 << (3 + (sizeof (a->element[0]) >> 1))) - 1); \
+            unsigned int mask = ((1 <<                                  \
+                                  (3 + (sizeof(a->element[0]) >> 1)))   \
+                                 - 1);                                  \
             unsigned int shift = b->element[i] & mask;                  \
+                                                                        \
             r->element[i] = a->element[i] >> shift;                     \
         }                                                               \
     }
@@ -2869,28 +3024,29 @@ VSR(h, u16)
 VSR(w, u32)
 #undef VSR
 
-void helper_vsro (ppc_avr_t *r, ppc_avr_t *a, ppc_avr_t *b)
+void helper_vsro(ppc_avr_t *r, ppc_avr_t *a, ppc_avr_t *b)
 {
-  int sh = (b->u8[LO_IDX*0xf] >> 3) & 0xf;
+    int sh = (b->u8[LO_IDX * 0xf] >> 3) & 0xf;
 
-#if defined (HOST_WORDS_BIGENDIAN)
-  memmove (&r->u8[sh], &a->u8[0], 16-sh);
-  memset (&r->u8[0], 0, sh);
+#if defined(HOST_WORDS_BIGENDIAN)
+    memmove(&r->u8[sh], &a->u8[0], 16 - sh);
+    memset(&r->u8[0], 0, sh);
 #else
-  memmove (&r->u8[0], &a->u8[sh], 16-sh);
-  memset (&r->u8[16-sh], 0, sh);
+    memmove(&r->u8[0], &a->u8[sh], 16 - sh);
+    memset(&r->u8[16 - sh], 0, sh);
 #endif
 }
 
-void helper_vsubcuw (ppc_avr_t *r, ppc_avr_t *a, ppc_avr_t *b)
+void helper_vsubcuw(ppc_avr_t *r, ppc_avr_t *a, ppc_avr_t *b)
 {
     int i;
+
     for (i = 0; i < ARRAY_SIZE(r->u32); i++) {
         r->u32[i] = a->u32[i] >= b->u32[i];
     }
 }
 
-void helper_vsumsws (ppc_avr_t *r, ppc_avr_t *a, ppc_avr_t *b)
+void helper_vsumsws(ppc_avr_t *r, ppc_avr_t *a, ppc_avr_t *b)
 {
     int64_t t;
     int i, upper;
@@ -2915,7 +3071,7 @@ void helper_vsumsws (ppc_avr_t *r, ppc_avr_t *a, ppc_avr_t *b)
     }
 }
 
-void helper_vsum2sws (ppc_avr_t *r, ppc_avr_t *a, ppc_avr_t *b)
+void helper_vsum2sws(ppc_avr_t *r, ppc_avr_t *a, ppc_avr_t *b)
 {
     int i, j, upper;
     ppc_avr_t result;
@@ -2927,12 +3083,13 @@ void helper_vsum2sws (ppc_avr_t *r, ppc_avr_t *a, ppc_avr_t *b)
     upper = 0;
 #endif
     for (i = 0; i < ARRAY_SIZE(r->u64); i++) {
-        int64_t t = (int64_t)b->s32[upper+i*2];
+        int64_t t = (int64_t)b->s32[upper + i * 2];
+
         result.u64[i] = 0;
         for (j = 0; j < ARRAY_SIZE(r->u64); j++) {
-            t += a->s32[2*i+j];
+            t += a->s32[2 * i + j];
         }
-        result.s32[upper+i*2] = cvtsdsw(t, &sat);
+        result.s32[upper + i * 2] = cvtsdsw(t, &sat);
     }
 
     *r = result;
@@ -2941,15 +3098,16 @@ void helper_vsum2sws (ppc_avr_t *r, ppc_avr_t *a, ppc_avr_t *b)
     }
 }
 
-void helper_vsum4sbs (ppc_avr_t *r, ppc_avr_t *a, ppc_avr_t *b)
+void helper_vsum4sbs(ppc_avr_t *r, ppc_avr_t *a, ppc_avr_t *b)
 {
     int i, j;
     int sat = 0;
 
     for (i = 0; i < ARRAY_SIZE(r->s32); i++) {
         int64_t t = (int64_t)b->s32[i];
+
         for (j = 0; j < ARRAY_SIZE(r->s32); j++) {
-            t += a->s8[4*i+j];
+            t += a->s8[4 * i + j];
         }
         r->s32[i] = cvtsdsw(t, &sat);
     }
@@ -2959,14 +3117,15 @@ void helper_vsum4sbs (ppc_avr_t *r, ppc_avr_t *a, ppc_avr_t *b)
     }
 }
 
-void helper_vsum4shs (ppc_avr_t *r, ppc_avr_t *a, ppc_avr_t *b)
+void helper_vsum4shs(ppc_avr_t *r, ppc_avr_t *a, ppc_avr_t *b)
 {
     int sat = 0;
     int i;
 
     for (i = 0; i < ARRAY_SIZE(r->s32); i++) {
         int64_t t = (int64_t)b->s32[i];
-        t += a->s16[2*i] + a->s16[2*i+1];
+
+        t += a->s16[2 * i] + a->s16[2 * i + 1];
         r->s32[i] = cvtsdsw(t, &sat);
     }
 
@@ -2975,15 +3134,16 @@ void helper_vsum4shs (ppc_avr_t *r, ppc_avr_t *a, ppc_avr_t *b)
     }
 }
 
-void helper_vsum4ubs (ppc_avr_t *r, ppc_avr_t *a, ppc_avr_t *b)
+void helper_vsum4ubs(ppc_avr_t *r, ppc_avr_t *a, ppc_avr_t *b)
 {
     int i, j;
     int sat = 0;
 
     for (i = 0; i < ARRAY_SIZE(r->u32); i++) {
         uint64_t t = (uint64_t)b->u32[i];
+
         for (j = 0; j < ARRAY_SIZE(r->u32); j++) {
-            t += a->u8[4*i+j];
+            t += a->u8[4 * i + j];
         }
         r->u32[i] = cvtuduw(t, &sat);
     }
@@ -3000,17 +3160,19 @@ void helper_vsum4ubs (ppc_avr_t *r, ppc_avr_t *a, ppc_avr_t *b)
 #define UPKHI 0
 #define UPKLO 1
 #endif
-#define VUPKPX(suffix, hi)                                      \
-    void helper_vupk##suffix (ppc_avr_t *r, ppc_avr_t *b)       \
-    {                                                           \
-        int i;                                                  \
-        ppc_avr_t result;                                       \
-        for (i = 0; i < ARRAY_SIZE(r->u32); i++) {              \
-            uint16_t e = b->u16[hi ? i : i+4];                  \
-            uint8_t a = (e >> 15) ? 0xff : 0;                   \
-            uint8_t r = (e >> 10) & 0x1f;                       \
-            uint8_t g = (e >> 5) & 0x1f;                        \
-            uint8_t b = e & 0x1f;                               \
+#define VUPKPX(suffix, hi)                                              \
+    void helper_vupk##suffix(ppc_avr_t *r, ppc_avr_t *b)                \
+    {                                                                   \
+        int i;                                                          \
+        ppc_avr_t result;                                               \
+                                                                        \
+        for (i = 0; i < ARRAY_SIZE(r->u32); i++) {                      \
+            uint16_t e = b->u16[hi ? i : i+4];                          \
+            uint8_t a = (e >> 15) ? 0xff : 0;                           \
+            uint8_t r = (e >> 10) & 0x1f;                               \
+            uint8_t g = (e >> 5) & 0x1f;                                \
+            uint8_t b = e & 0x1f;                                       \
+                                                                        \
             result.u32[i] = (a << 24) | (r << 16) | (g << 8) | b;       \
         }                                                               \
         *r = result;                                                    \
@@ -3020,17 +3182,19 @@ VUPKPX(hpx, UPKHI)
 #undef VUPKPX
 
 #define VUPK(suffix, unpacked, packee, hi)                              \
-    void helper_vupk##suffix (ppc_avr_t *r, ppc_avr_t *b)               \
+    void helper_vupk##suffix(ppc_avr_t *r, ppc_avr_t *b)                \
     {                                                                   \
         int i;                                                          \
         ppc_avr_t result;                                               \
+                                                                        \
         if (hi) {                                                       \
             for (i = 0; i < ARRAY_SIZE(r->unpacked); i++) {             \
                 result.unpacked[i] = b->packee[i];                      \
             }                                                           \
         } else {                                                        \
-            for (i = ARRAY_SIZE(r->unpacked); i < ARRAY_SIZE(r->packee); i++) { \
-                result.unpacked[i-ARRAY_SIZE(r->unpacked)] = b->packee[i]; \
+            for (i = ARRAY_SIZE(r->unpacked); i < ARRAY_SIZE(r->packee); \
+                 i++) {                                                 \
+                result.unpacked[i - ARRAY_SIZE(r->unpacked)] = b->packee[i]; \
             }                                                           \
         }                                                               \
         *r = result;                                                    \
@@ -3070,8 +3234,8 @@ static inline uint32_t word_reverse(uint32_t val)
         (byte_reverse(val >> 8) << 16) | (byte_reverse(val) << 24);
 }
 
-#define MASKBITS 16 // Random value - to be fixed (implementation dependent)
-target_ulong helper_brinc (target_ulong arg1, target_ulong arg2)
+#define MASKBITS 16 /* Random value - to be fixed (implementation dependent) */
+target_ulong helper_brinc(target_ulong arg1, target_ulong arg2)
 {
     uint32_t a, b, d, mask;
 
@@ -3082,15 +3246,16 @@ target_ulong helper_brinc (target_ulong arg1, target_ulong arg2)
     return (arg1 & ~mask) | (d & b);
 }
 
-uint32_t helper_cntlsw32 (uint32_t val)
+uint32_t helper_cntlsw32(uint32_t val)
 {
-    if (val & 0x80000000)
+    if (val & 0x80000000) {
         return clz32(~val);
-    else
+    } else {
         return clz32(val);
+    }
 }
 
-uint32_t helper_cntlzw32 (uint32_t val)
+uint32_t helper_cntlzw32(uint32_t val)
 {
     return clz32(val);
 }
@@ -3120,8 +3285,9 @@ static inline int32_t efsctsi(uint32_t val)
 
     u.l = val;
     /* NaN are not treated the same way IEEE 754 does */
-    if (unlikely(float32_is_quiet_nan(u.f)))
+    if (unlikely(float32_is_quiet_nan(u.f))) {
         return 0;
+    }
 
     return float32_to_int32(u.f, &env->vec_status);
 }
@@ -3132,8 +3298,9 @@ static inline uint32_t efsctui(uint32_t val)
 
     u.l = val;
     /* NaN are not treated the same way IEEE 754 does */
-    if (unlikely(float32_is_quiet_nan(u.f)))
+    if (unlikely(float32_is_quiet_nan(u.f))) {
         return 0;
+    }
 
     return float32_to_uint32(u.f, &env->vec_status);
 }
@@ -3144,8 +3311,9 @@ static inline uint32_t efsctsiz(uint32_t val)
 
     u.l = val;
     /* NaN are not treated the same way IEEE 754 does */
-    if (unlikely(float32_is_quiet_nan(u.f)))
+    if (unlikely(float32_is_quiet_nan(u.f))) {
         return 0;
+    }
 
     return float32_to_int32_round_to_zero(u.f, &env->vec_status);
 }
@@ -3156,8 +3324,9 @@ static inline uint32_t efsctuiz(uint32_t val)
 
     u.l = val;
     /* NaN are not treated the same way IEEE 754 does */
-    if (unlikely(float32_is_quiet_nan(u.f)))
+    if (unlikely(float32_is_quiet_nan(u.f))) {
         return 0;
+    }
 
     return float32_to_uint32_round_to_zero(u.f, &env->vec_status);
 }
@@ -3193,8 +3362,9 @@ static inline uint32_t efsctsf(uint32_t val)
 
     u.l = val;
     /* NaN are not treated the same way IEEE 754 does */
-    if (unlikely(float32_is_quiet_nan(u.f)))
+    if (unlikely(float32_is_quiet_nan(u.f))) {
         return 0;
+    }
     tmp = uint64_to_float32(1ULL << 32, &env->vec_status);
     u.f = float32_mul(u.f, tmp, &env->vec_status);
 
@@ -3208,19 +3378,20 @@ static inline uint32_t efsctuf(uint32_t val)
 
     u.l = val;
     /* NaN are not treated the same way IEEE 754 does */
-    if (unlikely(float32_is_quiet_nan(u.f)))
+    if (unlikely(float32_is_quiet_nan(u.f))) {
         return 0;
+    }
     tmp = uint64_to_float32(1ULL << 32, &env->vec_status);
     u.f = float32_mul(u.f, tmp, &env->vec_status);
 
     return float32_to_uint32(u.f, &env->vec_status);
 }
 
-#define HELPER_SPE_SINGLE_CONV(name)                                          \
-uint32_t helper_e##name (uint32_t val)                                        \
-{                                                                             \
-    return e##name(val);                                                      \
-}
+#define HELPER_SPE_SINGLE_CONV(name)            \
+    uint32_t helper_e##name(uint32_t val)       \
+    {                                           \
+        return e##name(val);                    \
+    }
 /* efscfsi */
 HELPER_SPE_SINGLE_CONV(fscfsi);
 /* efscfui */
@@ -3242,12 +3413,12 @@ HELPER_SPE_SINGLE_CONV(fsctsf);
 /* efsctuf */
 HELPER_SPE_SINGLE_CONV(fsctuf);
 
-#define HELPER_SPE_VECTOR_CONV(name)                                          \
-uint64_t helper_ev##name (uint64_t val)                                       \
-{                                                                             \
-    return ((uint64_t)e##name(val >> 32) << 32) |                             \
-            (uint64_t)e##name(val);                                           \
-}
+#define HELPER_SPE_VECTOR_CONV(name)                    \
+    uint64_t helper_ev##name(uint64_t val)              \
+    {                                                   \
+        return ((uint64_t)e##name(val >> 32) << 32) |   \
+            (uint64_t)e##name(val);                     \
+    }
 /* evfscfsi */
 HELPER_SPE_VECTOR_CONV(fscfsi);
 /* evfscfui */
@@ -3273,6 +3444,7 @@ HELPER_SPE_VECTOR_CONV(fsctuf);
 static inline uint32_t efsadd(uint32_t op1, uint32_t op2)
 {
     CPU_FloatU u1, u2;
+
     u1.l = op1;
     u2.l = op2;
     u1.f = float32_add(u1.f, u2.f, &env->vec_status);
@@ -3282,6 +3454,7 @@ static inline uint32_t efsadd(uint32_t op1, uint32_t op2)
 static inline uint32_t efssub(uint32_t op1, uint32_t op2)
 {
     CPU_FloatU u1, u2;
+
     u1.l = op1;
     u2.l = op2;
     u1.f = float32_sub(u1.f, u2.f, &env->vec_status);
@@ -3291,6 +3464,7 @@ static inline uint32_t efssub(uint32_t op1, uint32_t op2)
 static inline uint32_t efsmul(uint32_t op1, uint32_t op2)
 {
     CPU_FloatU u1, u2;
+
     u1.l = op1;
     u2.l = op2;
     u1.f = float32_mul(u1.f, u2.f, &env->vec_status);
@@ -3300,17 +3474,18 @@ static inline uint32_t efsmul(uint32_t op1, uint32_t op2)
 static inline uint32_t efsdiv(uint32_t op1, uint32_t op2)
 {
     CPU_FloatU u1, u2;
+
     u1.l = op1;
     u2.l = op2;
     u1.f = float32_div(u1.f, u2.f, &env->vec_status);
     return u1.l;
 }
 
-#define HELPER_SPE_SINGLE_ARITH(name)                                         \
-uint32_t helper_e##name (uint32_t op1, uint32_t op2)                          \
-{                                                                             \
-    return e##name(op1, op2);                                                 \
-}
+#define HELPER_SPE_SINGLE_ARITH(name)                   \
+    uint32_t helper_e##name(uint32_t op1, uint32_t op2) \
+    {                                                   \
+        return e##name(op1, op2);                       \
+    }
 /* efsadd */
 HELPER_SPE_SINGLE_ARITH(fsadd);
 /* efssub */
@@ -3320,12 +3495,12 @@ HELPER_SPE_SINGLE_ARITH(fsmul);
 /* efsdiv */
 HELPER_SPE_SINGLE_ARITH(fsdiv);
 
-#define HELPER_SPE_VECTOR_ARITH(name)                                         \
-uint64_t helper_ev##name (uint64_t op1, uint64_t op2)                         \
-{                                                                             \
-    return ((uint64_t)e##name(op1 >> 32, op2 >> 32) << 32) |                  \
-            (uint64_t)e##name(op1, op2);                                      \
-}
+#define HELPER_SPE_VECTOR_ARITH(name)                                   \
+    uint64_t helper_ev##name(uint64_t op1, uint64_t op2)                \
+    {                                                                   \
+        return ((uint64_t)e##name(op1 >> 32, op2 >> 32) << 32) |        \
+            (uint64_t)e##name(op1, op2);                                \
+    }
 /* evfsadd */
 HELPER_SPE_VECTOR_ARITH(fsadd);
 /* evfssub */
@@ -3339,6 +3514,7 @@ HELPER_SPE_VECTOR_ARITH(fsdiv);
 static inline uint32_t efscmplt(uint32_t op1, uint32_t op2)
 {
     CPU_FloatU u1, u2;
+
     u1.l = op1;
     u2.l = op2;
     return float32_lt(u1.f, u2.f, &env->vec_status) ? 4 : 0;
@@ -3347,6 +3523,7 @@ static inline uint32_t efscmplt(uint32_t op1, uint32_t op2)
 static inline uint32_t efscmpgt(uint32_t op1, uint32_t op2)
 {
     CPU_FloatU u1, u2;
+
     u1.l = op1;
     u2.l = op2;
     return float32_le(u1.f, u2.f, &env->vec_status) ? 0 : 4;
@@ -3355,6 +3532,7 @@ static inline uint32_t efscmpgt(uint32_t op1, uint32_t op2)
 static inline uint32_t efscmpeq(uint32_t op1, uint32_t op2)
 {
     CPU_FloatU u1, u2;
+
     u1.l = op1;
     u2.l = op2;
     return float32_eq(u1.f, u2.f, &env->vec_status) ? 4 : 0;
@@ -3378,11 +3556,11 @@ static inline uint32_t efststeq(uint32_t op1, uint32_t op2)
     return efscmpeq(op1, op2);
 }
 
-#define HELPER_SINGLE_SPE_CMP(name)                                           \
-uint32_t helper_e##name (uint32_t op1, uint32_t op2)                          \
-{                                                                             \
-    return e##name(op1, op2) << 2;                                            \
-}
+#define HELPER_SINGLE_SPE_CMP(name)                     \
+    uint32_t helper_e##name(uint32_t op1, uint32_t op2) \
+    {                                                   \
+        return e##name(op1, op2) << 2;                  \
+    }
 /* efststlt */
 HELPER_SINGLE_SPE_CMP(fststlt);
 /* efststgt */
@@ -3401,11 +3579,11 @@ static inline uint32_t evcmp_merge(int t0, int t1)
     return (t0 << 3) | (t1 << 2) | ((t0 | t1) << 1) | (t0 & t1);
 }
 
-#define HELPER_VECTOR_SPE_CMP(name)                                           \
-uint32_t helper_ev##name (uint64_t op1, uint64_t op2)                         \
-{                                                                             \
-    return evcmp_merge(e##name(op1 >> 32, op2 >> 32), e##name(op1, op2));     \
-}
+#define HELPER_VECTOR_SPE_CMP(name)                                     \
+    uint32_t helper_ev##name(uint64_t op1, uint64_t op2)                \
+    {                                                                   \
+        return evcmp_merge(e##name(op1 >> 32, op2 >> 32), e##name(op1, op2)); \
+    }
 /* evfststlt */
 HELPER_VECTOR_SPE_CMP(fststlt);
 /* evfststgt */
@@ -3420,7 +3598,7 @@ HELPER_VECTOR_SPE_CMP(fscmpgt);
 HELPER_VECTOR_SPE_CMP(fscmpeq);
 
 /* Double-precision floating-point conversion */
-uint64_t helper_efdcfsi (uint32_t val)
+uint64_t helper_efdcfsi(uint32_t val)
 {
     CPU_DoubleU u;
 
@@ -3429,7 +3607,7 @@ uint64_t helper_efdcfsi (uint32_t val)
     return u.ll;
 }
 
-uint64_t helper_efdcfsid (uint64_t val)
+uint64_t helper_efdcfsid(uint64_t val)
 {
     CPU_DoubleU u;
 
@@ -3438,7 +3616,7 @@ uint64_t helper_efdcfsid (uint64_t val)
     return u.ll;
 }
 
-uint64_t helper_efdcfui (uint32_t val)
+uint64_t helper_efdcfui(uint32_t val)
 {
     CPU_DoubleU u;
 
@@ -3447,7 +3625,7 @@ uint64_t helper_efdcfui (uint32_t val)
     return u.ll;
 }
 
-uint64_t helper_efdcfuid (uint64_t val)
+uint64_t helper_efdcfuid(uint64_t val)
 {
     CPU_DoubleU u;
 
@@ -3456,7 +3634,7 @@ uint64_t helper_efdcfuid (uint64_t val)
     return u.ll;
 }
 
-uint32_t helper_efdctsi (uint64_t val)
+uint32_t helper_efdctsi(uint64_t val)
 {
     CPU_DoubleU u;
 
@@ -3469,7 +3647,7 @@ uint32_t helper_efdctsi (uint64_t val)
     return float64_to_int32(u.d, &env->vec_status);
 }
 
-uint32_t helper_efdctui (uint64_t val)
+uint32_t helper_efdctui(uint64_t val)
 {
     CPU_DoubleU u;
 
@@ -3482,7 +3660,7 @@ uint32_t helper_efdctui (uint64_t val)
     return float64_to_uint32(u.d, &env->vec_status);
 }
 
-uint32_t helper_efdctsiz (uint64_t val)
+uint32_t helper_efdctsiz(uint64_t val)
 {
     CPU_DoubleU u;
 
@@ -3495,7 +3673,7 @@ uint32_t helper_efdctsiz (uint64_t val)
     return float64_to_int32_round_to_zero(u.d, &env->vec_status);
 }
 
-uint64_t helper_efdctsidz (uint64_t val)
+uint64_t helper_efdctsidz(uint64_t val)
 {
     CPU_DoubleU u;
 
@@ -3508,7 +3686,7 @@ uint64_t helper_efdctsidz (uint64_t val)
     return float64_to_int64_round_to_zero(u.d, &env->vec_status);
 }
 
-uint32_t helper_efdctuiz (uint64_t val)
+uint32_t helper_efdctuiz(uint64_t val)
 {
     CPU_DoubleU u;
 
@@ -3521,7 +3699,7 @@ uint32_t helper_efdctuiz (uint64_t val)
     return float64_to_uint32_round_to_zero(u.d, &env->vec_status);
 }
 
-uint64_t helper_efdctuidz (uint64_t val)
+uint64_t helper_efdctuidz(uint64_t val)
 {
     CPU_DoubleU u;
 
@@ -3534,7 +3712,7 @@ uint64_t helper_efdctuidz (uint64_t val)
     return float64_to_uint64_round_to_zero(u.d, &env->vec_status);
 }
 
-uint64_t helper_efdcfsf (uint32_t val)
+uint64_t helper_efdcfsf(uint32_t val)
 {
     CPU_DoubleU u;
     float64 tmp;
@@ -3546,7 +3724,7 @@ uint64_t helper_efdcfsf (uint32_t val)
     return u.ll;
 }
 
-uint64_t helper_efdcfuf (uint32_t val)
+uint64_t helper_efdcfuf(uint32_t val)
 {
     CPU_DoubleU u;
     float64 tmp;
@@ -3558,7 +3736,7 @@ uint64_t helper_efdcfuf (uint32_t val)
     return u.ll;
 }
 
-uint32_t helper_efdctsf (uint64_t val)
+uint32_t helper_efdctsf(uint64_t val)
 {
     CPU_DoubleU u;
     float64 tmp;
@@ -3574,7 +3752,7 @@ uint32_t helper_efdctsf (uint64_t val)
     return float64_to_int32(u.d, &env->vec_status);
 }
 
-uint32_t helper_efdctuf (uint64_t val)
+uint32_t helper_efdctuf(uint64_t val)
 {
     CPU_DoubleU u;
     float64 tmp;
@@ -3590,7 +3768,7 @@ uint32_t helper_efdctuf (uint64_t val)
     return float64_to_uint32(u.d, &env->vec_status);
 }
 
-uint32_t helper_efscfd (uint64_t val)
+uint32_t helper_efscfd(uint64_t val)
 {
     CPU_DoubleU u1;
     CPU_FloatU u2;
@@ -3601,7 +3779,7 @@ uint32_t helper_efscfd (uint64_t val)
     return u2.l;
 }
 
-uint64_t helper_efdcfs (uint32_t val)
+uint64_t helper_efdcfs(uint32_t val)
 {
     CPU_DoubleU u2;
     CPU_FloatU u1;
@@ -3613,36 +3791,40 @@ uint64_t helper_efdcfs (uint32_t val)
 }
 
 /* Double precision fixed-point arithmetic */
-uint64_t helper_efdadd (uint64_t op1, uint64_t op2)
+uint64_t helper_efdadd(uint64_t op1, uint64_t op2)
 {
     CPU_DoubleU u1, u2;
+
     u1.ll = op1;
     u2.ll = op2;
     u1.d = float64_add(u1.d, u2.d, &env->vec_status);
     return u1.ll;
 }
 
-uint64_t helper_efdsub (uint64_t op1, uint64_t op2)
+uint64_t helper_efdsub(uint64_t op1, uint64_t op2)
 {
     CPU_DoubleU u1, u2;
+
     u1.ll = op1;
     u2.ll = op2;
     u1.d = float64_sub(u1.d, u2.d, &env->vec_status);
     return u1.ll;
 }
 
-uint64_t helper_efdmul (uint64_t op1, uint64_t op2)
+uint64_t helper_efdmul(uint64_t op1, uint64_t op2)
 {
     CPU_DoubleU u1, u2;
+
     u1.ll = op1;
     u2.ll = op2;
     u1.d = float64_mul(u1.d, u2.d, &env->vec_status);
     return u1.ll;
 }
 
-uint64_t helper_efddiv (uint64_t op1, uint64_t op2)
+uint64_t helper_efddiv(uint64_t op1, uint64_t op2)
 {
     CPU_DoubleU u1, u2;
+
     u1.ll = op1;
     u2.ll = op2;
     u1.d = float64_div(u1.d, u2.d, &env->vec_status);
@@ -3650,43 +3832,46 @@ uint64_t helper_efddiv (uint64_t op1, uint64_t op2)
 }
 
 /* Double precision floating point helpers */
-uint32_t helper_efdtstlt (uint64_t op1, uint64_t op2)
+uint32_t helper_efdtstlt(uint64_t op1, uint64_t op2)
 {
     CPU_DoubleU u1, u2;
+
     u1.ll = op1;
     u2.ll = op2;
     return float64_lt(u1.d, u2.d, &env->vec_status) ? 4 : 0;
 }
 
-uint32_t helper_efdtstgt (uint64_t op1, uint64_t op2)
+uint32_t helper_efdtstgt(uint64_t op1, uint64_t op2)
 {
     CPU_DoubleU u1, u2;
+
     u1.ll = op1;
     u2.ll = op2;
     return float64_le(u1.d, u2.d, &env->vec_status) ? 0 : 4;
 }
 
-uint32_t helper_efdtsteq (uint64_t op1, uint64_t op2)
+uint32_t helper_efdtsteq(uint64_t op1, uint64_t op2)
 {
     CPU_DoubleU u1, u2;
+
     u1.ll = op1;
     u2.ll = op2;
     return float64_eq_quiet(u1.d, u2.d, &env->vec_status) ? 4 : 0;
 }
 
-uint32_t helper_efdcmplt (uint64_t op1, uint64_t op2)
+uint32_t helper_efdcmplt(uint64_t op1, uint64_t op2)
 {
     /* XXX: TODO: test special values (NaN, infinites, ...) */
     return helper_efdtstlt(op1, op2);
 }
 
-uint32_t helper_efdcmpgt (uint64_t op1, uint64_t op2)
+uint32_t helper_efdcmpgt(uint64_t op1, uint64_t op2)
 {
     /* XXX: TODO: test special values (NaN, infinites, ...) */
     return helper_efdtstgt(op1, op2);
 }
 
-uint32_t helper_efdcmpeq (uint64_t op1, uint64_t op2)
+uint32_t helper_efdcmpeq(uint64_t op1, uint64_t op2)
 {
     /* XXX: TODO: test special values (NaN, infinites, ...) */
     return helper_efdtsteq(op1, op2);
@@ -3694,7 +3879,7 @@ uint32_t helper_efdcmpeq (uint64_t op1, uint64_t op2)
 
 /*****************************************************************************/
 /* Softmmu support */
-#if !defined (CONFIG_USER_ONLY)
+#if !defined(CONFIG_USER_ONLY)
 
 #define MMUSUFFIX _mmu
 
@@ -3740,30 +3925,31 @@ void tlb_fill(CPUPPCState *env1, target_ulong addr, int is_write, int mmu_idx,
 }
 
 /* Segment registers load and store */
-target_ulong helper_load_sr (target_ulong sr_num)
+target_ulong helper_load_sr(target_ulong sr_num)
 {
 #if defined(TARGET_PPC64)
-    if (env->mmu_model & POWERPC_MMU_64)
+    if (env->mmu_model & POWERPC_MMU_64) {
         return ppc_load_sr(env, sr_num);
+    }
 #endif
     return env->sr[sr_num];
 }
 
-void helper_store_sr (target_ulong sr_num, target_ulong val)
+void helper_store_sr(target_ulong sr_num, target_ulong val)
 {
     ppc_store_sr(env, sr_num, val);
 }
 
 /* SLB management */
 #if defined(TARGET_PPC64)
-void helper_store_slb (target_ulong rb, target_ulong rs)
+void helper_store_slb(target_ulong rb, target_ulong rs)
 {
     if (ppc_store_slb(env, rb, rs) < 0) {
         helper_raise_exception_err(POWERPC_EXCP_PROGRAM, POWERPC_EXCP_INVAL);
     }
 }
 
-target_ulong helper_load_slb_esid (target_ulong rb)
+target_ulong helper_load_slb_esid(target_ulong rb)
 {
     target_ulong rt;
 
@@ -3773,7 +3959,7 @@ target_ulong helper_load_slb_esid (target_ulong rb)
     return rt;
 }
 
-target_ulong helper_load_slb_vsid (target_ulong rb)
+target_ulong helper_load_slb_vsid(target_ulong rb)
 {
     target_ulong rt;
 
@@ -3783,12 +3969,12 @@ target_ulong helper_load_slb_vsid (target_ulong rb)
     return rt;
 }
 
-void helper_slbia (void)
+void helper_slbia(void)
 {
     ppc_slb_invalidate_all(env);
 }
 
-void helper_slbie (target_ulong addr)
+void helper_slbie(target_ulong addr)
 {
     ppc_slb_invalidate_one(env, addr);
 }
@@ -3796,19 +3982,19 @@ void helper_slbie (target_ulong addr)
 #endif /* defined(TARGET_PPC64) */
 
 /* TLB management */
-void helper_tlbia (void)
+void helper_tlbia(void)
 {
     ppc_tlb_invalidate_all(env);
 }
 
-void helper_tlbie (target_ulong addr)
+void helper_tlbie(target_ulong addr)
 {
     ppc_tlb_invalidate_one(env, addr);
 }
 
 /* Software driven TLBs management */
 /* PowerPC 602/603 software TLB load instructions helpers */
-static void do_6xx_tlb (target_ulong new_EPN, int is_code)
+static void do_6xx_tlb(target_ulong new_EPN, int is_code)
 {
     target_ulong RPN, CMP, EPN;
     int way;
@@ -3831,18 +4017,18 @@ static void do_6xx_tlb (target_ulong new_EPN, int is_code)
                      way, is_code, CMP, RPN);
 }
 
-void helper_6xx_tlbd (target_ulong EPN)
+void helper_6xx_tlbd(target_ulong EPN)
 {
     do_6xx_tlb(EPN, 0);
 }
 
-void helper_6xx_tlbi (target_ulong EPN)
+void helper_6xx_tlbi(target_ulong EPN)
 {
     do_6xx_tlb(EPN, 1);
 }
 
 /* PowerPC 74xx software TLB load instructions helpers */
-static void do_74xx_tlb (target_ulong new_EPN, int is_code)
+static void do_74xx_tlb(target_ulong new_EPN, int is_code)
 {
     target_ulong RPN, CMP, EPN;
     int way;
@@ -3860,12 +4046,12 @@ static void do_74xx_tlb (target_ulong new_EPN, int is_code)
                      way, is_code, CMP, RPN);
 }
 
-void helper_74xx_tlbd (target_ulong EPN)
+void helper_74xx_tlbd(target_ulong EPN)
 {
     do_74xx_tlb(EPN, 0);
 }
 
-void helper_74xx_tlbi (target_ulong EPN)
+void helper_74xx_tlbi(target_ulong EPN)
 {
     do_74xx_tlb(EPN, 1);
 }
@@ -3913,7 +4099,7 @@ static inline int booke_page_size_to_tlb(target_ulong page_size)
     case 0x40000000UL:
         size = 0xA;
         break;
-#if defined (TARGET_PPC64)
+#if defined(TARGET_PPC64)
     case 0x000100000000ULL:
         size = 0xB;
         break;
@@ -3954,7 +4140,7 @@ static inline int booke_page_size_to_tlb(target_ulong page_size)
 #define PPC4XX_TLBLO_ATTR_MASK      0x000000FF
 #define PPC4XX_TLBLO_RPN_MASK       0xFFFFFC00
 
-target_ulong helper_4xx_tlbre_hi (target_ulong entry)
+target_ulong helper_4xx_tlbre_hi(target_ulong entry)
 {
     ppcemb_tlb_t *tlb;
     target_ulong ret;
@@ -3975,7 +4161,7 @@ target_ulong helper_4xx_tlbre_hi (target_ulong entry)
     return ret;
 }
 
-target_ulong helper_4xx_tlbre_lo (target_ulong entry)
+target_ulong helper_4xx_tlbre_lo(target_ulong entry)
 {
     ppcemb_tlb_t *tlb;
     target_ulong ret;
@@ -3992,7 +4178,7 @@ target_ulong helper_4xx_tlbre_lo (target_ulong entry)
     return ret;
 }
 
-void helper_4xx_tlbwe_hi (target_ulong entry, target_ulong val)
+void helper_4xx_tlbwe_hi(target_ulong entry, target_ulong val)
 {
     ppcemb_tlb_t *tlb;
     target_ulong page, end;
@@ -4051,7 +4237,7 @@ void helper_4xx_tlbwe_hi (target_ulong entry, target_ulong val)
     }
 }
 
-void helper_4xx_tlbwe_lo (target_ulong entry, target_ulong val)
+void helper_4xx_tlbwe_lo(target_ulong entry, target_ulong val)
 {
     ppcemb_tlb_t *tlb;
 
@@ -4077,13 +4263,13 @@ void helper_4xx_tlbwe_lo (target_ulong entry, target_ulong val)
               tlb->prot & PAGE_VALID ? 'v' : '-', (int)tlb->PID);
 }
 
-target_ulong helper_4xx_tlbsx (target_ulong address)
+target_ulong helper_4xx_tlbsx(target_ulong address)
 {
     return ppcemb_tlb_search(env, address, env->spr[SPR_40x_PID]);
 }
 
 /* PowerPC 440 TLB management */
-void helper_440_tlbwe (uint32_t word, target_ulong entry, target_ulong value)
+void helper_440_tlbwe(uint32_t word, target_ulong entry, target_ulong value)
 {
     ppcemb_tlb_t *tlb;
     target_ulong EPN, RPN, size;
@@ -4099,12 +4285,14 @@ void helper_440_tlbwe (uint32_t word, target_ulong entry, target_ulong value)
         /* Just here to please gcc */
     case 0:
         EPN = value & 0xFFFFFC00;
-        if ((tlb->prot & PAGE_VALID) && EPN != tlb->EPN)
+        if ((tlb->prot & PAGE_VALID) && EPN != tlb->EPN) {
             do_flush_tlbs = 1;
+        }
         tlb->EPN = EPN;
         size = booke_tlb_to_page_size((value >> 4) & 0xF);
-        if ((tlb->prot & PAGE_VALID) && tlb->size < size)
+        if ((tlb->prot & PAGE_VALID) && tlb->size < size) {
             do_flush_tlbs = 1;
+        }
         tlb->size = size;
         tlb->attr &= ~0x1;
         tlb->attr |= (value >> 8) & 1;
@@ -4117,35 +4305,43 @@ void helper_440_tlbwe (uint32_t word, target_ulong entry, target_ulong value)
             }
         }
         tlb->PID = env->spr[SPR_440_MMUCR] & 0x000000FF;
-        if (do_flush_tlbs)
+        if (do_flush_tlbs) {
             tlb_flush(env, 1);
+        }
         break;
     case 1:
         RPN = value & 0xFFFFFC0F;
-        if ((tlb->prot & PAGE_VALID) && tlb->RPN != RPN)
+        if ((tlb->prot & PAGE_VALID) && tlb->RPN != RPN) {
             tlb_flush(env, 1);
+        }
         tlb->RPN = RPN;
         break;
     case 2:
         tlb->attr = (tlb->attr & 0x1) | (value & 0x0000FF00);
         tlb->prot = tlb->prot & PAGE_VALID;
-        if (value & 0x1)
+        if (value & 0x1) {
             tlb->prot |= PAGE_READ << 4;
-        if (value & 0x2)
+        }
+        if (value & 0x2) {
             tlb->prot |= PAGE_WRITE << 4;
-        if (value & 0x4)
+        }
+        if (value & 0x4) {
             tlb->prot |= PAGE_EXEC << 4;
-        if (value & 0x8)
+        }
+        if (value & 0x8) {
             tlb->prot |= PAGE_READ;
-        if (value & 0x10)
+        }
+        if (value & 0x10) {
             tlb->prot |= PAGE_WRITE;
-        if (value & 0x20)
+        }
+        if (value & 0x20) {
             tlb->prot |= PAGE_EXEC;
+        }
         break;
     }
 }
 
-target_ulong helper_440_tlbre (uint32_t word, target_ulong entry)
+target_ulong helper_440_tlbre(uint32_t word, target_ulong entry)
 {
     ppcemb_tlb_t *tlb;
     target_ulong ret;
@@ -4159,13 +4355,16 @@ target_ulong helper_440_tlbre (uint32_t word, target_ulong entry)
     case 0:
         ret = tlb->EPN;
         size = booke_page_size_to_tlb(tlb->size);
-        if (size < 0 || size > 0xF)
+        if (size < 0 || size > 0xF) {
             size = 1;
+        }
         ret |= size << 4;
-        if (tlb->attr & 0x1)
+        if (tlb->attr & 0x1) {
             ret |= 0x100;
-        if (tlb->prot & PAGE_VALID)
+        }
+        if (tlb->prot & PAGE_VALID) {
             ret |= 0x200;
+        }
         env->spr[SPR_440_MMUCR] &= ~0x000000FF;
         env->spr[SPR_440_MMUCR] |= tlb->PID;
         break;
@@ -4174,24 +4373,30 @@ target_ulong helper_440_tlbre (uint32_t word, target_ulong entry)
         break;
     case 2:
         ret = tlb->attr & ~0x1;
-        if (tlb->prot & (PAGE_READ << 4))
+        if (tlb->prot & (PAGE_READ << 4)) {
             ret |= 0x1;
-        if (tlb->prot & (PAGE_WRITE << 4))
+        }
+        if (tlb->prot & (PAGE_WRITE << 4)) {
             ret |= 0x2;
-        if (tlb->prot & (PAGE_EXEC << 4))
+        }
+        if (tlb->prot & (PAGE_EXEC << 4)) {
             ret |= 0x4;
-        if (tlb->prot & PAGE_READ)
+        }
+        if (tlb->prot & PAGE_READ) {
             ret |= 0x8;
-        if (tlb->prot & PAGE_WRITE)
+        }
+        if (tlb->prot & PAGE_WRITE) {
             ret |= 0x10;
-        if (tlb->prot & PAGE_EXEC)
+        }
+        if (tlb->prot & PAGE_EXEC) {
             ret |= 0x20;
+        }
         break;
     }
     return ret;
 }
 
-target_ulong helper_440_tlbsx (target_ulong address)
+target_ulong helper_440_tlbsx(target_ulong address)
 {
     return ppcemb_tlb_search(env, address, env->spr[SPR_440_MMUCR] & 0xFF);
 }
@@ -4247,7 +4452,7 @@ void helper_booke206_tlbwe(void)
     }
 
     if (((env->spr[SPR_BOOKE_MAS0] & MAS0_ATSEL) == MAS0_ATSEL_LRAT) &&
-         !msr_gs) {
+        !msr_gs) {
         /* XXX we don't support direct LRAT setting yet */
         fprintf(stderr, "cpu: don't support LRAT setting yet\n");
         return;
@@ -4278,7 +4483,7 @@ void helper_booke206_tlbwe(void)
         cpu_abort(env, "missing HV implementation\n");
     }
     tlb->mas7_3 = ((uint64_t)env->spr[SPR_BOOKE_MAS7] << 32) |
-                  env->spr[SPR_BOOKE_MAS3];
+        env->spr[SPR_BOOKE_MAS3];
     tlb->mas1 = env->spr[SPR_BOOKE_MAS1];
 
     /* MAV 1.0 only */
@@ -4376,7 +4581,7 @@ void helper_booke206_tlbsx(target_ulong address)
     }
 
     env->spr[SPR_BOOKE_MAS1] |= (env->spr[SPR_BOOKE_MAS6] >> 16)
-                                << MAS1_TID_SHIFT;
+        << MAS1_TID_SHIFT;
 
     /* next victim logic */
     env->spr[SPR_BOOKE_MAS0] |= env->last_way << MAS0_ESEL_SHIFT;
commit affe5189907f397514cdd4ee7446595c1246a0e9
Author: Alexander Graf <agraf at suse.de>
Date:   Sun Jun 24 00:05:36 2012 +0200

    TCG: Fix compile breakage in tcg_dump_ops
    
    Commit eeacee4d865 changed the syntax of tcg_dump_ops, but didn't convert
    all users (notably missing the ppc ones) to it. Fix them to the new syntax.
    
    Signed-off-by: Alexander Graf <agraf at suse.de>
    Signed-off-by: malc <av1474 at comtv.ru>

diff --git a/tcg/ppc/tcg-target.c b/tcg/ppc/tcg-target.c
index d265697..0cff181 100644
--- a/tcg/ppc/tcg-target.c
+++ b/tcg/ppc/tcg-target.c
@@ -1865,7 +1865,7 @@ static void tcg_out_op(TCGContext *s, TCGOpcode opc, const TCGArg *args,
         break;
 
     default:
-        tcg_dump_ops (s, stderr);
+        tcg_dump_ops (s);
         tcg_abort ();
     }
 }
diff --git a/tcg/ppc64/tcg-target.c b/tcg/ppc64/tcg-target.c
index c800574..27a0ae8 100644
--- a/tcg/ppc64/tcg-target.c
+++ b/tcg/ppc64/tcg-target.c
@@ -1613,7 +1613,7 @@ static void tcg_out_op (TCGContext *s, TCGOpcode opc, const TCGArg *args,
         break;
 
     default:
-        tcg_dump_ops (s, stderr);
+        tcg_dump_ops (s);
         tcg_abort ();
     }
 }
commit 6a69226f22011673dbce99d5e32cfeaad5bff426
Author: Stefan Weil <sw at weilnetz.de>
Date:   Wed Jun 20 18:07:24 2012 +0200

    tci: Support INDEX_op_bswap64_i64
    
    Running the Windows 7 (64 bit) boot process needs INDEX_op_bswap64_i64.
    It was already implemented, but untested. Remove the TODO() statement.
    
    Signed-off-by: Stefan Weil <sw at weilnetz.de>
    Signed-off-by: Stefan Hajnoczi <stefanha at linux.vnet.ibm.com>

diff --git a/tci.c b/tci.c
index a412a4e..c79350d 100644
--- a/tci.c
+++ b/tci.c
@@ -1014,7 +1014,6 @@ tcg_target_ulong tcg_qemu_tb_exec(CPUArchState *cpustate, uint8_t *tb_ptr)
 #endif
 #if TCG_TARGET_HAS_bswap64_i64
         case INDEX_op_bswap64_i64:
-            TODO();
             t0 = *tb_ptr++;
             t1 = tci_read_r64(&tb_ptr);
             tci_write_reg64(t0, bswap64(t1));
commit 09faecf257387d88c457ca255d5c6a003a96623f
Author: Stefan Weil <sw at weilnetz.de>
Date:   Wed Jun 20 06:05:51 2012 +0200

    target-i386: Use QEMU instead of Qemu
    
    This new 'QEmu' was recently added.
    Replace it by the official all upper case 'QEMU'.
    
    Signed-off-by: Stefan Weil <sw at weilnetz.de>
    Signed-off-by: Stefan Hajnoczi <stefanha at linux.vnet.ibm.com>

diff --git a/target-i386/cpu.c b/target-i386/cpu.c
index fdd95be..5521709 100644
--- a/target-i386/cpu.c
+++ b/target-i386/cpu.c
@@ -1303,7 +1303,7 @@ void x86_cpudef_setup(void)
         builtin_x86_defs[i].flags = 1;
 
         /* Look for specific "cpudef" models that */
-        /* have the QEmu version in .model_id */
+        /* have the QEMU version in .model_id */
         for (j = 0; j < ARRAY_SIZE(model_with_versions); j++) {
             if (strcmp(model_with_versions[j], builtin_x86_defs[i].name) == 0) {
                 pstrcpy(builtin_x86_defs[i].model_id, sizeof(builtin_x86_defs[i].model_id), "QEMU Virtual CPU version ");
commit 30fd45adb2e54c7369505ac840907dc33a1078fa
Author: Peter Maydell <peter.maydell at linaro.org>
Date:   Tue Jun 19 15:55:38 2012 +0100

    Makefile.hw: avoid overly large 'make clean' rm command
    
    Avoid 'make clean' producing an 'rm' command which has a lot
    of duplicate 'hw//*.o' arguments, by using $(sort $(dir ..))
    rather than $(dir $(sort ..)) so Make's sort function will
    remove the duplicates for us. We can also remove the double
    '//' safely because $(dir ..) is guaranteed to return a string
    ending in '/'.
    
    Signed-off-by: Peter Maydell <peter.maydell at linaro.org>
    Signed-off-by: Stefan Hajnoczi <stefanha at linux.vnet.ibm.com>

diff --git a/Makefile.hw b/Makefile.hw
index 2bcbaff..28fe100 100644
--- a/Makefile.hw
+++ b/Makefile.hw
@@ -19,8 +19,8 @@ all: $(hw-obj-y)
 	@true
 
 clean:
-	rm -f $(addsuffix /*.o, $(dir $(sort $(hw-obj-y))))
-	rm -f $(addsuffix /*.d, $(dir $(sort $(hw-obj-y))))
+	rm -f $(addsuffix *.o, $(sort $(dir $(hw-obj-y))))
+	rm -f $(addsuffix *.d, $(sort $(dir $(hw-obj-y))))
 
 # Include automatically generated dependency files
 -include $(patsubst %.o, %.d, $(hw-obj-y))
commit 9e56edcf8dd1d4bc7ba2b1efb3641f36c0fad8ba
Author: Gerd Hoffmann <kraxel at redhat.com>
Date:   Mon Jun 11 10:42:53 2012 +0200

    vga: raise default vgamem size
    
    Old size: 8 MB (traditional upstream qemu value).
    New size: 16 MB (traditional qemu-kvm value).
    
    Also adds compat properties so old machine types
    keep the old default values.
    
    Signed-off-by: Gerd Hoffmann <kraxel at redhat.com>

diff --git a/hw/pc_piix.c b/hw/pc_piix.c
index 2ed9f1a..0c0096f 100644
--- a/hw/pc_piix.c
+++ b/hw/pc_piix.c
@@ -358,14 +358,38 @@ static QEMUMachine pc_machine_v1_2 = {
     .is_default = 1,
 };
 
+#define PC_COMPAT_1_1 \
+        {\
+            .driver   = "VGA",\
+            .property = "vgamem_mb",\
+            .value    = stringify(8),\
+        },{\
+            .driver   = "vmware-svga",\
+            .property = "vgamem_mb",\
+            .value    = stringify(8),\
+        },{\
+            .driver   = "qxl-vga",\
+            .property = "vgamem_mb",\
+            .value    = stringify(8),\
+        },{\
+            .driver   = "qxl",\
+            .property = "vgamem_mb",\
+            .value    = stringify(8),\
+        }
+
 static QEMUMachine pc_machine_v1_1 = {
     .name = "pc-1.1",
     .desc = "Standard PC",
     .init = pc_init_pci,
     .max_cpus = 255,
+    .compat_props = (GlobalProperty[]) {
+        PC_COMPAT_1_1,
+        { /* end of list */ }
+    },
 };
 
 #define PC_COMPAT_1_0 \
+        PC_COMPAT_1_1,\
         {\
             .driver   = "pc-sysfw",\
             .property = "rom_only",\
diff --git a/hw/qxl.c b/hw/qxl.c
index 62eed05..c2dd3b4 100644
--- a/hw/qxl.c
+++ b/hw/qxl.c
@@ -2067,7 +2067,7 @@ static Property qxl_properties[] = {
         DEFINE_PROP_UINT32("ram_size_mb",  PCIQXLDevice, ram_size_mb, -1),
         DEFINE_PROP_UINT32("vram_size_mb", PCIQXLDevice, vram32_size_mb, -1),
         DEFINE_PROP_UINT32("vram64_size_mb", PCIQXLDevice, vram_size_mb, -1),
-        DEFINE_PROP_UINT32("vgamem_mb", PCIQXLDevice, vgamem_size_mb, 8),
+        DEFINE_PROP_UINT32("vgamem_mb", PCIQXLDevice, vgamem_size_mb, 16),
         DEFINE_PROP_END_OF_LIST(),
 };
 
diff --git a/hw/vga-pci.c b/hw/vga-pci.c
index 0848126..37dc019 100644
--- a/hw/vga-pci.c
+++ b/hw/vga-pci.c
@@ -76,7 +76,7 @@ DeviceState *pci_vga_init(PCIBus *bus)
 }
 
 static Property vga_pci_properties[] = {
-    DEFINE_PROP_UINT32("vgamem_mb", PCIVGAState, vga.vram_size_mb, 8),
+    DEFINE_PROP_UINT32("vgamem_mb", PCIVGAState, vga.vram_size_mb, 16),
     DEFINE_PROP_END_OF_LIST(),
 };
 
diff --git a/hw/vmware_vga.c b/hw/vmware_vga.c
index f8eb46d..476dc89 100644
--- a/hw/vmware_vga.c
+++ b/hw/vmware_vga.c
@@ -1201,7 +1201,7 @@ static int pci_vmsvga_initfn(PCIDevice *dev)
 
 static Property vga_vmware_properties[] = {
     DEFINE_PROP_UINT32("vgamem_mb", struct pci_vmsvga_state_s,
-                       chip.vga.vram_size_mb, 8),
+                       chip.vga.vram_size_mb, 16),
     DEFINE_PROP_END_OF_LIST(),
 };
 
commit f1dacf1cedbf0f46c13139f3961ef8a976dc71e3
Author: Gerd Hoffmann <kraxel at redhat.com>
Date:   Mon Jun 11 10:38:22 2012 +0200

    add pc-1.2

diff --git a/hw/pc_piix.c b/hw/pc_piix.c
index eae258c..2ed9f1a 100644
--- a/hw/pc_piix.c
+++ b/hw/pc_piix.c
@@ -349,8 +349,8 @@ static void pc_xen_hvm_init(ram_addr_t ram_size,
 }
 #endif
 
-static QEMUMachine pc_machine_v1_1 = {
-    .name = "pc-1.1",
+static QEMUMachine pc_machine_v1_2 = {
+    .name = "pc-1.2",
     .alias = "pc",
     .desc = "Standard PC",
     .init = pc_init_pci,
@@ -358,6 +358,13 @@ static QEMUMachine pc_machine_v1_1 = {
     .is_default = 1,
 };
 
+static QEMUMachine pc_machine_v1_1 = {
+    .name = "pc-1.1",
+    .desc = "Standard PC",
+    .init = pc_init_pci,
+    .max_cpus = 255,
+};
+
 #define PC_COMPAT_1_0 \
         {\
             .driver   = "pc-sysfw",\
@@ -612,6 +619,7 @@ static QEMUMachine xenfv_machine = {
 
 static void pc_machine_init(void)
 {
+    qemu_register_machine(&pc_machine_v1_2);
     qemu_register_machine(&pc_machine_v1_1);
     qemu_register_machine(&pc_machine_v1_0);
     qemu_register_machine(&pc_machine_v0_15);
commit 13d1fd44c46629aad672f192abbf02238c6cbf36
Author: Alon Levy <alevy at redhat.com>
Date:   Sun Jun 10 18:05:06 2012 +0300

    qxl: add vgamem_size_mb and vgamem_size
    
    In preperation for supporting a larger framebuffer for multiple monitors
    on a single card, add a property to qxl vgamem_size_mb, and corresponding
    byte sized vgamem_size, and use instead of VGA_RAM_SIZE.
    
    [ kraxel: simplify property handling, add sanity checks ]
    [ kraxel: fix mode copying ]
    
    Signed-off-by: Alon Levy <alevy at redhat.com>
    Signed-off-by: Gerd Hoffmann <kraxel at redhat.com>

diff --git a/hw/qxl.c b/hw/qxl.c
index c40cf55..62eed05 100644
--- a/hw/qxl.c
+++ b/hw/qxl.c
@@ -27,8 +27,6 @@
 
 #include "qxl.h"
 
-#define VGA_RAM_SIZE (8192 * 1024)
-
 /*
  * NOTE: SPICE_RING_PROD_ITEM accesses memory on the pci bar and as
  * such can be changed by the guest, so to avoid a guest trigerrable
@@ -116,20 +114,16 @@ static QXLMode qxl_modes[] = {
     QXL_MODE_EX(1600, 1200),
     QXL_MODE_EX(1680, 1050),
     QXL_MODE_EX(1920, 1080),
-#if VGA_RAM_SIZE >= (16 * 1024 * 1024)
     /* these modes need more than 8 MB video memory */
     QXL_MODE_EX(1920, 1200),
     QXL_MODE_EX(1920, 1440),
     QXL_MODE_EX(2048, 1536),
     QXL_MODE_EX(2560, 1440),
     QXL_MODE_EX(2560, 1600),
-#endif
-#if VGA_RAM_SIZE >= (32 * 1024 * 1024)
     /* these modes need more than 16 MB video memory */
     QXL_MODE_EX(2560, 2048),
     QXL_MODE_EX(2800, 2100),
     QXL_MODE_EX(3200, 2400),
-#endif
 };
 
 static PCIQXLDevice *qxl0;
@@ -286,6 +280,7 @@ static inline uint32_t msb_mask(uint32_t val)
 static ram_addr_t qxl_rom_size(void)
 {
     uint32_t rom_size = sizeof(QXLRom) + sizeof(QXLModes) + sizeof(qxl_modes);
+
     rom_size = MAX(rom_size, TARGET_PAGE_SIZE);
     rom_size = msb_mask(rom_size * 2 - 1);
     return rom_size;
@@ -298,8 +293,8 @@ static void init_qxl_rom(PCIQXLDevice *d)
     uint32_t ram_header_size;
     uint32_t surface0_area_size;
     uint32_t num_pages;
-    uint32_t fb, maxfb = 0;
-    int i;
+    uint32_t fb;
+    int i, n;
 
     memset(rom, 0, d->rom_size);
 
@@ -314,26 +309,25 @@ static void init_qxl_rom(PCIQXLDevice *d)
     rom->slots_end     = NUM_MEMSLOTS - 1;
     rom->n_surfaces    = cpu_to_le32(NUM_SURFACES);
 
-    modes->n_modes     = cpu_to_le32(ARRAY_SIZE(qxl_modes));
-    for (i = 0; i < modes->n_modes; i++) {
+    for (i = 0, n = 0; i < ARRAY_SIZE(qxl_modes); i++) {
         fb = qxl_modes[i].y_res * qxl_modes[i].stride;
-        if (maxfb < fb) {
-            maxfb = fb;
+        if (fb > d->vgamem_size) {
+            continue;
         }
-        modes->modes[i].id          = cpu_to_le32(i);
-        modes->modes[i].x_res       = cpu_to_le32(qxl_modes[i].x_res);
-        modes->modes[i].y_res       = cpu_to_le32(qxl_modes[i].y_res);
-        modes->modes[i].bits        = cpu_to_le32(qxl_modes[i].bits);
-        modes->modes[i].stride      = cpu_to_le32(qxl_modes[i].stride);
-        modes->modes[i].x_mili      = cpu_to_le32(qxl_modes[i].x_mili);
-        modes->modes[i].y_mili      = cpu_to_le32(qxl_modes[i].y_mili);
-        modes->modes[i].orientation = cpu_to_le32(qxl_modes[i].orientation);
-    }
-    if (maxfb < VGA_RAM_SIZE && d->id == 0)
-        maxfb = VGA_RAM_SIZE;
+        modes->modes[n].id          = cpu_to_le32(i);
+        modes->modes[n].x_res       = cpu_to_le32(qxl_modes[i].x_res);
+        modes->modes[n].y_res       = cpu_to_le32(qxl_modes[i].y_res);
+        modes->modes[n].bits        = cpu_to_le32(qxl_modes[i].bits);
+        modes->modes[n].stride      = cpu_to_le32(qxl_modes[i].stride);
+        modes->modes[n].x_mili      = cpu_to_le32(qxl_modes[i].x_mili);
+        modes->modes[n].y_mili      = cpu_to_le32(qxl_modes[i].y_mili);
+        modes->modes[n].orientation = cpu_to_le32(qxl_modes[i].orientation);
+        n++;
+    }
+    modes->n_modes     = cpu_to_le32(n);
 
     ram_header_size    = ALIGN(sizeof(QXLRam), 4096);
-    surface0_area_size = ALIGN(maxfb, 4096);
+    surface0_area_size = ALIGN(d->vgamem_size, 4096);
     num_pages          = d->vga.vram_size;
     num_pages         -= ram_header_size;
     num_pages         -= surface0_area_size;
@@ -1205,6 +1199,16 @@ static void qxl_create_guest_primary(PCIQXLDevice *qxl, int loadvm,
 {
     QXLDevSurfaceCreate surface;
     QXLSurfaceCreate *sc = &qxl->guest_primary.surface;
+    int size;
+    int requested_height = le32_to_cpu(sc->height);
+    int requested_stride = le32_to_cpu(sc->stride);
+
+    size = abs(requested_stride) * requested_height;
+    if (size > qxl->vgamem_size) {
+        qxl_set_guest_bug(qxl, "%s: requested primary larger then framebuffer"
+                               " size", __func__);
+        return;
+    }
 
     if (qxl->mode == QXL_MODE_NATIVE) {
         qxl_set_guest_bug(qxl, "%s: nop since already in QXL_MODE_NATIVE",
@@ -1714,14 +1718,20 @@ static DisplayChangeListener display_listener = {
     .dpy_refresh = display_refresh,
 };
 
-static void qxl_init_ramsize(PCIQXLDevice *qxl, uint32_t ram_min_mb)
+static void qxl_init_ramsize(PCIQXLDevice *qxl)
 {
-    /* vga ram (bar 0) */
+    /* vga mode framebuffer / primary surface (bar 0, first part) */
+    if (qxl->vgamem_size_mb < 8) {
+        qxl->vgamem_size_mb = 8;
+    }
+    qxl->vgamem_size = qxl->vgamem_size_mb * 1024 * 1024;
+
+    /* vga ram (bar 0, total) */
     if (qxl->ram_size_mb != -1) {
         qxl->vga.vram_size = qxl->ram_size_mb * 1024 * 1024;
     }
-    if (qxl->vga.vram_size < ram_min_mb * 1024 * 1024) {
-        qxl->vga.vram_size = ram_min_mb * 1024 * 1024;
+    if (qxl->vga.vram_size < qxl->vgamem_size * 2) {
+        qxl->vga.vram_size = qxl->vgamem_size * 2;
     }
 
     /* vram32 (surfaces, 32bit, bar 1) */
@@ -1744,6 +1754,7 @@ static void qxl_init_ramsize(PCIQXLDevice *qxl, uint32_t ram_min_mb)
         qxl->vram32_size = 4096;
         qxl->vram_size = 4096;
     }
+    qxl->vgamem_size = msb_mask(qxl->vgamem_size * 2 - 1);
     qxl->vga.vram_size = msb_mask(qxl->vga.vram_size * 2 - 1);
     qxl->vram32_size = msb_mask(qxl->vram32_size * 2 - 1);
     qxl->vram_size = msb_mask(qxl->vram_size * 2 - 1);
@@ -1855,7 +1866,7 @@ static int qxl_init_primary(PCIDevice *dev)
     PortioList *qxl_vga_port_list = g_new(PortioList, 1);
 
     qxl->id = 0;
-    qxl_init_ramsize(qxl, 32);
+    qxl_init_ramsize(qxl);
     vga->vram_size_mb = qxl->vga.vram_size >> 20;
     vga_common_init(vga);
     vga_init(vga, pci_address_space(dev), pci_address_space_io(dev), false);
@@ -1878,7 +1889,7 @@ static int qxl_init_secondary(PCIDevice *dev)
     PCIQXLDevice *qxl = DO_UPCAST(PCIQXLDevice, pci, dev);
 
     qxl->id = device_id++;
-    qxl_init_ramsize(qxl, 16);
+    qxl_init_ramsize(qxl);
     memory_region_init_ram(&qxl->vga.vram, "qxl.vgavram", qxl->vga.vram_size);
     vmstate_register_ram(&qxl->vga.vram, &qxl->pci.qdev);
     qxl->vga.vram_ptr = memory_region_get_ram_ptr(&qxl->vga.vram);
@@ -2056,6 +2067,7 @@ static Property qxl_properties[] = {
         DEFINE_PROP_UINT32("ram_size_mb",  PCIQXLDevice, ram_size_mb, -1),
         DEFINE_PROP_UINT32("vram_size_mb", PCIQXLDevice, vram32_size_mb, -1),
         DEFINE_PROP_UINT32("vram64_size_mb", PCIQXLDevice, vram_size_mb, -1),
+        DEFINE_PROP_UINT32("vgamem_mb", PCIQXLDevice, vgamem_size_mb, 8),
         DEFINE_PROP_END_OF_LIST(),
 };
 
diff --git a/hw/qxl.h b/hw/qxl.h
index a4ab7cc..172baf6 100644
--- a/hw/qxl.h
+++ b/hw/qxl.h
@@ -84,6 +84,7 @@ typedef struct PCIQXLDevice {
     QXLReleaseInfo     *last_release;
     uint32_t           last_release_offset;
     uint32_t           oom_running;
+    uint32_t           vgamem_size;
 
     /* rom pci bar */
     QXLRom             shadow_rom;
@@ -105,6 +106,7 @@ typedef struct PCIQXLDevice {
     uint32_t          ram_size_mb;
     uint32_t          vram_size_mb;
     uint32_t          vram32_size_mb;
+    uint32_t          vgamem_size_mb;
 
     /* qxl_render_update state */
     int                render_update_cookie_num;
commit 4e1797f9a587ce39d1d67e25d73687eea7b1b04a
Author: Stefan Weil <sw at weilnetz.de>
Date:   Mon Jun 18 22:11:06 2012 +0200

    configure: Fix typo
    
    The typo did not cause an error because open_by_handle_at
    was only compared to "yes".
    
    Signed-off-by: Stefan Weil <sw at weilnetz.de>
    Signed-off-by: Stefan Hajnoczi <stefanha at linux.vnet.ibm.com>

diff --git a/configure b/configure
index b68c0ca..1446f52 100755
--- a/configure
+++ b/configure
@@ -2808,7 +2808,7 @@ fi
 ##########################################
 # check if we have open_by_handle_at
 
-open_by_hande_at=no
+open_by_handle_at=no
 cat > $TMPC << EOF
 #include <fcntl.h>
 #if !defined(AT_EMPTY_PATH)
commit 4a1e244eb65c646bdd938d9d137ace42d76c95a7
Author: Gerd Hoffmann <kraxel at redhat.com>
Date:   Thu May 24 09:59:44 2012 +0200

    vga: make vram size configurable
    
    Zap the global VGA_RAM_SIZE #define, make the vga ram size configurable
    for standard vga and vmware vga.  cirrus and qxl are left with a fixed
    size (and private VGA_RAM_SIZE #define) for now.
    
    qxl needs some non-trivial adjustments in the mode list handling deal
    with a runtime-configurable size, which calls for a separate qxl patch.
    
    cirrus emulates cards which have 2 MB (isa) and 4 MB (pci), so I guess
    it would make sense to use these sizes.  That change would break
    migration though, so I left it fixed at 8 MB size.  Making it
    configurabls is pretty pointless for cirrus as we have to match real
    hardware.
    
    Signed-off-by: Gerd Hoffmann <kraxel at redhat.com>

diff --git a/hw/cirrus_vga.c b/hw/cirrus_vga.c
index afedaa4..623dd68 100644
--- a/hw/cirrus_vga.c
+++ b/hw/cirrus_vga.c
@@ -43,6 +43,8 @@
 //#define DEBUG_CIRRUS
 //#define DEBUG_BITBLT
 
+#define VGA_RAM_SIZE (8192 * 1024)
+
 /***************************************
  *
  *  definitions
@@ -2891,7 +2893,8 @@ static int vga_initfn(ISADevice *dev)
     ISACirrusVGAState *d = DO_UPCAST(ISACirrusVGAState, dev, dev);
     VGACommonState *s = &d->cirrus_vga.vga;
 
-    vga_common_init(s, VGA_RAM_SIZE);
+    s->vram_size_mb = VGA_RAM_SIZE >> 20;
+    vga_common_init(s);
     cirrus_init_common(&d->cirrus_vga, CIRRUS_ID_CLGD5430, 0,
                        isa_address_space(dev));
     s->ds = graphic_console_init(s->update, s->invalidate,
@@ -2933,7 +2936,8 @@ static int pci_cirrus_vga_initfn(PCIDevice *dev)
      int16_t device_id = pc->device_id;
 
      /* setup VGA */
-     vga_common_init(&s->vga, VGA_RAM_SIZE);
+     s->vga.vram_size_mb = VGA_RAM_SIZE >> 20;
+     vga_common_init(&s->vga);
      cirrus_init_common(s, device_id, 1, pci_address_space(dev));
      s->vga.ds = graphic_console_init(s->vga.update, s->vga.invalidate,
                                       s->vga.screen_dump, s->vga.text_update,
diff --git a/hw/qxl.c b/hw/qxl.c
index 4be9462..c40cf55 100644
--- a/hw/qxl.c
+++ b/hw/qxl.c
@@ -27,6 +27,8 @@
 
 #include "qxl.h"
 
+#define VGA_RAM_SIZE (8192 * 1024)
+
 /*
  * NOTE: SPICE_RING_PROD_ITEM accesses memory on the pci bar and as
  * such can be changed by the guest, so to avoid a guest trigerrable
@@ -1854,7 +1856,8 @@ static int qxl_init_primary(PCIDevice *dev)
 
     qxl->id = 0;
     qxl_init_ramsize(qxl, 32);
-    vga_common_init(vga, qxl->vga.vram_size);
+    vga->vram_size_mb = qxl->vga.vram_size >> 20;
+    vga_common_init(vga);
     vga_init(vga, pci_address_space(dev), pci_address_space_io(dev), false);
     portio_list_init(qxl_vga_port_list, qxl_vga_portio_list, vga, "vga");
     portio_list_add(qxl_vga_port_list, pci_address_space_io(dev), 0x3b0);
diff --git a/hw/vga-isa-mm.c b/hw/vga-isa-mm.c
index f8984c6..44ae7d9 100644
--- a/hw/vga-isa-mm.c
+++ b/hw/vga-isa-mm.c
@@ -28,6 +28,8 @@
 #include "pixel_ops.h"
 #include "qemu-timer.h"
 
+#define VGA_RAM_SIZE (8192 * 1024)
+
 typedef struct ISAVGAMMState {
     VGACommonState vga;
     int it_shift;
@@ -128,7 +130,8 @@ int isa_vga_mm_init(target_phys_addr_t vram_base,
 
     s = g_malloc0(sizeof(*s));
 
-    vga_common_init(&s->vga, VGA_RAM_SIZE);
+    s->vga.vram_size_mb = VGA_RAM_SIZE >> 20;
+    vga_common_init(&s->vga);
     vga_mm_init(s, vram_base, ctrl_base, it_shift, address_space);
 
     s->vga.ds = graphic_console_init(s->vga.update, s->vga.invalidate,
diff --git a/hw/vga-isa.c b/hw/vga-isa.c
index 4bcc4db..d290473 100644
--- a/hw/vga-isa.c
+++ b/hw/vga-isa.c
@@ -49,7 +49,7 @@ static int vga_initfn(ISADevice *dev)
     MemoryRegion *vga_io_memory;
     const MemoryRegionPortio *vga_ports, *vbe_ports;
 
-    vga_common_init(s, VGA_RAM_SIZE);
+    vga_common_init(s);
     s->legacy_address_space = isa_address_space(dev);
     vga_io_memory = vga_init_io(s, &vga_ports, &vbe_ports);
     isa_register_portio_list(dev, 0x3b0, vga_ports, s, "vga");
@@ -69,6 +69,11 @@ static int vga_initfn(ISADevice *dev)
     return 0;
 }
 
+static Property vga_isa_properties[] = {
+    DEFINE_PROP_UINT32("vgamem_mb", ISAVGAState, state.vram_size_mb, 8),
+    DEFINE_PROP_END_OF_LIST(),
+};
+
 static void vga_class_initfn(ObjectClass *klass, void *data)
 {
     DeviceClass *dc = DEVICE_CLASS(klass);
@@ -76,6 +81,7 @@ static void vga_class_initfn(ObjectClass *klass, void *data)
     ic->init = vga_initfn;
     dc->reset = vga_reset_isa;
     dc->vmsd = &vmstate_vga_common;
+    dc->props = vga_isa_properties;
 }
 
 static TypeInfo vga_info = {
diff --git a/hw/vga-pci.c b/hw/vga-pci.c
index 465b643..0848126 100644
--- a/hw/vga-pci.c
+++ b/hw/vga-pci.c
@@ -53,7 +53,7 @@ static int pci_vga_initfn(PCIDevice *dev)
      VGACommonState *s = &d->vga;
 
      // vga + console init
-     vga_common_init(s, VGA_RAM_SIZE);
+     vga_common_init(s);
      vga_init(s, pci_address_space(dev), pci_address_space_io(dev), true);
 
      s->ds = graphic_console_init(s->update, s->invalidate,
@@ -75,6 +75,11 @@ DeviceState *pci_vga_init(PCIBus *bus)
     return &pci_create_simple(bus, -1, "VGA")->qdev;
 }
 
+static Property vga_pci_properties[] = {
+    DEFINE_PROP_UINT32("vgamem_mb", PCIVGAState, vga.vram_size_mb, 8),
+    DEFINE_PROP_END_OF_LIST(),
+};
+
 static void vga_class_init(ObjectClass *klass, void *data)
 {
     DeviceClass *dc = DEVICE_CLASS(klass);
@@ -87,6 +92,7 @@ static void vga_class_init(ObjectClass *klass, void *data)
     k->device_id = PCI_DEVICE_ID_QEMU_VGA;
     k->class_id = PCI_CLASS_DISPLAY_VGA;
     dc->vmsd = &vmstate_vga_pci;
+    dc->props = vga_pci_properties;
 }
 
 static TypeInfo vga_info = {
diff --git a/hw/vga.c b/hw/vga.c
index d784df7..acb3f7d 100644
--- a/hw/vga.c
+++ b/hw/vga.c
@@ -2225,7 +2225,7 @@ const VMStateDescription vmstate_vga_common = {
     }
 };
 
-void vga_common_init(VGACommonState *s, int vga_ram_size)
+void vga_common_init(VGACommonState *s)
 {
     int i, j, v, b;
 
@@ -2252,16 +2252,23 @@ void vga_common_init(VGACommonState *s, int vga_ram_size)
         expand4to8[i] = v;
     }
 
+    /* valid range: 1 MB -> 256 MB */
+    s->vram_size = 1024 * 1024;
+    while (s->vram_size < (s->vram_size_mb << 20) &&
+           s->vram_size < (256 << 20)) {
+        s->vram_size <<= 1;
+    }
+    s->vram_size_mb = s->vram_size >> 20;
+
 #ifdef CONFIG_BOCHS_VBE
     s->is_vbe_vmstate = 1;
 #else
     s->is_vbe_vmstate = 0;
 #endif
-    memory_region_init_ram(&s->vram, "vga.vram", vga_ram_size);
+    memory_region_init_ram(&s->vram, "vga.vram", s->vram_size);
     vmstate_register_ram_global(&s->vram);
     xen_register_framebuffer(&s->vram);
     s->vram_ptr = memory_region_get_ram_ptr(&s->vram);
-    s->vram_size = vga_ram_size;
     s->get_bpp = vga_get_bpp;
     s->get_offsets = vga_get_offsets;
     s->get_resolution = vga_get_resolution;
diff --git a/hw/vga_int.h b/hw/vga_int.h
index ce33e66..3b38764 100644
--- a/hw/vga_int.h
+++ b/hw/vga_int.h
@@ -107,6 +107,7 @@ typedef struct VGACommonState {
     MemoryRegion vram;
     MemoryRegion vram_vbe;
     uint32_t vram_size;
+    uint32_t vram_size_mb; /* property */
     uint32_t latch;
     MemoryRegion *chain4_alias;
     uint8_t sr_index;
@@ -184,7 +185,7 @@ static inline int c6_to_8(int v)
     return (v << 2) | (b << 1) | b;
 }
 
-void vga_common_init(VGACommonState *s, int vga_ram_size);
+void vga_common_init(VGACommonState *s);
 void vga_init(VGACommonState *s, MemoryRegion *address_space,
               MemoryRegion *address_space_io, bool init_vga_ports);
 MemoryRegion *vga_init_io(VGACommonState *s,
@@ -209,7 +210,6 @@ void vga_init_vbe(VGACommonState *s, MemoryRegion *address_space);
 extern const uint8_t sr_mask[8];
 extern const uint8_t gr_mask[16];
 
-#define VGA_RAM_SIZE (8192 * 1024)
 #define VGABIOS_FILENAME "vgabios.bin"
 #define VGABIOS_CIRRUS_FILENAME "vgabios-cirrus.bin"
 
diff --git a/hw/vmware_vga.c b/hw/vmware_vga.c
index 142d9f4..f8eb46d 100644
--- a/hw/vmware_vga.c
+++ b/hw/vmware_vga.c
@@ -1078,7 +1078,7 @@ static const VMStateDescription vmstate_vmware_vga = {
     }
 };
 
-static void vmsvga_init(struct vmsvga_state_s *s, int vga_ram_size,
+static void vmsvga_init(struct vmsvga_state_s *s,
                         MemoryRegion *address_space, MemoryRegion *io)
 {
     s->scratch_size = SVGA_SCRATCH_SIZE;
@@ -1095,7 +1095,7 @@ static void vmsvga_init(struct vmsvga_state_s *s, int vga_ram_size,
     vmstate_register_ram_global(&s->fifo_ram);
     s->fifo_ptr = memory_region_get_ram_ptr(&s->fifo_ram);
 
-    vga_common_init(&s->vga, vga_ram_size);
+    vga_common_init(&s->vga);
     vga_init(&s->vga, address_space, io, true);
     vmstate_register(NULL, 0, &vmstate_vga_common, &s->vga);
 
@@ -1184,7 +1184,7 @@ static int pci_vmsvga_initfn(PCIDevice *dev)
                           "vmsvga-io", 0x10);
     pci_register_bar(&s->card, 0, PCI_BASE_ADDRESS_SPACE_IO, &s->io_bar);
 
-    vmsvga_init(&s->chip, VGA_RAM_SIZE, pci_address_space(dev),
+    vmsvga_init(&s->chip, pci_address_space(dev),
                 pci_address_space_io(dev));
 
     pci_register_bar(&s->card, 1, PCI_BASE_ADDRESS_MEM_PREFETCH, iomem);
@@ -1199,6 +1199,12 @@ static int pci_vmsvga_initfn(PCIDevice *dev)
     return 0;
 }
 
+static Property vga_vmware_properties[] = {
+    DEFINE_PROP_UINT32("vgamem_mb", struct pci_vmsvga_state_s,
+                       chip.vga.vram_size_mb, 8),
+    DEFINE_PROP_END_OF_LIST(),
+};
+
 static void vmsvga_class_init(ObjectClass *klass, void *data)
 {
     DeviceClass *dc = DEVICE_CLASS(klass);
@@ -1214,6 +1220,7 @@ static void vmsvga_class_init(ObjectClass *klass, void *data)
     k->subsystem_id = SVGA_PCI_DEVICE_ID;
     dc->reset = vmsvga_reset;
     dc->vmsd = &vmstate_vmware_vga;
+    dc->props = vga_vmware_properties;
 }
 
 static TypeInfo vmsvga_info = {
commit e9c6149f6ae6873f14a12eea554925b6aa4c4dec
Author: Gerd Hoffmann <kraxel at redhat.com>
Date:   Thu May 24 09:16:29 2012 +0200

    vga: raise xres+yres limits
    
    The vgabios will check whenever any given video mode will fit into the
    given video memory before adding it to the list of available modes, so
    there is no need to keep xmax * ymax * 32bpp lower than VGA_RAM_SIZE.
    
    Lets raise the limits a bit.  Should be good for a few years, display
    sizes are not growing that fast.
    
    Signed-off-by: Gerd Hoffmann <kraxel at redhat.com>

diff --git a/hw/vga_int.h b/hw/vga_int.h
index d244d8f..ce33e66 100644
--- a/hw/vga_int.h
+++ b/hw/vga_int.h
@@ -31,8 +31,8 @@
 /* bochs VBE support */
 #define CONFIG_BOCHS_VBE
 
-#define VBE_DISPI_MAX_XRES              1600
-#define VBE_DISPI_MAX_YRES              1200
+#define VBE_DISPI_MAX_XRES              16000
+#define VBE_DISPI_MAX_YRES              12000
 #define VBE_DISPI_MAX_BPP               32
 
 #define VBE_DISPI_INDEX_ID              0x0
commit a5f68c22e76bc4108401046081b058a901555bf4
Author: Alon Levy <alevy at redhat.com>
Date:   Mon Jun 11 09:24:01 2012 +0300

    qxl: reset current_async on qxl_soft_reset
    
    Signed-off-by: Alon Levy <alevy at redhat.com>
    Signed-off-by: Gerd Hoffmann <kraxel at redhat.com>

diff --git a/hw/qxl.c b/hw/qxl.c
index b5e53ce..4be9462 100644
--- a/hw/qxl.c
+++ b/hw/qxl.c
@@ -986,6 +986,7 @@ static void qxl_soft_reset(PCIQXLDevice *d)
     trace_qxl_soft_reset(d->id);
     qxl_check_state(d);
     qxl_clear_guest_bug(d);
+    d->current_async = QXL_UNDEFINED_IO;
 
     if (d->id == 0) {
         qxl_enter_vga_mode(d);
commit 087e6a42ed6ddba524a343563611d2a7b78f15a8
Author: Alon Levy <alevy at redhat.com>
Date:   Thu May 24 19:18:54 2012 +0300

    hw/qxl: ignore guest from guestbug until reset
    
    soft_reset is called from any of:
     * QXL_IO_RESET
     * vga io
     * pci reset handler
    
    Signed-off-by: Alon Levy <alevy at redhat.com>
    Signed-off-by: Gerd Hoffmann <kraxel at redhat.com>

diff --git a/hw/qxl.c b/hw/qxl.c
index 5a7be60..b5e53ce 100644
--- a/hw/qxl.c
+++ b/hw/qxl.c
@@ -141,6 +141,7 @@ static void qxl_ring_set_dirty(PCIQXLDevice *qxl);
 void qxl_set_guest_bug(PCIQXLDevice *qxl, const char *msg, ...)
 {
     qxl_send_events(qxl, QXL_INTERRUPT_ERROR);
+    qxl->guest_bug = 1;
     if (qxl->guestdebug) {
         va_list ap;
         va_start(ap, msg);
@@ -151,6 +152,10 @@ void qxl_set_guest_bug(PCIQXLDevice *qxl, const char *msg, ...)
     }
 }
 
+static void qxl_clear_guest_bug(PCIQXLDevice *qxl)
+{
+    qxl->guest_bug = 0;
+}
 
 void qxl_spice_update_area(PCIQXLDevice *qxl, uint32_t surface_id,
                            struct QXLRect *area, struct QXLRect *dirty_rects,
@@ -572,7 +577,7 @@ static int interface_get_command(QXLInstance *sin, struct QXLCommandExt *ext)
     case QXL_MODE_NATIVE:
     case QXL_MODE_UNDEFINED:
         ring = &qxl->ram->cmd_ring;
-        if (SPICE_RING_IS_EMPTY(ring)) {
+        if (qxl->guest_bug || SPICE_RING_IS_EMPTY(ring)) {
             return false;
         }
         SPICE_RING_CONS_ITEM(qxl, ring, cmd);
@@ -980,6 +985,7 @@ static void qxl_soft_reset(PCIQXLDevice *d)
 {
     trace_qxl_soft_reset(d->id);
     qxl_check_state(d);
+    qxl_clear_guest_bug(d);
 
     if (d->id == 0) {
         qxl_enter_vga_mode(d);
@@ -1297,6 +1303,10 @@ static void ioport_write(void *opaque, target_phys_addr_t addr,
     qxl_async_io async = QXL_SYNC;
     uint32_t orig_io_port = io_port;
 
+    if (d->guest_bug && !io_port == QXL_IO_RESET) {
+        return;
+    }
+
     switch (io_port) {
     case QXL_IO_RESET:
     case QXL_IO_SET_MODE:
@@ -1749,6 +1759,7 @@ static int qxl_init_common(PCIQXLDevice *qxl)
     qemu_mutex_init(&qxl->track_lock);
     qemu_mutex_init(&qxl->async_lock);
     qxl->current_async = QXL_UNDEFINED_IO;
+    qxl->guest_bug = 0;
 
     switch (qxl->revision) {
     case 1: /* spice 0.4 -- qxl-1 */
diff --git a/hw/qxl.h b/hw/qxl.h
index f2d4fdc..a4ab7cc 100644
--- a/hw/qxl.h
+++ b/hw/qxl.h
@@ -31,6 +31,9 @@ typedef struct PCIQXLDevice {
     uint32_t           debug;
     uint32_t           guestdebug;
     uint32_t           cmdlog;
+
+    uint32_t           guest_bug;
+
     enum qxl_mode      mode;
     uint32_t           cmdflags;
     int                generation;
commit 0f7bfd8198ffad58a5095ac5d7a46288ea7f5c6e
Author: Alon Levy <alevy at redhat.com>
Date:   Thu May 24 19:18:53 2012 +0300

    qxl: stop dirty loging when not in vga mode
    
    Tested with linux guest. Not sure how to check actual performance affect
    of this. Checked with the previously send traceevent that the kvm ioctl
    to start/stop dirty logging is being called.
    (KVM_SET_USER_MEMORY_REGION).
    
    Signed-off-by: Alon Levy <alevy at redhat.com>
    Signed-off-by: Gerd Hoffmann <kraxel at redhat.com>

diff --git a/hw/qxl.c b/hw/qxl.c
index 8777ba9..5a7be60 100644
--- a/hw/qxl.c
+++ b/hw/qxl.c
@@ -932,6 +932,7 @@ static void qxl_enter_vga_mode(PCIQXLDevice *d)
     qemu_spice_create_host_primary(&d->ssd);
     d->mode = QXL_MODE_VGA;
     memset(&d->ssd.dirty, 0, sizeof(d->ssd.dirty));
+    vga_dirty_log_start(&d->vga);
 }
 
 static void qxl_exit_vga_mode(PCIQXLDevice *d)
@@ -940,6 +941,7 @@ static void qxl_exit_vga_mode(PCIQXLDevice *d)
         return;
     }
     trace_qxl_exit_vga_mode(d->id);
+    vga_dirty_log_stop(&d->vga);
     qxl_destroy_primary(d, QXL_SYNC);
 }
 
commit 0a530548a1007dd24a9ea3429af2c9dfae690386
Author: Alon Levy <alevy at redhat.com>
Date:   Thu May 24 12:38:12 2012 +0300

    hw/qxl: s/qxl_guest_bug/qxl_set_guest_bug/
    
    Signed-off-by: Alon Levy <alevy at redhat.com>
    Signed-off-by: Gerd Hoffmann <kraxel at redhat.com>

diff --git a/hw/qxl.c b/hw/qxl.c
index 3da3399..8777ba9 100644
--- a/hw/qxl.c
+++ b/hw/qxl.c
@@ -30,7 +30,7 @@
 /*
  * NOTE: SPICE_RING_PROD_ITEM accesses memory on the pci bar and as
  * such can be changed by the guest, so to avoid a guest trigerrable
- * abort we just set qxl_guest_bug and set the return to NULL. Still
+ * abort we just qxl_set_guest_bug and set the return to NULL. Still
  * it may happen as a result of emulator bug as well.
  */
 #undef SPICE_RING_PROD_ITEM
@@ -40,7 +40,7 @@
         uint32_t prod = (r)->prod & SPICE_RING_INDEX_MASK(r);           \
         typeof(&(r)->items[prod]) m_item = &(r)->items[prod];           \
         if (!((uint8_t*)m_item >= (uint8_t*)(start) && (uint8_t*)(m_item + 1) <= (uint8_t*)(end))) { \
-            qxl_guest_bug(qxl, "SPICE_RING_PROD_ITEM indices mismatch " \
+            qxl_set_guest_bug(qxl, "SPICE_RING_PROD_ITEM indices mismatch " \
                           "! %p <= %p < %p", (uint8_t *)start,          \
                           (uint8_t *)m_item, (uint8_t *)end);           \
             ret = NULL;                                                 \
@@ -56,7 +56,7 @@
         uint32_t cons = (r)->cons & SPICE_RING_INDEX_MASK(r);           \
         typeof(&(r)->items[cons]) m_item = &(r)->items[cons];           \
         if (!((uint8_t*)m_item >= (uint8_t*)(start) && (uint8_t*)(m_item + 1) <= (uint8_t*)(end))) { \
-            qxl_guest_bug(qxl, "SPICE_RING_CONS_ITEM indices mismatch " \
+            qxl_set_guest_bug(qxl, "SPICE_RING_CONS_ITEM indices mismatch " \
                           "! %p <= %p < %p", (uint8_t *)start,          \
                           (uint8_t *)m_item, (uint8_t *)end);           \
             ret = NULL;                                                 \
@@ -138,7 +138,7 @@ static void qxl_reset_memslots(PCIQXLDevice *d);
 static void qxl_reset_surfaces(PCIQXLDevice *d);
 static void qxl_ring_set_dirty(PCIQXLDevice *qxl);
 
-void qxl_guest_bug(PCIQXLDevice *qxl, const char *msg, ...)
+void qxl_set_guest_bug(PCIQXLDevice *qxl, const char *msg, ...)
 {
     qxl_send_events(qxl, QXL_INTERRUPT_ERROR);
     if (qxl->guestdebug) {
@@ -411,7 +411,8 @@ static int qxl_track_command(PCIQXLDevice *qxl, struct QXLCommandExt *ext)
         uint32_t id = le32_to_cpu(cmd->surface_id);
 
         if (id >= NUM_SURFACES) {
-            qxl_guest_bug(qxl, "QXL_CMD_SURFACE id %d >= %d", id, NUM_SURFACES);
+            qxl_set_guest_bug(qxl, "QXL_CMD_SURFACE id %d >= %d", id,
+                              NUM_SURFACES);
             return 1;
         }
         qemu_mutex_lock(&qxl->track_lock);
@@ -1061,12 +1062,12 @@ static int qxl_add_memslot(PCIQXLDevice *d, uint32_t slot_id, uint64_t delta,
     trace_qxl_memslot_add_guest(d->id, slot_id, guest_start, guest_end);
 
     if (slot_id >= NUM_MEMSLOTS) {
-        qxl_guest_bug(d, "%s: slot_id >= NUM_MEMSLOTS %d >= %d", __func__,
+        qxl_set_guest_bug(d, "%s: slot_id >= NUM_MEMSLOTS %d >= %d", __func__,
                       slot_id, NUM_MEMSLOTS);
         return 1;
     }
     if (guest_start > guest_end) {
-        qxl_guest_bug(d, "%s: guest_start > guest_end 0x%" PRIx64
+        qxl_set_guest_bug(d, "%s: guest_start > guest_end 0x%" PRIx64
                          " > 0x%" PRIx64, __func__, guest_start, guest_end);
         return 1;
     }
@@ -1091,7 +1092,7 @@ static int qxl_add_memslot(PCIQXLDevice *d, uint32_t slot_id, uint64_t delta,
         break;
     }
     if (i == ARRAY_SIZE(regions)) {
-        qxl_guest_bug(d, "%s: finished loop without match", __func__);
+        qxl_set_guest_bug(d, "%s: finished loop without match", __func__);
         return 1;
     }
 
@@ -1105,7 +1106,7 @@ static int qxl_add_memslot(PCIQXLDevice *d, uint32_t slot_id, uint64_t delta,
         break;
     default:
         /* should not happen */
-        qxl_guest_bug(d, "%s: pci_region = %d", __func__, pci_region);
+        qxl_set_guest_bug(d, "%s: pci_region = %d", __func__, pci_region);
         return 1;
     }
 
@@ -1156,21 +1157,24 @@ void *qxl_phys2virt(PCIQXLDevice *qxl, QXLPHYSICAL pqxl, int group_id)
         return (void *)(intptr_t)offset;
     case MEMSLOT_GROUP_GUEST:
         if (slot >= NUM_MEMSLOTS) {
-            qxl_guest_bug(qxl, "slot too large %d >= %d", slot, NUM_MEMSLOTS);
+            qxl_set_guest_bug(qxl, "slot too large %d >= %d", slot,
+                              NUM_MEMSLOTS);
             return NULL;
         }
         if (!qxl->guest_slots[slot].active) {
-            qxl_guest_bug(qxl, "inactive slot %d\n", slot);
+            qxl_set_guest_bug(qxl, "inactive slot %d\n", slot);
             return NULL;
         }
         if (offset < qxl->guest_slots[slot].delta) {
-            qxl_guest_bug(qxl, "slot %d offset %"PRIu64" < delta %"PRIu64"\n",
+            qxl_set_guest_bug(qxl,
+                          "slot %d offset %"PRIu64" < delta %"PRIu64"\n",
                           slot, offset, qxl->guest_slots[slot].delta);
             return NULL;
         }
         offset -= qxl->guest_slots[slot].delta;
         if (offset > qxl->guest_slots[slot].size) {
-            qxl_guest_bug(qxl, "slot %d offset %"PRIu64" > size %"PRIu64"\n",
+            qxl_set_guest_bug(qxl,
+                          "slot %d offset %"PRIu64" > size %"PRIu64"\n",
                           slot, offset, qxl->guest_slots[slot].size);
             return NULL;
         }
@@ -1192,7 +1196,7 @@ static void qxl_create_guest_primary(PCIQXLDevice *qxl, int loadvm,
     QXLSurfaceCreate *sc = &qxl->guest_primary.surface;
 
     if (qxl->mode == QXL_MODE_NATIVE) {
-        qxl_guest_bug(qxl, "%s: nop since already in QXL_MODE_NATIVE",
+        qxl_set_guest_bug(qxl, "%s: nop since already in QXL_MODE_NATIVE",
                       __func__);
     }
     qxl_exit_vga_mode(qxl);
@@ -1342,7 +1346,7 @@ async_common:
         async = QXL_ASYNC;
         qemu_mutex_lock(&d->async_lock);
         if (d->current_async != QXL_UNDEFINED_IO) {
-            qxl_guest_bug(d, "%d async started before last (%d) complete",
+            qxl_set_guest_bug(d, "%d async started before last (%d) complete",
                 io_port, d->current_async);
             qemu_mutex_unlock(&d->async_lock);
             return;
@@ -1403,11 +1407,12 @@ async_common:
         break;
     case QXL_IO_MEMSLOT_ADD:
         if (val >= NUM_MEMSLOTS) {
-            qxl_guest_bug(d, "QXL_IO_MEMSLOT_ADD: val out of range");
+            qxl_set_guest_bug(d, "QXL_IO_MEMSLOT_ADD: val out of range");
             break;
         }
         if (d->guest_slots[val].active) {
-            qxl_guest_bug(d, "QXL_IO_MEMSLOT_ADD: memory slot already active");
+            qxl_set_guest_bug(d,
+                        "QXL_IO_MEMSLOT_ADD: memory slot already active");
             break;
         }
         d->guest_slots[val].slot = d->ram->mem_slot;
@@ -1415,14 +1420,14 @@ async_common:
         break;
     case QXL_IO_MEMSLOT_DEL:
         if (val >= NUM_MEMSLOTS) {
-            qxl_guest_bug(d, "QXL_IO_MEMSLOT_DEL: val out of range");
+            qxl_set_guest_bug(d, "QXL_IO_MEMSLOT_DEL: val out of range");
             break;
         }
         qxl_del_memslot(d, val);
         break;
     case QXL_IO_CREATE_PRIMARY:
         if (val != 0) {
-            qxl_guest_bug(d, "QXL_IO_CREATE_PRIMARY (async=%d): val != 0",
+            qxl_set_guest_bug(d, "QXL_IO_CREATE_PRIMARY (async=%d): val != 0",
                           async);
             goto cancel_async;
         }
@@ -1431,7 +1436,7 @@ async_common:
         break;
     case QXL_IO_DESTROY_PRIMARY:
         if (val != 0) {
-            qxl_guest_bug(d, "QXL_IO_DESTROY_PRIMARY (async=%d): val != 0",
+            qxl_set_guest_bug(d, "QXL_IO_DESTROY_PRIMARY (async=%d): val != 0",
                           async);
             goto cancel_async;
         }
@@ -1443,7 +1448,7 @@ async_common:
         break;
     case QXL_IO_DESTROY_SURFACE_WAIT:
         if (val >= NUM_SURFACES) {
-            qxl_guest_bug(d, "QXL_IO_DESTROY_SURFACE (async=%d):"
+            qxl_set_guest_bug(d, "QXL_IO_DESTROY_SURFACE (async=%d):"
                              "%" PRIu64 " >= NUM_SURFACES", async, val);
             goto cancel_async;
         }
@@ -1467,7 +1472,7 @@ async_common:
         qxl_spice_destroy_surfaces(d, async);
         break;
     default:
-        qxl_guest_bug(d, "%s: unexpected ioport=0x%x\n", __func__, io_port);
+        qxl_set_guest_bug(d, "%s: unexpected ioport=0x%x\n", __func__, io_port);
     }
     return;
 cancel_async:
diff --git a/hw/qxl.h b/hw/qxl.h
index 3102950..f2d4fdc 100644
--- a/hw/qxl.h
+++ b/hw/qxl.h
@@ -127,7 +127,8 @@ typedef struct PCIQXLDevice {
 
 /* qxl.c */
 void *qxl_phys2virt(PCIQXLDevice *qxl, QXLPHYSICAL phys, int group_id);
-void qxl_guest_bug(PCIQXLDevice *qxl, const char *msg, ...) GCC_FMT_ATTR(2, 3);
+void qxl_set_guest_bug(PCIQXLDevice *qxl, const char *msg, ...)
+    GCC_FMT_ATTR(2, 3);
 
 void qxl_spice_update_area(PCIQXLDevice *qxl, uint32_t surface_id,
                            struct QXLRect *area, struct QXLRect *dirty_rects,
commit 160c31f78fb4eb747e50d077835dbb70dbdbbb9f
Author: Alon Levy <alevy at redhat.com>
Date:   Thu May 24 12:38:11 2012 +0300

    ui/spice-display.c: add missing initialization for valgrind
    
    We can't initialize QXLDevSurfaceCreate field by field because it has a
    pa hole, and so 4 bytes remain uninitialized when building on x86-64, so
    just memset.
    
    Signed-off-by: Alon Levy <alevy at redhat.com>
    Signed-off-by: Gerd Hoffmann <kraxel at redhat.com>

diff --git a/ui/spice-display.c b/ui/spice-display.c
index 5418eb3..3e8f0b3 100644
--- a/ui/spice-display.c
+++ b/ui/spice-display.c
@@ -244,6 +244,8 @@ void qemu_spice_create_host_primary(SimpleSpiceDisplay *ssd)
 {
     QXLDevSurfaceCreate surface;
 
+    memset(&surface, 0, sizeof(surface));
+
     dprint(1, "%s: %dx%d\n", __FUNCTION__,
            ds_get_width(ssd->ds), ds_get_height(ssd->ds));
 
commit 5eb98401719dfcccf42cf5ec61ac106c5aaa499e
Author: Peter A. G. Crosthwaite <peter.crosthwaite at petalogix.com>
Date:   Mon Jun 18 11:00:18 2012 +1000

    arm_gic: Send dbg msgs to stderr not stdout
    
    Signed-off-by: Peter A. G. Crosthwaite <peter.crosthwaite at petalogix.com>
    Signed-off-by: Stefan Hajnoczi <stefanha at linux.vnet.ibm.com>

diff --git a/hw/arm_gic.c b/hw/arm_gic.c
index 72298b4..c78d58e 100644
--- a/hw/arm_gic.c
+++ b/hw/arm_gic.c
@@ -35,7 +35,7 @@
 
 #ifdef DEBUG_GIC
 #define DPRINTF(fmt, ...) \
-do { printf("arm_gic: " fmt , ## __VA_ARGS__); } while (0)
+do { fprintf(stderr, "arm_gic: " fmt , ## __VA_ARGS__); } while (0)
 #else
 #define DPRINTF(fmt, ...) do {} while(0)
 #endif
commit 9964d8f9422e72fc6026049b966544c8e40a7b67
Author: Stefan Weil <sw at weilnetz.de>
Date:   Sun Jun 17 06:57:41 2012 +0200

    checkpatch: Add QEMU specific rule
    
    The new rule detects two wrong variants of QEMU.
    It was tested with commit b5a8fe5e.
    
    Signed-off-by: Stefan Weil <sw at weilnetz.de>
    Signed-off-by: Stefan Hajnoczi <stefanha at linux.vnet.ibm.com>

diff --git a/scripts/checkpatch.pl b/scripts/checkpatch.pl
index 8850a5f..b98dc6c 100755
--- a/scripts/checkpatch.pl
+++ b/scripts/checkpatch.pl
@@ -2849,6 +2849,11 @@ sub process {
 				ERROR("lockdep_no_validate class is reserved for device->mutex.\n" . $herecurr);
 			}
 		}
+
+# QEMU specific tests
+		if ($rawline =~ /\b(?:Qemu|QEmu)\b/) {
+			WARN("use QEMU instead of Qemu or QEmu\n" . $herecurr);
+		}
 	}
 
 	# If we have no input at all, then there is nothing to report on
commit bf7eaa5ffcd65ccca2ace9db37a403202d7f1274
Author: Stefan Weil <sw at weilnetz.de>
Date:   Sat Jun 16 09:29:10 2012 +0200

    qemu-config: Use QEMU instead of Qemu
    
    This new 'Qemu' was recently added.
    Replace it by the official all upper case 'QEMU'.
    
    Signed-off-by: Stefan Weil <sw at weilnetz.de>
    Signed-off-by: Stefan Hajnoczi <stefanha at linux.vnet.ibm.com>

diff --git a/qemu-config.h b/qemu-config.h
index e9f2ef4..12ddf3e 100644
--- a/qemu-config.h
+++ b/qemu-config.h
@@ -19,7 +19,7 @@ int qemu_config_parse(FILE *fp, QemuOptsList **lists, const char *fname);
 
 int qemu_read_config_file(const char *filename);
 
-/* Read default Qemu config files
+/* Read default QEMU config files
  */
 int qemu_read_default_config_files(bool userconfig);
 
commit b34d259516ae2377186171c58c3bc535eb9ed263
Author: Andreas Färber <andreas.faerber at web.de>
Date:   Mon May 28 00:53:20 2012 +0200

    libqtest: Fix socket_accept() to pass address_len
    
    accept() expects address_len to point to the length of the sockaddr on
    input. Initialize it accordingly.
    
    Resolves an assertion due to EFAULT on illumos.
    
    Signed-off-by: Andreas Färber <andreas.faerber at web.de>
    Signed-off-by: Stefan Hajnoczi <stefanha at linux.vnet.ibm.com>

diff --git a/tests/libqtest.c b/tests/libqtest.c
index 6d333ef..1d73fd1 100644
--- a/tests/libqtest.c
+++ b/tests/libqtest.c
@@ -74,6 +74,7 @@ static int socket_accept(int sock)
     socklen_t addrlen;
     int ret;
 
+    addrlen = sizeof(addr);
     do {
         ret = accept(sock, (struct sockaddr *)&addr, &addrlen);
     } while (ret == -1 && errno == EINTR);
commit fc8c5b8c41ee5ba69d7a2be63b02a08c7b0b155b
Author: Andreas Färber <afaerber at suse.de>
Date:   Sat Jun 9 13:56:42 2012 +0200

    Makefile.user: Define CONFIG_USER_ONLY for libuser/
    
    In *-*-user/ build dirs CONFIG_USER_ONLY is defined via config-target.h.
    In libuser/ it is not defined.
    
    Add it via QEMU_CFLAGS.
    
    Signed-off-by: Andreas Färber <afaerber at suse.de>
    Reviewed-by: Paolo Bonzini <pbonzini at redhat.com>
    Signed-off-by: Stefan Hajnoczi <stefanha at linux.vnet.ibm.com>

diff --git a/Makefile.user b/Makefile.user
index 0ffefe8..1783b2a 100644
--- a/Makefile.user
+++ b/Makefile.user
@@ -10,6 +10,7 @@ $(call set-vpath, $(SRC_PATH))
 
 QEMU_CFLAGS+=-I..
 QEMU_CFLAGS += -I$(SRC_PATH)/include
+QEMU_CFLAGS += -DCONFIG_USER_ONLY
 
 include $(SRC_PATH)/Makefile.objs
 
commit 8f0e5c6bb724671350df783c8bdb7ef8f54c4221
Author: Stefan Weil <sw at weilnetz.de>
Date:   Sat Jun 9 09:08:39 2012 +0200

    Makefile: Remove macro qapi-dir
    
    As qapi-dir was now a constant, it can be replaced by its value.
    
    Signed-off-by: Stefan Weil <sw at weilnetz.de>
    Signed-off-by: Stefan Hajnoczi <stefanha at linux.vnet.ibm.com>

diff --git a/Makefile b/Makefile
index d0847c5..26ffa51 100644
--- a/Makefile
+++ b/Makefile
@@ -171,9 +171,8 @@ fsdev/virtfs-proxy-helper$(EXESUF): LIBS += -lcap
 qemu-img-cmds.h: $(SRC_PATH)/qemu-img-cmds.hx
 	$(call quiet-command,sh $(SRC_PATH)/scripts/hxtool -h < $< > $@,"  GEN   $@")
 
-qapi-dir := qapi-generated
 qemu-ga$(EXESUF): LIBS = $(LIBS_QGA)
-qemu-ga$(EXESUF): QEMU_CFLAGS += -I $(qapi-dir)
+qemu-ga$(EXESUF): QEMU_CFLAGS += -I qapi-generated
 
 gen-out-type = $(subst .,-,$(suffix $@))
 
@@ -181,15 +180,15 @@ ifneq ($(wildcard config-host.mak),)
 include $(SRC_PATH)/tests/Makefile
 endif
 
-$(qapi-dir)/qga-qapi-types.c $(qapi-dir)/qga-qapi-types.h :\
+qapi-generated/qga-qapi-types.c qapi-generated/qga-qapi-types.h :\
 $(SRC_PATH)/qapi-schema-guest.json $(SRC_PATH)/scripts/qapi-types.py
-	$(call quiet-command,$(PYTHON) $(SRC_PATH)/scripts/qapi-types.py $(gen-out-type) -o "$(qapi-dir)" -p "qga-" < $<, "  GEN   $@")
-$(qapi-dir)/qga-qapi-visit.c $(qapi-dir)/qga-qapi-visit.h :\
+	$(call quiet-command,$(PYTHON) $(SRC_PATH)/scripts/qapi-types.py $(gen-out-type) -o qapi-generated -p "qga-" < $<, "  GEN   $@")
+qapi-generated/qga-qapi-visit.c qapi-generated/qga-qapi-visit.h :\
 $(SRC_PATH)/qapi-schema-guest.json $(SRC_PATH)/scripts/qapi-visit.py
-	$(call quiet-command,$(PYTHON) $(SRC_PATH)/scripts/qapi-visit.py $(gen-out-type) -o "$(qapi-dir)" -p "qga-" < $<, "  GEN   $@")
-$(qapi-dir)/qga-qmp-commands.h $(qapi-dir)/qga-qmp-marshal.c :\
+	$(call quiet-command,$(PYTHON) $(SRC_PATH)/scripts/qapi-visit.py $(gen-out-type) -o qapi-generated -p "qga-" < $<, "  GEN   $@")
+qapi-generated/qga-qmp-commands.h qapi-generated/qga-qmp-marshal.c :\
 $(SRC_PATH)/qapi-schema-guest.json $(SRC_PATH)/scripts/qapi-commands.py
-	$(call quiet-command,$(PYTHON) $(SRC_PATH)/scripts/qapi-commands.py $(gen-out-type) -o "$(qapi-dir)" -p "qga-" < $<, "  GEN   $@")
+	$(call quiet-command,$(PYTHON) $(SRC_PATH)/scripts/qapi-commands.py $(gen-out-type) -o qapi-generated -p "qga-" < $<, "  GEN   $@")
 
 qapi-types.c qapi-types.h :\
 $(SRC_PATH)/qapi-schema.json $(SRC_PATH)/scripts/qapi-types.py
@@ -201,8 +200,8 @@ qmp-commands.h qmp-marshal.c :\
 $(SRC_PATH)/qapi-schema.json $(SRC_PATH)/scripts/qapi-commands.py
 	$(call quiet-command,$(PYTHON) $(SRC_PATH)/scripts/qapi-commands.py $(gen-out-type) -m -o "." < $<, "  GEN   $@")
 
-QGALIB_OBJ=$(addprefix $(qapi-dir)/, qga-qapi-types.o qga-qapi-visit.o qga-qmp-marshal.o)
-QGALIB_GEN=$(addprefix $(qapi-dir)/, qga-qapi-types.h qga-qapi-visit.h qga-qmp-commands.h)
+QGALIB_OBJ=$(addprefix qapi-generated/, qga-qapi-types.o qga-qapi-visit.o qga-qmp-marshal.o)
+QGALIB_GEN=$(addprefix qapi-generated/, qga-qapi-types.h qga-qapi-visit.h qga-qmp-commands.h)
 $(QGALIB_OBJ): $(QGALIB_GEN)
 $(qga-obj-y) qemu-ga.o: $(QGALIB_GEN)
 
@@ -226,7 +225,7 @@ clean:
 	rm -f trace-dtrace.h trace-dtrace.h-timestamp
 	rm -f $(foreach f,$(GENERATED_HEADERS),$(f) $(f)-timestamp)
 	rm -f $(foreach f,$(GENERATED_SOURCES),$(f) $(f)-timestamp)
-	rm -rf $(qapi-dir)
+	rm -rf qapi-generated
 	$(MAKE) -C tests/tcg clean
 	for d in $(ALL_SUBDIRS) $(QEMULIBS) libcacard; do \
 	if test -d $$d; then $(MAKE) -C $$d $@ || exit 1; fi; \
commit f69a9c666b6f8f1b688f5c0f0cf9b780c598f966
Author: Stefan Weil <sw at weilnetz.de>
Date:   Sat Jun 9 09:08:38 2012 +0200

    Makefile: Remove BUILD_DIR from qapi-dir
    
    qapi-dir does not need an absolute path. All other build directories
    are relative. When BUILD_DIR is removed, the build output looks better
    (no long lines with absolute paths when everything else uses short
    lines):
    
      GEN   qapi-generated/qga-qapi-types.c
      CC    qapi-generated/qga-qapi-types.o
      GEN   qapi-generated/qga-qapi-visit.c
      CC    qapi-generated/qga-qapi-visit.o
      GEN   qapi-generated/qga-qmp-marshal.c
      CC    qapi-generated/qga-qmp-marshal.o
    
    Using a relative path also avoids potential problems when BUILD_DIR
    includes blanks.
    
    Signed-off-by: Stefan Weil <sw at weilnetz.de>
    Signed-off-by: Stefan Hajnoczi <stefanha at linux.vnet.ibm.com>

diff --git a/Makefile b/Makefile
index 277ae73..d0847c5 100644
--- a/Makefile
+++ b/Makefile
@@ -171,7 +171,7 @@ fsdev/virtfs-proxy-helper$(EXESUF): LIBS += -lcap
 qemu-img-cmds.h: $(SRC_PATH)/qemu-img-cmds.hx
 	$(call quiet-command,sh $(SRC_PATH)/scripts/hxtool -h < $< > $@,"  GEN   $@")
 
-qapi-dir := $(BUILD_DIR)/qapi-generated
+qapi-dir := qapi-generated
 qemu-ga$(EXESUF): LIBS = $(LIBS_QGA)
 qemu-ga$(EXESUF): QEMU_CFLAGS += -I $(qapi-dir)
 
commit 471fbf4ab87bc6a564d8050aa6bba242b978ea4d
Author: Frédéric Boiteux <fboiteux at free.fr>
Date:   Fri Jun 8 20:06:25 2012 +0200

    Install 'bepo' keymap already included in Qemu source
    
    The 'bepo' layout (a french dvorak-like keyboard layout) was added
    about one year ago, (see commit 2a3c633c1eb8692716220195b6d3fe78b7e411d0),
    but I missed to declare to install it.
    
    Signed-off-by: Frédéric Boiteux <fboiteux at free.fr>
    Signed-off-by: Stefan Hajnoczi <stefanha at linux.vnet.ibm.com>

diff --git a/Makefile b/Makefile
index a7281b0..277ae73 100644
--- a/Makefile
+++ b/Makefile
@@ -250,7 +250,8 @@ distclean: clean
 
 KEYMAPS=da     en-gb  et  fr     fr-ch  is  lt  modifiers  no  pt-br  sv \
 ar      de     en-us  fi  fr-be  hr     it  lv  nl         pl  ru     th \
-common  de-ch  es     fo  fr-ca  hu     ja  mk  nl-be      pt  sl     tr
+common  de-ch  es     fo  fr-ca  hu     ja  mk  nl-be      pt  sl     tr \
+bepo
 
 ifdef INSTALL_BLOBS
 BLOBS=bios.bin sgabios.bin vgabios.bin vgabios-cirrus.bin \
commit eab5fd5989a1ac48d123ccaec7346ce325b9ee77
Author: Paolo Bonzini <pbonzini at redhat.com>
Date:   Wed Jun 13 07:41:28 2012 +0200

    qemu-ga: add guest-fstrim command
    
    FITRIM is a mounted filesystem feature to discard (or "trim") blocks which
    are not in use by the filesystem. This is useful for solid-state drives
    (SSDs) and thinly-provisioned storage.  Provide access to the feature
    from the host so that filesystems can be trimmed periodically or before
    migration.
    
    Here is an example using scsi_debug:
    
        # modprobe scsi_debug lbpu=1 lbpws=1
        # sg_vpd -p0xb2 /dev/sdb
        Logical block provisioning VPD page (SBC):
          Unmap command supported (LBPU): 1
          Write same (16) with unmap bit supported (LBWS): 1
          Write same (10) with unmap bit supported (LBWS10): 0
        # mke2fs /dev/sdb
        # cat /sys/bus/pseudo/drivers/scsi_debug/map
        1-616,16257-16383
        # mount /dev/sdb /run/media/pbonzini/test
        # dd if=/dev/zero of=/run/media/pbonzini/test/file
        # cat map
        1-616,645-1588,1599-4026,4029-16383
        # rm /run/media/pbonzini/test/file
        # ./qemu-ga /dev/fd/0
        {"execute":"guest-fstrim"}
        {"return": {}}
        # cat map
        1-612
    
    Signed-off-by: Paolo Bonzini <pbonzini at redhat.com>
    Reviewed-by: Luiz Capitulino <lcapitulino at redhat.com>
    Reviewed-by: Michal Privoznik <mprivozn at redhat.com>
    Signed-off-by: Michael Roth <mdroth at linux.vnet.ibm.com>

diff --git a/qapi-schema-guest.json b/qapi-schema-guest.json
index d4055d2..d955cf1 100644
--- a/qapi-schema-guest.json
+++ b/qapi-schema-guest.json
@@ -351,6 +351,26 @@
   'returns': 'int' }
 
 ##
+# @guest-fstrim:
+#
+# Discard (or "trim") blocks which are not in use by the filesystem.
+#
+# @minimum:
+#       Minimum contiguous free range to discard, in bytes. Free ranges
+#       smaller than this may be ignored (this is a hint and the guest
+#       may not respect it).  By increasing this value, the fstrim
+#       operation will complete more quickly for filesystems with badly
+#       fragmented free space, although not all blocks will be discarded.
+#       The default value is zero, meaning "discard every free block".
+#
+# Returns: Nothing.
+#
+# Since: 1.2
+##
+{ 'command': 'guest-fstrim',
+  'data': { '*minimum': 'int' } }
+
+##
 # @guest-suspend-disk
 #
 # Suspend guest to disk.
diff --git a/qga/commands-posix.c b/qga/commands-posix.c
index b1a7ce6..ce90421 100644
--- a/qga/commands-posix.c
+++ b/qga/commands-posix.c
@@ -38,9 +38,12 @@ extern char **environ;
 #include <sys/socket.h>
 #include <net/if.h>
 
-#if defined(__linux__) && defined(FIFREEZE)
+#ifdef FIFREEZE
 #define CONFIG_FSFREEZE
 #endif
+#ifdef FITRIM
+#define CONFIG_FSTRIM
+#endif
 #endif
 
 void qmp_guest_shutdown(bool has_mode, const char *mode, Error **err)
@@ -312,8 +315,7 @@ static void guest_file_init(void)
 /* linux-specific implementations. avoid this if at all possible. */
 #if defined(__linux__)
 
-#if defined(CONFIG_FSFREEZE)
-
+#if defined(CONFIG_FSFREEZE) || defined(CONFIG_FSTRIM)
 typedef struct FsMount {
     char *dirname;
     char *devtype;
@@ -378,6 +380,9 @@ static int build_fs_mount_list(FsMountList *mounts)
 
     return 0;
 }
+#endif
+
+#if defined(CONFIG_FSFREEZE)
 
 /*
  * Return status of freeze/thaw
@@ -525,6 +530,65 @@ static void guest_fsfreeze_cleanup(void)
 }
 #endif /* CONFIG_FSFREEZE */
 
+#if defined(CONFIG_FSTRIM)
+/*
+ * Walk list of mounted file systems in the guest, and trim them.
+ */
+void qmp_guest_fstrim(bool has_minimum, int64_t minimum, Error **err)
+{
+    int ret = 0;
+    FsMountList mounts;
+    struct FsMount *mount;
+    int fd;
+    char err_msg[512];
+    struct fstrim_range r = {
+        .start = 0,
+        .len = -1,
+        .minlen = has_minimum ? minimum : 0,
+    };
+
+    slog("guest-fstrim called");
+
+    QTAILQ_INIT(&mounts);
+    ret = build_fs_mount_list(&mounts);
+    if (ret < 0) {
+        return;
+    }
+
+    QTAILQ_FOREACH(mount, &mounts, next) {
+        fd = qemu_open(mount->dirname, O_RDONLY);
+        if (fd == -1) {
+            sprintf(err_msg, "failed to open %s, %s", mount->dirname,
+                    strerror(errno));
+            error_set(err, QERR_QGA_COMMAND_FAILED, err_msg);
+            goto error;
+        }
+
+        /* We try to cull filesytems we know won't work in advance, but other
+         * filesytems may not implement fstrim for less obvious reasons.  These
+         * will report EOPNOTSUPP; we simply ignore these errors.  Any other
+         * error means an unexpected error, so return it in those cases.  In
+         * some other cases ENOTTY will be reported (e.g. CD-ROMs).
+         */
+        ret = ioctl(fd, FITRIM, &r);
+        if (ret == -1) {
+            if (errno != ENOTTY && errno != EOPNOTSUPP) {
+                sprintf(err_msg, "failed to trim %s, %s",
+                        mount->dirname, strerror(errno));
+                error_set(err, QERR_QGA_COMMAND_FAILED, err_msg);
+                close(fd);
+                goto error;
+            }
+        }
+        close(fd);
+    }
+
+error:
+    free_fs_mount_list(&mounts);
+}
+#endif /* CONFIG_FSTRIM */
+
+
 #define LINUX_SYS_STATE_FILE "/sys/power/state"
 #define SUSPEND_SUPPORTED 0
 #define SUSPEND_NOT_SUPPORTED 1
@@ -918,7 +982,15 @@ int64_t qmp_guest_fsfreeze_thaw(Error **err)
 
     return 0;
 }
+#endif /* CONFIG_FSFREEZE */
+
+#if !defined(CONFIG_FSTRIM)
+void qmp_guest_fstrim(bool has_minimum, int64_t minimum, Error **err)
+{
+    error_set(err, QERR_UNSUPPORTED);
 
+    return;
+}
 #endif
 
 /* register init/cleanup routines for stateful command groups */
diff --git a/qga/commands-win32.c b/qga/commands-win32.c
index eb8d140..54bc546 100644
--- a/qga/commands-win32.c
+++ b/qga/commands-win32.c
@@ -173,6 +173,17 @@ int64_t qmp_guest_fsfreeze_thaw(Error **err)
     return 0;
 }
 
+/*
+ * Walk list of mounted file systems in the guest, and discard unused
+ * areas.
+ */
+void qmp_guest_fstrim(bool has_minimum, int64_t minimum, Error **err)
+{
+    error_set(err, QERR_UNSUPPORTED);
+
+    return;
+}
+
 typedef enum {
     GUEST_SUSPEND_MODE_DISK,
     GUEST_SUSPEND_MODE_RAM
commit af02203fbe03f0634fea26a6e30febdeed14ede9
Author: Paolo Bonzini <pbonzini at redhat.com>
Date:   Wed Jun 13 07:41:27 2012 +0200

    qemu-ga: make names more generic for mount list functions
    
    We will use these functions and types for more than FSFREEZE, so rename them.
    
    Signed-off-by: Paolo Bonzini <pbonzini at redhat.com>
    Reviewed-by: Luiz Capitulino <lcapitulino at redhat.com>
    Reviewed-by: Michal Privoznik <mprivozn at redhat.com>
    Signed-off-by: Michael Roth <mdroth at linux.vnet.ibm.com>

diff --git a/qga/commands-posix.c b/qga/commands-posix.c
index 00d035d..b1a7ce6 100644
--- a/qga/commands-posix.c
+++ b/qga/commands-posix.c
@@ -314,17 +314,17 @@ static void guest_file_init(void)
 
 #if defined(CONFIG_FSFREEZE)
 
-typedef struct GuestFsfreezeMount {
+typedef struct FsMount {
     char *dirname;
     char *devtype;
-    QTAILQ_ENTRY(GuestFsfreezeMount) next;
-} GuestFsfreezeMount;
+    QTAILQ_ENTRY(FsMount) next;
+} FsMount;
 
-typedef QTAILQ_HEAD(, GuestFsfreezeMount) GuestFsfreezeMountList;
+typedef QTAILQ_HEAD(, FsMount) FsMountList;
 
-static void guest_fsfreeze_free_mount_list(GuestFsfreezeMountList *mounts)
+static void free_fs_mount_list(FsMountList *mounts)
 {
-     GuestFsfreezeMount *mount, *temp;
+     FsMount *mount, *temp;
 
      if (!mounts) {
          return;
@@ -341,10 +341,10 @@ static void guest_fsfreeze_free_mount_list(GuestFsfreezeMountList *mounts)
 /*
  * Walk the mount table and build a list of local file systems
  */
-static int guest_fsfreeze_build_mount_list(GuestFsfreezeMountList *mounts)
+static int build_fs_mount_list(FsMountList *mounts)
 {
     struct mntent *ment;
-    GuestFsfreezeMount *mount;
+    FsMount *mount;
     char const *mtab = "/proc/self/mounts";
     FILE *fp;
 
@@ -367,7 +367,7 @@ static int guest_fsfreeze_build_mount_list(GuestFsfreezeMountList *mounts)
             continue;
         }
 
-        mount = g_malloc0(sizeof(GuestFsfreezeMount));
+        mount = g_malloc0(sizeof(FsMount));
         mount->dirname = g_strdup(ment->mnt_dir);
         mount->devtype = g_strdup(ment->mnt_type);
 
@@ -398,15 +398,15 @@ GuestFsfreezeStatus qmp_guest_fsfreeze_status(Error **err)
 int64_t qmp_guest_fsfreeze_freeze(Error **err)
 {
     int ret = 0, i = 0;
-    GuestFsfreezeMountList mounts;
-    struct GuestFsfreezeMount *mount;
+    FsMountList mounts;
+    struct FsMount *mount;
     int fd;
     char err_msg[512];
 
     slog("guest-fsfreeze called");
 
     QTAILQ_INIT(&mounts);
-    ret = guest_fsfreeze_build_mount_list(&mounts);
+    ret = build_fs_mount_list(&mounts);
     if (ret < 0) {
         return ret;
     }
@@ -447,11 +447,11 @@ int64_t qmp_guest_fsfreeze_freeze(Error **err)
         close(fd);
     }
 
-    guest_fsfreeze_free_mount_list(&mounts);
+    free_fs_mount_list(&mounts);
     return i;
 
 error:
-    guest_fsfreeze_free_mount_list(&mounts);
+    free_fs_mount_list(&mounts);
     qmp_guest_fsfreeze_thaw(NULL);
     return 0;
 }
@@ -462,12 +462,12 @@ error:
 int64_t qmp_guest_fsfreeze_thaw(Error **err)
 {
     int ret;
-    GuestFsfreezeMountList mounts;
-    GuestFsfreezeMount *mount;
+    FsMountList mounts;
+    FsMount *mount;
     int fd, i = 0, logged;
 
     QTAILQ_INIT(&mounts);
-    ret = guest_fsfreeze_build_mount_list(&mounts);
+    ret = build_fs_mount_list(&mounts);
     if (ret) {
         error_set(err, QERR_QGA_COMMAND_FAILED,
                   "failed to enumerate filesystems");
@@ -507,7 +507,7 @@ int64_t qmp_guest_fsfreeze_thaw(Error **err)
     }
 
     ga_unset_frozen(ga_state);
-    guest_fsfreeze_free_mount_list(&mounts);
+    free_fs_mount_list(&mounts);
     return i;
 }
 
commit 3854ca577dad92c4fe97b4a6ebce360e25407af7
Author: Jiang Yunhong <yunhong.jiang at intel.com>
Date:   Thu Jun 21 15:42:35 2012 +0000

    Introduce Xen PCI Passthrough, MSI
    
    A more complete history can be found here:
    git://xenbits.xensource.com/qemu-xen-unstable.git
    
    Signed-off-by: Jiang Yunhong <yunhong.jiang at intel.com>
    Signed-off-by: Shan Haitao <haitao.shan at intel.com>
    Signed-off-by: Anthony PERARD <anthony.perard at citrix.com>
    Acked-by: Stefano Stabellini <stefano.stabellini at eu.citrix.com>

diff --git a/hw/i386/Makefile.objs b/hw/i386/Makefile.objs
index 054f409..8c764bb 100644
--- a/hw/i386/Makefile.objs
+++ b/hw/i386/Makefile.objs
@@ -8,7 +8,7 @@ obj-y += pc_piix.o
 obj-y += pc_sysfw.o
 obj-$(CONFIG_XEN) += xen_platform.o xen_apic.o
 obj-$(CONFIG_XEN_PCI_PASSTHROUGH) += xen-host-pci-device.o
-obj-$(CONFIG_XEN_PCI_PASSTHROUGH) += xen_pt.o xen_pt_config_init.o
+obj-$(CONFIG_XEN_PCI_PASSTHROUGH) += xen_pt.o xen_pt_config_init.o xen_pt_msi.o
 obj-y += kvm/
 obj-$(CONFIG_SPICE) += qxl.o qxl-logger.o qxl-render.o
 
diff --git a/hw/xen_pt.c b/hw/xen_pt.c
index 92ad0fa..3b6d186 100644
--- a/hw/xen_pt.c
+++ b/hw/xen_pt.c
@@ -36,6 +36,20 @@
  *
  *     Write '1'
  *       - Set real bit to '1'.
+ *
+ * MSI interrupt:
+ *   Initialize MSI register(xen_pt_msi_setup, xen_pt_msi_update)
+ *     Bind MSI(xc_domain_update_msi_irq)
+ *       <fail>
+ *         - Unmap MSI.
+ *         - Set dev->msi->pirq to '-1'.
+ *
+ * MSI-X interrupt:
+ *   Initialize MSI-X register(xen_pt_msix_update_one)
+ *     Bind MSI-X(xc_domain_update_msi_irq)
+ *       <fail>
+ *         - Unmap MSI-X.
+ *         - Set entry->pirq to '-1'.
  */
 
 #include <sys/ioctl.h>
@@ -534,7 +548,15 @@ static void xen_pt_region_update(XenPCIPassthroughState *s,
     };
 
     bar = xen_pt_bar_from_region(s, mr);
-    if (bar == -1) {
+    if (bar == -1 && (!s->msix || &s->msix->mmio != mr)) {
+        return;
+    }
+
+    if (s->msix && &s->msix->mmio == mr) {
+        if (adding) {
+            s->msix->mmio_base_addr = sec->offset_within_address_space;
+            rc = xen_pt_msix_update_remap(s, s->msix->bar_index);
+        }
         return;
     }
 
@@ -764,6 +786,13 @@ static int xen_pt_unregister_device(PCIDevice *d)
         }
     }
 
+    if (s->msi) {
+        xen_pt_msi_disable(s);
+    }
+    if (s->msix) {
+        xen_pt_msix_disable(s);
+    }
+
     if (machine_irq) {
         xen_pt_mapped_machine_irq[machine_irq]--;
 
diff --git a/hw/xen_pt.h b/hw/xen_pt.h
index 4b76073..41904ec 100644
--- a/hw/xen_pt.h
+++ b/hw/xen_pt.h
@@ -160,6 +160,36 @@ typedef struct XenPTRegGroup {
 
 
 #define XEN_PT_UNASSIGNED_PIRQ (-1)
+typedef struct XenPTMSI {
+    uint16_t flags;
+    uint32_t addr_lo;  /* guest message address */
+    uint32_t addr_hi;  /* guest message upper address */
+    uint16_t data;     /* guest message data */
+    uint32_t ctrl_offset; /* saved control offset */
+    int pirq;          /* guest pirq corresponding */
+    bool initialized;  /* when guest MSI is initialized */
+    bool mapped;       /* when pirq is mapped */
+} XenPTMSI;
+
+typedef struct XenPTMSIXEntry {
+    int pirq;
+    uint64_t addr;
+    uint32_t data;
+    uint32_t vector_ctrl;
+    bool updated; /* indicate whether MSI ADDR or DATA is updated */
+} XenPTMSIXEntry;
+typedef struct XenPTMSIX {
+    uint32_t ctrl_offset;
+    bool enabled;
+    int total_entries;
+    int bar_index;
+    uint64_t table_base;
+    uint32_t table_offset_adjust; /* page align mmap */
+    uint64_t mmio_base_addr;
+    MemoryRegion mmio;
+    void *phys_iomem_base;
+    XenPTMSIXEntry msix_entry[0];
+} XenPTMSIX;
 
 struct XenPCIPassthroughState {
     PCIDevice dev;
@@ -172,6 +202,9 @@ struct XenPCIPassthroughState {
 
     uint32_t machine_irq;
 
+    XenPTMSI *msi;
+    XenPTMSIX *msix;
+
     MemoryRegion bar[PCI_NUM_REGIONS - 1];
     MemoryRegion rom;
 
@@ -247,4 +280,22 @@ static inline uint8_t xen_pt_pci_intx(XenPCIPassthroughState *s)
     return r_val;
 }
 
+/* MSI/MSI-X */
+int xen_pt_msi_set_enable(XenPCIPassthroughState *s, bool en);
+int xen_pt_msi_setup(XenPCIPassthroughState *s);
+int xen_pt_msi_update(XenPCIPassthroughState *d);
+void xen_pt_msi_disable(XenPCIPassthroughState *s);
+
+int xen_pt_msix_init(XenPCIPassthroughState *s, uint32_t base);
+void xen_pt_msix_delete(XenPCIPassthroughState *s);
+int xen_pt_msix_update(XenPCIPassthroughState *s);
+int xen_pt_msix_update_remap(XenPCIPassthroughState *s, int bar_index);
+void xen_pt_msix_disable(XenPCIPassthroughState *s);
+
+static inline bool xen_pt_has_msix_mapping(XenPCIPassthroughState *s, int bar)
+{
+    return s->msix && s->msix->bar_index == bar;
+}
+
+
 #endif /* !XEN_PT_H */
diff --git a/hw/xen_pt_config_init.c b/hw/xen_pt_config_init.c
index 1d97876..00eb3d9 100644
--- a/hw/xen_pt_config_init.c
+++ b/hw/xen_pt_config_init.c
@@ -1022,6 +1022,410 @@ static XenPTRegInfo xen_pt_emu_reg_pm[] = {
 };
 
 
+/********************************
+ * MSI Capability
+ */
+
+/* Helper */
+static bool xen_pt_msgdata_check_type(uint32_t offset, uint16_t flags)
+{
+    /* check the offset whether matches the type or not */
+    bool is_32 = (offset == PCI_MSI_DATA_32) && !(flags & PCI_MSI_FLAGS_64BIT);
+    bool is_64 = (offset == PCI_MSI_DATA_64) &&  (flags & PCI_MSI_FLAGS_64BIT);
+    return is_32 || is_64;
+}
+
+/* Message Control register */
+static int xen_pt_msgctrl_reg_init(XenPCIPassthroughState *s,
+                                   XenPTRegInfo *reg, uint32_t real_offset,
+                                   uint32_t *data)
+{
+    PCIDevice *d = &s->dev;
+    XenPTMSI *msi = s->msi;
+    uint16_t reg_field = 0;
+
+    /* use I/O device register's value as initial value */
+    reg_field = pci_get_word(d->config + real_offset);
+
+    if (reg_field & PCI_MSI_FLAGS_ENABLE) {
+        XEN_PT_LOG(&s->dev, "MSI already enabled, disabling it first\n");
+        xen_host_pci_set_word(&s->real_device, real_offset,
+                              reg_field & ~PCI_MSI_FLAGS_ENABLE);
+    }
+    msi->flags |= reg_field;
+    msi->ctrl_offset = real_offset;
+    msi->initialized = false;
+    msi->mapped = false;
+
+    *data = reg->init_val;
+    return 0;
+}
+static int xen_pt_msgctrl_reg_write(XenPCIPassthroughState *s,
+                                    XenPTReg *cfg_entry, uint16_t *val,
+                                    uint16_t dev_value, uint16_t valid_mask)
+{
+    XenPTRegInfo *reg = cfg_entry->reg;
+    XenPTMSI *msi = s->msi;
+    uint16_t writable_mask = 0;
+    uint16_t throughable_mask = 0;
+    uint16_t raw_val;
+
+    /* Currently no support for multi-vector */
+    if (*val & PCI_MSI_FLAGS_QSIZE) {
+        XEN_PT_WARN(&s->dev, "Tries to set more than 1 vector ctrl %x\n", *val);
+    }
+
+    /* modify emulate register */
+    writable_mask = reg->emu_mask & ~reg->ro_mask & valid_mask;
+    cfg_entry->data = XEN_PT_MERGE_VALUE(*val, cfg_entry->data, writable_mask);
+    msi->flags |= cfg_entry->data & ~PCI_MSI_FLAGS_ENABLE;
+
+    /* create value for writing to I/O device register */
+    raw_val = *val;
+    throughable_mask = ~reg->emu_mask & valid_mask;
+    *val = XEN_PT_MERGE_VALUE(*val, dev_value, throughable_mask);
+
+    /* update MSI */
+    if (raw_val & PCI_MSI_FLAGS_ENABLE) {
+        /* setup MSI pirq for the first time */
+        if (!msi->initialized) {
+            /* Init physical one */
+            XEN_PT_LOG(&s->dev, "setup MSI\n");
+            if (xen_pt_msi_setup(s)) {
+                /* We do not broadcast the error to the framework code, so
+                 * that MSI errors are contained in MSI emulation code and
+                 * QEMU can go on running.
+                 * Guest MSI would be actually not working.
+                 */
+                *val &= ~PCI_MSI_FLAGS_ENABLE;
+                XEN_PT_WARN(&s->dev, "Can not map MSI.\n");
+                return 0;
+            }
+            if (xen_pt_msi_update(s)) {
+                *val &= ~PCI_MSI_FLAGS_ENABLE;
+                XEN_PT_WARN(&s->dev, "Can not bind MSI\n");
+                return 0;
+            }
+            msi->initialized = true;
+            msi->mapped = true;
+        }
+        msi->flags |= PCI_MSI_FLAGS_ENABLE;
+    } else {
+        msi->flags &= ~PCI_MSI_FLAGS_ENABLE;
+    }
+
+    /* pass through MSI_ENABLE bit */
+    *val &= ~PCI_MSI_FLAGS_ENABLE;
+    *val |= raw_val & PCI_MSI_FLAGS_ENABLE;
+
+    return 0;
+}
+
+/* initialize Message Upper Address register */
+static int xen_pt_msgaddr64_reg_init(XenPCIPassthroughState *s,
+                                     XenPTRegInfo *reg, uint32_t real_offset,
+                                     uint32_t *data)
+{
+    /* no need to initialize in case of 32 bit type */
+    if (!(s->msi->flags & PCI_MSI_FLAGS_64BIT)) {
+        *data = XEN_PT_INVALID_REG;
+    } else {
+        *data = reg->init_val;
+    }
+
+    return 0;
+}
+/* this function will be called twice (for 32 bit and 64 bit type) */
+/* initialize Message Data register */
+static int xen_pt_msgdata_reg_init(XenPCIPassthroughState *s,
+                                   XenPTRegInfo *reg, uint32_t real_offset,
+                                   uint32_t *data)
+{
+    uint32_t flags = s->msi->flags;
+    uint32_t offset = reg->offset;
+
+    /* check the offset whether matches the type or not */
+    if (xen_pt_msgdata_check_type(offset, flags)) {
+        *data = reg->init_val;
+    } else {
+        *data = XEN_PT_INVALID_REG;
+    }
+    return 0;
+}
+
+/* write Message Address register */
+static int xen_pt_msgaddr32_reg_write(XenPCIPassthroughState *s,
+                                      XenPTReg *cfg_entry, uint32_t *val,
+                                      uint32_t dev_value, uint32_t valid_mask)
+{
+    XenPTRegInfo *reg = cfg_entry->reg;
+    uint32_t writable_mask = 0;
+    uint32_t throughable_mask = 0;
+    uint32_t old_addr = cfg_entry->data;
+
+    /* modify emulate register */
+    writable_mask = reg->emu_mask & ~reg->ro_mask & valid_mask;
+    cfg_entry->data = XEN_PT_MERGE_VALUE(*val, cfg_entry->data, writable_mask);
+    s->msi->addr_lo = cfg_entry->data;
+
+    /* create value for writing to I/O device register */
+    throughable_mask = ~reg->emu_mask & valid_mask;
+    *val = XEN_PT_MERGE_VALUE(*val, dev_value, throughable_mask);
+
+    /* update MSI */
+    if (cfg_entry->data != old_addr) {
+        if (s->msi->mapped) {
+            xen_pt_msi_update(s);
+        }
+    }
+
+    return 0;
+}
+/* write Message Upper Address register */
+static int xen_pt_msgaddr64_reg_write(XenPCIPassthroughState *s,
+                                      XenPTReg *cfg_entry, uint32_t *val,
+                                      uint32_t dev_value, uint32_t valid_mask)
+{
+    XenPTRegInfo *reg = cfg_entry->reg;
+    uint32_t writable_mask = 0;
+    uint32_t throughable_mask = 0;
+    uint32_t old_addr = cfg_entry->data;
+
+    /* check whether the type is 64 bit or not */
+    if (!(s->msi->flags & PCI_MSI_FLAGS_64BIT)) {
+        XEN_PT_ERR(&s->dev,
+                   "Can't write to the upper address without 64 bit support\n");
+        return -1;
+    }
+
+    /* modify emulate register */
+    writable_mask = reg->emu_mask & ~reg->ro_mask & valid_mask;
+    cfg_entry->data = XEN_PT_MERGE_VALUE(*val, cfg_entry->data, writable_mask);
+    /* update the msi_info too */
+    s->msi->addr_hi = cfg_entry->data;
+
+    /* create value for writing to I/O device register */
+    throughable_mask = ~reg->emu_mask & valid_mask;
+    *val = XEN_PT_MERGE_VALUE(*val, dev_value, throughable_mask);
+
+    /* update MSI */
+    if (cfg_entry->data != old_addr) {
+        if (s->msi->mapped) {
+            xen_pt_msi_update(s);
+        }
+    }
+
+    return 0;
+}
+
+
+/* this function will be called twice (for 32 bit and 64 bit type) */
+/* write Message Data register */
+static int xen_pt_msgdata_reg_write(XenPCIPassthroughState *s,
+                                    XenPTReg *cfg_entry, uint16_t *val,
+                                    uint16_t dev_value, uint16_t valid_mask)
+{
+    XenPTRegInfo *reg = cfg_entry->reg;
+    XenPTMSI *msi = s->msi;
+    uint16_t writable_mask = 0;
+    uint16_t throughable_mask = 0;
+    uint16_t old_data = cfg_entry->data;
+    uint32_t offset = reg->offset;
+
+    /* check the offset whether matches the type or not */
+    if (!xen_pt_msgdata_check_type(offset, msi->flags)) {
+        /* exit I/O emulator */
+        XEN_PT_ERR(&s->dev, "the offset does not match the 32/64 bit type!\n");
+        return -1;
+    }
+
+    /* modify emulate register */
+    writable_mask = reg->emu_mask & ~reg->ro_mask & valid_mask;
+    cfg_entry->data = XEN_PT_MERGE_VALUE(*val, cfg_entry->data, writable_mask);
+    /* update the msi_info too */
+    msi->data = cfg_entry->data;
+
+    /* create value for writing to I/O device register */
+    throughable_mask = ~reg->emu_mask & valid_mask;
+    *val = XEN_PT_MERGE_VALUE(*val, dev_value, throughable_mask);
+
+    /* update MSI */
+    if (cfg_entry->data != old_data) {
+        if (msi->mapped) {
+            xen_pt_msi_update(s);
+        }
+    }
+
+    return 0;
+}
+
+/* MSI Capability Structure reg static infomation table */
+static XenPTRegInfo xen_pt_emu_reg_msi[] = {
+    /* Next Pointer reg */
+    {
+        .offset     = PCI_CAP_LIST_NEXT,
+        .size       = 1,
+        .init_val   = 0x00,
+        .ro_mask    = 0xFF,
+        .emu_mask   = 0xFF,
+        .init       = xen_pt_ptr_reg_init,
+        .u.b.read   = xen_pt_byte_reg_read,
+        .u.b.write  = xen_pt_byte_reg_write,
+    },
+    /* Message Control reg */
+    {
+        .offset     = PCI_MSI_FLAGS,
+        .size       = 2,
+        .init_val   = 0x0000,
+        .ro_mask    = 0xFF8E,
+        .emu_mask   = 0x007F,
+        .init       = xen_pt_msgctrl_reg_init,
+        .u.w.read   = xen_pt_word_reg_read,
+        .u.w.write  = xen_pt_msgctrl_reg_write,
+    },
+    /* Message Address reg */
+    {
+        .offset     = PCI_MSI_ADDRESS_LO,
+        .size       = 4,
+        .init_val   = 0x00000000,
+        .ro_mask    = 0x00000003,
+        .emu_mask   = 0xFFFFFFFF,
+        .no_wb      = 1,
+        .init       = xen_pt_common_reg_init,
+        .u.dw.read  = xen_pt_long_reg_read,
+        .u.dw.write = xen_pt_msgaddr32_reg_write,
+    },
+    /* Message Upper Address reg (if PCI_MSI_FLAGS_64BIT set) */
+    {
+        .offset     = PCI_MSI_ADDRESS_HI,
+        .size       = 4,
+        .init_val   = 0x00000000,
+        .ro_mask    = 0x00000000,
+        .emu_mask   = 0xFFFFFFFF,
+        .no_wb      = 1,
+        .init       = xen_pt_msgaddr64_reg_init,
+        .u.dw.read  = xen_pt_long_reg_read,
+        .u.dw.write = xen_pt_msgaddr64_reg_write,
+    },
+    /* Message Data reg (16 bits of data for 32-bit devices) */
+    {
+        .offset     = PCI_MSI_DATA_32,
+        .size       = 2,
+        .init_val   = 0x0000,
+        .ro_mask    = 0x0000,
+        .emu_mask   = 0xFFFF,
+        .no_wb      = 1,
+        .init       = xen_pt_msgdata_reg_init,
+        .u.w.read   = xen_pt_word_reg_read,
+        .u.w.write  = xen_pt_msgdata_reg_write,
+    },
+    /* Message Data reg (16 bits of data for 64-bit devices) */
+    {
+        .offset     = PCI_MSI_DATA_64,
+        .size       = 2,
+        .init_val   = 0x0000,
+        .ro_mask    = 0x0000,
+        .emu_mask   = 0xFFFF,
+        .no_wb      = 1,
+        .init       = xen_pt_msgdata_reg_init,
+        .u.w.read   = xen_pt_word_reg_read,
+        .u.w.write  = xen_pt_msgdata_reg_write,
+    },
+    {
+        .size = 0,
+    },
+};
+
+
+/**************************************
+ * MSI-X Capability
+ */
+
+/* Message Control register for MSI-X */
+static int xen_pt_msixctrl_reg_init(XenPCIPassthroughState *s,
+                                    XenPTRegInfo *reg, uint32_t real_offset,
+                                    uint32_t *data)
+{
+    PCIDevice *d = &s->dev;
+    uint16_t reg_field = 0;
+
+    /* use I/O device register's value as initial value */
+    reg_field = pci_get_word(d->config + real_offset);
+
+    if (reg_field & PCI_MSIX_FLAGS_ENABLE) {
+        XEN_PT_LOG(d, "MSIX already enabled, disabling it first\n");
+        xen_host_pci_set_word(&s->real_device, real_offset,
+                              reg_field & ~PCI_MSIX_FLAGS_ENABLE);
+    }
+
+    s->msix->ctrl_offset = real_offset;
+
+    *data = reg->init_val;
+    return 0;
+}
+static int xen_pt_msixctrl_reg_write(XenPCIPassthroughState *s,
+                                     XenPTReg *cfg_entry, uint16_t *val,
+                                     uint16_t dev_value, uint16_t valid_mask)
+{
+    XenPTRegInfo *reg = cfg_entry->reg;
+    uint16_t writable_mask = 0;
+    uint16_t throughable_mask = 0;
+    int debug_msix_enabled_old;
+
+    /* modify emulate register */
+    writable_mask = reg->emu_mask & ~reg->ro_mask & valid_mask;
+    cfg_entry->data = XEN_PT_MERGE_VALUE(*val, cfg_entry->data, writable_mask);
+
+    /* create value for writing to I/O device register */
+    throughable_mask = ~reg->emu_mask & valid_mask;
+    *val = XEN_PT_MERGE_VALUE(*val, dev_value, throughable_mask);
+
+    /* update MSI-X */
+    if ((*val & PCI_MSIX_FLAGS_ENABLE)
+        && !(*val & PCI_MSIX_FLAGS_MASKALL)) {
+        xen_pt_msix_update(s);
+    }
+
+    debug_msix_enabled_old = s->msix->enabled;
+    s->msix->enabled = !!(*val & PCI_MSIX_FLAGS_ENABLE);
+    if (s->msix->enabled != debug_msix_enabled_old) {
+        XEN_PT_LOG(&s->dev, "%s MSI-X\n",
+                   s->msix->enabled ? "enable" : "disable");
+    }
+
+    return 0;
+}
+
+/* MSI-X Capability Structure reg static infomation table */
+static XenPTRegInfo xen_pt_emu_reg_msix[] = {
+    /* Next Pointer reg */
+    {
+        .offset     = PCI_CAP_LIST_NEXT,
+        .size       = 1,
+        .init_val   = 0x00,
+        .ro_mask    = 0xFF,
+        .emu_mask   = 0xFF,
+        .init       = xen_pt_ptr_reg_init,
+        .u.b.read   = xen_pt_byte_reg_read,
+        .u.b.write  = xen_pt_byte_reg_write,
+    },
+    /* Message Control reg */
+    {
+        .offset     = PCI_MSI_FLAGS,
+        .size       = 2,
+        .init_val   = 0x0000,
+        .ro_mask    = 0x3FFF,
+        .emu_mask   = 0x0000,
+        .init       = xen_pt_msixctrl_reg_init,
+        .u.w.read   = xen_pt_word_reg_read,
+        .u.w.write  = xen_pt_msixctrl_reg_write,
+    },
+    {
+        .size = 0,
+    },
+};
+
+
 /****************************
  * Capabilities
  */
@@ -1115,6 +1519,49 @@ static int xen_pt_pcie_size_init(XenPCIPassthroughState *s,
     *size = pcie_size;
     return 0;
 }
+/* get MSI Capability Structure register group size */
+static int xen_pt_msi_size_init(XenPCIPassthroughState *s,
+                                const XenPTRegGroupInfo *grp_reg,
+                                uint32_t base_offset, uint8_t *size)
+{
+    PCIDevice *d = &s->dev;
+    uint16_t msg_ctrl = 0;
+    uint8_t msi_size = 0xa;
+
+    msg_ctrl = pci_get_word(d->config + (base_offset + PCI_MSI_FLAGS));
+
+    /* check if 64-bit address is capable of per-vector masking */
+    if (msg_ctrl & PCI_MSI_FLAGS_64BIT) {
+        msi_size += 4;
+    }
+    if (msg_ctrl & PCI_MSI_FLAGS_MASKBIT) {
+        msi_size += 10;
+    }
+
+    s->msi = g_new0(XenPTMSI, 1);
+    s->msi->pirq = XEN_PT_UNASSIGNED_PIRQ;
+
+    *size = msi_size;
+    return 0;
+}
+/* get MSI-X Capability Structure register group size */
+static int xen_pt_msix_size_init(XenPCIPassthroughState *s,
+                                 const XenPTRegGroupInfo *grp_reg,
+                                 uint32_t base_offset, uint8_t *size)
+{
+    int rc = 0;
+
+    rc = xen_pt_msix_init(s, base_offset);
+
+    if (rc < 0) {
+        XEN_PT_ERR(&s->dev, "Internal error: Invalid xen_pt_msix_init.\n");
+        return rc;
+    }
+
+    *size = grp_reg->grp_size;
+    return 0;
+}
+
 
 static const XenPTRegGroupInfo xen_pt_emu_reg_grps[] = {
     /* Header Type0 reg group */
@@ -1155,6 +1602,14 @@ static const XenPTRegGroupInfo xen_pt_emu_reg_grps[] = {
         .grp_size   = 0x04,
         .size_init  = xen_pt_reg_grp_size_init,
     },
+    /* MSI Capability Structure reg group */
+    {
+        .grp_id      = PCI_CAP_ID_MSI,
+        .grp_type    = XEN_PT_GRP_TYPE_EMU,
+        .grp_size    = 0xFF,
+        .size_init   = xen_pt_msi_size_init,
+        .emu_regs = xen_pt_emu_reg_msi,
+    },
     /* PCI-X Capabilities List Item reg group */
     {
         .grp_id     = PCI_CAP_ID_PCIX,
@@ -1199,6 +1654,14 @@ static const XenPTRegGroupInfo xen_pt_emu_reg_grps[] = {
         .size_init   = xen_pt_pcie_size_init,
         .emu_regs = xen_pt_emu_reg_pcie,
     },
+    /* MSI-X Capability Structure reg group */
+    {
+        .grp_id      = PCI_CAP_ID_MSIX,
+        .grp_type    = XEN_PT_GRP_TYPE_EMU,
+        .grp_size    = 0x0C,
+        .size_init   = xen_pt_msix_size_init,
+        .emu_regs = xen_pt_emu_reg_msix,
+    },
     {
         .grp_size = 0,
     },
@@ -1384,6 +1847,14 @@ void xen_pt_config_delete(XenPCIPassthroughState *s)
     struct XenPTRegGroup *reg_group, *next_grp;
     struct XenPTReg *reg, *next_reg;
 
+    /* free MSI/MSI-X info table */
+    if (s->msix) {
+        xen_pt_msix_delete(s);
+    }
+    if (s->msi) {
+        g_free(s->msi);
+    }
+
     /* free all register group entry */
     QLIST_FOREACH_SAFE(reg_group, &s->reg_grps, entries, next_grp) {
         /* free all register entry */
diff --git a/hw/xen_pt_msi.c b/hw/xen_pt_msi.c
new file mode 100644
index 0000000..2299cc7
--- /dev/null
+++ b/hw/xen_pt_msi.c
@@ -0,0 +1,620 @@
+/*
+ * Copyright (c) 2007, Intel Corporation.
+ *
+ * This work is licensed under the terms of the GNU GPL, version 2.  See
+ * the COPYING file in the top-level directory.
+ *
+ * Jiang Yunhong <yunhong.jiang at intel.com>
+ *
+ * This file implements direct PCI assignment to a HVM guest
+ */
+
+#include <sys/mman.h>
+
+#include "xen_backend.h"
+#include "xen_pt.h"
+#include "apic-msidef.h"
+
+
+#define XEN_PT_AUTO_ASSIGN -1
+
+/* shift count for gflags */
+#define XEN_PT_GFLAGS_SHIFT_DEST_ID        0
+#define XEN_PT_GFLAGS_SHIFT_RH             8
+#define XEN_PT_GFLAGS_SHIFT_DM             9
+#define XEN_PT_GFLAGSSHIFT_DELIV_MODE     12
+#define XEN_PT_GFLAGSSHIFT_TRG_MODE       15
+
+
+/*
+ * Helpers
+ */
+
+static inline uint8_t msi_vector(uint32_t data)
+{
+    return (data & MSI_DATA_VECTOR_MASK) >> MSI_DATA_VECTOR_SHIFT;
+}
+
+static inline uint8_t msi_dest_id(uint32_t addr)
+{
+    return (addr & MSI_ADDR_DEST_ID_MASK) >> MSI_ADDR_DEST_ID_SHIFT;
+}
+
+static inline uint32_t msi_ext_dest_id(uint32_t addr_hi)
+{
+    return addr_hi & 0xffffff00;
+}
+
+static uint32_t msi_gflags(uint32_t data, uint64_t addr)
+{
+    uint32_t result = 0;
+    int rh, dm, dest_id, deliv_mode, trig_mode;
+
+    rh = (addr >> MSI_ADDR_REDIRECTION_SHIFT) & 0x1;
+    dm = (addr >> MSI_ADDR_DEST_MODE_SHIFT) & 0x1;
+    dest_id = msi_dest_id(addr);
+    deliv_mode = (data >> MSI_DATA_DELIVERY_MODE_SHIFT) & 0x7;
+    trig_mode = (data >> MSI_DATA_TRIGGER_SHIFT) & 0x1;
+
+    result = dest_id | (rh << XEN_PT_GFLAGS_SHIFT_RH)
+        | (dm << XEN_PT_GFLAGS_SHIFT_DM)
+        | (deliv_mode << XEN_PT_GFLAGSSHIFT_DELIV_MODE)
+        | (trig_mode << XEN_PT_GFLAGSSHIFT_TRG_MODE);
+
+    return result;
+}
+
+static inline uint64_t msi_addr64(XenPTMSI *msi)
+{
+    return (uint64_t)msi->addr_hi << 32 | msi->addr_lo;
+}
+
+static int msi_msix_enable(XenPCIPassthroughState *s,
+                           uint32_t address,
+                           uint16_t flag,
+                           bool enable)
+{
+    uint16_t val = 0;
+
+    if (!address) {
+        return -1;
+    }
+
+    xen_host_pci_get_word(&s->real_device, address, &val);
+    if (enable) {
+        val |= flag;
+    } else {
+        val &= ~flag;
+    }
+    xen_host_pci_set_word(&s->real_device, address, val);
+    return 0;
+}
+
+static int msi_msix_setup(XenPCIPassthroughState *s,
+                          uint64_t addr,
+                          uint32_t data,
+                          int *ppirq,
+                          bool is_msix,
+                          int msix_entry,
+                          bool is_not_mapped)
+{
+    uint8_t gvec = msi_vector(data);
+    int rc = 0;
+
+    assert((!is_msix && msix_entry == 0) || is_msix);
+
+    if (gvec == 0) {
+        /* if gvec is 0, the guest is asking for a particular pirq that
+         * is passed as dest_id */
+        *ppirq = msi_ext_dest_id(addr >> 32) | msi_dest_id(addr);
+        if (!*ppirq) {
+            /* this probably identifies an misconfiguration of the guest,
+             * try the emulated path */
+            *ppirq = XEN_PT_UNASSIGNED_PIRQ;
+        } else {
+            XEN_PT_LOG(&s->dev, "requested pirq %d for MSI%s"
+                       " (vec: %#x, entry: %#x)\n",
+                       *ppirq, is_msix ? "-X" : "", gvec, msix_entry);
+        }
+    }
+
+    if (is_not_mapped) {
+        uint64_t table_base = 0;
+
+        if (is_msix) {
+            table_base = s->msix->table_base;
+        }
+
+        rc = xc_physdev_map_pirq_msi(xen_xc, xen_domid, XEN_PT_AUTO_ASSIGN,
+                                     ppirq, PCI_DEVFN(s->real_device.dev,
+                                                      s->real_device.func),
+                                     s->real_device.bus,
+                                     msix_entry, table_base);
+        if (rc) {
+            XEN_PT_ERR(&s->dev,
+                       "Mapping of MSI%s (rc: %i, vec: %#x, entry %#x)\n",
+                       is_msix ? "-X" : "", rc, gvec, msix_entry);
+            return rc;
+        }
+    }
+
+    return 0;
+}
+static int msi_msix_update(XenPCIPassthroughState *s,
+                           uint64_t addr,
+                           uint32_t data,
+                           int pirq,
+                           bool is_msix,
+                           int msix_entry,
+                           int *old_pirq)
+{
+    PCIDevice *d = &s->dev;
+    uint8_t gvec = msi_vector(data);
+    uint32_t gflags = msi_gflags(data, addr);
+    int rc = 0;
+    uint64_t table_addr = 0;
+
+    XEN_PT_LOG(d, "Updating MSI%s with pirq %d gvec %#x gflags %#x"
+               " (entry: %#x)\n",
+               is_msix ? "-X" : "", pirq, gvec, gflags, msix_entry);
+
+    if (is_msix) {
+        table_addr = s->msix->mmio_base_addr;
+    }
+
+    rc = xc_domain_update_msi_irq(xen_xc, xen_domid, gvec,
+                                  pirq, gflags, table_addr);
+
+    if (rc) {
+        XEN_PT_ERR(d, "Updating of MSI%s failed. (rc: %d)\n",
+                   is_msix ? "-X" : "", rc);
+
+        if (xc_physdev_unmap_pirq(xen_xc, xen_domid, *old_pirq)) {
+            XEN_PT_ERR(d, "Unmapping of MSI%s pirq %d failed.\n",
+                       is_msix ? "-X" : "", *old_pirq);
+        }
+        *old_pirq = XEN_PT_UNASSIGNED_PIRQ;
+    }
+    return rc;
+}
+
+static int msi_msix_disable(XenPCIPassthroughState *s,
+                            uint64_t addr,
+                            uint32_t data,
+                            int pirq,
+                            bool is_msix,
+                            bool is_binded)
+{
+    PCIDevice *d = &s->dev;
+    uint8_t gvec = msi_vector(data);
+    uint32_t gflags = msi_gflags(data, addr);
+    int rc = 0;
+
+    if (pirq == XEN_PT_UNASSIGNED_PIRQ) {
+        return 0;
+    }
+
+    if (is_binded) {
+        XEN_PT_LOG(d, "Unbind MSI%s with pirq %d, gvec %#x\n",
+                   is_msix ? "-X" : "", pirq, gvec);
+        rc = xc_domain_unbind_msi_irq(xen_xc, xen_domid, gvec, pirq, gflags);
+        if (rc) {
+            XEN_PT_ERR(d, "Unbinding of MSI%s failed. (pirq: %d, gvec: %#x)\n",
+                       is_msix ? "-X" : "", pirq, gvec);
+            return rc;
+        }
+    }
+
+    XEN_PT_LOG(d, "Unmap MSI%s pirq %d\n", is_msix ? "-X" : "", pirq);
+    rc = xc_physdev_unmap_pirq(xen_xc, xen_domid, pirq);
+    if (rc) {
+        XEN_PT_ERR(d, "Unmapping of MSI%s pirq %d failed. (rc: %i)\n",
+                   is_msix ? "-X" : "", pirq, rc);
+        return rc;
+    }
+
+    return 0;
+}
+
+/*
+ * MSI virtualization functions
+ */
+
+int xen_pt_msi_set_enable(XenPCIPassthroughState *s, bool enable)
+{
+    XEN_PT_LOG(&s->dev, "%s MSI.\n", enable ? "enabling" : "disabling");
+
+    if (!s->msi) {
+        return -1;
+    }
+
+    return msi_msix_enable(s, s->msi->ctrl_offset, PCI_MSI_FLAGS_ENABLE,
+                           enable);
+}
+
+/* setup physical msi, but don't enable it */
+int xen_pt_msi_setup(XenPCIPassthroughState *s)
+{
+    int pirq = XEN_PT_UNASSIGNED_PIRQ;
+    int rc = 0;
+    XenPTMSI *msi = s->msi;
+
+    if (msi->initialized) {
+        XEN_PT_ERR(&s->dev,
+                   "Setup physical MSI when it has been properly initialized.\n");
+        return -1;
+    }
+
+    rc = msi_msix_setup(s, msi_addr64(msi), msi->data, &pirq, false, 0, true);
+    if (rc) {
+        return rc;
+    }
+
+    if (pirq < 0) {
+        XEN_PT_ERR(&s->dev, "Invalid pirq number: %d.\n", pirq);
+        return -1;
+    }
+
+    msi->pirq = pirq;
+    XEN_PT_LOG(&s->dev, "MSI mapped with pirq %d.\n", pirq);
+
+    return 0;
+}
+
+int xen_pt_msi_update(XenPCIPassthroughState *s)
+{
+    XenPTMSI *msi = s->msi;
+    return msi_msix_update(s, msi_addr64(msi), msi->data, msi->pirq,
+                           false, 0, &msi->pirq);
+}
+
+void xen_pt_msi_disable(XenPCIPassthroughState *s)
+{
+    XenPTMSI *msi = s->msi;
+
+    if (!msi) {
+        return;
+    }
+
+    xen_pt_msi_set_enable(s, false);
+
+    msi_msix_disable(s, msi_addr64(msi), msi->data, msi->pirq, false,
+                     msi->initialized);
+
+    /* clear msi info */
+    msi->flags = 0;
+    msi->mapped = false;
+    msi->pirq = XEN_PT_UNASSIGNED_PIRQ;
+}
+
+/*
+ * MSI-X virtualization functions
+ */
+
+static int msix_set_enable(XenPCIPassthroughState *s, bool enabled)
+{
+    XEN_PT_LOG(&s->dev, "%s MSI-X.\n", enabled ? "enabling" : "disabling");
+
+    if (!s->msix) {
+        return -1;
+    }
+
+    return msi_msix_enable(s, s->msix->ctrl_offset, PCI_MSIX_FLAGS_ENABLE,
+                           enabled);
+}
+
+static int xen_pt_msix_update_one(XenPCIPassthroughState *s, int entry_nr)
+{
+    XenPTMSIXEntry *entry = NULL;
+    int pirq;
+    int rc;
+
+    if (entry_nr < 0 || entry_nr >= s->msix->total_entries) {
+        return -EINVAL;
+    }
+
+    entry = &s->msix->msix_entry[entry_nr];
+
+    if (!entry->updated) {
+        return 0;
+    }
+
+    pirq = entry->pirq;
+
+    rc = msi_msix_setup(s, entry->data, entry->data, &pirq, true, entry_nr,
+                        entry->pirq == XEN_PT_UNASSIGNED_PIRQ);
+    if (rc) {
+        return rc;
+    }
+    if (entry->pirq == XEN_PT_UNASSIGNED_PIRQ) {
+        entry->pirq = pirq;
+    }
+
+    rc = msi_msix_update(s, entry->addr, entry->data, pirq, true,
+                         entry_nr, &entry->pirq);
+
+    if (!rc) {
+        entry->updated = false;
+    }
+
+    return rc;
+}
+
+int xen_pt_msix_update(XenPCIPassthroughState *s)
+{
+    XenPTMSIX *msix = s->msix;
+    int i;
+
+    for (i = 0; i < msix->total_entries; i++) {
+        xen_pt_msix_update_one(s, i);
+    }
+
+    return 0;
+}
+
+void xen_pt_msix_disable(XenPCIPassthroughState *s)
+{
+    int i = 0;
+
+    msix_set_enable(s, false);
+
+    for (i = 0; i < s->msix->total_entries; i++) {
+        XenPTMSIXEntry *entry = &s->msix->msix_entry[i];
+
+        msi_msix_disable(s, entry->addr, entry->data, entry->pirq, true, true);
+
+        /* clear MSI-X info */
+        entry->pirq = XEN_PT_UNASSIGNED_PIRQ;
+        entry->updated = false;
+    }
+}
+
+int xen_pt_msix_update_remap(XenPCIPassthroughState *s, int bar_index)
+{
+    XenPTMSIXEntry *entry;
+    int i, ret;
+
+    if (!(s->msix && s->msix->bar_index == bar_index)) {
+        return 0;
+    }
+
+    for (i = 0; i < s->msix->total_entries; i++) {
+        entry = &s->msix->msix_entry[i];
+        if (entry->pirq != XEN_PT_UNASSIGNED_PIRQ) {
+            ret = xc_domain_unbind_pt_irq(xen_xc, xen_domid, entry->pirq,
+                                          PT_IRQ_TYPE_MSI, 0, 0, 0, 0);
+            if (ret) {
+                XEN_PT_ERR(&s->dev, "unbind MSI-X entry %d failed\n",
+                           entry->pirq);
+            }
+            entry->updated = true;
+        }
+    }
+    return xen_pt_msix_update(s);
+}
+
+static uint32_t get_entry_value(XenPTMSIXEntry *e, int offset)
+{
+    switch (offset) {
+    case PCI_MSIX_ENTRY_LOWER_ADDR:
+        return e->addr & UINT32_MAX;
+    case PCI_MSIX_ENTRY_UPPER_ADDR:
+        return e->addr >> 32;
+    case PCI_MSIX_ENTRY_DATA:
+        return e->data;
+    case PCI_MSIX_ENTRY_VECTOR_CTRL:
+        return e->vector_ctrl;
+    default:
+        return 0;
+    }
+}
+
+static void set_entry_value(XenPTMSIXEntry *e, int offset, uint32_t val)
+{
+    switch (offset) {
+    case PCI_MSIX_ENTRY_LOWER_ADDR:
+        e->addr = (e->addr & ((uint64_t)UINT32_MAX << 32)) | val;
+        break;
+    case PCI_MSIX_ENTRY_UPPER_ADDR:
+        e->addr = (uint64_t)val << 32 | (e->addr & UINT32_MAX);
+        break;
+    case PCI_MSIX_ENTRY_DATA:
+        e->data = val;
+        break;
+    case PCI_MSIX_ENTRY_VECTOR_CTRL:
+        e->vector_ctrl = val;
+        break;
+    }
+}
+
+static void pci_msix_write(void *opaque, target_phys_addr_t addr,
+                           uint64_t val, unsigned size)
+{
+    XenPCIPassthroughState *s = opaque;
+    XenPTMSIX *msix = s->msix;
+    XenPTMSIXEntry *entry;
+    int entry_nr, offset;
+
+    entry_nr = addr / PCI_MSIX_ENTRY_SIZE;
+    if (entry_nr < 0 || entry_nr >= msix->total_entries) {
+        XEN_PT_ERR(&s->dev, "asked MSI-X entry '%i' invalid!\n", entry_nr);
+        return;
+    }
+    entry = &msix->msix_entry[entry_nr];
+    offset = addr % PCI_MSIX_ENTRY_SIZE;
+
+    if (offset != PCI_MSIX_ENTRY_VECTOR_CTRL) {
+        const volatile uint32_t *vec_ctrl;
+
+        if (get_entry_value(entry, offset) == val) {
+            return;
+        }
+
+        /*
+         * If Xen intercepts the mask bit access, entry->vec_ctrl may not be
+         * up-to-date. Read from hardware directly.
+         */
+        vec_ctrl = s->msix->phys_iomem_base + entry_nr * PCI_MSIX_ENTRY_SIZE
+            + PCI_MSIX_ENTRY_VECTOR_CTRL;
+
+        if (msix->enabled && !(*vec_ctrl & PCI_MSIX_ENTRY_CTRL_MASKBIT)) {
+            XEN_PT_ERR(&s->dev, "Can't update msix entry %d since MSI-X is"
+                       " already enabled.\n", entry_nr);
+            return;
+        }
+
+        entry->updated = true;
+    }
+
+    set_entry_value(entry, offset, val);
+
+    if (offset == PCI_MSIX_ENTRY_VECTOR_CTRL) {
+        if (msix->enabled && !(val & PCI_MSIX_ENTRY_CTRL_MASKBIT)) {
+            xen_pt_msix_update_one(s, entry_nr);
+        }
+    }
+}
+
+static uint64_t pci_msix_read(void *opaque, target_phys_addr_t addr,
+                              unsigned size)
+{
+    XenPCIPassthroughState *s = opaque;
+    XenPTMSIX *msix = s->msix;
+    int entry_nr, offset;
+
+    entry_nr = addr / PCI_MSIX_ENTRY_SIZE;
+    if (entry_nr < 0) {
+        XEN_PT_ERR(&s->dev, "asked MSI-X entry '%i' invalid!\n", entry_nr);
+        return 0;
+    }
+
+    offset = addr % PCI_MSIX_ENTRY_SIZE;
+
+    if (addr < msix->total_entries * PCI_MSIX_ENTRY_SIZE) {
+        return get_entry_value(&msix->msix_entry[entry_nr], offset);
+    } else {
+        /* Pending Bit Array (PBA) */
+        return *(uint32_t *)(msix->phys_iomem_base + addr);
+    }
+}
+
+static const MemoryRegionOps pci_msix_ops = {
+    .read = pci_msix_read,
+    .write = pci_msix_write,
+    .endianness = DEVICE_NATIVE_ENDIAN,
+    .valid = {
+        .min_access_size = 4,
+        .max_access_size = 4,
+        .unaligned = false,
+    },
+};
+
+int xen_pt_msix_init(XenPCIPassthroughState *s, uint32_t base)
+{
+    uint8_t id = 0;
+    uint16_t control = 0;
+    uint32_t table_off = 0;
+    int i, total_entries, bar_index;
+    XenHostPCIDevice *hd = &s->real_device;
+    PCIDevice *d = &s->dev;
+    int fd = -1;
+    XenPTMSIX *msix = NULL;
+    int rc = 0;
+
+    rc = xen_host_pci_get_byte(hd, base + PCI_CAP_LIST_ID, &id);
+    if (rc) {
+        return rc;
+    }
+
+    if (id != PCI_CAP_ID_MSIX) {
+        XEN_PT_ERR(d, "Invalid id %#x base %#x\n", id, base);
+        return -1;
+    }
+
+    xen_host_pci_get_word(hd, base + PCI_MSIX_FLAGS, &control);
+    total_entries = control & PCI_MSIX_FLAGS_QSIZE;
+    total_entries += 1;
+
+    s->msix = g_malloc0(sizeof (XenPTMSIX)
+                        + total_entries * sizeof (XenPTMSIXEntry));
+    msix = s->msix;
+
+    msix->total_entries = total_entries;
+    for (i = 0; i < total_entries; i++) {
+        msix->msix_entry[i].pirq = XEN_PT_UNASSIGNED_PIRQ;
+    }
+
+    memory_region_init_io(&msix->mmio, &pci_msix_ops, s, "xen-pci-pt-msix",
+                          (total_entries * PCI_MSIX_ENTRY_SIZE
+                           + XC_PAGE_SIZE - 1)
+                          & XC_PAGE_MASK);
+
+    xen_host_pci_get_long(hd, base + PCI_MSIX_TABLE, &table_off);
+    bar_index = msix->bar_index = table_off & PCI_MSIX_FLAGS_BIRMASK;
+    table_off = table_off & ~PCI_MSIX_FLAGS_BIRMASK;
+    msix->table_base = s->real_device.io_regions[bar_index].base_addr;
+    XEN_PT_LOG(d, "get MSI-X table BAR base 0x%"PRIx64"\n", msix->table_base);
+
+    fd = open("/dev/mem", O_RDWR);
+    if (fd == -1) {
+        rc = -errno;
+        XEN_PT_ERR(d, "Can't open /dev/mem: %s\n", strerror(errno));
+        goto error_out;
+    }
+    XEN_PT_LOG(d, "table_off = %#x, total_entries = %d\n",
+               table_off, total_entries);
+    msix->table_offset_adjust = table_off & 0x0fff;
+    msix->phys_iomem_base =
+        mmap(NULL,
+             total_entries * PCI_MSIX_ENTRY_SIZE + msix->table_offset_adjust,
+             PROT_READ,
+             MAP_SHARED | MAP_LOCKED,
+             fd,
+             msix->table_base + table_off - msix->table_offset_adjust);
+    close(fd);
+    if (msix->phys_iomem_base == MAP_FAILED) {
+        rc = -errno;
+        XEN_PT_ERR(d, "Can't map physical MSI-X table: %s\n", strerror(errno));
+        goto error_out;
+    }
+    msix->phys_iomem_base = (char *)msix->phys_iomem_base
+        + msix->table_offset_adjust;
+
+    XEN_PT_LOG(d, "mapping physical MSI-X table to %p\n",
+               msix->phys_iomem_base);
+
+    memory_region_add_subregion_overlap(&s->bar[bar_index], table_off,
+                                        &msix->mmio,
+                                        2); /* Priority: pci default + 1 */
+
+    return 0;
+
+error_out:
+    memory_region_destroy(&msix->mmio);
+    g_free(s->msix);
+    s->msix = NULL;
+    return rc;
+}
+
+void xen_pt_msix_delete(XenPCIPassthroughState *s)
+{
+    XenPTMSIX *msix = s->msix;
+
+    if (!msix) {
+        return;
+    }
+
+    /* unmap the MSI-X memory mapped register area */
+    if (msix->phys_iomem_base) {
+        XEN_PT_LOG(&s->dev, "unmapping physical MSI-X table from %p\n",
+                   msix->phys_iomem_base);
+        munmap(msix->phys_iomem_base, msix->total_entries * PCI_MSIX_ENTRY_SIZE
+               + msix->table_offset_adjust);
+    }
+
+    memory_region_del_subregion(&s->bar[msix->bar_index], &msix->mmio);
+    memory_region_destroy(&msix->mmio);
+
+    g_free(s->msix);
+    s->msix = NULL;
+}
commit 9886c23aed27ceaa6d04ad2d72a21633d014eb2e
Author: Anthony PERARD <anthony.perard at citrix.com>
Date:   Thu Jun 21 15:41:28 2012 +0000

    Introduce apic-msidef.h
    
    This patch move the msi definition from apic.c to apic-msidef.h. So it can be
    used also by other .c files.
    
    Signed-off-by: Anthony PERARD <anthony.perard at citrix.com>
    Acked-by: Stefano Stabellini <stefano.stabellini at eu.citrix.com>
    Acked-by: Michael S. Tsirkin <mst at redhat.com>

diff --git a/hw/apic-msidef.h b/hw/apic-msidef.h
new file mode 100644
index 0000000..6e2eb71
--- /dev/null
+++ b/hw/apic-msidef.h
@@ -0,0 +1,30 @@
+#ifndef HW_APIC_MSIDEF_H
+#define HW_APIC_MSIDEF_H
+
+/*
+ * Intel APIC constants: from include/asm/msidef.h
+ */
+
+/*
+ * Shifts for MSI data
+ */
+
+#define MSI_DATA_VECTOR_SHIFT           0
+#define  MSI_DATA_VECTOR_MASK           0x000000ff
+
+#define MSI_DATA_DELIVERY_MODE_SHIFT    8
+#define MSI_DATA_LEVEL_SHIFT            14
+#define MSI_DATA_TRIGGER_SHIFT          15
+
+/*
+ * Shift/mask fields for msi address
+ */
+
+#define MSI_ADDR_DEST_MODE_SHIFT        2
+
+#define MSI_ADDR_REDIRECTION_SHIFT      3
+
+#define MSI_ADDR_DEST_ID_SHIFT          12
+#define  MSI_ADDR_DEST_ID_MASK          0x00ffff0
+
+#endif /* HW_APIC_MSIDEF_H */
diff --git a/hw/apic.c b/hw/apic.c
index 5fbf01c..60552df 100644
--- a/hw/apic.c
+++ b/hw/apic.c
@@ -23,19 +23,10 @@
 #include "host-utils.h"
 #include "trace.h"
 #include "pc.h"
+#include "apic-msidef.h"
 
 #define MAX_APIC_WORDS 8
 
-/* Intel APIC constants: from include/asm/msidef.h */
-#define MSI_DATA_VECTOR_SHIFT		0
-#define MSI_DATA_VECTOR_MASK		0x000000ff
-#define MSI_DATA_DELIVERY_MODE_SHIFT	8
-#define MSI_DATA_TRIGGER_SHIFT		15
-#define MSI_DATA_LEVEL_SHIFT		14
-#define MSI_ADDR_DEST_MODE_SHIFT	2
-#define MSI_ADDR_DEST_ID_SHIFT		12
-#define	MSI_ADDR_DEST_ID_MASK		0x00ffff0
-
 #define SYNC_FROM_VAPIC                 0x1
 #define SYNC_TO_VAPIC                   0x2
 #define SYNC_ISR_IRR_TO_VAPIC           0x4
commit 93d7ae8e77681bcdf537a2b5ff1febfd814d59c4
Author: Allen Kay <allen.m.kay at intel.com>
Date:   Thu Jun 21 15:40:48 2012 +0000

    Introduce Xen PCI Passthrough, PCI config space helpers
    
    A more complete history can be found here:
    git://xenbits.xensource.com/qemu-xen-unstable.git
    
    Signed-off-by: Allen Kay <allen.m.kay at intel.com>
    Signed-off-by: Guy Zana <guy at neocleus.com>
    Signed-off-by: Anthony PERARD <anthony.perard at citrix.com>
    Acked-by: Stefano Stabellini <stefano.stabellini at eu.citrix.com>

diff --git a/hw/xen_pt.c b/hw/xen_pt.c
index 63a5c80..92ad0fa 100644
--- a/hw/xen_pt.c
+++ b/hw/xen_pt.c
@@ -673,6 +673,13 @@ static int xen_pt_initfn(PCIDevice *d)
     /* Handle real device's MMIO/PIO BARs */
     xen_pt_register_regions(s);
 
+    /* reinitialize each config register to be emulated */
+    if (xen_pt_config_init(s)) {
+        XEN_PT_ERR(d, "PCI Config space initialisation failed.\n");
+        xen_host_pci_device_put(&s->real_device);
+        return -1;
+    }
+
     /* Bind interrupt */
     if (!s->dev.config[PCI_INTERRUPT_PIN]) {
         XEN_PT_LOG(d, "no pin interrupt\n");
@@ -771,6 +778,9 @@ static int xen_pt_unregister_device(PCIDevice *d)
         }
     }
 
+    /* delete all emulated config registers */
+    xen_pt_config_delete(s);
+
     xen_pt_unregister_regions(s);
     memory_listener_unregister(&s->memory_listener);
 
diff --git a/hw/xen_pt.h b/hw/xen_pt.h
index 36001a7..4b76073 100644
--- a/hw/xen_pt.h
+++ b/hw/xen_pt.h
@@ -62,6 +62,8 @@ typedef int (*xen_pt_conf_byte_read)
 #define XEN_PT_BAR_ALLF 0xFFFFFFFF
 #define XEN_PT_BAR_UNMAPPED (-1)
 
+#define PCI_CAP_MAX 48
+
 
 typedef enum {
     XEN_PT_GRP_TYPE_HARDWIRED = 0,  /* 0 Hardwired reg group */
diff --git a/hw/xen_pt_config_init.c b/hw/xen_pt_config_init.c
index 64d22e8..1d97876 100644
--- a/hw/xen_pt_config_init.c
+++ b/hw/xen_pt_config_init.c
@@ -1,11 +1,1398 @@
+/*
+ * Copyright (c) 2007, Neocleus Corporation.
+ * Copyright (c) 2007, Intel Corporation.
+ *
+ * This work is licensed under the terms of the GNU GPL, version 2.  See
+ * the COPYING file in the top-level directory.
+ *
+ * Alex Novik <alex at neocleus.com>
+ * Allen Kay <allen.m.kay at intel.com>
+ * Guy Zana <guy at neocleus.com>
+ *
+ * This file implements direct PCI assignment to a HVM guest
+ */
+
+#include "qemu-timer.h"
+#include "xen_backend.h"
 #include "xen_pt.h"
 
+#define XEN_PT_MERGE_VALUE(value, data, val_mask) \
+    (((value) & (val_mask)) | ((data) & ~(val_mask)))
+
+#define XEN_PT_INVALID_REG          0xFFFFFFFF      /* invalid register value */
+
+/* prototype */
+
+static int xen_pt_ptr_reg_init(XenPCIPassthroughState *s, XenPTRegInfo *reg,
+                               uint32_t real_offset, uint32_t *data);
+
+
+/* helper */
+
+/* A return value of 1 means the capability should NOT be exposed to guest. */
+static int xen_pt_hide_dev_cap(const XenHostPCIDevice *d, uint8_t grp_id)
+{
+    switch (grp_id) {
+    case PCI_CAP_ID_EXP:
+        /* The PCI Express Capability Structure of the VF of Intel 82599 10GbE
+         * Controller looks trivial, e.g., the PCI Express Capabilities
+         * Register is 0. We should not try to expose it to guest.
+         *
+         * The datasheet is available at
+         * http://download.intel.com/design/network/datashts/82599_datasheet.pdf
+         *
+         * See 'Table 9.7. VF PCIe Configuration Space' of the datasheet, the
+         * PCI Express Capability Structure of the VF of Intel 82599 10GbE
+         * Controller looks trivial, e.g., the PCI Express Capabilities
+         * Register is 0, so the Capability Version is 0 and
+         * xen_pt_pcie_size_init() would fail.
+         */
+        if (d->vendor_id == PCI_VENDOR_ID_INTEL &&
+            d->device_id == PCI_DEVICE_ID_INTEL_82599_SFP_VF) {
+            return 1;
+        }
+        break;
+    }
+    return 0;
+}
+
+/*   find emulate register group entry */
 XenPTRegGroup *xen_pt_find_reg_grp(XenPCIPassthroughState *s, uint32_t address)
 {
+    XenPTRegGroup *entry = NULL;
+
+    /* find register group entry */
+    QLIST_FOREACH(entry, &s->reg_grps, entries) {
+        /* check address */
+        if ((entry->base_offset <= address)
+            && ((entry->base_offset + entry->size) > address)) {
+            return entry;
+        }
+    }
+
+    /* group entry not found */
     return NULL;
 }
 
+/* find emulate register entry */
 XenPTReg *xen_pt_find_reg(XenPTRegGroup *reg_grp, uint32_t address)
 {
+    XenPTReg *reg_entry = NULL;
+    XenPTRegInfo *reg = NULL;
+    uint32_t real_offset = 0;
+
+    /* find register entry */
+    QLIST_FOREACH(reg_entry, &reg_grp->reg_tbl_list, entries) {
+        reg = reg_entry->reg;
+        real_offset = reg_grp->base_offset + reg->offset;
+        /* check address */
+        if ((real_offset <= address)
+            && ((real_offset + reg->size) > address)) {
+            return reg_entry;
+        }
+    }
+
     return NULL;
 }
+
+
+/****************
+ * general register functions
+ */
+
+/* register initialization function */
+
+static int xen_pt_common_reg_init(XenPCIPassthroughState *s,
+                                  XenPTRegInfo *reg, uint32_t real_offset,
+                                  uint32_t *data)
+{
+    *data = reg->init_val;
+    return 0;
+}
+
+/* Read register functions */
+
+static int xen_pt_byte_reg_read(XenPCIPassthroughState *s, XenPTReg *cfg_entry,
+                                uint8_t *value, uint8_t valid_mask)
+{
+    XenPTRegInfo *reg = cfg_entry->reg;
+    uint8_t valid_emu_mask = 0;
+
+    /* emulate byte register */
+    valid_emu_mask = reg->emu_mask & valid_mask;
+    *value = XEN_PT_MERGE_VALUE(*value, cfg_entry->data, ~valid_emu_mask);
+
+    return 0;
+}
+static int xen_pt_word_reg_read(XenPCIPassthroughState *s, XenPTReg *cfg_entry,
+                                uint16_t *value, uint16_t valid_mask)
+{
+    XenPTRegInfo *reg = cfg_entry->reg;
+    uint16_t valid_emu_mask = 0;
+
+    /* emulate word register */
+    valid_emu_mask = reg->emu_mask & valid_mask;
+    *value = XEN_PT_MERGE_VALUE(*value, cfg_entry->data, ~valid_emu_mask);
+
+    return 0;
+}
+static int xen_pt_long_reg_read(XenPCIPassthroughState *s, XenPTReg *cfg_entry,
+                                uint32_t *value, uint32_t valid_mask)
+{
+    XenPTRegInfo *reg = cfg_entry->reg;
+    uint32_t valid_emu_mask = 0;
+
+    /* emulate long register */
+    valid_emu_mask = reg->emu_mask & valid_mask;
+    *value = XEN_PT_MERGE_VALUE(*value, cfg_entry->data, ~valid_emu_mask);
+
+    return 0;
+}
+
+/* Write register functions */
+
+static int xen_pt_byte_reg_write(XenPCIPassthroughState *s, XenPTReg *cfg_entry,
+                                 uint8_t *val, uint8_t dev_value,
+                                 uint8_t valid_mask)
+{
+    XenPTRegInfo *reg = cfg_entry->reg;
+    uint8_t writable_mask = 0;
+    uint8_t throughable_mask = 0;
+
+    /* modify emulate register */
+    writable_mask = reg->emu_mask & ~reg->ro_mask & valid_mask;
+    cfg_entry->data = XEN_PT_MERGE_VALUE(*val, cfg_entry->data, writable_mask);
+
+    /* create value for writing to I/O device register */
+    throughable_mask = ~reg->emu_mask & valid_mask;
+    *val = XEN_PT_MERGE_VALUE(*val, dev_value, throughable_mask);
+
+    return 0;
+}
+static int xen_pt_word_reg_write(XenPCIPassthroughState *s, XenPTReg *cfg_entry,
+                                 uint16_t *val, uint16_t dev_value,
+                                 uint16_t valid_mask)
+{
+    XenPTRegInfo *reg = cfg_entry->reg;
+    uint16_t writable_mask = 0;
+    uint16_t throughable_mask = 0;
+
+    /* modify emulate register */
+    writable_mask = reg->emu_mask & ~reg->ro_mask & valid_mask;
+    cfg_entry->data = XEN_PT_MERGE_VALUE(*val, cfg_entry->data, writable_mask);
+
+    /* create value for writing to I/O device register */
+    throughable_mask = ~reg->emu_mask & valid_mask;
+    *val = XEN_PT_MERGE_VALUE(*val, dev_value, throughable_mask);
+
+    return 0;
+}
+static int xen_pt_long_reg_write(XenPCIPassthroughState *s, XenPTReg *cfg_entry,
+                                 uint32_t *val, uint32_t dev_value,
+                                 uint32_t valid_mask)
+{
+    XenPTRegInfo *reg = cfg_entry->reg;
+    uint32_t writable_mask = 0;
+    uint32_t throughable_mask = 0;
+
+    /* modify emulate register */
+    writable_mask = reg->emu_mask & ~reg->ro_mask & valid_mask;
+    cfg_entry->data = XEN_PT_MERGE_VALUE(*val, cfg_entry->data, writable_mask);
+
+    /* create value for writing to I/O device register */
+    throughable_mask = ~reg->emu_mask & valid_mask;
+    *val = XEN_PT_MERGE_VALUE(*val, dev_value, throughable_mask);
+
+    return 0;
+}
+
+
+/* XenPTRegInfo declaration
+ * - only for emulated register (either a part or whole bit).
+ * - for passthrough register that need special behavior (like interacting with
+ *   other component), set emu_mask to all 0 and specify r/w func properly.
+ * - do NOT use ALL F for init_val, otherwise the tbl will not be registered.
+ */
+
+/********************
+ * Header Type0
+ */
+
+static int xen_pt_vendor_reg_init(XenPCIPassthroughState *s,
+                                  XenPTRegInfo *reg, uint32_t real_offset,
+                                  uint32_t *data)
+{
+    *data = s->real_device.vendor_id;
+    return 0;
+}
+static int xen_pt_device_reg_init(XenPCIPassthroughState *s,
+                                  XenPTRegInfo *reg, uint32_t real_offset,
+                                  uint32_t *data)
+{
+    *data = s->real_device.device_id;
+    return 0;
+}
+static int xen_pt_status_reg_init(XenPCIPassthroughState *s,
+                                  XenPTRegInfo *reg, uint32_t real_offset,
+                                  uint32_t *data)
+{
+    XenPTRegGroup *reg_grp_entry = NULL;
+    XenPTReg *reg_entry = NULL;
+    uint32_t reg_field = 0;
+
+    /* find Header register group */
+    reg_grp_entry = xen_pt_find_reg_grp(s, PCI_CAPABILITY_LIST);
+    if (reg_grp_entry) {
+        /* find Capabilities Pointer register */
+        reg_entry = xen_pt_find_reg(reg_grp_entry, PCI_CAPABILITY_LIST);
+        if (reg_entry) {
+            /* check Capabilities Pointer register */
+            if (reg_entry->data) {
+                reg_field |= PCI_STATUS_CAP_LIST;
+            } else {
+                reg_field &= ~PCI_STATUS_CAP_LIST;
+            }
+        } else {
+            xen_shutdown_fatal_error("Internal error: Couldn't find XenPTReg*"
+                                     " for Capabilities Pointer register."
+                                     " (%s)\n", __func__);
+            return -1;
+        }
+    } else {
+        xen_shutdown_fatal_error("Internal error: Couldn't find XenPTRegGroup"
+                                 " for Header. (%s)\n", __func__);
+        return -1;
+    }
+
+    *data = reg_field;
+    return 0;
+}
+static int xen_pt_header_type_reg_init(XenPCIPassthroughState *s,
+                                       XenPTRegInfo *reg, uint32_t real_offset,
+                                       uint32_t *data)
+{
+    /* read PCI_HEADER_TYPE */
+    *data = reg->init_val | 0x80;
+    return 0;
+}
+
+/* initialize Interrupt Pin register */
+static int xen_pt_irqpin_reg_init(XenPCIPassthroughState *s,
+                                  XenPTRegInfo *reg, uint32_t real_offset,
+                                  uint32_t *data)
+{
+    *data = xen_pt_pci_read_intx(s);
+    return 0;
+}
+
+/* Command register */
+static int xen_pt_cmd_reg_read(XenPCIPassthroughState *s, XenPTReg *cfg_entry,
+                               uint16_t *value, uint16_t valid_mask)
+{
+    XenPTRegInfo *reg = cfg_entry->reg;
+    uint16_t valid_emu_mask = 0;
+    uint16_t emu_mask = reg->emu_mask;
+
+    if (s->is_virtfn) {
+        emu_mask |= PCI_COMMAND_MEMORY;
+    }
+
+    /* emulate word register */
+    valid_emu_mask = emu_mask & valid_mask;
+    *value = XEN_PT_MERGE_VALUE(*value, cfg_entry->data, ~valid_emu_mask);
+
+    return 0;
+}
+static int xen_pt_cmd_reg_write(XenPCIPassthroughState *s, XenPTReg *cfg_entry,
+                                uint16_t *val, uint16_t dev_value,
+                                uint16_t valid_mask)
+{
+    XenPTRegInfo *reg = cfg_entry->reg;
+    uint16_t writable_mask = 0;
+    uint16_t throughable_mask = 0;
+    uint16_t emu_mask = reg->emu_mask;
+
+    if (s->is_virtfn) {
+        emu_mask |= PCI_COMMAND_MEMORY;
+    }
+
+    /* modify emulate register */
+    writable_mask = ~reg->ro_mask & valid_mask;
+    cfg_entry->data = XEN_PT_MERGE_VALUE(*val, cfg_entry->data, writable_mask);
+
+    /* create value for writing to I/O device register */
+    throughable_mask = ~emu_mask & valid_mask;
+
+    if (*val & PCI_COMMAND_INTX_DISABLE) {
+        throughable_mask |= PCI_COMMAND_INTX_DISABLE;
+    } else {
+        if (s->machine_irq) {
+            throughable_mask |= PCI_COMMAND_INTX_DISABLE;
+        }
+    }
+
+    *val = XEN_PT_MERGE_VALUE(*val, dev_value, throughable_mask);
+
+    return 0;
+}
+
+/* BAR */
+#define XEN_PT_BAR_MEM_RO_MASK    0x0000000F  /* BAR ReadOnly mask(Memory) */
+#define XEN_PT_BAR_MEM_EMU_MASK   0xFFFFFFF0  /* BAR emul mask(Memory) */
+#define XEN_PT_BAR_IO_RO_MASK     0x00000003  /* BAR ReadOnly mask(I/O) */
+#define XEN_PT_BAR_IO_EMU_MASK    0xFFFFFFFC  /* BAR emul mask(I/O) */
+
+static XenPTBarFlag xen_pt_bar_reg_parse(XenPCIPassthroughState *s,
+                                         XenPTRegInfo *reg)
+{
+    PCIDevice *d = &s->dev;
+    XenPTRegion *region = NULL;
+    PCIIORegion *r;
+    int index = 0;
+
+    /* check 64bit BAR */
+    index = xen_pt_bar_offset_to_index(reg->offset);
+    if ((0 < index) && (index < PCI_ROM_SLOT)) {
+        int type = s->real_device.io_regions[index - 1].type;
+
+        if ((type & XEN_HOST_PCI_REGION_TYPE_MEM)
+            && (type & XEN_HOST_PCI_REGION_TYPE_MEM_64)) {
+            region = &s->bases[index - 1];
+            if (region->bar_flag != XEN_PT_BAR_FLAG_UPPER) {
+                return XEN_PT_BAR_FLAG_UPPER;
+            }
+        }
+    }
+
+    /* check unused BAR */
+    r = &d->io_regions[index];
+    if (r->size == 0) {
+        return XEN_PT_BAR_FLAG_UNUSED;
+    }
+
+    /* for ExpROM BAR */
+    if (index == PCI_ROM_SLOT) {
+        return XEN_PT_BAR_FLAG_MEM;
+    }
+
+    /* check BAR I/O indicator */
+    if (s->real_device.io_regions[index].type & XEN_HOST_PCI_REGION_TYPE_IO) {
+        return XEN_PT_BAR_FLAG_IO;
+    } else {
+        return XEN_PT_BAR_FLAG_MEM;
+    }
+}
+
+static inline uint32_t base_address_with_flags(XenHostPCIIORegion *hr)
+{
+    if (hr->type & XEN_HOST_PCI_REGION_TYPE_IO) {
+        return hr->base_addr | (hr->bus_flags & ~PCI_BASE_ADDRESS_IO_MASK);
+    } else {
+        return hr->base_addr | (hr->bus_flags & ~PCI_BASE_ADDRESS_MEM_MASK);
+    }
+}
+
+static int xen_pt_bar_reg_init(XenPCIPassthroughState *s, XenPTRegInfo *reg,
+                               uint32_t real_offset, uint32_t *data)
+{
+    uint32_t reg_field = 0;
+    int index;
+
+    index = xen_pt_bar_offset_to_index(reg->offset);
+    if (index < 0 || index >= PCI_NUM_REGIONS) {
+        XEN_PT_ERR(&s->dev, "Internal error: Invalid BAR index [%d].\n", index);
+        return -1;
+    }
+
+    /* set BAR flag */
+    s->bases[index].bar_flag = xen_pt_bar_reg_parse(s, reg);
+    if (s->bases[index].bar_flag == XEN_PT_BAR_FLAG_UNUSED) {
+        reg_field = XEN_PT_INVALID_REG;
+    }
+
+    *data = reg_field;
+    return 0;
+}
+static int xen_pt_bar_reg_read(XenPCIPassthroughState *s, XenPTReg *cfg_entry,
+                               uint32_t *value, uint32_t valid_mask)
+{
+    XenPTRegInfo *reg = cfg_entry->reg;
+    uint32_t valid_emu_mask = 0;
+    uint32_t bar_emu_mask = 0;
+    int index;
+
+    /* get BAR index */
+    index = xen_pt_bar_offset_to_index(reg->offset);
+    if (index < 0 || index >= PCI_NUM_REGIONS) {
+        XEN_PT_ERR(&s->dev, "Internal error: Invalid BAR index [%d].\n", index);
+        return -1;
+    }
+
+    /* use fixed-up value from kernel sysfs */
+    *value = base_address_with_flags(&s->real_device.io_regions[index]);
+
+    /* set emulate mask depend on BAR flag */
+    switch (s->bases[index].bar_flag) {
+    case XEN_PT_BAR_FLAG_MEM:
+        bar_emu_mask = XEN_PT_BAR_MEM_EMU_MASK;
+        break;
+    case XEN_PT_BAR_FLAG_IO:
+        bar_emu_mask = XEN_PT_BAR_IO_EMU_MASK;
+        break;
+    case XEN_PT_BAR_FLAG_UPPER:
+        bar_emu_mask = XEN_PT_BAR_ALLF;
+        break;
+    default:
+        break;
+    }
+
+    /* emulate BAR */
+    valid_emu_mask = bar_emu_mask & valid_mask;
+    *value = XEN_PT_MERGE_VALUE(*value, cfg_entry->data, ~valid_emu_mask);
+
+    return 0;
+}
+static int xen_pt_bar_reg_write(XenPCIPassthroughState *s, XenPTReg *cfg_entry,
+                                uint32_t *val, uint32_t dev_value,
+                                uint32_t valid_mask)
+{
+    XenPTRegInfo *reg = cfg_entry->reg;
+    XenPTRegion *base = NULL;
+    PCIDevice *d = &s->dev;
+    const PCIIORegion *r;
+    uint32_t writable_mask = 0;
+    uint32_t throughable_mask = 0;
+    uint32_t bar_emu_mask = 0;
+    uint32_t bar_ro_mask = 0;
+    uint32_t r_size = 0;
+    int index = 0;
+
+    index = xen_pt_bar_offset_to_index(reg->offset);
+    if (index < 0 || index >= PCI_NUM_REGIONS) {
+        XEN_PT_ERR(d, "Internal error: Invalid BAR index [%d].\n", index);
+        return -1;
+    }
+
+    r = &d->io_regions[index];
+    base = &s->bases[index];
+    r_size = xen_pt_get_emul_size(base->bar_flag, r->size);
+
+    /* set emulate mask and read-only mask values depend on the BAR flag */
+    switch (s->bases[index].bar_flag) {
+    case XEN_PT_BAR_FLAG_MEM:
+        bar_emu_mask = XEN_PT_BAR_MEM_EMU_MASK;
+        bar_ro_mask = XEN_PT_BAR_MEM_RO_MASK | (r_size - 1);
+        break;
+    case XEN_PT_BAR_FLAG_IO:
+        bar_emu_mask = XEN_PT_BAR_IO_EMU_MASK;
+        bar_ro_mask = XEN_PT_BAR_IO_RO_MASK | (r_size - 1);
+        break;
+    case XEN_PT_BAR_FLAG_UPPER:
+        bar_emu_mask = XEN_PT_BAR_ALLF;
+        bar_ro_mask = 0;    /* all upper 32bit are R/W */
+        break;
+    default:
+        break;
+    }
+
+    /* modify emulate register */
+    writable_mask = bar_emu_mask & ~bar_ro_mask & valid_mask;
+    cfg_entry->data = XEN_PT_MERGE_VALUE(*val, cfg_entry->data, writable_mask);
+
+    /* check whether we need to update the virtual region address or not */
+    switch (s->bases[index].bar_flag) {
+    case XEN_PT_BAR_FLAG_MEM:
+        /* nothing to do */
+        break;
+    case XEN_PT_BAR_FLAG_IO:
+        /* nothing to do */
+        break;
+    case XEN_PT_BAR_FLAG_UPPER:
+        if (cfg_entry->data) {
+            if (cfg_entry->data != (XEN_PT_BAR_ALLF & ~bar_ro_mask)) {
+                XEN_PT_WARN(d, "Guest attempt to set high MMIO Base Address. "
+                            "Ignore mapping. "
+                            "(offset: 0x%02x, high address: 0x%08x)\n",
+                            reg->offset, cfg_entry->data);
+            }
+        }
+        break;
+    default:
+        break;
+    }
+
+    /* create value for writing to I/O device register */
+    throughable_mask = ~bar_emu_mask & valid_mask;
+    *val = XEN_PT_MERGE_VALUE(*val, dev_value, throughable_mask);
+
+    return 0;
+}
+
+/* write Exp ROM BAR */
+static int xen_pt_exp_rom_bar_reg_write(XenPCIPassthroughState *s,
+                                        XenPTReg *cfg_entry, uint32_t *val,
+                                        uint32_t dev_value, uint32_t valid_mask)
+{
+    XenPTRegInfo *reg = cfg_entry->reg;
+    XenPTRegion *base = NULL;
+    PCIDevice *d = (PCIDevice *)&s->dev;
+    uint32_t writable_mask = 0;
+    uint32_t throughable_mask = 0;
+    pcibus_t r_size = 0;
+    uint32_t bar_emu_mask = 0;
+    uint32_t bar_ro_mask = 0;
+
+    r_size = d->io_regions[PCI_ROM_SLOT].size;
+    base = &s->bases[PCI_ROM_SLOT];
+    /* align memory type resource size */
+    r_size = xen_pt_get_emul_size(base->bar_flag, r_size);
+
+    /* set emulate mask and read-only mask */
+    bar_emu_mask = reg->emu_mask;
+    bar_ro_mask = (reg->ro_mask | (r_size - 1)) & ~PCI_ROM_ADDRESS_ENABLE;
+
+    /* modify emulate register */
+    writable_mask = ~bar_ro_mask & valid_mask;
+    cfg_entry->data = XEN_PT_MERGE_VALUE(*val, cfg_entry->data, writable_mask);
+
+    /* create value for writing to I/O device register */
+    throughable_mask = ~bar_emu_mask & valid_mask;
+    *val = XEN_PT_MERGE_VALUE(*val, dev_value, throughable_mask);
+
+    return 0;
+}
+
+/* Header Type0 reg static infomation table */
+static XenPTRegInfo xen_pt_emu_reg_header0[] = {
+    /* Vendor ID reg */
+    {
+        .offset     = PCI_VENDOR_ID,
+        .size       = 2,
+        .init_val   = 0x0000,
+        .ro_mask    = 0xFFFF,
+        .emu_mask   = 0xFFFF,
+        .init       = xen_pt_vendor_reg_init,
+        .u.w.read   = xen_pt_word_reg_read,
+        .u.w.write  = xen_pt_word_reg_write,
+    },
+    /* Device ID reg */
+    {
+        .offset     = PCI_DEVICE_ID,
+        .size       = 2,
+        .init_val   = 0x0000,
+        .ro_mask    = 0xFFFF,
+        .emu_mask   = 0xFFFF,
+        .init       = xen_pt_device_reg_init,
+        .u.w.read   = xen_pt_word_reg_read,
+        .u.w.write  = xen_pt_word_reg_write,
+    },
+    /* Command reg */
+    {
+        .offset     = PCI_COMMAND,
+        .size       = 2,
+        .init_val   = 0x0000,
+        .ro_mask    = 0xF880,
+        .emu_mask   = 0x0740,
+        .init       = xen_pt_common_reg_init,
+        .u.w.read   = xen_pt_cmd_reg_read,
+        .u.w.write  = xen_pt_cmd_reg_write,
+    },
+    /* Capabilities Pointer reg */
+    {
+        .offset     = PCI_CAPABILITY_LIST,
+        .size       = 1,
+        .init_val   = 0x00,
+        .ro_mask    = 0xFF,
+        .emu_mask   = 0xFF,
+        .init       = xen_pt_ptr_reg_init,
+        .u.b.read   = xen_pt_byte_reg_read,
+        .u.b.write  = xen_pt_byte_reg_write,
+    },
+    /* Status reg */
+    /* use emulated Cap Ptr value to initialize,
+     * so need to be declared after Cap Ptr reg
+     */
+    {
+        .offset     = PCI_STATUS,
+        .size       = 2,
+        .init_val   = 0x0000,
+        .ro_mask    = 0x06FF,
+        .emu_mask   = 0x0010,
+        .init       = xen_pt_status_reg_init,
+        .u.w.read   = xen_pt_word_reg_read,
+        .u.w.write  = xen_pt_word_reg_write,
+    },
+    /* Cache Line Size reg */
+    {
+        .offset     = PCI_CACHE_LINE_SIZE,
+        .size       = 1,
+        .init_val   = 0x00,
+        .ro_mask    = 0x00,
+        .emu_mask   = 0xFF,
+        .init       = xen_pt_common_reg_init,
+        .u.b.read   = xen_pt_byte_reg_read,
+        .u.b.write  = xen_pt_byte_reg_write,
+    },
+    /* Latency Timer reg */
+    {
+        .offset     = PCI_LATENCY_TIMER,
+        .size       = 1,
+        .init_val   = 0x00,
+        .ro_mask    = 0x00,
+        .emu_mask   = 0xFF,
+        .init       = xen_pt_common_reg_init,
+        .u.b.read   = xen_pt_byte_reg_read,
+        .u.b.write  = xen_pt_byte_reg_write,
+    },
+    /* Header Type reg */
+    {
+        .offset     = PCI_HEADER_TYPE,
+        .size       = 1,
+        .init_val   = 0x00,
+        .ro_mask    = 0xFF,
+        .emu_mask   = 0x00,
+        .init       = xen_pt_header_type_reg_init,
+        .u.b.read   = xen_pt_byte_reg_read,
+        .u.b.write  = xen_pt_byte_reg_write,
+    },
+    /* Interrupt Line reg */
+    {
+        .offset     = PCI_INTERRUPT_LINE,
+        .size       = 1,
+        .init_val   = 0x00,
+        .ro_mask    = 0x00,
+        .emu_mask   = 0xFF,
+        .init       = xen_pt_common_reg_init,
+        .u.b.read   = xen_pt_byte_reg_read,
+        .u.b.write  = xen_pt_byte_reg_write,
+    },
+    /* Interrupt Pin reg */
+    {
+        .offset     = PCI_INTERRUPT_PIN,
+        .size       = 1,
+        .init_val   = 0x00,
+        .ro_mask    = 0xFF,
+        .emu_mask   = 0xFF,
+        .init       = xen_pt_irqpin_reg_init,
+        .u.b.read   = xen_pt_byte_reg_read,
+        .u.b.write  = xen_pt_byte_reg_write,
+    },
+    /* BAR 0 reg */
+    /* mask of BAR need to be decided later, depends on IO/MEM type */
+    {
+        .offset     = PCI_BASE_ADDRESS_0,
+        .size       = 4,
+        .init_val   = 0x00000000,
+        .init       = xen_pt_bar_reg_init,
+        .u.dw.read  = xen_pt_bar_reg_read,
+        .u.dw.write = xen_pt_bar_reg_write,
+    },
+    /* BAR 1 reg */
+    {
+        .offset     = PCI_BASE_ADDRESS_1,
+        .size       = 4,
+        .init_val   = 0x00000000,
+        .init       = xen_pt_bar_reg_init,
+        .u.dw.read  = xen_pt_bar_reg_read,
+        .u.dw.write = xen_pt_bar_reg_write,
+    },
+    /* BAR 2 reg */
+    {
+        .offset     = PCI_BASE_ADDRESS_2,
+        .size       = 4,
+        .init_val   = 0x00000000,
+        .init       = xen_pt_bar_reg_init,
+        .u.dw.read  = xen_pt_bar_reg_read,
+        .u.dw.write = xen_pt_bar_reg_write,
+    },
+    /* BAR 3 reg */
+    {
+        .offset     = PCI_BASE_ADDRESS_3,
+        .size       = 4,
+        .init_val   = 0x00000000,
+        .init       = xen_pt_bar_reg_init,
+        .u.dw.read  = xen_pt_bar_reg_read,
+        .u.dw.write = xen_pt_bar_reg_write,
+    },
+    /* BAR 4 reg */
+    {
+        .offset     = PCI_BASE_ADDRESS_4,
+        .size       = 4,
+        .init_val   = 0x00000000,
+        .init       = xen_pt_bar_reg_init,
+        .u.dw.read  = xen_pt_bar_reg_read,
+        .u.dw.write = xen_pt_bar_reg_write,
+    },
+    /* BAR 5 reg */
+    {
+        .offset     = PCI_BASE_ADDRESS_5,
+        .size       = 4,
+        .init_val   = 0x00000000,
+        .init       = xen_pt_bar_reg_init,
+        .u.dw.read  = xen_pt_bar_reg_read,
+        .u.dw.write = xen_pt_bar_reg_write,
+    },
+    /* Expansion ROM BAR reg */
+    {
+        .offset     = PCI_ROM_ADDRESS,
+        .size       = 4,
+        .init_val   = 0x00000000,
+        .ro_mask    = 0x000007FE,
+        .emu_mask   = 0xFFFFF800,
+        .init       = xen_pt_bar_reg_init,
+        .u.dw.read  = xen_pt_long_reg_read,
+        .u.dw.write = xen_pt_exp_rom_bar_reg_write,
+    },
+    {
+        .size = 0,
+    },
+};
+
+
+/*********************************
+ * Vital Product Data Capability
+ */
+
+/* Vital Product Data Capability Structure reg static infomation table */
+static XenPTRegInfo xen_pt_emu_reg_vpd[] = {
+    {
+        .offset     = PCI_CAP_LIST_NEXT,
+        .size       = 1,
+        .init_val   = 0x00,
+        .ro_mask    = 0xFF,
+        .emu_mask   = 0xFF,
+        .init       = xen_pt_ptr_reg_init,
+        .u.b.read   = xen_pt_byte_reg_read,
+        .u.b.write  = xen_pt_byte_reg_write,
+    },
+    {
+        .size = 0,
+    },
+};
+
+
+/**************************************
+ * Vendor Specific Capability
+ */
+
+/* Vendor Specific Capability Structure reg static infomation table */
+static XenPTRegInfo xen_pt_emu_reg_vendor[] = {
+    {
+        .offset     = PCI_CAP_LIST_NEXT,
+        .size       = 1,
+        .init_val   = 0x00,
+        .ro_mask    = 0xFF,
+        .emu_mask   = 0xFF,
+        .init       = xen_pt_ptr_reg_init,
+        .u.b.read   = xen_pt_byte_reg_read,
+        .u.b.write  = xen_pt_byte_reg_write,
+    },
+    {
+        .size = 0,
+    },
+};
+
+
+/*****************************
+ * PCI Express Capability
+ */
+
+static inline uint8_t get_capability_version(XenPCIPassthroughState *s,
+                                             uint32_t offset)
+{
+    uint8_t flags = pci_get_byte(s->dev.config + offset + PCI_EXP_FLAGS);
+    return flags & PCI_EXP_FLAGS_VERS;
+}
+
+static inline uint8_t get_device_type(XenPCIPassthroughState *s,
+                                      uint32_t offset)
+{
+    uint8_t flags = pci_get_byte(s->dev.config + offset + PCI_EXP_FLAGS);
+    return (flags & PCI_EXP_FLAGS_TYPE) >> 4;
+}
+
+/* initialize Link Control register */
+static int xen_pt_linkctrl_reg_init(XenPCIPassthroughState *s,
+                                    XenPTRegInfo *reg, uint32_t real_offset,
+                                    uint32_t *data)
+{
+    uint8_t cap_ver = get_capability_version(s, real_offset - reg->offset);
+    uint8_t dev_type = get_device_type(s, real_offset - reg->offset);
+
+    /* no need to initialize in case of Root Complex Integrated Endpoint
+     * with cap_ver 1.x
+     */
+    if ((dev_type == PCI_EXP_TYPE_RC_END) && (cap_ver == 1)) {
+        *data = XEN_PT_INVALID_REG;
+    }
+
+    *data = reg->init_val;
+    return 0;
+}
+/* initialize Device Control 2 register */
+static int xen_pt_devctrl2_reg_init(XenPCIPassthroughState *s,
+                                    XenPTRegInfo *reg, uint32_t real_offset,
+                                    uint32_t *data)
+{
+    uint8_t cap_ver = get_capability_version(s, real_offset - reg->offset);
+
+    /* no need to initialize in case of cap_ver 1.x */
+    if (cap_ver == 1) {
+        *data = XEN_PT_INVALID_REG;
+    }
+
+    *data = reg->init_val;
+    return 0;
+}
+/* initialize Link Control 2 register */
+static int xen_pt_linkctrl2_reg_init(XenPCIPassthroughState *s,
+                                     XenPTRegInfo *reg, uint32_t real_offset,
+                                     uint32_t *data)
+{
+    uint8_t cap_ver = get_capability_version(s, real_offset - reg->offset);
+    uint32_t reg_field = 0;
+
+    /* no need to initialize in case of cap_ver 1.x */
+    if (cap_ver == 1) {
+        reg_field = XEN_PT_INVALID_REG;
+    } else {
+        /* set Supported Link Speed */
+        uint8_t lnkcap = pci_get_byte(s->dev.config + real_offset - reg->offset
+                                      + PCI_EXP_LNKCAP);
+        reg_field |= PCI_EXP_LNKCAP_SLS & lnkcap;
+    }
+
+    *data = reg_field;
+    return 0;
+}
+
+/* PCI Express Capability Structure reg static infomation table */
+static XenPTRegInfo xen_pt_emu_reg_pcie[] = {
+    /* Next Pointer reg */
+    {
+        .offset     = PCI_CAP_LIST_NEXT,
+        .size       = 1,
+        .init_val   = 0x00,
+        .ro_mask    = 0xFF,
+        .emu_mask   = 0xFF,
+        .init       = xen_pt_ptr_reg_init,
+        .u.b.read   = xen_pt_byte_reg_read,
+        .u.b.write  = xen_pt_byte_reg_write,
+    },
+    /* Device Capabilities reg */
+    {
+        .offset     = PCI_EXP_DEVCAP,
+        .size       = 4,
+        .init_val   = 0x00000000,
+        .ro_mask    = 0x1FFCFFFF,
+        .emu_mask   = 0x10000000,
+        .init       = xen_pt_common_reg_init,
+        .u.dw.read  = xen_pt_long_reg_read,
+        .u.dw.write = xen_pt_long_reg_write,
+    },
+    /* Device Control reg */
+    {
+        .offset     = PCI_EXP_DEVCTL,
+        .size       = 2,
+        .init_val   = 0x2810,
+        .ro_mask    = 0x8400,
+        .emu_mask   = 0xFFFF,
+        .init       = xen_pt_common_reg_init,
+        .u.w.read   = xen_pt_word_reg_read,
+        .u.w.write  = xen_pt_word_reg_write,
+    },
+    /* Link Control reg */
+    {
+        .offset     = PCI_EXP_LNKCTL,
+        .size       = 2,
+        .init_val   = 0x0000,
+        .ro_mask    = 0xFC34,
+        .emu_mask   = 0xFFFF,
+        .init       = xen_pt_linkctrl_reg_init,
+        .u.w.read   = xen_pt_word_reg_read,
+        .u.w.write  = xen_pt_word_reg_write,
+    },
+    /* Device Control 2 reg */
+    {
+        .offset     = 0x28,
+        .size       = 2,
+        .init_val   = 0x0000,
+        .ro_mask    = 0xFFE0,
+        .emu_mask   = 0xFFFF,
+        .init       = xen_pt_devctrl2_reg_init,
+        .u.w.read   = xen_pt_word_reg_read,
+        .u.w.write  = xen_pt_word_reg_write,
+    },
+    /* Link Control 2 reg */
+    {
+        .offset     = 0x30,
+        .size       = 2,
+        .init_val   = 0x0000,
+        .ro_mask    = 0xE040,
+        .emu_mask   = 0xFFFF,
+        .init       = xen_pt_linkctrl2_reg_init,
+        .u.w.read   = xen_pt_word_reg_read,
+        .u.w.write  = xen_pt_word_reg_write,
+    },
+    {
+        .size = 0,
+    },
+};
+
+
+/*********************************
+ * Power Management Capability
+ */
+
+/* read Power Management Control/Status register */
+static int xen_pt_pmcsr_reg_read(XenPCIPassthroughState *s, XenPTReg *cfg_entry,
+                                 uint16_t *value, uint16_t valid_mask)
+{
+    XenPTRegInfo *reg = cfg_entry->reg;
+    uint16_t valid_emu_mask = reg->emu_mask;
+
+    valid_emu_mask |= PCI_PM_CTRL_STATE_MASK | PCI_PM_CTRL_NO_SOFT_RESET;
+
+    valid_emu_mask = valid_emu_mask & valid_mask;
+    *value = XEN_PT_MERGE_VALUE(*value, cfg_entry->data, ~valid_emu_mask);
+
+    return 0;
+}
+/* write Power Management Control/Status register */
+static int xen_pt_pmcsr_reg_write(XenPCIPassthroughState *s,
+                                  XenPTReg *cfg_entry, uint16_t *val,
+                                  uint16_t dev_value, uint16_t valid_mask)
+{
+    XenPTRegInfo *reg = cfg_entry->reg;
+    uint16_t emu_mask = reg->emu_mask;
+    uint16_t writable_mask = 0;
+    uint16_t throughable_mask = 0;
+
+    emu_mask |= PCI_PM_CTRL_STATE_MASK | PCI_PM_CTRL_NO_SOFT_RESET;
+
+    /* modify emulate register */
+    writable_mask = emu_mask & ~reg->ro_mask & valid_mask;
+    cfg_entry->data = XEN_PT_MERGE_VALUE(*val, cfg_entry->data, writable_mask);
+
+    /* create value for writing to I/O device register */
+    throughable_mask = ~emu_mask & valid_mask;
+    *val = XEN_PT_MERGE_VALUE(*val, dev_value, throughable_mask);
+
+    return 0;
+}
+
+/* Power Management Capability reg static infomation table */
+static XenPTRegInfo xen_pt_emu_reg_pm[] = {
+    /* Next Pointer reg */
+    {
+        .offset     = PCI_CAP_LIST_NEXT,
+        .size       = 1,
+        .init_val   = 0x00,
+        .ro_mask    = 0xFF,
+        .emu_mask   = 0xFF,
+        .init       = xen_pt_ptr_reg_init,
+        .u.b.read   = xen_pt_byte_reg_read,
+        .u.b.write  = xen_pt_byte_reg_write,
+    },
+    /* Power Management Capabilities reg */
+    {
+        .offset     = PCI_CAP_FLAGS,
+        .size       = 2,
+        .init_val   = 0x0000,
+        .ro_mask    = 0xFFFF,
+        .emu_mask   = 0xF9C8,
+        .init       = xen_pt_common_reg_init,
+        .u.w.read   = xen_pt_word_reg_read,
+        .u.w.write  = xen_pt_word_reg_write,
+    },
+    /* PCI Power Management Control/Status reg */
+    {
+        .offset     = PCI_PM_CTRL,
+        .size       = 2,
+        .init_val   = 0x0008,
+        .ro_mask    = 0xE1FC,
+        .emu_mask   = 0x8100,
+        .init       = xen_pt_common_reg_init,
+        .u.w.read   = xen_pt_pmcsr_reg_read,
+        .u.w.write  = xen_pt_pmcsr_reg_write,
+    },
+    {
+        .size = 0,
+    },
+};
+
+
+/****************************
+ * Capabilities
+ */
+
+/* capability structure register group size functions */
+
+static int xen_pt_reg_grp_size_init(XenPCIPassthroughState *s,
+                                    const XenPTRegGroupInfo *grp_reg,
+                                    uint32_t base_offset, uint8_t *size)
+{
+    *size = grp_reg->grp_size;
+    return 0;
+}
+/* get Vendor Specific Capability Structure register group size */
+static int xen_pt_vendor_size_init(XenPCIPassthroughState *s,
+                                   const XenPTRegGroupInfo *grp_reg,
+                                   uint32_t base_offset, uint8_t *size)
+{
+    *size = pci_get_byte(s->dev.config + base_offset + 0x02);
+    return 0;
+}
+/* get PCI Express Capability Structure register group size */
+static int xen_pt_pcie_size_init(XenPCIPassthroughState *s,
+                                 const XenPTRegGroupInfo *grp_reg,
+                                 uint32_t base_offset, uint8_t *size)
+{
+    PCIDevice *d = &s->dev;
+    uint8_t version = get_capability_version(s, base_offset);
+    uint8_t type = get_device_type(s, base_offset);
+    uint8_t pcie_size = 0;
+
+
+    /* calculate size depend on capability version and device/port type */
+    /* in case of PCI Express Base Specification Rev 1.x */
+    if (version == 1) {
+        /* The PCI Express Capabilities, Device Capabilities, and Device
+         * Status/Control registers are required for all PCI Express devices.
+         * The Link Capabilities and Link Status/Control are required for all
+         * Endpoints that are not Root Complex Integrated Endpoints. Endpoints
+         * are not required to implement registers other than those listed
+         * above and terminate the capability structure.
+         */
+        switch (type) {
+        case PCI_EXP_TYPE_ENDPOINT:
+        case PCI_EXP_TYPE_LEG_END:
+            pcie_size = 0x14;
+            break;
+        case PCI_EXP_TYPE_RC_END:
+            /* has no link */
+            pcie_size = 0x0C;
+            break;
+            /* only EndPoint passthrough is supported */
+        case PCI_EXP_TYPE_ROOT_PORT:
+        case PCI_EXP_TYPE_UPSTREAM:
+        case PCI_EXP_TYPE_DOWNSTREAM:
+        case PCI_EXP_TYPE_PCI_BRIDGE:
+        case PCI_EXP_TYPE_PCIE_BRIDGE:
+        case PCI_EXP_TYPE_RC_EC:
+        default:
+            XEN_PT_ERR(d, "Unsupported device/port type %#x.\n", type);
+            return -1;
+        }
+    }
+    /* in case of PCI Express Base Specification Rev 2.0 */
+    else if (version == 2) {
+        switch (type) {
+        case PCI_EXP_TYPE_ENDPOINT:
+        case PCI_EXP_TYPE_LEG_END:
+        case PCI_EXP_TYPE_RC_END:
+            /* For Functions that do not implement the registers,
+             * these spaces must be hardwired to 0b.
+             */
+            pcie_size = 0x3C;
+            break;
+            /* only EndPoint passthrough is supported */
+        case PCI_EXP_TYPE_ROOT_PORT:
+        case PCI_EXP_TYPE_UPSTREAM:
+        case PCI_EXP_TYPE_DOWNSTREAM:
+        case PCI_EXP_TYPE_PCI_BRIDGE:
+        case PCI_EXP_TYPE_PCIE_BRIDGE:
+        case PCI_EXP_TYPE_RC_EC:
+        default:
+            XEN_PT_ERR(d, "Unsupported device/port type %#x.\n", type);
+            return -1;
+        }
+    } else {
+        XEN_PT_ERR(d, "Unsupported capability version %#x.\n", version);
+        return -1;
+    }
+
+    *size = pcie_size;
+    return 0;
+}
+
+static const XenPTRegGroupInfo xen_pt_emu_reg_grps[] = {
+    /* Header Type0 reg group */
+    {
+        .grp_id      = 0xFF,
+        .grp_type    = XEN_PT_GRP_TYPE_EMU,
+        .grp_size    = 0x40,
+        .size_init   = xen_pt_reg_grp_size_init,
+        .emu_regs = xen_pt_emu_reg_header0,
+    },
+    /* PCI PowerManagement Capability reg group */
+    {
+        .grp_id      = PCI_CAP_ID_PM,
+        .grp_type    = XEN_PT_GRP_TYPE_EMU,
+        .grp_size    = PCI_PM_SIZEOF,
+        .size_init   = xen_pt_reg_grp_size_init,
+        .emu_regs = xen_pt_emu_reg_pm,
+    },
+    /* AGP Capability Structure reg group */
+    {
+        .grp_id     = PCI_CAP_ID_AGP,
+        .grp_type   = XEN_PT_GRP_TYPE_HARDWIRED,
+        .grp_size   = 0x30,
+        .size_init  = xen_pt_reg_grp_size_init,
+    },
+    /* Vital Product Data Capability Structure reg group */
+    {
+        .grp_id      = PCI_CAP_ID_VPD,
+        .grp_type    = XEN_PT_GRP_TYPE_EMU,
+        .grp_size    = 0x08,
+        .size_init   = xen_pt_reg_grp_size_init,
+        .emu_regs = xen_pt_emu_reg_vpd,
+    },
+    /* Slot Identification reg group */
+    {
+        .grp_id     = PCI_CAP_ID_SLOTID,
+        .grp_type   = XEN_PT_GRP_TYPE_HARDWIRED,
+        .grp_size   = 0x04,
+        .size_init  = xen_pt_reg_grp_size_init,
+    },
+    /* PCI-X Capabilities List Item reg group */
+    {
+        .grp_id     = PCI_CAP_ID_PCIX,
+        .grp_type   = XEN_PT_GRP_TYPE_HARDWIRED,
+        .grp_size   = 0x18,
+        .size_init  = xen_pt_reg_grp_size_init,
+    },
+    /* Vendor Specific Capability Structure reg group */
+    {
+        .grp_id      = PCI_CAP_ID_VNDR,
+        .grp_type    = XEN_PT_GRP_TYPE_EMU,
+        .grp_size    = 0xFF,
+        .size_init   = xen_pt_vendor_size_init,
+        .emu_regs = xen_pt_emu_reg_vendor,
+    },
+    /* SHPC Capability List Item reg group */
+    {
+        .grp_id     = PCI_CAP_ID_SHPC,
+        .grp_type   = XEN_PT_GRP_TYPE_HARDWIRED,
+        .grp_size   = 0x08,
+        .size_init  = xen_pt_reg_grp_size_init,
+    },
+    /* Subsystem ID and Subsystem Vendor ID Capability List Item reg group */
+    {
+        .grp_id     = PCI_CAP_ID_SSVID,
+        .grp_type   = XEN_PT_GRP_TYPE_HARDWIRED,
+        .grp_size   = 0x08,
+        .size_init  = xen_pt_reg_grp_size_init,
+    },
+    /* AGP 8x Capability Structure reg group */
+    {
+        .grp_id     = PCI_CAP_ID_AGP3,
+        .grp_type   = XEN_PT_GRP_TYPE_HARDWIRED,
+        .grp_size   = 0x30,
+        .size_init  = xen_pt_reg_grp_size_init,
+    },
+    /* PCI Express Capability Structure reg group */
+    {
+        .grp_id      = PCI_CAP_ID_EXP,
+        .grp_type    = XEN_PT_GRP_TYPE_EMU,
+        .grp_size    = 0xFF,
+        .size_init   = xen_pt_pcie_size_init,
+        .emu_regs = xen_pt_emu_reg_pcie,
+    },
+    {
+        .grp_size = 0,
+    },
+};
+
+/* initialize Capabilities Pointer or Next Pointer register */
+static int xen_pt_ptr_reg_init(XenPCIPassthroughState *s,
+                               XenPTRegInfo *reg, uint32_t real_offset,
+                               uint32_t *data)
+{
+    int i;
+    uint8_t *config = s->dev.config;
+    uint32_t reg_field = pci_get_byte(config + real_offset);
+    uint8_t cap_id = 0;
+
+    /* find capability offset */
+    while (reg_field) {
+        for (i = 0; xen_pt_emu_reg_grps[i].grp_size != 0; i++) {
+            if (xen_pt_hide_dev_cap(&s->real_device,
+                                    xen_pt_emu_reg_grps[i].grp_id)) {
+                continue;
+            }
+
+            cap_id = pci_get_byte(config + reg_field + PCI_CAP_LIST_ID);
+            if (xen_pt_emu_reg_grps[i].grp_id == cap_id) {
+                if (xen_pt_emu_reg_grps[i].grp_type == XEN_PT_GRP_TYPE_EMU) {
+                    goto out;
+                }
+                /* ignore the 0 hardwired capability, find next one */
+                break;
+            }
+        }
+
+        /* next capability */
+        reg_field = pci_get_byte(config + reg_field + PCI_CAP_LIST_NEXT);
+    }
+
+out:
+    *data = reg_field;
+    return 0;
+}
+
+
+/*************
+ * Main
+ */
+
+static uint8_t find_cap_offset(XenPCIPassthroughState *s, uint8_t cap)
+{
+    uint8_t id;
+    unsigned max_cap = PCI_CAP_MAX;
+    uint8_t pos = PCI_CAPABILITY_LIST;
+    uint8_t status = 0;
+
+    if (xen_host_pci_get_byte(&s->real_device, PCI_STATUS, &status)) {
+        return 0;
+    }
+    if ((status & PCI_STATUS_CAP_LIST) == 0) {
+        return 0;
+    }
+
+    while (max_cap--) {
+        if (xen_host_pci_get_byte(&s->real_device, pos, &pos)) {
+            break;
+        }
+        if (pos < PCI_CONFIG_HEADER_SIZE) {
+            break;
+        }
+
+        pos &= ~3;
+        if (xen_host_pci_get_byte(&s->real_device,
+                                  pos + PCI_CAP_LIST_ID, &id)) {
+            break;
+        }
+
+        if (id == 0xff) {
+            break;
+        }
+        if (id == cap) {
+            return pos;
+        }
+
+        pos += PCI_CAP_LIST_NEXT;
+    }
+    return 0;
+}
+
+static int xen_pt_config_reg_init(XenPCIPassthroughState *s,
+                                  XenPTRegGroup *reg_grp, XenPTRegInfo *reg)
+{
+    XenPTReg *reg_entry;
+    uint32_t data = 0;
+    int rc = 0;
+
+    reg_entry = g_new0(XenPTReg, 1);
+    reg_entry->reg = reg;
+
+    if (reg->init) {
+        /* initialize emulate register */
+        rc = reg->init(s, reg_entry->reg,
+                       reg_grp->base_offset + reg->offset, &data);
+        if (rc < 0) {
+            free(reg_entry);
+            return rc;
+        }
+        if (data == XEN_PT_INVALID_REG) {
+            /* free unused BAR register entry */
+            free(reg_entry);
+            return 0;
+        }
+        /* set register value */
+        reg_entry->data = data;
+    }
+    /* list add register entry */
+    QLIST_INSERT_HEAD(&reg_grp->reg_tbl_list, reg_entry, entries);
+
+    return 0;
+}
+
+int xen_pt_config_init(XenPCIPassthroughState *s)
+{
+    int i, rc;
+
+    QLIST_INIT(&s->reg_grps);
+
+    for (i = 0; xen_pt_emu_reg_grps[i].grp_size != 0; i++) {
+        uint32_t reg_grp_offset = 0;
+        XenPTRegGroup *reg_grp_entry = NULL;
+
+        if (xen_pt_emu_reg_grps[i].grp_id != 0xFF) {
+            if (xen_pt_hide_dev_cap(&s->real_device,
+                                    xen_pt_emu_reg_grps[i].grp_id)) {
+                continue;
+            }
+
+            reg_grp_offset = find_cap_offset(s, xen_pt_emu_reg_grps[i].grp_id);
+
+            if (!reg_grp_offset) {
+                continue;
+            }
+        }
+
+        reg_grp_entry = g_new0(XenPTRegGroup, 1);
+        QLIST_INIT(&reg_grp_entry->reg_tbl_list);
+        QLIST_INSERT_HEAD(&s->reg_grps, reg_grp_entry, entries);
+
+        reg_grp_entry->base_offset = reg_grp_offset;
+        reg_grp_entry->reg_grp = xen_pt_emu_reg_grps + i;
+        if (xen_pt_emu_reg_grps[i].size_init) {
+            /* get register group size */
+            rc = xen_pt_emu_reg_grps[i].size_init(s, reg_grp_entry->reg_grp,
+                                                  reg_grp_offset,
+                                                  &reg_grp_entry->size);
+            if (rc < 0) {
+                xen_pt_config_delete(s);
+                return rc;
+            }
+        }
+
+        if (xen_pt_emu_reg_grps[i].grp_type == XEN_PT_GRP_TYPE_EMU) {
+            if (xen_pt_emu_reg_grps[i].emu_regs) {
+                int j = 0;
+                XenPTRegInfo *regs = xen_pt_emu_reg_grps[i].emu_regs;
+                /* initialize capability register */
+                for (j = 0; regs->size != 0; j++, regs++) {
+                    /* initialize capability register */
+                    rc = xen_pt_config_reg_init(s, reg_grp_entry, regs);
+                    if (rc < 0) {
+                        xen_pt_config_delete(s);
+                        return rc;
+                    }
+                }
+            }
+        }
+    }
+
+    return 0;
+}
+
+/* delete all emulate register */
+void xen_pt_config_delete(XenPCIPassthroughState *s)
+{
+    struct XenPTRegGroup *reg_group, *next_grp;
+    struct XenPTReg *reg, *next_reg;
+
+    /* free all register group entry */
+    QLIST_FOREACH_SAFE(reg_group, &s->reg_grps, entries, next_grp) {
+        /* free all register entry */
+        QLIST_FOREACH_SAFE(reg, &reg_group->reg_tbl_list, entries, next_reg) {
+            QLIST_REMOVE(reg, entries);
+            g_free(reg);
+        }
+
+        QLIST_REMOVE(reg_group, entries);
+        g_free(reg_group);
+    }
+}
commit eaab4d60d3ad908936564492862e8a84f5fa59b2
Author: Allen Kay <allen.m.kay at intel.com>
Date:   Thu Jun 21 15:40:09 2012 +0000

    Introduce Xen PCI Passthrough, qdevice
    
    A more complete history can be found here:
    git://xenbits.xensource.com/qemu-xen-unstable.git
    
    Signed-off-by: Allen Kay <allen.m.kay at intel.com>
    Signed-off-by: Guy Zana <guy at neocleus.com>
    Signed-off-by: Anthony PERARD <anthony.perard at citrix.com>
    Acked-by: Stefano Stabellini <stefano.stabellini at eu.citrix.com>

diff --git a/hw/i386/Makefile.objs b/hw/i386/Makefile.objs
index b1d318b..054f409 100644
--- a/hw/i386/Makefile.objs
+++ b/hw/i386/Makefile.objs
@@ -8,6 +8,7 @@ obj-y += pc_piix.o
 obj-y += pc_sysfw.o
 obj-$(CONFIG_XEN) += xen_platform.o xen_apic.o
 obj-$(CONFIG_XEN_PCI_PASSTHROUGH) += xen-host-pci-device.o
+obj-$(CONFIG_XEN_PCI_PASSTHROUGH) += xen_pt.o xen_pt_config_init.o
 obj-y += kvm/
 obj-$(CONFIG_SPICE) += qxl.o qxl-logger.o qxl-render.o
 
diff --git a/hw/xen_common.h b/hw/xen_common.h
index fe7f227..03b0bb1 100644
--- a/hw/xen_common.h
+++ b/hw/xen_common.h
@@ -150,4 +150,7 @@ static inline int xen_xc_hvm_inject_msi(XenXC xen_xc, domid_t dom,
 
 void destroy_hvm_domain(bool reboot);
 
+/* shutdown/destroy current domain because of an error */
+void xen_shutdown_fatal_error(const char *fmt, ...) GCC_FMT_ATTR(1, 2);
+
 #endif /* QEMU_HW_XEN_COMMON_H */
diff --git a/hw/xen_pt.c b/hw/xen_pt.c
new file mode 100644
index 0000000..63a5c80
--- /dev/null
+++ b/hw/xen_pt.c
@@ -0,0 +1,812 @@
+/*
+ * Copyright (c) 2007, Neocleus Corporation.
+ * Copyright (c) 2007, Intel Corporation.
+ *
+ * This work is licensed under the terms of the GNU GPL, version 2.  See
+ * the COPYING file in the top-level directory.
+ *
+ * Alex Novik <alex at neocleus.com>
+ * Allen Kay <allen.m.kay at intel.com>
+ * Guy Zana <guy at neocleus.com>
+ *
+ * This file implements direct PCI assignment to a HVM guest
+ */
+
+/*
+ * Interrupt Disable policy:
+ *
+ * INTx interrupt:
+ *   Initialize(register_real_device)
+ *     Map INTx(xc_physdev_map_pirq):
+ *       <fail>
+ *         - Set real Interrupt Disable bit to '1'.
+ *         - Set machine_irq and assigned_device->machine_irq to '0'.
+ *         * Don't bind INTx.
+ *
+ *     Bind INTx(xc_domain_bind_pt_pci_irq):
+ *       <fail>
+ *         - Set real Interrupt Disable bit to '1'.
+ *         - Unmap INTx.
+ *         - Decrement xen_pt_mapped_machine_irq[machine_irq]
+ *         - Set assigned_device->machine_irq to '0'.
+ *
+ *   Write to Interrupt Disable bit by guest software(xen_pt_cmd_reg_write)
+ *     Write '0'
+ *       - Set real bit to '0' if assigned_device->machine_irq isn't '0'.
+ *
+ *     Write '1'
+ *       - Set real bit to '1'.
+ */
+
+#include <sys/ioctl.h>
+
+#include "pci.h"
+#include "xen.h"
+#include "xen_backend.h"
+#include "xen_pt.h"
+#include "range.h"
+
+#define XEN_PT_NR_IRQS (256)
+static uint8_t xen_pt_mapped_machine_irq[XEN_PT_NR_IRQS] = {0};
+
+void xen_pt_log(const PCIDevice *d, const char *f, ...)
+{
+    va_list ap;
+
+    va_start(ap, f);
+    if (d) {
+        fprintf(stderr, "[%02x:%02x.%d] ", pci_bus_num(d->bus),
+                PCI_SLOT(d->devfn), PCI_FUNC(d->devfn));
+    }
+    vfprintf(stderr, f, ap);
+    va_end(ap);
+}
+
+/* Config Space */
+
+static int xen_pt_pci_config_access_check(PCIDevice *d, uint32_t addr, int len)
+{
+    /* check offset range */
+    if (addr >= 0xFF) {
+        XEN_PT_ERR(d, "Failed to access register with offset exceeding 0xFF. "
+                   "(addr: 0x%02x, len: %d)\n", addr, len);
+        return -1;
+    }
+
+    /* check read size */
+    if ((len != 1) && (len != 2) && (len != 4)) {
+        XEN_PT_ERR(d, "Failed to access register with invalid access length. "
+                   "(addr: 0x%02x, len: %d)\n", addr, len);
+        return -1;
+    }
+
+    /* check offset alignment */
+    if (addr & (len - 1)) {
+        XEN_PT_ERR(d, "Failed to access register with invalid access size "
+                   "alignment. (addr: 0x%02x, len: %d)\n", addr, len);
+        return -1;
+    }
+
+    return 0;
+}
+
+int xen_pt_bar_offset_to_index(uint32_t offset)
+{
+    int index = 0;
+
+    /* check Exp ROM BAR */
+    if (offset == PCI_ROM_ADDRESS) {
+        return PCI_ROM_SLOT;
+    }
+
+    /* calculate BAR index */
+    index = (offset - PCI_BASE_ADDRESS_0) >> 2;
+    if (index >= PCI_NUM_REGIONS) {
+        return -1;
+    }
+
+    return index;
+}
+
+static uint32_t xen_pt_pci_read_config(PCIDevice *d, uint32_t addr, int len)
+{
+    XenPCIPassthroughState *s = DO_UPCAST(XenPCIPassthroughState, dev, d);
+    uint32_t val = 0;
+    XenPTRegGroup *reg_grp_entry = NULL;
+    XenPTReg *reg_entry = NULL;
+    int rc = 0;
+    int emul_len = 0;
+    uint32_t find_addr = addr;
+
+    if (xen_pt_pci_config_access_check(d, addr, len)) {
+        goto exit;
+    }
+
+    /* find register group entry */
+    reg_grp_entry = xen_pt_find_reg_grp(s, addr);
+    if (reg_grp_entry) {
+        /* check 0-Hardwired register group */
+        if (reg_grp_entry->reg_grp->grp_type == XEN_PT_GRP_TYPE_HARDWIRED) {
+            /* no need to emulate, just return 0 */
+            val = 0;
+            goto exit;
+        }
+    }
+
+    /* read I/O device register value */
+    rc = xen_host_pci_get_block(&s->real_device, addr, (uint8_t *)&val, len);
+    if (rc < 0) {
+        XEN_PT_ERR(d, "pci_read_block failed. return value: %d.\n", rc);
+        memset(&val, 0xff, len);
+    }
+
+    /* just return the I/O device register value for
+     * passthrough type register group */
+    if (reg_grp_entry == NULL) {
+        goto exit;
+    }
+
+    /* adjust the read value to appropriate CFC-CFF window */
+    val <<= (addr & 3) << 3;
+    emul_len = len;
+
+    /* loop around the guest requested size */
+    while (emul_len > 0) {
+        /* find register entry to be emulated */
+        reg_entry = xen_pt_find_reg(reg_grp_entry, find_addr);
+        if (reg_entry) {
+            XenPTRegInfo *reg = reg_entry->reg;
+            uint32_t real_offset = reg_grp_entry->base_offset + reg->offset;
+            uint32_t valid_mask = 0xFFFFFFFF >> ((4 - emul_len) << 3);
+            uint8_t *ptr_val = NULL;
+
+            valid_mask <<= (find_addr - real_offset) << 3;
+            ptr_val = (uint8_t *)&val + (real_offset & 3);
+
+            /* do emulation based on register size */
+            switch (reg->size) {
+            case 1:
+                if (reg->u.b.read) {
+                    rc = reg->u.b.read(s, reg_entry, ptr_val, valid_mask);
+                }
+                break;
+            case 2:
+                if (reg->u.w.read) {
+                    rc = reg->u.w.read(s, reg_entry,
+                                       (uint16_t *)ptr_val, valid_mask);
+                }
+                break;
+            case 4:
+                if (reg->u.dw.read) {
+                    rc = reg->u.dw.read(s, reg_entry,
+                                        (uint32_t *)ptr_val, valid_mask);
+                }
+                break;
+            }
+
+            if (rc < 0) {
+                xen_shutdown_fatal_error("Internal error: Invalid read "
+                                         "emulation. (%s, rc: %d)\n",
+                                         __func__, rc);
+                return 0;
+            }
+
+            /* calculate next address to find */
+            emul_len -= reg->size;
+            if (emul_len > 0) {
+                find_addr = real_offset + reg->size;
+            }
+        } else {
+            /* nothing to do with passthrough type register,
+             * continue to find next byte */
+            emul_len--;
+            find_addr++;
+        }
+    }
+
+    /* need to shift back before returning them to pci bus emulator */
+    val >>= ((addr & 3) << 3);
+
+exit:
+    XEN_PT_LOG_CONFIG(d, addr, val, len);
+    return val;
+}
+
+static void xen_pt_pci_write_config(PCIDevice *d, uint32_t addr,
+                                    uint32_t val, int len)
+{
+    XenPCIPassthroughState *s = DO_UPCAST(XenPCIPassthroughState, dev, d);
+    int index = 0;
+    XenPTRegGroup *reg_grp_entry = NULL;
+    int rc = 0;
+    uint32_t read_val = 0;
+    int emul_len = 0;
+    XenPTReg *reg_entry = NULL;
+    uint32_t find_addr = addr;
+    XenPTRegInfo *reg = NULL;
+
+    if (xen_pt_pci_config_access_check(d, addr, len)) {
+        return;
+    }
+
+    XEN_PT_LOG_CONFIG(d, addr, val, len);
+
+    /* check unused BAR register */
+    index = xen_pt_bar_offset_to_index(addr);
+    if ((index >= 0) && (val > 0 && val < XEN_PT_BAR_ALLF) &&
+        (s->bases[index].bar_flag == XEN_PT_BAR_FLAG_UNUSED)) {
+        XEN_PT_WARN(d, "Guest attempt to set address to unused Base Address "
+                    "Register. (addr: 0x%02x, len: %d)\n", addr, len);
+    }
+
+    /* find register group entry */
+    reg_grp_entry = xen_pt_find_reg_grp(s, addr);
+    if (reg_grp_entry) {
+        /* check 0-Hardwired register group */
+        if (reg_grp_entry->reg_grp->grp_type == XEN_PT_GRP_TYPE_HARDWIRED) {
+            /* ignore silently */
+            XEN_PT_WARN(d, "Access to 0-Hardwired register. "
+                        "(addr: 0x%02x, len: %d)\n", addr, len);
+            return;
+        }
+    }
+
+    rc = xen_host_pci_get_block(&s->real_device, addr,
+                                (uint8_t *)&read_val, len);
+    if (rc < 0) {
+        XEN_PT_ERR(d, "pci_read_block failed. return value: %d.\n", rc);
+        memset(&read_val, 0xff, len);
+    }
+
+    /* pass directly to the real device for passthrough type register group */
+    if (reg_grp_entry == NULL) {
+        goto out;
+    }
+
+    memory_region_transaction_begin();
+    pci_default_write_config(d, addr, val, len);
+
+    /* adjust the read and write value to appropriate CFC-CFF window */
+    read_val <<= (addr & 3) << 3;
+    val <<= (addr & 3) << 3;
+    emul_len = len;
+
+    /* loop around the guest requested size */
+    while (emul_len > 0) {
+        /* find register entry to be emulated */
+        reg_entry = xen_pt_find_reg(reg_grp_entry, find_addr);
+        if (reg_entry) {
+            reg = reg_entry->reg;
+            uint32_t real_offset = reg_grp_entry->base_offset + reg->offset;
+            uint32_t valid_mask = 0xFFFFFFFF >> ((4 - emul_len) << 3);
+            uint8_t *ptr_val = NULL;
+
+            valid_mask <<= (find_addr - real_offset) << 3;
+            ptr_val = (uint8_t *)&val + (real_offset & 3);
+
+            /* do emulation based on register size */
+            switch (reg->size) {
+            case 1:
+                if (reg->u.b.write) {
+                    rc = reg->u.b.write(s, reg_entry, ptr_val,
+                                        read_val >> ((real_offset & 3) << 3),
+                                        valid_mask);
+                }
+                break;
+            case 2:
+                if (reg->u.w.write) {
+                    rc = reg->u.w.write(s, reg_entry, (uint16_t *)ptr_val,
+                                        (read_val >> ((real_offset & 3) << 3)),
+                                        valid_mask);
+                }
+                break;
+            case 4:
+                if (reg->u.dw.write) {
+                    rc = reg->u.dw.write(s, reg_entry, (uint32_t *)ptr_val,
+                                         (read_val >> ((real_offset & 3) << 3)),
+                                         valid_mask);
+                }
+                break;
+            }
+
+            if (rc < 0) {
+                xen_shutdown_fatal_error("Internal error: Invalid write"
+                                         " emulation. (%s, rc: %d)\n",
+                                         __func__, rc);
+                return;
+            }
+
+            /* calculate next address to find */
+            emul_len -= reg->size;
+            if (emul_len > 0) {
+                find_addr = real_offset + reg->size;
+            }
+        } else {
+            /* nothing to do with passthrough type register,
+             * continue to find next byte */
+            emul_len--;
+            find_addr++;
+        }
+    }
+
+    /* need to shift back before passing them to xen_host_pci_device */
+    val >>= (addr & 3) << 3;
+
+    memory_region_transaction_commit();
+
+out:
+    if (!(reg && reg->no_wb)) {
+        /* unknown regs are passed through */
+        rc = xen_host_pci_set_block(&s->real_device, addr,
+                                    (uint8_t *)&val, len);
+
+        if (rc < 0) {
+            XEN_PT_ERR(d, "pci_write_block failed. return value: %d.\n", rc);
+        }
+    }
+}
+
+/* register regions */
+
+static uint64_t xen_pt_bar_read(void *o, target_phys_addr_t addr,
+                                unsigned size)
+{
+    PCIDevice *d = o;
+    /* if this function is called, that probably means that there is a
+     * misconfiguration of the IOMMU. */
+    XEN_PT_ERR(d, "Should not read BAR through QEMU. @0x"TARGET_FMT_plx"\n",
+               addr);
+    return 0;
+}
+static void xen_pt_bar_write(void *o, target_phys_addr_t addr, uint64_t val,
+                             unsigned size)
+{
+    PCIDevice *d = o;
+    /* Same comment as xen_pt_bar_read function */
+    XEN_PT_ERR(d, "Should not write BAR through QEMU. @0x"TARGET_FMT_plx"\n",
+               addr);
+}
+
+static const MemoryRegionOps ops = {
+    .endianness = DEVICE_NATIVE_ENDIAN,
+    .read = xen_pt_bar_read,
+    .write = xen_pt_bar_write,
+};
+
+static int xen_pt_register_regions(XenPCIPassthroughState *s)
+{
+    int i = 0;
+    XenHostPCIDevice *d = &s->real_device;
+
+    /* Register PIO/MMIO BARs */
+    for (i = 0; i < PCI_ROM_SLOT; i++) {
+        XenHostPCIIORegion *r = &d->io_regions[i];
+        uint8_t type;
+
+        if (r->base_addr == 0 || r->size == 0) {
+            continue;
+        }
+
+        s->bases[i].access.u = r->base_addr;
+
+        if (r->type & XEN_HOST_PCI_REGION_TYPE_IO) {
+            type = PCI_BASE_ADDRESS_SPACE_IO;
+        } else {
+            type = PCI_BASE_ADDRESS_SPACE_MEMORY;
+            if (r->type & XEN_HOST_PCI_REGION_TYPE_PREFETCH) {
+                type |= PCI_BASE_ADDRESS_MEM_PREFETCH;
+            }
+        }
+
+        memory_region_init_io(&s->bar[i], &ops, &s->dev,
+                              "xen-pci-pt-bar", r->size);
+        pci_register_bar(&s->dev, i, type, &s->bar[i]);
+
+        XEN_PT_LOG(&s->dev, "IO region %i registered (size=0x%08"PRIx64
+                   " base_addr=0x%08"PRIx64" type: %#x)\n",
+                   i, r->size, r->base_addr, type);
+    }
+
+    /* Register expansion ROM address */
+    if (d->rom.base_addr && d->rom.size) {
+        uint32_t bar_data = 0;
+
+        /* Re-set BAR reported by OS, otherwise ROM can't be read. */
+        if (xen_host_pci_get_long(d, PCI_ROM_ADDRESS, &bar_data)) {
+            return 0;
+        }
+        if ((bar_data & PCI_ROM_ADDRESS_MASK) == 0) {
+            bar_data |= d->rom.base_addr & PCI_ROM_ADDRESS_MASK;
+            xen_host_pci_set_long(d, PCI_ROM_ADDRESS, bar_data);
+        }
+
+        s->bases[PCI_ROM_SLOT].access.maddr = d->rom.base_addr;
+
+        memory_region_init_rom_device(&s->rom, NULL, NULL,
+                                      "xen-pci-pt-rom", d->rom.size);
+        pci_register_bar(&s->dev, PCI_ROM_SLOT, PCI_BASE_ADDRESS_MEM_PREFETCH,
+                         &s->rom);
+
+        XEN_PT_LOG(&s->dev, "Expansion ROM registered (size=0x%08"PRIx64
+                   " base_addr=0x%08"PRIx64")\n",
+                   d->rom.size, d->rom.base_addr);
+    }
+
+    return 0;
+}
+
+static void xen_pt_unregister_regions(XenPCIPassthroughState *s)
+{
+    XenHostPCIDevice *d = &s->real_device;
+    int i;
+
+    for (i = 0; i < PCI_NUM_REGIONS - 1; i++) {
+        XenHostPCIIORegion *r = &d->io_regions[i];
+
+        if (r->base_addr == 0 || r->size == 0) {
+            continue;
+        }
+
+        memory_region_destroy(&s->bar[i]);
+    }
+    if (d->rom.base_addr && d->rom.size) {
+        memory_region_destroy(&s->rom);
+    }
+}
+
+/* region mapping */
+
+static int xen_pt_bar_from_region(XenPCIPassthroughState *s, MemoryRegion *mr)
+{
+    int i = 0;
+
+    for (i = 0; i < PCI_NUM_REGIONS - 1; i++) {
+        if (mr == &s->bar[i]) {
+            return i;
+        }
+    }
+    if (mr == &s->rom) {
+        return PCI_ROM_SLOT;
+    }
+    return -1;
+}
+
+/*
+ * This function checks if an io_region overlaps an io_region from another
+ * device.  The io_region to check is provided with (addr, size and type)
+ * A callback can be provided and will be called for every region that is
+ * overlapped.
+ * The return value indicates if the region is overlappsed */
+struct CheckBarArgs {
+    XenPCIPassthroughState *s;
+    pcibus_t addr;
+    pcibus_t size;
+    uint8_t type;
+    bool rc;
+};
+static void xen_pt_check_bar_overlap(PCIBus *bus, PCIDevice *d, void *opaque)
+{
+    struct CheckBarArgs *arg = opaque;
+    XenPCIPassthroughState *s = arg->s;
+    uint8_t type = arg->type;
+    int i;
+
+    if (d->devfn == s->dev.devfn) {
+        return;
+    }
+
+    /* xxx: This ignores bridges. */
+    for (i = 0; i < PCI_NUM_REGIONS; i++) {
+        const PCIIORegion *r = &d->io_regions[i];
+
+        if (!r->size) {
+            continue;
+        }
+        if ((type & PCI_BASE_ADDRESS_SPACE_IO)
+            != (r->type & PCI_BASE_ADDRESS_SPACE_IO)) {
+            continue;
+        }
+
+        if (ranges_overlap(arg->addr, arg->size, r->addr, r->size)) {
+            XEN_PT_WARN(&s->dev,
+                        "Overlapped to device [%02x:%02x.%d] Region: %i"
+                        " (addr: %#"FMT_PCIBUS", len: %#"FMT_PCIBUS")\n",
+                        pci_bus_num(bus), PCI_SLOT(d->devfn),
+                        PCI_FUNC(d->devfn), i, r->addr, r->size);
+            arg->rc = true;
+        }
+    }
+}
+
+static void xen_pt_region_update(XenPCIPassthroughState *s,
+                                 MemoryRegionSection *sec, bool adding)
+{
+    PCIDevice *d = &s->dev;
+    MemoryRegion *mr = sec->mr;
+    int bar = -1;
+    int rc;
+    int op = adding ? DPCI_ADD_MAPPING : DPCI_REMOVE_MAPPING;
+    struct CheckBarArgs args = {
+        .s = s,
+        .addr = sec->offset_within_address_space,
+        .size = sec->size,
+        .rc = false,
+    };
+
+    bar = xen_pt_bar_from_region(s, mr);
+    if (bar == -1) {
+        return;
+    }
+
+    args.type = d->io_regions[bar].type;
+    pci_for_each_device(d->bus, pci_bus_num(d->bus),
+                        xen_pt_check_bar_overlap, &args);
+    if (args.rc) {
+        XEN_PT_WARN(d, "Region: %d (addr: %#"FMT_PCIBUS
+                    ", len: %#"FMT_PCIBUS") is overlapped.\n",
+                    bar, sec->offset_within_address_space, sec->size);
+    }
+
+    if (d->io_regions[bar].type & PCI_BASE_ADDRESS_SPACE_IO) {
+        uint32_t guest_port = sec->offset_within_address_space;
+        uint32_t machine_port = s->bases[bar].access.pio_base;
+        uint32_t size = sec->size;
+        rc = xc_domain_ioport_mapping(xen_xc, xen_domid,
+                                      guest_port, machine_port, size,
+                                      op);
+        if (rc) {
+            XEN_PT_ERR(d, "%s ioport mapping failed! (rc: %i)\n",
+                       adding ? "create new" : "remove old", rc);
+        }
+    } else {
+        pcibus_t guest_addr = sec->offset_within_address_space;
+        pcibus_t machine_addr = s->bases[bar].access.maddr
+            + sec->offset_within_region;
+        pcibus_t size = sec->size;
+        rc = xc_domain_memory_mapping(xen_xc, xen_domid,
+                                      XEN_PFN(guest_addr + XC_PAGE_SIZE - 1),
+                                      XEN_PFN(machine_addr + XC_PAGE_SIZE - 1),
+                                      XEN_PFN(size + XC_PAGE_SIZE - 1),
+                                      op);
+        if (rc) {
+            XEN_PT_ERR(d, "%s mem mapping failed! (rc: %i)\n",
+                       adding ? "create new" : "remove old", rc);
+        }
+    }
+}
+
+static void xen_pt_begin(MemoryListener *l)
+{
+}
+
+static void xen_pt_commit(MemoryListener *l)
+{
+}
+
+static void xen_pt_region_add(MemoryListener *l, MemoryRegionSection *sec)
+{
+    XenPCIPassthroughState *s = container_of(l, XenPCIPassthroughState,
+                                             memory_listener);
+
+    xen_pt_region_update(s, sec, true);
+}
+
+static void xen_pt_region_del(MemoryListener *l, MemoryRegionSection *sec)
+{
+    XenPCIPassthroughState *s = container_of(l, XenPCIPassthroughState,
+                                             memory_listener);
+
+    xen_pt_region_update(s, sec, false);
+}
+
+static void xen_pt_region_nop(MemoryListener *l, MemoryRegionSection *s)
+{
+}
+
+static void xen_pt_log_fns(MemoryListener *l, MemoryRegionSection *s)
+{
+}
+
+static void xen_pt_log_global_fns(MemoryListener *l)
+{
+}
+
+static void xen_pt_eventfd_fns(MemoryListener *l, MemoryRegionSection *s,
+                               bool match_data, uint64_t data, int fd)
+{
+}
+
+static const MemoryListener xen_pt_memory_listener = {
+    .begin = xen_pt_begin,
+    .commit = xen_pt_commit,
+    .region_add = xen_pt_region_add,
+    .region_nop = xen_pt_region_nop,
+    .region_del = xen_pt_region_del,
+    .log_start = xen_pt_log_fns,
+    .log_stop = xen_pt_log_fns,
+    .log_sync = xen_pt_log_fns,
+    .log_global_start = xen_pt_log_global_fns,
+    .log_global_stop = xen_pt_log_global_fns,
+    .eventfd_add = xen_pt_eventfd_fns,
+    .eventfd_del = xen_pt_eventfd_fns,
+    .priority = 10,
+};
+
+/* init */
+
+static int xen_pt_initfn(PCIDevice *d)
+{
+    XenPCIPassthroughState *s = DO_UPCAST(XenPCIPassthroughState, dev, d);
+    int rc = 0;
+    uint8_t machine_irq = 0;
+    int pirq = XEN_PT_UNASSIGNED_PIRQ;
+
+    /* register real device */
+    XEN_PT_LOG(d, "Assigning real physical device %02x:%02x.%d"
+               " to devfn %#x\n",
+               s->hostaddr.bus, s->hostaddr.slot, s->hostaddr.function,
+               s->dev.devfn);
+
+    rc = xen_host_pci_device_get(&s->real_device,
+                                 s->hostaddr.domain, s->hostaddr.bus,
+                                 s->hostaddr.slot, s->hostaddr.function);
+    if (rc) {
+        XEN_PT_ERR(d, "Failed to \"open\" the real pci device. rc: %i\n", rc);
+        return -1;
+    }
+
+    s->is_virtfn = s->real_device.is_virtfn;
+    if (s->is_virtfn) {
+        XEN_PT_LOG(d, "%04x:%02x:%02x.%d is a SR-IOV Virtual Function\n",
+                   s->real_device.domain, bus, slot, func);
+    }
+
+    /* Initialize virtualized PCI configuration (Extended 256 Bytes) */
+    if (xen_host_pci_get_block(&s->real_device, 0, d->config,
+                               PCI_CONFIG_SPACE_SIZE) == -1) {
+        xen_host_pci_device_put(&s->real_device);
+        return -1;
+    }
+
+    s->memory_listener = xen_pt_memory_listener;
+
+    /* Handle real device's MMIO/PIO BARs */
+    xen_pt_register_regions(s);
+
+    /* Bind interrupt */
+    if (!s->dev.config[PCI_INTERRUPT_PIN]) {
+        XEN_PT_LOG(d, "no pin interrupt\n");
+        goto out;
+    }
+
+    machine_irq = s->real_device.irq;
+    rc = xc_physdev_map_pirq(xen_xc, xen_domid, machine_irq, &pirq);
+
+    if (rc < 0) {
+        XEN_PT_ERR(d, "Mapping machine irq %u to pirq %i failed, (rc: %d)\n",
+                   machine_irq, pirq, rc);
+
+        /* Disable PCI intx assertion (turn on bit10 of devctl) */
+        xen_host_pci_set_word(&s->real_device,
+                              PCI_COMMAND,
+                              pci_get_word(s->dev.config + PCI_COMMAND)
+                              | PCI_COMMAND_INTX_DISABLE);
+        machine_irq = 0;
+        s->machine_irq = 0;
+    } else {
+        machine_irq = pirq;
+        s->machine_irq = pirq;
+        xen_pt_mapped_machine_irq[machine_irq]++;
+    }
+
+    /* bind machine_irq to device */
+    if (machine_irq != 0) {
+        uint8_t e_intx = xen_pt_pci_intx(s);
+
+        rc = xc_domain_bind_pt_pci_irq(xen_xc, xen_domid, machine_irq,
+                                       pci_bus_num(d->bus),
+                                       PCI_SLOT(d->devfn),
+                                       e_intx);
+        if (rc < 0) {
+            XEN_PT_ERR(d, "Binding of interrupt %i failed! (rc: %d)\n",
+                       e_intx, rc);
+
+            /* Disable PCI intx assertion (turn on bit10 of devctl) */
+            xen_host_pci_set_word(&s->real_device, PCI_COMMAND,
+                                  *(uint16_t *)(&s->dev.config[PCI_COMMAND])
+                                  | PCI_COMMAND_INTX_DISABLE);
+            xen_pt_mapped_machine_irq[machine_irq]--;
+
+            if (xen_pt_mapped_machine_irq[machine_irq] == 0) {
+                if (xc_physdev_unmap_pirq(xen_xc, xen_domid, machine_irq)) {
+                    XEN_PT_ERR(d, "Unmapping of machine interrupt %i failed!"
+                               " (rc: %d)\n", machine_irq, rc);
+                }
+            }
+            s->machine_irq = 0;
+        }
+    }
+
+out:
+    memory_listener_register(&s->memory_listener, NULL);
+    XEN_PT_LOG(d, "Real physical device %02x:%02x.%d registered successfuly!\n",
+               bus, slot, func);
+
+    return 0;
+}
+
+static int xen_pt_unregister_device(PCIDevice *d)
+{
+    XenPCIPassthroughState *s = DO_UPCAST(XenPCIPassthroughState, dev, d);
+    uint8_t machine_irq = s->machine_irq;
+    uint8_t intx = xen_pt_pci_intx(s);
+    int rc;
+
+    if (machine_irq) {
+        rc = xc_domain_unbind_pt_irq(xen_xc, xen_domid, machine_irq,
+                                     PT_IRQ_TYPE_PCI,
+                                     pci_bus_num(d->bus),
+                                     PCI_SLOT(s->dev.devfn),
+                                     intx,
+                                     0 /* isa_irq */);
+        if (rc < 0) {
+            XEN_PT_ERR(d, "unbinding of interrupt INT%c failed."
+                       " (machine irq: %i, rc: %d)"
+                       " But bravely continuing on..\n",
+                       'a' + intx, machine_irq, rc);
+        }
+    }
+
+    if (machine_irq) {
+        xen_pt_mapped_machine_irq[machine_irq]--;
+
+        if (xen_pt_mapped_machine_irq[machine_irq] == 0) {
+            rc = xc_physdev_unmap_pirq(xen_xc, xen_domid, machine_irq);
+
+            if (rc < 0) {
+                XEN_PT_ERR(d, "unmapping of interrupt %i failed. (rc: %d)"
+                           " But bravely continuing on..\n",
+                           machine_irq, rc);
+            }
+        }
+    }
+
+    xen_pt_unregister_regions(s);
+    memory_listener_unregister(&s->memory_listener);
+
+    xen_host_pci_device_put(&s->real_device);
+
+    return 0;
+}
+
+static Property xen_pci_passthrough_properties[] = {
+    DEFINE_PROP_PCI_HOST_DEVADDR("hostaddr", XenPCIPassthroughState, hostaddr),
+    DEFINE_PROP_END_OF_LIST(),
+};
+
+static void xen_pci_passthrough_class_init(ObjectClass *klass, void *data)
+{
+    DeviceClass *dc = DEVICE_CLASS(klass);
+    PCIDeviceClass *k = PCI_DEVICE_CLASS(klass);
+
+    k->init = xen_pt_initfn;
+    k->exit = xen_pt_unregister_device;
+    k->config_read = xen_pt_pci_read_config;
+    k->config_write = xen_pt_pci_write_config;
+    dc->desc = "Assign an host PCI device with Xen";
+    dc->props = xen_pci_passthrough_properties;
+};
+
+static TypeInfo xen_pci_passthrough_info = {
+    .name = "xen-pci-passthrough",
+    .parent = TYPE_PCI_DEVICE,
+    .instance_size = sizeof(XenPCIPassthroughState),
+    .class_init = xen_pci_passthrough_class_init,
+};
+
+static void xen_pci_passthrough_register_types(void)
+{
+    type_register_static(&xen_pci_passthrough_info);
+}
+
+type_init(xen_pci_passthrough_register_types)
diff --git a/hw/xen_pt.h b/hw/xen_pt.h
new file mode 100644
index 0000000..36001a7
--- /dev/null
+++ b/hw/xen_pt.h
@@ -0,0 +1,248 @@
+#ifndef XEN_PT_H
+#define XEN_PT_H
+
+#include "qemu-common.h"
+#include "xen_common.h"
+#include "pci.h"
+#include "xen-host-pci-device.h"
+
+void xen_pt_log(const PCIDevice *d, const char *f, ...) GCC_FMT_ATTR(2, 3);
+
+#define XEN_PT_ERR(d, _f, _a...) xen_pt_log(d, "%s: Error: "_f, __func__, ##_a)
+
+#ifdef XEN_PT_LOGGING_ENABLED
+#  define XEN_PT_LOG(d, _f, _a...)  xen_pt_log(d, "%s: " _f, __func__, ##_a)
+#  define XEN_PT_WARN(d, _f, _a...) \
+    xen_pt_log(d, "%s: Warning: "_f, __func__, ##_a)
+#else
+#  define XEN_PT_LOG(d, _f, _a...)
+#  define XEN_PT_WARN(d, _f, _a...)
+#endif
+
+#ifdef XEN_PT_DEBUG_PCI_CONFIG_ACCESS
+#  define XEN_PT_LOG_CONFIG(d, addr, val, len) \
+    xen_pt_log(d, "%s: address=0x%04x val=0x%08x len=%d\n", \
+               __func__, addr, val, len)
+#else
+#  define XEN_PT_LOG_CONFIG(d, addr, val, len)
+#endif
+
+
+/* Helper */
+#define XEN_PFN(x) ((x) >> XC_PAGE_SHIFT)
+
+typedef struct XenPTRegInfo XenPTRegInfo;
+typedef struct XenPTReg XenPTReg;
+
+typedef struct XenPCIPassthroughState XenPCIPassthroughState;
+
+/* function type for config reg */
+typedef int (*xen_pt_conf_reg_init)
+    (XenPCIPassthroughState *, XenPTRegInfo *, uint32_t real_offset,
+     uint32_t *data);
+typedef int (*xen_pt_conf_dword_write)
+    (XenPCIPassthroughState *, XenPTReg *cfg_entry,
+     uint32_t *val, uint32_t dev_value, uint32_t valid_mask);
+typedef int (*xen_pt_conf_word_write)
+    (XenPCIPassthroughState *, XenPTReg *cfg_entry,
+     uint16_t *val, uint16_t dev_value, uint16_t valid_mask);
+typedef int (*xen_pt_conf_byte_write)
+    (XenPCIPassthroughState *, XenPTReg *cfg_entry,
+     uint8_t *val, uint8_t dev_value, uint8_t valid_mask);
+typedef int (*xen_pt_conf_dword_read)
+    (XenPCIPassthroughState *, XenPTReg *cfg_entry,
+     uint32_t *val, uint32_t valid_mask);
+typedef int (*xen_pt_conf_word_read)
+    (XenPCIPassthroughState *, XenPTReg *cfg_entry,
+     uint16_t *val, uint16_t valid_mask);
+typedef int (*xen_pt_conf_byte_read)
+    (XenPCIPassthroughState *, XenPTReg *cfg_entry,
+     uint8_t *val, uint8_t valid_mask);
+
+#define XEN_PT_BAR_ALLF 0xFFFFFFFF
+#define XEN_PT_BAR_UNMAPPED (-1)
+
+
+typedef enum {
+    XEN_PT_GRP_TYPE_HARDWIRED = 0,  /* 0 Hardwired reg group */
+    XEN_PT_GRP_TYPE_EMU,            /* emul reg group */
+} XenPTRegisterGroupType;
+
+typedef enum {
+    XEN_PT_BAR_FLAG_MEM = 0,        /* Memory type BAR */
+    XEN_PT_BAR_FLAG_IO,             /* I/O type BAR */
+    XEN_PT_BAR_FLAG_UPPER,          /* upper 64bit BAR */
+    XEN_PT_BAR_FLAG_UNUSED,         /* unused BAR */
+} XenPTBarFlag;
+
+
+typedef struct XenPTRegion {
+    /* BAR flag */
+    XenPTBarFlag bar_flag;
+    /* Translation of the emulated address */
+    union {
+        uint64_t maddr;
+        uint64_t pio_base;
+        uint64_t u;
+    } access;
+} XenPTRegion;
+
+/* XenPTRegInfo declaration
+ * - only for emulated register (either a part or whole bit).
+ * - for passthrough register that need special behavior (like interacting with
+ *   other component), set emu_mask to all 0 and specify r/w func properly.
+ * - do NOT use ALL F for init_val, otherwise the tbl will not be registered.
+ */
+
+/* emulated register infomation */
+struct XenPTRegInfo {
+    uint32_t offset;
+    uint32_t size;
+    uint32_t init_val;
+    /* reg read only field mask (ON:RO/ROS, OFF:other) */
+    uint32_t ro_mask;
+    /* reg emulate field mask (ON:emu, OFF:passthrough) */
+    uint32_t emu_mask;
+    /* no write back allowed */
+    uint32_t no_wb;
+    xen_pt_conf_reg_init init;
+    /* read/write function pointer
+     * for double_word/word/byte size */
+    union {
+        struct {
+            xen_pt_conf_dword_write write;
+            xen_pt_conf_dword_read read;
+        } dw;
+        struct {
+            xen_pt_conf_word_write write;
+            xen_pt_conf_word_read read;
+        } w;
+        struct {
+            xen_pt_conf_byte_write write;
+            xen_pt_conf_byte_read read;
+        } b;
+    } u;
+};
+
+/* emulated register management */
+struct XenPTReg {
+    QLIST_ENTRY(XenPTReg) entries;
+    XenPTRegInfo *reg;
+    uint32_t data; /* emulated value */
+};
+
+typedef struct XenPTRegGroupInfo XenPTRegGroupInfo;
+
+/* emul reg group size initialize method */
+typedef int (*xen_pt_reg_size_init_fn)
+    (XenPCIPassthroughState *, const XenPTRegGroupInfo *,
+     uint32_t base_offset, uint8_t *size);
+
+/* emulated register group infomation */
+struct XenPTRegGroupInfo {
+    uint8_t grp_id;
+    XenPTRegisterGroupType grp_type;
+    uint8_t grp_size;
+    xen_pt_reg_size_init_fn size_init;
+    XenPTRegInfo *emu_regs;
+};
+
+/* emul register group management table */
+typedef struct XenPTRegGroup {
+    QLIST_ENTRY(XenPTRegGroup) entries;
+    const XenPTRegGroupInfo *reg_grp;
+    uint32_t base_offset;
+    uint8_t size;
+    QLIST_HEAD(, XenPTReg) reg_tbl_list;
+} XenPTRegGroup;
+
+
+#define XEN_PT_UNASSIGNED_PIRQ (-1)
+
+struct XenPCIPassthroughState {
+    PCIDevice dev;
+
+    PCIHostDeviceAddress hostaddr;
+    bool is_virtfn;
+    XenHostPCIDevice real_device;
+    XenPTRegion bases[PCI_NUM_REGIONS]; /* Access regions */
+    QLIST_HEAD(, XenPTRegGroup) reg_grps;
+
+    uint32_t machine_irq;
+
+    MemoryRegion bar[PCI_NUM_REGIONS - 1];
+    MemoryRegion rom;
+
+    MemoryListener memory_listener;
+};
+
+int xen_pt_config_init(XenPCIPassthroughState *s);
+void xen_pt_config_delete(XenPCIPassthroughState *s);
+XenPTRegGroup *xen_pt_find_reg_grp(XenPCIPassthroughState *s, uint32_t address);
+XenPTReg *xen_pt_find_reg(XenPTRegGroup *reg_grp, uint32_t address);
+int xen_pt_bar_offset_to_index(uint32_t offset);
+
+static inline pcibus_t xen_pt_get_emul_size(XenPTBarFlag flag, pcibus_t r_size)
+{
+    /* align resource size (memory type only) */
+    if (flag == XEN_PT_BAR_FLAG_MEM) {
+        return (r_size + XC_PAGE_SIZE - 1) & XC_PAGE_MASK;
+    } else {
+        return r_size;
+    }
+}
+
+/* INTx */
+/* The PCI Local Bus Specification, Rev. 3.0,
+ * Section 6.2.4 Miscellaneous Registers, pp 223
+ * outlines 5 valid values for the interrupt pin (intx).
+ *  0: For devices (or device functions) that don't use an interrupt in
+ *  1: INTA#
+ *  2: INTB#
+ *  3: INTC#
+ *  4: INTD#
+ *
+ * Xen uses the following 4 values for intx
+ *  0: INTA#
+ *  1: INTB#
+ *  2: INTC#
+ *  3: INTD#
+ *
+ * Observing that these list of values are not the same, xen_pt_pci_read_intx()
+ * uses the following mapping from hw to xen values.
+ * This seems to reflect the current usage within Xen.
+ *
+ * PCI hardware    | Xen | Notes
+ * ----------------+-----+----------------------------------------------------
+ * 0               | 0   | No interrupt
+ * 1               | 0   | INTA#
+ * 2               | 1   | INTB#
+ * 3               | 2   | INTC#
+ * 4               | 3   | INTD#
+ * any other value | 0   | This should never happen, log error message
+ */
+
+static inline uint8_t xen_pt_pci_read_intx(XenPCIPassthroughState *s)
+{
+    uint8_t v = 0;
+    xen_host_pci_get_byte(&s->real_device, PCI_INTERRUPT_PIN, &v);
+    return v;
+}
+
+static inline uint8_t xen_pt_pci_intx(XenPCIPassthroughState *s)
+{
+    uint8_t r_val = xen_pt_pci_read_intx(s);
+
+    XEN_PT_LOG(&s->dev, "intx=%i\n", r_val);
+    if (r_val < 1 || r_val > 4) {
+        XEN_PT_LOG(&s->dev, "Interrupt pin read from hardware is out of range:"
+                   " value=%i, acceptable range is 1 - 4\n", r_val);
+        r_val = 0;
+    } else {
+        r_val -= 1;
+    }
+
+    return r_val;
+}
+
+#endif /* !XEN_PT_H */
diff --git a/hw/xen_pt_config_init.c b/hw/xen_pt_config_init.c
new file mode 100644
index 0000000..64d22e8
--- /dev/null
+++ b/hw/xen_pt_config_init.c
@@ -0,0 +1,11 @@
+#include "xen_pt.h"
+
+XenPTRegGroup *xen_pt_find_reg_grp(XenPCIPassthroughState *s, uint32_t address)
+{
+    return NULL;
+}
+
+XenPTReg *xen_pt_find_reg(XenPTRegGroup *reg_grp, uint32_t address)
+{
+    return NULL;
+}
diff --git a/xen-all.c b/xen-all.c
index b5220cc..59f2323 100644
--- a/xen-all.c
+++ b/xen-all.c
@@ -1191,3 +1191,15 @@ void xen_register_framebuffer(MemoryRegion *mr)
 {
     framebuffer = mr;
 }
+
+void xen_shutdown_fatal_error(const char *fmt, ...)
+{
+    va_list ap;
+
+    va_start(ap, fmt);
+    vfprintf(stderr, fmt, ap);
+    va_end(ap);
+    fprintf(stderr, "Will destroy the domain.\n");
+    /* destroy the domain */
+    qemu_system_shutdown_request();
+}
commit 679042f0e1eac0af1e03759efe8761e7b4422588
Author: Anthony PERARD <anthony.perard at citrix.com>
Date:   Thu Jun 21 15:36:23 2012 +0000

    qdev-properties: Introduce pci-host-devaddr.
    
    This new property will be used to specify a host pci device address.
    
    Signed-off-by: Anthony PERARD <anthony.perard at citrix.com>
    Acked-by: Michael S. Tsirkin <mst at redhat.com>
    Acked-by: Stefano Stabellini <stefano.stabellini at eu.citrix.com>

diff --git a/hw/qdev-properties.c b/hw/qdev-properties.c
index 099a7aa..0b89462 100644
--- a/hw/qdev-properties.c
+++ b/hw/qdev-properties.c
@@ -899,6 +899,113 @@ PropertyInfo qdev_prop_blocksize = {
     .set   = set_blocksize,
 };
 
+/* --- pci host address --- */
+
+static void get_pci_host_devaddr(Object *obj, Visitor *v, void *opaque,
+                                 const char *name, Error **errp)
+{
+    DeviceState *dev = DEVICE(obj);
+    Property *prop = opaque;
+    PCIHostDeviceAddress *addr = qdev_get_prop_ptr(dev, prop);
+    char buffer[] = "xxxx:xx:xx.x";
+    char *p = buffer;
+    int rc = 0;
+
+    rc = snprintf(buffer, sizeof(buffer), "%04x:%02x:%02x.%d",
+                  addr->domain, addr->bus, addr->slot, addr->function);
+    assert(rc == sizeof(buffer) - 1);
+
+    visit_type_str(v, &p, name, errp);
+}
+
+/*
+ * Parse [<domain>:]<bus>:<slot>.<func>
+ *   if <domain> is not supplied, it's assumed to be 0.
+ */
+static void set_pci_host_devaddr(Object *obj, Visitor *v, void *opaque,
+                                 const char *name, Error **errp)
+{
+    DeviceState *dev = DEVICE(obj);
+    Property *prop = opaque;
+    PCIHostDeviceAddress *addr = qdev_get_prop_ptr(dev, prop);
+    Error *local_err = NULL;
+    char *str, *p;
+    char *e;
+    unsigned long val;
+    unsigned long dom = 0, bus = 0;
+    unsigned int slot = 0, func = 0;
+
+    if (dev->state != DEV_STATE_CREATED) {
+        error_set(errp, QERR_PERMISSION_DENIED);
+        return;
+    }
+
+    visit_type_str(v, &str, name, &local_err);
+    if (local_err) {
+        error_propagate(errp, local_err);
+        return;
+    }
+
+    p = str;
+    val = strtoul(p, &e, 16);
+    if (e == p || *e != ':') {
+        goto inval;
+    }
+    bus = val;
+
+    p = e + 1;
+    val = strtoul(p, &e, 16);
+    if (e == p) {
+        goto inval;
+    }
+    if (*e == ':') {
+        dom = bus;
+        bus = val;
+        p = e + 1;
+        val = strtoul(p, &e, 16);
+        if (e == p) {
+            goto inval;
+        }
+    }
+    slot = val;
+
+    if (*e != '.') {
+        goto inval;
+    }
+    p = e + 1;
+    val = strtoul(p, &e, 10);
+    if (e == p) {
+        goto inval;
+    }
+    func = val;
+
+    if (dom > 0xffff || bus > 0xff || slot > 0x1f || func > 7) {
+        goto inval;
+    }
+
+    if (*e) {
+        goto inval;
+    }
+
+    addr->domain = dom;
+    addr->bus = bus;
+    addr->slot = slot;
+    addr->function = func;
+
+    g_free(str);
+    return;
+
+inval:
+    error_set_from_qdev_prop_error(errp, EINVAL, dev, prop, str);
+    g_free(str);
+}
+
+PropertyInfo qdev_prop_pci_host_devaddr = {
+    .name = "pci-host-devaddr",
+    .get = get_pci_host_devaddr,
+    .set = set_pci_host_devaddr,
+};
+
 /* --- public helpers --- */
 
 static Property *qdev_prop_walk(Property *props, const char *name)
diff --git a/hw/qdev.h b/hw/qdev.h
index ae1d281..f4683dc 100644
--- a/hw/qdev.h
+++ b/hw/qdev.h
@@ -237,6 +237,7 @@ extern PropertyInfo qdev_prop_netdev;
 extern PropertyInfo qdev_prop_vlan;
 extern PropertyInfo qdev_prop_pci_devfn;
 extern PropertyInfo qdev_prop_blocksize;
+extern PropertyInfo qdev_prop_pci_host_devaddr;
 
 #define DEFINE_PROP(_name, _state, _field, _prop, _type) { \
         .name      = (_name),                                    \
@@ -300,6 +301,8 @@ extern PropertyInfo qdev_prop_blocksize;
                         LostTickPolicy)
 #define DEFINE_PROP_BLOCKSIZE(_n, _s, _f, _d) \
     DEFINE_PROP_DEFAULT(_n, _s, _f, _d, qdev_prop_blocksize, uint16_t)
+#define DEFINE_PROP_PCI_HOST_DEVADDR(_n, _s, _f) \
+    DEFINE_PROP(_n, _s, _f, qdev_prop_pci_host_devaddr, PCIHostDeviceAddress)
 
 #define DEFINE_PROP_END_OF_LIST()               \
     {}
diff --git a/qemu-common.h b/qemu-common.h
index 8f87e41..9d9e603 100644
--- a/qemu-common.h
+++ b/qemu-common.h
@@ -275,6 +275,13 @@ typedef enum LostTickPolicy {
     LOST_TICK_MAX
 } LostTickPolicy;
 
+typedef struct PCIHostDeviceAddress {
+    unsigned int domain;
+    unsigned int bus;
+    unsigned int slot;
+    unsigned int function;
+} PCIHostDeviceAddress;
+
 void tcg_exec_init(unsigned long tb_size);
 bool tcg_enabled(void);
 
commit 7aa8cbb9211a7c93d37b79502915df5757d2fb17
Author: Anthony PERARD <anthony.perard at citrix.com>
Date:   Thu Jun 21 15:35:28 2012 +0000

    pci.c: Add opaque argument to pci_for_each_device.
    
    The purpose is to have a more generic pci_for_each_device by passing an extra
    argument to the function called on every device.
    
    This patch will be used in a next patch.
    
    Signed-off-by: Anthony PERARD <anthony.perard at citrix.com>
    Acked-by: Stefano Stabellini <stefano.stabellini at eu.citrix.com>
    Acked-by: Michael S. Tsirkin <mst at redhat.com>
    Reviewed-by: Konrad Rzeszutek Wilk <konrad.wilk at oracle.com>

diff --git a/hw/pci.c b/hw/pci.c
index bdfb3d6..5c75f16 100644
--- a/hw/pci.c
+++ b/hw/pci.c
@@ -1144,7 +1144,9 @@ static const pci_class_desc pci_class_descriptions[] =
 };
 
 static void pci_for_each_device_under_bus(PCIBus *bus,
-                                          void (*fn)(PCIBus *b, PCIDevice *d))
+                                          void (*fn)(PCIBus *b, PCIDevice *d,
+                                                     void *opaque),
+                                          void *opaque)
 {
     PCIDevice *d;
     int devfn;
@@ -1152,18 +1154,19 @@ static void pci_for_each_device_under_bus(PCIBus *bus,
     for(devfn = 0; devfn < ARRAY_SIZE(bus->devices); devfn++) {
         d = bus->devices[devfn];
         if (d) {
-            fn(bus, d);
+            fn(bus, d, opaque);
         }
     }
 }
 
 void pci_for_each_device(PCIBus *bus, int bus_num,
-                         void (*fn)(PCIBus *b, PCIDevice *d))
+                         void (*fn)(PCIBus *b, PCIDevice *d, void *opaque),
+                         void *opaque)
 {
     bus = pci_find_bus_nr(bus, bus_num);
 
     if (bus) {
-        pci_for_each_device_under_bus(bus, fn);
+        pci_for_each_device_under_bus(bus, fn, opaque);
     }
 }
 
diff --git a/hw/pci.h b/hw/pci.h
index 7f223c0..95b608c 100644
--- a/hw/pci.h
+++ b/hw/pci.h
@@ -312,7 +312,9 @@ PCIDevice *pci_nic_init(NICInfo *nd, const char *default_model,
 PCIDevice *pci_nic_init_nofail(NICInfo *nd, const char *default_model,
                                const char *default_devaddr);
 int pci_bus_num(PCIBus *s);
-void pci_for_each_device(PCIBus *bus, int bus_num, void (*fn)(PCIBus *bus, PCIDevice *d));
+void pci_for_each_device(PCIBus *bus, int bus_num,
+                         void (*fn)(PCIBus *bus, PCIDevice *d, void *opaque),
+                         void *opaque);
 PCIBus *pci_find_root_bus(int domain);
 int pci_find_domain(const PCIBus *bus);
 PCIDevice *pci_find_device(PCIBus *bus, int bus_num, uint8_t devfn);
diff --git a/hw/xen_platform.c b/hw/xen_platform.c
index 0214f37..c1fe984 100644
--- a/hw/xen_platform.c
+++ b/hw/xen_platform.c
@@ -83,7 +83,7 @@ static void log_writeb(PCIXenPlatformState *s, char val)
 #define UNPLUG_ALL_NICS 2
 #define UNPLUG_AUX_IDE_DISKS 4
 
-static void unplug_nic(PCIBus *b, PCIDevice *d)
+static void unplug_nic(PCIBus *b, PCIDevice *d, void *o)
 {
     if (pci_get_word(d->config + PCI_CLASS_DEVICE) ==
             PCI_CLASS_NETWORK_ETHERNET) {
@@ -96,10 +96,10 @@ static void unplug_nic(PCIBus *b, PCIDevice *d)
 
 static void pci_unplug_nics(PCIBus *bus)
 {
-    pci_for_each_device(bus, 0, unplug_nic);
+    pci_for_each_device(bus, 0, unplug_nic, NULL);
 }
 
-static void unplug_disks(PCIBus *b, PCIDevice *d)
+static void unplug_disks(PCIBus *b, PCIDevice *d, void *o)
 {
     if (pci_get_word(d->config + PCI_CLASS_DEVICE) ==
             PCI_CLASS_STORAGE_IDE) {
@@ -109,7 +109,7 @@ static void unplug_disks(PCIBus *b, PCIDevice *d)
 
 static void pci_unplug_disks(PCIBus *bus)
 {
-    pci_for_each_device(bus, 0, unplug_disks);
+    pci_for_each_device(bus, 0, unplug_disks, NULL);
 }
 
 static void platform_fixed_ioport_writew(void *opaque, uint32_t addr, uint32_t val)
commit 396af688fcac4495d4805f319c6d05930db63fb4
Author: Anthony PERARD <anthony.perard at citrix.com>
Date:   Thu Jun 21 15:34:24 2012 +0000

    Introduce XenHostPCIDevice to access a pci device on the host.
    
    Signed-off-by: Anthony PERARD <anthony.perard at citrix.com>
    Signed-off-by: Stefano Stabellini <stefano.stabellini at eu.citrix.com>
    Reviewed-by: Konrad Rzeszutek Wilk <konrad.wilk at oracle.com>

diff --git a/hw/i386/Makefile.objs b/hw/i386/Makefile.objs
index eb171b7..b1d318b 100644
--- a/hw/i386/Makefile.objs
+++ b/hw/i386/Makefile.objs
@@ -7,6 +7,7 @@ obj-y += debugcon.o multiboot.o
 obj-y += pc_piix.o
 obj-y += pc_sysfw.o
 obj-$(CONFIG_XEN) += xen_platform.o xen_apic.o
+obj-$(CONFIG_XEN_PCI_PASSTHROUGH) += xen-host-pci-device.o
 obj-y += kvm/
 obj-$(CONFIG_SPICE) += qxl.o qxl-logger.o qxl-render.o
 
diff --git a/hw/xen-host-pci-device.c b/hw/xen-host-pci-device.c
new file mode 100644
index 0000000..e7ff680
--- /dev/null
+++ b/hw/xen-host-pci-device.c
@@ -0,0 +1,396 @@
+/*
+ * Copyright (C) 2011       Citrix Ltd.
+ *
+ * This work is licensed under the terms of the GNU GPL, version 2.  See
+ * the COPYING file in the top-level directory.
+ *
+ */
+
+#include "qemu-common.h"
+#include "xen-host-pci-device.h"
+
+#define XEN_HOST_PCI_MAX_EXT_CAP \
+    ((PCIE_CONFIG_SPACE_SIZE - PCI_CONFIG_SPACE_SIZE) / (PCI_CAP_SIZEOF + 4))
+
+#ifdef XEN_HOST_PCI_DEVICE_DEBUG
+#  define XEN_HOST_PCI_LOG(f, a...) fprintf(stderr, "%s: " f, __func__, ##a)
+#else
+#  define XEN_HOST_PCI_LOG(f, a...) (void)0
+#endif
+
+/*
+ * from linux/ioport.h
+ * IO resources have these defined flags.
+ */
+#define IORESOURCE_BITS         0x000000ff      /* Bus-specific bits */
+
+#define IORESOURCE_TYPE_BITS    0x00000f00      /* Resource type */
+#define IORESOURCE_IO           0x00000100
+#define IORESOURCE_MEM          0x00000200
+
+#define IORESOURCE_PREFETCH     0x00001000      /* No side effects */
+#define IORESOURCE_MEM_64       0x00100000
+
+static int xen_host_pci_sysfs_path(const XenHostPCIDevice *d,
+                                   const char *name, char *buf, ssize_t size)
+{
+    int rc;
+
+    rc = snprintf(buf, size, "/sys/bus/pci/devices/%04x:%02x:%02x.%d/%s",
+                  d->domain, d->bus, d->dev, d->func, name);
+
+    if (rc >= size || rc < 0) {
+        /* The ouput is truncated or an other error is encountered */
+        return -ENODEV;
+    }
+    return 0;
+}
+
+
+/* This size should be enough to read the first 7 lines of a ressource file */
+#define XEN_HOST_PCI_RESSOURCE_BUFFER_SIZE 400
+static int xen_host_pci_get_resource(XenHostPCIDevice *d)
+{
+    int i, rc, fd;
+    char path[PATH_MAX];
+    char buf[XEN_HOST_PCI_RESSOURCE_BUFFER_SIZE];
+    unsigned long long start, end, flags, size;
+    char *endptr, *s;
+    uint8_t type;
+
+    rc = xen_host_pci_sysfs_path(d, "resource", path, sizeof (path));
+    if (rc) {
+        return rc;
+    }
+    fd = open(path, O_RDONLY);
+    if (fd == -1) {
+        XEN_HOST_PCI_LOG("Error: Can't open %s: %s\n", path, strerror(errno));
+        return -errno;
+    }
+
+    do {
+        rc = read(fd, &buf, sizeof (buf) - 1);
+        if (rc < 0 && errno != EINTR) {
+            rc = -errno;
+            goto out;
+        }
+    } while (rc < 0);
+    buf[rc] = 0;
+    rc = 0;
+
+    s = buf;
+    for (i = 0; i < PCI_NUM_REGIONS; i++) {
+        type = 0;
+
+        start = strtoll(s, &endptr, 16);
+        if (*endptr != ' ' || s == endptr) {
+            break;
+        }
+        s = endptr + 1;
+        end = strtoll(s, &endptr, 16);
+        if (*endptr != ' ' || s == endptr) {
+            break;
+        }
+        s = endptr + 1;
+        flags = strtoll(s, &endptr, 16);
+        if (*endptr != '\n' || s == endptr) {
+            break;
+        }
+        s = endptr + 1;
+
+        if (start) {
+            size = end - start + 1;
+        } else {
+            size = 0;
+        }
+
+        if (flags & IORESOURCE_IO) {
+            type |= XEN_HOST_PCI_REGION_TYPE_IO;
+        }
+        if (flags & IORESOURCE_MEM) {
+            type |= XEN_HOST_PCI_REGION_TYPE_MEM;
+        }
+        if (flags & IORESOURCE_PREFETCH) {
+            type |= XEN_HOST_PCI_REGION_TYPE_PREFETCH;
+        }
+        if (flags & IORESOURCE_MEM_64) {
+            type |= XEN_HOST_PCI_REGION_TYPE_MEM_64;
+        }
+
+        if (i < PCI_ROM_SLOT) {
+            d->io_regions[i].base_addr = start;
+            d->io_regions[i].size = size;
+            d->io_regions[i].type = type;
+            d->io_regions[i].bus_flags = flags & IORESOURCE_BITS;
+        } else {
+            d->rom.base_addr = start;
+            d->rom.size = size;
+            d->rom.type = type;
+            d->rom.bus_flags = flags & IORESOURCE_BITS;
+        }
+    }
+    if (i != PCI_NUM_REGIONS) {
+        /* Invalid format or input to short */
+        rc = -ENODEV;
+    }
+
+out:
+    close(fd);
+    return rc;
+}
+
+/* This size should be enough to read a long from a file */
+#define XEN_HOST_PCI_GET_VALUE_BUFFER_SIZE 22
+static int xen_host_pci_get_value(XenHostPCIDevice *d, const char *name,
+                                  unsigned int *pvalue, int base)
+{
+    char path[PATH_MAX];
+    char buf[XEN_HOST_PCI_GET_VALUE_BUFFER_SIZE];
+    int fd, rc;
+    unsigned long value;
+    char *endptr;
+
+    rc = xen_host_pci_sysfs_path(d, name, path, sizeof (path));
+    if (rc) {
+        return rc;
+    }
+    fd = open(path, O_RDONLY);
+    if (fd == -1) {
+        XEN_HOST_PCI_LOG("Error: Can't open %s: %s\n", path, strerror(errno));
+        return -errno;
+    }
+    do {
+        rc = read(fd, &buf, sizeof (buf) - 1);
+        if (rc < 0 && errno != EINTR) {
+            rc = -errno;
+            goto out;
+        }
+    } while (rc < 0);
+    buf[rc] = 0;
+    value = strtol(buf, &endptr, base);
+    if (endptr == buf || *endptr != '\n') {
+        rc = -1;
+    } else if ((value == LONG_MIN || value == LONG_MAX) && errno == ERANGE) {
+        rc = -errno;
+    } else {
+        rc = 0;
+        *pvalue = value;
+    }
+out:
+    close(fd);
+    return rc;
+}
+
+static inline int xen_host_pci_get_hex_value(XenHostPCIDevice *d,
+                                             const char *name,
+                                             unsigned int *pvalue)
+{
+    return xen_host_pci_get_value(d, name, pvalue, 16);
+}
+
+static inline int xen_host_pci_get_dec_value(XenHostPCIDevice *d,
+                                             const char *name,
+                                             unsigned int *pvalue)
+{
+    return xen_host_pci_get_value(d, name, pvalue, 10);
+}
+
+static bool xen_host_pci_dev_is_virtfn(XenHostPCIDevice *d)
+{
+    char path[PATH_MAX];
+    struct stat buf;
+
+    if (xen_host_pci_sysfs_path(d, "physfn", path, sizeof (path))) {
+        return false;
+    }
+    return !stat(path, &buf);
+}
+
+static int xen_host_pci_config_open(XenHostPCIDevice *d)
+{
+    char path[PATH_MAX];
+    int rc;
+
+    rc = xen_host_pci_sysfs_path(d, "config", path, sizeof (path));
+    if (rc) {
+        return rc;
+    }
+    d->config_fd = open(path, O_RDWR);
+    if (d->config_fd < 0) {
+        return -errno;
+    }
+    return 0;
+}
+
+static int xen_host_pci_config_read(XenHostPCIDevice *d,
+                                    int pos, void *buf, int len)
+{
+    int rc;
+
+    do {
+        rc = pread(d->config_fd, buf, len, pos);
+    } while (rc < 0 && (errno == EINTR || errno == EAGAIN));
+    if (rc != len) {
+        return -errno;
+    }
+    return 0;
+}
+
+static int xen_host_pci_config_write(XenHostPCIDevice *d,
+                                     int pos, const void *buf, int len)
+{
+    int rc;
+
+    do {
+        rc = pwrite(d->config_fd, buf, len, pos);
+    } while (rc < 0 && (errno == EINTR || errno == EAGAIN));
+    if (rc != len) {
+        return -errno;
+    }
+    return 0;
+}
+
+
+int xen_host_pci_get_byte(XenHostPCIDevice *d, int pos, uint8_t *p)
+{
+    uint8_t buf;
+    int rc = xen_host_pci_config_read(d, pos, &buf, 1);
+    if (!rc) {
+        *p = buf;
+    }
+    return rc;
+}
+
+int xen_host_pci_get_word(XenHostPCIDevice *d, int pos, uint16_t *p)
+{
+    uint16_t buf;
+    int rc = xen_host_pci_config_read(d, pos, &buf, 2);
+    if (!rc) {
+        *p = le16_to_cpu(buf);
+    }
+    return rc;
+}
+
+int xen_host_pci_get_long(XenHostPCIDevice *d, int pos, uint32_t *p)
+{
+    uint32_t buf;
+    int rc = xen_host_pci_config_read(d, pos, &buf, 4);
+    if (!rc) {
+        *p = le32_to_cpu(buf);
+    }
+    return rc;
+}
+
+int xen_host_pci_get_block(XenHostPCIDevice *d, int pos, uint8_t *buf, int len)
+{
+    return xen_host_pci_config_read(d, pos, buf, len);
+}
+
+int xen_host_pci_set_byte(XenHostPCIDevice *d, int pos, uint8_t data)
+{
+    return xen_host_pci_config_write(d, pos, &data, 1);
+}
+
+int xen_host_pci_set_word(XenHostPCIDevice *d, int pos, uint16_t data)
+{
+    data = cpu_to_le16(data);
+    return xen_host_pci_config_write(d, pos, &data, 2);
+}
+
+int xen_host_pci_set_long(XenHostPCIDevice *d, int pos, uint32_t data)
+{
+    data = cpu_to_le32(data);
+    return xen_host_pci_config_write(d, pos, &data, 4);
+}
+
+int xen_host_pci_set_block(XenHostPCIDevice *d, int pos, uint8_t *buf, int len)
+{
+    return xen_host_pci_config_write(d, pos, buf, len);
+}
+
+int xen_host_pci_find_ext_cap_offset(XenHostPCIDevice *d, uint32_t cap)
+{
+    uint32_t header = 0;
+    int max_cap = XEN_HOST_PCI_MAX_EXT_CAP;
+    int pos = PCI_CONFIG_SPACE_SIZE;
+
+    do {
+        if (xen_host_pci_get_long(d, pos, &header)) {
+            break;
+        }
+        /*
+         * If we have no capabilities, this is indicated by cap ID,
+         * cap version and next pointer all being 0.
+         */
+        if (header == 0) {
+            break;
+        }
+
+        if (PCI_EXT_CAP_ID(header) == cap) {
+            return pos;
+        }
+
+        pos = PCI_EXT_CAP_NEXT(header);
+        if (pos < PCI_CONFIG_SPACE_SIZE) {
+            break;
+        }
+
+        max_cap--;
+    } while (max_cap > 0);
+
+    return -1;
+}
+
+int xen_host_pci_device_get(XenHostPCIDevice *d, uint16_t domain,
+                            uint8_t bus, uint8_t dev, uint8_t func)
+{
+    unsigned int v;
+    int rc = 0;
+
+    d->config_fd = -1;
+    d->domain = domain;
+    d->bus = bus;
+    d->dev = dev;
+    d->func = func;
+
+    rc = xen_host_pci_config_open(d);
+    if (rc) {
+        goto error;
+    }
+    rc = xen_host_pci_get_resource(d);
+    if (rc) {
+        goto error;
+    }
+    rc = xen_host_pci_get_hex_value(d, "vendor", &v);
+    if (rc) {
+        goto error;
+    }
+    d->vendor_id = v;
+    rc = xen_host_pci_get_hex_value(d, "device", &v);
+    if (rc) {
+        goto error;
+    }
+    d->device_id = v;
+    rc = xen_host_pci_get_dec_value(d, "irq", &v);
+    if (rc) {
+        goto error;
+    }
+    d->irq = v;
+    d->is_virtfn = xen_host_pci_dev_is_virtfn(d);
+
+    return 0;
+error:
+    if (d->config_fd >= 0) {
+        close(d->config_fd);
+        d->config_fd = -1;
+    }
+    return rc;
+}
+
+void xen_host_pci_device_put(XenHostPCIDevice *d)
+{
+    if (d->config_fd >= 0) {
+        close(d->config_fd);
+        d->config_fd = -1;
+    }
+}
diff --git a/hw/xen-host-pci-device.h b/hw/xen-host-pci-device.h
new file mode 100644
index 0000000..0079dac
--- /dev/null
+++ b/hw/xen-host-pci-device.h
@@ -0,0 +1,55 @@
+#ifndef XEN_HOST_PCI_DEVICE_H
+#define XEN_HOST_PCI_DEVICE_H
+
+#include "pci.h"
+
+enum {
+    XEN_HOST_PCI_REGION_TYPE_IO = 1 << 1,
+    XEN_HOST_PCI_REGION_TYPE_MEM = 1 << 2,
+    XEN_HOST_PCI_REGION_TYPE_PREFETCH = 1 << 3,
+    XEN_HOST_PCI_REGION_TYPE_MEM_64 = 1 << 4,
+};
+
+typedef struct XenHostPCIIORegion {
+    pcibus_t base_addr;
+    pcibus_t size;
+    uint8_t type;
+    uint8_t bus_flags; /* Bus-specific bits */
+} XenHostPCIIORegion;
+
+typedef struct XenHostPCIDevice {
+    uint16_t domain;
+    uint8_t bus;
+    uint8_t dev;
+    uint8_t func;
+
+    uint16_t vendor_id;
+    uint16_t device_id;
+    int irq;
+
+    XenHostPCIIORegion io_regions[PCI_NUM_REGIONS - 1];
+    XenHostPCIIORegion rom;
+
+    bool is_virtfn;
+
+    int config_fd;
+} XenHostPCIDevice;
+
+int xen_host_pci_device_get(XenHostPCIDevice *d, uint16_t domain,
+                            uint8_t bus, uint8_t dev, uint8_t func);
+void xen_host_pci_device_put(XenHostPCIDevice *pci_dev);
+
+int xen_host_pci_get_byte(XenHostPCIDevice *d, int pos, uint8_t *p);
+int xen_host_pci_get_word(XenHostPCIDevice *d, int pos, uint16_t *p);
+int xen_host_pci_get_long(XenHostPCIDevice *d, int pos, uint32_t *p);
+int xen_host_pci_get_block(XenHostPCIDevice *d, int pos, uint8_t *buf,
+                           int len);
+int xen_host_pci_set_byte(XenHostPCIDevice *d, int pos, uint8_t data);
+int xen_host_pci_set_word(XenHostPCIDevice *d, int pos, uint16_t data);
+int xen_host_pci_set_long(XenHostPCIDevice *d, int pos, uint32_t data);
+int xen_host_pci_set_block(XenHostPCIDevice *d, int pos, uint8_t *buf,
+                           int len);
+
+int xen_host_pci_find_ext_cap_offset(XenHostPCIDevice *s, uint32_t cap);
+
+#endif /* !XEN_HOST_PCI_DEVICE_H_ */
commit eb6fda0f515ac8b35bd0d36b2962085051c898b0
Author: Anthony PERARD <anthony.perard at citrix.com>
Date:   Thu Jun 21 15:32:59 2012 +0000

    configure: Introduce --enable-xen-pci-passthrough.
    
    Signed-off-by: Anthony PERARD <anthony.perard at citrix.com>
    Acked-by: Stefano Stabellini <stefano.stabellini at eu.citrix.com>
    Reviewed-by: Konrad Rzeszutek Wilk <konrad.wilk at oracle.com>

diff --git a/configure b/configure
index b68c0ca..de3fae8 100755
--- a/configure
+++ b/configure
@@ -137,6 +137,7 @@ vnc_png=""
 vnc_thread="no"
 xen=""
 xen_ctrl_version=""
+xen_pci_passthrough=""
 linux_aio=""
 cap_ng=""
 attr=""
@@ -684,6 +685,10 @@ for opt do
   ;;
   --enable-xen) xen="yes"
   ;;
+  --disable-xen-pci-passthrough) xen_pci_passthrough="no"
+  ;;
+  --enable-xen-pci-passthrough) xen_pci_passthrough="yes"
+  ;;
   --disable-brlapi) brlapi="no"
   ;;
   --enable-brlapi) brlapi="yes"
@@ -1031,6 +1036,8 @@ echo "                           (affects only QEMU, not qemu-img)"
 echo "  --enable-mixemu          enable mixer emulation"
 echo "  --disable-xen            disable xen backend driver support"
 echo "  --enable-xen             enable xen backend driver support"
+echo "  --disable-xen-pci-passthrough"
+echo "  --enable-xen-pci-passthrough"
 echo "  --disable-brlapi         disable BrlAPI"
 echo "  --enable-brlapi          enable BrlAPI"
 echo "  --disable-vnc-tls        disable TLS encryption for VNC server"
@@ -1507,6 +1514,25 @@ EOF
   fi
 fi
 
+if test "$xen_pci_passthrough" != "no"; then
+  if test "$xen" = "yes" && test "$linux" = "yes" &&
+    test "$xen_ctrl_version" -ge 340; then
+    xen_pci_passthrough=yes
+  else
+    if test "$xen_pci_passthrough" = "yes"; then
+      echo "ERROR"
+      echo "ERROR: User requested feature Xen PCI Passthrough"
+      echo "ERROR: but this feature require /sys from Linux"
+      if test "$xen_ctrl_version" -lt 340; then
+        echo "ERROR: This feature does not work with Xen 3.3"
+      fi
+      echo "ERROR"
+      exit 1;
+    fi
+    xen_pci_passthrough=no
+  fi
+fi
+
 ##########################################
 # pkg-config probe
 
@@ -3702,6 +3728,9 @@ case "$target_arch2" in
     if test "$xen" = "yes" -a "$target_softmmu" = "yes" ; then
       target_phys_bits=64
       echo "CONFIG_XEN=y" >> $config_target_mak
+      if test "$xen_pci_passthrough" = yes; then
+        echo "CONFIG_XEN_PCI_PASSTHROUGH=y" >> "$config_target_mak"
+      fi
     else
       echo "CONFIG_NO_XEN=y" >> $config_target_mak
     fi
commit 9ff706c8158892c00eb01d6b721b17d5a87f7f0a
Author: Anthony PERARD <anthony.perard at citrix.com>
Date:   Thu Jun 21 15:31:47 2012 +0000

    pci_ids: Add INTEL_82599_SFP_VF id.
    
    We are using this in our quirk lookup provided by patch
    titled: Introduce Xen PCI Passthrough, PCI config space helpers.
    
    Signed-off-by: Anthony PERARD <anthony.perard at citrix.com>
    Acked-by: Stefano Stabellini <stefano.stabellini at eu.citrix.com>
    Acked-by: Michael S. Tsirkin <mst at redhat.com>
    Reviewed-by: Konrad Rzeszutek Wilk <konrad.wilk at oracle.com>

diff --git a/hw/pci_ids.h b/hw/pci_ids.h
index e8235a7..649e6b3 100644
--- a/hw/pci_ids.h
+++ b/hw/pci_ids.h
@@ -118,6 +118,7 @@
 #define PCI_DEVICE_ID_INTEL_82801I_UHCI6 0x2939
 #define PCI_DEVICE_ID_INTEL_82801I_EHCI1 0x293a
 #define PCI_DEVICE_ID_INTEL_82801I_EHCI2 0x293c
+#define PCI_DEVICE_ID_INTEL_82599_SFP_VF 0x10ed
 
 #define PCI_VENDOR_ID_XEN               0x5853
 #define PCI_DEVICE_ID_XEN_PLATFORM      0x0001
commit e108a3c110506faf3ef43448be3e0d39ef0ead8f
Author: Anthony PERARD <anthony.perard at citrix.com>
Date:   Thu Jun 21 11:44:35 2012 +0000

    xenstore: Use <xenstore.h>
    
    In the next release of Xen (4.2), xs.h became deprecated.
    
    Signed-off-by: Anthony PERARD <anthony.perard at citrix.com>
    Signed-off-by: Stefano Stabellini <stefano.stabellini at eu.citrix.com>

diff --git a/configure b/configure
index b68c0ca..c4e4960 100755
--- a/configure
+++ b/configure
@@ -1381,7 +1381,7 @@ EOF
   elif (
       cat > $TMPC <<EOF
 #include <xenctrl.h>
-#include <xs.h>
+#include <xenstore.h>
 #include <stdint.h>
 #include <xen/hvm/hvm_info_table.h>
 #if !defined(HVM_MAX_VCPUS)
diff --git a/hw/xen_common.h b/hw/xen_common.h
index fe7f227..cc99204 100644
--- a/hw/xen_common.h
+++ b/hw/xen_common.h
@@ -7,7 +7,11 @@
 #include <inttypes.h>
 
 #include <xenctrl.h>
-#include <xs.h>
+#if CONFIG_XEN_CTRL_INTERFACE_VERSION < 420
+#  include <xs.h>
+#else
+#  include <xenstore.h>
+#endif
 #include <xen/io/xenbus.h>
 
 #include "hw.h"
commit b41f67197208e7b72ba2207473a74b89a821190a
Author: Anthony PERARD <anthony.perard at citrix.com>
Date:   Thu Jun 21 11:43:59 2012 +0000

    xen: Reorganize includes of Xen headers.
    
    Because xs.h will be remove in future release of Xen, this patch removes the
    extra includes of this headers.
    
    Also, it removes the extra includes of xenctrl.h and xen/io/xenbus.h as there
    already are in xen_common.h.
    
    Signed-off-by: Anthony PERARD <anthony.perard at citrix.com>
    Signed-off-by: Stefano Stabellini <stefano.stabellini at eu.citrix.com>

diff --git a/hw/xen_backend.c b/hw/xen_backend.c
index 66cb144..f83a1e1 100644
--- a/hw/xen_backend.c
+++ b/hw/xen_backend.c
@@ -34,15 +34,13 @@
 #include <sys/mman.h>
 #include <sys/signal.h>
 
-#include <xs.h>
-#include <xenctrl.h>
-#include <xen/grant_table.h>
-
 #include "hw.h"
 #include "qemu-char.h"
 #include "qemu-log.h"
 #include "xen_backend.h"
 
+#include <xen/grant_table.h>
+
 /* ------------------------------------------------------------- */
 
 /* public */
diff --git a/hw/xen_console.c b/hw/xen_console.c
index 3794b19..9426d73 100644
--- a/hw/xen_console.c
+++ b/hw/xen_console.c
@@ -28,14 +28,13 @@
 #include <termios.h>
 #include <stdarg.h>
 #include <sys/mman.h>
-#include <xs.h>
-#include <xen/io/console.h>
-#include <xenctrl.h>
 
 #include "hw.h"
 #include "qemu-char.h"
 #include "xen_backend.h"
 
+#include <xen/io/console.h>
+
 struct buffer {
     uint8_t *data;
     size_t consumed;
diff --git a/hw/xen_disk.c b/hw/xen_disk.c
index fb68ed9..e6bb2f2 100644
--- a/hw/xen_disk.c
+++ b/hw/xen_disk.c
@@ -35,14 +35,10 @@
 #include <sys/mman.h>
 #include <sys/uio.h>
 
-#include <xs.h>
-#include <xenctrl.h>
-#include <xen/io/xenbus.h>
-
 #include "hw.h"
 #include "qemu-char.h"
-#include "xen_blkif.h"
 #include "xen_backend.h"
+#include "xen_blkif.h"
 #include "blockdev.h"
 
 /* ------------------------------------------------------------- */
diff --git a/hw/xen_nic.c b/hw/xen_nic.c
index 9a59bda..98db9bb 100644
--- a/hw/xen_nic.c
+++ b/hw/xen_nic.c
@@ -35,11 +35,6 @@
 #include <sys/mman.h>
 #include <sys/wait.h>
 
-#include <xs.h>
-#include <xenctrl.h>
-#include <xen/io/xenbus.h>
-#include <xen/io/netif.h>
-
 #include "hw.h"
 #include "net.h"
 #include "net/checksum.h"
@@ -47,6 +42,8 @@
 #include "qemu-char.h"
 #include "xen_backend.h"
 
+#include <xen/io/netif.h>
+
 /* ------------------------------------------------------------- */
 
 struct XenNetDev {
diff --git a/hw/xenfb.c b/hw/xenfb.c
index 1bcf171..338800a 100644
--- a/hw/xenfb.c
+++ b/hw/xenfb.c
@@ -35,19 +35,16 @@
 #include <string.h>
 #include <time.h>
 
-#include <xs.h>
-#include <xenctrl.h>
-#include <xen/event_channel.h>
-#include <xen/io/xenbus.h>
-#include <xen/io/fbif.h>
-#include <xen/io/kbdif.h>
-#include <xen/io/protocols.h>
-
 #include "hw.h"
 #include "console.h"
 #include "qemu-char.h"
 #include "xen_backend.h"
 
+#include <xen/event_channel.h>
+#include <xen/io/fbif.h>
+#include <xen/io/kbdif.h>
+#include <xen/io/protocols.h>
+
 #ifndef BTN_LEFT
 #define BTN_LEFT 0x110 /* from <linux/input.h> */
 #endif
commit 77fa9aee38758a078870e25f0dcf642066b4d5cc
Author: Gerd Hoffmann <kraxel at redhat.com>
Date:   Fri Jun 15 09:39:50 2012 +0200

    uhci: fix uhci_async_cancel_all
    
    We update the QTAILQ in the loop, thus we must use the SAFE version
    to make sure we don't touch the queue struct after freeing it.
    
    https://bugzilla.novell.com/show_bug.cgi?id=766310
    
    Signed-off-by: Gerd Hoffmann <kraxel at redhat.com>

diff --git a/hw/usb/hcd-uhci.c b/hw/usb/hcd-uhci.c
index 9871e24..2ebce04 100644
--- a/hw/usb/hcd-uhci.c
+++ b/hw/usb/hcd-uhci.c
@@ -292,10 +292,10 @@ static void uhci_async_cancel_device(UHCIState *s, USBDevice *dev)
 
 static void uhci_async_cancel_all(UHCIState *s)
 {
-    UHCIQueue *queue;
+    UHCIQueue *queue, *nq;
     UHCIAsync *curr, *n;
 
-    QTAILQ_FOREACH(queue, &s->queues, next) {
+    QTAILQ_FOREACH_SAFE(queue, &s->queues, next, nq) {
         QTAILQ_FOREACH_SAFE(curr, &queue->asyncs, next, n) {
             uhci_async_unlink(curr);
             uhci_async_cancel(curr);
commit a229c0535bd336efaec786dd6e352a54e0a8187d
Author: Gerd Hoffmann <kraxel at redhat.com>
Date:   Fri Jun 8 13:02:16 2012 +0200

    usb-host: live migration support
    
    Signed-off-by: Gerd Hoffmann <kraxel at redhat.com>

diff --git a/hw/usb/host-linux.c b/hw/usb/host-linux.c
index 06b6ed3..5479fb5 100644
--- a/hw/usb/host-linux.c
+++ b/hw/usb/host-linux.c
@@ -111,6 +111,7 @@ typedef struct USBHostDevice {
     uint32_t  iso_urb_count;
     uint32_t  options;
     Notifier  exit;
+    QEMUBH    *bh;
 
     struct endp_data ep_in[USB_MAX_ENDPOINTS];
     struct endp_data ep_out[USB_MAX_ENDPOINTS];
@@ -1421,6 +1422,43 @@ static void usb_host_exit_notifier(struct Notifier *n, void *data)
     }
 }
 
+/*
+ * This is *NOT* about restoring state.  We have absolutely no idea
+ * what state the host device is in at the moment and whenever it is
+ * still present in the first place.  Attemping to contine where we
+ * left off is impossible.
+ *
+ * What we are going to to to here is emulate a surprise removal of
+ * the usb device passed through, then kick host scan so the device
+ * will get re-attached (and re-initialized by the guest) in case it
+ * is still present.
+ *
+ * As the device removal will change the state of other devices (usb
+ * host controller, most likely interrupt controller too) we have to
+ * wait with it until *all* vmstate is loaded.  Thus post_load just
+ * kicks a bottom half which then does the actual work.
+ */
+static void usb_host_post_load_bh(void *opaque)
+{
+    USBHostDevice *dev = opaque;
+
+    if (dev->fd != -1) {
+        usb_host_close(dev);
+    }
+    if (dev->dev.attached) {
+        usb_device_detach(&dev->dev);
+    }
+    usb_host_auto_check(NULL);
+}
+
+static int usb_host_post_load(void *opaque, int version_id)
+{
+    USBHostDevice *dev = opaque;
+
+    qemu_bh_schedule(dev->bh);
+    return 0;
+}
+
 static int usb_host_initfn(USBDevice *dev)
 {
     USBHostDevice *s = DO_UPCAST(USBHostDevice, dev, dev);
@@ -1432,6 +1470,7 @@ static int usb_host_initfn(USBDevice *dev)
     QTAILQ_INSERT_TAIL(&hostdevs, s, next);
     s->exit.notify = usb_host_exit_notifier;
     qemu_add_exit_notifier(&s->exit);
+    s->bh = qemu_bh_new(usb_host_post_load_bh, s);
     usb_host_auto_check(NULL);
 
     if (s->match.bus_num != 0 && s->match.port != NULL) {
@@ -1443,7 +1482,13 @@ static int usb_host_initfn(USBDevice *dev)
 
 static const VMStateDescription vmstate_usb_host = {
     .name = "usb-host",
-    .unmigratable = 1,
+    .version_id = 1,
+    .minimum_version_id = 1,
+    .post_load = usb_host_post_load,
+    .fields = (VMStateField[]) {
+        VMSTATE_USB_DEVICE(dev, USBHostDevice),
+        VMSTATE_END_OF_LIST()
+    }
 };
 
 static Property usb_host_dev_properties[] = {
commit a844ed842d9a9d929645c09ae0f52f753d7a02e0
Author: Gerd Hoffmann <kraxel at redhat.com>
Date:   Fri Jun 8 13:02:52 2012 +0200

    usb-host: attach only to running guest
    
    Signed-off-by: Gerd Hoffmann <kraxel at redhat.com>

diff --git a/hw/usb/host-linux.c b/hw/usb/host-linux.c
index a95b0ed..06b6ed3 100644
--- a/hw/usb/host-linux.c
+++ b/hw/usb/host-linux.c
@@ -1737,25 +1737,27 @@ static void usb_host_auto_check(void *unused)
     struct USBHostDevice *s;
     int unconnected = 0;
 
-    usb_host_scan(NULL, usb_host_auto_scan);
+    if (runstate_is_running()) {
+        usb_host_scan(NULL, usb_host_auto_scan);
 
-    QTAILQ_FOREACH(s, &hostdevs, next) {
-        if (s->fd == -1) {
-            unconnected++;
-        }
-        if (s->seen == 0) {
-            s->errcount = 0;
+        QTAILQ_FOREACH(s, &hostdevs, next) {
+            if (s->fd == -1) {
+                unconnected++;
+            }
+            if (s->seen == 0) {
+                s->errcount = 0;
+            }
+            s->seen = 0;
         }
-        s->seen = 0;
-    }
 
-    if (unconnected == 0) {
-        /* nothing to watch */
-        if (usb_auto_timer) {
-            qemu_del_timer(usb_auto_timer);
-            trace_usb_host_auto_scan_disabled();
+        if (unconnected == 0) {
+            /* nothing to watch */
+            if (usb_auto_timer) {
+                qemu_del_timer(usb_auto_timer);
+                trace_usb_host_auto_scan_disabled();
+            }
+            return;
         }
-        return;
     }
 
     if (!usb_auto_timer) {
commit 30e9d4120faa7b0e9318aa41529a936aa1cdb334
Author: Gerd Hoffmann <kraxel at redhat.com>
Date:   Fri Jun 8 13:00:44 2012 +0200

    ehci: tracing improvements
    
    Signed-off-by: Gerd Hoffmann <kraxel at redhat.com>

diff --git a/hw/usb/hcd-ehci.c b/hw/usb/hcd-ehci.c
index 45b774d..6d2d549 100644
--- a/hw/usb/hcd-ehci.c
+++ b/hw/usb/hcd-ehci.c
@@ -569,6 +569,7 @@ static inline void ehci_set_interrupt(EHCIState *s, int intr)
         level = 1;
     }
 
+    trace_usb_ehci_interrupt(level, s->usbsts, s->usbintr);
     qemu_set_irq(s->irq, level);
 }
 
@@ -822,8 +823,9 @@ static void ehci_attach(USBPort *port)
 {
     EHCIState *s = port->opaque;
     uint32_t *portsc = &s->portsc[port->index];
+    const char *owner = (*portsc & PORTSC_POWNER) ? "comp" : "ehci";
 
-    trace_usb_ehci_port_attach(port->index, port->dev->product_desc);
+    trace_usb_ehci_port_attach(port->index, owner, port->dev->product_desc);
 
     if (*portsc & PORTSC_POWNER) {
         USBPort *companion = s->companion_ports[port->index];
@@ -842,8 +844,9 @@ static void ehci_detach(USBPort *port)
 {
     EHCIState *s = port->opaque;
     uint32_t *portsc = &s->portsc[port->index];
+    const char *owner = (*portsc & PORTSC_POWNER) ? "comp" : "ehci";
 
-    trace_usb_ehci_port_detach(port->index);
+    trace_usb_ehci_port_detach(port->index, owner);
 
     if (*portsc & PORTSC_POWNER) {
         USBPort *companion = s->companion_ports[port->index];
diff --git a/trace-events b/trace-events
index 5c82b3a..c935ba2 100644
--- a/trace-events
+++ b/trace-events
@@ -252,12 +252,13 @@ usb_ehci_qtd_fields(uint32_t addr, int tbytes, int cpage, int cerr, int pid) "QT
 usb_ehci_qtd_bits(uint32_t addr, int ioc, int active, int halt, int babble, int xacterr) "QTD @ %08x - ioc %d, active %d, halt %d, babble %d, xacterr %d"
 usb_ehci_itd(uint32_t addr, uint32_t nxt, uint32_t mplen, uint32_t mult, uint32_t ep, uint32_t devaddr) "ITD @ %08x: next %08x - mplen %d, mult %d, ep %d, dev %d"
 usb_ehci_sitd(uint32_t addr, uint32_t nxt, uint32_t active) "ITD @ %08x: next %08x - active %d"
-usb_ehci_port_attach(uint32_t port, const char *device) "attach port #%d - %s"
-usb_ehci_port_detach(uint32_t port) "detach port #%d"
+usb_ehci_port_attach(uint32_t port, const char *owner, const char *device) "attach port #%d, owner %s, device %s"
+usb_ehci_port_detach(uint32_t port, const char *owner) "detach port #%d, owner %s"
 usb_ehci_port_reset(uint32_t port, int enable) "reset port #%d - %d"
 usb_ehci_data(int rw, uint32_t cpage, uint32_t offset, uint32_t addr, uint32_t len, uint32_t bufpos) "write %d, cpage %d, offset 0x%03x, addr 0x%08x, len %d, bufpos %d"
 usb_ehci_queue_action(void *q, const char *action) "q %p: %s"
 usb_ehci_packet_action(void *q, void *p, const char *action) "q %p p %p: %s"
+usb_ehci_interrupt(uint32_t level, uint32_t sts, uint32_t mask) "level %d, sts 0x%x, mask 0x%x"
 
 # hw/usb/hcd-uhci.c
 usb_uhci_reset(void) "=== RESET ==="
commit 495d544798151206bafca65ec588c0388637eb40
Author: Gerd Hoffmann <kraxel at redhat.com>
Date:   Fri Jun 8 12:58:46 2012 +0200

    usb: restore USBDevice->attached on vmload
    
    Signed-off-by: Gerd Hoffmann <kraxel at redhat.com>

diff --git a/hw/usb/bus.c b/hw/usb/bus.c
index f87cc5f..b649360 100644
--- a/hw/usb/bus.c
+++ b/hw/usb/bus.c
@@ -37,10 +37,23 @@ static const TypeInfo usb_bus_info = {
 static int next_usb_bus = 0;
 static QTAILQ_HEAD(, USBBus) busses = QTAILQ_HEAD_INITIALIZER(busses);
 
+static int usb_device_post_load(void *opaque, int version_id)
+{
+    USBDevice *dev = opaque;
+
+    if (dev->state == USB_STATE_NOTATTACHED) {
+        dev->attached = 0;
+    } else {
+        dev->attached = 1;
+    }
+    return 0;
+}
+
 const VMStateDescription vmstate_usb_device = {
     .name = "USBDevice",
     .version_id = 1,
     .minimum_version_id = 1,
+    .post_load = usb_device_post_load,
     .fields = (VMStateField []) {
         VMSTATE_UINT8(addr, USBDevice),
         VMSTATE_INT32(state, USBDevice),
commit 9a77340827cd48c5c9b6daab614009a0594abf38
Author: Gerd Hoffmann <kraxel at redhat.com>
Date:   Mon May 14 13:55:44 2012 +0200

    ehci: add live migration support
    
    Signed-off-by: Gerd Hoffmann <kraxel at redhat.com>

diff --git a/hw/usb/hcd-ehci.c b/hw/usb/hcd-ehci.c
index 5298204..45b774d 100644
--- a/hw/usb/hcd-ehci.c
+++ b/hw/usb/hcd-ehci.c
@@ -414,16 +414,17 @@ struct EHCIState {
      */
     QEMUTimer *frame_timer;
     QEMUBH *async_bh;
-    int astate;                        // Current state in asynchronous schedule
-    int pstate;                        // Current state in periodic schedule
+    uint32_t astate;         /* Current state in asynchronous schedule */
+    uint32_t pstate;         /* Current state in periodic schedule     */
     USBPort ports[NB_PORTS];
     USBPort *companion_ports[NB_PORTS];
     uint32_t usbsts_pending;
     EHCIQueueHead aqueues;
     EHCIQueueHead pqueues;
 
-    uint32_t a_fetch_addr;   // which address to look at next
-    uint32_t p_fetch_addr;   // which address to look at next
+    /* which address to look at next */
+    uint32_t a_fetch_addr;
+    uint32_t p_fetch_addr;
 
     USBPacket ipacket;
     QEMUSGList isgl;
@@ -2390,9 +2391,58 @@ static USBBusOps ehci_bus_ops = {
     .register_companion = ehci_register_companion,
 };
 
+static int usb_ehci_post_load(void *opaque, int version_id)
+{
+    EHCIState *s = opaque;
+    int i;
+
+    for (i = 0; i < NB_PORTS; i++) {
+        USBPort *companion = s->companion_ports[i];
+        if (companion == NULL) {
+            continue;
+        }
+        if (s->portsc[i] & PORTSC_POWNER) {
+            companion->dev = s->ports[i].dev;
+        } else {
+            companion->dev = NULL;
+        }
+    }
+
+    return 0;
+}
+
 static const VMStateDescription vmstate_ehci = {
-    .name = "ehci",
-    .unmigratable = 1,
+    .name        = "ehci",
+    .version_id  = 1,
+    .post_load   = usb_ehci_post_load,
+    .fields      = (VMStateField[]) {
+        VMSTATE_PCI_DEVICE(dev, EHCIState),
+        /* mmio registers */
+        VMSTATE_UINT32(usbcmd, EHCIState),
+        VMSTATE_UINT32(usbsts, EHCIState),
+        VMSTATE_UINT32(usbintr, EHCIState),
+        VMSTATE_UINT32(frindex, EHCIState),
+        VMSTATE_UINT32(ctrldssegment, EHCIState),
+        VMSTATE_UINT32(periodiclistbase, EHCIState),
+        VMSTATE_UINT32(asynclistaddr, EHCIState),
+        VMSTATE_UINT32(configflag, EHCIState),
+        VMSTATE_UINT32(portsc[0], EHCIState),
+        VMSTATE_UINT32(portsc[1], EHCIState),
+        VMSTATE_UINT32(portsc[2], EHCIState),
+        VMSTATE_UINT32(portsc[3], EHCIState),
+        VMSTATE_UINT32(portsc[4], EHCIState),
+        VMSTATE_UINT32(portsc[5], EHCIState),
+        /* frame timer */
+        VMSTATE_TIMER(frame_timer, EHCIState),
+        VMSTATE_UINT64(last_run_ns, EHCIState),
+        VMSTATE_UINT32(async_stepdown, EHCIState),
+        /* schedule state */
+        VMSTATE_UINT32(astate, EHCIState),
+        VMSTATE_UINT32(pstate, EHCIState),
+        VMSTATE_UINT32(a_fetch_addr, EHCIState),
+        VMSTATE_UINT32(p_fetch_addr, EHCIState),
+        VMSTATE_END_OF_LIST()
+    }
 };
 
 static Property ehci_properties[] = {
commit b2d06f9607e36333686b0e52a188881ce38495c7
Author: Peter Maydell <peter.maydell at linaro.org>
Date:   Wed Jun 20 11:57:23 2012 +0000

    target-arm: Remove ARM_CPUID_* macros
    
    All the uses of ARM_CPUID() to vary behaviour have now been
    removed, so we can delete the ARM_CPUID_* macros now.
    The one exception is the TI915T/925T, because of its odd behaviour
    where the MIDR value can be changed at runtime.
    
    Signed-off-by: Peter Maydell <peter.maydell at linaro.org>
    Reviewed-by: Andreas Färber <afaerber at suse.de>

diff --git a/linux-user/cpu-uname.c b/linux-user/cpu-uname.c
index ddc37be..59cd647 100644
--- a/linux-user/cpu-uname.c
+++ b/linux-user/cpu-uname.c
@@ -35,10 +35,7 @@ const char *cpu_to_uname_machine(void *cpu_env)
      * armv7l; to get a list of CPU arch names from the linux source, use:
      *     grep arch_name: -A1 linux/arch/arm/mm/proc-*.S
      * see arch/arm/kernel/setup.c: setup_processor()
-     *
-     * to test by CPU id, compare cpu_env->cp15.c0_cpuid to ARM_CPUID_*
-     * defines and to test by CPU feature, use arm_feature(cpu_env,
-     * ARM_FEATURE_*) */
+     */
 
     /* in theory, endianness is configurable on some ARM CPUs, but this isn't
      * used in user mode emulation */
diff --git a/target-arm/cpu.c b/target-arm/cpu.c
index 3ea3527..ae57953 100644
--- a/target-arm/cpu.c
+++ b/target-arm/cpu.c
@@ -205,7 +205,7 @@ static void arm926_initfn(Object *obj)
     set_feature(&cpu->env, ARM_FEATURE_VFP);
     set_feature(&cpu->env, ARM_FEATURE_DUMMY_C15_REGS);
     set_feature(&cpu->env, ARM_FEATURE_CACHE_TEST_CLEAN);
-    cpu->midr = ARM_CPUID_ARM926;
+    cpu->midr = 0x41069265;
     cpu->reset_fpsid = 0x41011090;
     cpu->ctr = 0x1dd20d2;
     cpu->reset_sctlr = 0x00090078;
@@ -217,7 +217,7 @@ static void arm946_initfn(Object *obj)
     set_feature(&cpu->env, ARM_FEATURE_V5);
     set_feature(&cpu->env, ARM_FEATURE_MPU);
     set_feature(&cpu->env, ARM_FEATURE_DUMMY_C15_REGS);
-    cpu->midr = ARM_CPUID_ARM946;
+    cpu->midr = 0x41059461;
     cpu->ctr = 0x0f004006;
     cpu->reset_sctlr = 0x00000078;
 }
@@ -230,7 +230,7 @@ static void arm1026_initfn(Object *obj)
     set_feature(&cpu->env, ARM_FEATURE_AUXCR);
     set_feature(&cpu->env, ARM_FEATURE_DUMMY_C15_REGS);
     set_feature(&cpu->env, ARM_FEATURE_CACHE_TEST_CLEAN);
-    cpu->midr = ARM_CPUID_ARM1026;
+    cpu->midr = 0x4106a262;
     cpu->reset_fpsid = 0x410110a0;
     cpu->ctr = 0x1dd20d2;
     cpu->reset_sctlr = 0x00090078;
@@ -262,7 +262,7 @@ static void arm1136_r2_initfn(Object *obj)
     set_feature(&cpu->env, ARM_FEATURE_DUMMY_C15_REGS);
     set_feature(&cpu->env, ARM_FEATURE_CACHE_DIRTY_REG);
     set_feature(&cpu->env, ARM_FEATURE_CACHE_BLOCK_OPS);
-    cpu->midr = ARM_CPUID_ARM1136_R2;
+    cpu->midr = 0x4107b362;
     cpu->reset_fpsid = 0x410120b4;
     cpu->mvfr0 = 0x11111111;
     cpu->mvfr1 = 0x00000000;
@@ -292,7 +292,7 @@ static void arm1136_initfn(Object *obj)
     set_feature(&cpu->env, ARM_FEATURE_DUMMY_C15_REGS);
     set_feature(&cpu->env, ARM_FEATURE_CACHE_DIRTY_REG);
     set_feature(&cpu->env, ARM_FEATURE_CACHE_BLOCK_OPS);
-    cpu->midr = ARM_CPUID_ARM1136;
+    cpu->midr = 0x4117b363;
     cpu->reset_fpsid = 0x410120b4;
     cpu->mvfr0 = 0x11111111;
     cpu->mvfr1 = 0x00000000;
@@ -322,7 +322,7 @@ static void arm1176_initfn(Object *obj)
     set_feature(&cpu->env, ARM_FEATURE_DUMMY_C15_REGS);
     set_feature(&cpu->env, ARM_FEATURE_CACHE_DIRTY_REG);
     set_feature(&cpu->env, ARM_FEATURE_CACHE_BLOCK_OPS);
-    cpu->midr = ARM_CPUID_ARM1176;
+    cpu->midr = 0x410fb767;
     cpu->reset_fpsid = 0x410120b5;
     cpu->mvfr0 = 0x11111111;
     cpu->mvfr1 = 0x00000000;
@@ -351,7 +351,7 @@ static void arm11mpcore_initfn(Object *obj)
     set_feature(&cpu->env, ARM_FEATURE_VAPA);
     set_feature(&cpu->env, ARM_FEATURE_MPIDR);
     set_feature(&cpu->env, ARM_FEATURE_DUMMY_C15_REGS);
-    cpu->midr = ARM_CPUID_ARM11MPCORE;
+    cpu->midr = 0x410fb022;
     cpu->reset_fpsid = 0x410120b4;
     cpu->mvfr0 = 0x11111111;
     cpu->mvfr1 = 0x00000000;
@@ -376,7 +376,7 @@ static void cortex_m3_initfn(Object *obj)
     ARMCPU *cpu = ARM_CPU(obj);
     set_feature(&cpu->env, ARM_FEATURE_V7);
     set_feature(&cpu->env, ARM_FEATURE_M);
-    cpu->midr = ARM_CPUID_CORTEXM3;
+    cpu->midr = 0x410fc231;
 }
 
 static const ARMCPRegInfo cortexa8_cp_reginfo[] = {
@@ -395,7 +395,7 @@ static void cortex_a8_initfn(Object *obj)
     set_feature(&cpu->env, ARM_FEATURE_NEON);
     set_feature(&cpu->env, ARM_FEATURE_THUMB2EE);
     set_feature(&cpu->env, ARM_FEATURE_DUMMY_C15_REGS);
-    cpu->midr = ARM_CPUID_CORTEXA8;
+    cpu->midr = 0x410fc080;
     cpu->reset_fpsid = 0x410330c0;
     cpu->mvfr0 = 0x11110222;
     cpu->mvfr1 = 0x00011100;
@@ -464,7 +464,7 @@ static void cortex_a9_initfn(Object *obj)
      * and valid configurations; we don't model A9UP).
      */
     set_feature(&cpu->env, ARM_FEATURE_V7MP);
-    cpu->midr = ARM_CPUID_CORTEXA9;
+    cpu->midr = 0x410fc090;
     cpu->reset_fpsid = 0x41033090;
     cpu->mvfr0 = 0x11110222;
     cpu->mvfr1 = 0x01111111;
@@ -532,7 +532,7 @@ static void cortex_a15_initfn(Object *obj)
     set_feature(&cpu->env, ARM_FEATURE_V7MP);
     set_feature(&cpu->env, ARM_FEATURE_GENERIC_TIMER);
     set_feature(&cpu->env, ARM_FEATURE_DUMMY_C15_REGS);
-    cpu->midr = ARM_CPUID_CORTEXA15;
+    cpu->midr = 0x412fc0f1;
     cpu->reset_fpsid = 0x410430f0;
     cpu->mvfr0 = 0x10110222;
     cpu->mvfr1 = 0x11111111;
@@ -573,7 +573,7 @@ static void sa1100_initfn(Object *obj)
     ARMCPU *cpu = ARM_CPU(obj);
     set_feature(&cpu->env, ARM_FEATURE_STRONGARM);
     set_feature(&cpu->env, ARM_FEATURE_DUMMY_C15_REGS);
-    cpu->midr = ARM_CPUID_SA1100;
+    cpu->midr = 0x4401A11B;
     cpu->reset_sctlr = 0x00000070;
 }
 
@@ -582,7 +582,7 @@ static void sa1110_initfn(Object *obj)
     ARMCPU *cpu = ARM_CPU(obj);
     set_feature(&cpu->env, ARM_FEATURE_STRONGARM);
     set_feature(&cpu->env, ARM_FEATURE_DUMMY_C15_REGS);
-    cpu->midr = ARM_CPUID_SA1110;
+    cpu->midr = 0x6901B119;
     cpu->reset_sctlr = 0x00000070;
 }
 
@@ -591,7 +591,7 @@ static void pxa250_initfn(Object *obj)
     ARMCPU *cpu = ARM_CPU(obj);
     set_feature(&cpu->env, ARM_FEATURE_V5);
     set_feature(&cpu->env, ARM_FEATURE_XSCALE);
-    cpu->midr = ARM_CPUID_PXA250;
+    cpu->midr = 0x69052100;
     cpu->ctr = 0xd172172;
     cpu->reset_sctlr = 0x00000078;
 }
@@ -601,7 +601,7 @@ static void pxa255_initfn(Object *obj)
     ARMCPU *cpu = ARM_CPU(obj);
     set_feature(&cpu->env, ARM_FEATURE_V5);
     set_feature(&cpu->env, ARM_FEATURE_XSCALE);
-    cpu->midr = ARM_CPUID_PXA255;
+    cpu->midr = 0x69052d00;
     cpu->ctr = 0xd172172;
     cpu->reset_sctlr = 0x00000078;
 }
@@ -611,7 +611,7 @@ static void pxa260_initfn(Object *obj)
     ARMCPU *cpu = ARM_CPU(obj);
     set_feature(&cpu->env, ARM_FEATURE_V5);
     set_feature(&cpu->env, ARM_FEATURE_XSCALE);
-    cpu->midr = ARM_CPUID_PXA260;
+    cpu->midr = 0x69052903;
     cpu->ctr = 0xd172172;
     cpu->reset_sctlr = 0x00000078;
 }
@@ -621,7 +621,7 @@ static void pxa261_initfn(Object *obj)
     ARMCPU *cpu = ARM_CPU(obj);
     set_feature(&cpu->env, ARM_FEATURE_V5);
     set_feature(&cpu->env, ARM_FEATURE_XSCALE);
-    cpu->midr = ARM_CPUID_PXA261;
+    cpu->midr = 0x69052d05;
     cpu->ctr = 0xd172172;
     cpu->reset_sctlr = 0x00000078;
 }
@@ -631,7 +631,7 @@ static void pxa262_initfn(Object *obj)
     ARMCPU *cpu = ARM_CPU(obj);
     set_feature(&cpu->env, ARM_FEATURE_V5);
     set_feature(&cpu->env, ARM_FEATURE_XSCALE);
-    cpu->midr = ARM_CPUID_PXA262;
+    cpu->midr = 0x69052d06;
     cpu->ctr = 0xd172172;
     cpu->reset_sctlr = 0x00000078;
 }
@@ -642,7 +642,7 @@ static void pxa270a0_initfn(Object *obj)
     set_feature(&cpu->env, ARM_FEATURE_V5);
     set_feature(&cpu->env, ARM_FEATURE_XSCALE);
     set_feature(&cpu->env, ARM_FEATURE_IWMMXT);
-    cpu->midr = ARM_CPUID_PXA270_A0;
+    cpu->midr = 0x69054110;
     cpu->ctr = 0xd172172;
     cpu->reset_sctlr = 0x00000078;
 }
@@ -653,7 +653,7 @@ static void pxa270a1_initfn(Object *obj)
     set_feature(&cpu->env, ARM_FEATURE_V5);
     set_feature(&cpu->env, ARM_FEATURE_XSCALE);
     set_feature(&cpu->env, ARM_FEATURE_IWMMXT);
-    cpu->midr = ARM_CPUID_PXA270_A1;
+    cpu->midr = 0x69054111;
     cpu->ctr = 0xd172172;
     cpu->reset_sctlr = 0x00000078;
 }
@@ -664,7 +664,7 @@ static void pxa270b0_initfn(Object *obj)
     set_feature(&cpu->env, ARM_FEATURE_V5);
     set_feature(&cpu->env, ARM_FEATURE_XSCALE);
     set_feature(&cpu->env, ARM_FEATURE_IWMMXT);
-    cpu->midr = ARM_CPUID_PXA270_B0;
+    cpu->midr = 0x69054112;
     cpu->ctr = 0xd172172;
     cpu->reset_sctlr = 0x00000078;
 }
@@ -675,7 +675,7 @@ static void pxa270b1_initfn(Object *obj)
     set_feature(&cpu->env, ARM_FEATURE_V5);
     set_feature(&cpu->env, ARM_FEATURE_XSCALE);
     set_feature(&cpu->env, ARM_FEATURE_IWMMXT);
-    cpu->midr = ARM_CPUID_PXA270_B1;
+    cpu->midr = 0x69054113;
     cpu->ctr = 0xd172172;
     cpu->reset_sctlr = 0x00000078;
 }
@@ -686,7 +686,7 @@ static void pxa270c0_initfn(Object *obj)
     set_feature(&cpu->env, ARM_FEATURE_V5);
     set_feature(&cpu->env, ARM_FEATURE_XSCALE);
     set_feature(&cpu->env, ARM_FEATURE_IWMMXT);
-    cpu->midr = ARM_CPUID_PXA270_C0;
+    cpu->midr = 0x69054114;
     cpu->ctr = 0xd172172;
     cpu->reset_sctlr = 0x00000078;
 }
@@ -697,7 +697,7 @@ static void pxa270c5_initfn(Object *obj)
     set_feature(&cpu->env, ARM_FEATURE_V5);
     set_feature(&cpu->env, ARM_FEATURE_XSCALE);
     set_feature(&cpu->env, ARM_FEATURE_IWMMXT);
-    cpu->midr = ARM_CPUID_PXA270_C5;
+    cpu->midr = 0x69054117;
     cpu->ctr = 0xd172172;
     cpu->reset_sctlr = 0x00000078;
 }
@@ -712,7 +712,7 @@ static void arm_any_initfn(Object *obj)
     set_feature(&cpu->env, ARM_FEATURE_THUMB2EE);
     set_feature(&cpu->env, ARM_FEATURE_ARM_DIV);
     set_feature(&cpu->env, ARM_FEATURE_V7MP);
-    cpu->midr = ARM_CPUID_ANY;
+    cpu->midr = 0xffffffff;
 }
 
 typedef struct ARMCPUInfo {
diff --git a/target-arm/cpu.h b/target-arm/cpu.h
index 27e398b..33afa18 100644
--- a/target-arm/cpu.h
+++ b/target-arm/cpu.h
@@ -606,36 +606,9 @@ static inline bool cp_access_ok(CPUARMState *env,
    conventional cores (ie. Application or Realtime profile).  */
 
 #define IS_M(env) arm_feature(env, ARM_FEATURE_M)
-#define ARM_CPUID(env) (env->cp15.c0_cpuid)
 
-#define ARM_CPUID_ARM1026     0x4106a262
-#define ARM_CPUID_ARM926      0x41069265
-#define ARM_CPUID_ARM946      0x41059461
 #define ARM_CPUID_TI915T      0x54029152
 #define ARM_CPUID_TI925T      0x54029252
-#define ARM_CPUID_SA1100      0x4401A11B
-#define ARM_CPUID_SA1110      0x6901B119
-#define ARM_CPUID_PXA250      0x69052100
-#define ARM_CPUID_PXA255      0x69052d00
-#define ARM_CPUID_PXA260      0x69052903
-#define ARM_CPUID_PXA261      0x69052d05
-#define ARM_CPUID_PXA262      0x69052d06
-#define ARM_CPUID_PXA270      0x69054110
-#define ARM_CPUID_PXA270_A0   0x69054110
-#define ARM_CPUID_PXA270_A1   0x69054111
-#define ARM_CPUID_PXA270_B0   0x69054112
-#define ARM_CPUID_PXA270_B1   0x69054113
-#define ARM_CPUID_PXA270_C0   0x69054114
-#define ARM_CPUID_PXA270_C5   0x69054117
-#define ARM_CPUID_ARM1136     0x4117b363
-#define ARM_CPUID_ARM1136_R2  0x4107b362
-#define ARM_CPUID_ARM1176     0x410fb767
-#define ARM_CPUID_ARM11MPCORE 0x410fb022
-#define ARM_CPUID_CORTEXA8    0x410fc080
-#define ARM_CPUID_CORTEXA9    0x410fc090
-#define ARM_CPUID_CORTEXA15   0x412fc0f1
-#define ARM_CPUID_CORTEXM3    0x410fc231
-#define ARM_CPUID_ANY         0xffffffff
 
 #if defined(CONFIG_USER_ONLY)
 #define TARGET_PAGE_BITS 12
commit 4a9a539ffb5226009a1bb4aa3a569fcd80cf1436
Author: Peter Maydell <peter.maydell at linaro.org>
Date:   Wed Jun 20 11:57:22 2012 +0000

    target-arm: Remove remaining old cp15 infrastructure
    
    There are now no uses of the old cp15 infrastructure,
    so it can be deleted.
    
    Signed-off-by: Peter Maydell <peter.maydell at linaro.org>

diff --git a/target-arm/helper.c b/target-arm/helper.c
index 10d4635..2309923 100644
--- a/target-arm/helper.c
+++ b/target-arm/helper.c
@@ -1441,16 +1441,6 @@ int cpu_arm_handle_mmu_fault (CPUARMState *env, target_ulong address, int rw,
     return 1;
 }
 
-void HELPER(set_cp15)(CPUARMState *env, uint32_t insn, uint32_t val)
-{
-    cpu_abort(env, "cp15 insn %08x\n", insn);
-}
-
-uint32_t HELPER(get_cp15)(CPUARMState *env, uint32_t insn)
-{
-    cpu_abort(env, "cp15 insn %08x\n", insn);
-}
-
 /* These should probably raise undefined insn exceptions.  */
 void HELPER(v7m_msr)(CPUARMState *env, uint32_t reg, uint32_t val)
 {
@@ -2177,35 +2167,6 @@ target_phys_addr_t cpu_get_phys_page_debug(CPUARMState *env, target_ulong addr)
     return phys_addr;
 }
 
-void HELPER(set_cp15)(CPUARMState *env, uint32_t insn, uint32_t val)
-{
-    int op1;
-    int op2;
-    int crm;
-
-    op1 = (insn >> 21) & 7;
-    op2 = (insn >> 5) & 7;
-    crm = insn & 0xf;
-    /* ??? For debugging only.  Should raise illegal instruction exception.  */
-    cpu_abort(env, "Unimplemented cp15 register write (c%d, c%d, {%d, %d})\n",
-              (insn >> 16) & 0xf, crm, op1, op2);
-}
-
-uint32_t HELPER(get_cp15)(CPUARMState *env, uint32_t insn)
-{
-    int op1;
-    int op2;
-    int crm;
-
-    op1 = (insn >> 21) & 7;
-    op2 = (insn >> 5) & 7;
-    crm = insn & 0xf;
-    /* ??? For debugging only.  Should raise illegal instruction exception.  */
-    cpu_abort(env, "Unimplemented cp15 register read (c%d, c%d, {%d, %d})\n",
-              (insn >> 16) & 0xf, crm, op1, op2);
-    return 0;
-}
-
 void HELPER(set_r13_banked)(CPUARMState *env, uint32_t mode, uint32_t val)
 {
     if ((env->uncached_cpsr & CPSR_M) == mode) {
diff --git a/target-arm/helper.h b/target-arm/helper.h
index a0034ae..21e9cfe 100644
--- a/target-arm/helper.h
+++ b/target-arm/helper.h
@@ -59,9 +59,6 @@ DEF_HELPER_0(cpsr_read, i32)
 DEF_HELPER_3(v7m_msr, void, env, i32, i32)
 DEF_HELPER_2(v7m_mrs, i32, env, i32)
 
-DEF_HELPER_3(set_cp15, void, env, i32, i32)
-DEF_HELPER_2(get_cp15, i32, env, i32)
-
 DEF_HELPER_3(set_cp_reg, void, env, ptr, i32)
 DEF_HELPER_2(get_cp_reg, i32, env, ptr)
 DEF_HELPER_3(set_cp_reg64, void, env, ptr, i64)
diff --git a/target-arm/translate.c b/target-arm/translate.c
index fcdc9d3..a2a0ecd 100644
--- a/target-arm/translate.c
+++ b/target-arm/translate.c
@@ -2439,55 +2439,6 @@ static int disas_dsp_insn(CPUARMState *env, DisasContext *s, uint32_t insn)
     return 1;
 }
 
-/* Disassemble system coprocessor (cp15) instruction.  Return nonzero if
-   instruction is not defined.  */
-static int disas_cp15_insn(CPUARMState *env, DisasContext *s, uint32_t insn)
-{
-    uint32_t rd;
-    TCGv tmp, tmp2;
-
-    /* M profile cores use memory mapped registers instead of cp15.  */
-    if (arm_feature(env, ARM_FEATURE_M))
-	return 1;
-
-    if ((insn & (1 << 25)) == 0) {
-        return 1;
-    }
-    if ((insn & (1 << 4)) == 0) {
-        /* cdp */
-        return 1;
-    }
-
-    if (IS_USER(s)) {
-        return 1;
-    }
-
-    rd = (insn >> 12) & 0xf;
-
-    tmp2 = tcg_const_i32(insn);
-    if (insn & ARM_CP_RW_BIT) {
-        tmp = tcg_temp_new_i32();
-        gen_helper_get_cp15(tmp, cpu_env, tmp2);
-        /* If the destination register is r15 then sets condition codes.  */
-        if (rd != 15)
-            store_reg(s, rd, tmp);
-        else
-            tcg_temp_free_i32(tmp);
-    } else {
-        tmp = load_reg(s, rd);
-        gen_helper_set_cp15(cpu_env, tmp2, tmp);
-        tcg_temp_free_i32(tmp);
-        /* Normally we would always end the TB here, but Linux
-         * arch/arm/mach-pxa/sleep.S expects two instructions following
-         * an MMU enable to execute from cache.  Imitate this behaviour.  */
-        if (!arm_feature(env, ARM_FEATURE_XSCALE) ||
-                (insn & 0x0fff0fff) != 0x0e010f10)
-            gen_lookup_tb(s);
-    }
-    tcg_temp_free_i32(tmp2);
-    return 0;
-}
-
 #define VFP_REG_SHR(x, n) (((n) > 0) ? (x) >> (n) : (x) << -(n))
 #define VFP_SREG(insn, bigbit, smallbit) \
   ((VFP_REG_SHR(insn, bigbit - 1) & 0x1e) | (((insn) >> (smallbit)) & 1))
@@ -6388,15 +6339,7 @@ static int disas_coproc_insn(CPUARMState * env, DisasContext *s, uint32_t insn)
         return 0;
     }
 
-    /* Fallback code: handle coprocessor registers not yet converted
-     * to ARMCPRegInfo.
-     */
-    switch (cpnum) {
-    case 15:
-	return disas_cp15_insn (env, s, insn);
-    default:
-        return 1;
-    }
+    return 1;
 }
 
 
commit 30b05bba1122c13206d85d3704e86ff30cc09750
Author: Peter Maydell <peter.maydell at linaro.org>
Date:   Wed Jun 20 11:57:22 2012 +0000

    target-arm: Move block cache ops to new cp15 framework
    
    Move the v6 optional block cache ops to the new cp15 framework.
    This includes only providing them on the CPUs which implemented
    them, rather than the previous blunderbuss approach of making
    all MCRR instructions on all CPUs act as NOPs.
    
    Signed-off-by: Peter Maydell <peter.maydell at linaro.org>

diff --git a/target-arm/helper.c b/target-arm/helper.c
index 9b28f6b..10d4635 100644
--- a/target-arm/helper.c
+++ b/target-arm/helper.c
@@ -810,6 +810,19 @@ static const ARMCPRegInfo cache_block_ops_cp_reginfo[] = {
     /* We never have a a block transfer operation in progress */
     { .name = "BXSR", .cp = 15, .crn = 7, .crm = 12, .opc1 = 0, .opc2 = 4,
       .access = PL0_R, .type = ARM_CP_CONST, .resetvalue = 0 },
+    /* The cache ops themselves: these all NOP for QEMU */
+    { .name = "IICR", .cp = 15, .crm = 5, .opc1 = 0,
+      .access = PL1_W, .type = ARM_CP_NOP|ARM_CP_64BIT },
+    { .name = "IDCR", .cp = 15, .crm = 6, .opc1 = 0,
+      .access = PL1_W, .type = ARM_CP_NOP|ARM_CP_64BIT },
+    { .name = "CDCR", .cp = 15, .crm = 12, .opc1 = 0,
+      .access = PL0_W, .type = ARM_CP_NOP|ARM_CP_64BIT },
+    { .name = "PIR", .cp = 15, .crm = 12, .opc1 = 1,
+      .access = PL0_W, .type = ARM_CP_NOP|ARM_CP_64BIT },
+    { .name = "PDR", .cp = 15, .crm = 12, .opc1 = 2,
+      .access = PL0_W, .type = ARM_CP_NOP|ARM_CP_64BIT },
+    { .name = "CIDCR", .cp = 15, .crm = 14, .opc1 = 0,
+      .access = PL1_W, .type = ARM_CP_NOP|ARM_CP_64BIT },
     REGINFO_SENTINEL
 };
 
diff --git a/target-arm/translate.c b/target-arm/translate.c
index f4e9435..fcdc9d3 100644
--- a/target-arm/translate.c
+++ b/target-arm/translate.c
@@ -2451,12 +2451,7 @@ static int disas_cp15_insn(CPUARMState *env, DisasContext *s, uint32_t insn)
 	return 1;
 
     if ((insn & (1 << 25)) == 0) {
-        if (insn & (1 << 20)) {
-            /* mrrc */
-            return 1;
-        }
-        /* mcrr.  Used for block cache operations, so implement as no-op.  */
-        return 0;
+        return 1;
     }
     if ((insn & (1 << 4)) == 0) {
         /* cdp */
commit b22af022b22091f22deead5f0cbea332b6280acb
Author: Peter Maydell <peter.maydell at linaro.org>
Date:   Wed Jun 20 11:57:21 2012 +0000

    target-arm: Remove c0_cachetype CPUARMState field
    
    Remove the no-longer-used CPUARMState c0_cachetype field.
    Although this was a constant register we had it in our
    migration state. Drop this (with resulting version bump)
    because for ARM currently we prefer cleaner migration
    code and have not stabilised migration format yet.
    
    Signed-off-by: Peter Maydell <peter.maydell at linaro.org>

diff --git a/target-arm/cpu.h b/target-arm/cpu.h
index 2630fe7..27e398b 100644
--- a/target-arm/cpu.h
+++ b/target-arm/cpu.h
@@ -107,7 +107,6 @@ typedef struct CPUARMState {
     /* System control coprocessor (cp15) */
     struct {
         uint32_t c0_cpuid;
-        uint32_t c0_cachetype;
         uint32_t c0_cssel; /* Cache size selection.  */
         uint32_t c1_sys; /* System control register.  */
         uint32_t c1_coproc; /* Coprocessor access register.  */
@@ -664,7 +663,7 @@ static inline CPUARMState *cpu_init(const char *cpu_model)
 #define cpu_signal_handler cpu_arm_signal_handler
 #define cpu_list arm_cpu_list
 
-#define CPU_SAVE_VERSION 6
+#define CPU_SAVE_VERSION 7
 
 /* MMU modes definitions */
 #define MMU_MODE0_SUFFIX _kernel
diff --git a/target-arm/machine.c b/target-arm/machine.c
index f66b8df..a2a75fb 100644
--- a/target-arm/machine.c
+++ b/target-arm/machine.c
@@ -21,7 +21,6 @@ void cpu_save(QEMUFile *f, void *opaque)
         qemu_put_be32(f, env->fiq_regs[i]);
     }
     qemu_put_be32(f, env->cp15.c0_cpuid);
-    qemu_put_be32(f, env->cp15.c0_cachetype);
     qemu_put_be32(f, env->cp15.c0_cssel);
     qemu_put_be32(f, env->cp15.c1_sys);
     qemu_put_be32(f, env->cp15.c1_coproc);
@@ -139,7 +138,6 @@ int cpu_load(QEMUFile *f, void *opaque, int version_id)
         env->fiq_regs[i] = qemu_get_be32(f);
     }
     env->cp15.c0_cpuid = qemu_get_be32(f);
-    env->cp15.c0_cachetype = qemu_get_be32(f);
     env->cp15.c0_cssel = qemu_get_be32(f);
     env->cp15.c1_sys = qemu_get_be32(f);
     env->cp15.c1_coproc = qemu_get_be32(f);
commit 7884849cc5b99f5e40217765d62809789ef76bc8
Author: Peter Maydell <peter.maydell at linaro.org>
Date:   Wed Jun 20 11:57:20 2012 +0000

    target-arm: Convert final ID registers
    
    Convert the final ID registers to the new cp15 scheme.
    
    Signed-off-by: Peter Maydell <peter.maydell at linaro.org>

diff --git a/target-arm/cpu.c b/target-arm/cpu.c
index 0c031ba..3ea3527 100644
--- a/target-arm/cpu.c
+++ b/target-arm/cpu.c
@@ -72,11 +72,9 @@ static void arm_cpu_reset(CPUState *s)
 
     memset(env, 0, offsetof(CPUARMState, breakpoints));
     g_hash_table_foreach(cpu->cp_regs, cp_reg_reset, cpu);
-    env->cp15.c0_cpuid = cpu->midr;
     env->vfp.xregs[ARM_VFP_FPSID] = cpu->reset_fpsid;
     env->vfp.xregs[ARM_VFP_MVFR0] = cpu->mvfr0;
     env->vfp.xregs[ARM_VFP_MVFR1] = cpu->mvfr1;
-    env->cp15.c0_cachetype = cpu->ctr;
 
     if (arm_feature(env, ARM_FEATURE_IWMMXT)) {
         env->iwmmxt.cregs[ARM_IWMMXT_wCID] = 0x69051000 | 'Q';
diff --git a/target-arm/helper.c b/target-arm/helper.c
index 1acc212..9b28f6b 100644
--- a/target-arm/helper.c
+++ b/target-arm/helper.c
@@ -1003,6 +1003,74 @@ void register_cp_regs_for_features(ARMCPU *cpu)
     if (arm_feature(env, ARM_FEATURE_MPIDR)) {
         define_arm_cp_regs(cpu, mpidr_cp_reginfo);
     }
+    /* Slightly awkwardly, the OMAP and StrongARM cores need all of
+     * cp15 crn=0 to be writes-ignored, whereas for other cores they should
+     * be read-only (ie write causes UNDEF exception).
+     */
+    {
+        ARMCPRegInfo id_cp_reginfo[] = {
+            /* Note that the MIDR isn't a simple constant register because
+             * of the TI925 behaviour where writes to another register can
+             * cause the MIDR value to change.
+             */
+            { .name = "MIDR",
+              .cp = 15, .crn = 0, .crm = 0, .opc1 = 0, .opc2 = 0,
+              .access = PL1_R, .resetvalue = cpu->midr,
+              .writefn = arm_cp_write_ignore,
+              .fieldoffset = offsetof(CPUARMState, cp15.c0_cpuid) },
+            { .name = "CTR",
+              .cp = 15, .crn = 0, .crm = 0, .opc1 = 0, .opc2 = 1,
+              .access = PL1_R, .type = ARM_CP_CONST, .resetvalue = cpu->ctr },
+            { .name = "TCMTR",
+              .cp = 15, .crn = 0, .crm = 0, .opc1 = 0, .opc2 = 2,
+              .access = PL1_R, .type = ARM_CP_CONST, .resetvalue = 0 },
+            { .name = "TLBTR",
+              .cp = 15, .crn = 0, .crm = 0, .opc1 = 0, .opc2 = 3,
+              .access = PL1_R, .type = ARM_CP_CONST, .resetvalue = 0 },
+            /* crn = 0 op1 = 0 crm = 3..7 : currently unassigned; we RAZ. */
+            { .name = "DUMMY",
+              .cp = 15, .crn = 0, .crm = 3, .opc1 = 0, .opc2 = CP_ANY,
+              .access = PL1_R, .type = ARM_CP_CONST, .resetvalue = 0 },
+            { .name = "DUMMY",
+              .cp = 15, .crn = 0, .crm = 4, .opc1 = 0, .opc2 = CP_ANY,
+              .access = PL1_R, .type = ARM_CP_CONST, .resetvalue = 0 },
+            { .name = "DUMMY",
+              .cp = 15, .crn = 0, .crm = 5, .opc1 = 0, .opc2 = CP_ANY,
+              .access = PL1_R, .type = ARM_CP_CONST, .resetvalue = 0 },
+            { .name = "DUMMY",
+              .cp = 15, .crn = 0, .crm = 6, .opc1 = 0, .opc2 = CP_ANY,
+              .access = PL1_R, .type = ARM_CP_CONST, .resetvalue = 0 },
+            { .name = "DUMMY",
+              .cp = 15, .crn = 0, .crm = 7, .opc1 = 0, .opc2 = CP_ANY,
+              .access = PL1_R, .type = ARM_CP_CONST, .resetvalue = 0 },
+            REGINFO_SENTINEL
+        };
+        ARMCPRegInfo crn0_wi_reginfo = {
+            .name = "CRN0_WI", .cp = 15, .crn = 0, .crm = CP_ANY,
+            .opc1 = CP_ANY, .opc2 = CP_ANY, .access = PL1_W,
+            .type = ARM_CP_NOP | ARM_CP_OVERRIDE
+        };
+        if (arm_feature(env, ARM_FEATURE_OMAPCP) ||
+            arm_feature(env, ARM_FEATURE_STRONGARM)) {
+            ARMCPRegInfo *r;
+            /* Register the blanket "writes ignored" value first to cover the
+             * whole space. Then define the specific ID registers, but update
+             * their access field to allow write access, so that they ignore
+             * writes rather than causing them to UNDEF.
+             */
+            define_one_arm_cp_reg(cpu, &crn0_wi_reginfo);
+            for (r = id_cp_reginfo; r->type != ARM_CP_SENTINEL; r++) {
+                r->access = PL1_RW;
+                define_one_arm_cp_reg(cpu, r);
+            }
+        } else {
+            /* Just register the standard ID registers (read-only, meaning
+             * that writes will UNDEF).
+             */
+            define_arm_cp_regs(cpu, id_cp_reginfo);
+        }
+    }
+
     if (arm_feature(env, ARM_FEATURE_AUXCR)) {
         ARMCPRegInfo auxcr = {
             .name = "AUXCR", .cp = 15, .crn = 1, .crm = 0, .opc1 = 0, .opc2 = 1,
@@ -2105,21 +2173,6 @@ void HELPER(set_cp15)(CPUARMState *env, uint32_t insn, uint32_t val)
     op1 = (insn >> 21) & 7;
     op2 = (insn >> 5) & 7;
     crm = insn & 0xf;
-    switch ((insn >> 16) & 0xf) {
-    case 0:
-        /* ID codes.  */
-        if (arm_feature(env, ARM_FEATURE_XSCALE))
-            break;
-        if (arm_feature(env, ARM_FEATURE_OMAPCP))
-            break;
-        goto bad_reg;
-    case 4: /* Reserved.  */
-        goto bad_reg;
-    case 12: /* Reserved.  */
-        goto bad_reg;
-    }
-    return;
-bad_reg:
     /* ??? For debugging only.  Should raise illegal instruction exception.  */
     cpu_abort(env, "Unimplemented cp15 register write (c%d, c%d, {%d, %d})\n",
               (insn >> 16) & 0xf, crm, op1, op2);
@@ -2134,39 +2187,6 @@ uint32_t HELPER(get_cp15)(CPUARMState *env, uint32_t insn)
     op1 = (insn >> 21) & 7;
     op2 = (insn >> 5) & 7;
     crm = insn & 0xf;
-    switch ((insn >> 16) & 0xf) {
-    case 0: /* ID codes.  */
-        switch (op1) {
-        case 0:
-            switch (crm) {
-            case 0:
-                switch (op2) {
-                case 0: /* Device ID.  */
-                    return env->cp15.c0_cpuid;
-                case 1: /* Cache Type.  */
-		    return env->cp15.c0_cachetype;
-                case 2: /* TCM status.  */
-                    return 0;
-                case 3: /* TLB type register.  */
-                    return 0; /* No lockable TLB entries.  */
-                default:
-                    goto bad_reg;
-                }
-            case 3: case 4: case 5: case 6: case 7:
-                return 0;
-            default:
-                goto bad_reg;
-            }
-        default:
-            goto bad_reg;
-        }
-    case 4: /* Reserved.  */
-        goto bad_reg;
-    case 11: /* TCM DMA control.  */
-    case 12: /* Reserved.  */
-        goto bad_reg;
-    }
-bad_reg:
     /* ??? For debugging only.  Should raise illegal instruction exception.  */
     cpu_abort(env, "Unimplemented cp15 register read (c%d, c%d, {%d, %d})\n",
               (insn >> 16) & 0xf, crm, op1, op2);
commit 81bdde9dcdba5bbc358b2c6b8f776a05a751cc72
Author: Peter Maydell <peter.maydell at linaro.org>
Date:   Wed Jun 20 11:57:20 2012 +0000

    target-arm: Convert MPIDR
    
    Convert the MPIDR to the new cp15 register scheme.
    This includes giving it its own feature bit rather
    than doing a CPUID value check.
    
    Signed-off-by: Peter Maydell <peter.maydell at linaro.org>

diff --git a/target-arm/cpu.c b/target-arm/cpu.c
index f4c9116..0c031ba 100644
--- a/target-arm/cpu.c
+++ b/target-arm/cpu.c
@@ -162,6 +162,7 @@ void arm_cpu_realize(ARMCPU *cpu)
     if (arm_feature(env, ARM_FEATURE_V7)) {
         set_feature(env, ARM_FEATURE_VAPA);
         set_feature(env, ARM_FEATURE_THUMB2);
+        set_feature(env, ARM_FEATURE_MPIDR);
         if (!arm_feature(env, ARM_FEATURE_M)) {
             set_feature(env, ARM_FEATURE_V6K);
         } else {
@@ -350,6 +351,7 @@ static void arm11mpcore_initfn(Object *obj)
     set_feature(&cpu->env, ARM_FEATURE_V6K);
     set_feature(&cpu->env, ARM_FEATURE_VFP);
     set_feature(&cpu->env, ARM_FEATURE_VAPA);
+    set_feature(&cpu->env, ARM_FEATURE_MPIDR);
     set_feature(&cpu->env, ARM_FEATURE_DUMMY_C15_REGS);
     cpu->midr = ARM_CPUID_ARM11MPCORE;
     cpu->reset_fpsid = 0x410120b4;
diff --git a/target-arm/cpu.h b/target-arm/cpu.h
index 0b984d8..2630fe7 100644
--- a/target-arm/cpu.h
+++ b/target-arm/cpu.h
@@ -386,6 +386,7 @@ enum arm_features {
     ARM_FEATURE_CACHE_TEST_CLEAN, /* 926/1026 style test-and-clean ops */
     ARM_FEATURE_CACHE_DIRTY_REG, /* 1136/1176 cache dirty status register */
     ARM_FEATURE_CACHE_BLOCK_OPS, /* v6 optional cache block operations */
+    ARM_FEATURE_MPIDR, /* has cp15 MPIDR */
 };
 
 static inline int arm_feature(CPUARMState *env, int feature)
diff --git a/target-arm/helper.c b/target-arm/helper.c
index 269740d..1acc212 100644
--- a/target-arm/helper.c
+++ b/target-arm/helper.c
@@ -833,6 +833,31 @@ static const ARMCPRegInfo strongarm_cp_reginfo[] = {
     REGINFO_SENTINEL
 };
 
+static int mpidr_read(CPUARMState *env, const ARMCPRegInfo *ri,
+                      uint64_t *value)
+{
+    uint32_t mpidr = env->cpu_index;
+    /* We don't support setting cluster ID ([8..11])
+     * so these bits always RAZ.
+     */
+    if (arm_feature(env, ARM_FEATURE_V7MP)) {
+        mpidr |= (1 << 31);
+        /* Cores which are uniprocessor (non-coherent)
+         * but still implement the MP extensions set
+         * bit 30. (For instance, A9UP.) However we do
+         * not currently model any of those cores.
+         */
+    }
+    *value = mpidr;
+    return 0;
+}
+
+static const ARMCPRegInfo mpidr_cp_reginfo[] = {
+    { .name = "MPIDR", .cp = 15, .crn = 0, .crm = 0, .opc1 = 0, .opc2 = 5,
+      .access = PL1_R, .readfn = mpidr_read },
+    REGINFO_SENTINEL
+};
+
 static int sctlr_write(CPUARMState *env, const ARMCPRegInfo *ri, uint64_t value)
 {
     env->cp15.c1_sys = value;
@@ -975,6 +1000,9 @@ void register_cp_regs_for_features(ARMCPU *cpu)
     if (arm_feature(env, ARM_FEATURE_DUMMY_C15_REGS)) {
         define_arm_cp_regs(cpu, dummy_c15_cp_reginfo);
     }
+    if (arm_feature(env, ARM_FEATURE_MPIDR)) {
+        define_arm_cp_regs(cpu, mpidr_cp_reginfo);
+    }
     if (arm_feature(env, ARM_FEATURE_AUXCR)) {
         ARMCPRegInfo auxcr = {
             .name = "AUXCR", .cp = 15, .crn = 1, .crm = 0, .opc1 = 0, .opc2 = 1,
@@ -2121,28 +2149,6 @@ uint32_t HELPER(get_cp15)(CPUARMState *env, uint32_t insn)
                     return 0;
                 case 3: /* TLB type register.  */
                     return 0; /* No lockable TLB entries.  */
-                case 5: /* MPIDR */
-                    /* The MPIDR was standardised in v7; prior to
-                     * this it was implemented only in the 11MPCore.
-                     * For all other pre-v7 cores it does not exist.
-                     */
-                    if (arm_feature(env, ARM_FEATURE_V7) ||
-                        ARM_CPUID(env) == ARM_CPUID_ARM11MPCORE) {
-                        int mpidr = env->cpu_index;
-                        /* We don't support setting cluster ID ([8..11])
-                         * so these bits always RAZ.
-                         */
-                        if (arm_feature(env, ARM_FEATURE_V7MP)) {
-                            mpidr |= (1 << 31);
-                            /* Cores which are uniprocessor (non-coherent)
-                             * but still implement the MP extensions set
-                             * bit 30. (For instance, A9UP.) However we do
-                             * not currently model any of those cores.
-                             */
-                        }
-                        return mpidr;
-                    }
-                    /* otherwise fall through to the unimplemented-reg case */
                 default:
                     goto bad_reg;
                 }
commit 776d4e5c6ca47f8d7b73c9c8eccf20209bf57529
Author: Peter Maydell <peter.maydell at linaro.org>
Date:   Wed Jun 20 11:57:19 2012 +0000

    target-arm: Convert cp15 cache ID registers
    
    Convert the cp15 cache ID registers to the new scheme.
    
    Signed-off-by: Peter Maydell <peter.maydell at linaro.org>

diff --git a/target-arm/cpu.c b/target-arm/cpu.c
index f9b3046..f4c9116 100644
--- a/target-arm/cpu.c
+++ b/target-arm/cpu.c
@@ -77,8 +77,6 @@ static void arm_cpu_reset(CPUState *s)
     env->vfp.xregs[ARM_VFP_MVFR0] = cpu->mvfr0;
     env->vfp.xregs[ARM_VFP_MVFR1] = cpu->mvfr1;
     env->cp15.c0_cachetype = cpu->ctr;
-    env->cp15.c0_clid = cpu->clidr;
-    memcpy(env->cp15.c0_ccsid, cpu->ccsidr, ARRAY_SIZE(cpu->ccsidr));
 
     if (arm_feature(env, ARM_FEATURE_IWMMXT)) {
         env->iwmmxt.cregs[ARM_IWMMXT_wCID] = 0x69051000 | 'Q';
diff --git a/target-arm/cpu.h b/target-arm/cpu.h
index 0953543..0b984d8 100644
--- a/target-arm/cpu.h
+++ b/target-arm/cpu.h
@@ -108,8 +108,6 @@ typedef struct CPUARMState {
     struct {
         uint32_t c0_cpuid;
         uint32_t c0_cachetype;
-        uint32_t c0_ccsid[16]; /* Cache size.  */
-        uint32_t c0_clid; /* Cache level.  */
         uint32_t c0_cssel; /* Cache size selection.  */
         uint32_t c1_sys; /* System control register.  */
         uint32_t c1_coproc; /* Coprocessor access register.  */
diff --git a/target-arm/helper.c b/target-arm/helper.c
index 11b2ad9..269740d 100644
--- a/target-arm/helper.c
+++ b/target-arm/helper.c
@@ -193,6 +193,9 @@ static const ARMCPRegInfo not_v7_cp_reginfo[] = {
     { .name = "ILOCKDOWN", .cp = 15, .crn = 9, .crm = 0, .opc1 = 0, .opc2 = 1,
       .access = PL1_RW, .fieldoffset = offsetof(CPUARMState, cp15.c9_insn),
       .resetvalue = 0 },
+    /* v6 doesn't have the cache ID registers but Linux reads them anyway */
+    { .name = "DUMMY", .cp = 15, .crn = 0, .crm = 0, .opc1 = 1, .opc2 = CP_ANY,
+      .access = PL1_R, .type = ARM_CP_CONST, .resetvalue = 0 },
     REGINFO_SENTINEL
 };
 
@@ -322,6 +325,21 @@ static int pmintenclr_write(CPUARMState *env, const ARMCPRegInfo *ri,
     return 0;
 }
 
+static int ccsidr_read(CPUARMState *env, const ARMCPRegInfo *ri,
+                       uint64_t *value)
+{
+    ARMCPU *cpu = arm_env_get_cpu(env);
+    *value = cpu->ccsidr[env->cp15.c0_cssel];
+    return 0;
+}
+
+static int csselr_write(CPUARMState *env, const ARMCPRegInfo *ri,
+                        uint64_t value)
+{
+    env->cp15.c0_cssel = value & 0xf;
+    return 0;
+}
+
 static const ARMCPRegInfo v7_cp_reginfo[] = {
     /* DBGDRAR, DBGDSAR: always RAZ since we don't implement memory mapped
      * debug components
@@ -392,6 +410,16 @@ static const ARMCPRegInfo v7_cp_reginfo[] = {
     { .name = "SCR", .cp = 15, .crn = 1, .crm = 1, .opc1 = 0, .opc2 = 0,
       .access = PL1_RW, .fieldoffset = offsetof(CPUARMState, cp15.c1_scr),
       .resetvalue = 0, },
+    { .name = "CCSIDR", .cp = 15, .crn = 0, .crm = 0, .opc1 = 1, .opc2 = 0,
+      .access = PL1_R, .readfn = ccsidr_read },
+    { .name = "CSSELR", .cp = 15, .crn = 0, .crm = 0, .opc1 = 2, .opc2 = 0,
+      .access = PL1_RW, .fieldoffset = offsetof(CPUARMState, cp15.c0_cssel),
+      .writefn = csselr_write, .resetvalue = 0 },
+    /* Auxiliary ID register: this actually has an IMPDEF value but for now
+     * just RAZ for all cores:
+     */
+    { .name = "AIDR", .cp = 15, .crn = 0, .crm = 0, .opc1 = 1, .opc2 = 7,
+      .access = PL1_R, .type = ARM_CP_CONST, .resetvalue = 0 },
     REGINFO_SENTINEL
 };
 
@@ -896,7 +924,12 @@ void register_cp_regs_for_features(ARMCPU *cpu)
             .fieldoffset = offsetof(CPUARMState, cp15.c9_pmcr),
             .readfn = pmreg_read, .writefn = pmcr_write
         };
+        ARMCPRegInfo clidr = {
+            .name = "CLIDR", .cp = 15, .crn = 0, .crm = 0, .opc1 = 1, .opc2 = 1,
+            .access = PL1_R, .type = ARM_CP_CONST, .resetvalue = cpu->clidr
+        };
         define_one_arm_cp_reg(cpu, &pmcr);
+        define_one_arm_cp_reg(cpu, &clidr);
         define_arm_cp_regs(cpu, v7_cp_reginfo);
     } else {
         define_arm_cp_regs(cpu, not_v7_cp_reginfo);
@@ -2051,11 +2084,6 @@ void HELPER(set_cp15)(CPUARMState *env, uint32_t insn, uint32_t val)
             break;
         if (arm_feature(env, ARM_FEATURE_OMAPCP))
             break;
-        if (arm_feature(env, ARM_FEATURE_V7)
-                && op1 == 2 && crm == 0 && op2 == 0) {
-            env->cp15.c0_cssel = val & 0xf;
-            break;
-        }
         goto bad_reg;
     case 4: /* Reserved.  */
         goto bad_reg;
@@ -2123,29 +2151,6 @@ uint32_t HELPER(get_cp15)(CPUARMState *env, uint32_t insn)
             default:
                 goto bad_reg;
             }
-        case 1:
-            /* These registers aren't documented on arm11 cores.  However
-               Linux looks at them anyway.  */
-            if (!arm_feature(env, ARM_FEATURE_V6))
-                goto bad_reg;
-            if (crm != 0)
-                goto bad_reg;
-            if (!arm_feature(env, ARM_FEATURE_V7))
-                return 0;
-
-            switch (op2) {
-            case 0:
-                return env->cp15.c0_ccsid[env->cp15.c0_cssel];
-            case 1:
-                return env->cp15.c0_clid;
-            case 7:
-                return 0;
-            }
-            goto bad_reg;
-        case 2:
-            if (op2 != 0 || crm != 0)
-                goto bad_reg;
-            return env->cp15.c0_cssel;
         default:
             goto bad_reg;
         }
commit 8515a092948584ce112b90030edcef344c6a0f90
Author: Peter Maydell <peter.maydell at linaro.org>
Date:   Wed Jun 20 11:57:19 2012 +0000

    target-arm: Convert cp15 crn=0 crm={1,2} feature registers
    
    Convert the cp15 crn=0 crm={1,2} features registers to
    the new cp reg framework.
    
    Signed-off-by: Peter Maydell <peter.maydell at linaro.org>

diff --git a/target-arm/cpu.c b/target-arm/cpu.c
index d84db53..f9b3046 100644
--- a/target-arm/cpu.c
+++ b/target-arm/cpu.c
@@ -77,20 +77,6 @@ static void arm_cpu_reset(CPUState *s)
     env->vfp.xregs[ARM_VFP_MVFR0] = cpu->mvfr0;
     env->vfp.xregs[ARM_VFP_MVFR1] = cpu->mvfr1;
     env->cp15.c0_cachetype = cpu->ctr;
-    env->cp15.c0_c1[0] = cpu->id_pfr0;
-    env->cp15.c0_c1[1] = cpu->id_pfr1;
-    env->cp15.c0_c1[2] = cpu->id_dfr0;
-    env->cp15.c0_c1[3] = cpu->id_afr0;
-    env->cp15.c0_c1[4] = cpu->id_mmfr0;
-    env->cp15.c0_c1[5] = cpu->id_mmfr1;
-    env->cp15.c0_c1[6] = cpu->id_mmfr2;
-    env->cp15.c0_c1[7] = cpu->id_mmfr3;
-    env->cp15.c0_c2[0] = cpu->id_isar0;
-    env->cp15.c0_c2[1] = cpu->id_isar1;
-    env->cp15.c0_c2[2] = cpu->id_isar2;
-    env->cp15.c0_c2[3] = cpu->id_isar3;
-    env->cp15.c0_c2[4] = cpu->id_isar4;
-    env->cp15.c0_c2[5] = cpu->id_isar5;
     env->cp15.c0_clid = cpu->clidr;
     memcpy(env->cp15.c0_ccsid, cpu->ccsidr, ARRAY_SIZE(cpu->ccsidr));
 
diff --git a/target-arm/cpu.h b/target-arm/cpu.h
index 02d86ca..0953543 100644
--- a/target-arm/cpu.h
+++ b/target-arm/cpu.h
@@ -111,8 +111,6 @@ typedef struct CPUARMState {
         uint32_t c0_ccsid[16]; /* Cache size.  */
         uint32_t c0_clid; /* Cache level.  */
         uint32_t c0_cssel; /* Cache size selection.  */
-        uint32_t c0_c1[8]; /* Feature registers.  */
-        uint32_t c0_c2[8]; /* Instruction set registers.  */
         uint32_t c1_sys; /* System control register.  */
         uint32_t c1_coproc; /* Coprocessor access register.  */
         uint32_t c1_xscaleauxcr; /* XScale auxiliary control register.  */
diff --git a/target-arm/helper.c b/target-arm/helper.c
index 00934cd..11b2ad9 100644
--- a/target-arm/helper.c
+++ b/target-arm/helper.c
@@ -825,6 +825,60 @@ void register_cp_regs_for_features(ARMCPU *cpu)
 
     define_arm_cp_regs(cpu, cp_reginfo);
     if (arm_feature(env, ARM_FEATURE_V6)) {
+        /* The ID registers all have impdef reset values */
+        ARMCPRegInfo v6_idregs[] = {
+            { .name = "ID_PFR0", .cp = 15, .crn = 0, .crm = 1,
+              .opc1 = 0, .opc2 = 0, .access = PL1_R, .type = ARM_CP_CONST,
+              .resetvalue = cpu->id_pfr0 },
+            { .name = "ID_PFR1", .cp = 15, .crn = 0, .crm = 1,
+              .opc1 = 0, .opc2 = 1, .access = PL1_R, .type = ARM_CP_CONST,
+              .resetvalue = cpu->id_pfr1 },
+            { .name = "ID_DFR0", .cp = 15, .crn = 0, .crm = 1,
+              .opc1 = 0, .opc2 = 2, .access = PL1_R, .type = ARM_CP_CONST,
+              .resetvalue = cpu->id_dfr0 },
+            { .name = "ID_AFR0", .cp = 15, .crn = 0, .crm = 1,
+              .opc1 = 0, .opc2 = 3, .access = PL1_R, .type = ARM_CP_CONST,
+              .resetvalue = cpu->id_afr0 },
+            { .name = "ID_MMFR0", .cp = 15, .crn = 0, .crm = 1,
+              .opc1 = 0, .opc2 = 4, .access = PL1_R, .type = ARM_CP_CONST,
+              .resetvalue = cpu->id_mmfr0 },
+            { .name = "ID_MMFR1", .cp = 15, .crn = 0, .crm = 1,
+              .opc1 = 0, .opc2 = 5, .access = PL1_R, .type = ARM_CP_CONST,
+              .resetvalue = cpu->id_mmfr1 },
+            { .name = "ID_MMFR2", .cp = 15, .crn = 0, .crm = 1,
+              .opc1 = 0, .opc2 = 6, .access = PL1_R, .type = ARM_CP_CONST,
+              .resetvalue = cpu->id_mmfr2 },
+            { .name = "ID_MMFR3", .cp = 15, .crn = 0, .crm = 1,
+              .opc1 = 0, .opc2 = 7, .access = PL1_R, .type = ARM_CP_CONST,
+              .resetvalue = cpu->id_mmfr3 },
+            { .name = "ID_ISAR0", .cp = 15, .crn = 0, .crm = 2,
+              .opc1 = 0, .opc2 = 0, .access = PL1_R, .type = ARM_CP_CONST,
+              .resetvalue = cpu->id_isar0 },
+            { .name = "ID_ISAR1", .cp = 15, .crn = 0, .crm = 2,
+              .opc1 = 0, .opc2 = 1, .access = PL1_R, .type = ARM_CP_CONST,
+              .resetvalue = cpu->id_isar1 },
+            { .name = "ID_ISAR2", .cp = 15, .crn = 0, .crm = 2,
+              .opc1 = 0, .opc2 = 2, .access = PL1_R, .type = ARM_CP_CONST,
+              .resetvalue = cpu->id_isar2 },
+            { .name = "ID_ISAR3", .cp = 15, .crn = 0, .crm = 2,
+              .opc1 = 0, .opc2 = 3, .access = PL1_R, .type = ARM_CP_CONST,
+              .resetvalue = cpu->id_isar3 },
+            { .name = "ID_ISAR4", .cp = 15, .crn = 0, .crm = 2,
+              .opc1 = 0, .opc2 = 4, .access = PL1_R, .type = ARM_CP_CONST,
+              .resetvalue = cpu->id_isar4 },
+            { .name = "ID_ISAR5", .cp = 15, .crn = 0, .crm = 2,
+              .opc1 = 0, .opc2 = 5, .access = PL1_R, .type = ARM_CP_CONST,
+              .resetvalue = cpu->id_isar5 },
+            /* 6..7 are as yet unallocated and must RAZ */
+            { .name = "ID_ISAR6", .cp = 15, .crn = 0, .crm = 2,
+              .opc1 = 0, .opc2 = 6, .access = PL1_R, .type = ARM_CP_CONST,
+              .resetvalue = 0 },
+            { .name = "ID_ISAR7", .cp = 15, .crn = 0, .crm = 2,
+              .opc1 = 0, .opc2 = 7, .access = PL1_R, .type = ARM_CP_CONST,
+              .resetvalue = 0 },
+            REGINFO_SENTINEL
+        };
+        define_arm_cp_regs(cpu, v6_idregs);
         define_arm_cp_regs(cpu, v6_cp_reginfo);
     } else {
         define_arm_cp_regs(cpu, not_v6_cp_reginfo);
@@ -2064,14 +2118,6 @@ uint32_t HELPER(get_cp15)(CPUARMState *env, uint32_t insn)
                 default:
                     goto bad_reg;
                 }
-            case 1:
-                if (!arm_feature(env, ARM_FEATURE_V6))
-                    goto bad_reg;
-                return env->cp15.c0_c1[op2];
-            case 2:
-                if (!arm_feature(env, ARM_FEATURE_V6))
-                    goto bad_reg;
-                return env->cp15.c0_c2[op2];
             case 3: case 4: case 5: case 6: case 7:
                 return 0;
             default:
commit 2771db274193420b82f988b995282820631cdd99
Author: Peter Maydell <peter.maydell at linaro.org>
Date:   Wed Jun 20 11:57:18 2012 +0000

    target-arm: Convert cp15 crn=1 registers
    
    Convert the cp15 crn=1 registers to the new scheme.
    
    Signed-off-by: Peter Maydell <peter.maydell at linaro.org>

diff --git a/target-arm/cpu-qom.h b/target-arm/cpu-qom.h
index 4ccfc89..beabf9a 100644
--- a/target-arm/cpu-qom.h
+++ b/target-arm/cpu-qom.h
@@ -97,6 +97,7 @@ typedef struct ARMCPU {
      */
     uint32_t ccsidr[16];
     uint32_t reset_cbar;
+    uint32_t reset_auxcr;
 } ARMCPU;
 
 static inline ARMCPU *arm_env_get_cpu(CPUARMState *env)
diff --git a/target-arm/cpu.c b/target-arm/cpu.c
index c03db20..d84db53 100644
--- a/target-arm/cpu.c
+++ b/target-arm/cpu.c
@@ -77,7 +77,6 @@ static void arm_cpu_reset(CPUState *s)
     env->vfp.xregs[ARM_VFP_MVFR0] = cpu->mvfr0;
     env->vfp.xregs[ARM_VFP_MVFR1] = cpu->mvfr1;
     env->cp15.c0_cachetype = cpu->ctr;
-    env->cp15.c1_sys = cpu->reset_sctlr;
     env->cp15.c0_c1[0] = cpu->id_pfr0;
     env->cp15.c0_c1[1] = cpu->id_pfr1;
     env->cp15.c0_c1[2] = cpu->id_dfr0;
@@ -252,6 +251,7 @@ static void arm1026_initfn(Object *obj)
     cpu->reset_fpsid = 0x410110a0;
     cpu->ctr = 0x1dd20d2;
     cpu->reset_sctlr = 0x00090078;
+    cpu->reset_auxcr = 1;
     {
         /* The 1026 had an IFAR at c6,c0,0,1 rather than the ARMv6 c6,c0,0,2 */
         ARMCPRegInfo ifar = {
@@ -297,6 +297,7 @@ static void arm1136_r2_initfn(Object *obj)
     cpu->id_isar2 = 0x11231111;
     cpu->id_isar3 = 0x01102131;
     cpu->id_isar4 = 0x141;
+    cpu->reset_auxcr = 7;
 }
 
 static void arm1136_initfn(Object *obj)
@@ -326,6 +327,7 @@ static void arm1136_initfn(Object *obj)
     cpu->id_isar2 = 0x11231111;
     cpu->id_isar3 = 0x01102131;
     cpu->id_isar4 = 0x141;
+    cpu->reset_auxcr = 7;
 }
 
 static void arm1176_initfn(Object *obj)
@@ -355,6 +357,7 @@ static void arm1176_initfn(Object *obj)
     cpu->id_isar2 = 0x11231121;
     cpu->id_isar3 = 0x01102131;
     cpu->id_isar4 = 0x01141;
+    cpu->reset_auxcr = 7;
 }
 
 static void arm11mpcore_initfn(Object *obj)
@@ -381,6 +384,7 @@ static void arm11mpcore_initfn(Object *obj)
     cpu->id_isar2 = 0x11221011;
     cpu->id_isar3 = 0x01102131;
     cpu->id_isar4 = 0x141;
+    cpu->reset_auxcr = 1;
 }
 
 static void cortex_m3_initfn(Object *obj)
@@ -430,6 +434,7 @@ static void cortex_a8_initfn(Object *obj)
     cpu->ccsidr[0] = 0xe007e01a; /* 16k L1 dcache. */
     cpu->ccsidr[1] = 0x2007e01a; /* 16k L1 icache. */
     cpu->ccsidr[2] = 0xf0000000; /* No L2 icache. */
+    cpu->reset_auxcr = 2;
     define_arm_cp_regs(cpu, cortexa8_cp_reginfo);
 }
 
diff --git a/target-arm/helper.c b/target-arm/helper.c
index 2c6e7ed..00934cd 100644
--- a/target-arm/helper.c
+++ b/target-arm/helper.c
@@ -196,6 +196,16 @@ static const ARMCPRegInfo not_v7_cp_reginfo[] = {
     REGINFO_SENTINEL
 };
 
+static int cpacr_write(CPUARMState *env, const ARMCPRegInfo *ri, uint64_t value)
+{
+    if (env->cp15.c1_coproc != value) {
+        env->cp15.c1_coproc = value;
+        /* ??? Is this safe when called from within a TB?  */
+        tb_flush(env);
+    }
+    return 0;
+}
+
 static const ARMCPRegInfo v6_cp_reginfo[] = {
     /* prefetch by MVA in v6, NOP in v7 */
     { .name = "MVA_prefetch",
@@ -215,6 +225,9 @@ static const ARMCPRegInfo v6_cp_reginfo[] = {
      */
     { .name = "WFAR", .cp = 15, .crn = 6, .crm = 0, .opc1 = 0, .opc2 = 1,
       .access = PL1_RW, .type = ARM_CP_CONST, .resetvalue = 0, },
+    { .name = "CPACR", .cp = 15, .crn = 1, .crm = 0, .opc1 = 0, .opc2 = 2,
+      .access = PL1_RW, .fieldoffset = offsetof(CPUARMState, cp15.c1_coproc),
+      .resetvalue = 0, .writefn = cpacr_write },
     REGINFO_SENTINEL
 };
 
@@ -376,6 +389,9 @@ static const ARMCPRegInfo v7_cp_reginfo[] = {
       .fieldoffset = offsetof(CPUARMState, cp15.c9_pminten),
       .resetvalue = 0,
       .writefn = pmintenclr_write },
+    { .name = "SCR", .cp = 15, .crn = 1, .crm = 1, .opc1 = 0, .opc2 = 0,
+      .access = PL1_RW, .fieldoffset = offsetof(CPUARMState, cp15.c1_scr),
+      .resetvalue = 0, },
     REGINFO_SENTINEL
 };
 
@@ -736,6 +752,10 @@ static const ARMCPRegInfo xscale_cp_reginfo[] = {
       .cp = 15, .crn = 15, .crm = 1, .opc1 = 0, .opc2 = 0, .access = PL1_RW,
       .fieldoffset = offsetof(CPUARMState, cp15.c15_cpar), .resetvalue = 0,
       .writefn = xscale_cpar_write, },
+    { .name = "XSCALE_AUXCR",
+      .cp = 15, .crn = 1, .crm = 0, .opc1 = 0, .opc2 = 1, .access = PL1_RW,
+      .fieldoffset = offsetof(CPUARMState, cp15.c1_xscaleauxcr),
+      .resetvalue = 0, },
     REGINFO_SENTINEL
 };
 
@@ -785,6 +805,15 @@ static const ARMCPRegInfo strongarm_cp_reginfo[] = {
     REGINFO_SENTINEL
 };
 
+static int sctlr_write(CPUARMState *env, const ARMCPRegInfo *ri, uint64_t value)
+{
+    env->cp15.c1_sys = value;
+    /* ??? Lots of these bits are not implemented.  */
+    /* This may enable/disable the MMU, so do a TLB flush.  */
+    tlb_flush(env, 1);
+    return 0;
+}
+
 void register_cp_regs_for_features(ARMCPU *cpu)
 {
     /* Register all the coprocessor registers based on feature bits */
@@ -859,6 +888,31 @@ void register_cp_regs_for_features(ARMCPU *cpu)
     if (arm_feature(env, ARM_FEATURE_DUMMY_C15_REGS)) {
         define_arm_cp_regs(cpu, dummy_c15_cp_reginfo);
     }
+    if (arm_feature(env, ARM_FEATURE_AUXCR)) {
+        ARMCPRegInfo auxcr = {
+            .name = "AUXCR", .cp = 15, .crn = 1, .crm = 0, .opc1 = 0, .opc2 = 1,
+            .access = PL1_RW, .type = ARM_CP_CONST,
+            .resetvalue = cpu->reset_auxcr
+        };
+        define_one_arm_cp_reg(cpu, &auxcr);
+    }
+
+    /* Generic registers whose values depend on the implementation */
+    {
+        ARMCPRegInfo sctlr = {
+            .name = "SCTLR", .cp = 15, .crn = 1, .crm = 0, .opc1 = 0, .opc2 = 0,
+            .access = PL1_RW, .fieldoffset = offsetof(CPUARMState, cp15.c1_sys),
+            .writefn = sctlr_write, .resetvalue = cpu->reset_sctlr
+        };
+        if (arm_feature(env, ARM_FEATURE_XSCALE)) {
+            /* Normally we would always end the TB on an SCTLR write, but Linux
+             * arch/arm/mach-pxa/sleep.S expects two instructions following
+             * an MMU enable to execute from cache.  Imitate this behaviour.
+             */
+            sctlr.type |= ARM_CP_SUPPRESS_TB_END;
+        }
+        define_one_arm_cp_reg(cpu, &sctlr);
+    }
 }
 
 ARMCPU *cpu_arm_init(const char *cpu_model)
@@ -1949,42 +2003,6 @@ void HELPER(set_cp15)(CPUARMState *env, uint32_t insn, uint32_t val)
             break;
         }
         goto bad_reg;
-    case 1: /* System configuration.  */
-        if (arm_feature(env, ARM_FEATURE_V7)
-                && op1 == 0 && crm == 1 && op2 == 0) {
-            env->cp15.c1_scr = val;
-            break;
-        }
-        if (arm_feature(env, ARM_FEATURE_OMAPCP))
-            op2 = 0;
-        switch (op2) {
-        case 0:
-            if (!arm_feature(env, ARM_FEATURE_XSCALE) || crm == 0)
-                env->cp15.c1_sys = val;
-            /* ??? Lots of these bits are not implemented.  */
-            /* This may enable/disable the MMU, so do a TLB flush.  */
-            tlb_flush(env, 1);
-            break;
-        case 1: /* Auxiliary control register.  */
-            if (arm_feature(env, ARM_FEATURE_XSCALE)) {
-                env->cp15.c1_xscaleauxcr = val;
-                break;
-            }
-            /* Not implemented.  */
-            break;
-        case 2:
-            if (arm_feature(env, ARM_FEATURE_XSCALE))
-                goto bad_reg;
-            if (env->cp15.c1_coproc != val) {
-                env->cp15.c1_coproc = val;
-                /* ??? Is this safe when called from within a TB?  */
-                tb_flush(env);
-            }
-            break;
-        default:
-            goto bad_reg;
-        }
-        break;
     case 4: /* Reserved.  */
         goto bad_reg;
     case 12: /* Reserved.  */
@@ -2085,45 +2103,6 @@ uint32_t HELPER(get_cp15)(CPUARMState *env, uint32_t insn)
         default:
             goto bad_reg;
         }
-    case 1: /* System configuration.  */
-        if (arm_feature(env, ARM_FEATURE_V7)
-            && op1 == 0 && crm == 1 && op2 == 0) {
-            return env->cp15.c1_scr;
-        }
-        if (arm_feature(env, ARM_FEATURE_OMAPCP))
-            op2 = 0;
-        switch (op2) {
-        case 0: /* Control register.  */
-            return env->cp15.c1_sys;
-        case 1: /* Auxiliary control register.  */
-            if (arm_feature(env, ARM_FEATURE_XSCALE))
-                return env->cp15.c1_xscaleauxcr;
-            if (!arm_feature(env, ARM_FEATURE_AUXCR))
-                goto bad_reg;
-            switch (ARM_CPUID(env)) {
-            case ARM_CPUID_ARM1026:
-                return 1;
-            case ARM_CPUID_ARM1136:
-            case ARM_CPUID_ARM1136_R2:
-            case ARM_CPUID_ARM1176:
-                return 7;
-            case ARM_CPUID_ARM11MPCORE:
-                return 1;
-            case ARM_CPUID_CORTEXA8:
-                return 2;
-            case ARM_CPUID_CORTEXA9:
-            case ARM_CPUID_CORTEXA15:
-                return 0;
-            default:
-                goto bad_reg;
-            }
-        case 2: /* Coprocessor access register.  */
-            if (arm_feature(env, ARM_FEATURE_XSCALE))
-                goto bad_reg;
-            return env->cp15.c1_coproc;
-        default:
-            goto bad_reg;
-        }
     case 4: /* Reserved.  */
         goto bad_reg;
     case 11: /* TCM DMA control.  */
commit 34f9052967b2495c524560906023dbebf6556b5d
Author: Peter Maydell <peter.maydell at linaro.org>
Date:   Wed Jun 20 11:57:18 2012 +0000

    target-arm: Convert cp15 crn=9 registers
    
    Convert cp15 crn=9 registers (mostly cache lockdown) to the new scheme.
    
    Note that this change makes OMAPCP cores RAZ/WI the whole c9 space.  This is
    a change from previous behaviour, but a return to the behaviour of commit
    c3d2689d when OMAP1 support was first added -- subsequent commits have
    clearly accidentally relegated the OMAPCP RAZ condition to only a subset of
    the crn=9 space when adding support for other cores.
    
    Signed-off-by: Peter Maydell <peter.maydell at linaro.org>

diff --git a/target-arm/cpu.c b/target-arm/cpu.c
index f37380f..c03db20 100644
--- a/target-arm/cpu.c
+++ b/target-arm/cpu.c
@@ -23,6 +23,7 @@
 #if !defined(CONFIG_USER_ONLY)
 #include "hw/loader.h"
 #endif
+#include "sysemu.h"
 
 static void cp_reg_reset(gpointer key, gpointer value, gpointer opaque)
 {
@@ -390,6 +391,14 @@ static void cortex_m3_initfn(Object *obj)
     cpu->midr = ARM_CPUID_CORTEXM3;
 }
 
+static const ARMCPRegInfo cortexa8_cp_reginfo[] = {
+    { .name = "L2LOCKDOWN", .cp = 15, .crn = 9, .crm = 0, .opc1 = 1, .opc2 = 0,
+      .access = PL1_RW, .type = ARM_CP_CONST, .resetvalue = 0 },
+    { .name = "L2AUXCR", .cp = 15, .crn = 9, .crm = 0, .opc1 = 1, .opc2 = 2,
+      .access = PL1_RW, .type = ARM_CP_CONST, .resetvalue = 0 },
+    REGINFO_SENTINEL
+};
+
 static void cortex_a8_initfn(Object *obj)
 {
     ARMCPU *cpu = ARM_CPU(obj);
@@ -421,6 +430,7 @@ static void cortex_a8_initfn(Object *obj)
     cpu->ccsidr[0] = 0xe007e01a; /* 16k L1 dcache. */
     cpu->ccsidr[1] = 0x2007e01a; /* 16k L1 icache. */
     cpu->ccsidr[2] = 0xf0000000; /* No L2 icache. */
+    define_arm_cp_regs(cpu, cortexa8_cp_reginfo);
 }
 
 static const ARMCPRegInfo cortexa9_cp_reginfo[] = {
@@ -498,6 +508,29 @@ static void cortex_a9_initfn(Object *obj)
     }
 }
 
+#ifndef CONFIG_USER_ONLY
+static int a15_l2ctlr_read(CPUARMState *env, const ARMCPRegInfo *ri,
+                           uint64_t *value)
+{
+    /* Linux wants the number of processors from here.
+     * Might as well set the interrupt-controller bit too.
+     */
+    *value = ((smp_cpus - 1) << 24) | (1 << 23);
+    return 0;
+}
+#endif
+
+static const ARMCPRegInfo cortexa15_cp_reginfo[] = {
+#ifndef CONFIG_USER_ONLY
+    { .name = "L2CTLR", .cp = 15, .crn = 9, .crm = 0, .opc1 = 1, .opc2 = 2,
+      .access = PL1_RW, .resetvalue = 0, .readfn = a15_l2ctlr_read,
+      .writefn = arm_cp_write_ignore, },
+#endif
+    { .name = "L2ECTLR", .cp = 15, .crn = 9, .crm = 0, .opc1 = 1, .opc2 = 3,
+      .access = PL1_RW, .type = ARM_CP_CONST, .resetvalue = 0 },
+    REGINFO_SENTINEL
+};
+
 static void cortex_a15_initfn(Object *obj)
 {
     ARMCPU *cpu = ARM_CPU(obj);
@@ -533,6 +566,7 @@ static void cortex_a15_initfn(Object *obj)
     cpu->ccsidr[0] = 0x701fe00a; /* 32K L1 dcache */
     cpu->ccsidr[1] = 0x201fe00a; /* 32K L1 icache */
     cpu->ccsidr[2] = 0x711fe07a; /* 4096K L2 unified cache */
+    define_arm_cp_regs(cpu, cortexa15_cp_reginfo);
 }
 
 static void ti925t_initfn(Object *obj)
diff --git a/target-arm/helper.c b/target-arm/helper.c
index 5b77453..2c6e7ed 100644
--- a/target-arm/helper.c
+++ b/target-arm/helper.c
@@ -183,6 +183,16 @@ static const ARMCPRegInfo not_v7_cp_reginfo[] = {
      */
     { .name = "WFI_v6", .cp = 15, .crn = 7, .crm = 0, .opc1 = 0, .opc2 = 4,
       .access = PL1_W, .type = ARM_CP_WFI },
+    /* L1 cache lockdown. Not architectural in v6 and earlier but in practice
+     * implemented in 926, 946, 1026, 1136, 1176 and 11MPCore. StrongARM and
+     * OMAPCP will override this space.
+     */
+    { .name = "DLOCKDOWN", .cp = 15, .crn = 9, .crm = 0, .opc1 = 0, .opc2 = 0,
+      .access = PL1_RW, .fieldoffset = offsetof(CPUARMState, cp15.c9_data),
+      .resetvalue = 0 },
+    { .name = "ILOCKDOWN", .cp = 15, .crn = 9, .crm = 0, .opc1 = 0, .opc2 = 1,
+      .access = PL1_RW, .fieldoffset = offsetof(CPUARMState, cp15.c9_insn),
+      .resetvalue = 0 },
     REGINFO_SENTINEL
 };
 
@@ -703,6 +713,9 @@ static const ARMCPRegInfo omap_cp_reginfo[] = {
     { .name = "OMAP_CACHEMAINT", .cp = 15, .crn = 7, .crm = CP_ANY,
       .opc1 = 0, .opc2 = CP_ANY, .access = PL1_W, .type = ARM_CP_OVERRIDE,
       .writefn = omap_cachemaint_write },
+    { .name = "C9", .cp = 15, .crn = 9,
+      .crm = CP_ANY, .opc1 = CP_ANY, .opc2 = CP_ANY, .access = PL1_RW,
+      .type = ARM_CP_CONST | ARM_CP_OVERRIDE, .resetvalue = 0 },
     REGINFO_SENTINEL
 };
 
@@ -763,6 +776,15 @@ static const ARMCPRegInfo cache_test_clean_cp_reginfo[] = {
     REGINFO_SENTINEL
 };
 
+static const ARMCPRegInfo strongarm_cp_reginfo[] = {
+    /* Ignore ReadBuffer accesses */
+    { .name = "C9_READBUFFER", .cp = 15, .crn = 9,
+      .crm = CP_ANY, .opc1 = CP_ANY, .opc2 = CP_ANY,
+      .access = PL1_RW, .type = ARM_CP_CONST | ARM_CP_OVERRIDE,
+      .resetvalue = 0 },
+    REGINFO_SENTINEL
+};
+
 void register_cp_regs_for_features(ARMCPU *cpu)
 {
     /* Register all the coprocessor registers based on feature bits */
@@ -828,6 +850,9 @@ void register_cp_regs_for_features(ARMCPU *cpu)
     if (arm_feature(env, ARM_FEATURE_OMAPCP)) {
         define_arm_cp_regs(cpu, omap_cp_reginfo);
     }
+    if (arm_feature(env, ARM_FEATURE_STRONGARM)) {
+        define_arm_cp_regs(cpu, strongarm_cp_reginfo);
+    }
     if (arm_feature(env, ARM_FEATURE_XSCALE)) {
         define_arm_cp_regs(cpu, xscale_cp_reginfo);
     }
@@ -1962,40 +1987,6 @@ void HELPER(set_cp15)(CPUARMState *env, uint32_t insn, uint32_t val)
         break;
     case 4: /* Reserved.  */
         goto bad_reg;
-    case 9:
-        if (arm_feature(env, ARM_FEATURE_OMAPCP))
-            break;
-        if (arm_feature(env, ARM_FEATURE_STRONGARM))
-            break; /* Ignore ReadBuffer access */
-        switch (crm) {
-        case 0: /* Cache lockdown.  */
-	    switch (op1) {
-	    case 0: /* L1 cache.  */
-		switch (op2) {
-		case 0:
-		    env->cp15.c9_data = val;
-		    break;
-		case 1:
-		    env->cp15.c9_insn = val;
-		    break;
-		default:
-		    goto bad_reg;
-		}
-		break;
-	    case 1: /* L2 cache.  */
-		/* Ignore writes to L2 lockdown/auxiliary registers.  */
-		break;
-	    default:
-		goto bad_reg;
-	    }
-	    break;
-        case 1: /* TCM memory region registers.  */
-            /* Not implemented.  */
-            goto bad_reg;
-        default:
-            goto bad_reg;
-        }
-        break;
     case 12: /* Reserved.  */
         goto bad_reg;
     }
@@ -2135,51 +2126,6 @@ uint32_t HELPER(get_cp15)(CPUARMState *env, uint32_t insn)
         }
     case 4: /* Reserved.  */
         goto bad_reg;
-    case 9:
-        switch (crm) {
-        case 0: /* Cache lockdown */
-            switch (op1) {
-            case 0: /* L1 cache.  */
-                if (arm_feature(env, ARM_FEATURE_OMAPCP)) {
-                    return 0;
-                }
-                switch (op2) {
-                case 0:
-                    return env->cp15.c9_data;
-                case 1:
-                    return env->cp15.c9_insn;
-                default:
-                    goto bad_reg;
-                }
-            case 1: /* L2 cache */
-                /* L2 Lockdown and Auxiliary control.  */
-                switch (op2) {
-                case 0:
-                    /* L2 cache lockdown (A8 only) */
-                    return 0;
-                case 2:
-                    /* L2 cache auxiliary control (A8) or control (A15) */
-                    if (ARM_CPUID(env) == ARM_CPUID_CORTEXA15) {
-                        /* Linux wants the number of processors from here.
-                         * Might as well set the interrupt-controller bit too.
-                         */
-                        return ((smp_cpus - 1) << 24) | (1 << 23);
-                    }
-                    return 0;
-                case 3:
-                    /* L2 cache extended control (A15) */
-                    return 0;
-                default:
-                    goto bad_reg;
-                }
-            default:
-                goto bad_reg;
-            }
-            break;
-        default:
-            goto bad_reg;
-        }
-        break;
     case 11: /* TCM DMA control.  */
     case 12: /* Reserved.  */
         goto bad_reg;
commit 06d76f319f2ea1cf8a66392670a04f649d6280ce
Author: Peter Maydell <peter.maydell at linaro.org>
Date:   Wed Jun 20 11:57:17 2012 +0000

    target-arm: Convert cp15 crn=6 registers
    
    Convert the cp15 crn=6 registers to the new scheme.
    Note that this includes some minor tidyup: drop an unnecessary
    underdecoding of op2 on OMAPCP cores, and only implement the
    pre-v6 c6,c0,0,1 IFAR on the 1026 and not on the other ARMv5
    cores, which didn't have it.
    
    Signed-off-by: Peter Maydell <peter.maydell at linaro.org>

diff --git a/target-arm/cpu.c b/target-arm/cpu.c
index f8534a7..f37380f 100644
--- a/target-arm/cpu.c
+++ b/target-arm/cpu.c
@@ -251,6 +251,16 @@ static void arm1026_initfn(Object *obj)
     cpu->reset_fpsid = 0x410110a0;
     cpu->ctr = 0x1dd20d2;
     cpu->reset_sctlr = 0x00090078;
+    {
+        /* The 1026 had an IFAR at c6,c0,0,1 rather than the ARMv6 c6,c0,0,2 */
+        ARMCPRegInfo ifar = {
+            .name = "IFAR", .cp = 15, .crn = 6, .crm = 0, .opc1 = 0, .opc2 = 1,
+            .access = PL1_RW,
+            .fieldoffset = offsetof(CPUARMState, cp15.c6_insn),
+            .resetvalue = 0
+        };
+        define_one_arm_cp_reg(cpu, &ifar);
+    }
 }
 
 static void arm1136_r2_initfn(Object *obj)
diff --git a/target-arm/helper.c b/target-arm/helper.c
index 907ccbf..5b77453 100644
--- a/target-arm/helper.c
+++ b/target-arm/helper.c
@@ -197,6 +197,14 @@ static const ARMCPRegInfo v6_cp_reginfo[] = {
       .access = PL0_W, .type = ARM_CP_NOP },
     { .name = "ISB", .cp = 15, .crn = 7, .crm = 10, .opc1 = 0, .opc2 = 5,
       .access = PL0_W, .type = ARM_CP_NOP },
+    { .name = "IFAR", .cp = 15, .crn = 6, .crm = 0, .opc1 = 0, .opc2 = 2,
+      .access = PL1_RW, .fieldoffset = offsetof(CPUARMState, cp15.c6_insn),
+      .resetvalue = 0, },
+    /* Watchpoint Fault Address Register : should actually only be present
+     * for 1136, 1176, 11MPCore.
+     */
+    { .name = "WFAR", .cp = 15, .crn = 6, .crm = 0, .opc1 = 0, .opc2 = 1,
+      .access = PL1_RW, .type = ARM_CP_CONST, .resetvalue = 0, },
     REGINFO_SENTINEL
 };
 
@@ -540,6 +548,26 @@ static int pmsav5_insn_ap_read(CPUARMState *env, const ARMCPRegInfo *ri,
     return 0;
 }
 
+static int arm946_prbs_read(CPUARMState *env, const ARMCPRegInfo *ri,
+                            uint64_t *value)
+{
+    if (ri->crm > 8) {
+        return EXCP_UDEF;
+    }
+    *value = env->cp15.c6_region[ri->crm];
+    return 0;
+}
+
+static int arm946_prbs_write(CPUARMState *env, const ARMCPRegInfo *ri,
+                             uint64_t value)
+{
+    if (ri->crm > 8) {
+        return EXCP_UDEF;
+    }
+    env->cp15.c6_region[ri->crm] = value;
+    return 0;
+}
+
 static const ARMCPRegInfo pmsav5_cp_reginfo[] = {
     { .name = "DATA_AP", .cp = 15, .crn = 5, .crm = 0, .opc1 = 0, .opc2 = 0,
       .access = PL1_RW,
@@ -561,6 +589,10 @@ static const ARMCPRegInfo pmsav5_cp_reginfo[] = {
     { .name = "ICACHE_CFG", .cp = 15, .crn = 2, .crm = 0, .opc1 = 0, .opc2 = 1,
       .access = PL1_RW,
       .fieldoffset = offsetof(CPUARMState, cp15.c2_insn), .resetvalue = 0, },
+    /* Protection region base and size registers */
+    { .name = "946_PRBS", .cp = 15, .crn = 6, .crm = CP_ANY, .opc1 = 0,
+      .opc2 = CP_ANY, .access = PL1_RW,
+      .readfn = arm946_prbs_read, .writefn = arm946_prbs_write, },
     REGINFO_SENTINEL
 };
 
@@ -598,6 +630,9 @@ static const ARMCPRegInfo vmsa_cp_reginfo[] = {
       .access = PL1_RW, .writefn = vmsa_ttbcr_write,
       .resetfn = vmsa_ttbcr_reset,
       .fieldoffset = offsetof(CPUARMState, cp15.c2_control) },
+    { .name = "DFAR", .cp = 15, .crn = 6, .crm = 0, .opc1 = 0, .opc2 = 0,
+      .access = PL1_RW, .fieldoffset = offsetof(CPUARMState, cp15.c6_data),
+      .resetvalue = 0, },
     REGINFO_SENTINEL
 };
 
@@ -1927,27 +1962,6 @@ void HELPER(set_cp15)(CPUARMState *env, uint32_t insn, uint32_t val)
         break;
     case 4: /* Reserved.  */
         goto bad_reg;
-    case 6: /* MMU Fault address / MPU base/size.  */
-        if (arm_feature(env, ARM_FEATURE_MPU)) {
-            if (crm >= 8)
-                goto bad_reg;
-            env->cp15.c6_region[crm] = val;
-        } else {
-            if (arm_feature(env, ARM_FEATURE_OMAPCP))
-                op2 = 0;
-            switch (op2) {
-            case 0:
-                env->cp15.c6_data = val;
-                break;
-            case 1: /* ??? This is WFAR on armv6 */
-            case 2:
-                env->cp15.c6_insn = val;
-                break;
-            default:
-                goto bad_reg;
-            }
-        }
-        break;
     case 9:
         if (arm_feature(env, ARM_FEATURE_OMAPCP))
             break;
@@ -2121,38 +2135,6 @@ uint32_t HELPER(get_cp15)(CPUARMState *env, uint32_t insn)
         }
     case 4: /* Reserved.  */
         goto bad_reg;
-    case 6: /* MMU Fault address.  */
-        if (arm_feature(env, ARM_FEATURE_MPU)) {
-            if (crm >= 8)
-                goto bad_reg;
-            return env->cp15.c6_region[crm];
-        } else {
-            if (arm_feature(env, ARM_FEATURE_OMAPCP))
-                op2 = 0;
-	    switch (op2) {
-	    case 0:
-		return env->cp15.c6_data;
-	    case 1:
-		if (arm_feature(env, ARM_FEATURE_V6)) {
-		    /* Watchpoint Fault Adrress.  */
-		    return 0; /* Not implemented.  */
-		} else {
-		    /* Instruction Fault Adrress.  */
-		    /* Arm9 doesn't have an IFAR, but implementing it anyway
-		       shouldn't do any harm.  */
-		    return env->cp15.c6_insn;
-		}
-	    case 2:
-		if (arm_feature(env, ARM_FEATURE_V6)) {
-		    /* Instruction Fault Adrress.  */
-		    return env->cp15.c6_insn;
-		} else {
-		    goto bad_reg;
-		}
-	    default:
-		goto bad_reg;
-	    }
-        }
     case 9:
         switch (crm) {
         case 0: /* Cache lockdown */
commit c480421426c984068a27502c2948d2fa51b8cf96
Author: Peter Maydell <peter.maydell at linaro.org>
Date:   Wed Jun 20 11:57:17 2012 +0000

    target-arm: convert cp15 crn=7 registers
    
    Convert the cp15 crn=7 registers to the new scheme.
    Note that to do this we have to distinguish some registers
    used on the ARM9 and ARM10 from some which are ARM1176
    only. This is because the old code returned a value of 0
    but always set the Z flag (by clearing env->ZF, since we
    store the Z flag in CPUState inverted). This is inconsistent
    with actual ARM CPU behaviour, which only sets flags for
    reads to r15 and sets them based on the top bits of the result.
    However it happened to work for the two common use cases for
    cp15 crn=7 reads:
     * On ARM9 and ARM10 the cache clean-and-test operations are
    typically done with a destination of r15 so that you can do
    a "loop: mrc ... ; bne loop" to keep cleaning until the cache
    is finally clean; always setting the Z flag means this loop
    terminates immediately
     * on ARM1176 the Cache Dirty Status Register reads as zero
    if the cache is dirty; returning 0 means this is correctly
    implemented for QEMU
    
    Since the new coprocessor register framework does the right
    thing of always setting flags based on the returned result
    for reads to r15, we need to split these up so that we can
    return (1<<30) for the ARM9/ARM10 registers but 0 for the
    ARM1176 one.
    
    This allows us to remove the nasty hack which always sets Z.
    
    Signed-off-by: Peter Maydell <peter.maydell at linaro.org>

diff --git a/target-arm/cpu.c b/target-arm/cpu.c
index 6190091..f8534a7 100644
--- a/target-arm/cpu.c
+++ b/target-arm/cpu.c
@@ -220,6 +220,8 @@ static void arm926_initfn(Object *obj)
     ARMCPU *cpu = ARM_CPU(obj);
     set_feature(&cpu->env, ARM_FEATURE_V5);
     set_feature(&cpu->env, ARM_FEATURE_VFP);
+    set_feature(&cpu->env, ARM_FEATURE_DUMMY_C15_REGS);
+    set_feature(&cpu->env, ARM_FEATURE_CACHE_TEST_CLEAN);
     cpu->midr = ARM_CPUID_ARM926;
     cpu->reset_fpsid = 0x41011090;
     cpu->ctr = 0x1dd20d2;
@@ -231,6 +233,7 @@ static void arm946_initfn(Object *obj)
     ARMCPU *cpu = ARM_CPU(obj);
     set_feature(&cpu->env, ARM_FEATURE_V5);
     set_feature(&cpu->env, ARM_FEATURE_MPU);
+    set_feature(&cpu->env, ARM_FEATURE_DUMMY_C15_REGS);
     cpu->midr = ARM_CPUID_ARM946;
     cpu->ctr = 0x0f004006;
     cpu->reset_sctlr = 0x00000078;
@@ -242,6 +245,8 @@ static void arm1026_initfn(Object *obj)
     set_feature(&cpu->env, ARM_FEATURE_V5);
     set_feature(&cpu->env, ARM_FEATURE_VFP);
     set_feature(&cpu->env, ARM_FEATURE_AUXCR);
+    set_feature(&cpu->env, ARM_FEATURE_DUMMY_C15_REGS);
+    set_feature(&cpu->env, ARM_FEATURE_CACHE_TEST_CLEAN);
     cpu->midr = ARM_CPUID_ARM1026;
     cpu->reset_fpsid = 0x410110a0;
     cpu->ctr = 0x1dd20d2;
@@ -260,6 +265,9 @@ static void arm1136_r2_initfn(Object *obj)
      */
     set_feature(&cpu->env, ARM_FEATURE_V6);
     set_feature(&cpu->env, ARM_FEATURE_VFP);
+    set_feature(&cpu->env, ARM_FEATURE_DUMMY_C15_REGS);
+    set_feature(&cpu->env, ARM_FEATURE_CACHE_DIRTY_REG);
+    set_feature(&cpu->env, ARM_FEATURE_CACHE_BLOCK_OPS);
     cpu->midr = ARM_CPUID_ARM1136_R2;
     cpu->reset_fpsid = 0x410120b4;
     cpu->mvfr0 = 0x11111111;
@@ -286,6 +294,9 @@ static void arm1136_initfn(Object *obj)
     set_feature(&cpu->env, ARM_FEATURE_V6K);
     set_feature(&cpu->env, ARM_FEATURE_V6);
     set_feature(&cpu->env, ARM_FEATURE_VFP);
+    set_feature(&cpu->env, ARM_FEATURE_DUMMY_C15_REGS);
+    set_feature(&cpu->env, ARM_FEATURE_CACHE_DIRTY_REG);
+    set_feature(&cpu->env, ARM_FEATURE_CACHE_BLOCK_OPS);
     cpu->midr = ARM_CPUID_ARM1136;
     cpu->reset_fpsid = 0x410120b4;
     cpu->mvfr0 = 0x11111111;
@@ -312,6 +323,9 @@ static void arm1176_initfn(Object *obj)
     set_feature(&cpu->env, ARM_FEATURE_V6K);
     set_feature(&cpu->env, ARM_FEATURE_VFP);
     set_feature(&cpu->env, ARM_FEATURE_VAPA);
+    set_feature(&cpu->env, ARM_FEATURE_DUMMY_C15_REGS);
+    set_feature(&cpu->env, ARM_FEATURE_CACHE_DIRTY_REG);
+    set_feature(&cpu->env, ARM_FEATURE_CACHE_BLOCK_OPS);
     cpu->midr = ARM_CPUID_ARM1176;
     cpu->reset_fpsid = 0x410120b5;
     cpu->mvfr0 = 0x11111111;
@@ -338,6 +352,7 @@ static void arm11mpcore_initfn(Object *obj)
     set_feature(&cpu->env, ARM_FEATURE_V6K);
     set_feature(&cpu->env, ARM_FEATURE_VFP);
     set_feature(&cpu->env, ARM_FEATURE_VAPA);
+    set_feature(&cpu->env, ARM_FEATURE_DUMMY_C15_REGS);
     cpu->midr = ARM_CPUID_ARM11MPCORE;
     cpu->reset_fpsid = 0x410120b4;
     cpu->mvfr0 = 0x11111111;
@@ -372,6 +387,7 @@ static void cortex_a8_initfn(Object *obj)
     set_feature(&cpu->env, ARM_FEATURE_VFP3);
     set_feature(&cpu->env, ARM_FEATURE_NEON);
     set_feature(&cpu->env, ARM_FEATURE_THUMB2EE);
+    set_feature(&cpu->env, ARM_FEATURE_DUMMY_C15_REGS);
     cpu->midr = ARM_CPUID_CORTEXA8;
     cpu->reset_fpsid = 0x410330c0;
     cpu->mvfr0 = 0x11110222;
@@ -483,6 +499,7 @@ static void cortex_a15_initfn(Object *obj)
     set_feature(&cpu->env, ARM_FEATURE_ARM_DIV);
     set_feature(&cpu->env, ARM_FEATURE_V7MP);
     set_feature(&cpu->env, ARM_FEATURE_GENERIC_TIMER);
+    set_feature(&cpu->env, ARM_FEATURE_DUMMY_C15_REGS);
     cpu->midr = ARM_CPUID_CORTEXA15;
     cpu->reset_fpsid = 0x410430f0;
     cpu->mvfr0 = 0x10110222;
@@ -522,6 +539,7 @@ static void sa1100_initfn(Object *obj)
 {
     ARMCPU *cpu = ARM_CPU(obj);
     set_feature(&cpu->env, ARM_FEATURE_STRONGARM);
+    set_feature(&cpu->env, ARM_FEATURE_DUMMY_C15_REGS);
     cpu->midr = ARM_CPUID_SA1100;
     cpu->reset_sctlr = 0x00000070;
 }
@@ -530,6 +548,7 @@ static void sa1110_initfn(Object *obj)
 {
     ARMCPU *cpu = ARM_CPU(obj);
     set_feature(&cpu->env, ARM_FEATURE_STRONGARM);
+    set_feature(&cpu->env, ARM_FEATURE_DUMMY_C15_REGS);
     cpu->midr = ARM_CPUID_SA1110;
     cpu->reset_sctlr = 0x00000070;
 }
diff --git a/target-arm/cpu.h b/target-arm/cpu.h
index b94503d..02d86ca 100644
--- a/target-arm/cpu.h
+++ b/target-arm/cpu.h
@@ -387,6 +387,9 @@ enum arm_features {
     ARM_FEATURE_GENERIC_TIMER,
     ARM_FEATURE_MVFR, /* Media and VFP Feature Registers 0 and 1 */
     ARM_FEATURE_DUMMY_C15_REGS, /* RAZ/WI all of cp15 crn=15 */
+    ARM_FEATURE_CACHE_TEST_CLEAN, /* 926/1026 style test-and-clean ops */
+    ARM_FEATURE_CACHE_DIRTY_REG, /* 1136/1176 cache dirty status register */
+    ARM_FEATURE_CACHE_BLOCK_OPS, /* v6 optional cache block operations */
 };
 
 static inline int arm_feature(CPUARMState *env, int feature)
diff --git a/target-arm/helper.c b/target-arm/helper.c
index b7fc2db..907ccbf 100644
--- a/target-arm/helper.c
+++ b/target-arm/helper.c
@@ -161,6 +161,10 @@ static const ARMCPRegInfo cp_reginfo[] = {
       .opc1 = CP_ANY, .opc2 = 2, .access = PL1_W, .writefn = tlbiasid_write, },
     { .name = "TLBIMVAA", .cp = 15, .crn = 8, .crm = CP_ANY,
       .opc1 = CP_ANY, .opc2 = 3, .access = PL1_W, .writefn = tlbimvaa_write, },
+    /* Cache maintenance ops; some of this space may be overridden later. */
+    { .name = "CACHEMAINT", .cp = 15, .crn = 7, .crm = CP_ANY,
+      .opc1 = 0, .opc2 = CP_ANY, .access = PL1_W,
+      .type = ARM_CP_NOP | ARM_CP_OVERRIDE },
     REGINFO_SENTINEL
 };
 
@@ -622,6 +626,17 @@ static int omap_wfi_write(CPUARMState *env, const ARMCPRegInfo *ri,
     return 0;
 }
 
+static int omap_cachemaint_write(CPUARMState *env, const ARMCPRegInfo *ri,
+                                 uint64_t value)
+{
+    /* On OMAP there are registers indicating the max/min index of dcache lines
+     * containing a dirty line; cache flush operations have to reset these.
+     */
+    env->cp15.c15_i_max = 0x000;
+    env->cp15.c15_i_min = 0xff0;
+    return 0;
+}
+
 static const ARMCPRegInfo omap_cp_reginfo[] = {
     { .name = "DFSR", .cp = 15, .crn = 5, .crm = CP_ANY,
       .opc1 = CP_ANY, .opc2 = CP_ANY, .access = PL1_RW, .type = ARM_CP_OVERRIDE,
@@ -650,6 +665,9 @@ static const ARMCPRegInfo omap_cp_reginfo[] = {
      * base address at $rn & ~0xfff and map size of 0x200 << ($rn & 0xfff),
      * when MMU is off.
      */
+    { .name = "OMAP_CACHEMAINT", .cp = 15, .crn = 7, .crm = CP_ANY,
+      .opc1 = 0, .opc2 = CP_ANY, .access = PL1_W, .type = ARM_CP_OVERRIDE,
+      .writefn = omap_cachemaint_write },
     REGINFO_SENTINEL
 };
 
@@ -685,6 +703,31 @@ static const ARMCPRegInfo dummy_c15_cp_reginfo[] = {
     REGINFO_SENTINEL
 };
 
+static const ARMCPRegInfo cache_dirty_status_cp_reginfo[] = {
+    /* Cache status: RAZ because we have no cache so it's always clean */
+    { .name = "CDSR", .cp = 15, .crn = 7, .crm = 10, .opc1 = 0, .opc2 = 6,
+      .access = PL1_R, .type = ARM_CP_CONST, .resetvalue = 0 },
+    REGINFO_SENTINEL
+};
+
+static const ARMCPRegInfo cache_block_ops_cp_reginfo[] = {
+    /* We never have a a block transfer operation in progress */
+    { .name = "BXSR", .cp = 15, .crn = 7, .crm = 12, .opc1 = 0, .opc2 = 4,
+      .access = PL0_R, .type = ARM_CP_CONST, .resetvalue = 0 },
+    REGINFO_SENTINEL
+};
+
+static const ARMCPRegInfo cache_test_clean_cp_reginfo[] = {
+    /* The cache test-and-clean instructions always return (1 << 30)
+     * to indicate that there are no dirty cache lines.
+     */
+    { .name = "TC_DCACHE", .cp = 15, .crn = 7, .crm = 10, .opc1 = 0, .opc2 = 3,
+      .access = PL0_R, .type = ARM_CP_CONST, .resetvalue = (1 << 30) },
+    { .name = "TCI_DCACHE", .cp = 15, .crn = 7, .crm = 14, .opc1 = 0, .opc2 = 3,
+      .access = PL0_R, .type = ARM_CP_CONST, .resetvalue = (1 << 30) },
+    REGINFO_SENTINEL
+};
+
 void register_cp_regs_for_features(ARMCPU *cpu)
 {
     /* Register all the coprocessor registers based on feature bits */
@@ -738,6 +781,15 @@ void register_cp_regs_for_features(ARMCPU *cpu)
     if (arm_feature(env, ARM_FEATURE_VAPA)) {
         define_arm_cp_regs(cpu, vapa_cp_reginfo);
     }
+    if (arm_feature(env, ARM_FEATURE_CACHE_TEST_CLEAN)) {
+        define_arm_cp_regs(cpu, cache_test_clean_cp_reginfo);
+    }
+    if (arm_feature(env, ARM_FEATURE_CACHE_DIRTY_REG)) {
+        define_arm_cp_regs(cpu, cache_dirty_status_cp_reginfo);
+    }
+    if (arm_feature(env, ARM_FEATURE_CACHE_BLOCK_OPS)) {
+        define_arm_cp_regs(cpu, cache_block_ops_cp_reginfo);
+    }
     if (arm_feature(env, ARM_FEATURE_OMAPCP)) {
         define_arm_cp_regs(cpu, omap_cp_reginfo);
     }
@@ -1896,13 +1948,6 @@ void HELPER(set_cp15)(CPUARMState *env, uint32_t insn, uint32_t val)
             }
         }
         break;
-    case 7: /* Cache control.  */
-        env->cp15.c15_i_max = 0x000;
-        env->cp15.c15_i_min = 0xff0;
-        if (op1 != 0) {
-            goto bad_reg;
-        }
-        break;
     case 9:
         if (arm_feature(env, ARM_FEATURE_OMAPCP))
             break;
@@ -2108,10 +2153,6 @@ uint32_t HELPER(get_cp15)(CPUARMState *env, uint32_t insn)
 		goto bad_reg;
 	    }
         }
-    case 7: /* Cache control.  */
-        /* FIXME: Should only clear Z flag if destination is r15.  */
-        env->ZF = 0;
-        return 0;
     case 9:
         switch (crm) {
         case 0: /* Cache lockdown */
commit 4a501606662a07e7089d3e6f7021490d24b16cb1
Author: Peter Maydell <peter.maydell at linaro.org>
Date:   Wed Jun 20 11:57:16 2012 +0000

    target-arm: Convert cp15 VA-PA translation registers
    
    Convert the cp15 VA-PA translation registers (a subset of
    the crn=7 regs) to the new scheme.
    
    Signed-off-by: Peter Maydell <peter.maydell at linaro.org>

diff --git a/target-arm/helper.c b/target-arm/helper.c
index 8def356..b7fc2db 100644
--- a/target-arm/helper.c
+++ b/target-arm/helper.c
@@ -4,6 +4,13 @@
 #include "host-utils.h"
 #include "sysemu.h"
 
+#ifndef CONFIG_USER_ONLY
+static inline int get_phys_addr(CPUARMState *env, uint32_t address,
+                                int access_type, int is_user,
+                                uint32_t *phys_ptr, int *prot,
+                                target_ulong *page_size);
+#endif
+
 static int vfp_gdb_get_reg(CPUARMState *env, uint8_t *buf, int reg)
 {
     int nregs;
@@ -416,6 +423,61 @@ static const ARMCPRegInfo generic_timer_cp_reginfo[] = {
     REGINFO_SENTINEL
 };
 
+static int par_write(CPUARMState *env, const ARMCPRegInfo *ri, uint64_t value)
+{
+    if (arm_feature(env, ARM_FEATURE_V7)) {
+        env->cp15.c7_par = value & 0xfffff6ff;
+    } else {
+        env->cp15.c7_par = value & 0xfffff1ff;
+    }
+    return 0;
+}
+
+#ifndef CONFIG_USER_ONLY
+/* get_phys_addr() isn't present for user-mode-only targets */
+static int ats_write(CPUARMState *env, const ARMCPRegInfo *ri, uint64_t value)
+{
+    uint32_t phys_addr;
+    target_ulong page_size;
+    int prot;
+    int ret, is_user = ri->opc2 & 2;
+    int access_type = ri->opc2 & 1;
+
+    if (ri->opc2 & 4) {
+        /* Other states are only available with TrustZone */
+        return EXCP_UDEF;
+    }
+    ret = get_phys_addr(env, value, access_type, is_user,
+                        &phys_addr, &prot, &page_size);
+    if (ret == 0) {
+        /* We do not set any attribute bits in the PAR */
+        if (page_size == (1 << 24)
+            && arm_feature(env, ARM_FEATURE_V7)) {
+            env->cp15.c7_par = (phys_addr & 0xff000000) | 1 << 1;
+        } else {
+            env->cp15.c7_par = phys_addr & 0xfffff000;
+        }
+    } else {
+        env->cp15.c7_par = ((ret & (10 << 1)) >> 5) |
+            ((ret & (12 << 1)) >> 6) |
+            ((ret & 0xf) << 1) | 1;
+    }
+    return 0;
+}
+#endif
+
+static const ARMCPRegInfo vapa_cp_reginfo[] = {
+    { .name = "PAR", .cp = 15, .crn = 7, .crm = 4, .opc1 = 0, .opc2 = 0,
+      .access = PL1_RW, .resetvalue = 0,
+      .fieldoffset = offsetof(CPUARMState, cp15.c7_par),
+      .writefn = par_write },
+#ifndef CONFIG_USER_ONLY
+    { .name = "ATS", .cp = 15, .crn = 7, .crm = 8, .opc1 = 0, .opc2 = CP_ANY,
+      .access = PL1_W, .writefn = ats_write },
+#endif
+    REGINFO_SENTINEL
+};
+
 /* Return basic MPU access permission bits.  */
 static uint32_t simple_mpu_ap_bits(uint32_t val)
 {
@@ -673,6 +735,9 @@ void register_cp_regs_for_features(ARMCPU *cpu)
     if (arm_feature(env, ARM_FEATURE_GENERIC_TIMER)) {
         define_arm_cp_regs(cpu, generic_timer_cp_reginfo);
     }
+    if (arm_feature(env, ARM_FEATURE_VAPA)) {
+        define_arm_cp_regs(cpu, vapa_cp_reginfo);
+    }
     if (arm_feature(env, ARM_FEATURE_OMAPCP)) {
         define_arm_cp_regs(cpu, omap_cp_reginfo);
     }
@@ -1837,46 +1902,6 @@ void HELPER(set_cp15)(CPUARMState *env, uint32_t insn, uint32_t val)
         if (op1 != 0) {
             goto bad_reg;
         }
-        /* No cache, so nothing to do except VA->PA translations. */
-        if (arm_feature(env, ARM_FEATURE_VAPA)) {
-            switch (crm) {
-            case 4:
-                if (arm_feature(env, ARM_FEATURE_V7)) {
-                    env->cp15.c7_par = val & 0xfffff6ff;
-                } else {
-                    env->cp15.c7_par = val & 0xfffff1ff;
-                }
-                break;
-            case 8: {
-                uint32_t phys_addr;
-                target_ulong page_size;
-                int prot;
-                int ret, is_user = op2 & 2;
-                int access_type = op2 & 1;
-
-                if (op2 & 4) {
-                    /* Other states are only available with TrustZone */
-                    goto bad_reg;
-                }
-                ret = get_phys_addr(env, val, access_type, is_user,
-                                    &phys_addr, &prot, &page_size);
-                if (ret == 0) {
-                    /* We do not set any attribute bits in the PAR */
-                    if (page_size == (1 << 24)
-                        && arm_feature(env, ARM_FEATURE_V7)) {
-                        env->cp15.c7_par = (phys_addr & 0xff000000) | 1 << 1;
-                    } else {
-                        env->cp15.c7_par = phys_addr & 0xfffff000;
-                    }
-                } else {
-                    env->cp15.c7_par = ((ret & (10 << 1)) >> 5) |
-                                       ((ret & (12 << 1)) >> 6) |
-                                       ((ret & 0xf) << 1) | 1;
-                }
-                break;
-            }
-            }
-        }
         break;
     case 9:
         if (arm_feature(env, ARM_FEATURE_OMAPCP))
@@ -2084,9 +2109,6 @@ uint32_t HELPER(get_cp15)(CPUARMState *env, uint32_t insn)
 	    }
         }
     case 7: /* Cache control.  */
-        if (crm == 4 && op1 == 0 && op2 == 0) {
-            return env->cp15.c7_par;
-        }
         /* FIXME: Should only clear Z flag if destination is r15.  */
         env->ZF = 0;
         return 0;
commit d929823fa1e425054d45702aaea4b2c487d17eb1
Author: Peter Maydell <peter.maydell at linaro.org>
Date:   Wed Jun 20 11:57:16 2012 +0000

    target-arm: Convert cp15 MMU TLB control
    
    Convert cp15 MMU TLB control (crn=8) to new scheme.
    
    Signed-off-by: Peter Maydell <peter.maydell at linaro.org>

diff --git a/target-arm/helper.c b/target-arm/helper.c
index 0d7200f..8def356 100644
--- a/target-arm/helper.c
+++ b/target-arm/helper.c
@@ -88,6 +88,38 @@ static int contextidr_write(CPUARMState *env, const ARMCPRegInfo *ri,
     return 0;
 }
 
+static int tlbiall_write(CPUARMState *env, const ARMCPRegInfo *ri,
+                         uint64_t value)
+{
+    /* Invalidate all (TLBIALL) */
+    tlb_flush(env, 1);
+    return 0;
+}
+
+static int tlbimva_write(CPUARMState *env, const ARMCPRegInfo *ri,
+                         uint64_t value)
+{
+    /* Invalidate single TLB entry by MVA and ASID (TLBIMVA) */
+    tlb_flush_page(env, value & TARGET_PAGE_MASK);
+    return 0;
+}
+
+static int tlbiasid_write(CPUARMState *env, const ARMCPRegInfo *ri,
+                          uint64_t value)
+{
+    /* Invalidate by ASID (TLBIASID) */
+    tlb_flush(env, value == 0);
+    return 0;
+}
+
+static int tlbimvaa_write(CPUARMState *env, const ARMCPRegInfo *ri,
+                          uint64_t value)
+{
+    /* Invalidate single entry by MVA, all ASIDs (TLBIMVAA) */
+    tlb_flush_page(env, value & TARGET_PAGE_MASK);
+    return 0;
+}
+
 static const ARMCPRegInfo cp_reginfo[] = {
     /* DBGDIDR: just RAZ. In particular this means the "debug architecture
      * version" bits will read as a reserved value, which should cause
@@ -111,6 +143,17 @@ static const ARMCPRegInfo cp_reginfo[] = {
      */
     { .name = "TLB_LOCKDOWN", .cp = 15, .crn = 10, .crm = CP_ANY,
       .opc1 = CP_ANY, .opc2 = CP_ANY, .access = PL1_RW, .type = ARM_CP_NOP },
+    /* MMU TLB control. Note that the wildcarding means we cover not just
+     * the unified TLB ops but also the dside/iside/inner-shareable variants.
+     */
+    { .name = "TLBIALL", .cp = 15, .crn = 8, .crm = CP_ANY,
+      .opc1 = CP_ANY, .opc2 = 0, .access = PL1_W, .writefn = tlbiall_write, },
+    { .name = "TLBIMVA", .cp = 15, .crn = 8, .crm = CP_ANY,
+      .opc1 = CP_ANY, .opc2 = 1, .access = PL1_W, .writefn = tlbimva_write, },
+    { .name = "TLBIASID", .cp = 15, .crn = 8, .crm = CP_ANY,
+      .opc1 = CP_ANY, .opc2 = 2, .access = PL1_W, .writefn = tlbiasid_write, },
+    { .name = "TLBIMVAA", .cp = 15, .crn = 8, .crm = CP_ANY,
+      .opc1 = CP_ANY, .opc2 = 3, .access = PL1_W, .writefn = tlbimvaa_write, },
     REGINFO_SENTINEL
 };
 
@@ -1835,24 +1878,6 @@ void HELPER(set_cp15)(CPUARMState *env, uint32_t insn, uint32_t val)
             }
         }
         break;
-    case 8: /* MMU TLB control.  */
-        switch (op2) {
-        case 0: /* Invalidate all (TLBIALL) */
-            tlb_flush(env, 1);
-            break;
-        case 1: /* Invalidate single TLB entry by MVA and ASID (TLBIMVA) */
-            tlb_flush_page(env, val & TARGET_PAGE_MASK);
-            break;
-        case 2: /* Invalidate by ASID (TLBIASID) */
-            tlb_flush(env, val == 0);
-            break;
-        case 3: /* Invalidate single entry by MVA, all ASIDs (TLBIMVAA) */
-            tlb_flush_page(env, val & TARGET_PAGE_MASK);
-            break;
-        default:
-            goto bad_reg;
-        }
-        break;
     case 9:
         if (arm_feature(env, ARM_FEATURE_OMAPCP))
             break;
@@ -2065,8 +2090,6 @@ uint32_t HELPER(get_cp15)(CPUARMState *env, uint32_t insn)
         /* FIXME: Should only clear Z flag if destination is r15.  */
         env->ZF = 0;
         return 0;
-    case 8: /* MMU TLB control.  */
-        goto bad_reg;
     case 9:
         switch (crm) {
         case 0: /* Cache lockdown */
commit 1047b9d7bbda3d035e6d94c4a0e6d56d91ce95ec
Author: Peter Maydell <peter.maydell at linaro.org>
Date:   Wed Jun 20 11:57:15 2012 +0000

    target-arm: Convert cp15 crn=15 registers
    
    Convert the cp15 crn=15 (implementation specific) registers
    to the new scheme.
    
    Signed-off-by: Peter Maydell <peter.maydell at linaro.org>

diff --git a/target-arm/cpu.c b/target-arm/cpu.c
index 8fcb730..6190091 100644
--- a/target-arm/cpu.c
+++ b/target-arm/cpu.c
@@ -71,7 +71,6 @@ static void arm_cpu_reset(CPUState *s)
 
     memset(env, 0, offsetof(CPUARMState, breakpoints));
     g_hash_table_foreach(cpu->cp_regs, cp_reg_reset, cpu);
-    env->cp15.c15_config_base_address = cpu->reset_cbar;
     env->cp15.c0_cpuid = cpu->midr;
     env->vfp.xregs[ARM_VFP_FPSID] = cpu->reset_fpsid;
     env->vfp.xregs[ARM_VFP_MVFR0] = cpu->mvfr0;
@@ -92,7 +91,6 @@ static void arm_cpu_reset(CPUState *s)
     env->cp15.c0_c2[3] = cpu->id_isar3;
     env->cp15.c0_c2[4] = cpu->id_isar4;
     env->cp15.c0_c2[5] = cpu->id_isar5;
-    env->cp15.c15_i_min = 0xff0;
     env->cp15.c0_clid = cpu->clidr;
     memcpy(env->cp15.c0_ccsid, cpu->ccsidr, ARRAY_SIZE(cpu->ccsidr));
 
@@ -399,6 +397,35 @@ static void cortex_a8_initfn(Object *obj)
     cpu->ccsidr[2] = 0xf0000000; /* No L2 icache. */
 }
 
+static const ARMCPRegInfo cortexa9_cp_reginfo[] = {
+    /* power_control should be set to maximum latency. Again,
+     * default to 0 and set by private hook
+     */
+    { .name = "A9_PWRCTL", .cp = 15, .crn = 15, .crm = 0, .opc1 = 0, .opc2 = 0,
+      .access = PL1_RW, .resetvalue = 0,
+      .fieldoffset = offsetof(CPUARMState, cp15.c15_power_control) },
+    { .name = "A9_DIAG", .cp = 15, .crn = 15, .crm = 0, .opc1 = 0, .opc2 = 1,
+      .access = PL1_RW, .resetvalue = 0,
+      .fieldoffset = offsetof(CPUARMState, cp15.c15_diagnostic) },
+    { .name = "A9_PWRDIAG", .cp = 15, .crn = 15, .crm = 0, .opc1 = 0, .opc2 = 2,
+      .access = PL1_RW, .resetvalue = 0,
+      .fieldoffset = offsetof(CPUARMState, cp15.c15_power_diagnostic) },
+    { .name = "NEONBUSY", .cp = 15, .crn = 15, .crm = 1, .opc1 = 0, .opc2 = 0,
+      .access = PL1_RW, .resetvalue = 0, .type = ARM_CP_CONST },
+    /* TLB lockdown control */
+    { .name = "TLB_LOCKR", .cp = 15, .crn = 15, .crm = 4, .opc1 = 5, .opc2 = 2,
+      .access = PL1_W, .resetvalue = 0, .type = ARM_CP_NOP },
+    { .name = "TLB_LOCKW", .cp = 15, .crn = 15, .crm = 4, .opc1 = 5, .opc2 = 4,
+      .access = PL1_W, .resetvalue = 0, .type = ARM_CP_NOP },
+    { .name = "TLB_VA", .cp = 15, .crn = 15, .crm = 5, .opc1 = 5, .opc2 = 2,
+      .access = PL1_RW, .resetvalue = 0, .type = ARM_CP_CONST },
+    { .name = "TLB_PA", .cp = 15, .crn = 15, .crm = 6, .opc1 = 5, .opc2 = 2,
+      .access = PL1_RW, .resetvalue = 0, .type = ARM_CP_CONST },
+    { .name = "TLB_ATTR", .cp = 15, .crn = 15, .crm = 7, .opc1 = 5, .opc2 = 2,
+      .access = PL1_RW, .resetvalue = 0, .type = ARM_CP_CONST },
+    REGINFO_SENTINEL
+};
+
 static void cortex_a9_initfn(Object *obj)
 {
     ARMCPU *cpu = ARM_CPU(obj);
@@ -434,6 +461,15 @@ static void cortex_a9_initfn(Object *obj)
     cpu->clidr = (1 << 27) | (1 << 24) | 3;
     cpu->ccsidr[0] = 0xe00fe015; /* 16k L1 dcache. */
     cpu->ccsidr[1] = 0x200fe015; /* 16k L1 icache. */
+    {
+        ARMCPRegInfo cbar = {
+            .name = "CBAR", .cp = 15, .crn = 15,  .crm = 0, .opc1 = 4,
+            .opc2 = 0, .access = PL1_R|PL3_W, .resetvalue = cpu->reset_cbar,
+            .fieldoffset = offsetof(CPUARMState, cp15.c15_config_base_address)
+        };
+        define_one_arm_cp_reg(cpu, &cbar);
+        define_arm_cp_regs(cpu, cortexa9_cp_reginfo);
+    }
 }
 
 static void cortex_a15_initfn(Object *obj)
diff --git a/target-arm/cpu.h b/target-arm/cpu.h
index a61cb07..b94503d 100644
--- a/target-arm/cpu.h
+++ b/target-arm/cpu.h
@@ -386,6 +386,7 @@ enum arm_features {
     ARM_FEATURE_VFP4, /* VFPv4 (implies that NEON is v2) */
     ARM_FEATURE_GENERIC_TIMER,
     ARM_FEATURE_MVFR, /* Media and VFP Feature Registers 0 and 1 */
+    ARM_FEATURE_DUMMY_C15_REGS, /* RAZ/WI all of cp15 crn=15 */
 };
 
 static inline int arm_feature(CPUARMState *env, int feature)
diff --git a/target-arm/helper.c b/target-arm/helper.c
index 5fa4ed5..0d7200f 100644
--- a/target-arm/helper.c
+++ b/target-arm/helper.c
@@ -492,10 +492,91 @@ static const ARMCPRegInfo vmsa_cp_reginfo[] = {
     REGINFO_SENTINEL
 };
 
+static int omap_ticonfig_write(CPUARMState *env, const ARMCPRegInfo *ri,
+                               uint64_t value)
+{
+    env->cp15.c15_ticonfig = value & 0xe7;
+    /* The OS_TYPE bit in this register changes the reported CPUID! */
+    env->cp15.c0_cpuid = (value & (1 << 5)) ?
+        ARM_CPUID_TI915T : ARM_CPUID_TI925T;
+    return 0;
+}
+
+static int omap_threadid_write(CPUARMState *env, const ARMCPRegInfo *ri,
+                               uint64_t value)
+{
+    env->cp15.c15_threadid = value & 0xffff;
+    return 0;
+}
+
+static int omap_wfi_write(CPUARMState *env, const ARMCPRegInfo *ri,
+                          uint64_t value)
+{
+    /* Wait-for-interrupt (deprecated) */
+    cpu_interrupt(env, CPU_INTERRUPT_HALT);
+    return 0;
+}
+
 static const ARMCPRegInfo omap_cp_reginfo[] = {
     { .name = "DFSR", .cp = 15, .crn = 5, .crm = CP_ANY,
       .opc1 = CP_ANY, .opc2 = CP_ANY, .access = PL1_RW, .type = ARM_CP_OVERRIDE,
       .fieldoffset = offsetof(CPUARMState, cp15.c5_data), .resetvalue = 0, },
+    { .name = "", .cp = 15, .crn = 15, .crm = 0, .opc1 = 0, .opc2 = 0,
+      .access = PL1_RW, .type = ARM_CP_NOP },
+    { .name = "TICONFIG", .cp = 15, .crn = 15, .crm = 1, .opc1 = 0, .opc2 = 0,
+      .access = PL1_RW,
+      .fieldoffset = offsetof(CPUARMState, cp15.c15_ticonfig), .resetvalue = 0,
+      .writefn = omap_ticonfig_write },
+    { .name = "IMAX", .cp = 15, .crn = 15, .crm = 2, .opc1 = 0, .opc2 = 0,
+      .access = PL1_RW,
+      .fieldoffset = offsetof(CPUARMState, cp15.c15_i_max), .resetvalue = 0, },
+    { .name = "IMIN", .cp = 15, .crn = 15, .crm = 3, .opc1 = 0, .opc2 = 0,
+      .access = PL1_RW, .resetvalue = 0xff0,
+      .fieldoffset = offsetof(CPUARMState, cp15.c15_i_min) },
+    { .name = "THREADID", .cp = 15, .crn = 15, .crm = 4, .opc1 = 0, .opc2 = 0,
+      .access = PL1_RW,
+      .fieldoffset = offsetof(CPUARMState, cp15.c15_threadid), .resetvalue = 0,
+      .writefn = omap_threadid_write },
+    { .name = "TI925T_STATUS", .cp = 15, .crn = 15,
+      .crm = 8, .opc1 = 0, .opc2 = 0, .access = PL1_RW,
+      .readfn = arm_cp_read_zero, .writefn = omap_wfi_write, },
+    /* TODO: Peripheral port remap register:
+     * On OMAP2 mcr p15, 0, rn, c15, c2, 4 sets up the interrupt controller
+     * base address at $rn & ~0xfff and map size of 0x200 << ($rn & 0xfff),
+     * when MMU is off.
+     */
+    REGINFO_SENTINEL
+};
+
+static int xscale_cpar_write(CPUARMState *env, const ARMCPRegInfo *ri,
+                             uint64_t value)
+{
+    value &= 0x3fff;
+    if (env->cp15.c15_cpar != value) {
+        /* Changes cp0 to cp13 behavior, so needs a TB flush.  */
+        tb_flush(env);
+        env->cp15.c15_cpar = value;
+    }
+    return 0;
+}
+
+static const ARMCPRegInfo xscale_cp_reginfo[] = {
+    { .name = "XSCALE_CPAR",
+      .cp = 15, .crn = 15, .crm = 1, .opc1 = 0, .opc2 = 0, .access = PL1_RW,
+      .fieldoffset = offsetof(CPUARMState, cp15.c15_cpar), .resetvalue = 0,
+      .writefn = xscale_cpar_write, },
+    REGINFO_SENTINEL
+};
+
+static const ARMCPRegInfo dummy_c15_cp_reginfo[] = {
+    /* RAZ/WI the whole crn=15 space, when we don't have a more specific
+     * implementation of this implementation-defined space.
+     * Ideally this should eventually disappear in favour of actually
+     * implementing the correct behaviour for all cores.
+     */
+    { .name = "C15_IMPDEF", .cp = 15, .crn = 15,
+      .crm = CP_ANY, .opc1 = CP_ANY, .opc2 = CP_ANY,
+      .access = PL1_RW, .type = ARM_CP_CONST, .resetvalue = 0 },
     REGINFO_SENTINEL
 };
 
@@ -552,6 +633,12 @@ void register_cp_regs_for_features(ARMCPU *cpu)
     if (arm_feature(env, ARM_FEATURE_OMAPCP)) {
         define_arm_cp_regs(cpu, omap_cp_reginfo);
     }
+    if (arm_feature(env, ARM_FEATURE_XSCALE)) {
+        define_arm_cp_regs(cpu, xscale_cp_reginfo);
+    }
+    if (arm_feature(env, ARM_FEATURE_DUMMY_C15_REGS)) {
+        define_arm_cp_regs(cpu, dummy_c15_cp_reginfo);
+    }
 }
 
 ARMCPU *cpu_arm_init(const char *cpu_model)
@@ -1802,58 +1889,6 @@ void HELPER(set_cp15)(CPUARMState *env, uint32_t insn, uint32_t val)
         break;
     case 12: /* Reserved.  */
         goto bad_reg;
-    case 15: /* Implementation specific.  */
-        if (arm_feature(env, ARM_FEATURE_XSCALE)) {
-            if (op2 == 0 && crm == 1) {
-                if (env->cp15.c15_cpar != (val & 0x3fff)) {
-                    /* Changes cp0 to cp13 behavior, so needs a TB flush.  */
-                    tb_flush(env);
-                    env->cp15.c15_cpar = val & 0x3fff;
-                }
-                break;
-            }
-            goto bad_reg;
-        }
-        if (arm_feature(env, ARM_FEATURE_OMAPCP)) {
-            switch (crm) {
-            case 0:
-                break;
-            case 1: /* Set TI925T configuration.  */
-                env->cp15.c15_ticonfig = val & 0xe7;
-                env->cp15.c0_cpuid = (val & (1 << 5)) ? /* OS_TYPE bit */
-                        ARM_CPUID_TI915T : ARM_CPUID_TI925T;
-                break;
-            case 2: /* Set I_max.  */
-                env->cp15.c15_i_max = val;
-                break;
-            case 3: /* Set I_min.  */
-                env->cp15.c15_i_min = val;
-                break;
-            case 4: /* Set thread-ID.  */
-                env->cp15.c15_threadid = val & 0xffff;
-                break;
-            case 8: /* Wait-for-interrupt (deprecated).  */
-                cpu_interrupt(env, CPU_INTERRUPT_HALT);
-                break;
-            default:
-                goto bad_reg;
-            }
-        }
-        if (ARM_CPUID(env) == ARM_CPUID_CORTEXA9) {
-            switch (crm) {
-            case 0:
-                if ((op1 == 0) && (op2 == 0)) {
-                    env->cp15.c15_power_control = val;
-                } else if ((op1 == 0) && (op2 == 1)) {
-                    env->cp15.c15_diagnostic = val;
-                } else if ((op1 == 0) && (op2 == 2)) {
-                    env->cp15.c15_power_diagnostic = val;
-                }
-            default:
-                break;
-            }
-        }
-        break;
     }
     return;
 bad_reg:
@@ -2080,69 +2115,6 @@ uint32_t HELPER(get_cp15)(CPUARMState *env, uint32_t insn)
     case 11: /* TCM DMA control.  */
     case 12: /* Reserved.  */
         goto bad_reg;
-    case 15: /* Implementation specific.  */
-        if (arm_feature(env, ARM_FEATURE_XSCALE)) {
-            if (op2 == 0 && crm == 1)
-                return env->cp15.c15_cpar;
-
-            goto bad_reg;
-        }
-        if (arm_feature(env, ARM_FEATURE_OMAPCP)) {
-            switch (crm) {
-            case 0:
-                return 0;
-            case 1: /* Read TI925T configuration.  */
-                return env->cp15.c15_ticonfig;
-            case 2: /* Read I_max.  */
-                return env->cp15.c15_i_max;
-            case 3: /* Read I_min.  */
-                return env->cp15.c15_i_min;
-            case 4: /* Read thread-ID.  */
-                return env->cp15.c15_threadid;
-            case 8: /* TI925T_status */
-                return 0;
-            }
-            /* TODO: Peripheral port remap register:
-             * On OMAP2 mcr p15, 0, rn, c15, c2, 4 sets up the interrupt
-             * controller base address at $rn & ~0xfff and map size of
-             * 0x200 << ($rn & 0xfff), when MMU is off.  */
-            goto bad_reg;
-        }
-        if (ARM_CPUID(env) == ARM_CPUID_CORTEXA9) {
-            switch (crm) {
-            case 0:
-                if ((op1 == 4) && (op2 == 0)) {
-                    /* The config_base_address should hold the value of
-                     * the peripheral base. ARM should get this from a CPU
-                     * object property, but that support isn't available in
-                     * December 2011. Default to 0 for now and board models
-                     * that care can set it by a private hook */
-                    return env->cp15.c15_config_base_address;
-                } else if ((op1 == 0) && (op2 == 0)) {
-                    /* power_control should be set to maximum latency. Again,
-                       default to 0 and set by private hook */
-                    return env->cp15.c15_power_control;
-                } else if ((op1 == 0) && (op2 == 1)) {
-                    return env->cp15.c15_diagnostic;
-                } else if ((op1 == 0) && (op2 == 2)) {
-                    return env->cp15.c15_power_diagnostic;
-                }
-                break;
-            case 1: /* NEON Busy */
-                return 0;
-            case 5: /* tlb lockdown */
-            case 6:
-            case 7:
-                if ((op1 == 5) && (op2 == 2)) {
-                    return 0;
-                }
-                break;
-            default:
-                break;
-            }
-            goto bad_reg;
-        }
-        return 0;
     }
 bad_reg:
     /* ??? For debugging only.  Should raise illegal instruction exception.  */
commit 4fdd17dd3505ea5444d08d1347783d2347ec3520
Author: Peter Maydell <peter.maydell at linaro.org>
Date:   Wed Jun 20 11:57:15 2012 +0000

    target-arm: Convert cp15 crn=10 registers
    
    We RAZ/WI the entire block of crn=10 registers. Note that this
    actually covers not just the implementation-defined TLB
    lockdown registers but also a number of v7 VMSA memory
    attribute registers which we would need to implement to
    support TEX remap. We retain the previous QEMU behaviour
    in this conversion, though.
    
    Signed-off-by: Peter Maydell <peter.maydell at linaro.org>

diff --git a/target-arm/helper.c b/target-arm/helper.c
index 3cffa00..5fa4ed5 100644
--- a/target-arm/helper.c
+++ b/target-arm/helper.c
@@ -106,6 +106,11 @@ static const ARMCPRegInfo cp_reginfo[] = {
     { .name = "CONTEXTIDR", .cp = 15, .crn = 13, .crm = 0, .opc1 = 0, .opc2 = 1,
       .access = PL1_RW, .fieldoffset = offsetof(CPUARMState, cp15.c13_fcse),
       .resetvalue = 0, .writefn = contextidr_write },
+    /* ??? This covers not just the impdef TLB lockdown registers but also
+     * some v7VMSA registers relating to TEX remap, so it is overly broad.
+     */
+    { .name = "TLB_LOCKDOWN", .cp = 15, .crn = 10, .crm = CP_ANY,
+      .opc1 = CP_ANY, .opc2 = CP_ANY, .access = PL1_RW, .type = ARM_CP_NOP },
     REGINFO_SENTINEL
 };
 
@@ -1795,9 +1800,6 @@ void HELPER(set_cp15)(CPUARMState *env, uint32_t insn, uint32_t val)
             goto bad_reg;
         }
         break;
-    case 10: /* MMU TLB lockdown.  */
-        /* ??? TLB lockdown not implemented.  */
-        break;
     case 12: /* Reserved.  */
         goto bad_reg;
     case 15: /* Implementation specific.  */
@@ -2075,9 +2077,6 @@ uint32_t HELPER(get_cp15)(CPUARMState *env, uint32_t insn)
             goto bad_reg;
         }
         break;
-    case 10: /* MMU TLB lockdown.  */
-        /* ??? TLB lockdown not implemented.  */
-        return 0;
     case 11: /* TCM DMA control.  */
     case 12: /* Reserved.  */
         goto bad_reg;
commit 08de207bc52108df5d8e9074909e98f5df8e1212
Author: Peter Maydell <peter.maydell at linaro.org>
Date:   Wed Jun 20 11:57:14 2012 +0000

    target-arm: Convert cp15 crn=13 registers
    
    Convert the cp15 crn=13 registers (FCSEIDR, CONTEXTIDR,
    and the ARM946 Trace Process Identifier Register).
    
    Signed-off-by: Peter Maydell <peter.maydell at linaro.org>

diff --git a/target-arm/helper.c b/target-arm/helper.c
index bda7947..3cffa00 100644
--- a/target-arm/helper.c
+++ b/target-arm/helper.c
@@ -63,6 +63,31 @@ static int dacr_write(CPUARMState *env, const ARMCPRegInfo *ri, uint64_t value)
     return 0;
 }
 
+static int fcse_write(CPUARMState *env, const ARMCPRegInfo *ri, uint64_t value)
+{
+    if (env->cp15.c13_fcse != value) {
+        /* Unlike real hardware the qemu TLB uses virtual addresses,
+         * not modified virtual addresses, so this causes a TLB flush.
+         */
+        tlb_flush(env, 1);
+        env->cp15.c13_fcse = value;
+    }
+    return 0;
+}
+static int contextidr_write(CPUARMState *env, const ARMCPRegInfo *ri,
+                            uint64_t value)
+{
+    if (env->cp15.c13_context != value && !arm_feature(env, ARM_FEATURE_MPU)) {
+        /* For VMSA (when not using the LPAE long descriptor page table
+         * format) this register includes the ASID, so do a TLB flush.
+         * For PMSA it is purely a process ID and no action is needed.
+         */
+        tlb_flush(env, 1);
+    }
+    env->cp15.c13_context = value;
+    return 0;
+}
+
 static const ARMCPRegInfo cp_reginfo[] = {
     /* DBGDIDR: just RAZ. In particular this means the "debug architecture
      * version" bits will read as a reserved value, which should cause
@@ -75,6 +100,12 @@ static const ARMCPRegInfo cp_reginfo[] = {
       .crn = 3, .crm = CP_ANY, .opc1 = CP_ANY, .opc2 = CP_ANY,
       .access = PL1_RW, .fieldoffset = offsetof(CPUARMState, cp15.c3),
       .resetvalue = 0, .writefn = dacr_write },
+    { .name = "FCSEIDR", .cp = 15, .crn = 13, .crm = 0, .opc1 = 0, .opc2 = 0,
+      .access = PL1_RW, .fieldoffset = offsetof(CPUARMState, cp15.c13_fcse),
+      .resetvalue = 0, .writefn = fcse_write },
+    { .name = "CONTEXTIDR", .cp = 15, .crn = 13, .crm = 0, .opc1 = 0, .opc2 = 1,
+      .access = PL1_RW, .fieldoffset = offsetof(CPUARMState, cp15.c13_fcse),
+      .resetvalue = 0, .writefn = contextidr_write },
     REGINFO_SENTINEL
 };
 
@@ -1769,27 +1800,6 @@ void HELPER(set_cp15)(CPUARMState *env, uint32_t insn, uint32_t val)
         break;
     case 12: /* Reserved.  */
         goto bad_reg;
-    case 13: /* Process ID.  */
-        switch (op2) {
-        case 0:
-            /* Unlike real hardware the qemu TLB uses virtual addresses,
-               not modified virtual addresses, so this causes a TLB flush.
-             */
-            if (env->cp15.c13_fcse != val)
-              tlb_flush(env, 1);
-            env->cp15.c13_fcse = val;
-            break;
-        case 1:
-            /* This changes the ASID, so do a TLB flush.  */
-            if (env->cp15.c13_context != val
-                && !arm_feature(env, ARM_FEATURE_MPU))
-              tlb_flush(env, 0);
-            env->cp15.c13_context = val;
-            break;
-        default:
-            goto bad_reg;
-        }
-        break;
     case 15: /* Implementation specific.  */
         if (arm_feature(env, ARM_FEATURE_XSCALE)) {
             if (op2 == 0 && crm == 1) {
@@ -2071,15 +2081,6 @@ uint32_t HELPER(get_cp15)(CPUARMState *env, uint32_t insn)
     case 11: /* TCM DMA control.  */
     case 12: /* Reserved.  */
         goto bad_reg;
-    case 13: /* Process ID.  */
-        switch (op2) {
-        case 0:
-            return env->cp15.c13_fcse;
-        case 1:
-            return env->cp15.c13_context;
-        default:
-            goto bad_reg;
-        }
     case 15: /* Implementation specific.  */
         if (arm_feature(env, ARM_FEATURE_XSCALE)) {
             if (op2 == 0 && crm == 1)
commit ecce5c3c90653b82c2910da53210ba4ce589da89
Author: Peter Maydell <peter.maydell at linaro.org>
Date:   Wed Jun 20 11:57:14 2012 +0000

    target-arm: Convert cp15 crn=2 registers
    
    Convert the cp15 crn=2 registers (MMU page table control,
    MPU cache control) to the new scheme.
    
    Signed-off-by: Peter Maydell <peter.maydell at linaro.org>

diff --git a/target-arm/cpu.c b/target-arm/cpu.c
index 0098787..8fcb730 100644
--- a/target-arm/cpu.c
+++ b/target-arm/cpu.c
@@ -131,7 +131,6 @@ static void arm_cpu_reset(CPUState *s)
         }
     }
     env->vfp.xregs[ARM_VFP_FPEXC] = 0;
-    env->cp15.c2_base_mask = 0xffffc000u;
 #endif
     set_flush_to_zero(1, &env->vfp.standard_fp_status);
     set_flush_inputs_to_zero(1, &env->vfp.standard_fp_status);
diff --git a/target-arm/helper.c b/target-arm/helper.c
index d2c7b9f..bda7947 100644
--- a/target-arm/helper.c
+++ b/target-arm/helper.c
@@ -410,9 +410,32 @@ static const ARMCPRegInfo pmsav5_cp_reginfo[] = {
     { .name = "INSN_EXT_AP", .cp = 15, .crn = 5, .crm = 0, .opc1 = 0, .opc2 = 3,
       .access = PL1_RW,
       .fieldoffset = offsetof(CPUARMState, cp15.c5_insn), .resetvalue = 0, },
+    { .name = "DCACHE_CFG", .cp = 15, .crn = 2, .crm = 0, .opc1 = 0, .opc2 = 0,
+      .access = PL1_RW,
+      .fieldoffset = offsetof(CPUARMState, cp15.c2_data), .resetvalue = 0, },
+    { .name = "ICACHE_CFG", .cp = 15, .crn = 2, .crm = 0, .opc1 = 0, .opc2 = 1,
+      .access = PL1_RW,
+      .fieldoffset = offsetof(CPUARMState, cp15.c2_insn), .resetvalue = 0, },
     REGINFO_SENTINEL
 };
 
+static int vmsa_ttbcr_write(CPUARMState *env, const ARMCPRegInfo *ri,
+                            uint64_t value)
+{
+    value &= 7;
+    env->cp15.c2_control = value;
+    env->cp15.c2_mask = ~(((uint32_t)0xffffffffu) >> value);
+    env->cp15.c2_base_mask = ~((uint32_t)0x3fffu >> value);
+    return 0;
+}
+
+static void vmsa_ttbcr_reset(CPUARMState *env, const ARMCPRegInfo *ri)
+{
+    env->cp15.c2_base_mask = 0xffffc000u;
+    env->cp15.c2_control = 0;
+    env->cp15.c2_mask = 0;
+}
+
 static const ARMCPRegInfo vmsa_cp_reginfo[] = {
     { .name = "DFSR", .cp = 15, .crn = 5, .crm = 0, .opc1 = 0, .opc2 = 0,
       .access = PL1_RW,
@@ -420,6 +443,16 @@ static const ARMCPRegInfo vmsa_cp_reginfo[] = {
     { .name = "IFSR", .cp = 15, .crn = 5, .crm = 0, .opc1 = 0, .opc2 = 1,
       .access = PL1_RW,
       .fieldoffset = offsetof(CPUARMState, cp15.c5_insn), .resetvalue = 0, },
+    { .name = "TTBR0", .cp = 15, .crn = 2, .crm = 0, .opc1 = 0, .opc2 = 0,
+      .access = PL1_RW,
+      .fieldoffset = offsetof(CPUARMState, cp15.c2_base0), .resetvalue = 0, },
+    { .name = "TTBR1", .cp = 15, .crn = 2, .crm = 0, .opc1 = 0, .opc2 = 1,
+      .access = PL1_RW,
+      .fieldoffset = offsetof(CPUARMState, cp15.c2_base0), .resetvalue = 0, },
+    { .name = "TTBCR", .cp = 15, .crn = 2, .crm = 0, .opc1 = 0, .opc2 = 2,
+      .access = PL1_RW, .writefn = vmsa_ttbcr_write,
+      .resetfn = vmsa_ttbcr_reset,
+      .fieldoffset = offsetof(CPUARMState, cp15.c2_control) },
     REGINFO_SENTINEL
 };
 
@@ -1609,37 +1642,6 @@ void HELPER(set_cp15)(CPUARMState *env, uint32_t insn, uint32_t val)
             goto bad_reg;
         }
         break;
-    case 2: /* MMU Page table control / MPU cache control.  */
-        if (arm_feature(env, ARM_FEATURE_MPU)) {
-            switch (op2) {
-            case 0:
-                env->cp15.c2_data = val;
-                break;
-            case 1:
-                env->cp15.c2_insn = val;
-                break;
-            default:
-                goto bad_reg;
-            }
-        } else {
-	    switch (op2) {
-	    case 0:
-		env->cp15.c2_base0 = val;
-		break;
-	    case 1:
-		env->cp15.c2_base1 = val;
-		break;
-	    case 2:
-                val &= 7;
-                env->cp15.c2_control = val;
-		env->cp15.c2_mask = ~(((uint32_t)0xffffffffu) >> val);
-                env->cp15.c2_base_mask = ~((uint32_t)0x3fffu >> val);
-		break;
-	    default:
-		goto bad_reg;
-	    }
-        }
-        break;
     case 4: /* Reserved.  */
         goto bad_reg;
     case 6: /* MMU Fault address / MPU base/size.  */
@@ -1975,30 +1977,6 @@ uint32_t HELPER(get_cp15)(CPUARMState *env, uint32_t insn)
         default:
             goto bad_reg;
         }
-    case 2: /* MMU Page table control / MPU cache control.  */
-        if (arm_feature(env, ARM_FEATURE_MPU)) {
-            switch (op2) {
-            case 0:
-                return env->cp15.c2_data;
-                break;
-            case 1:
-                return env->cp15.c2_insn;
-                break;
-            default:
-                goto bad_reg;
-            }
-        } else {
-	    switch (op2) {
-	    case 0:
-		return env->cp15.c2_base0;
-	    case 1:
-		return env->cp15.c2_base1;
-	    case 2:
-                return env->cp15.c2_control;
-	    default:
-		goto bad_reg;
-	    }
-	}
     case 4: /* Reserved.  */
         goto bad_reg;
     case 6: /* MMU Fault address.  */
commit 18032bec5cd4fa3e45987e021b2f89fbff12ba5f
Author: Peter Maydell <peter.maydell at linaro.org>
Date:   Wed Jun 20 11:57:13 2012 +0000

    target-arm: Convert MMU fault status cp15 registers
    
    Convert the MMU fault status and MPU access permission cp15
    registers to the new scheme.
    
    Signed-off-by: Peter Maydell <peter.maydell at linaro.org>

diff --git a/target-arm/helper.c b/target-arm/helper.c
index d579a20..d2c7b9f 100644
--- a/target-arm/helper.c
+++ b/target-arm/helper.c
@@ -337,6 +337,99 @@ static const ARMCPRegInfo generic_timer_cp_reginfo[] = {
     REGINFO_SENTINEL
 };
 
+/* Return basic MPU access permission bits.  */
+static uint32_t simple_mpu_ap_bits(uint32_t val)
+{
+    uint32_t ret;
+    uint32_t mask;
+    int i;
+    ret = 0;
+    mask = 3;
+    for (i = 0; i < 16; i += 2) {
+        ret |= (val >> i) & mask;
+        mask <<= 2;
+    }
+    return ret;
+}
+
+/* Pad basic MPU access permission bits to extended format.  */
+static uint32_t extended_mpu_ap_bits(uint32_t val)
+{
+    uint32_t ret;
+    uint32_t mask;
+    int i;
+    ret = 0;
+    mask = 3;
+    for (i = 0; i < 16; i += 2) {
+        ret |= (val & mask) << i;
+        mask <<= 2;
+    }
+    return ret;
+}
+
+static int pmsav5_data_ap_write(CPUARMState *env, const ARMCPRegInfo *ri,
+                                uint64_t value)
+{
+    env->cp15.c5_data = extended_mpu_ap_bits(value);
+    return 0;
+}
+
+static int pmsav5_data_ap_read(CPUARMState *env, const ARMCPRegInfo *ri,
+                               uint64_t *value)
+{
+    *value = simple_mpu_ap_bits(env->cp15.c5_data);
+    return 0;
+}
+
+static int pmsav5_insn_ap_write(CPUARMState *env, const ARMCPRegInfo *ri,
+                                uint64_t value)
+{
+    env->cp15.c5_insn = extended_mpu_ap_bits(value);
+    return 0;
+}
+
+static int pmsav5_insn_ap_read(CPUARMState *env, const ARMCPRegInfo *ri,
+                               uint64_t *value)
+{
+    *value = simple_mpu_ap_bits(env->cp15.c5_insn);
+    return 0;
+}
+
+static const ARMCPRegInfo pmsav5_cp_reginfo[] = {
+    { .name = "DATA_AP", .cp = 15, .crn = 5, .crm = 0, .opc1 = 0, .opc2 = 0,
+      .access = PL1_RW,
+      .fieldoffset = offsetof(CPUARMState, cp15.c5_data), .resetvalue = 0,
+      .readfn = pmsav5_data_ap_read, .writefn = pmsav5_data_ap_write, },
+    { .name = "INSN_AP", .cp = 15, .crn = 5, .crm = 0, .opc1 = 0, .opc2 = 1,
+      .access = PL1_RW,
+      .fieldoffset = offsetof(CPUARMState, cp15.c5_insn), .resetvalue = 0,
+      .readfn = pmsav5_insn_ap_read, .writefn = pmsav5_insn_ap_write, },
+    { .name = "DATA_EXT_AP", .cp = 15, .crn = 5, .crm = 0, .opc1 = 0, .opc2 = 2,
+      .access = PL1_RW,
+      .fieldoffset = offsetof(CPUARMState, cp15.c5_data), .resetvalue = 0, },
+    { .name = "INSN_EXT_AP", .cp = 15, .crn = 5, .crm = 0, .opc1 = 0, .opc2 = 3,
+      .access = PL1_RW,
+      .fieldoffset = offsetof(CPUARMState, cp15.c5_insn), .resetvalue = 0, },
+    REGINFO_SENTINEL
+};
+
+static const ARMCPRegInfo vmsa_cp_reginfo[] = {
+    { .name = "DFSR", .cp = 15, .crn = 5, .crm = 0, .opc1 = 0, .opc2 = 0,
+      .access = PL1_RW,
+      .fieldoffset = offsetof(CPUARMState, cp15.c5_data), .resetvalue = 0, },
+    { .name = "IFSR", .cp = 15, .crn = 5, .crm = 0, .opc1 = 0, .opc2 = 1,
+      .access = PL1_RW,
+      .fieldoffset = offsetof(CPUARMState, cp15.c5_insn), .resetvalue = 0, },
+    REGINFO_SENTINEL
+};
+
+static const ARMCPRegInfo omap_cp_reginfo[] = {
+    { .name = "DFSR", .cp = 15, .crn = 5, .crm = CP_ANY,
+      .opc1 = CP_ANY, .opc2 = CP_ANY, .access = PL1_RW, .type = ARM_CP_OVERRIDE,
+      .fieldoffset = offsetof(CPUARMState, cp15.c5_data), .resetvalue = 0, },
+    REGINFO_SENTINEL
+};
+
 void register_cp_regs_for_features(ARMCPU *cpu)
 {
     /* Register all the coprocessor registers based on feature bits */
@@ -370,12 +463,26 @@ void register_cp_regs_for_features(ARMCPU *cpu)
     } else {
         define_arm_cp_regs(cpu, not_v7_cp_reginfo);
     }
+    if (arm_feature(env, ARM_FEATURE_MPU)) {
+        /* These are the MPU registers prior to PMSAv6. Any new
+         * PMSA core later than the ARM946 will require that we
+         * implement the PMSAv6 or PMSAv7 registers, which are
+         * completely different.
+         */
+        assert(!arm_feature(env, ARM_FEATURE_V6));
+        define_arm_cp_regs(cpu, pmsav5_cp_reginfo);
+    } else {
+        define_arm_cp_regs(cpu, vmsa_cp_reginfo);
+    }
     if (arm_feature(env, ARM_FEATURE_THUMB2EE)) {
         define_arm_cp_regs(cpu, t2ee_cp_reginfo);
     }
     if (arm_feature(env, ARM_FEATURE_GENERIC_TIMER)) {
         define_arm_cp_regs(cpu, generic_timer_cp_reginfo);
     }
+    if (arm_feature(env, ARM_FEATURE_OMAPCP)) {
+        define_arm_cp_regs(cpu, omap_cp_reginfo);
+    }
 }
 
 ARMCPU *cpu_arm_init(const char *cpu_model)
@@ -1444,36 +1551,6 @@ target_phys_addr_t cpu_get_phys_page_debug(CPUARMState *env, target_ulong addr)
     return phys_addr;
 }
 
-/* Return basic MPU access permission bits.  */
-static uint32_t simple_mpu_ap_bits(uint32_t val)
-{
-    uint32_t ret;
-    uint32_t mask;
-    int i;
-    ret = 0;
-    mask = 3;
-    for (i = 0; i < 16; i += 2) {
-        ret |= (val >> i) & mask;
-        mask <<= 2;
-    }
-    return ret;
-}
-
-/* Pad basic MPU access permission bits to extended format.  */
-static uint32_t extended_mpu_ap_bits(uint32_t val)
-{
-    uint32_t ret;
-    uint32_t mask;
-    int i;
-    ret = 0;
-    mask = 3;
-    for (i = 0; i < 16; i += 2) {
-        ret |= (val & mask) << i;
-        mask <<= 2;
-    }
-    return ret;
-}
-
 void HELPER(set_cp15)(CPUARMState *env, uint32_t insn, uint32_t val)
 {
     int op1;
@@ -1565,34 +1642,6 @@ void HELPER(set_cp15)(CPUARMState *env, uint32_t insn, uint32_t val)
         break;
     case 4: /* Reserved.  */
         goto bad_reg;
-    case 5: /* MMU Fault status / MPU access permission.  */
-        if (arm_feature(env, ARM_FEATURE_OMAPCP))
-            op2 = 0;
-        switch (op2) {
-        case 0:
-            if (arm_feature(env, ARM_FEATURE_MPU))
-                val = extended_mpu_ap_bits(val);
-            env->cp15.c5_data = val;
-            break;
-        case 1:
-            if (arm_feature(env, ARM_FEATURE_MPU))
-                val = extended_mpu_ap_bits(val);
-            env->cp15.c5_insn = val;
-            break;
-        case 2:
-            if (!arm_feature(env, ARM_FEATURE_MPU))
-                goto bad_reg;
-            env->cp15.c5_data = val;
-            break;
-        case 3:
-            if (!arm_feature(env, ARM_FEATURE_MPU))
-                goto bad_reg;
-            env->cp15.c5_insn = val;
-            break;
-        default:
-            goto bad_reg;
-        }
-        break;
     case 6: /* MMU Fault address / MPU base/size.  */
         if (arm_feature(env, ARM_FEATURE_MPU)) {
             if (crm >= 8)
@@ -1952,29 +2001,6 @@ uint32_t HELPER(get_cp15)(CPUARMState *env, uint32_t insn)
 	}
     case 4: /* Reserved.  */
         goto bad_reg;
-    case 5: /* MMU Fault status / MPU access permission.  */
-        if (arm_feature(env, ARM_FEATURE_OMAPCP))
-            op2 = 0;
-        switch (op2) {
-        case 0:
-            if (arm_feature(env, ARM_FEATURE_MPU))
-                return simple_mpu_ap_bits(env->cp15.c5_data);
-            return env->cp15.c5_data;
-        case 1:
-            if (arm_feature(env, ARM_FEATURE_MPU))
-                return simple_mpu_ap_bits(env->cp15.c5_insn);
-            return env->cp15.c5_insn;
-        case 2:
-            if (!arm_feature(env, ARM_FEATURE_MPU))
-                goto bad_reg;
-            return env->cp15.c5_data;
-        case 3:
-            if (!arm_feature(env, ARM_FEATURE_MPU))
-                goto bad_reg;
-            return env->cp15.c5_insn;
-        default:
-            goto bad_reg;
-        }
     case 6: /* MMU Fault address.  */
         if (arm_feature(env, ARM_FEATURE_MPU)) {
             if (crm >= 8)
commit c983fe6cf199f919e1d9b24c86167e46ac20d8b8
Author: Peter Maydell <peter.maydell at linaro.org>
Date:   Wed Jun 20 11:57:13 2012 +0000

    target-arm: Convert cp15 c3 register
    
    Convert the cp15 c3 register (MMU domain access control
    or MPU write buffer control). NB that this is horribly
    underdecoded for modern cores (should be crn=3,crm=0,
    opc1=0,opc2=0) but this change preserves the existing
    QEMU behaviour.
    
    Signed-off-by: Peter Maydell <peter.maydell at linaro.org>

diff --git a/target-arm/helper.c b/target-arm/helper.c
index 2d58eb5..d579a20 100644
--- a/target-arm/helper.c
+++ b/target-arm/helper.c
@@ -56,6 +56,13 @@ static int vfp_gdb_set_reg(CPUARMState *env, uint8_t *buf, int reg)
     return 0;
 }
 
+static int dacr_write(CPUARMState *env, const ARMCPRegInfo *ri, uint64_t value)
+{
+    env->cp15.c3 = value;
+    tlb_flush(env, 1); /* Flush TLB as domain not tracked in TLB */
+    return 0;
+}
+
 static const ARMCPRegInfo cp_reginfo[] = {
     /* DBGDIDR: just RAZ. In particular this means the "debug architecture
      * version" bits will read as a reserved value, which should cause
@@ -63,6 +70,11 @@ static const ARMCPRegInfo cp_reginfo[] = {
      */
     { .name = "DBGDIDR", .cp = 14, .crn = 0, .crm = 0, .opc1 = 0, .opc2 = 0,
       .access = PL0_R, .type = ARM_CP_CONST, .resetvalue = 0 },
+    /* MMU Domain access control / MPU write buffer control */
+    { .name = "DACR", .cp = 15,
+      .crn = 3, .crm = CP_ANY, .opc1 = CP_ANY, .opc2 = CP_ANY,
+      .access = PL1_RW, .fieldoffset = offsetof(CPUARMState, cp15.c3),
+      .resetvalue = 0, .writefn = dacr_write },
     REGINFO_SENTINEL
 };
 
@@ -1551,10 +1563,6 @@ void HELPER(set_cp15)(CPUARMState *env, uint32_t insn, uint32_t val)
 	    }
         }
         break;
-    case 3: /* MMU Domain access control / MPU write buffer control.  */
-        env->cp15.c3 = val;
-        tlb_flush(env, 1); /* Flush TLB as domain not tracked in TLB */
-        break;
     case 4: /* Reserved.  */
         goto bad_reg;
     case 5: /* MMU Fault status / MPU access permission.  */
@@ -1942,8 +1950,6 @@ uint32_t HELPER(get_cp15)(CPUARMState *env, uint32_t insn)
 		goto bad_reg;
 	    }
 	}
-    case 3: /* MMU Domain access control / MPU write buffer control.  */
-        return env->cp15.c3;
     case 4: /* Reserved.  */
         goto bad_reg;
     case 5: /* MMU Fault status / MPU access permission.  */
commit 6cc7a3aee6259ca9d94312b1af0255c92a30fe34
Author: Peter Maydell <peter.maydell at linaro.org>
Date:   Wed Jun 20 11:57:12 2012 +0000

    target-arm: Convert generic timer cp15 regs
    
    Convert the (dummy) generic timer cp15 implementation.
    
    Signed-off-by: Peter Maydell <peter.maydell at linaro.org>

diff --git a/target-arm/helper.c b/target-arm/helper.c
index ebe6a55..2d58eb5 100644
--- a/target-arm/helper.c
+++ b/target-arm/helper.c
@@ -317,6 +317,14 @@ static const ARMCPRegInfo v6k_cp_reginfo[] = {
     REGINFO_SENTINEL
 };
 
+static const ARMCPRegInfo generic_timer_cp_reginfo[] = {
+    /* Dummy implementation: RAZ/WI the whole crn=14 space */
+    { .name = "GENERIC_TIMER", .cp = 15, .crn = 14,
+      .crm = CP_ANY, .opc1 = CP_ANY, .opc2 = CP_ANY,
+      .access = PL1_RW, .type = ARM_CP_CONST, .resetvalue = 0 },
+    REGINFO_SENTINEL
+};
+
 void register_cp_regs_for_features(ARMCPU *cpu)
 {
     /* Register all the coprocessor registers based on feature bits */
@@ -353,6 +361,9 @@ void register_cp_regs_for_features(ARMCPU *cpu)
     if (arm_feature(env, ARM_FEATURE_THUMB2EE)) {
         define_arm_cp_regs(cpu, t2ee_cp_reginfo);
     }
+    if (arm_feature(env, ARM_FEATURE_GENERIC_TIMER)) {
+        define_arm_cp_regs(cpu, generic_timer_cp_reginfo);
+    }
 }
 
 ARMCPU *cpu_arm_init(const char *cpu_model)
@@ -1720,12 +1731,6 @@ void HELPER(set_cp15)(CPUARMState *env, uint32_t insn, uint32_t val)
             goto bad_reg;
         }
         break;
-    case 14: /* Generic timer */
-        if (arm_feature(env, ARM_FEATURE_GENERIC_TIMER)) {
-            /* Dummy implementation: RAZ/WI for all */
-            break;
-        }
-        goto bad_reg;
     case 15: /* Implementation specific.  */
         if (arm_feature(env, ARM_FEATURE_XSCALE)) {
             if (op2 == 0 && crm == 1) {
@@ -2065,12 +2070,6 @@ uint32_t HELPER(get_cp15)(CPUARMState *env, uint32_t insn)
         default:
             goto bad_reg;
         }
-    case 14: /* Generic timer */
-        if (arm_feature(env, ARM_FEATURE_GENERIC_TIMER)) {
-            /* Dummy implementation: RAZ/WI for all */
-            return 0;
-        }
-        goto bad_reg;
     case 15: /* Implementation specific.  */
         if (arm_feature(env, ARM_FEATURE_XSCALE)) {
             if (op2 == 0 && crm == 1)
commit 200ac0ef87d3d076ccd5d738e4d1acb7f7b2879f
Author: Peter Maydell <peter.maydell at linaro.org>
Date:   Wed Jun 20 11:57:12 2012 +0000

    target-arm: Convert performance monitor registers
    
    Convert the v7 performance monitor cp15 registers to
    the new scheme.
    
    Signed-off-by: Peter Maydell <peter.maydell at linaro.org>

diff --git a/target-arm/cpu.c b/target-arm/cpu.c
index 1aff266..0098787 100644
--- a/target-arm/cpu.c
+++ b/target-arm/cpu.c
@@ -132,10 +132,6 @@ static void arm_cpu_reset(CPUState *s)
     }
     env->vfp.xregs[ARM_VFP_FPEXC] = 0;
     env->cp15.c2_base_mask = 0xffffc000u;
-    /* v7 performance monitor control register: same implementor
-     * field as main ID register, and we implement no event counters.
-     */
-    env->cp15.c9_pmcr = (cpu->midr & 0xff000000);
 #endif
     set_flush_to_zero(1, &env->vfp.standard_fp_status);
     set_flush_inputs_to_zero(1, &env->vfp.standard_fp_status);
diff --git a/target-arm/helper.c b/target-arm/helper.c
index d4c8a1c..ebe6a55 100644
--- a/target-arm/helper.c
+++ b/target-arm/helper.c
@@ -98,6 +98,97 @@ static const ARMCPRegInfo v6_cp_reginfo[] = {
     REGINFO_SENTINEL
 };
 
+static int pmreg_read(CPUARMState *env, const ARMCPRegInfo *ri,
+                      uint64_t *value)
+{
+    /* Generic performance monitor register read function for where
+     * user access may be allowed by PMUSERENR.
+     */
+    if (arm_current_pl(env) == 0 && !env->cp15.c9_pmuserenr) {
+        return EXCP_UDEF;
+    }
+    *value = CPREG_FIELD32(env, ri);
+    return 0;
+}
+
+static int pmcr_write(CPUARMState *env, const ARMCPRegInfo *ri,
+                      uint64_t value)
+{
+    if (arm_current_pl(env) == 0 && !env->cp15.c9_pmuserenr) {
+        return EXCP_UDEF;
+    }
+    /* only the DP, X, D and E bits are writable */
+    env->cp15.c9_pmcr &= ~0x39;
+    env->cp15.c9_pmcr |= (value & 0x39);
+    return 0;
+}
+
+static int pmcntenset_write(CPUARMState *env, const ARMCPRegInfo *ri,
+                            uint64_t value)
+{
+    if (arm_current_pl(env) == 0 && !env->cp15.c9_pmuserenr) {
+        return EXCP_UDEF;
+    }
+    value &= (1 << 31);
+    env->cp15.c9_pmcnten |= value;
+    return 0;
+}
+
+static int pmcntenclr_write(CPUARMState *env, const ARMCPRegInfo *ri,
+                            uint64_t value)
+{
+    if (arm_current_pl(env) == 0 && !env->cp15.c9_pmuserenr) {
+        return EXCP_UDEF;
+    }
+    value &= (1 << 31);
+    env->cp15.c9_pmcnten &= ~value;
+    return 0;
+}
+
+static int pmovsr_write(CPUARMState *env, const ARMCPRegInfo *ri,
+                        uint64_t value)
+{
+    if (arm_current_pl(env) == 0 && !env->cp15.c9_pmuserenr) {
+        return EXCP_UDEF;
+    }
+    env->cp15.c9_pmovsr &= ~value;
+    return 0;
+}
+
+static int pmxevtyper_write(CPUARMState *env, const ARMCPRegInfo *ri,
+                            uint64_t value)
+{
+    if (arm_current_pl(env) == 0 && !env->cp15.c9_pmuserenr) {
+        return EXCP_UDEF;
+    }
+    env->cp15.c9_pmxevtyper = value & 0xff;
+    return 0;
+}
+
+static int pmuserenr_write(CPUARMState *env, const ARMCPRegInfo *ri,
+                            uint64_t value)
+{
+    env->cp15.c9_pmuserenr = value & 1;
+    return 0;
+}
+
+static int pmintenset_write(CPUARMState *env, const ARMCPRegInfo *ri,
+                            uint64_t value)
+{
+    /* We have no event counters so only the C bit can be changed */
+    value &= (1 << 31);
+    env->cp15.c9_pminten |= value;
+    return 0;
+}
+
+static int pmintenclr_write(CPUARMState *env, const ARMCPRegInfo *ri,
+                            uint64_t value)
+{
+    value &= (1 << 31);
+    env->cp15.c9_pminten &= ~value;
+    return 0;
+}
+
 static const ARMCPRegInfo v7_cp_reginfo[] = {
     /* DBGDRAR, DBGDSAR: always RAZ since we don't implement memory mapped
      * debug components
@@ -109,6 +200,62 @@ static const ARMCPRegInfo v7_cp_reginfo[] = {
     /* the old v6 WFI, UNPREDICTABLE in v7 but we choose to NOP */
     { .name = "NOP", .cp = 15, .crn = 7, .crm = 0, .opc1 = 0, .opc2 = 4,
       .access = PL1_W, .type = ARM_CP_NOP },
+    /* Performance monitors are implementation defined in v7,
+     * but with an ARM recommended set of registers, which we
+     * follow (although we don't actually implement any counters)
+     *
+     * Performance registers fall into three categories:
+     *  (a) always UNDEF in PL0, RW in PL1 (PMINTENSET, PMINTENCLR)
+     *  (b) RO in PL0 (ie UNDEF on write), RW in PL1 (PMUSERENR)
+     *  (c) UNDEF in PL0 if PMUSERENR.EN==0, otherwise accessible (all others)
+     * For the cases controlled by PMUSERENR we must set .access to PL0_RW
+     * or PL0_RO as appropriate and then check PMUSERENR in the helper fn.
+     */
+    { .name = "PMCNTENSET", .cp = 15, .crn = 9, .crm = 12, .opc1 = 0, .opc2 = 1,
+      .access = PL0_RW, .resetvalue = 0,
+      .fieldoffset = offsetof(CPUARMState, cp15.c9_pmcnten),
+      .readfn = pmreg_read, .writefn = pmcntenset_write },
+    { .name = "PMCNTENCLR", .cp = 15, .crn = 9, .crm = 12, .opc1 = 0, .opc2 = 2,
+      .access = PL0_RW, .fieldoffset = offsetof(CPUARMState, cp15.c9_pmcnten),
+      .readfn = pmreg_read, .writefn = pmcntenclr_write },
+    { .name = "PMOVSR", .cp = 15, .crn = 9, .crm = 12, .opc1 = 0, .opc2 = 3,
+      .access = PL0_RW, .fieldoffset = offsetof(CPUARMState, cp15.c9_pmovsr),
+      .readfn = pmreg_read, .writefn = pmovsr_write },
+    /* Unimplemented so WI. Strictly speaking write accesses in PL0 should
+     * respect PMUSERENR.
+     */
+    { .name = "PMSWINC", .cp = 15, .crn = 9, .crm = 12, .opc1 = 0, .opc2 = 4,
+      .access = PL0_W, .type = ARM_CP_NOP },
+    /* Since we don't implement any events, writing to PMSELR is UNPREDICTABLE.
+     * We choose to RAZ/WI. XXX should respect PMUSERENR.
+     */
+    { .name = "PMSELR", .cp = 15, .crn = 9, .crm = 12, .opc1 = 0, .opc2 = 5,
+      .access = PL0_RW, .type = ARM_CP_CONST, .resetvalue = 0 },
+    /* Unimplemented, RAZ/WI. XXX PMUSERENR */
+    { .name = "PMCCNTR", .cp = 15, .crn = 9, .crm = 13, .opc1 = 0, .opc2 = 0,
+      .access = PL0_RW, .type = ARM_CP_CONST, .resetvalue = 0 },
+    { .name = "PMXEVTYPER", .cp = 15, .crn = 9, .crm = 13, .opc1 = 0, .opc2 = 1,
+      .access = PL0_RW,
+      .fieldoffset = offsetof(CPUARMState, cp15.c9_pmxevtyper),
+      .readfn = pmreg_read, .writefn = pmxevtyper_write },
+    /* Unimplemented, RAZ/WI. XXX PMUSERENR */
+    { .name = "PMXEVCNTR", .cp = 15, .crn = 9, .crm = 13, .opc1 = 0, .opc2 = 2,
+      .access = PL0_RW, .type = ARM_CP_CONST, .resetvalue = 0 },
+    { .name = "PMUSERENR", .cp = 15, .crn = 9, .crm = 14, .opc1 = 0, .opc2 = 0,
+      .access = PL0_R | PL1_RW,
+      .fieldoffset = offsetof(CPUARMState, cp15.c9_pmuserenr),
+      .resetvalue = 0,
+      .writefn = pmuserenr_write },
+    { .name = "PMINTENSET", .cp = 15, .crn = 9, .crm = 14, .opc1 = 0, .opc2 = 1,
+      .access = PL1_RW,
+      .fieldoffset = offsetof(CPUARMState, cp15.c9_pminten),
+      .resetvalue = 0,
+      .writefn = pmintenset_write },
+    { .name = "PMINTENCLR", .cp = 15, .crn = 9, .crm = 14, .opc1 = 0, .opc2 = 2,
+      .access = PL1_RW,
+      .fieldoffset = offsetof(CPUARMState, cp15.c9_pminten),
+      .resetvalue = 0,
+      .writefn = pmintenclr_write },
     REGINFO_SENTINEL
 };
 
@@ -189,6 +336,16 @@ void register_cp_regs_for_features(ARMCPU *cpu)
         define_arm_cp_regs(cpu, v6k_cp_reginfo);
     }
     if (arm_feature(env, ARM_FEATURE_V7)) {
+        /* v7 performance monitor control register: same implementor
+         * field as main ID register, and we implement no event counters.
+         */
+        ARMCPRegInfo pmcr = {
+            .name = "PMCR", .cp = 15, .crn = 9, .crm = 12, .opc1 = 0, .opc2 = 0,
+            .access = PL0_RW, .resetvalue = cpu->midr & 0xff000000,
+            .fieldoffset = offsetof(CPUARMState, cp15.c9_pmcr),
+            .readfn = pmreg_read, .writefn = pmcr_write
+        };
+        define_one_arm_cp_reg(cpu, &pmcr);
         define_arm_cp_regs(cpu, v7_cp_reginfo);
     } else {
         define_arm_cp_regs(cpu, not_v7_cp_reginfo);
@@ -1533,81 +1690,6 @@ void HELPER(set_cp15)(CPUARMState *env, uint32_t insn, uint32_t val)
         case 1: /* TCM memory region registers.  */
             /* Not implemented.  */
             goto bad_reg;
-        case 12: /* Performance monitor control */
-            /* Performance monitors are implementation defined in v7,
-             * but with an ARM recommended set of registers, which we
-             * follow (although we don't actually implement any counters)
-             */
-            if (!arm_feature(env, ARM_FEATURE_V7)) {
-                goto bad_reg;
-            }
-            switch (op2) {
-            case 0: /* performance monitor control register */
-                /* only the DP, X, D and E bits are writable */
-                env->cp15.c9_pmcr &= ~0x39;
-                env->cp15.c9_pmcr |= (val & 0x39);
-                break;
-            case 1: /* Count enable set register */
-                val &= (1 << 31);
-                env->cp15.c9_pmcnten |= val;
-                break;
-            case 2: /* Count enable clear */
-                val &= (1 << 31);
-                env->cp15.c9_pmcnten &= ~val;
-                break;
-            case 3: /* Overflow flag status */
-                env->cp15.c9_pmovsr &= ~val;
-                break;
-            case 4: /* Software increment */
-                /* RAZ/WI since we don't implement the software-count event */
-                break;
-            case 5: /* Event counter selection register */
-                /* Since we don't implement any events, writing to this register
-                 * is actually UNPREDICTABLE. So we choose to RAZ/WI.
-                 */
-                break;
-            default:
-                goto bad_reg;
-            }
-            break;
-        case 13: /* Performance counters */
-            if (!arm_feature(env, ARM_FEATURE_V7)) {
-                goto bad_reg;
-            }
-            switch (op2) {
-            case 0: /* Cycle count register: not implemented, so RAZ/WI */
-                break;
-            case 1: /* Event type select */
-                env->cp15.c9_pmxevtyper = val & 0xff;
-                break;
-            case 2: /* Event count register */
-                /* Unimplemented (we have no events), RAZ/WI */
-                break;
-            default:
-                goto bad_reg;
-            }
-            break;
-        case 14: /* Performance monitor control */
-            if (!arm_feature(env, ARM_FEATURE_V7)) {
-                goto bad_reg;
-            }
-            switch (op2) {
-            case 0: /* user enable */
-                env->cp15.c9_pmuserenr = val & 1;
-                /* changes access rights for cp registers, so flush tbs */
-                tb_flush(env);
-                break;
-            case 1: /* interrupt enable set */
-                /* We have no event counters so only the C bit can be changed */
-                val &= (1 << 31);
-                env->cp15.c9_pminten |= val;
-                break;
-            case 2: /* interrupt enable clear */
-                val &= (1 << 31);
-                env->cp15.c9_pminten &= ~val;
-                break;
-            }
-            break;
         default:
             goto bad_reg;
         }
@@ -1964,51 +2046,6 @@ uint32_t HELPER(get_cp15)(CPUARMState *env, uint32_t insn)
                 goto bad_reg;
             }
             break;
-        case 12: /* Performance monitor control */
-            if (!arm_feature(env, ARM_FEATURE_V7)) {
-                goto bad_reg;
-            }
-            switch (op2) {
-            case 0: /* performance monitor control register */
-                return env->cp15.c9_pmcr;
-            case 1: /* count enable set */
-            case 2: /* count enable clear */
-                return env->cp15.c9_pmcnten;
-            case 3: /* overflow flag status */
-                return env->cp15.c9_pmovsr;
-            case 4: /* software increment */
-            case 5: /* event counter selection register */
-                return 0; /* Unimplemented, RAZ/WI */
-            default:
-                goto bad_reg;
-            }
-        case 13: /* Performance counters */
-            if (!arm_feature(env, ARM_FEATURE_V7)) {
-                goto bad_reg;
-            }
-            switch (op2) {
-            case 1: /* Event type select */
-                return env->cp15.c9_pmxevtyper;
-            case 0: /* Cycle count register */
-            case 2: /* Event count register */
-                /* Unimplemented, so RAZ/WI */
-                return 0;
-            default:
-                goto bad_reg;
-            }
-        case 14: /* Performance monitor control */
-            if (!arm_feature(env, ARM_FEATURE_V7)) {
-                goto bad_reg;
-            }
-            switch (op2) {
-            case 0: /* user enable */
-                return env->cp15.c9_pmuserenr;
-            case 1: /* interrupt enable set */
-            case 2: /* interrupt enable clear */
-                return env->cp15.c9_pminten;
-            default:
-                goto bad_reg;
-            }
         default:
             goto bad_reg;
         }
diff --git a/target-arm/translate.c b/target-arm/translate.c
index e6b0d87..f4e9435 100644
--- a/target-arm/translate.c
+++ b/target-arm/translate.c
@@ -2439,30 +2439,6 @@ static int disas_dsp_insn(CPUARMState *env, DisasContext *s, uint32_t insn)
     return 1;
 }
 
-static int cp15_user_ok(CPUARMState *env, uint32_t insn)
-{
-    int cpn = (insn >> 16) & 0xf;
-    int cpm = insn & 0xf;
-    int op = ((insn >> 5) & 7) | ((insn >> 18) & 0x38);
-
-    if (arm_feature(env, ARM_FEATURE_V7) && cpn == 9) {
-        /* Performance monitor registers fall into three categories:
-         *  (a) always UNDEF in usermode
-         *  (b) UNDEF only if PMUSERENR.EN is 0
-         *  (c) always read OK and UNDEF on write (PMUSERENR only)
-         */
-        if ((cpm == 12 && (op < 6)) ||
-            (cpm == 13 && (op < 3))) {
-            return env->cp15.c9_pmuserenr;
-        } else if (cpm == 14 && op == 0 && (insn & ARM_CP_RW_BIT)) {
-            /* PMUSERENR, read only */
-            return 1;
-        }
-        return 0;
-    }
-    return 0;
-}
-
 /* Disassemble system coprocessor (cp15) instruction.  Return nonzero if
    instruction is not defined.  */
 static int disas_cp15_insn(CPUARMState *env, DisasContext *s, uint32_t insn)
@@ -2487,7 +2463,7 @@ static int disas_cp15_insn(CPUARMState *env, DisasContext *s, uint32_t insn)
         return 1;
     }
 
-    if (IS_USER(s) && !cp15_user_ok(env, insn)) {
+    if (IS_USER(s)) {
         return 1;
     }
 
commit 4d31c5967979d11c22c69a52beb1a03cab377e4f
Author: Peter Maydell <peter.maydell at linaro.org>
Date:   Wed Jun 20 11:57:11 2012 +0000

    target-arm: Convert TLS registers
    
    Convert TLS registers to the new cp15 framework
    
    Signed-off-by: Peter Maydell <peter.maydell at linaro.org>

diff --git a/target-arm/helper.c b/target-arm/helper.c
index c7addea..d4c8a1c 100644
--- a/target-arm/helper.c
+++ b/target-arm/helper.c
@@ -154,6 +154,22 @@ static const ARMCPRegInfo t2ee_cp_reginfo[] = {
     REGINFO_SENTINEL
 };
 
+static const ARMCPRegInfo v6k_cp_reginfo[] = {
+    { .name = "TPIDRURW", .cp = 15, .crn = 13, .crm = 0, .opc1 = 0, .opc2 = 2,
+      .access = PL0_RW,
+      .fieldoffset = offsetof(CPUARMState, cp15.c13_tls1),
+      .resetvalue = 0 },
+    { .name = "TPIDRURO", .cp = 15, .crn = 13, .crm = 0, .opc1 = 0, .opc2 = 3,
+      .access = PL0_R|PL1_W,
+      .fieldoffset = offsetof(CPUARMState, cp15.c13_tls2),
+      .resetvalue = 0 },
+    { .name = "TPIDRPRW", .cp = 15, .crn = 13, .crm = 0, .opc1 = 0, .opc2 = 4,
+      .access = PL1_RW,
+      .fieldoffset = offsetof(CPUARMState, cp15.c13_tls3),
+      .resetvalue = 0 },
+    REGINFO_SENTINEL
+};
+
 void register_cp_regs_for_features(ARMCPU *cpu)
 {
     /* Register all the coprocessor registers based on feature bits */
@@ -169,6 +185,9 @@ void register_cp_regs_for_features(ARMCPU *cpu)
     } else {
         define_arm_cp_regs(cpu, not_v6_cp_reginfo);
     }
+    if (arm_feature(env, ARM_FEATURE_V6K)) {
+        define_arm_cp_regs(cpu, v6k_cp_reginfo);
+    }
     if (arm_feature(env, ARM_FEATURE_V7)) {
         define_arm_cp_regs(cpu, v7_cp_reginfo);
     } else {
diff --git a/target-arm/translate.c b/target-arm/translate.c
index a4429ea..e6b0d87 100644
--- a/target-arm/translate.c
+++ b/target-arm/translate.c
@@ -2460,64 +2460,9 @@ static int cp15_user_ok(CPUARMState *env, uint32_t insn)
         }
         return 0;
     }
-
-    if (cpn == 13 && cpm == 0) {
-        /* TLS register.  */
-        if (op == 2 || (op == 3 && (insn & ARM_CP_RW_BIT)))
-            return 1;
-    }
     return 0;
 }
 
-static int cp15_tls_load_store(CPUARMState *env, DisasContext *s, uint32_t insn, uint32_t rd)
-{
-    TCGv tmp;
-    int cpn = (insn >> 16) & 0xf;
-    int cpm = insn & 0xf;
-    int op = ((insn >> 5) & 7) | ((insn >> 18) & 0x38);
-
-    if (!arm_feature(env, ARM_FEATURE_V6K))
-        return 0;
-
-    if (!(cpn == 13 && cpm == 0))
-        return 0;
-
-    if (insn & ARM_CP_RW_BIT) {
-        switch (op) {
-        case 2:
-            tmp = load_cpu_field(cp15.c13_tls1);
-            break;
-        case 3:
-            tmp = load_cpu_field(cp15.c13_tls2);
-            break;
-        case 4:
-            tmp = load_cpu_field(cp15.c13_tls3);
-            break;
-        default:
-            return 0;
-        }
-        store_reg(s, rd, tmp);
-
-    } else {
-        tmp = load_reg(s, rd);
-        switch (op) {
-        case 2:
-            store_cpu_field(tmp, cp15.c13_tls1);
-            break;
-        case 3:
-            store_cpu_field(tmp, cp15.c13_tls2);
-            break;
-        case 4:
-            store_cpu_field(tmp, cp15.c13_tls3);
-            break;
-        default:
-            tcg_temp_free_i32(tmp);
-            return 0;
-        }
-    }
-    return 1;
-}
-
 /* Disassemble system coprocessor (cp15) instruction.  Return nonzero if
    instruction is not defined.  */
 static int disas_cp15_insn(CPUARMState *env, DisasContext *s, uint32_t insn)
@@ -2548,9 +2493,6 @@ static int disas_cp15_insn(CPUARMState *env, DisasContext *s, uint32_t insn)
 
     rd = (insn >> 12) & 0xf;
 
-    if (cp15_tls_load_store(env, s, insn, rd))
-        return 0;
-
     tmp2 = tcg_const_i32(insn);
     if (insn & ARM_CP_RW_BIT) {
         tmp = tcg_temp_new_i32();
commit 7d57f40877675db150d8afbf781de385c3828012
Author: Peter Maydell <peter.maydell at linaro.org>
Date:   Wed Jun 20 11:57:11 2012 +0000

    target-arm: Convert WFI/barriers special cases to cp_reginfo
    
    Convert the various WFI and barrier instruction special cases to use
    cp_reginfo infrastructure.
    
    Signed-off-by: Peter Maydell <peter.maydell at linaro.org>

diff --git a/target-arm/helper.c b/target-arm/helper.c
index c003fe0..c7addea 100644
--- a/target-arm/helper.c
+++ b/target-arm/helper.c
@@ -66,6 +66,38 @@ static const ARMCPRegInfo cp_reginfo[] = {
     REGINFO_SENTINEL
 };
 
+static const ARMCPRegInfo not_v6_cp_reginfo[] = {
+    /* Not all pre-v6 cores implemented this WFI, so this is slightly
+     * over-broad.
+     */
+    { .name = "WFI_v5", .cp = 15, .crn = 7, .crm = 8, .opc1 = 0, .opc2 = 2,
+      .access = PL1_W, .type = ARM_CP_WFI },
+    REGINFO_SENTINEL
+};
+
+static const ARMCPRegInfo not_v7_cp_reginfo[] = {
+    /* Standard v6 WFI (also used in some pre-v6 cores); not in v7 (which
+     * is UNPREDICTABLE; we choose to NOP as most implementations do).
+     */
+    { .name = "WFI_v6", .cp = 15, .crn = 7, .crm = 0, .opc1 = 0, .opc2 = 4,
+      .access = PL1_W, .type = ARM_CP_WFI },
+    REGINFO_SENTINEL
+};
+
+static const ARMCPRegInfo v6_cp_reginfo[] = {
+    /* prefetch by MVA in v6, NOP in v7 */
+    { .name = "MVA_prefetch",
+      .cp = 15, .crn = 7, .crm = 13, .opc1 = 0, .opc2 = 1,
+      .access = PL1_W, .type = ARM_CP_NOP },
+    { .name = "ISB", .cp = 15, .crn = 7, .crm = 5, .opc1 = 0, .opc2 = 4,
+      .access = PL0_W, .type = ARM_CP_NOP },
+    { .name = "ISB", .cp = 15, .crn = 7, .crm = 10, .opc1 = 0, .opc2 = 4,
+      .access = PL0_W, .type = ARM_CP_NOP },
+    { .name = "ISB", .cp = 15, .crn = 7, .crm = 10, .opc1 = 0, .opc2 = 5,
+      .access = PL0_W, .type = ARM_CP_NOP },
+    REGINFO_SENTINEL
+};
+
 static const ARMCPRegInfo v7_cp_reginfo[] = {
     /* DBGDRAR, DBGDSAR: always RAZ since we don't implement memory mapped
      * debug components
@@ -74,6 +106,9 @@ static const ARMCPRegInfo v7_cp_reginfo[] = {
       .access = PL0_R, .type = ARM_CP_CONST, .resetvalue = 0 },
     { .name = "DBGDRAR", .cp = 14, .crn = 2, .crm = 0, .opc1 = 0, .opc2 = 0,
       .access = PL0_R, .type = ARM_CP_CONST, .resetvalue = 0 },
+    /* the old v6 WFI, UNPREDICTABLE in v7 but we choose to NOP */
+    { .name = "NOP", .cp = 15, .crn = 7, .crm = 0, .opc1 = 0, .opc2 = 4,
+      .access = PL1_W, .type = ARM_CP_NOP },
     REGINFO_SENTINEL
 };
 
@@ -129,8 +164,15 @@ void register_cp_regs_for_features(ARMCPU *cpu)
     }
 
     define_arm_cp_regs(cpu, cp_reginfo);
+    if (arm_feature(env, ARM_FEATURE_V6)) {
+        define_arm_cp_regs(cpu, v6_cp_reginfo);
+    } else {
+        define_arm_cp_regs(cpu, not_v6_cp_reginfo);
+    }
     if (arm_feature(env, ARM_FEATURE_V7)) {
         define_arm_cp_regs(cpu, v7_cp_reginfo);
+    } else {
+        define_arm_cp_regs(cpu, not_v7_cp_reginfo);
     }
     if (arm_feature(env, ARM_FEATURE_THUMB2EE)) {
         define_arm_cp_regs(cpu, t2ee_cp_reginfo);
diff --git a/target-arm/translate.c b/target-arm/translate.c
index ba1bb94..a4429ea 100644
--- a/target-arm/translate.c
+++ b/target-arm/translate.c
@@ -2541,57 +2541,6 @@ static int disas_cp15_insn(CPUARMState *env, DisasContext *s, uint32_t insn)
         /* cdp */
         return 1;
     }
-    /* We special case a number of cp15 instructions which were used
-     * for things which are real instructions in ARMv7. This allows
-     * them to work in linux-user mode which doesn't provide functional
-     * get_cp15/set_cp15 helpers, and is more efficient anyway.
-     */
-    switch ((insn & 0x0fff0fff)) {
-    case 0x0e070f90:
-        /* 0,c7,c0,4: Standard v6 WFI (also used in some pre-v6 cores).
-         * In v7, this must NOP.
-         */
-        if (IS_USER(s)) {
-            return 1;
-        }
-        if (!arm_feature(env, ARM_FEATURE_V7)) {
-            /* Wait for interrupt.  */
-            gen_set_pc_im(s->pc);
-            s->is_jmp = DISAS_WFI;
-        }
-        return 0;
-    case 0x0e070f58:
-        /* 0,c7,c8,2: Not all pre-v6 cores implemented this WFI,
-         * so this is slightly over-broad.
-         */
-        if (!IS_USER(s) && !arm_feature(env, ARM_FEATURE_V6)) {
-            /* Wait for interrupt.  */
-            gen_set_pc_im(s->pc);
-            s->is_jmp = DISAS_WFI;
-            return 0;
-        }
-        /* Otherwise continue to handle via helper function.
-         * In particular, on v7 and some v6 cores this is one of
-         * the VA-PA registers.
-         */
-        break;
-    case 0x0e070f3d:
-        /* 0,c7,c13,1: prefetch-by-MVA in v6, NOP in v7 */
-        if (arm_feature(env, ARM_FEATURE_V6)) {
-            return IS_USER(s) ? 1 : 0;
-        }
-        break;
-    case 0x0e070f95: /* 0,c7,c5,4 : ISB */
-    case 0x0e070f9a: /* 0,c7,c10,4: DSB */
-    case 0x0e070fba: /* 0,c7,c10,5: DMB */
-        /* Barriers in both v6 and v7 */
-        if (arm_feature(env, ARM_FEATURE_V6)) {
-            return 0;
-        }
-        break;
-    default:
-        break;
-    }
 
     if (IS_USER(s) && !cp15_user_ok(env, insn)) {
         return 1;
commit c326b9796fe1f8661310ff9b9be4e38148b8baa4
Author: Peter Maydell <peter.maydell at linaro.org>
Date:   Wed Jun 20 11:57:10 2012 +0000

    target-arm: Convert TEECR, TEEHBR to new scheme
    
    Convert the THUMB2EE cp14 registers TEECR and TEEHBR to
    use arm_cp_reginfo.
    
    Signed-off-by: Peter Maydell <peter.maydell at linaro.org>

diff --git a/target-arm/helper.c b/target-arm/helper.c
index a750637..c003fe0 100644
--- a/target-arm/helper.c
+++ b/target-arm/helper.c
@@ -77,6 +77,48 @@ static const ARMCPRegInfo v7_cp_reginfo[] = {
     REGINFO_SENTINEL
 };
 
+static int teecr_write(CPUARMState *env, const ARMCPRegInfo *ri, uint64_t value)
+{
+    value &= 1;
+    env->teecr = value;
+    return 0;
+}
+
+static int teehbr_read(CPUARMState *env, const ARMCPRegInfo *ri,
+                       uint64_t *value)
+{
+    /* This is a helper function because the user access rights
+     * depend on the value of the TEECR.
+     */
+    if (arm_current_pl(env) == 0 && (env->teecr & 1)) {
+        return EXCP_UDEF;
+    }
+    *value = env->teehbr;
+    return 0;
+}
+
+static int teehbr_write(CPUARMState *env, const ARMCPRegInfo *ri,
+                        uint64_t value)
+{
+    if (arm_current_pl(env) == 0 && (env->teecr & 1)) {
+        return EXCP_UDEF;
+    }
+    env->teehbr = value;
+    return 0;
+}
+
+static const ARMCPRegInfo t2ee_cp_reginfo[] = {
+    { .name = "TEECR", .cp = 14, .crn = 0, .crm = 0, .opc1 = 6, .opc2 = 0,
+      .access = PL1_RW, .fieldoffset = offsetof(CPUARMState, teecr),
+      .resetvalue = 0,
+      .writefn = teecr_write },
+    { .name = "TEEHBR", .cp = 14, .crn = 1, .crm = 0, .opc1 = 6, .opc2 = 0,
+      .access = PL0_RW, .fieldoffset = offsetof(CPUARMState, teehbr),
+      .resetvalue = 0,
+      .readfn = teehbr_read, .writefn = teehbr_write },
+    REGINFO_SENTINEL
+};
+
 void register_cp_regs_for_features(ARMCPU *cpu)
 {
     /* Register all the coprocessor registers based on feature bits */
@@ -90,6 +132,9 @@ void register_cp_regs_for_features(ARMCPU *cpu)
     if (arm_feature(env, ARM_FEATURE_V7)) {
         define_arm_cp_regs(cpu, v7_cp_reginfo);
     }
+    if (arm_feature(env, ARM_FEATURE_THUMB2EE)) {
+        define_arm_cp_regs(cpu, t2ee_cp_reginfo);
+    }
 }
 
 ARMCPU *cpu_arm_init(const char *cpu_model)
@@ -2951,12 +2996,3 @@ float64 VFP_HELPER(muladd, d)(float64 a, float64 b, float64 c, void *fpstp)
     float_status *fpst = fpstp;
     return float64_muladd(a, b, c, 0, fpst);
 }
-
-void HELPER(set_teecr)(CPUARMState *env, uint32_t val)
-{
-    val &= 1;
-    if (env->teecr != val) {
-        env->teecr = val;
-        tb_flush(env);
-    }
-}
diff --git a/target-arm/helper.h b/target-arm/helper.h
index bb6b85d..a0034ae 100644
--- a/target-arm/helper.h
+++ b/target-arm/helper.h
@@ -461,8 +461,6 @@ DEF_HELPER_3(iwmmxt_muladdsl, i64, i64, i32, i32)
 DEF_HELPER_3(iwmmxt_muladdsw, i64, i64, i32, i32)
 DEF_HELPER_3(iwmmxt_muladdswl, i64, i64, i32, i32)
 
-DEF_HELPER_2(set_teecr, void, env, i32)
-
 DEF_HELPER_3(neon_unzip8, void, env, i32, i32)
 DEF_HELPER_3(neon_unzip16, void, env, i32, i32)
 DEF_HELPER_3(neon_qunzip8, void, env, i32, i32)
diff --git a/target-arm/translate.c b/target-arm/translate.c
index d9fa431..ba1bb94 100644
--- a/target-arm/translate.c
+++ b/target-arm/translate.c
@@ -6355,67 +6355,6 @@ static int disas_neon_data_insn(CPUARMState * env, DisasContext *s, uint32_t ins
     return 0;
 }
 
-static int disas_cp14_read(CPUARMState * env, DisasContext *s, uint32_t insn)
-{
-    int crn = (insn >> 16) & 0xf;
-    int crm = insn & 0xf;
-    int op1 = (insn >> 21) & 7;
-    int op2 = (insn >> 5) & 7;
-    int rt = (insn >> 12) & 0xf;
-    TCGv tmp;
-
-    if (arm_feature(env, ARM_FEATURE_THUMB2EE)) {
-        if (op1 == 6 && crn == 0 && crm == 0 && op2 == 0) {
-            /* TEECR */
-            if (IS_USER(s))
-                return 1;
-            tmp = load_cpu_field(teecr);
-            store_reg(s, rt, tmp);
-            return 0;
-        }
-        if (op1 == 6 && crn == 1 && crm == 0 && op2 == 0) {
-            /* TEEHBR */
-            if (IS_USER(s) && (env->teecr & 1))
-                return 1;
-            tmp = load_cpu_field(teehbr);
-            store_reg(s, rt, tmp);
-            return 0;
-        }
-    }
-    return 1;
-}
-
-static int disas_cp14_write(CPUARMState * env, DisasContext *s, uint32_t insn)
-{
-    int crn = (insn >> 16) & 0xf;
-    int crm = insn & 0xf;
-    int op1 = (insn >> 21) & 7;
-    int op2 = (insn >> 5) & 7;
-    int rt = (insn >> 12) & 0xf;
-    TCGv tmp;
-
-    if (arm_feature(env, ARM_FEATURE_THUMB2EE)) {
-        if (op1 == 6 && crn == 0 && crm == 0 && op2 == 0) {
-            /* TEECR */
-            if (IS_USER(s))
-                return 1;
-            tmp = load_reg(s, rt);
-            gen_helper_set_teecr(cpu_env, tmp);
-            tcg_temp_free_i32(tmp);
-            return 0;
-        }
-        if (op1 == 6 && crn == 1 && crm == 0 && op2 == 0) {
-            /* TEEHBR */
-            if (IS_USER(s) && (env->teecr & 1))
-                return 1;
-            tmp = load_reg(s, rt);
-            store_cpu_field(tmp, teehbr);
-            return 0;
-        }
-    }
-    return 1;
-}
-
 static int disas_coproc_insn(CPUARMState * env, DisasContext *s, uint32_t insn)
 {
     int cpnum, is64, crn, crm, opc1, opc2, isread, rt, rt2;
@@ -6591,11 +6530,6 @@ static int disas_coproc_insn(CPUARMState * env, DisasContext *s, uint32_t insn)
      * to ARMCPRegInfo.
      */
     switch (cpnum) {
-    case 14:
-        if (insn & (1 << 20))
-            return disas_cp14_read(env, s, insn);
-        else
-            return disas_cp14_write(env, s, insn);
     case 15:
 	return disas_cp15_insn (env, s, insn);
     default:
commit e9aa6c21483bc50767132c305284cd5446001df7
Author: Peter Maydell <peter.maydell at linaro.org>
Date:   Wed Jun 20 11:57:09 2012 +0000

    target-arm: Convert debug registers to cp_reginfo
    
    Convert the cp14 debug registers (DBGDIDR, DBGDRAR, DBGDSAR) to the
    cp_reginfo scheme.
    
    Signed-off-by: Peter Maydell <peter.maydell at linaro.org>

diff --git a/target-arm/helper.c b/target-arm/helper.c
index f7c9a3a..a750637 100644
--- a/target-arm/helper.c
+++ b/target-arm/helper.c
@@ -56,6 +56,27 @@ static int vfp_gdb_set_reg(CPUARMState *env, uint8_t *buf, int reg)
     return 0;
 }
 
+static const ARMCPRegInfo cp_reginfo[] = {
+    /* DBGDIDR: just RAZ. In particular this means the "debug architecture
+     * version" bits will read as a reserved value, which should cause
+     * Linux to not try to use the debug hardware.
+     */
+    { .name = "DBGDIDR", .cp = 14, .crn = 0, .crm = 0, .opc1 = 0, .opc2 = 0,
+      .access = PL0_R, .type = ARM_CP_CONST, .resetvalue = 0 },
+    REGINFO_SENTINEL
+};
+
+static const ARMCPRegInfo v7_cp_reginfo[] = {
+    /* DBGDRAR, DBGDSAR: always RAZ since we don't implement memory mapped
+     * debug components
+     */
+    { .name = "DBGDRAR", .cp = 14, .crn = 1, .crm = 0, .opc1 = 0, .opc2 = 0,
+      .access = PL0_R, .type = ARM_CP_CONST, .resetvalue = 0 },
+    { .name = "DBGDRAR", .cp = 14, .crn = 2, .crm = 0, .opc1 = 0, .opc2 = 0,
+      .access = PL0_R, .type = ARM_CP_CONST, .resetvalue = 0 },
+    REGINFO_SENTINEL
+};
+
 void register_cp_regs_for_features(ARMCPU *cpu)
 {
     /* Register all the coprocessor registers based on feature bits */
@@ -65,6 +86,10 @@ void register_cp_regs_for_features(ARMCPU *cpu)
         return;
     }
 
+    define_arm_cp_regs(cpu, cp_reginfo);
+    if (arm_feature(env, ARM_FEATURE_V7)) {
+        define_arm_cp_regs(cpu, v7_cp_reginfo);
+    }
 }
 
 ARMCPU *cpu_arm_init(const char *cpu_model)
diff --git a/target-arm/translate.c b/target-arm/translate.c
index 75e464d..d9fa431 100644
--- a/target-arm/translate.c
+++ b/target-arm/translate.c
@@ -6364,34 +6364,6 @@ static int disas_cp14_read(CPUARMState * env, DisasContext *s, uint32_t insn)
     int rt = (insn >> 12) & 0xf;
     TCGv tmp;
 
-    /* Minimal set of debug registers, since we don't support debug */
-    if (op1 == 0 && crn == 0 && op2 == 0) {
-        switch (crm) {
-        case 0:
-            /* DBGDIDR: just RAZ. In particular this means the
-             * "debug architecture version" bits will read as
-             * a reserved value, which should cause Linux to
-             * not try to use the debug hardware.
-             */
-            tmp = tcg_const_i32(0);
-            store_reg(s, rt, tmp);
-            return 0;
-        case 1:
-        case 2:
-            /* DBGDRAR and DBGDSAR: v7 only. Always RAZ since we
-             * don't implement memory mapped debug components
-             */
-            if (ENABLE_ARCH_7) {
-                tmp = tcg_const_i32(0);
-                store_reg(s, rt, tmp);
-                return 0;
-            }
-            break;
-        default:
-            break;
-        }
-    }
-
     if (arm_feature(env, ARM_FEATURE_THUMB2EE)) {
         if (op1 == 6 && crn == 0 && crm == 0 && op2 == 0) {
             /* TEECR */
commit 2ceb98c0079a68078947c222111238c7c7ae89b5
Author: Peter Maydell <peter.maydell at linaro.org>
Date:   Wed Jun 20 11:57:09 2012 +0000

    target-arm: Add register_cp_regs_for_features()
    
    Add new function register_cp_regs_for_features() as a place to
    register coprocessor registers dependent on feature flags.
    
    Signed-off-by: Peter Maydell <peter.maydell at linaro.org>

diff --git a/target-arm/cpu-qom.h b/target-arm/cpu-qom.h
index 848ac2f..4ccfc89 100644
--- a/target-arm/cpu-qom.h
+++ b/target-arm/cpu-qom.h
@@ -107,5 +107,6 @@ static inline ARMCPU *arm_env_get_cpu(CPUARMState *env)
 #define ENV_GET_CPU(e) CPU(arm_env_get_cpu(e))
 
 void arm_cpu_realize(ARMCPU *cpu);
+void register_cp_regs_for_features(ARMCPU *cpu);
 
 #endif
diff --git a/target-arm/cpu.c b/target-arm/cpu.c
index 6456a3d..1aff266 100644
--- a/target-arm/cpu.c
+++ b/target-arm/cpu.c
@@ -216,6 +216,8 @@ void arm_cpu_realize(ARMCPU *cpu)
     if (arm_feature(env, ARM_FEATURE_VFP3)) {
         set_feature(env, ARM_FEATURE_VFP);
     }
+
+    register_cp_regs_for_features(cpu);
 }
 
 /* CPU models */
diff --git a/target-arm/helper.c b/target-arm/helper.c
index 57bb78b..f7c9a3a 100644
--- a/target-arm/helper.c
+++ b/target-arm/helper.c
@@ -56,6 +56,17 @@ static int vfp_gdb_set_reg(CPUARMState *env, uint8_t *buf, int reg)
     return 0;
 }
 
+void register_cp_regs_for_features(ARMCPU *cpu)
+{
+    /* Register all the coprocessor registers based on feature bits */
+    CPUARMState *env = &cpu->env;
+    if (arm_feature(env, ARM_FEATURE_M)) {
+        /* M profile has no coprocessor registers */
+        return;
+    }
+
+}
+
 ARMCPU *cpu_arm_init(const char *cpu_model)
 {
     ARMCPU *cpu;
commit e8070a23a8f9f6fa28ac1dcb4399c11492f18b10
Author: Peter Maydell <peter.maydell at linaro.org>
Date:   Wed Jun 20 11:57:08 2012 +0000

    target-arm: Remove old cpu_arm_set_cp_io infrastructure
    
    All the users of cpu_arm_set_cp_io have been converted, so we
    can remove it and the infrastructure it used.
    
    Signed-off-by: Peter Maydell <peter.maydell at linaro.org>

diff --git a/target-arm/cpu.h b/target-arm/cpu.h
index 6c7d3e7..a61cb07 100644
--- a/target-arm/cpu.h
+++ b/target-arm/cpu.h
@@ -228,12 +228,6 @@ typedef struct CPUARMState {
     /* Internal CPU feature flags.  */
     uint32_t features;
 
-    /* Coprocessor IO used by peripherals */
-    struct {
-        ARMReadCPFunc *cp_read;
-        ARMWriteCPFunc *cp_write;
-        void *opaque;
-    } cp[15];
     void *nvic;
     const struct arm_boot_info *boot_info;
 } CPUARMState;
@@ -406,10 +400,6 @@ void armv7m_nvic_set_pending(void *opaque, int irq);
 int armv7m_nvic_acknowledge_irq(void *opaque);
 void armv7m_nvic_complete_irq(void *opaque, int irq);
 
-void cpu_arm_set_cp_io(CPUARMState *env, int cpnum,
-                       ARMReadCPFunc *cp_read, ARMWriteCPFunc *cp_write,
-                       void *opaque);
-
 /* Interface for defining coprocessor registers.
  * Registers are defined in tables of arm_cp_reginfo structs
  * which are passed to define_arm_cp_regs().
diff --git a/target-arm/helper.c b/target-arm/helper.c
index 7032423..57bb78b 100644
--- a/target-arm/helper.c
+++ b/target-arm/helper.c
@@ -386,21 +386,6 @@ int cpu_arm_handle_mmu_fault (CPUARMState *env, target_ulong address, int rw,
     return 1;
 }
 
-/* These should probably raise undefined insn exceptions.  */
-void HELPER(set_cp)(CPUARMState *env, uint32_t insn, uint32_t val)
-{
-    int op1 = (insn >> 8) & 0xf;
-    cpu_abort(env, "cp%i insn %08x\n", op1, insn);
-    return;
-}
-
-uint32_t HELPER(get_cp)(CPUARMState *env, uint32_t insn)
-{
-    int op1 = (insn >> 8) & 0xf;
-    cpu_abort(env, "cp%i insn %08x\n", op1, insn);
-    return 0;
-}
-
 void HELPER(set_cp15)(CPUARMState *env, uint32_t insn, uint32_t val)
 {
     cpu_abort(env, "cp15 insn %08x\n", insn);
@@ -1137,31 +1122,6 @@ target_phys_addr_t cpu_get_phys_page_debug(CPUARMState *env, target_ulong addr)
     return phys_addr;
 }
 
-void HELPER(set_cp)(CPUARMState *env, uint32_t insn, uint32_t val)
-{
-    int cp_num = (insn >> 8) & 0xf;
-    int cp_info = (insn >> 5) & 7;
-    int src = (insn >> 16) & 0xf;
-    int operand = insn & 0xf;
-
-    if (env->cp[cp_num].cp_write)
-        env->cp[cp_num].cp_write(env->cp[cp_num].opaque,
-                                 cp_info, src, operand, val);
-}
-
-uint32_t HELPER(get_cp)(CPUARMState *env, uint32_t insn)
-{
-    int cp_num = (insn >> 8) & 0xf;
-    int cp_info = (insn >> 5) & 7;
-    int dest = (insn >> 16) & 0xf;
-    int operand = insn & 0xf;
-
-    if (env->cp[cp_num].cp_read)
-        return env->cp[cp_num].cp_read(env->cp[cp_num].opaque,
-                                       cp_info, dest, operand);
-    return 0;
-}
-
 /* Return basic MPU access permission bits.  */
 static uint32_t simple_mpu_ap_bits(uint32_t val)
 {
@@ -2125,20 +2085,6 @@ void HELPER(v7m_msr)(CPUARMState *env, uint32_t reg, uint32_t val)
     }
 }
 
-void cpu_arm_set_cp_io(CPUARMState *env, int cpnum,
-                ARMReadCPFunc *cp_read, ARMWriteCPFunc *cp_write,
-                void *opaque)
-{
-    if (cpnum < 0 || cpnum > 14) {
-        cpu_abort(env, "Bad coprocessor number: %i\n", cpnum);
-        return;
-    }
-
-    env->cp[cpnum].cp_read = cp_read;
-    env->cp[cpnum].cp_write = cp_write;
-    env->cp[cpnum].opaque = opaque;
-}
-
 #endif
 
 /* Note that signed overflow is undefined in C.  The following routines are
diff --git a/target-arm/helper.h b/target-arm/helper.h
index b6cefed..bb6b85d 100644
--- a/target-arm/helper.h
+++ b/target-arm/helper.h
@@ -62,9 +62,6 @@ DEF_HELPER_2(v7m_mrs, i32, env, i32)
 DEF_HELPER_3(set_cp15, void, env, i32, i32)
 DEF_HELPER_2(get_cp15, i32, env, i32)
 
-DEF_HELPER_3(set_cp, void, env, i32, i32)
-DEF_HELPER_2(get_cp, i32, env, i32)
-
 DEF_HELPER_3(set_cp_reg, void, env, ptr, i32)
 DEF_HELPER_2(get_cp_reg, i32, env, ptr)
 DEF_HELPER_3(set_cp_reg64, void, env, ptr, i64)
diff --git a/target-arm/translate.c b/target-arm/translate.c
index d7edda7..75e464d 100644
--- a/target-arm/translate.c
+++ b/target-arm/translate.c
@@ -2439,39 +2439,6 @@ static int disas_dsp_insn(CPUARMState *env, DisasContext *s, uint32_t insn)
     return 1;
 }
 
-/* Disassemble system coprocessor instruction.  Return nonzero if
-   instruction is not defined.  */
-static int disas_cp_insn(CPUARMState *env, DisasContext *s, uint32_t insn)
-{
-    TCGv tmp, tmp2;
-    uint32_t rd = (insn >> 12) & 0xf;
-    uint32_t cp = (insn >> 8) & 0xf;
-    if (IS_USER(s)) {
-        return 1;
-    }
-
-    if (insn & ARM_CP_RW_BIT) {
-        if (!env->cp[cp].cp_read)
-            return 1;
-        gen_set_pc_im(s->pc);
-        tmp = tcg_temp_new_i32();
-        tmp2 = tcg_const_i32(insn);
-        gen_helper_get_cp(tmp, cpu_env, tmp2);
-        tcg_temp_free(tmp2);
-        store_reg(s, rd, tmp);
-    } else {
-        if (!env->cp[cp].cp_write)
-            return 1;
-        gen_set_pc_im(s->pc);
-        tmp = load_reg(s, rd);
-        tmp2 = tcg_const_i32(insn);
-        gen_helper_set_cp(cpu_env, tmp2, tmp);
-        tcg_temp_free(tmp2);
-        tcg_temp_free_i32(tmp);
-    }
-    return 0;
-}
-
 static int cp15_user_ok(CPUARMState *env, uint32_t insn)
 {
     int cpn = (insn >> 16) & 0xf;
@@ -6653,10 +6620,6 @@ static int disas_coproc_insn(CPUARMState * env, DisasContext *s, uint32_t insn)
      */
     switch (cpnum) {
     case 14:
-        /* Coprocessors 7-15 are architecturally reserved by ARM.
-           Unfortunately Intel decided to ignore this.  */
-        if (arm_feature(env, ARM_FEATURE_XSCALE))
-            goto board;
         if (insn & (1 << 20))
             return disas_cp14_read(env, s, insn);
         else
@@ -6664,9 +6627,7 @@ static int disas_coproc_insn(CPUARMState * env, DisasContext *s, uint32_t insn)
     case 15:
 	return disas_cp15_insn (env, s, insn);
     default:
-    board:
-	/* Unknown coprocessor.  See if the board has hooked it.  */
-	return disas_cp_insn (env, s, insn);
+        return 1;
     }
 }
 
commit 9ee703b0965fb8dc52b22a3511fa67a1c120d52b
Author: Peter Maydell <peter.maydell at linaro.org>
Date:   Wed Jun 20 11:57:08 2012 +0000

    hw/pxa2xx_pic: Convert coprocessor registers to new scheme
    
    Convert the coprocessor access functions for the pxa2xx PIC to the
    arm_cp_reginfo scheme.
    
    Signed-off-by: Peter Maydell <peter.maydell at linaro.org>

diff --git a/hw/pxa2xx_pic.c b/hw/pxa2xx_pic.c
index c560133..e1e8830 100644
--- a/hw/pxa2xx_pic.c
+++ b/hw/pxa2xx_pic.c
@@ -209,33 +209,42 @@ static const int pxa2xx_cp_reg_map[0x10] = {
     [0xa] = ICPR2,
 };
 
-static uint32_t pxa2xx_pic_cp_read(void *opaque, int op2, int reg, int crm)
+static int pxa2xx_pic_cp_read(CPUARMState *env, const ARMCPRegInfo *ri,
+                              uint64_t *value)
 {
-    target_phys_addr_t offset;
-
-    if (pxa2xx_cp_reg_map[reg] == -1) {
-        printf("%s: Bad register 0x%x\n", __FUNCTION__, reg);
-        return 0;
-    }
-
-    offset = pxa2xx_cp_reg_map[reg];
-    return pxa2xx_pic_mem_read(opaque, offset, 4);
+    int offset = pxa2xx_cp_reg_map[ri->crn];
+    *value = pxa2xx_pic_mem_read(ri->opaque, offset, 4);
+    return 0;
 }
 
-static void pxa2xx_pic_cp_write(void *opaque, int op2, int reg, int crm,
-                uint32_t value)
+static int pxa2xx_pic_cp_write(CPUARMState *env, const ARMCPRegInfo *ri,
+                               uint64_t value)
 {
-    target_phys_addr_t offset;
-
-    if (pxa2xx_cp_reg_map[reg] == -1) {
-        printf("%s: Bad register 0x%x\n", __FUNCTION__, reg);
-        return;
-    }
-
-    offset = pxa2xx_cp_reg_map[reg];
-    pxa2xx_pic_mem_write(opaque, offset, value, 4);
+    int offset = pxa2xx_cp_reg_map[ri->crn];
+    pxa2xx_pic_mem_write(ri->opaque, offset, value, 4);
+    return 0;
 }
 
+#define REGINFO_FOR_PIC_CP(NAME, CRN) \
+    { .name = NAME, .cp = 6, .crn = CRN, .crm = 0, .opc1 = 0, .opc2 = 0, \
+      .access = PL1_RW, \
+      .readfn = pxa2xx_pic_cp_read, .writefn = pxa2xx_pic_cp_write }
+
+static const ARMCPRegInfo pxa_pic_cp_reginfo[] = {
+    REGINFO_FOR_PIC_CP("ICIP", 0),
+    REGINFO_FOR_PIC_CP("ICMR", 1),
+    REGINFO_FOR_PIC_CP("ICLR", 2),
+    REGINFO_FOR_PIC_CP("ICFP", 3),
+    REGINFO_FOR_PIC_CP("ICPR", 4),
+    REGINFO_FOR_PIC_CP("ICHP", 5),
+    REGINFO_FOR_PIC_CP("ICIP2", 6),
+    REGINFO_FOR_PIC_CP("ICMR2", 7),
+    REGINFO_FOR_PIC_CP("ICLR2", 8),
+    REGINFO_FOR_PIC_CP("ICFP2", 9),
+    REGINFO_FOR_PIC_CP("ICPR2", 0xa),
+    REGINFO_SENTINEL
+};
+
 static const MemoryRegionOps pxa2xx_pic_ops = {
     .read = pxa2xx_pic_mem_read,
     .write = pxa2xx_pic_mem_write,
@@ -274,7 +283,7 @@ DeviceState *pxa2xx_pic_init(target_phys_addr_t base, ARMCPU *cpu)
     sysbus_mmio_map(sysbus_from_qdev(dev), 0, base);
 
     /* Enable IC coprocessor access.  */
-    cpu_arm_set_cp_io(env, 6, pxa2xx_pic_cp_read, pxa2xx_pic_cp_write, s);
+    define_arm_cp_regs_with_opaque(arm_env_get_cpu(env), pxa_pic_cp_reginfo, s);
 
     return dev;
 }
commit e2f8a44d0d425a22cca5855702f534536f5e8c90
Author: Peter Maydell <peter.maydell at linaro.org>
Date:   Wed Jun 20 11:57:07 2012 +0000

    hw/pxa2xx.c: Convert CLKCFG and PWRMODE cp14 regs
    
    Convert the PXA2xx CLKCFG and PWRMODE cp14 registers to the
    new arm_cp_reginfo scheme.
    
    Signed-off-by: Peter Maydell <peter.maydell at linaro.org>

diff --git a/hw/pxa2xx.c b/hw/pxa2xx.c
index 2ab5a4c..d5f1420 100644
--- a/hw/pxa2xx.c
+++ b/hw/pxa2xx.c
@@ -224,131 +224,96 @@ static const VMStateDescription vmstate_pxa2xx_cm = {
     }
 };
 
-static uint32_t pxa2xx_clkpwr_read(void *opaque, int op2, int reg, int crm)
+static int pxa2xx_clkcfg_read(CPUARMState *env, const ARMCPRegInfo *ri,
+                              uint64_t *value)
 {
-    PXA2xxState *s = (PXA2xxState *) opaque;
-
-    switch (reg) {
-    case 6:	/* Clock Configuration register */
-        return s->clkcfg;
-
-    case 7:	/* Power Mode register */
-        return 0;
+    PXA2xxState *s = (PXA2xxState *)ri->opaque;
+    *value = s->clkcfg;
+    return 0;
+}
 
-    default:
-        printf("%s: Bad register 0x%x\n", __FUNCTION__, reg);
-        break;
+static int pxa2xx_clkcfg_write(CPUARMState *env, const ARMCPRegInfo *ri,
+                               uint64_t value)
+{
+    PXA2xxState *s = (PXA2xxState *)ri->opaque;
+    s->clkcfg = value & 0xf;
+    if (value & 2) {
+        printf("%s: CPU frequency change attempt\n", __func__);
     }
     return 0;
 }
 
-static void pxa2xx_clkpwr_write(void *opaque, int op2, int reg, int crm,
-                uint32_t value)
+static int pxa2xx_pwrmode_write(CPUARMState *env, const ARMCPRegInfo *ri,
+                                uint64_t value)
 {
-    PXA2xxState *s = (PXA2xxState *) opaque;
+    PXA2xxState *s = (PXA2xxState *)ri->opaque;
     static const char *pwrmode[8] = {
         "Normal", "Idle", "Deep-idle", "Standby",
         "Sleep", "reserved (!)", "reserved (!)", "Deep-sleep",
     };
 
-    switch (reg) {
-    case 6:	/* Clock Configuration register */
-        s->clkcfg = value & 0xf;
-        if (value & 2)
-            printf("%s: CPU frequency change attempt\n", __FUNCTION__);
+    if (value & 8) {
+        printf("%s: CPU voltage change attempt\n", __func__);
+    }
+    switch (value & 7) {
+    case 0:
+        /* Do nothing */
         break;
 
-    case 7:	/* Power Mode register */
-        if (value & 8)
-            printf("%s: CPU voltage change attempt\n", __FUNCTION__);
-        switch (value & 7) {
-        case 0:
-            /* Do nothing */
-            break;
-
-        case 1:
-            /* Idle */
-            if (!(s->cm_regs[CCCR >> 2] & (1 << 31))) {	/* CPDIS */
-                cpu_interrupt(&s->cpu->env, CPU_INTERRUPT_HALT);
-                break;
-            }
-            /* Fall through.  */
-
-        case 2:
-            /* Deep-Idle */
+    case 1:
+        /* Idle */
+        if (!(s->cm_regs[CCCR >> 2] & (1 << 31))) { /* CPDIS */
             cpu_interrupt(&s->cpu->env, CPU_INTERRUPT_HALT);
-            s->pm_regs[RCSR >> 2] |= 0x8;	/* Set GPR */
-            goto message;
-
-        case 3:
-            s->cpu->env.uncached_cpsr =
-                    ARM_CPU_MODE_SVC | CPSR_A | CPSR_F | CPSR_I;
-            s->cpu->env.cp15.c1_sys = 0;
-            s->cpu->env.cp15.c1_coproc = 0;
-            s->cpu->env.cp15.c2_base0 = 0;
-            s->cpu->env.cp15.c3 = 0;
-            s->pm_regs[PSSR >> 2] |= 0x8;	/* Set STS */
-            s->pm_regs[RCSR >> 2] |= 0x8;	/* Set GPR */
-
-            /*
-             * The scratch-pad register is almost universally used
-             * for storing the return address on suspend.  For the
-             * lack of a resuming bootloader, perform a jump
-             * directly to that address.
-             */
-            memset(s->cpu->env.regs, 0, 4 * 15);
-            s->cpu->env.regs[15] = s->pm_regs[PSPR >> 2];
+            break;
+        }
+        /* Fall through.  */
+
+    case 2:
+        /* Deep-Idle */
+        cpu_interrupt(&s->cpu->env, CPU_INTERRUPT_HALT);
+        s->pm_regs[RCSR >> 2] |= 0x8; /* Set GPR */
+        goto message;
+
+    case 3:
+        s->cpu->env.uncached_cpsr =
+            ARM_CPU_MODE_SVC | CPSR_A | CPSR_F | CPSR_I;
+        s->cpu->env.cp15.c1_sys = 0;
+        s->cpu->env.cp15.c1_coproc = 0;
+        s->cpu->env.cp15.c2_base0 = 0;
+        s->cpu->env.cp15.c3 = 0;
+        s->pm_regs[PSSR >> 2] |= 0x8; /* Set STS */
+        s->pm_regs[RCSR >> 2] |= 0x8; /* Set GPR */
+
+        /*
+         * The scratch-pad register is almost universally used
+         * for storing the return address on suspend.  For the
+         * lack of a resuming bootloader, perform a jump
+         * directly to that address.
+         */
+        memset(s->cpu->env.regs, 0, 4 * 15);
+        s->cpu->env.regs[15] = s->pm_regs[PSPR >> 2];
 
 #if 0
-            buffer = 0xe59ff000;	/* ldr     pc, [pc, #0] */
-            cpu_physical_memory_write(0, &buffer, 4);
-            buffer = s->pm_regs[PSPR >> 2];
-            cpu_physical_memory_write(8, &buffer, 4);
+        buffer = 0xe59ff000; /* ldr     pc, [pc, #0] */
+        cpu_physical_memory_write(0, &buffer, 4);
+        buffer = s->pm_regs[PSPR >> 2];
+        cpu_physical_memory_write(8, &buffer, 4);
 #endif
 
-            /* Suspend */
-            cpu_interrupt(cpu_single_env, CPU_INTERRUPT_HALT);
-
-            goto message;
+        /* Suspend */
+        cpu_interrupt(cpu_single_env, CPU_INTERRUPT_HALT);
 
-        default:
-        message:
-            printf("%s: machine entered %s mode\n", __FUNCTION__,
-                            pwrmode[value & 7]);
-        }
-        break;
+        goto message;
 
     default:
-        printf("%s: Bad register 0x%x\n", __FUNCTION__, reg);
-        break;
+    message:
+        printf("%s: machine entered %s mode\n", __func__,
+               pwrmode[value & 7]);
     }
-}
 
-static uint32_t pxa2xx_cp14_read(void *opaque, int op2, int reg, int crm)
-{
-    switch (crm) {
-    case 0:
-        return pxa2xx_clkpwr_read(opaque, op2, reg, crm);
-    default:
-        printf("%s: Bad register 0x%x\n", __FUNCTION__, reg);
-        break;
-    }
     return 0;
 }
 
-static void pxa2xx_cp14_write(void *opaque, int op2, int reg, int crm,
-                uint32_t value)
-{
-    switch (crm) {
-    case 0:
-        pxa2xx_clkpwr_write(opaque, op2, reg, crm, value);
-        break;
-    default:
-        printf("%s: Bad register 0x%x\n", __FUNCTION__, reg);
-        break;
-    }
-}
-
 static int pxa2xx_cppmnc_read(CPUARMState *env, const ARMCPRegInfo *ri,
                               uint64_t *value)
 {
@@ -400,6 +365,14 @@ static const ARMCPRegInfo pxa_cp_reginfo[] = {
       .access = PL1_RW, .type = ARM_CP_CONST, .resetvalue = 0 },
     { .name = "CPPMN3", .cp = 14, .crn = 2, .crm = 3, .opc1 = 0, .opc2 = 0,
       .access = PL1_RW, .type = ARM_CP_CONST, .resetvalue = 0 },
+    /* cp14 crn==6: CLKCFG */
+    { .name = "CLKCFG", .cp = 14, .crn = 6, .crm = 0, .opc1 = 0, .opc2 = 0,
+      .access = PL1_RW,
+      .readfn = pxa2xx_clkcfg_read, .writefn = pxa2xx_clkcfg_write },
+    /* cp14 crn==7: PWRMODE */
+    { .name = "PWRMODE", .cp = 14, .crn = 7, .crm = 0, .opc1 = 0, .opc2 = 0,
+      .access = PL1_RW,
+      .readfn = arm_cp_read_zero, .writefn = pxa2xx_pwrmode_write },
     REGINFO_SENTINEL
 };
 
@@ -2111,7 +2084,6 @@ PXA2xxState *pxa270_init(MemoryRegion *address_space,
     memory_region_add_subregion(address_space, s->cm_base, &s->cm_iomem);
     vmstate_register(NULL, 0, &vmstate_pxa2xx_cm, s);
 
-    cpu_arm_set_cp_io(&s->cpu->env, 14, pxa2xx_cp14_read, pxa2xx_cp14_write, s);
     pxa2xx_setup_cp14(s);
 
     s->mm_base = 0x48000000;
@@ -2243,7 +2215,6 @@ PXA2xxState *pxa255_init(MemoryRegion *address_space, unsigned int sdram_size)
     memory_region_add_subregion(address_space, s->cm_base, &s->cm_iomem);
     vmstate_register(NULL, 0, &vmstate_pxa2xx_cm, s);
 
-    cpu_arm_set_cp_io(&s->cpu->env, 14, pxa2xx_cp14_read, pxa2xx_cp14_write, s);
     pxa2xx_setup_cp14(s);
 
     s->mm_base = 0x48000000;
commit dc2a9045cff0f0c0bb1f58bf82473afb1e9f1c6a
Author: Peter Maydell <peter.maydell at linaro.org>
Date:   Wed Jun 20 11:57:07 2012 +0000

    hw/pxa2xx: Convert cp14 perf registers to new scheme
    
    Convert the PXA2xx cp14 perf registers from old-style
    coprocessor hooks to the new scheme.
    
    Signed-off-by: Peter Maydell <peter.maydell at linaro.org>

diff --git a/hw/pxa2xx.c b/hw/pxa2xx.c
index 7958d14..2ab5a4c 100644
--- a/hw/pxa2xx.c
+++ b/hw/pxa2xx.c
@@ -324,80 +324,11 @@ static void pxa2xx_clkpwr_write(void *opaque, int op2, int reg, int crm,
     }
 }
 
-/* Performace Monitoring Registers */
-#define CPPMNC		0	/* Performance Monitor Control register */
-#define CPCCNT		1	/* Clock Counter register */
-#define CPINTEN		4	/* Interrupt Enable register */
-#define CPFLAG		5	/* Overflow Flag register */
-#define CPEVTSEL	8	/* Event Selection register */
-
-#define CPPMN0		0	/* Performance Count register 0 */
-#define CPPMN1		1	/* Performance Count register 1 */
-#define CPPMN2		2	/* Performance Count register 2 */
-#define CPPMN3		3	/* Performance Count register 3 */
-
-static uint32_t pxa2xx_perf_read(void *opaque, int op2, int reg, int crm)
-{
-    PXA2xxState *s = (PXA2xxState *) opaque;
-
-    switch (reg) {
-    case CPPMNC:
-        return s->pmnc;
-    case CPCCNT:
-        if (s->pmnc & 1)
-            return qemu_get_clock_ns(vm_clock);
-        else
-            return 0;
-    case CPINTEN:
-    case CPFLAG:
-    case CPEVTSEL:
-        return 0;
-
-    default:
-        printf("%s: Bad register 0x%x\n", __FUNCTION__, reg);
-        break;
-    }
-    return 0;
-}
-
-static void pxa2xx_perf_write(void *opaque, int op2, int reg, int crm,
-                uint32_t value)
-{
-    PXA2xxState *s = (PXA2xxState *) opaque;
-
-    switch (reg) {
-    case CPPMNC:
-        s->pmnc = value;
-        break;
-
-    case CPCCNT:
-    case CPINTEN:
-    case CPFLAG:
-    case CPEVTSEL:
-        break;
-
-    default:
-        printf("%s: Bad register 0x%x\n", __FUNCTION__, reg);
-        break;
-    }
-}
-
 static uint32_t pxa2xx_cp14_read(void *opaque, int op2, int reg, int crm)
 {
     switch (crm) {
     case 0:
         return pxa2xx_clkpwr_read(opaque, op2, reg, crm);
-    case 1:
-        return pxa2xx_perf_read(opaque, op2, reg, crm);
-    case 2:
-        switch (reg) {
-        case CPPMN0:
-        case CPPMN1:
-        case CPPMN2:
-        case CPPMN3:
-            return 0;
-        }
-        /* Fall through */
     default:
         printf("%s: Bad register 0x%x\n", __FUNCTION__, reg);
         break;
@@ -412,24 +343,71 @@ static void pxa2xx_cp14_write(void *opaque, int op2, int reg, int crm,
     case 0:
         pxa2xx_clkpwr_write(opaque, op2, reg, crm, value);
         break;
-    case 1:
-        pxa2xx_perf_write(opaque, op2, reg, crm, value);
-        break;
-    case 2:
-        switch (reg) {
-        case CPPMN0:
-        case CPPMN1:
-        case CPPMN2:
-        case CPPMN3:
-            return;
-        }
-        /* Fall through */
     default:
         printf("%s: Bad register 0x%x\n", __FUNCTION__, reg);
         break;
     }
 }
 
+static int pxa2xx_cppmnc_read(CPUARMState *env, const ARMCPRegInfo *ri,
+                              uint64_t *value)
+{
+    PXA2xxState *s = (PXA2xxState *)ri->opaque;
+    *value = s->pmnc;
+    return 0;
+}
+
+static int pxa2xx_cppmnc_write(CPUARMState *env, const ARMCPRegInfo *ri,
+                               uint64_t value)
+{
+    PXA2xxState *s = (PXA2xxState *)ri->opaque;
+    s->pmnc = value;
+    return 0;
+}
+
+static int pxa2xx_cpccnt_read(CPUARMState *env, const ARMCPRegInfo *ri,
+                              uint64_t *value)
+{
+    PXA2xxState *s = (PXA2xxState *)ri->opaque;
+    if (s->pmnc & 1) {
+        *value = qemu_get_clock_ns(vm_clock);
+    } else {
+        *value = 0;
+    }
+    return 0;
+}
+
+static const ARMCPRegInfo pxa_cp_reginfo[] = {
+    /* cp14 crn==1: perf registers */
+    { .name = "CPPMNC", .cp = 14, .crn = 1, .crm = 0, .opc1 = 0, .opc2 = 0,
+      .access = PL1_RW,
+      .readfn = pxa2xx_cppmnc_read, .writefn = pxa2xx_cppmnc_write },
+    { .name = "CPCCNT", .cp = 14, .crn = 1, .crm = 1, .opc1 = 0, .opc2 = 0,
+      .access = PL1_RW,
+      .readfn = pxa2xx_cpccnt_read, .writefn = arm_cp_write_ignore },
+    { .name = "CPINTEN", .cp = 14, .crn = 1, .crm = 4, .opc1 = 0, .opc2 = 0,
+      .access = PL1_RW, .type = ARM_CP_CONST, .resetvalue = 0 },
+    { .name = "CPFLAG", .cp = 14, .crn = 1, .crm = 5, .opc1 = 0, .opc2 = 0,
+      .access = PL1_RW, .type = ARM_CP_CONST, .resetvalue = 0 },
+    { .name = "CPEVTSEL", .cp = 14, .crn = 1, .crm = 8, .opc1 = 0, .opc2 = 0,
+      .access = PL1_RW, .type = ARM_CP_CONST, .resetvalue = 0 },
+    /* cp14 crn==2: performance count registers */
+    { .name = "CPPMN0", .cp = 14, .crn = 2, .crm = 0, .opc1 = 0, .opc2 = 0,
+      .access = PL1_RW, .type = ARM_CP_CONST, .resetvalue = 0 },
+    { .name = "CPPMN1", .cp = 14, .crn = 2, .crm = 1, .opc1 = 0, .opc2 = 0,
+      .access = PL1_RW, .type = ARM_CP_CONST, .resetvalue = 0 },
+    { .name = "CPPMN2", .cp = 14, .crn = 2, .crm = 2, .opc1 = 0, .opc2 = 0,
+      .access = PL1_RW, .type = ARM_CP_CONST, .resetvalue = 0 },
+    { .name = "CPPMN3", .cp = 14, .crn = 2, .crm = 3, .opc1 = 0, .opc2 = 0,
+      .access = PL1_RW, .type = ARM_CP_CONST, .resetvalue = 0 },
+    REGINFO_SENTINEL
+};
+
+static void pxa2xx_setup_cp14(PXA2xxState *s)
+{
+    define_arm_cp_regs_with_opaque(s->cpu, pxa_cp_reginfo, s);
+}
+
 #define MDCNFG		0x00	/* SDRAM Configuration register */
 #define MDREFR		0x04	/* SDRAM Refresh Control register */
 #define MSC0		0x08	/* Static Memory Control register 0 */
@@ -2134,6 +2112,7 @@ PXA2xxState *pxa270_init(MemoryRegion *address_space,
     vmstate_register(NULL, 0, &vmstate_pxa2xx_cm, s);
 
     cpu_arm_set_cp_io(&s->cpu->env, 14, pxa2xx_cp14_read, pxa2xx_cp14_write, s);
+    pxa2xx_setup_cp14(s);
 
     s->mm_base = 0x48000000;
     s->mm_regs[MDMRS >> 2] = 0x00020002;
@@ -2265,6 +2244,7 @@ PXA2xxState *pxa255_init(MemoryRegion *address_space, unsigned int sdram_size)
     vmstate_register(NULL, 0, &vmstate_pxa2xx_cm, s);
 
     cpu_arm_set_cp_io(&s->cpu->env, 14, pxa2xx_cp14_read, pxa2xx_cp14_write, s);
+    pxa2xx_setup_cp14(s);
 
     s->mm_base = 0x48000000;
     s->mm_regs[MDMRS >> 2] = 0x00020002;
commit 4b6a83fb0c34a6fcc7bb1058284e3c3674e54421
Author: Peter Maydell <peter.maydell at linaro.org>
Date:   Wed Jun 20 11:57:06 2012 +0000

    target-arm: initial coprocessor register framework
    
    Initial infrastructure for data-driven registration of
    coprocessor register implementations.
    
    We still fall back to the old-style switch statements pending
    complete conversion of all existing registers.
    
    Signed-off-by: Peter Maydell <peter.maydell at linaro.org>

diff --git a/target-arm/cpu-qom.h b/target-arm/cpu-qom.h
index a61c68d..848ac2f 100644
--- a/target-arm/cpu-qom.h
+++ b/target-arm/cpu-qom.h
@@ -58,6 +58,9 @@ typedef struct ARMCPU {
 
     CPUARMState env;
 
+    /* Coprocessor information */
+    GHashTable *cp_regs;
+
     /* The instance init functions for implementation-specific subclasses
      * set these fields to specify the implementation-dependent values of
      * various constant registers and reset values of non-constant
diff --git a/target-arm/cpu.c b/target-arm/cpu.c
index 934894b..6456a3d 100644
--- a/target-arm/cpu.c
+++ b/target-arm/cpu.c
@@ -24,6 +24,37 @@
 #include "hw/loader.h"
 #endif
 
+static void cp_reg_reset(gpointer key, gpointer value, gpointer opaque)
+{
+    /* Reset a single ARMCPRegInfo register */
+    ARMCPRegInfo *ri = value;
+    ARMCPU *cpu = opaque;
+
+    if (ri->type & ARM_CP_SPECIAL) {
+        return;
+    }
+
+    if (ri->resetfn) {
+        ri->resetfn(&cpu->env, ri);
+        return;
+    }
+
+    /* A zero offset is never possible as it would be regs[0]
+     * so we use it to indicate that reset is being handled elsewhere.
+     * This is basically only used for fields in non-core coprocessors
+     * (like the pxa2xx ones).
+     */
+    if (!ri->fieldoffset) {
+        return;
+    }
+
+    if (ri->type & ARM_CP_64BIT) {
+        CPREG_FIELD64(&cpu->env, ri) = ri->resetvalue;
+    } else {
+        CPREG_FIELD32(&cpu->env, ri) = ri->resetvalue;
+    }
+}
+
 /* CPUClass::reset() */
 static void arm_cpu_reset(CPUState *s)
 {
@@ -39,6 +70,7 @@ static void arm_cpu_reset(CPUState *s)
     acc->parent_reset(s);
 
     memset(env, 0, offsetof(CPUARMState, breakpoints));
+    g_hash_table_foreach(cpu->cp_regs, cp_reg_reset, cpu);
     env->cp15.c15_config_base_address = cpu->reset_cbar;
     env->cp15.c0_cpuid = cpu->midr;
     env->vfp.xregs[ARM_VFP_FPSID] = cpu->reset_fpsid;
@@ -130,6 +162,14 @@ static void arm_cpu_initfn(Object *obj)
     ARMCPU *cpu = ARM_CPU(obj);
 
     cpu_exec_init(&cpu->env);
+    cpu->cp_regs = g_hash_table_new_full(g_int_hash, g_int_equal,
+                                         g_free, g_free);
+}
+
+static void arm_cpu_finalizefn(Object *obj)
+{
+    ARMCPU *cpu = ARM_CPU(obj);
+    g_hash_table_destroy(cpu->cp_regs);
 }
 
 void arm_cpu_realize(ARMCPU *cpu)
@@ -657,6 +697,7 @@ static const TypeInfo arm_cpu_type_info = {
     .parent = TYPE_CPU,
     .instance_size = sizeof(ARMCPU),
     .instance_init = arm_cpu_initfn,
+    .instance_finalize = arm_cpu_finalizefn,
     .abstract = true,
     .class_size = sizeof(ARMCPUClass),
     .class_init = arm_cpu_class_init,
diff --git a/target-arm/cpu.h b/target-arm/cpu.h
index d01285f..6c7d3e7 100644
--- a/target-arm/cpu.h
+++ b/target-arm/cpu.h
@@ -410,6 +410,207 @@ void cpu_arm_set_cp_io(CPUARMState *env, int cpnum,
                        ARMReadCPFunc *cp_read, ARMWriteCPFunc *cp_write,
                        void *opaque);
 
+/* Interface for defining coprocessor registers.
+ * Registers are defined in tables of arm_cp_reginfo structs
+ * which are passed to define_arm_cp_regs().
+ */
+
+/* When looking up a coprocessor register we look for it
+ * via an integer which encodes all of:
+ *  coprocessor number
+ *  Crn, Crm, opc1, opc2 fields
+ *  32 or 64 bit register (ie is it accessed via MRC/MCR
+ *    or via MRRC/MCRR?)
+ * We allow 4 bits for opc1 because MRRC/MCRR have a 4 bit field.
+ * (In this case crn and opc2 should be zero.)
+ */
+#define ENCODE_CP_REG(cp, is64, crn, crm, opc1, opc2)   \
+    (((cp) << 16) | ((is64) << 15) | ((crn) << 11) |    \
+     ((crm) << 7) | ((opc1) << 3) | (opc2))
+
+#define DECODE_CPREG_CRN(enc) (((enc) >> 7) & 0xf)
+
+/* ARMCPRegInfo type field bits. If the SPECIAL bit is set this is a
+ * special-behaviour cp reg and bits [15..8] indicate what behaviour
+ * it has. Otherwise it is a simple cp reg, where CONST indicates that
+ * TCG can assume the value to be constant (ie load at translate time)
+ * and 64BIT indicates a 64 bit wide coprocessor register. SUPPRESS_TB_END
+ * indicates that the TB should not be ended after a write to this register
+ * (the default is that the TB ends after cp writes). OVERRIDE permits
+ * a register definition to override a previous definition for the
+ * same (cp, is64, crn, crm, opc1, opc2) tuple: either the new or the
+ * old must have the OVERRIDE bit set.
+ */
+#define ARM_CP_SPECIAL 1
+#define ARM_CP_CONST 2
+#define ARM_CP_64BIT 4
+#define ARM_CP_SUPPRESS_TB_END 8
+#define ARM_CP_OVERRIDE 16
+#define ARM_CP_NOP (ARM_CP_SPECIAL | (1 << 8))
+#define ARM_CP_WFI (ARM_CP_SPECIAL | (2 << 8))
+#define ARM_LAST_SPECIAL ARM_CP_WFI
+/* Used only as a terminator for ARMCPRegInfo lists */
+#define ARM_CP_SENTINEL 0xffff
+/* Mask of only the flag bits in a type field */
+#define ARM_CP_FLAG_MASK 0x1f
+
+/* Return true if cptype is a valid type field. This is used to try to
+ * catch errors where the sentinel has been accidentally left off the end
+ * of a list of registers.
+ */
+static inline bool cptype_valid(int cptype)
+{
+    return ((cptype & ~ARM_CP_FLAG_MASK) == 0)
+        || ((cptype & ARM_CP_SPECIAL) &&
+            (cptype <= ARM_LAST_SPECIAL));
+}
+
+/* Access rights:
+ * We define bits for Read and Write access for what rev C of the v7-AR ARM ARM
+ * defines as PL0 (user), PL1 (fiq/irq/svc/abt/und/sys, ie privileged), and
+ * PL2 (hyp). The other level which has Read and Write bits is Secure PL1
+ * (ie any of the privileged modes in Secure state, or Monitor mode).
+ * If a register is accessible in one privilege level it's always accessible
+ * in higher privilege levels too. Since "Secure PL1" also follows this rule
+ * (ie anything visible in PL2 is visible in S-PL1, some things are only
+ * visible in S-PL1) but "Secure PL1" is a bit of a mouthful, we bend the
+ * terminology a little and call this PL3.
+ *
+ * If access permissions for a register are more complex than can be
+ * described with these bits, then use a laxer set of restrictions, and
+ * do the more restrictive/complex check inside a helper function.
+ */
+#define PL3_R 0x80
+#define PL3_W 0x40
+#define PL2_R (0x20 | PL3_R)
+#define PL2_W (0x10 | PL3_W)
+#define PL1_R (0x08 | PL2_R)
+#define PL1_W (0x04 | PL2_W)
+#define PL0_R (0x02 | PL1_R)
+#define PL0_W (0x01 | PL1_W)
+
+#define PL3_RW (PL3_R | PL3_W)
+#define PL2_RW (PL2_R | PL2_W)
+#define PL1_RW (PL1_R | PL1_W)
+#define PL0_RW (PL0_R | PL0_W)
+
+static inline int arm_current_pl(CPUARMState *env)
+{
+    if ((env->uncached_cpsr & 0x1f) == ARM_CPU_MODE_USR) {
+        return 0;
+    }
+    /* We don't currently implement the Virtualization or TrustZone
+     * extensions, so PL2 and PL3 don't exist for us.
+     */
+    return 1;
+}
+
+typedef struct ARMCPRegInfo ARMCPRegInfo;
+
+/* Access functions for coprocessor registers. These should return
+ * 0 on success, or one of the EXCP_* constants if access should cause
+ * an exception (in which case *value is not written).
+ */
+typedef int CPReadFn(CPUARMState *env, const ARMCPRegInfo *opaque,
+                     uint64_t *value);
+typedef int CPWriteFn(CPUARMState *env, const ARMCPRegInfo *opaque,
+                      uint64_t value);
+/* Hook function for register reset */
+typedef void CPResetFn(CPUARMState *env, const ARMCPRegInfo *opaque);
+
+#define CP_ANY 0xff
+
+/* Definition of an ARM coprocessor register */
+struct ARMCPRegInfo {
+    /* Name of register (useful mainly for debugging, need not be unique) */
+    const char *name;
+    /* Location of register: coprocessor number and (crn,crm,opc1,opc2)
+     * tuple. Any of crm, opc1 and opc2 may be CP_ANY to indicate a
+     * 'wildcard' field -- any value of that field in the MRC/MCR insn
+     * will be decoded to this register. The register read and write
+     * callbacks will be passed an ARMCPRegInfo with the crn/crm/opc1/opc2
+     * used by the program, so it is possible to register a wildcard and
+     * then behave differently on read/write if necessary.
+     * For 64 bit registers, only crm and opc1 are relevant; crn and opc2
+     * must both be zero.
+     */
+    uint8_t cp;
+    uint8_t crn;
+    uint8_t crm;
+    uint8_t opc1;
+    uint8_t opc2;
+    /* Register type: ARM_CP_* bits/values */
+    int type;
+    /* Access rights: PL*_[RW] */
+    int access;
+    /* The opaque pointer passed to define_arm_cp_regs_with_opaque() when
+     * this register was defined: can be used to hand data through to the
+     * register read/write functions, since they are passed the ARMCPRegInfo*.
+     */
+    void *opaque;
+    /* Value of this register, if it is ARM_CP_CONST. Otherwise, if
+     * fieldoffset is non-zero, the reset value of the register.
+     */
+    uint64_t resetvalue;
+    /* Offset of the field in CPUARMState for this register. This is not
+     * needed if either:
+     *  1. type is ARM_CP_CONST or one of the ARM_CP_SPECIALs
+     *  2. both readfn and writefn are specified
+     */
+    ptrdiff_t fieldoffset; /* offsetof(CPUARMState, field) */
+    /* Function for handling reads of this register. If NULL, then reads
+     * will be done by loading from the offset into CPUARMState specified
+     * by fieldoffset.
+     */
+    CPReadFn *readfn;
+    /* Function for handling writes of this register. If NULL, then writes
+     * will be done by writing to the offset into CPUARMState specified
+     * by fieldoffset.
+     */
+    CPWriteFn *writefn;
+    /* Function for resetting the register. If NULL, then reset will be done
+     * by writing resetvalue to the field specified in fieldoffset. If
+     * fieldoffset is 0 then no reset will be done.
+     */
+    CPResetFn *resetfn;
+};
+
+/* Macros which are lvalues for the field in CPUARMState for the
+ * ARMCPRegInfo *ri.
+ */
+#define CPREG_FIELD32(env, ri) \
+    (*(uint32_t *)((char *)(env) + (ri)->fieldoffset))
+#define CPREG_FIELD64(env, ri) \
+    (*(uint64_t *)((char *)(env) + (ri)->fieldoffset))
+
+#define REGINFO_SENTINEL { .type = ARM_CP_SENTINEL }
+
+void define_arm_cp_regs_with_opaque(ARMCPU *cpu,
+                                    const ARMCPRegInfo *regs, void *opaque);
+void define_one_arm_cp_reg_with_opaque(ARMCPU *cpu,
+                                       const ARMCPRegInfo *regs, void *opaque);
+static inline void define_arm_cp_regs(ARMCPU *cpu, const ARMCPRegInfo *regs)
+{
+    define_arm_cp_regs_with_opaque(cpu, regs, 0);
+}
+static inline void define_one_arm_cp_reg(ARMCPU *cpu, const ARMCPRegInfo *regs)
+{
+    define_one_arm_cp_reg_with_opaque(cpu, regs, 0);
+}
+const ARMCPRegInfo *get_arm_cp_reginfo(ARMCPU *cpu, uint32_t encoded_cp);
+
+/* CPWriteFn that can be used to implement writes-ignored behaviour */
+int arm_cp_write_ignore(CPUARMState *env, const ARMCPRegInfo *ri,
+                        uint64_t value);
+/* CPReadFn that can be used for read-as-zero behaviour */
+int arm_cp_read_zero(CPUARMState *env, const ARMCPRegInfo *ri, uint64_t *value);
+
+static inline bool cp_access_ok(CPUARMState *env,
+                                const ARMCPRegInfo *ri, int isread)
+{
+    return (ri->access >> ((arm_current_pl(env) * 2) + isread)) & 1;
+}
+
 /* Does the core conform to the the "MicroController" profile. e.g. Cortex-M3.
    Note the M in older cores (eg. ARM7TDMI) stands for Multiply. These are
    conventional cores (ie. Application or Realtime profile).  */
diff --git a/target-arm/helper.c b/target-arm/helper.c
index bbb1d05..7032423 100644
--- a/target-arm/helper.c
+++ b/target-arm/helper.c
@@ -137,6 +137,107 @@ void arm_cpu_list(FILE *f, fprintf_function cpu_fprintf)
     g_slist_free(list);
 }
 
+void define_one_arm_cp_reg_with_opaque(ARMCPU *cpu,
+                                       const ARMCPRegInfo *r, void *opaque)
+{
+    /* Define implementations of coprocessor registers.
+     * We store these in a hashtable because typically
+     * there are less than 150 registers in a space which
+     * is 16*16*16*8*8 = 262144 in size.
+     * Wildcarding is supported for the crm, opc1 and opc2 fields.
+     * If a register is defined twice then the second definition is
+     * used, so this can be used to define some generic registers and
+     * then override them with implementation specific variations.
+     * At least one of the original and the second definition should
+     * include ARM_CP_OVERRIDE in its type bits -- this is just a guard
+     * against accidental use.
+     */
+    int crm, opc1, opc2;
+    int crmmin = (r->crm == CP_ANY) ? 0 : r->crm;
+    int crmmax = (r->crm == CP_ANY) ? 15 : r->crm;
+    int opc1min = (r->opc1 == CP_ANY) ? 0 : r->opc1;
+    int opc1max = (r->opc1 == CP_ANY) ? 7 : r->opc1;
+    int opc2min = (r->opc2 == CP_ANY) ? 0 : r->opc2;
+    int opc2max = (r->opc2 == CP_ANY) ? 7 : r->opc2;
+    /* 64 bit registers have only CRm and Opc1 fields */
+    assert(!((r->type & ARM_CP_64BIT) && (r->opc2 || r->crn)));
+    /* Check that the register definition has enough info to handle
+     * reads and writes if they are permitted.
+     */
+    if (!(r->type & (ARM_CP_SPECIAL|ARM_CP_CONST))) {
+        if (r->access & PL3_R) {
+            assert(r->fieldoffset || r->readfn);
+        }
+        if (r->access & PL3_W) {
+            assert(r->fieldoffset || r->writefn);
+        }
+    }
+    /* Bad type field probably means missing sentinel at end of reg list */
+    assert(cptype_valid(r->type));
+    for (crm = crmmin; crm <= crmmax; crm++) {
+        for (opc1 = opc1min; opc1 <= opc1max; opc1++) {
+            for (opc2 = opc2min; opc2 <= opc2max; opc2++) {
+                uint32_t *key = g_new(uint32_t, 1);
+                ARMCPRegInfo *r2 = g_memdup(r, sizeof(ARMCPRegInfo));
+                int is64 = (r->type & ARM_CP_64BIT) ? 1 : 0;
+                *key = ENCODE_CP_REG(r->cp, is64, r->crn, crm, opc1, opc2);
+                r2->opaque = opaque;
+                /* Make sure reginfo passed to helpers for wildcarded regs
+                 * has the correct crm/opc1/opc2 for this reg, not CP_ANY:
+                 */
+                r2->crm = crm;
+                r2->opc1 = opc1;
+                r2->opc2 = opc2;
+                /* Overriding of an existing definition must be explicitly
+                 * requested.
+                 */
+                if (!(r->type & ARM_CP_OVERRIDE)) {
+                    ARMCPRegInfo *oldreg;
+                    oldreg = g_hash_table_lookup(cpu->cp_regs, key);
+                    if (oldreg && !(oldreg->type & ARM_CP_OVERRIDE)) {
+                        fprintf(stderr, "Register redefined: cp=%d %d bit "
+                                "crn=%d crm=%d opc1=%d opc2=%d, "
+                                "was %s, now %s\n", r2->cp, 32 + 32 * is64,
+                                r2->crn, r2->crm, r2->opc1, r2->opc2,
+                                oldreg->name, r2->name);
+                        assert(0);
+                    }
+                }
+                g_hash_table_insert(cpu->cp_regs, key, r2);
+            }
+        }
+    }
+}
+
+void define_arm_cp_regs_with_opaque(ARMCPU *cpu,
+                                    const ARMCPRegInfo *regs, void *opaque)
+{
+    /* Define a whole list of registers */
+    const ARMCPRegInfo *r;
+    for (r = regs; r->type != ARM_CP_SENTINEL; r++) {
+        define_one_arm_cp_reg_with_opaque(cpu, r, opaque);
+    }
+}
+
+const ARMCPRegInfo *get_arm_cp_reginfo(ARMCPU *cpu, uint32_t encoded_cp)
+{
+    return g_hash_table_lookup(cpu->cp_regs, &encoded_cp);
+}
+
+int arm_cp_write_ignore(CPUARMState *env, const ARMCPRegInfo *ri,
+                        uint64_t value)
+{
+    /* Helper coprocessor write function for write-ignore registers */
+    return 0;
+}
+
+int arm_cp_read_zero(CPUARMState *env, const ARMCPRegInfo *ri, uint64_t *value)
+{
+    /* Helper coprocessor write function for read-as-zero registers */
+    *value = 0;
+    return 0;
+}
+
 static int bad_mode_switch(CPUARMState *env, int mode)
 {
     /* Return true if it is not valid for us to switch to
diff --git a/target-arm/helper.h b/target-arm/helper.h
index 16dd5fc..b6cefed 100644
--- a/target-arm/helper.h
+++ b/target-arm/helper.h
@@ -65,6 +65,11 @@ DEF_HELPER_2(get_cp15, i32, env, i32)
 DEF_HELPER_3(set_cp, void, env, i32, i32)
 DEF_HELPER_2(get_cp, i32, env, i32)
 
+DEF_HELPER_3(set_cp_reg, void, env, ptr, i32)
+DEF_HELPER_2(get_cp_reg, i32, env, ptr)
+DEF_HELPER_3(set_cp_reg64, void, env, ptr, i64)
+DEF_HELPER_2(get_cp_reg64, i64, env, ptr)
+
 DEF_HELPER_2(get_r13_banked, i32, env, i32)
 DEF_HELPER_3(set_r13_banked, void, env, i32, i32)
 
diff --git a/target-arm/op_helper.c b/target-arm/op_helper.c
index b53369d..490111c 100644
--- a/target-arm/op_helper.c
+++ b/target-arm/op_helper.c
@@ -23,13 +23,11 @@
 #define SIGNBIT (uint32_t)0x80000000
 #define SIGNBIT64 ((uint64_t)1 << 63)
 
-#if !defined(CONFIG_USER_ONLY)
 static void raise_exception(int tt)
 {
     env->exception_index = tt;
     cpu_loop_exit(env);
 }
-#endif
 
 uint32_t HELPER(neon_tbl)(uint32_t ireg, uint32_t def,
                           uint32_t rn, uint32_t maxindex)
@@ -287,6 +285,46 @@ void HELPER(set_user_reg)(uint32_t regno, uint32_t val)
     }
 }
 
+void HELPER(set_cp_reg)(CPUARMState *env, void *rip, uint32_t value)
+{
+    const ARMCPRegInfo *ri = rip;
+    int excp = ri->writefn(env, ri, value);
+    if (excp) {
+        raise_exception(excp);
+    }
+}
+
+uint32_t HELPER(get_cp_reg)(CPUARMState *env, void *rip)
+{
+    const ARMCPRegInfo *ri = rip;
+    uint64_t value;
+    int excp = ri->readfn(env, ri, &value);
+    if (excp) {
+        raise_exception(excp);
+    }
+    return value;
+}
+
+void HELPER(set_cp_reg64)(CPUARMState *env, void *rip, uint64_t value)
+{
+    const ARMCPRegInfo *ri = rip;
+    int excp = ri->writefn(env, ri, value);
+    if (excp) {
+        raise_exception(excp);
+    }
+}
+
+uint64_t HELPER(get_cp_reg64)(CPUARMState *env, void *rip)
+{
+    const ARMCPRegInfo *ri = rip;
+    uint64_t value;
+    int excp = ri->readfn(env, ri, &value);
+    if (excp) {
+        raise_exception(excp);
+    }
+    return value;
+}
+
 /* ??? Flag setting arithmetic is awkward because we need to do comparisons.
    The only way to do that in TCG is a conditional branch, which clobbers
    all our temporaries.  For now implement these as helper functions.  */
diff --git a/target-arm/translate.c b/target-arm/translate.c
index 437d9db..d7edda7 100644
--- a/target-arm/translate.c
+++ b/target-arm/translate.c
@@ -6479,13 +6479,16 @@ static int disas_cp14_write(CPUARMState * env, DisasContext *s, uint32_t insn)
 
 static int disas_coproc_insn(CPUARMState * env, DisasContext *s, uint32_t insn)
 {
-    int cpnum;
+    int cpnum, is64, crn, crm, opc1, opc2, isread, rt, rt2;
+    const ARMCPRegInfo *ri;
+    ARMCPU *cpu = arm_env_get_cpu(env);
 
     cpnum = (insn >> 8) & 0xf;
     if (arm_feature(env, ARM_FEATURE_XSCALE)
 	    && ((env->cp15.c15_cpar ^ 0x3fff) & (1 << cpnum)))
 	return 1;
 
+    /* First check for coprocessor space used for actual instructions */
     switch (cpnum) {
       case 0:
       case 1:
@@ -6498,6 +6501,157 @@ static int disas_coproc_insn(CPUARMState * env, DisasContext *s, uint32_t insn)
     case 10:
     case 11:
 	return disas_vfp_insn (env, s, insn);
+    default:
+        break;
+    }
+
+    /* Otherwise treat as a generic register access */
+    is64 = (insn & (1 << 25)) == 0;
+    if (!is64 && ((insn & (1 << 4)) == 0)) {
+        /* cdp */
+        return 1;
+    }
+
+    crm = insn & 0xf;
+    if (is64) {
+        crn = 0;
+        opc1 = (insn >> 4) & 0xf;
+        opc2 = 0;
+        rt2 = (insn >> 16) & 0xf;
+    } else {
+        crn = (insn >> 16) & 0xf;
+        opc1 = (insn >> 21) & 7;
+        opc2 = (insn >> 5) & 7;
+        rt2 = 0;
+    }
+    isread = (insn >> 20) & 1;
+    rt = (insn >> 12) & 0xf;
+
+    ri = get_arm_cp_reginfo(cpu,
+                            ENCODE_CP_REG(cpnum, is64, crn, crm, opc1, opc2));
+    if (ri) {
+        /* Check access permissions */
+        if (!cp_access_ok(env, ri, isread)) {
+            return 1;
+        }
+
+        /* Handle special cases first */
+        switch (ri->type & ~(ARM_CP_FLAG_MASK & ~ARM_CP_SPECIAL)) {
+        case ARM_CP_NOP:
+            return 0;
+        case ARM_CP_WFI:
+            if (isread) {
+                return 1;
+            }
+            gen_set_pc_im(s->pc);
+            s->is_jmp = DISAS_WFI;
+            break;
+        default:
+            break;
+        }
+
+        if (isread) {
+            /* Read */
+            if (is64) {
+                TCGv_i64 tmp64;
+                TCGv_i32 tmp;
+                if (ri->type & ARM_CP_CONST) {
+                    tmp64 = tcg_const_i64(ri->resetvalue);
+                } else if (ri->readfn) {
+                    TCGv_ptr tmpptr;
+                    gen_set_pc_im(s->pc);
+                    tmp64 = tcg_temp_new_i64();
+                    tmpptr = tcg_const_ptr(ri);
+                    gen_helper_get_cp_reg64(tmp64, cpu_env, tmpptr);
+                    tcg_temp_free_ptr(tmpptr);
+                } else {
+                    tmp64 = tcg_temp_new_i64();
+                    tcg_gen_ld_i64(tmp64, cpu_env, ri->fieldoffset);
+                }
+                tmp = tcg_temp_new_i32();
+                tcg_gen_trunc_i64_i32(tmp, tmp64);
+                store_reg(s, rt, tmp);
+                tcg_gen_shri_i64(tmp64, tmp64, 32);
+                tcg_gen_trunc_i64_i32(tmp, tmp64);
+                store_reg(s, rt2, tmp);
+            } else {
+                TCGv tmp;
+                if (ri->type & ARM_CP_CONST) {
+                    tmp = tcg_const_i32(ri->resetvalue);
+                } else if (ri->readfn) {
+                    TCGv_ptr tmpptr;
+                    gen_set_pc_im(s->pc);
+                    tmp = tcg_temp_new_i32();
+                    tmpptr = tcg_const_ptr(ri);
+                    gen_helper_get_cp_reg(tmp, cpu_env, tmpptr);
+                    tcg_temp_free_ptr(tmpptr);
+                } else {
+                    tmp = load_cpu_offset(ri->fieldoffset);
+                }
+                if (rt == 15) {
+                    /* Destination register of r15 for 32 bit loads sets
+                     * the condition codes from the high 4 bits of the value
+                     */
+                    gen_set_nzcv(tmp);
+                    tcg_temp_free_i32(tmp);
+                } else {
+                    store_reg(s, rt, tmp);
+                }
+            }
+        } else {
+            /* Write */
+            if (ri->type & ARM_CP_CONST) {
+                /* If not forbidden by access permissions, treat as WI */
+                return 0;
+            }
+
+            if (is64) {
+                TCGv tmplo, tmphi;
+                TCGv_i64 tmp64 = tcg_temp_new_i64();
+                tmplo = load_reg(s, rt);
+                tmphi = load_reg(s, rt2);
+                tcg_gen_concat_i32_i64(tmp64, tmplo, tmphi);
+                tcg_temp_free_i32(tmplo);
+                tcg_temp_free_i32(tmphi);
+                if (ri->writefn) {
+                    TCGv_ptr tmpptr = tcg_const_ptr(ri);
+                    gen_set_pc_im(s->pc);
+                    gen_helper_set_cp_reg64(cpu_env, tmpptr, tmp64);
+                    tcg_temp_free_ptr(tmpptr);
+                } else {
+                    tcg_gen_st_i64(tmp64, cpu_env, ri->fieldoffset);
+                }
+                tcg_temp_free_i64(tmp64);
+            } else {
+                if (ri->writefn) {
+                    TCGv tmp;
+                    TCGv_ptr tmpptr;
+                    gen_set_pc_im(s->pc);
+                    tmp = load_reg(s, rt);
+                    tmpptr = tcg_const_ptr(ri);
+                    gen_helper_set_cp_reg(cpu_env, tmpptr, tmp);
+                    tcg_temp_free_ptr(tmpptr);
+                    tcg_temp_free_i32(tmp);
+                } else {
+                    TCGv tmp = load_reg(s, rt);
+                    store_cpu_offset(tmp, ri->fieldoffset);
+                }
+            }
+            /* We default to ending the TB on a coprocessor register write,
+             * but allow this to be suppressed by the register definition
+             * (usually only necessary to work around guest bugs).
+             */
+            if (!(ri->type & ARM_CP_SUPPRESS_TB_END)) {
+                gen_lookup_tb(s);
+            }
+        }
+        return 0;
+    }
+
+    /* Fallback code: handle coprocessor registers not yet converted
+     * to ARMCPRegInfo.
+     */
+    switch (cpnum) {
     case 14:
         /* Coprocessors 7-15 are architecturally reserved by ARM.
            Unfortunately Intel decided to ignore this.  */
commit 200bf596b96820186883953de9bda26cac8e6bd7
Author: Peter Maydell <peter.maydell at linaro.org>
Date:   Wed Jun 20 11:57:06 2012 +0000

    target-arm: Fix 11MPCore cache type register value
    
    Make the 11MPCore report a valid value in its cache type register
    (the previous value appears to have been incorrectly copied from
    the 1136/1176). In particular, do not report that we have an
    aliasing VIPT cache, because this causes Linux to attempt to use
    the v6 block cache ops which the 11MPCore doesn't actually have.
    (This causes no problems currently because we over-broadly provide
    those ops on all cores, but prevents us correctly narrowing the
    block ops down to those cores which actually implement them.)
    
    Signed-off-by: Peter Maydell <peter.maydell at linaro.org>

diff --git a/target-arm/cpu.c b/target-arm/cpu.c
index 7eb323a..934894b 100644
--- a/target-arm/cpu.c
+++ b/target-arm/cpu.c
@@ -307,7 +307,7 @@ static void arm11mpcore_initfn(Object *obj)
     cpu->reset_fpsid = 0x410120b4;
     cpu->mvfr0 = 0x11111111;
     cpu->mvfr1 = 0x00000000;
-    cpu->ctr = 0x1dd20d2;
+    cpu->ctr = 0x1d192992; /* 32K icache 32K dcache */
     cpu->id_pfr0 = 0x111;
     cpu->id_pfr1 = 0x1;
     cpu->id_dfr0 = 0;
commit 5e87975c87b35c66be3f33080c0e5cf6c6d451a5
Author: Peter A. G. Crosthwaite <peter.crosthwaite at petalogix.com>
Date:   Sun Jun 17 15:35:36 2012 +0000

    arm_boot: Conditionalised DTB command line update
    
    The DTB command line should only be overwritten if the user provides a command
    line with -append. Otherwise whatever command line was in the DTB should stay
    unchanged.
    
    Signed-off-by: Peter A. G. Crosthwaite <peter.crosthwaite at petalogix.com>
    Signed-off-by: Peter Maydell <peter.maydell at linaro.org>

diff --git a/hw/arm_boot.c b/hw/arm_boot.c
index d0e643b..a1e6ddb 100644
--- a/hw/arm_boot.c
+++ b/hw/arm_boot.c
@@ -242,10 +242,12 @@ static int load_dtb(target_phys_addr_t addr, const struct arm_boot_info *binfo)
         fprintf(stderr, "couldn't set /memory/reg\n");
     }
 
-    rc = qemu_devtree_setprop_string(fdt, "/chosen", "bootargs",
-                                      binfo->kernel_cmdline);
-    if (rc < 0) {
-        fprintf(stderr, "couldn't set /chosen/bootargs\n");
+    if (binfo->kernel_cmdline && *binfo->kernel_cmdline) {
+        rc = qemu_devtree_setprop_string(fdt, "/chosen", "bootargs",
+                                          binfo->kernel_cmdline);
+        if (rc < 0) {
+            fprintf(stderr, "couldn't set /chosen/bootargs\n");
+        }
     }
 
     if (binfo->initrd_size) {
commit 69efc0265f3447a891fabe941208b1e11d6091af
Author: Peter A. G. Crosthwaite <peter.crosthwaite at petalogix.com>
Date:   Mon May 28 17:16:28 2012 +0000

    cadence_ttc: changed master clock frequency
    
    Change the timer clock frequency to 133MHz which is correct. the old 2.5MHz
    value was for the pre-silicon emulation platform.
    
    Signed-off-by: Peter A. G. Crosthwaite <peter.crosthwaite at petalogix.com>
    Signed-off-by: Peter Maydell <peter.maydell at linaro.org>

diff --git a/hw/cadence_ttc.c b/hw/cadence_ttc.c
index 2b5477b..dd02f86 100644
--- a/hw/cadence_ttc.c
+++ b/hw/cadence_ttc.c
@@ -405,7 +405,7 @@ static int cadence_ttc_init(SysBusDevice *dev)
     int i;
 
     for (i = 0; i < 3; ++i) {
-        cadence_timer_init(2500000, &s->timer[i]);
+        cadence_timer_init(133000000, &s->timer[i]);
         sysbus_init_irq(dev, &s->timer[i].irq);
     }
 
commit 5fbe02e8bb7c62ee55b8edc5fd688c369164c49c
Author: Jim Meyering <meyering at redhat.com>
Date:   Thu May 10 06:19:48 2012 +0000

    cadence_gem: avoid stack-writing buffer-overrun
    
    Use sizeof(rxbuf)-size (not sizeof(rxbuf-size)) as the number
    of bytes to clear.  The latter would always clear 4 or 8
    bytes, possibly writing beyond the end of that stack buffer.
    Alternatively, depending on the value of the "size" parameter,
    it could fail to initialize the end of "rxbuf".
    Spotted by coverity.
    
    Signed-off-by: Jim Meyering <meyering at redhat.com>
    Reviewed-by: Peter A.G. Crosthwaite <peter.crosthwaite at petalogix.com>
    Signed-off-by: Peter Maydell <peter.maydell at linaro.org>

diff --git a/hw/cadence_gem.c b/hw/cadence_gem.c
index e2140ae..dbde392 100644
--- a/hw/cadence_gem.c
+++ b/hw/cadence_gem.c
@@ -664,7 +664,7 @@ static ssize_t gem_receive(VLANClientState *nc, const uint8_t *buf, size_t size)
          */
 
         memcpy(rxbuf, buf, size);
-        memset(rxbuf + size, 0, sizeof(rxbuf - size));
+        memset(rxbuf + size, 0, sizeof(rxbuf) - size);
         rxbuf_ptr = rxbuf;
         crc_val = cpu_to_le32(crc32(0, rxbuf, MAX(size, 60)));
         if (size < 60) {
commit c97338dca0197abad7f0c789ad61d45940f67011
Author: Peter Maydell <peter.maydell at linaro.org>
Date:   Tue May 22 14:29:52 2012 +0000

    hw/a9mpcore: Fix compilation failure if physaddrs are 64 bit
    
    Add a cast to a logging printf to avoid a compilation failure
    if target_phys_addr_t is a 64 bit type. (This is better than
    using TARGET_FMT_plx because we really don't need a full
    16 digit hex string to print the offset into a device.)
    
    Signed-off-by: Peter Maydell <peter.maydell at linaro.org>
    Reviewed-by: Eric Blake <eblake at redhat.com>

diff --git a/hw/a9mpcore.c b/hw/a9mpcore.c
index c2ff74d..ebd5b29 100644
--- a/hw/a9mpcore.c
+++ b/hw/a9mpcore.c
@@ -75,7 +75,7 @@ static void a9_scu_write(void *opaque, target_phys_addr_t offset,
         break;
     default:
         fprintf(stderr, "Invalid size %u in write to a9 scu register %x\n",
-                size, offset);
+                size, (unsigned)offset);
         return;
     }
 
commit cff0cfbed5b8c41938af3d134381ea76ee0242f7
Author: Peter Maydell <peter.maydell at linaro.org>
Date:   Tue May 15 16:46:26 2012 +0000

    hw/omap.h: Drop broken MEM_VERBOSE tracing
    
    Remove the MEM_VERBOSE tracing option from omap.h. This worked by
    intercepting cpu_register_io_memory() calls; it has been broken
    since cpu_register_io_memory() was removed in favour of the
    MemoryRegion API.
    
    Signed-off-by: Peter Maydell <peter.maydell at linaro.org>

diff --git a/hw/omap.h b/hw/omap.h
index 2819e5d..3d98941 100644
--- a/hw/omap.h
+++ b/hw/omap.h
@@ -998,7 +998,6 @@ enum {
 #define OMAP_GPIOSW_OUTPUT	0x0002
 
 # define TCMI_VERBOSE			1
-//# define MEM_VERBOSE			1
 
 # ifdef TCMI_VERBOSE
 #  define OMAP_8B_REG(paddr)		\
@@ -1018,98 +1017,4 @@ enum {
 
 # define OMAP_MPUI_REG_MASK		0x000007ff
 
-# ifdef MEM_VERBOSE
-struct io_fn {
-    CPUReadMemoryFunc * const *mem_read;
-    CPUWriteMemoryFunc * const *mem_write;
-    void *opaque;
-    int in;
-};
-
-static uint32_t io_readb(void *opaque, target_phys_addr_t addr)
-{
-    struct io_fn *s = opaque;
-    uint32_t ret;
-
-    s->in ++;
-    ret = s->mem_read[0](s->opaque, addr);
-    s->in --;
-    if (!s->in)
-        fprintf(stderr, "%08x ---> %02x\n", (uint32_t) addr, ret);
-    return ret;
-}
-static uint32_t io_readh(void *opaque, target_phys_addr_t addr)
-{
-    struct io_fn *s = opaque;
-    uint32_t ret;
-
-    s->in ++;
-    ret = s->mem_read[1](s->opaque, addr);
-    s->in --;
-    if (!s->in)
-        fprintf(stderr, "%08x ---> %04x\n", (uint32_t) addr, ret);
-    return ret;
-}
-static uint32_t io_readw(void *opaque, target_phys_addr_t addr)
-{
-    struct io_fn *s = opaque;
-    uint32_t ret;
-
-    s->in ++;
-    ret = s->mem_read[2](s->opaque, addr);
-    s->in --;
-    if (!s->in)
-        fprintf(stderr, "%08x ---> %08x\n", (uint32_t) addr, ret);
-    return ret;
-}
-static void io_writeb(void *opaque, target_phys_addr_t addr, uint32_t value)
-{
-    struct io_fn *s = opaque;
-
-    if (!s->in)
-        fprintf(stderr, "%08x <--- %02x\n", (uint32_t) addr, value);
-    s->in ++;
-    s->mem_write[0](s->opaque, addr, value);
-    s->in --;
-}
-static void io_writeh(void *opaque, target_phys_addr_t addr, uint32_t value)
-{
-    struct io_fn *s = opaque;
-
-    if (!s->in)
-        fprintf(stderr, "%08x <--- %04x\n", (uint32_t) addr, value);
-    s->in ++;
-    s->mem_write[1](s->opaque, addr, value);
-    s->in --;
-}
-static void io_writew(void *opaque, target_phys_addr_t addr, uint32_t value)
-{
-    struct io_fn *s = opaque;
-
-    if (!s->in)
-        fprintf(stderr, "%08x <--- %08x\n", (uint32_t) addr, value);
-    s->in ++;
-    s->mem_write[2](s->opaque, addr, value);
-    s->in --;
-}
-
-static CPUReadMemoryFunc * const io_readfn[] = { io_readb, io_readh, io_readw, };
-static CPUWriteMemoryFunc * const io_writefn[] = { io_writeb, io_writeh, io_writew, };
-
-inline static int debug_register_io_memory(CPUReadMemoryFunc * const *mem_read,
-                                           CPUWriteMemoryFunc * const *mem_write,
-                                           void *opaque)
-{
-    struct io_fn *s = g_malloc(sizeof(struct io_fn));
-
-    s->mem_read = mem_read;
-    s->mem_write = mem_write;
-    s->opaque = opaque;
-    s->in = 0;
-    return cpu_register_io_memory(io_readfn, io_writefn, s,
-                                  DEVICE_NATIVE_ENDIAN);
-}
-#  define cpu_register_io_memory	debug_register_io_memory
-# endif
-
 #endif /* hw_omap_h */
commit 1e8cae4dfea2bcc91d3820dcf4f9284e7b0abb28
Author: Peter Maydell <peter.maydell at linaro.org>
Date:   Wed May 2 16:49:42 2012 +0000

    hw/armv7m_nvic: Make the NVIC a freestanding class
    
    Rearrange the GIC and NVIC so both are straightforward
    subclasses of a common class, rather than having the NVIC
    source file textually include arm_gic.c.
    
    Signed-off-by: Peter Maydell <peter.maydell at linaro.org>

diff --git a/hw/arm/Makefile.objs b/hw/arm/Makefile.objs
index a0ff6a6..88ff47d 100644
--- a/hw/arm/Makefile.objs
+++ b/hw/arm/Makefile.objs
@@ -6,7 +6,7 @@ obj-y += cadence_uart.o
 obj-y += cadence_ttc.o
 obj-y += cadence_gem.o
 obj-y += xilinx_zynq.o zynq_slcr.o
-obj-y += arm_gic.o
+obj-y += arm_gic.o arm_gic_common.o
 obj-y += realview_gic.o realview.o arm_sysctl.o arm11mpcore.o a9mpcore.o
 obj-y += exynos4210_gic.o exynos4210_combiner.o exynos4210.o
 obj-y += exynos4_boards.o exynos4210_uart.o exynos4210_pwm.o
diff --git a/hw/arm_gic.c b/hw/arm_gic.c
index ad5ab3c..ec22322 100644
--- a/hw/arm_gic.c
+++ b/hw/arm_gic.c
@@ -19,13 +19,7 @@
  */
 
 #include "sysbus.h"
-
-/* Maximum number of possible interrupts, determined by the GIC architecture */
-#define GIC_MAXIRQ 1020
-/* First 32 are private to each CPU (SGIs and PPIs). */
-#define GIC_INTERNAL 32
-/* Maximum number of possible CPU interfaces, determined by GIC architecture */
-#define NCPU 8
+#include "arm_gic_internal.h"
 
 //#define DEBUG_GIC
 
@@ -36,88 +30,12 @@ do { printf("arm_gic: " fmt , ## __VA_ARGS__); } while (0)
 #define DPRINTF(fmt, ...) do {} while(0)
 #endif
 
-/* The NVIC has 16 internal vectors.  However these are not exposed
-   through the normal GIC interface.  */
-#define GIC_BASE_IRQ ((s->revision == REV_NVIC) ? 32 : 0)
-
 static const uint8_t gic_id[] = {
     0x90, 0x13, 0x04, 0x00, 0x0d, 0xf0, 0x05, 0xb1
 };
 
-#define FROM_SYSBUSGIC(type, dev) \
-    DO_UPCAST(type, gic, FROM_SYSBUS(gic_state, dev))
-
-typedef struct gic_irq_state
-{
-    /* The enable bits are only banked for per-cpu interrupts.  */
-    unsigned enabled:NCPU;
-    unsigned pending:NCPU;
-    unsigned active:NCPU;
-    unsigned level:NCPU;
-    unsigned model:1; /* 0 = N:N, 1 = 1:N */
-    unsigned trigger:1; /* nonzero = edge triggered.  */
-} gic_irq_state;
-
-#define ALL_CPU_MASK ((unsigned)(((1 << NCPU) - 1)))
 #define NUM_CPU(s) ((s)->num_cpu)
 
-#define GIC_SET_ENABLED(irq, cm) s->irq_state[irq].enabled |= (cm)
-#define GIC_CLEAR_ENABLED(irq, cm) s->irq_state[irq].enabled &= ~(cm)
-#define GIC_TEST_ENABLED(irq, cm) ((s->irq_state[irq].enabled & (cm)) != 0)
-#define GIC_SET_PENDING(irq, cm) s->irq_state[irq].pending |= (cm)
-#define GIC_CLEAR_PENDING(irq, cm) s->irq_state[irq].pending &= ~(cm)
-#define GIC_TEST_PENDING(irq, cm) ((s->irq_state[irq].pending & (cm)) != 0)
-#define GIC_SET_ACTIVE(irq, cm) s->irq_state[irq].active |= (cm)
-#define GIC_CLEAR_ACTIVE(irq, cm) s->irq_state[irq].active &= ~(cm)
-#define GIC_TEST_ACTIVE(irq, cm) ((s->irq_state[irq].active & (cm)) != 0)
-#define GIC_SET_MODEL(irq) s->irq_state[irq].model = 1
-#define GIC_CLEAR_MODEL(irq) s->irq_state[irq].model = 0
-#define GIC_TEST_MODEL(irq) s->irq_state[irq].model
-#define GIC_SET_LEVEL(irq, cm) s->irq_state[irq].level = (cm)
-#define GIC_CLEAR_LEVEL(irq, cm) s->irq_state[irq].level &= ~(cm)
-#define GIC_TEST_LEVEL(irq, cm) ((s->irq_state[irq].level & (cm)) != 0)
-#define GIC_SET_TRIGGER(irq) s->irq_state[irq].trigger = 1
-#define GIC_CLEAR_TRIGGER(irq) s->irq_state[irq].trigger = 0
-#define GIC_TEST_TRIGGER(irq) s->irq_state[irq].trigger
-#define GIC_GET_PRIORITY(irq, cpu) (((irq) < GIC_INTERNAL) ?            \
-                                    s->priority1[irq][cpu] :            \
-                                    s->priority2[(irq) - GIC_INTERNAL])
-#define GIC_TARGET(irq) s->irq_target[irq]
-
-typedef struct gic_state
-{
-    SysBusDevice busdev;
-    qemu_irq parent_irq[NCPU];
-    int enabled;
-    int cpu_enabled[NCPU];
-
-    gic_irq_state irq_state[GIC_MAXIRQ];
-    int irq_target[GIC_MAXIRQ];
-    int priority1[GIC_INTERNAL][NCPU];
-    int priority2[GIC_MAXIRQ - GIC_INTERNAL];
-    int last_active[GIC_MAXIRQ][NCPU];
-
-    int priority_mask[NCPU];
-    int running_irq[NCPU];
-    int running_priority[NCPU];
-    int current_pending[NCPU];
-
-    uint32_t num_cpu;
-
-    MemoryRegion iomem; /* Distributor */
-    /* This is just so we can have an opaque pointer which identifies
-     * both this GIC and which CPU interface we should be accessing.
-     */
-    struct gic_state *backref[NCPU];
-    MemoryRegion cpuiomem[NCPU+1]; /* CPU interfaces */
-    uint32_t num_irq;
-    uint32_t revision;
-} gic_state;
-
-/* The special cases for the revision property: */
-#define REV_11MPCORE 0
-#define REV_NVIC 0xffffffff
-
 static inline int gic_get_current_cpu(gic_state *s)
 {
     if (s->num_cpu > 1) {
@@ -128,7 +46,7 @@ static inline int gic_get_current_cpu(gic_state *s)
 
 /* TODO: Many places that call this routine could be optimized.  */
 /* Update interrupt status after enabled or pending bits have been changed.  */
-static void gic_update(gic_state *s)
+void gic_update(gic_state *s)
 {
     int best_irq;
     int best_prio;
@@ -166,8 +84,7 @@ static void gic_update(gic_state *s)
     }
 }
 
-#ifdef NVIC
-static void gic_set_pending_private(gic_state *s, int cpu, int irq)
+void gic_set_pending_private(gic_state *s, int cpu, int irq)
 {
     int cm = 1 << cpu;
 
@@ -178,7 +95,6 @@ static void gic_set_pending_private(gic_state *s, int cpu, int irq)
     GIC_SET_PENDING(irq, cm);
     gic_update(s);
 }
-#endif
 
 /* Process a change in an external IRQ input.  */
 static void gic_set_irq(void *opaque, int irq, int level)
@@ -232,7 +148,7 @@ static void gic_set_running_irq(gic_state *s, int cpu, int irq)
     gic_update(s);
 }
 
-static uint32_t gic_acknowledge_irq(gic_state *s, int cpu)
+uint32_t gic_acknowledge_irq(gic_state *s, int cpu)
 {
     int new_irq;
     int cm = 1 << cpu;
@@ -251,7 +167,7 @@ static uint32_t gic_acknowledge_irq(gic_state *s, int cpu)
     return new_irq;
 }
 
-static void gic_complete_irq(gic_state * s, int cpu, int irq)
+void gic_complete_irq(gic_state *s, int cpu, int irq)
 {
     int update = 0;
     int cm = 1 << cpu;
@@ -623,7 +539,6 @@ static const MemoryRegionOps gic_dist_ops = {
     .endianness = DEVICE_NATIVE_ENDIAN,
 };
 
-#ifndef NVIC
 static uint32_t gic_cpu_read(gic_state *s, int cpu, int offset)
 {
     switch (offset) {
@@ -715,124 +630,10 @@ static const MemoryRegionOps gic_cpu_ops = {
     .write = gic_do_cpu_write,
     .endianness = DEVICE_NATIVE_ENDIAN,
 };
-#endif
 
-static void gic_reset(DeviceState *dev)
+void gic_init_irqs_and_distributor(gic_state *s, int num_irq)
 {
-    gic_state *s = FROM_SYSBUS(gic_state, sysbus_from_qdev(dev));
-    int i;
-    memset(s->irq_state, 0, GIC_MAXIRQ * sizeof(gic_irq_state));
-    for (i = 0 ; i < NUM_CPU(s); i++) {
-        s->priority_mask[i] = 0xf0;
-        s->current_pending[i] = 1023;
-        s->running_irq[i] = 1023;
-        s->running_priority[i] = 0x100;
-        s->cpu_enabled[i] = 0;
-    }
-    for (i = 0; i < 16; i++) {
-        GIC_SET_ENABLED(i, ALL_CPU_MASK);
-        GIC_SET_TRIGGER(i);
-    }
-    if (s->num_cpu == 1) {
-        /* For uniprocessor GICs all interrupts always target the sole CPU */
-        for (i = 0; i < GIC_MAXIRQ; i++) {
-            s->irq_target[i] = 1;
-        }
-    }
-    s->enabled = 0;
-}
-
-static void gic_save(QEMUFile *f, void *opaque)
-{
-    gic_state *s = (gic_state *)opaque;
-    int i;
-    int j;
-
-    qemu_put_be32(f, s->enabled);
-    for (i = 0; i < NUM_CPU(s); i++) {
-        qemu_put_be32(f, s->cpu_enabled[i]);
-        for (j = 0; j < GIC_INTERNAL; j++)
-            qemu_put_be32(f, s->priority1[j][i]);
-        for (j = 0; j < s->num_irq; j++)
-            qemu_put_be32(f, s->last_active[j][i]);
-        qemu_put_be32(f, s->priority_mask[i]);
-        qemu_put_be32(f, s->running_irq[i]);
-        qemu_put_be32(f, s->running_priority[i]);
-        qemu_put_be32(f, s->current_pending[i]);
-    }
-    for (i = 0; i < s->num_irq - GIC_INTERNAL; i++) {
-        qemu_put_be32(f, s->priority2[i]);
-    }
-    for (i = 0; i < s->num_irq; i++) {
-        qemu_put_be32(f, s->irq_target[i]);
-        qemu_put_byte(f, s->irq_state[i].enabled);
-        qemu_put_byte(f, s->irq_state[i].pending);
-        qemu_put_byte(f, s->irq_state[i].active);
-        qemu_put_byte(f, s->irq_state[i].level);
-        qemu_put_byte(f, s->irq_state[i].model);
-        qemu_put_byte(f, s->irq_state[i].trigger);
-    }
-}
-
-static int gic_load(QEMUFile *f, void *opaque, int version_id)
-{
-    gic_state *s = (gic_state *)opaque;
     int i;
-    int j;
-
-    if (version_id != 3) {
-        return -EINVAL;
-    }
-
-    s->enabled = qemu_get_be32(f);
-    for (i = 0; i < NUM_CPU(s); i++) {
-        s->cpu_enabled[i] = qemu_get_be32(f);
-        for (j = 0; j < GIC_INTERNAL; j++)
-            s->priority1[j][i] = qemu_get_be32(f);
-        for (j = 0; j < s->num_irq; j++)
-            s->last_active[j][i] = qemu_get_be32(f);
-        s->priority_mask[i] = qemu_get_be32(f);
-        s->running_irq[i] = qemu_get_be32(f);
-        s->running_priority[i] = qemu_get_be32(f);
-        s->current_pending[i] = qemu_get_be32(f);
-    }
-    for (i = 0; i < s->num_irq - GIC_INTERNAL; i++) {
-        s->priority2[i] = qemu_get_be32(f);
-    }
-    for (i = 0; i < s->num_irq; i++) {
-        s->irq_target[i] = qemu_get_be32(f);
-        s->irq_state[i].enabled = qemu_get_byte(f);
-        s->irq_state[i].pending = qemu_get_byte(f);
-        s->irq_state[i].active = qemu_get_byte(f);
-        s->irq_state[i].level = qemu_get_byte(f);
-        s->irq_state[i].model = qemu_get_byte(f);
-        s->irq_state[i].trigger = qemu_get_byte(f);
-    }
-
-    return 0;
-}
-
-static void gic_init_irqs_and_distributor(gic_state *s, int num_irq)
-{
-    int i;
-
-    if (s->num_cpu > NCPU) {
-        hw_error("requested %u CPUs exceeds GIC maximum %d\n",
-                 s->num_cpu, NCPU);
-    }
-    s->num_irq = num_irq + GIC_BASE_IRQ;
-    if (s->num_irq > GIC_MAXIRQ) {
-        hw_error("requested %u interrupt lines exceeds GIC maximum %d\n",
-                 num_irq, GIC_MAXIRQ);
-    }
-    /* ITLinesNumber is represented as (N / 32) - 1 (see
-     * gic_dist_readb) so this is an implementation imposed
-     * restriction, not an architectural one:
-     */
-    if (s->num_irq < 32 || (s->num_irq % 32)) {
-        hw_error("%d interrupt lines unsupported: not divisible by 32\n",
-                 num_irq);
-    }
 
     i = s->num_irq - GIC_INTERNAL;
     /* For the GIC, also expose incoming GPIO lines for PPIs for each CPU.
@@ -850,17 +651,17 @@ static void gic_init_irqs_and_distributor(gic_state *s, int num_irq)
         sysbus_init_irq(&s->busdev, &s->parent_irq[i]);
     }
     memory_region_init_io(&s->iomem, &gic_dist_ops, s, "gic_dist", 0x1000);
-
-    register_savevm(NULL, "arm_gic", -1, 3, gic_save, gic_load, s);
 }
 
-#ifndef NVIC
-
 static int arm_gic_init(SysBusDevice *dev)
 {
     /* Device instance init function for the GIC sysbus device */
     int i;
     gic_state *s = FROM_SYSBUS(gic_state, dev);
+    ARMGICClass *agc = ARM_GIC_GET_CLASS(s);
+
+    agc->parent_init(dev);
+
     gic_init_irqs_and_distributor(s, s->num_irq);
 
     /* Memory regions for the CPU interfaces (NVIC doesn't have these):
@@ -878,7 +679,6 @@ static int arm_gic_init(SysBusDevice *dev)
         memory_region_init_io(&s->cpuiomem[i+1], &gic_cpu_ops, &s->backref[i],
                               "gic_cpu", 0x100);
     }
-
     /* Distributor */
     sysbus_init_mmio(dev, &s->iomem);
     /* cpu interfaces (one for "current cpu" plus one per cpu) */
@@ -888,30 +688,19 @@ static int arm_gic_init(SysBusDevice *dev)
     return 0;
 }
 
-static Property arm_gic_properties[] = {
-    DEFINE_PROP_UINT32("num-cpu", gic_state, num_cpu, 1),
-    DEFINE_PROP_UINT32("num-irq", gic_state, num_irq, 32),
-    /* Revision can be 1 or 2 for GIC architecture specification
-     * versions 1 or 2, or 0 to indicate the legacy 11MPCore GIC.
-     * (Internally, 0xffffffff also indicates "not a GIC but an NVIC".)
-     */
-    DEFINE_PROP_UINT32("revision", gic_state, revision, 1),
-    DEFINE_PROP_END_OF_LIST(),
-};
-
 static void arm_gic_class_init(ObjectClass *klass, void *data)
 {
     DeviceClass *dc = DEVICE_CLASS(klass);
     SysBusDeviceClass *sbc = SYS_BUS_DEVICE_CLASS(klass);
+    ARMGICClass *agc = ARM_GIC_CLASS(klass);
+    agc->parent_init = sbc->init;
     sbc->init = arm_gic_init;
-    dc->props = arm_gic_properties;
-    dc->reset = gic_reset;
     dc->no_user = 1;
 }
 
 static TypeInfo arm_gic_info = {
-    .name = "arm_gic",
-    .parent = TYPE_SYS_BUS_DEVICE,
+    .name = TYPE_ARM_GIC,
+    .parent = TYPE_ARM_GIC_COMMON,
     .instance_size = sizeof(gic_state),
     .class_init = arm_gic_class_init,
 };
@@ -922,5 +711,3 @@ static void arm_gic_register_types(void)
 }
 
 type_init(arm_gic_register_types)
-
-#endif
diff --git a/hw/arm_gic_common.c b/hw/arm_gic_common.c
new file mode 100644
index 0000000..360e782
--- /dev/null
+++ b/hw/arm_gic_common.c
@@ -0,0 +1,184 @@
+/*
+ * ARM GIC support - common bits of emulated and KVM kernel model
+ *
+ * Copyright (c) 2012 Linaro Limited
+ * Written by Peter Maydell
+ *
+ * This program is free software; you can redistribute it and/or modify
+ * it under the terms of the GNU General Public License as published by
+ * the Free Software Foundation, either version 2 of the License, or
+ * (at your option) any later version.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License along
+ * with this program; if not, see <http://www.gnu.org/licenses/>.
+ */
+
+#include "arm_gic_internal.h"
+
+static void gic_save(QEMUFile *f, void *opaque)
+{
+    gic_state *s = (gic_state *)opaque;
+    int i;
+    int j;
+
+    qemu_put_be32(f, s->enabled);
+    for (i = 0; i < s->num_cpu; i++) {
+        qemu_put_be32(f, s->cpu_enabled[i]);
+        for (j = 0; j < GIC_INTERNAL; j++) {
+            qemu_put_be32(f, s->priority1[j][i]);
+        }
+        for (j = 0; j < s->num_irq; j++) {
+            qemu_put_be32(f, s->last_active[j][i]);
+        }
+        qemu_put_be32(f, s->priority_mask[i]);
+        qemu_put_be32(f, s->running_irq[i]);
+        qemu_put_be32(f, s->running_priority[i]);
+        qemu_put_be32(f, s->current_pending[i]);
+    }
+    for (i = 0; i < s->num_irq - GIC_INTERNAL; i++) {
+        qemu_put_be32(f, s->priority2[i]);
+    }
+    for (i = 0; i < s->num_irq; i++) {
+        qemu_put_be32(f, s->irq_target[i]);
+        qemu_put_byte(f, s->irq_state[i].enabled);
+        qemu_put_byte(f, s->irq_state[i].pending);
+        qemu_put_byte(f, s->irq_state[i].active);
+        qemu_put_byte(f, s->irq_state[i].level);
+        qemu_put_byte(f, s->irq_state[i].model);
+        qemu_put_byte(f, s->irq_state[i].trigger);
+    }
+}
+
+static int gic_load(QEMUFile *f, void *opaque, int version_id)
+{
+    gic_state *s = (gic_state *)opaque;
+    int i;
+    int j;
+
+    if (version_id != 3) {
+        return -EINVAL;
+    }
+
+    s->enabled = qemu_get_be32(f);
+    for (i = 0; i < s->num_cpu; i++) {
+        s->cpu_enabled[i] = qemu_get_be32(f);
+        for (j = 0; j < GIC_INTERNAL; j++) {
+            s->priority1[j][i] = qemu_get_be32(f);
+        }
+        for (j = 0; j < s->num_irq; j++) {
+            s->last_active[j][i] = qemu_get_be32(f);
+        }
+        s->priority_mask[i] = qemu_get_be32(f);
+        s->running_irq[i] = qemu_get_be32(f);
+        s->running_priority[i] = qemu_get_be32(f);
+        s->current_pending[i] = qemu_get_be32(f);
+    }
+    for (i = 0; i < s->num_irq - GIC_INTERNAL; i++) {
+        s->priority2[i] = qemu_get_be32(f);
+    }
+    for (i = 0; i < s->num_irq; i++) {
+        s->irq_target[i] = qemu_get_be32(f);
+        s->irq_state[i].enabled = qemu_get_byte(f);
+        s->irq_state[i].pending = qemu_get_byte(f);
+        s->irq_state[i].active = qemu_get_byte(f);
+        s->irq_state[i].level = qemu_get_byte(f);
+        s->irq_state[i].model = qemu_get_byte(f);
+        s->irq_state[i].trigger = qemu_get_byte(f);
+    }
+
+    return 0;
+}
+
+static int arm_gic_common_init(SysBusDevice *dev)
+{
+    gic_state *s = FROM_SYSBUS(gic_state, dev);
+    int num_irq = s->num_irq;
+
+    if (s->num_cpu > NCPU) {
+        hw_error("requested %u CPUs exceeds GIC maximum %d\n",
+                 s->num_cpu, NCPU);
+    }
+    s->num_irq += GIC_BASE_IRQ;
+    if (s->num_irq > GIC_MAXIRQ) {
+        hw_error("requested %u interrupt lines exceeds GIC maximum %d\n",
+                 num_irq, GIC_MAXIRQ);
+    }
+    /* ITLinesNumber is represented as (N / 32) - 1 (see
+     * gic_dist_readb) so this is an implementation imposed
+     * restriction, not an architectural one:
+     */
+    if (s->num_irq < 32 || (s->num_irq % 32)) {
+        hw_error("%d interrupt lines unsupported: not divisible by 32\n",
+                 num_irq);
+    }
+
+    register_savevm(NULL, "arm_gic", -1, 3, gic_save, gic_load, s);
+    return 0;
+}
+
+static void arm_gic_common_reset(DeviceState *dev)
+{
+    gic_state *s = FROM_SYSBUS(gic_state, sysbus_from_qdev(dev));
+    int i;
+    memset(s->irq_state, 0, GIC_MAXIRQ * sizeof(gic_irq_state));
+    for (i = 0 ; i < s->num_cpu; i++) {
+        s->priority_mask[i] = 0xf0;
+        s->current_pending[i] = 1023;
+        s->running_irq[i] = 1023;
+        s->running_priority[i] = 0x100;
+        s->cpu_enabled[i] = 0;
+    }
+    for (i = 0; i < 16; i++) {
+        GIC_SET_ENABLED(i, ALL_CPU_MASK);
+        GIC_SET_TRIGGER(i);
+    }
+    if (s->num_cpu == 1) {
+        /* For uniprocessor GICs all interrupts always target the sole CPU */
+        for (i = 0; i < GIC_MAXIRQ; i++) {
+            s->irq_target[i] = 1;
+        }
+    }
+    s->enabled = 0;
+}
+
+static Property arm_gic_common_properties[] = {
+    DEFINE_PROP_UINT32("num-cpu", gic_state, num_cpu, 1),
+    DEFINE_PROP_UINT32("num-irq", gic_state, num_irq, 32),
+    /* Revision can be 1 or 2 for GIC architecture specification
+     * versions 1 or 2, or 0 to indicate the legacy 11MPCore GIC.
+     * (Internally, 0xffffffff also indicates "not a GIC but an NVIC".)
+     */
+    DEFINE_PROP_UINT32("revision", gic_state, revision, 1),
+    DEFINE_PROP_END_OF_LIST(),
+};
+
+static void arm_gic_common_class_init(ObjectClass *klass, void *data)
+{
+    SysBusDeviceClass *sc = SYS_BUS_DEVICE_CLASS(klass);
+    DeviceClass *dc = DEVICE_CLASS(klass);
+    dc->reset = arm_gic_common_reset;
+    dc->props = arm_gic_common_properties;
+    dc->no_user = 1;
+    sc->init = arm_gic_common_init;
+}
+
+static TypeInfo arm_gic_common_type = {
+    .name = TYPE_ARM_GIC_COMMON,
+    .parent = TYPE_SYS_BUS_DEVICE,
+    .instance_size = sizeof(gic_state),
+    .class_size = sizeof(ARMGICCommonClass),
+    .class_init = arm_gic_common_class_init,
+    .abstract = true,
+};
+
+static void register_types(void)
+{
+    type_register_static(&arm_gic_common_type);
+}
+
+type_init(register_types)
diff --git a/hw/arm_gic_internal.h b/hw/arm_gic_internal.h
new file mode 100644
index 0000000..db4fad5
--- /dev/null
+++ b/hw/arm_gic_internal.h
@@ -0,0 +1,136 @@
+/*
+ * ARM GIC support - internal interfaces
+ *
+ * Copyright (c) 2012 Linaro Limited
+ * Written by Peter Maydell
+ *
+ * This program is free software; you can redistribute it and/or modify
+ * it under the terms of the GNU General Public License as published by
+ * the Free Software Foundation, either version 2 of the License, or
+ * (at your option) any later version.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License along
+ * with this program; if not, see <http://www.gnu.org/licenses/>.
+ */
+
+#ifndef QEMU_ARM_GIC_INTERNAL_H
+#define QEMU_ARM_GIC_INTERNAL_H
+
+#include "sysbus.h"
+
+/* Maximum number of possible interrupts, determined by the GIC architecture */
+#define GIC_MAXIRQ 1020
+/* First 32 are private to each CPU (SGIs and PPIs). */
+#define GIC_INTERNAL 32
+/* Maximum number of possible CPU interfaces, determined by GIC architecture */
+#define NCPU 8
+
+#define ALL_CPU_MASK ((unsigned)(((1 << NCPU) - 1)))
+
+/* The NVIC has 16 internal vectors.  However these are not exposed
+   through the normal GIC interface.  */
+#define GIC_BASE_IRQ ((s->revision == REV_NVIC) ? 32 : 0)
+
+#define GIC_SET_ENABLED(irq, cm) s->irq_state[irq].enabled |= (cm)
+#define GIC_CLEAR_ENABLED(irq, cm) s->irq_state[irq].enabled &= ~(cm)
+#define GIC_TEST_ENABLED(irq, cm) ((s->irq_state[irq].enabled & (cm)) != 0)
+#define GIC_SET_PENDING(irq, cm) s->irq_state[irq].pending |= (cm)
+#define GIC_CLEAR_PENDING(irq, cm) s->irq_state[irq].pending &= ~(cm)
+#define GIC_TEST_PENDING(irq, cm) ((s->irq_state[irq].pending & (cm)) != 0)
+#define GIC_SET_ACTIVE(irq, cm) s->irq_state[irq].active |= (cm)
+#define GIC_CLEAR_ACTIVE(irq, cm) s->irq_state[irq].active &= ~(cm)
+#define GIC_TEST_ACTIVE(irq, cm) ((s->irq_state[irq].active & (cm)) != 0)
+#define GIC_SET_MODEL(irq) s->irq_state[irq].model = 1
+#define GIC_CLEAR_MODEL(irq) s->irq_state[irq].model = 0
+#define GIC_TEST_MODEL(irq) s->irq_state[irq].model
+#define GIC_SET_LEVEL(irq, cm) s->irq_state[irq].level = (cm)
+#define GIC_CLEAR_LEVEL(irq, cm) s->irq_state[irq].level &= ~(cm)
+#define GIC_TEST_LEVEL(irq, cm) ((s->irq_state[irq].level & (cm)) != 0)
+#define GIC_SET_TRIGGER(irq) s->irq_state[irq].trigger = 1
+#define GIC_CLEAR_TRIGGER(irq) s->irq_state[irq].trigger = 0
+#define GIC_TEST_TRIGGER(irq) s->irq_state[irq].trigger
+#define GIC_GET_PRIORITY(irq, cpu) (((irq) < GIC_INTERNAL) ?            \
+                                    s->priority1[irq][cpu] :            \
+                                    s->priority2[(irq) - GIC_INTERNAL])
+#define GIC_TARGET(irq) s->irq_target[irq]
+
+typedef struct gic_irq_state {
+    /* The enable bits are only banked for per-cpu interrupts.  */
+    unsigned enabled:NCPU;
+    unsigned pending:NCPU;
+    unsigned active:NCPU;
+    unsigned level:NCPU;
+    unsigned model:1; /* 0 = N:N, 1 = 1:N */
+    unsigned trigger:1; /* nonzero = edge triggered.  */
+} gic_irq_state;
+
+typedef struct gic_state {
+    SysBusDevice busdev;
+    qemu_irq parent_irq[NCPU];
+    int enabled;
+    int cpu_enabled[NCPU];
+
+    gic_irq_state irq_state[GIC_MAXIRQ];
+    int irq_target[GIC_MAXIRQ];
+    int priority1[GIC_INTERNAL][NCPU];
+    int priority2[GIC_MAXIRQ - GIC_INTERNAL];
+    int last_active[GIC_MAXIRQ][NCPU];
+
+    int priority_mask[NCPU];
+    int running_irq[NCPU];
+    int running_priority[NCPU];
+    int current_pending[NCPU];
+
+    uint32_t num_cpu;
+
+    MemoryRegion iomem; /* Distributor */
+    /* This is just so we can have an opaque pointer which identifies
+     * both this GIC and which CPU interface we should be accessing.
+     */
+    struct gic_state *backref[NCPU];
+    MemoryRegion cpuiomem[NCPU+1]; /* CPU interfaces */
+    uint32_t num_irq;
+    uint32_t revision;
+} gic_state;
+
+/* The special cases for the revision property: */
+#define REV_11MPCORE 0
+#define REV_NVIC 0xffffffff
+
+void gic_set_pending_private(gic_state *s, int cpu, int irq);
+uint32_t gic_acknowledge_irq(gic_state *s, int cpu);
+void gic_complete_irq(gic_state *s, int cpu, int irq);
+void gic_update(gic_state *s);
+void gic_init_irqs_and_distributor(gic_state *s, int num_irq);
+
+#define TYPE_ARM_GIC_COMMON "arm_gic_common"
+#define ARM_GIC_COMMON(obj) \
+     OBJECT_CHECK(gic_state, (obj), TYPE_ARM_GIC_COMMON)
+#define ARM_GIC_COMMON_CLASS(klass) \
+     OBJECT_CLASS_CHECK(ARMGICCommonClass, (klass), TYPE_ARM_GIC_COMMON)
+#define ARM_GIC_COMMON_GET_CLASS(obj) \
+     OBJECT_GET_CLASS(ARMGICCommonClass, (obj), TYPE_ARM_GIC_COMMON)
+
+typedef struct ARMGICCommonClass {
+    SysBusDeviceClass parent_class;
+} ARMGICCommonClass;
+
+#define TYPE_ARM_GIC "arm_gic"
+#define ARM_GIC(obj) \
+     OBJECT_CHECK(gic_state, (obj), TYPE_ARM_GIC)
+#define ARM_GIC_CLASS(klass) \
+     OBJECT_CLASS_CHECK(ARMGICClass, (klass), TYPE_ARM_GIC)
+#define ARM_GIC_GET_CLASS(obj) \
+     OBJECT_GET_CLASS(ARMGICClass, (obj), TYPE_ARM_GIC)
+
+typedef struct ARMGICClass {
+    ARMGICCommonClass parent_class;
+    int (*parent_init)(SysBusDevice *dev);
+} ARMGICClass;
+
+#endif /* !QEMU_ARM_GIC_INTERNAL_H */
diff --git a/hw/armv7m_nvic.c b/hw/armv7m_nvic.c
index 031a7fd..4867c1d 100644
--- a/hw/armv7m_nvic.c
+++ b/hw/armv7m_nvic.c
@@ -14,13 +14,7 @@
 #include "qemu-timer.h"
 #include "arm-misc.h"
 #include "exec-memory.h"
-
-#define NVIC 1
-
-static uint32_t nvic_readl(void *opaque, uint32_t offset);
-static void nvic_writel(void *opaque, uint32_t offset, uint32_t value);
-
-#include "arm_gic.c"
+#include "arm_gic_internal.h"
 
 typedef struct {
     gic_state gic;
@@ -36,6 +30,28 @@ typedef struct {
     uint32_t num_irq;
 } nvic_state;
 
+#define TYPE_NVIC "armv7m_nvic"
+/**
+ * NVICClass:
+ * @parent_reset: the parent class' reset handler.
+ *
+ * A model of the v7M NVIC and System Controller
+ */
+typedef struct NVICClass {
+    /*< private >*/
+    ARMGICClass parent_class;
+    /*< public >*/
+    int (*parent_init)(SysBusDevice *dev);
+    void (*parent_reset)(DeviceState *dev);
+} NVICClass;
+
+#define NVIC_CLASS(klass) \
+    OBJECT_CLASS_CHECK(NVICClass, (klass), TYPE_NVIC)
+#define NVIC_GET_CLASS(obj) \
+    OBJECT_GET_CLASS(NVICClass, (obj), TYPE_NVIC)
+#define NVIC(obj) \
+    OBJECT_CHECK(nvic_state, (obj), TYPE_NVIC)
+
 static const uint8_t nvic_id[] = {
     0x00, 0xb0, 0x1b, 0x00, 0x0d, 0xe0, 0x05, 0xb1
 };
@@ -429,8 +445,9 @@ static const VMStateDescription vmstate_nvic = {
 
 static void armv7m_nvic_reset(DeviceState *dev)
 {
-    nvic_state *s = FROM_SYSBUSGIC(nvic_state, sysbus_from_qdev(dev));
-    gic_reset(&s->gic.busdev.qdev);
+    nvic_state *s = NVIC(dev);
+    NVICClass *nc = NVIC_GET_CLASS(s);
+    nc->parent_reset(dev);
     /* Common GIC reset resets to disabled; the NVIC doesn't have
      * per-CPU interfaces so mark our non-existent CPU interface
      * as enabled by default.
@@ -443,12 +460,15 @@ static void armv7m_nvic_reset(DeviceState *dev)
 
 static int armv7m_nvic_init(SysBusDevice *dev)
 {
-    nvic_state *s= FROM_SYSBUSGIC(nvic_state, dev);
+    nvic_state *s = NVIC(dev);
+    NVICClass *nc = NVIC_GET_CLASS(s);
 
     /* The NVIC always has only one CPU */
     s->gic.num_cpu = 1;
     /* Tell the common code we're an NVIC */
     s->gic.revision = 0xffffffff;
+    s->gic.num_irq = s->num_irq;
+    nc->parent_init(dev);
     gic_init_irqs_and_distributor(&s->gic, s->num_irq);
     /* The NVIC and system controller register area looks like this:
      *  0..0xff : system control registers, including systick
@@ -489,9 +509,12 @@ static Property armv7m_nvic_properties[] = {
 
 static void armv7m_nvic_class_init(ObjectClass *klass, void *data)
 {
+    NVICClass *nc = NVIC_CLASS(klass);
     DeviceClass *dc = DEVICE_CLASS(klass);
     SysBusDeviceClass *sdc = SYS_BUS_DEVICE_CLASS(klass);
 
+    nc->parent_reset = dc->reset;
+    nc->parent_init = sdc->init;
     sdc->init = armv7m_nvic_init;
     dc->vmsd  = &vmstate_nvic;
     dc->reset = armv7m_nvic_reset;
@@ -499,10 +522,11 @@ static void armv7m_nvic_class_init(ObjectClass *klass, void *data)
 }
 
 static TypeInfo armv7m_nvic_info = {
-    .name          = "armv7m_nvic",
-    .parent        = TYPE_SYS_BUS_DEVICE,
+    .name          = TYPE_NVIC,
+    .parent        = TYPE_ARM_GIC_COMMON,
     .instance_size = sizeof(nvic_state),
     .class_init    = armv7m_nvic_class_init,
+    .class_size    = sizeof(NVICClass),
 };
 
 static void armv7m_nvic_register_types(void)
commit 2b518c56a6cb7e58477942896bf626f14a112a90
Author: Peter Maydell <peter.maydell at linaro.org>
Date:   Wed May 2 16:49:41 2012 +0000

    hw/arm_gic: Move CPU interface memory region setup into arm_gic_init
    
    Remove more NVIC ifdefs by moving the code to setup the CPU interface
    memory regions into the GIC specific arm_gic_init() function rather
    than the gic_init() function. Rename the latter to more closely
    reflect what it's now actually doing.
    
    Signed-off-by: Peter Maydell <peter.maydell at linaro.org>

diff --git a/hw/arm_gic.c b/hw/arm_gic.c
index c288bc5..ad5ab3c 100644
--- a/hw/arm_gic.c
+++ b/hw/arm_gic.c
@@ -812,7 +812,7 @@ static int gic_load(QEMUFile *f, void *opaque, int version_id)
     return 0;
 }
 
-static void gic_init(gic_state *s, int num_irq)
+static void gic_init_irqs_and_distributor(gic_state *s, int num_irq)
 {
     int i;
 
@@ -850,7 +850,19 @@ static void gic_init(gic_state *s, int num_irq)
         sysbus_init_irq(&s->busdev, &s->parent_irq[i]);
     }
     memory_region_init_io(&s->iomem, &gic_dist_ops, s, "gic_dist", 0x1000);
+
+    register_savevm(NULL, "arm_gic", -1, 3, gic_save, gic_load, s);
+}
+
 #ifndef NVIC
+
+static int arm_gic_init(SysBusDevice *dev)
+{
+    /* Device instance init function for the GIC sysbus device */
+    int i;
+    gic_state *s = FROM_SYSBUS(gic_state, dev);
+    gic_init_irqs_and_distributor(s, s->num_irq);
+
     /* Memory regions for the CPU interfaces (NVIC doesn't have these):
      * a region for "CPU interface for this core", then a region for
      * "CPU interface for core 0", "for core 1", ...
@@ -866,19 +878,7 @@ static void gic_init(gic_state *s, int num_irq)
         memory_region_init_io(&s->cpuiomem[i+1], &gic_cpu_ops, &s->backref[i],
                               "gic_cpu", 0x100);
     }
-#endif
-
-    register_savevm(NULL, "arm_gic", -1, 3, gic_save, gic_load, s);
-}
-
-#ifndef NVIC
 
-static int arm_gic_init(SysBusDevice *dev)
-{
-    /* Device instance init function for the GIC sysbus device */
-    int i;
-    gic_state *s = FROM_SYSBUS(gic_state, dev);
-    gic_init(s, s->num_irq);
     /* Distributor */
     sysbus_init_mmio(dev, &s->iomem);
     /* cpu interfaces (one for "current cpu" plus one per cpu) */
diff --git a/hw/armv7m_nvic.c b/hw/armv7m_nvic.c
index 4c130f1..031a7fd 100644
--- a/hw/armv7m_nvic.c
+++ b/hw/armv7m_nvic.c
@@ -449,7 +449,7 @@ static int armv7m_nvic_init(SysBusDevice *dev)
     s->gic.num_cpu = 1;
     /* Tell the common code we're an NVIC */
     s->gic.revision = 0xffffffff;
-    gic_init(&s->gic, s->num_irq);
+    gic_init_irqs_and_distributor(&s->gic, s->num_irq);
     /* The NVIC and system controller register area looks like this:
      *  0..0xff : system control registers, including systick
      *  0x100..0xcff : GIC-like registers
commit 84e4fccb7f63ee2b9ac82c299d29b2a723479e3d
Author: Peter Maydell <peter.maydell at linaro.org>
Date:   Wed May 2 16:49:41 2012 +0000

    hw/arm_gic.c: Make NVIC interrupt numbering a runtime setting
    
    Make the minor tweaks to interrupt numbering used by the NVIC
    a runtime setting rather than a compile time one, so we can
    drop more NVIC ifdefs.
    
    Signed-off-by: Peter Maydell <peter.maydell at linaro.org>

diff --git a/hw/arm_gic.c b/hw/arm_gic.c
index a6e2431..c288bc5 100644
--- a/hw/arm_gic.c
+++ b/hw/arm_gic.c
@@ -36,13 +36,9 @@ do { printf("arm_gic: " fmt , ## __VA_ARGS__); } while (0)
 #define DPRINTF(fmt, ...) do {} while(0)
 #endif
 
-#ifdef NVIC
 /* The NVIC has 16 internal vectors.  However these are not exposed
    through the normal GIC interface.  */
-#define GIC_BASE_IRQ    32
-#else
-#define GIC_BASE_IRQ    0
-#endif
+#define GIC_BASE_IRQ ((s->revision == REV_NVIC) ? 32 : 0)
 
 static const uint8_t gic_id[] = {
     0x90, 0x13, 0x04, 0x00, 0x0d, 0xf0, 0x05, 0xb1
@@ -839,7 +835,6 @@ static void gic_init(gic_state *s, int num_irq)
     }
 
     i = s->num_irq - GIC_INTERNAL;
-#ifndef NVIC
     /* For the GIC, also expose incoming GPIO lines for PPIs for each CPU.
      * GPIO array layout is thus:
      *  [0..N-1] SPIs
@@ -847,8 +842,9 @@ static void gic_init(gic_state *s, int num_irq)
      *  [N+32..N+63] PPIs for CPU 1
      *   ...
      */
-    i += (GIC_INTERNAL * s->num_cpu);
-#endif
+    if (s->revision != REV_NVIC) {
+        i += (GIC_INTERNAL * s->num_cpu);
+    }
     qdev_init_gpio_in(&s->busdev.qdev, gic_set_irq, i);
     for (i = 0; i < NUM_CPU(s); i++) {
         sysbus_init_irq(&s->busdev, &s->parent_irq[i]);
commit 6b9680bb5826dcf0ead42bafb62946f472466d63
Author: Peter Maydell <peter.maydell at linaro.org>
Date:   Wed May 2 16:49:40 2012 +0000

    hw/arm_gic: Make CPU target registers RAZ/WI on uniprocessor
    
    The GIC spec says that the CPU target registers should RAZ/WI
    for uniprocessor implementations. Implement this, which also
    conveniently lets us drop an NVIC ifdef.
    
    Annoyingly, the 11MPCore's GIC is the odd one out, since
    it always has these registers, even in uniprocessor configs.
    
    Signed-off-by: Peter Maydell <peter.maydell at linaro.org>

diff --git a/hw/arm_gic.c b/hw/arm_gic.c
index ad72ac6..a6e2431 100644
--- a/hw/arm_gic.c
+++ b/hw/arm_gic.c
@@ -86,11 +86,7 @@ typedef struct gic_irq_state
 #define GIC_GET_PRIORITY(irq, cpu) (((irq) < GIC_INTERNAL) ?            \
                                     s->priority1[irq][cpu] :            \
                                     s->priority2[(irq) - GIC_INTERNAL])
-#ifdef NVIC
-#define GIC_TARGET(irq) 1
-#else
 #define GIC_TARGET(irq) s->irq_target[irq]
-#endif
 
 typedef struct gic_state
 {
@@ -377,18 +373,22 @@ static uint32_t gic_dist_readb(void *opaque, target_phys_addr_t offset)
         if (irq >= s->num_irq)
             goto bad_reg;
         res = GIC_GET_PRIORITY(irq, cpu);
-#ifndef NVIC
     } else if (offset < 0xc00) {
         /* Interrupt CPU Target.  */
-        irq = (offset - 0x800) + GIC_BASE_IRQ;
-        if (irq >= s->num_irq)
-            goto bad_reg;
-        if (irq >= 29 && irq <= 31) {
-            res = cm;
+        if (s->num_cpu == 1 && s->revision != REV_11MPCORE) {
+            /* For uniprocessor GICs these RAZ/WI */
+            res = 0;
         } else {
-            res = GIC_TARGET(irq);
+            irq = (offset - 0x800) + GIC_BASE_IRQ;
+            if (irq >= s->num_irq) {
+                goto bad_reg;
+            }
+            if (irq >= 29 && irq <= 31) {
+                res = cm;
+            } else {
+                res = GIC_TARGET(irq);
+            }
         }
-#endif
     } else if (offset < 0xf00) {
         /* Interrupt Configuration.  */
         irq = (offset - 0xc00) * 2 + GIC_BASE_IRQ;
@@ -533,18 +533,22 @@ static void gic_dist_writeb(void *opaque, target_phys_addr_t offset,
         } else {
             s->priority2[irq - GIC_INTERNAL] = value;
         }
-#ifndef NVIC
     } else if (offset < 0xc00) {
-        /* Interrupt CPU Target.  */
-        irq = (offset - 0x800) + GIC_BASE_IRQ;
-        if (irq >= s->num_irq)
-            goto bad_reg;
-        if (irq < 29)
-            value = 0;
-        else if (irq < GIC_INTERNAL)
-            value = ALL_CPU_MASK;
-        s->irq_target[irq] = value & ALL_CPU_MASK;
-#endif
+        /* Interrupt CPU Target. RAZ/WI on uniprocessor GICs, with the
+         * annoying exception of the 11MPCore's GIC.
+         */
+        if (s->num_cpu != 1 || s->revision == REV_11MPCORE) {
+            irq = (offset - 0x800) + GIC_BASE_IRQ;
+            if (irq >= s->num_irq) {
+                goto bad_reg;
+            }
+            if (irq < 29) {
+                value = 0;
+            } else if (irq < GIC_INTERNAL) {
+                value = ALL_CPU_MASK;
+            }
+            s->irq_target[irq] = value & ALL_CPU_MASK;
+        }
     } else if (offset < 0xf00) {
         /* Interrupt Configuration.  */
         irq = (offset - 0xc00) * 4 + GIC_BASE_IRQ;
@@ -733,6 +737,12 @@ static void gic_reset(DeviceState *dev)
         GIC_SET_ENABLED(i, ALL_CPU_MASK);
         GIC_SET_TRIGGER(i);
     }
+    if (s->num_cpu == 1) {
+        /* For uniprocessor GICs all interrupts always target the sole CPU */
+        for (i = 0; i < GIC_MAXIRQ; i++) {
+            s->irq_target[i] = 1;
+        }
+    }
     s->enabled = 0;
 }
 
commit 306a571a2d75e32cd2eae5486c2714b7b7792a63
Author: Peter Maydell <peter.maydell at linaro.org>
Date:   Wed May 2 16:49:40 2012 +0000

    hw/arm_gic: Add qdev property for GIC revision
    
    GIC behaviour can be different between revision 1 and
    2 of the architectural GIC specification; we also have
    to handle the legacy 11MPCore GIC, which is different
    again in some places. Introduce a qdev property so we
    can behave appropriately.
    
    Signed-off-by: Peter Maydell <peter.maydell at linaro.org>

diff --git a/hw/a15mpcore.c b/hw/a15mpcore.c
index 5a7b365..fc0a02a 100644
--- a/hw/a15mpcore.c
+++ b/hw/a15mpcore.c
@@ -44,6 +44,7 @@ static int a15mp_priv_init(SysBusDevice *dev)
     s->gic = qdev_create(NULL, "arm_gic");
     qdev_prop_set_uint32(s->gic, "num-cpu", s->num_cpu);
     qdev_prop_set_uint32(s->gic, "num-irq", s->num_irq);
+    qdev_prop_set_uint32(s->gic, "revision", 2);
     qdev_init_nofail(s->gic);
     busdev = sysbus_from_qdev(s->gic);
 
diff --git a/hw/arm11mpcore.c b/hw/arm11mpcore.c
index c528d7a..1bff3d3 100644
--- a/hw/arm11mpcore.c
+++ b/hw/arm11mpcore.c
@@ -123,6 +123,8 @@ static int mpcore_priv_init(SysBusDevice *dev)
     s->gic = qdev_create(NULL, "arm_gic");
     qdev_prop_set_uint32(s->gic, "num-cpu", s->num_cpu);
     qdev_prop_set_uint32(s->gic, "num-irq", s->num_irq);
+    /* Request the legacy 11MPCore GIC behaviour: */
+    qdev_prop_set_uint32(s->gic, "revision", 0);
     qdev_init_nofail(s->gic);
 
     /* Pass through outbound IRQ lines from the GIC */
diff --git a/hw/arm_gic.c b/hw/arm_gic.c
index 2ec10ce..ad72ac6 100644
--- a/hw/arm_gic.c
+++ b/hw/arm_gic.c
@@ -119,8 +119,13 @@ typedef struct gic_state
     struct gic_state *backref[NCPU];
     MemoryRegion cpuiomem[NCPU+1]; /* CPU interfaces */
     uint32_t num_irq;
+    uint32_t revision;
 } gic_state;
 
+/* The special cases for the revision property: */
+#define REV_11MPCORE 0
+#define REV_NVIC 0xffffffff
+
 static inline int gic_get_current_cpu(gic_state *s)
 {
     if (s->num_cpu > 1) {
@@ -880,6 +885,11 @@ static int arm_gic_init(SysBusDevice *dev)
 static Property arm_gic_properties[] = {
     DEFINE_PROP_UINT32("num-cpu", gic_state, num_cpu, 1),
     DEFINE_PROP_UINT32("num-irq", gic_state, num_irq, 32),
+    /* Revision can be 1 or 2 for GIC architecture specification
+     * versions 1 or 2, or 0 to indicate the legacy 11MPCore GIC.
+     * (Internally, 0xffffffff also indicates "not a GIC but an NVIC".)
+     */
+    DEFINE_PROP_UINT32("revision", gic_state, revision, 1),
     DEFINE_PROP_END_OF_LIST(),
 };
 
diff --git a/hw/armv7m_nvic.c b/hw/armv7m_nvic.c
index 747e245..4c130f1 100644
--- a/hw/armv7m_nvic.c
+++ b/hw/armv7m_nvic.c
@@ -447,6 +447,8 @@ static int armv7m_nvic_init(SysBusDevice *dev)
 
     /* The NVIC always has only one CPU */
     s->gic.num_cpu = 1;
+    /* Tell the common code we're an NVIC */
+    s->gic.revision = 0xffffffff;
     gic_init(&s->gic, s->num_irq);
     /* The NVIC and system controller register area looks like this:
      *  0..0xff : system control registers, including systick
commit 2a29ddee82029580fa85276767f73fedc30c8a0a
Author: Peter Maydell <peter.maydell at linaro.org>
Date:   Wed May 2 16:49:39 2012 +0000

    hw/armv7m_nvic: Use MemoryRegions for NVIC specific registers
    
    Implement the NVIC specific register areas using a set of
    overlaid MemoryRegions in a container, rather than by having
    the arm_gic read/write functions use special purpose callbacks.
    
    Signed-off-by: Peter Maydell <peter.maydell at linaro.org>

diff --git a/hw/arm_gic.c b/hw/arm_gic.c
index 3293ae4..2ec10ce 100644
--- a/hw/arm_gic.c
+++ b/hw/arm_gic.c
@@ -37,17 +37,17 @@ do { printf("arm_gic: " fmt , ## __VA_ARGS__); } while (0)
 #endif
 
 #ifdef NVIC
-static const uint8_t gic_id[] =
-{ 0x00, 0xb0, 0x1b, 0x00, 0x0d, 0xe0, 0x05, 0xb1 };
 /* The NVIC has 16 internal vectors.  However these are not exposed
    through the normal GIC interface.  */
 #define GIC_BASE_IRQ    32
 #else
-static const uint8_t gic_id[] =
-{ 0x90, 0x13, 0x04, 0x00, 0x0d, 0xf0, 0x05, 0xb1 };
 #define GIC_BASE_IRQ    0
 #endif
 
+static const uint8_t gic_id[] = {
+    0x90, 0x13, 0x04, 0x00, 0x0d, 0xf0, 0x05, 0xb1
+};
+
 #define FROM_SYSBUSGIC(type, dev) \
     DO_UPCAST(type, gic, FROM_SYSBUS(gic_state, dev))
 
@@ -312,7 +312,6 @@ static uint32_t gic_dist_readb(void *opaque, target_phys_addr_t offset)
     cpu = gic_get_current_cpu(s);
     cm = 1 << cpu;
     if (offset < 0x100) {
-#ifndef NVIC
         if (offset == 0)
             return s->enabled;
         if (offset == 4)
@@ -323,7 +322,6 @@ static uint32_t gic_dist_readb(void *opaque, target_phys_addr_t offset)
             /* Interrupt Security , RAZ/WI */
             return 0;
         }
-#endif
         goto bad_reg;
     } else if (offset < 0x200) {
         /* Interrupt Set/Clear Enable.  */
@@ -385,6 +383,7 @@ static uint32_t gic_dist_readb(void *opaque, target_phys_addr_t offset)
         } else {
             res = GIC_TARGET(irq);
         }
+#endif
     } else if (offset < 0xf00) {
         /* Interrupt Configuration.  */
         irq = (offset - 0xc00) * 2 + GIC_BASE_IRQ;
@@ -397,7 +396,6 @@ static uint32_t gic_dist_readb(void *opaque, target_phys_addr_t offset)
             if (GIC_TEST_TRIGGER(irq + i))
                 res |= (2 << (i * 2));
         }
-#endif
     } else if (offset < 0xfe0) {
         goto bad_reg;
     } else /* offset >= 0xfe0 */ {
@@ -424,13 +422,6 @@ static uint32_t gic_dist_readw(void *opaque, target_phys_addr_t offset)
 static uint32_t gic_dist_readl(void *opaque, target_phys_addr_t offset)
 {
     uint32_t val;
-#ifdef NVIC
-    gic_state *s = (gic_state *)opaque;
-    uint32_t addr;
-    addr = offset;
-    if (addr < 0x100 || addr > 0xd00)
-        return nvic_readl(s, addr);
-#endif
     val = gic_dist_readw(opaque, offset);
     val |= gic_dist_readw(opaque, offset + 2) << 16;
     return val;
@@ -446,9 +437,6 @@ static void gic_dist_writeb(void *opaque, target_phys_addr_t offset,
 
     cpu = gic_get_current_cpu(s);
     if (offset < 0x100) {
-#ifdef NVIC
-        goto bad_reg;
-#else
         if (offset == 0) {
             s->enabled = (value & 1);
             DPRINTF("Distribution %sabled\n", s->enabled ? "En" : "Dis");
@@ -459,7 +447,6 @@ static void gic_dist_writeb(void *opaque, target_phys_addr_t offset,
         } else {
             goto bad_reg;
         }
-#endif
     } else if (offset < 0x180) {
         /* Interrupt Set Enable.  */
         irq = (offset - 0x100) * 8 + GIC_BASE_IRQ;
@@ -552,6 +539,7 @@ static void gic_dist_writeb(void *opaque, target_phys_addr_t offset,
         else if (irq < GIC_INTERNAL)
             value = ALL_CPU_MASK;
         s->irq_target[irq] = value & ALL_CPU_MASK;
+#endif
     } else if (offset < 0xf00) {
         /* Interrupt Configuration.  */
         irq = (offset - 0xc00) * 4 + GIC_BASE_IRQ;
@@ -571,7 +559,6 @@ static void gic_dist_writeb(void *opaque, target_phys_addr_t offset,
                 GIC_CLEAR_TRIGGER(irq + i);
             }
         }
-#endif
     } else {
         /* 0xf00 is only handled for 32-bit writes.  */
         goto bad_reg;
@@ -593,14 +580,6 @@ static void gic_dist_writel(void *opaque, target_phys_addr_t offset,
                             uint32_t value)
 {
     gic_state *s = (gic_state *)opaque;
-#ifdef NVIC
-    uint32_t addr;
-    addr = offset;
-    if (addr < 0x100 || (addr > 0xd00 && addr != 0xf00)) {
-        nvic_writel(s, addr, value);
-        return;
-    }
-#endif
     if (offset == 0xf00) {
         int cpu;
         int irq;
diff --git a/hw/armv7m_nvic.c b/hw/armv7m_nvic.c
index 653c011..747e245 100644
--- a/hw/armv7m_nvic.c
+++ b/hw/armv7m_nvic.c
@@ -30,9 +30,16 @@ typedef struct {
         int64_t tick;
         QEMUTimer *timer;
     } systick;
+    MemoryRegion sysregmem;
+    MemoryRegion gic_iomem_alias;
+    MemoryRegion container;
     uint32_t num_irq;
 } nvic_state;
 
+static const uint8_t nvic_id[] = {
+    0x00, 0xb0, 0x1b, 0x00, 0x0d, 0xe0, 0x05, 0xb1
+};
+
 /* qemu timers run at 1GHz.   We want something closer to 1MHz.  */
 #define SYSTICK_SCALE 1000ULL
 
@@ -358,12 +365,54 @@ static void nvic_writel(void *opaque, uint32_t offset, uint32_t value)
     case 0xd38: /* Bus Fault Address.  */
     case 0xd3c: /* Aux Fault Status.  */
         goto bad_reg;
+    case 0xf00: /* Software Triggered Interrupt Register */
+        if ((value & 0x1ff) < s->num_irq) {
+            gic_set_pending_private(&s->gic, 0, value & 0x1ff);
+        }
+        break;
     default:
     bad_reg:
         hw_error("NVIC: Bad write offset 0x%x\n", offset);
     }
 }
 
+static uint64_t nvic_sysreg_read(void *opaque, target_phys_addr_t addr,
+                                 unsigned size)
+{
+    /* At the moment we only support the ID registers for byte/word access.
+     * This is not strictly correct as a few of the other registers also
+     * allow byte access.
+     */
+    uint32_t offset = addr;
+    if (offset >= 0xfe0) {
+        if (offset & 3) {
+            return 0;
+        }
+        return nvic_id[(offset - 0xfe0) >> 2];
+    }
+    if (size == 4) {
+        return nvic_readl(opaque, offset);
+    }
+    hw_error("NVIC: Bad read of size %d at offset 0x%x\n", size, offset);
+}
+
+static void nvic_sysreg_write(void *opaque, target_phys_addr_t addr,
+                              uint64_t value, unsigned size)
+{
+    uint32_t offset = addr;
+    if (size == 4) {
+        nvic_writel(opaque, offset, value);
+        return;
+    }
+    hw_error("NVIC: Bad write of size %d at offset 0x%x\n", size, offset);
+}
+
+static const MemoryRegionOps nvic_sysreg_ops = {
+    .read = nvic_sysreg_read,
+    .write = nvic_sysreg_write,
+    .endianness = DEVICE_NATIVE_ENDIAN,
+};
+
 static const VMStateDescription vmstate_nvic = {
     .name = "armv7m_nvic",
     .version_id = 1,
@@ -399,7 +448,30 @@ static int armv7m_nvic_init(SysBusDevice *dev)
     /* The NVIC always has only one CPU */
     s->gic.num_cpu = 1;
     gic_init(&s->gic, s->num_irq);
-    memory_region_add_subregion(get_system_memory(), 0xe000e000, &s->gic.iomem);
+    /* The NVIC and system controller register area looks like this:
+     *  0..0xff : system control registers, including systick
+     *  0x100..0xcff : GIC-like registers
+     *  0xd00..0xfff : system control registers
+     * We use overlaying to put the GIC like registers
+     * over the top of the system control register region.
+     */
+    memory_region_init(&s->container, "nvic", 0x1000);
+    /* The system register region goes at the bottom of the priority
+     * stack as it covers the whole page.
+     */
+    memory_region_init_io(&s->sysregmem, &nvic_sysreg_ops, s,
+                          "nvic_sysregs", 0x1000);
+    memory_region_add_subregion(&s->container, 0, &s->sysregmem);
+    /* Alias the GIC region so we can get only the section of it
+     * we need, and layer it on top of the system register region.
+     */
+    memory_region_init_alias(&s->gic_iomem_alias, "nvic-gic", &s->gic.iomem,
+                             0x100, 0xc00);
+    memory_region_add_subregion_overlap(&s->container, 0x100, &s->gic.iomem, 1);
+    /* Map the whole thing into system memory at the location required
+     * by the v7M architecture.
+     */
+    memory_region_add_subregion(get_system_memory(), 0xe000e000, &s->container);
     s->systick.timer = qemu_new_timer_ns(vm_clock, systick_timer_tick, s);
     return 0;
 }
commit b3387ede2f2b8a6ba3d5e922492f85a34db6f191
Author: Peter Maydell <peter.maydell at linaro.org>
Date:   Wed May 2 16:49:39 2012 +0000

    hw/arm_gic: Move NVIC specific reset to armv7m_nvic_reset
    
    Move the NVIC specific bits of reset to the NVIC's own
    reset function, rather than using ifdefs in the common
    arm_gic reset.
    
    Signed-off-by: Peter Maydell <peter.maydell at linaro.org>

diff --git a/hw/arm_gic.c b/hw/arm_gic.c
index 2d8ceb8..3293ae4 100644
--- a/hw/arm_gic.c
+++ b/hw/arm_gic.c
@@ -743,23 +743,13 @@ static void gic_reset(DeviceState *dev)
         s->current_pending[i] = 1023;
         s->running_irq[i] = 1023;
         s->running_priority[i] = 0x100;
-#ifdef NVIC
-        /* The NVIC doesn't have per-cpu interfaces, so enable by default.  */
-        s->cpu_enabled[i] = 1;
-#else
         s->cpu_enabled[i] = 0;
-#endif
     }
     for (i = 0; i < 16; i++) {
         GIC_SET_ENABLED(i, ALL_CPU_MASK);
         GIC_SET_TRIGGER(i);
     }
-#ifdef NVIC
-    /* The NVIC is always enabled.  */
-    s->enabled = 1;
-#else
     s->enabled = 0;
-#endif
 }
 
 static void gic_save(QEMUFile *f, void *opaque)
diff --git a/hw/armv7m_nvic.c b/hw/armv7m_nvic.c
index 99a87a2..653c011 100644
--- a/hw/armv7m_nvic.c
+++ b/hw/armv7m_nvic.c
@@ -382,6 +382,13 @@ static void armv7m_nvic_reset(DeviceState *dev)
 {
     nvic_state *s = FROM_SYSBUSGIC(nvic_state, sysbus_from_qdev(dev));
     gic_reset(&s->gic.busdev.qdev);
+    /* Common GIC reset resets to disabled; the NVIC doesn't have
+     * per-CPU interfaces so mark our non-existent CPU interface
+     * as enabled by default.
+     */
+    s->gic.cpu_enabled[0] = 1;
+    /* The NVIC as a whole is always enabled. */
+    s->gic.enabled = 1;
     systick_reset(s);
 }
 
commit c48c6522f550b9b704f7324164b00b5770ec7345
Author: Peter Maydell <peter.maydell at linaro.org>
Date:   Wed May 2 16:49:39 2012 +0000

    hw/arm_gic: Remove the special casing of NCPU for the NVIC
    
    Drop the special casing of NCPU=1 for the NVIC. This slightly
    increases the amount of memory used by its state structure,
    but removes some ifdeffery and means we can safely move the
    GIC state into a common subclass structure.
    
    Signed-off-by: Peter Maydell <peter.maydell at linaro.org>

diff --git a/hw/arm_gic.c b/hw/arm_gic.c
index 17b2eba..2d8ceb8 100644
--- a/hw/arm_gic.c
+++ b/hw/arm_gic.c
@@ -25,11 +25,7 @@
 /* First 32 are private to each CPU (SGIs and PPIs). */
 #define GIC_INTERNAL 32
 /* Maximum number of possible CPU interfaces, determined by GIC architecture */
-#ifdef NVIC
-#define NCPU 1
-#else
 #define NCPU 8
-#endif
 
 //#define DEBUG_GIC
 
@@ -67,11 +63,7 @@ typedef struct gic_irq_state
 } gic_irq_state;
 
 #define ALL_CPU_MASK ((unsigned)(((1 << NCPU) - 1)))
-#if NCPU > 1
 #define NUM_CPU(s) ((s)->num_cpu)
-#else
-#define NUM_CPU(s) 1
-#endif
 
 #define GIC_SET_ENABLED(irq, cm) s->irq_state[irq].enabled |= (cm)
 #define GIC_CLEAR_ENABLED(irq, cm) s->irq_state[irq].enabled &= ~(cm)
@@ -131,11 +123,9 @@ typedef struct gic_state
 
 static inline int gic_get_current_cpu(gic_state *s)
 {
-#if NCPU > 1
     if (s->num_cpu > 1) {
         return cpu_single_env->cpu_index;
     }
-#endif
     return 0;
 }
 
@@ -842,21 +832,14 @@ static int gic_load(QEMUFile *f, void *opaque, int version_id)
     return 0;
 }
 
-#if NCPU > 1
-static void gic_init(gic_state *s, int num_cpu, int num_irq)
-#else
 static void gic_init(gic_state *s, int num_irq)
-#endif
 {
     int i;
 
-#if NCPU > 1
-    s->num_cpu = num_cpu;
     if (s->num_cpu > NCPU) {
         hw_error("requested %u CPUs exceeds GIC maximum %d\n",
-                 num_cpu, NCPU);
+                 s->num_cpu, NCPU);
     }
-#endif
     s->num_irq = num_irq + GIC_BASE_IRQ;
     if (s->num_irq > GIC_MAXIRQ) {
         hw_error("requested %u interrupt lines exceeds GIC maximum %d\n",
@@ -880,7 +863,7 @@ static void gic_init(gic_state *s, int num_irq)
      *  [N+32..N+63] PPIs for CPU 1
      *   ...
      */
-    i += (GIC_INTERNAL * num_cpu);
+    i += (GIC_INTERNAL * s->num_cpu);
 #endif
     qdev_init_gpio_in(&s->busdev.qdev, gic_set_irq, i);
     for (i = 0; i < NUM_CPU(s); i++) {
@@ -915,7 +898,7 @@ static int arm_gic_init(SysBusDevice *dev)
     /* Device instance init function for the GIC sysbus device */
     int i;
     gic_state *s = FROM_SYSBUS(gic_state, dev);
-    gic_init(s, s->num_cpu, s->num_irq);
+    gic_init(s, s->num_irq);
     /* Distributor */
     sysbus_init_mmio(dev, &s->iomem);
     /* cpu interfaces (one for "current cpu" plus one per cpu) */
diff --git a/hw/armv7m_nvic.c b/hw/armv7m_nvic.c
index 986a6bb..99a87a2 100644
--- a/hw/armv7m_nvic.c
+++ b/hw/armv7m_nvic.c
@@ -389,9 +389,8 @@ static int armv7m_nvic_init(SysBusDevice *dev)
 {
     nvic_state *s= FROM_SYSBUSGIC(nvic_state, dev);
 
-   /* note that for the M profile gic_init() takes the number of external
-    * interrupt lines only.
-    */
+    /* The NVIC always has only one CPU */
+    s->gic.num_cpu = 1;
     gic_init(&s->gic, s->num_irq);
     memory_region_add_subregion(get_system_memory(), 0xe000e000, &s->gic.iomem);
     s->systick.timer = qemu_new_timer_ns(vm_clock, systick_timer_tick, s);
commit acd684280f9e91e8199d0b2126d4b057676dafec
Author: Peter Maydell <peter.maydell at linaro.org>
Date:   Wed May 2 16:49:38 2012 +0000

    hw/arm_gic: Remove NVIC ifdefs from gic_state struct
    
    Remove some NVIC ifdefs from the gic_state struct and its
    state save/load functions. This means there are some fields
    in it which are present for the NVIC but not used, but means
    it always has the same layout and can be pulled out into a
    common subclass.
    
    Note that the addition of irq_target[] to the save/load
    struct for the NVIC requires a vmstate version bump.
    
    Signed-off-by: Peter Maydell <peter.maydell at linaro.org>
    Reviewed-by: Andreas Färber <afaerber at suse.de>

diff --git a/hw/arm_gic.c b/hw/arm_gic.c
index 72298b4..17b2eba 100644
--- a/hw/arm_gic.c
+++ b/hw/arm_gic.c
@@ -108,9 +108,7 @@ typedef struct gic_state
     int cpu_enabled[NCPU];
 
     gic_irq_state irq_state[GIC_MAXIRQ];
-#ifndef NVIC
     int irq_target[GIC_MAXIRQ];
-#endif
     int priority1[GIC_INTERNAL][NCPU];
     int priority2[GIC_MAXIRQ - GIC_INTERNAL];
     int last_active[GIC_MAXIRQ][NCPU];
@@ -120,18 +118,14 @@ typedef struct gic_state
     int running_priority[NCPU];
     int current_pending[NCPU];
 
-#if NCPU > 1
     uint32_t num_cpu;
-#endif
 
     MemoryRegion iomem; /* Distributor */
-#ifndef NVIC
     /* This is just so we can have an opaque pointer which identifies
      * both this GIC and which CPU interface we should be accessing.
      */
     struct gic_state *backref[NCPU];
     MemoryRegion cpuiomem[NCPU+1]; /* CPU interfaces */
-#endif
     uint32_t num_irq;
 } gic_state;
 
@@ -800,9 +794,7 @@ static void gic_save(QEMUFile *f, void *opaque)
         qemu_put_be32(f, s->priority2[i]);
     }
     for (i = 0; i < s->num_irq; i++) {
-#ifndef NVIC
         qemu_put_be32(f, s->irq_target[i]);
-#endif
         qemu_put_byte(f, s->irq_state[i].enabled);
         qemu_put_byte(f, s->irq_state[i].pending);
         qemu_put_byte(f, s->irq_state[i].active);
@@ -818,8 +810,9 @@ static int gic_load(QEMUFile *f, void *opaque, int version_id)
     int i;
     int j;
 
-    if (version_id != 2)
+    if (version_id != 3) {
         return -EINVAL;
+    }
 
     s->enabled = qemu_get_be32(f);
     for (i = 0; i < NUM_CPU(s); i++) {
@@ -837,9 +830,7 @@ static int gic_load(QEMUFile *f, void *opaque, int version_id)
         s->priority2[i] = qemu_get_be32(f);
     }
     for (i = 0; i < s->num_irq; i++) {
-#ifndef NVIC
         s->irq_target[i] = qemu_get_be32(f);
-#endif
         s->irq_state[i].enabled = qemu_get_byte(f);
         s->irq_state[i].pending = qemu_get_byte(f);
         s->irq_state[i].active = qemu_get_byte(f);
@@ -914,7 +905,7 @@ static void gic_init(gic_state *s, int num_irq)
     }
 #endif
 
-    register_savevm(NULL, "arm_gic", -1, 2, gic_save, gic_load, s);
+    register_savevm(NULL, "arm_gic", -1, 3, gic_save, gic_load, s);
 }
 
 #ifndef NVIC
commit 9b574c29c199dbcf5f81fa14d1c692a23463ca7e
Author: Andreas Färber <afaerber at suse.de>
Date:   Mon May 28 04:11:49 2012 +0000

    arm_boot: Fix typos in comment
    
    mimicing -> mimicking
    thei -> the
    
    Signed-off-by: Andreas Färber <afaerber at suse.de>
    Reviewed-by: Stefan Weil <sw at weilnetz.de>
    Signed-off-by: Peter Maydell <peter.maydell at linaro.org>

diff --git a/hw/arm-misc.h b/hw/arm-misc.h
index 1d51570..1f96229 100644
--- a/hw/arm-misc.h
+++ b/hw/arm-misc.h
@@ -45,9 +45,9 @@ struct arm_boot_info {
     /* multicore boards that use the default secondary core boot functions
      * can ignore these two function calls. If the default functions won't
      * work, then write_secondary_boot() should write a suitable blob of
-     * code mimicing the secondary CPU startup process used by the board's
+     * code mimicking the secondary CPU startup process used by the board's
      * boot loader/boot ROM code, and secondary_cpu_reset_hook() should
-     * perform any necessary CPU reset handling and set the PC for thei
+     * perform any necessary CPU reset handling and set the PC for the
      * secondary CPUs to point at this boot blob.
      */
     void (*write_secondary_boot)(ARMCPU *cpu,
commit 61558e7a75e6f6d579e636ca5a5b79c68654f07c
Author: Evgeny Voevodin <e.voevodin at samsung.com>
Date:   Mon May 28 04:11:49 2012 +0000

    ARM: Exynos4210 IRQ: Introduce new IRQ gate functionality.
    
    New IRQ gate consists of n_in input qdev gpio lines and one
    output sysbus IRQ line. The output IRQ level is formed as OR
    between all gpio inputs.
    
    Signed-off-by: Evgeny Voevodin <e.voevodin at samsung.com>
    Signed-off-by: Peter Maydell <peter.maydell at linaro.org>

diff --git a/hw/exynos4210.c b/hw/exynos4210.c
index dd14d01..9c20b3f 100644
--- a/hw/exynos4210.c
+++ b/hw/exynos4210.c
@@ -97,11 +97,11 @@ void exynos4210_write_secondary(ARMCPU *cpu,
 Exynos4210State *exynos4210_init(MemoryRegion *system_mem,
         unsigned long ram_size)
 {
-    qemu_irq cpu_irq[4];
-    int n;
+    qemu_irq cpu_irq[EXYNOS4210_NCPUS];
+    int i, n;
     Exynos4210State *s = g_new(Exynos4210State, 1);
     qemu_irq *irqp;
-    qemu_irq gate_irq[EXYNOS4210_IRQ_GATE_NINPUTS];
+    qemu_irq gate_irq[EXYNOS4210_NCPUS][EXYNOS4210_IRQ_GATE_NINPUTS];
     unsigned long mem_size;
     DeviceState *dev;
     SysBusDevice *busdev;
@@ -128,16 +128,18 @@ Exynos4210State *exynos4210_init(MemoryRegion *system_mem,
     s->irq_table = exynos4210_init_irq(&s->irqs);
 
     /* IRQ Gate */
-    dev = qdev_create(NULL, "exynos4210.irq_gate");
-    qdev_init_nofail(dev);
-    /* Get IRQ Gate input in gate_irq */
-    for (n = 0; n < EXYNOS4210_IRQ_GATE_NINPUTS; n++) {
-        gate_irq[n] = qdev_get_gpio_in(dev, n);
-    }
-    busdev = sysbus_from_qdev(dev);
-    /* Connect IRQ Gate output to cpu_irq */
-    for (n = 0; n < EXYNOS4210_NCPUS; n++) {
-        sysbus_connect_irq(busdev, n, cpu_irq[n]);
+    for (i = 0; i < EXYNOS4210_NCPUS; i++) {
+        dev = qdev_create(NULL, "exynos4210.irq_gate");
+        qdev_prop_set_uint32(dev, "n_in", EXYNOS4210_IRQ_GATE_NINPUTS);
+        qdev_init_nofail(dev);
+        /* Get IRQ Gate input in gate_irq */
+        for (n = 0; n < EXYNOS4210_IRQ_GATE_NINPUTS; n++) {
+            gate_irq[i][n] = qdev_get_gpio_in(dev, n);
+        }
+        busdev = sysbus_from_qdev(dev);
+
+        /* Connect IRQ Gate output to cpu_irq */
+        sysbus_connect_irq(busdev, 0, cpu_irq[i]);
     }
 
     /* Private memory region and Internal GIC */
@@ -147,7 +149,7 @@ Exynos4210State *exynos4210_init(MemoryRegion *system_mem,
     busdev = sysbus_from_qdev(dev);
     sysbus_mmio_map(busdev, 0, EXYNOS4210_SMP_PRIVATE_BASE_ADDR);
     for (n = 0; n < EXYNOS4210_NCPUS; n++) {
-        sysbus_connect_irq(busdev, n, gate_irq[n * 2]);
+        sysbus_connect_irq(busdev, n, gate_irq[n][0]);
     }
     for (n = 0; n < EXYNOS4210_INT_GIC_NIRQ; n++) {
         s->irqs.int_gic_irq[n] = qdev_get_gpio_in(dev, n);
@@ -166,7 +168,7 @@ Exynos4210State *exynos4210_init(MemoryRegion *system_mem,
     /* Map Distributer interface */
     sysbus_mmio_map(busdev, 1, EXYNOS4210_EXT_GIC_DIST_BASE_ADDR);
     for (n = 0; n < EXYNOS4210_NCPUS; n++) {
-        sysbus_connect_irq(busdev, n, gate_irq[n * 2 + 1]);
+        sysbus_connect_irq(busdev, n, gate_irq[n][1]);
     }
     for (n = 0; n < EXYNOS4210_EXT_GIC_NIRQ; n++) {
         s->irqs.ext_gic_irq[n] = qdev_get_gpio_in(dev, n);
diff --git a/hw/exynos4210.h b/hw/exynos4210.h
index b1b4609..9b1ae4c 100644
--- a/hw/exynos4210.h
+++ b/hw/exynos4210.h
@@ -56,7 +56,7 @@
 /*
  * exynos4210 IRQ subsystem stub definitions.
  */
-#define EXYNOS4210_IRQ_GATE_NINPUTS 8
+#define EXYNOS4210_IRQ_GATE_NINPUTS 2 /* Internal and External GIC */
 
 #define EXYNOS4210_MAX_INT_COMBINER_OUT_IRQ  64
 #define EXYNOS4210_MAX_EXT_COMBINER_OUT_IRQ  16
diff --git a/hw/exynos4210_gic.c b/hw/exynos4210_gic.c
index e1b215e..7d03dd9 100644
--- a/hw/exynos4210_gic.c
+++ b/hw/exynos4210_gic.c
@@ -362,61 +362,64 @@ static void exynos4210_gic_register_types(void)
 
 type_init(exynos4210_gic_register_types)
 
-/*
- * IRQGate struct.
- * IRQ Gate represents OR gate between GICs to pass IRQ to PIC.
+/* IRQ OR Gate struct.
+ *
+ * This device models an OR gate. There are n_in input qdev gpio lines and one
+ * output sysbus IRQ line. The output IRQ level is formed as OR between all
+ * gpio inputs.
  */
 typedef struct {
     SysBusDevice busdev;
 
-    qemu_irq pic_irq[EXYNOS4210_NCPUS]; /* output IRQs to PICs */
-    uint32_t gpio_level[EXYNOS4210_IRQ_GATE_NINPUTS]; /* Input levels */
+    uint32_t n_in;      /* inputs amount */
+    uint32_t *level;    /* input levels */
+    qemu_irq out;       /* output IRQ */
 } Exynos4210IRQGateState;
 
+static Property exynos4210_irq_gate_properties[] = {
+    DEFINE_PROP_UINT32("n_in", Exynos4210IRQGateState, n_in, 1),
+    DEFINE_PROP_END_OF_LIST(),
+};
+
 static const VMStateDescription vmstate_exynos4210_irq_gate = {
     .name = "exynos4210.irq_gate",
-    .version_id = 1,
-    .minimum_version_id = 1,
-    .minimum_version_id_old = 1,
+    .version_id = 2,
+    .minimum_version_id = 2,
+    .minimum_version_id_old = 2,
     .fields = (VMStateField[]) {
-        VMSTATE_UINT32_ARRAY(gpio_level, Exynos4210IRQGateState,
-                EXYNOS4210_IRQ_GATE_NINPUTS),
+        VMSTATE_VBUFFER_UINT32(level, Exynos4210IRQGateState, 1, NULL, 0, n_in),
         VMSTATE_END_OF_LIST()
     }
 };
 
-/* Process a change in an external IRQ input.  */
+/* Process a change in IRQ input. */
 static void exynos4210_irq_gate_handler(void *opaque, int irq, int level)
 {
-    Exynos4210IRQGateState *s =
-            (Exynos4210IRQGateState *)opaque;
-    uint32_t odd, even;
-
-    if (irq & 1) {
-        odd = irq;
-        even = irq & ~1;
-    } else {
-        even = irq;
-        odd = irq | 1;
-    }
+    Exynos4210IRQGateState *s = (Exynos4210IRQGateState *)opaque;
+    uint32_t i;
 
-    assert(irq < EXYNOS4210_IRQ_GATE_NINPUTS);
-    s->gpio_level[irq] = level;
+    assert(irq < s->n_in);
 
-    if (s->gpio_level[odd] >= 1 || s->gpio_level[even] >= 1) {
-        qemu_irq_raise(s->pic_irq[even >> 1]);
-    } else {
-        qemu_irq_lower(s->pic_irq[even >> 1]);
+    s->level[irq] = level;
+
+    for (i = 0; i < s->n_in; i++) {
+        if (s->level[i] >= 1) {
+            qemu_irq_raise(s->out);
+            return;
+        }
     }
 
+    qemu_irq_lower(s->out);
+
     return;
 }
 
 static void exynos4210_irq_gate_reset(DeviceState *d)
 {
-    Exynos4210IRQGateState *s = (Exynos4210IRQGateState *)d;
+    Exynos4210IRQGateState *s =
+            DO_UPCAST(Exynos4210IRQGateState, busdev.qdev, d);
 
-    memset(&s->gpio_level, 0, sizeof(s->gpio_level));
+    memset(s->level, 0, s->n_in * sizeof(*s->level));
 }
 
 /*
@@ -424,19 +427,15 @@ static void exynos4210_irq_gate_reset(DeviceState *d)
  */
 static int exynos4210_irq_gate_init(SysBusDevice *dev)
 {
-    unsigned int i;
-    Exynos4210IRQGateState *s =
-            FROM_SYSBUS(Exynos4210IRQGateState, dev);
+    Exynos4210IRQGateState *s = FROM_SYSBUS(Exynos4210IRQGateState, dev);
 
     /* Allocate general purpose input signals and connect a handler to each of
      * them */
-    qdev_init_gpio_in(&s->busdev.qdev, exynos4210_irq_gate_handler,
-            EXYNOS4210_IRQ_GATE_NINPUTS);
+    qdev_init_gpio_in(&s->busdev.qdev, exynos4210_irq_gate_handler, s->n_in);
 
-    /* Connect SysBusDev irqs to device specific irqs */
-    for (i = 0; i < EXYNOS4210_NCPUS; i++) {
-        sysbus_init_irq(dev, &s->pic_irq[i]);
-    }
+    s->level = g_malloc0(s->n_in * sizeof(*s->level));
+
+    sysbus_init_irq(dev, &s->out);
 
     return 0;
 }
@@ -449,6 +448,7 @@ static void exynos4210_irq_gate_class_init(ObjectClass *klass, void *data)
     k->init = exynos4210_irq_gate_init;
     dc->reset = exynos4210_irq_gate_reset;
     dc->vmsd = &vmstate_exynos4210_irq_gate;
+    dc->props = exynos4210_irq_gate_properties;
 }
 
 static TypeInfo exynos4210_irq_gate_info = {
commit 2fb70f6f1727e9696c703a47861d1173e2b2836f
Author: Christian Borntraeger <borntraeger at de.ibm.com>
Date:   Wed Jun 6 02:05:19 2012 +0000

    s390: stop target cpu on sigp initial reset
    
    We must not run the target cpu after an initial reset. This makes
    system_reset more reliable for smp guests.
    
    Signed-off-by: Christian Borntraeger <borntraeger at de.ibm.com>
    Signed-off-by: Alexander Graf <agraf at suse.de>

diff --git a/target-s390x/kvm.c b/target-s390x/kvm.c
index 5800fd6..ec08dd0 100644
--- a/target-s390x/kvm.c
+++ b/target-s390x/kvm.c
@@ -314,6 +314,7 @@ static int s390_cpu_initial_reset(CPUS390XState *env)
 {
     int i;
 
+    s390_del_running_cpu(env);
     if (kvm_vcpu_ioctl(env, KVM_S390_INITIAL_RESET, NULL) < 0) {
         perror("cannot init reset vcpu");
     }
commit c5854acb75510969bc3c483f61fbddb027123173
Author: Jens Freimann <jfrei at linux.vnet.ibm.com>
Date:   Wed Jun 6 02:05:18 2012 +0000

    s390: make kvm_stat work on s390
    
    Add s390_exit_reasons so kvm_stat doesn't crash when called on s390.
    Look for 'vendor_id' in /proc/cpuinfo as well, instead of just for
    'flags', so we can determine if we run on S390.
    
    Signed-off-by: Jens Freimann <jfrei at linux.vnet.ibm.com>
    Signed-off-by: Alexander Graf <agraf at suse.de>

diff --git a/scripts/kvm/kvm_stat b/scripts/kvm/kvm_stat
index 56d2bd7..e8d68f0 100755
--- a/scripts/kvm/kvm_stat
+++ b/scripts/kvm/kvm_stat
@@ -141,15 +141,39 @@ svm_exit_reasons = {
     0x400: 'NPF',
 }
 
+s390_exit_reasons = {
+	0x000: 'UNKNOWN',
+	0x001: 'EXCEPTION',
+	0x002: 'IO',
+	0x003: 'HYPERCALL',
+	0x004: 'DEBUG',
+	0x005: 'HLT',
+	0x006: 'MMIO',
+	0x007: 'IRQ_WINDOW_OPEN',
+	0x008: 'SHUTDOWN',
+	0x009: 'FAIL_ENTRY',
+	0x010: 'INTR',
+	0x011: 'SET_TPR',
+	0x012: 'TPR_ACCESS',
+	0x013: 'S390_SIEIC',
+	0x014: 'S390_RESET',
+	0x015: 'DCR',
+	0x016: 'NMI',
+	0x017: 'INTERNAL_ERROR',
+	0x018: 'OSI',
+	0x019: 'PAPR_HCALL',
+}
+
 vendor_exit_reasons = {
     'vmx': vmx_exit_reasons,
     'svm': svm_exit_reasons,
+    'IBM/S390': s390_exit_reasons,
 }
 
 exit_reasons = None
 
 for line in file('/proc/cpuinfo').readlines():
-    if line.startswith('flags'):
+    if line.startswith('flags') or line.startswith('vendor_id'):
         for flag in line.split():
             if flag in vendor_exit_reasons:
                 exit_reasons = vendor_exit_reasons[flag]
commit 2a60dba43cbf607c2d8ac3f30d5515267b4739b2
Author: Alexander Graf <agraf at suse.de>
Date:   Tue Jun 12 11:15:23 2012 +0200

    kvm: Update kernel headers
    
    Corresponding kvm.git hash: 4e3c8a1b1c
    
    Signed-off-by: Alexander Graf <agraf at suse.de>

diff --git a/linux-headers/asm-s390/kvm.h b/linux-headers/asm-s390/kvm.h
index 9607667..bdcbe0f 100644
--- a/linux-headers/asm-s390/kvm.h
+++ b/linux-headers/asm-s390/kvm.h
@@ -52,4 +52,9 @@ struct kvm_sync_regs {
 	__u32 acrs[16];	/* access registers */
 	__u64 crs[16];	/* control registers */
 };
+
+#define KVM_REG_S390_TODPR	(KVM_REG_S390 | KVM_REG_SIZE_U32 | 0x1)
+#define KVM_REG_S390_EPOCHDIFF	(KVM_REG_S390 | KVM_REG_SIZE_U64 | 0x2)
+#define KVM_REG_S390_CPU_TIMER  (KVM_REG_S390 | KVM_REG_SIZE_U64 | 0x3)
+#define KVM_REG_S390_CLOCK_COMP (KVM_REG_S390 | KVM_REG_SIZE_U64 | 0x4)
 #endif
diff --git a/linux-headers/linux/kvm.h b/linux-headers/linux/kvm.h
index c4426ec..5a9d4e3 100644
--- a/linux-headers/linux/kvm.h
+++ b/linux-headers/linux/kvm.h
@@ -616,6 +616,7 @@ struct kvm_ppc_smmu_info {
 #define KVM_CAP_KVMCLOCK_CTRL 76
 #define KVM_CAP_SIGNAL_MSI 77
 #define KVM_CAP_PPC_GET_SMMU_INFO 78
+#define KVM_CAP_S390_COW 79
 
 #ifdef KVM_CAP_IRQ_ROUTING
 
commit 5f629d943cb0b11c37a891cf4f40a9166aee6f53
Author: Alexander Graf <agraf at suse.de>
Date:   Fri May 18 02:36:26 2012 +0200

    s390x: fix s390 virtio aliases
    
    Some of the virtio devices have the same frontend name, but actually
    implement different devices behind the scenes through aliases.
    
    The indicator which device type to use is the architecture. On s390, we
    want s390 virtio devices. On everything else, we want PCI devices.
    
    Reflect this in the alias selection code. This way we fix commands like
    -device virtio-blk on s390x which with this patch applied select the
    correct virtio-blk-s390 device rather than virtio-blk-pci.
    
    Reported-by: Christian Borntraeger <borntraeger at de.ibm.com>
    Signed-off-by: Anthony Liguori <aliguori at us.ibm.com>
    Signed-off-by: Alexander Graf <agraf at suse.de>

diff --git a/hw/qdev-monitor.c b/hw/qdev-monitor.c
index b01ef06..f83b3ad 100644
--- a/hw/qdev-monitor.c
+++ b/hw/qdev-monitor.c
@@ -20,6 +20,7 @@
 #include "qdev.h"
 #include "monitor.h"
 #include "qmp-commands.h"
+#include "arch_init.h"
 
 /*
  * Aliases were a bad idea from the start.  Let's keep them
@@ -29,16 +30,18 @@ typedef struct QDevAlias
 {
     const char *typename;
     const char *alias;
+    uint32_t arch_mask;
 } QDevAlias;
 
 static const QDevAlias qdev_alias_table[] = {
-    { "virtio-blk-pci", "virtio-blk" },
-    { "virtio-net-pci", "virtio-net" },
-    { "virtio-serial-pci", "virtio-serial" },
-    { "virtio-balloon-pci", "virtio-balloon" },
-    { "virtio-blk-s390", "virtio-blk" },
-    { "virtio-net-s390", "virtio-net" },
-    { "virtio-serial-s390", "virtio-serial" },
+    { "virtio-blk-pci", "virtio-blk", QEMU_ARCH_ALL & ~QEMU_ARCH_S390X },
+    { "virtio-net-pci", "virtio-net", QEMU_ARCH_ALL & ~QEMU_ARCH_S390X },
+    { "virtio-serial-pci", "virtio-serial", QEMU_ARCH_ALL & ~QEMU_ARCH_S390X },
+    { "virtio-balloon-pci", "virtio-balloon",
+            QEMU_ARCH_ALL & ~QEMU_ARCH_S390X },
+    { "virtio-blk-s390", "virtio-blk", QEMU_ARCH_S390X },
+    { "virtio-net-s390", "virtio-net", QEMU_ARCH_S390X },
+    { "virtio-serial-s390", "virtio-serial", QEMU_ARCH_S390X },
     { "lsi53c895a", "lsi" },
     { "ich9-ahci", "ahci" },
     { }
@@ -50,6 +53,11 @@ static const char *qdev_class_get_alias(DeviceClass *dc)
     int i;
 
     for (i = 0; qdev_alias_table[i].typename; i++) {
+        if (qdev_alias_table[i].arch_mask &&
+            !(qdev_alias_table[i].arch_mask & arch_type)) {
+            continue;
+        }
+
         if (strcmp(qdev_alias_table[i].typename, typename) == 0) {
             return qdev_alias_table[i].alias;
         }
@@ -110,6 +118,11 @@ static const char *find_typename_by_alias(const char *alias)
     int i;
 
     for (i = 0; qdev_alias_table[i].alias; i++) {
+        if (qdev_alias_table[i].arch_mask &&
+            !(qdev_alias_table[i].arch_mask & arch_type)) {
+            continue;
+        }
+
         if (strcmp(qdev_alias_table[i].alias, alias) == 0) {
             return qdev_alias_table[i].typename;
         }
commit 572992eefa74bfb92c24a28bd268de91a9311b0f
Author: Alex Williamson <alex.williamson at redhat.com>
Date:   Thu Jun 14 12:16:57 2012 -0600

    msix: Switch msix_uninit to return void
    
    It can't fail.
    
    Signed-off-by: Alex Williamson <alex.williamson at redhat.com>
    Signed-off-by: Michael S. Tsirkin <mst at redhat.com>

diff --git a/hw/msix.c b/hw/msix.c
index 15f8d7d..fd9ea95 100644
--- a/hw/msix.c
+++ b/hw/msix.c
@@ -328,10 +328,10 @@ static void msix_free_irq_entries(PCIDevice *dev)
 }
 
 /* Clean up resources for the device. */
-int msix_uninit(PCIDevice *dev, MemoryRegion *table_bar, MemoryRegion *pba_bar)
+void msix_uninit(PCIDevice *dev, MemoryRegion *table_bar, MemoryRegion *pba_bar)
 {
     if (!msix_present(dev)) {
-        return 0;
+        return;
     }
     pci_del_capability(dev, PCI_CAP_ID_MSIX, MSIX_CAP_LENGTH);
     dev->msix_cap = 0;
@@ -348,7 +348,7 @@ int msix_uninit(PCIDevice *dev, MemoryRegion *table_bar, MemoryRegion *pba_bar)
     g_free(dev->msix_entry_used);
     dev->msix_entry_used = NULL;
     dev->cap_present &= ~QEMU_PCI_CAP_MSIX;
-    return 0;
+    return;
 }
 
 void msix_uninit_exclusive_bar(PCIDevice *dev)
diff --git a/hw/msix.h b/hw/msix.h
index f637797..1786e27 100644
--- a/hw/msix.h
+++ b/hw/msix.h
@@ -13,8 +13,8 @@ int msix_init_exclusive_bar(PCIDevice *dev, unsigned short nentries,
 
 void msix_write_config(PCIDevice *dev, uint32_t address, uint32_t val, int len);
 
-int msix_uninit(PCIDevice *dev, MemoryRegion *table_bar,
-                MemoryRegion *pba_bar);
+void msix_uninit(PCIDevice *dev, MemoryRegion *table_bar,
+                 MemoryRegion *pba_bar);
 void msix_uninit_exclusive_bar(PCIDevice *dev);
 
 unsigned int msix_nr_vectors_allocated(const PCIDevice *dev);
commit 5a2c20298196e1eea212ca0fb6d0f68869a1b86d
Author: Alex Williamson <alex.williamson at redhat.com>
Date:   Thu Jun 14 12:16:47 2012 -0600

    msix: Allow full specification of MSIX layout
    
    Finally, complete the fully specified interface.  msix_add_config()
    gets folded into msix_init() because we now have quite a few parameters
    to pass and rolling it in let's us error earlier, avoiding the ugly
    unwind exit path.  msix_mmio_setup() also gets rolled in, just because
    it's redundant to rediscover offsets when we already have them for
    such a tiny function.
    
    Signed-off-by: Alex Williamson <alex.williamson at redhat.com>
    Signed-off-by: Michael S. Tsirkin <mst at redhat.com>

diff --git a/hw/msix.c b/hw/msix.c
index 3312139..15f8d7d 100644
--- a/hw/msix.c
+++ b/hw/msix.c
@@ -27,14 +27,6 @@
 #define MSIX_ENABLE_MASK (PCI_MSIX_FLAGS_ENABLE >> 8)
 #define MSIX_MASKALL_MASK (PCI_MSIX_FLAGS_MASKALL >> 8)
 
-/* How much space does an MSIX table need. */
-/* The spec requires giving the table structure
- * a 4K aligned region all by itself. */
-#define MSIX_PAGE_SIZE 0x1000
-/* Reserve second half of the page for pending bits */
-#define MSIX_PAGE_PENDING (MSIX_PAGE_SIZE / 2)
-#define MSIX_MAX_ENTRIES 32
-
 static MSIMessage msix_get_message(PCIDevice *dev, unsigned vector)
 {
     uint8_t *table_entry = dev->msix_table + vector * PCI_MSIX_ENTRY_SIZE;
@@ -45,47 +37,6 @@ static MSIMessage msix_get_message(PCIDevice *dev, unsigned vector)
     return msg;
 }
 
-/* Add MSI-X capability to the config space for the device. */
-/* Given a bar and its size, add MSI-X table on top of it
- * and fill MSI-X capability in the config space.
- * Original bar size must be a power of 2 or 0.
- * New bar size is returned. */
-static int msix_add_config(struct PCIDevice *pdev, unsigned short nentries,
-                           unsigned bar_nr, unsigned bar_size)
-{
-    int config_offset;
-    uint8_t *config;
-
-    if (nentries < 1 || nentries > PCI_MSIX_FLAGS_QSIZE + 1)
-        return -EINVAL;
-    if (bar_size > 0x80000000)
-        return -ENOSPC;
-
-    /* Require aligned offset for MSI-X structures */
-    if (bar_size & ~(MSIX_PAGE_SIZE - 1)) {
-        return -EINVAL;
-    }
-
-    config_offset = pci_add_capability(pdev, PCI_CAP_ID_MSIX,
-                                       0, MSIX_CAP_LENGTH);
-    if (config_offset < 0)
-        return config_offset;
-    config = pdev->config + config_offset;
-
-    pci_set_word(config + PCI_MSIX_FLAGS, nentries - 1);
-    /* Table on top of BAR */
-    pci_set_long(config + PCI_MSIX_TABLE, bar_size | bar_nr);
-    /* Pending bits on top of that */
-    pci_set_long(config + PCI_MSIX_PBA, (bar_size + MSIX_PAGE_PENDING) |
-                 bar_nr);
-    pdev->msix_cap = config_offset;
-    /* Make flags bit writable. */
-    pdev->wmask[config_offset + MSIX_CONTROL_OFFSET] |= MSIX_ENABLE_MASK |
-	    MSIX_MASKALL_MASK;
-    pdev->msix_function_masked = true;
-    return 0;
-}
-
 static uint8_t msix_pending_mask(int vector)
 {
     return 1 << (vector % 8);
@@ -242,20 +193,6 @@ static const MemoryRegionOps msix_pba_mmio_ops = {
     },
 };
 
-static void msix_mmio_setup(PCIDevice *d, MemoryRegion *bar)
-{
-    uint8_t *config = d->config + d->msix_cap;
-    uint32_t table = pci_get_long(config + PCI_MSIX_TABLE);
-    uint32_t table_offset = table & ~PCI_MSIX_FLAGS_BIRMASK;
-    uint32_t pba = pci_get_long(config + PCI_MSIX_PBA);
-    uint32_t pba_offset = pba & ~PCI_MSIX_FLAGS_BIRMASK;
-    /* TODO: for assigned devices, we'll want to make it possible to map
-     * pending bits separately in case they are in a separate bar. */
-
-    memory_region_add_subregion(bar, table_offset, &d->msix_table_mmio);
-    memory_region_add_subregion(bar, pba_offset, &d->msix_pba_mmio);
-}
-
 static void msix_mask_all(struct PCIDevice *dev, unsigned nentries)
 {
     int vector;
@@ -270,57 +207,71 @@ static void msix_mask_all(struct PCIDevice *dev, unsigned nentries)
     }
 }
 
-/* Initialize the MSI-X structures. Note: if MSI-X is supported, BAR size is
- * modified, it should be retrieved with msix_bar_size. */
+/* Initialize the MSI-X structures */
 int msix_init(struct PCIDevice *dev, unsigned short nentries,
-              MemoryRegion *bar,
-              unsigned bar_nr, unsigned bar_size)
+              MemoryRegion *table_bar, uint8_t table_bar_nr,
+              unsigned table_offset, MemoryRegion *pba_bar,
+              uint8_t pba_bar_nr, unsigned pba_offset, uint8_t cap_pos)
 {
-    int ret;
+    int cap;
     unsigned table_size, pba_size;
+    uint8_t *config;
 
     /* Nothing to do if MSI is not supported by interrupt controller */
     if (!msi_supported) {
         return -ENOTSUP;
     }
-    if (nentries > MSIX_MAX_ENTRIES)
+
+    if (nentries < 1 || nentries > PCI_MSIX_FLAGS_QSIZE + 1) {
         return -EINVAL;
+    }
 
     table_size = nentries * PCI_MSIX_ENTRY_SIZE;
     pba_size = QEMU_ALIGN_UP(nentries, 64) / 8;
 
-    dev->msix_entry_used = g_malloc0(MSIX_MAX_ENTRIES *
-                                        sizeof *dev->msix_entry_used);
+    /* Sanity test: table & pba don't overlap, fit within BARs, min aligned */
+    if ((table_bar_nr == pba_bar_nr &&
+         ranges_overlap(table_offset, table_size, pba_offset, pba_size)) ||
+        table_offset + table_size > memory_region_size(table_bar) ||
+        pba_offset + pba_size > memory_region_size(pba_bar) ||
+        (table_offset | pba_offset) & PCI_MSIX_FLAGS_BIRMASK) {
+        return -EINVAL;
+    }
+
+    cap = pci_add_capability(dev, PCI_CAP_ID_MSIX, cap_pos, MSIX_CAP_LENGTH);
+    if (cap < 0) {
+        return cap;
+    }
+
+    dev->msix_cap = cap;
+    dev->cap_present |= QEMU_PCI_CAP_MSIX;
+    config = dev->config + cap;
+
+    pci_set_word(config + PCI_MSIX_FLAGS, nentries - 1);
+    dev->msix_entries_nr = nentries;
+    dev->msix_function_masked = true;
+
+    pci_set_long(config + PCI_MSIX_TABLE, table_offset | table_bar_nr);
+    pci_set_long(config + PCI_MSIX_PBA, pba_offset | pba_bar_nr);
+
+    /* Make flags bit writable. */
+    dev->wmask[cap + MSIX_CONTROL_OFFSET] |= MSIX_ENABLE_MASK |
+                                             MSIX_MASKALL_MASK;
 
     dev->msix_table = g_malloc0(table_size);
     dev->msix_pba = g_malloc0(pba_size);
+    dev->msix_entry_used = g_malloc0(nentries * sizeof *dev->msix_entry_used);
+
     msix_mask_all(dev, nentries);
 
     memory_region_init_io(&dev->msix_table_mmio, &msix_table_mmio_ops, dev,
                           "msix-table", table_size);
+    memory_region_add_subregion(table_bar, table_offset, &dev->msix_table_mmio);
     memory_region_init_io(&dev->msix_pba_mmio, &msix_pba_mmio_ops, dev,
                           "msix-pba", pba_size);
+    memory_region_add_subregion(pba_bar, pba_offset, &dev->msix_pba_mmio);
 
-    dev->msix_entries_nr = nentries;
-    ret = msix_add_config(dev, nentries, bar_nr, bar_size);
-    if (ret)
-        goto err_config;
-
-    dev->cap_present |= QEMU_PCI_CAP_MSIX;
-    msix_mmio_setup(dev, bar);
     return 0;
-
-err_config:
-    dev->msix_entries_nr = 0;
-    memory_region_destroy(&dev->msix_pba_mmio);
-    g_free(dev->msix_pba);
-    dev->msix_pba = NULL;
-    memory_region_destroy(&dev->msix_table_mmio);
-    g_free(dev->msix_table);
-    dev->msix_table = NULL;
-    g_free(dev->msix_entry_used);
-    dev->msix_entry_used = NULL;
-    return ret;
 }
 
 int msix_init_exclusive_bar(PCIDevice *dev, unsigned short nentries,
@@ -335,7 +286,9 @@ int msix_init_exclusive_bar(PCIDevice *dev, unsigned short nentries,
      * the upper half.  Do not use these elsewhere!
      */
 #define MSIX_EXCLUSIVE_BAR_SIZE 4096
+#define MSIX_EXCLUSIVE_BAR_TABLE_OFFSET 0
 #define MSIX_EXCLUSIVE_BAR_PBA_OFFSET (MSIX_EXCLUSIVE_BAR_SIZE / 2)
+#define MSIX_EXCLUSIVE_CAP_OFFSET 0
 
     if (nentries * PCI_MSIX_ENTRY_SIZE > MSIX_EXCLUSIVE_BAR_PBA_OFFSET) {
         return -EINVAL;
@@ -350,7 +303,9 @@ int msix_init_exclusive_bar(PCIDevice *dev, unsigned short nentries,
     free(name);
 
     ret = msix_init(dev, nentries, &dev->msix_exclusive_bar, bar_nr,
-                    MSIX_EXCLUSIVE_BAR_SIZE);
+                    MSIX_EXCLUSIVE_BAR_TABLE_OFFSET, &dev->msix_exclusive_bar,
+                    bar_nr, MSIX_EXCLUSIVE_BAR_PBA_OFFSET,
+                    MSIX_EXCLUSIVE_CAP_OFFSET);
     if (ret) {
         memory_region_destroy(&dev->msix_exclusive_bar);
         return ret;
@@ -373,7 +328,7 @@ static void msix_free_irq_entries(PCIDevice *dev)
 }
 
 /* Clean up resources for the device. */
-int msix_uninit(PCIDevice *dev, MemoryRegion *bar)
+int msix_uninit(PCIDevice *dev, MemoryRegion *table_bar, MemoryRegion *pba_bar)
 {
     if (!msix_present(dev)) {
         return 0;
@@ -382,11 +337,11 @@ int msix_uninit(PCIDevice *dev, MemoryRegion *bar)
     dev->msix_cap = 0;
     msix_free_irq_entries(dev);
     dev->msix_entries_nr = 0;
-    memory_region_del_subregion(bar, &dev->msix_pba_mmio);
+    memory_region_del_subregion(pba_bar, &dev->msix_pba_mmio);
     memory_region_destroy(&dev->msix_pba_mmio);
     g_free(dev->msix_pba);
     dev->msix_pba = NULL;
-    memory_region_del_subregion(bar, &dev->msix_table_mmio);
+    memory_region_del_subregion(table_bar, &dev->msix_table_mmio);
     memory_region_destroy(&dev->msix_table_mmio);
     g_free(dev->msix_table);
     dev->msix_table = NULL;
@@ -399,7 +354,7 @@ int msix_uninit(PCIDevice *dev, MemoryRegion *bar)
 void msix_uninit_exclusive_bar(PCIDevice *dev)
 {
     if (msix_present(dev)) {
-        msix_uninit(dev, &dev->msix_exclusive_bar);
+        msix_uninit(dev, &dev->msix_exclusive_bar, &dev->msix_exclusive_bar);
         memory_region_destroy(&dev->msix_exclusive_bar);
     }
 }
diff --git a/hw/msix.h b/hw/msix.h
index f681bb0..f637797 100644
--- a/hw/msix.h
+++ b/hw/msix.h
@@ -4,15 +4,17 @@
 #include "qemu-common.h"
 #include "pci.h"
 
-int msix_init(PCIDevice *pdev, unsigned short nentries,
-              MemoryRegion *bar,
-              unsigned bar_nr, unsigned bar_size);
+int msix_init(PCIDevice *dev, unsigned short nentries,
+              MemoryRegion *table_bar, uint8_t table_bar_nr,
+              unsigned table_offset, MemoryRegion *pba_bar,
+              uint8_t pba_bar_nr, unsigned pba_offset, uint8_t cap_pos);
 int msix_init_exclusive_bar(PCIDevice *dev, unsigned short nentries,
                             uint8_t bar_nr);
 
 void msix_write_config(PCIDevice *dev, uint32_t address, uint32_t val, int len);
 
-int msix_uninit(PCIDevice *d, MemoryRegion *bar);
+int msix_uninit(PCIDevice *dev, MemoryRegion *table_bar,
+                MemoryRegion *pba_bar);
 void msix_uninit_exclusive_bar(PCIDevice *dev);
 
 unsigned int msix_nr_vectors_allocated(const PCIDevice *dev);
commit d35e428c8400f9ddc07e5a15ff19622c869b9ba0
Author: Alex Williamson <alex.williamson at redhat.com>
Date:   Thu Jun 14 12:16:37 2012 -0600

    msix: Split PBA into it's own MemoryRegion
    
    These don't have to be contiguous.  Size them to only what
    they need and use separate MemoryRegions for the vector
    table and PBA.
    
    Signed-off-by: Alex Williamson <alex.williamson at redhat.com>
    Signed-off-by: Michael S. Tsirkin <mst at redhat.com>

diff --git a/hw/msix.c b/hw/msix.c
index 87d316a..3312139 100644
--- a/hw/msix.c
+++ b/hw/msix.c
@@ -37,7 +37,7 @@
 
 static MSIMessage msix_get_message(PCIDevice *dev, unsigned vector)
 {
-    uint8_t *table_entry = dev->msix_table_page + vector * PCI_MSIX_ENTRY_SIZE;
+    uint8_t *table_entry = dev->msix_table + vector * PCI_MSIX_ENTRY_SIZE;
     MSIMessage msg;
 
     msg.address = pci_get_quad(table_entry + PCI_MSIX_ENTRY_LOWER_ADDR);
@@ -93,7 +93,7 @@ static uint8_t msix_pending_mask(int vector)
 
 static uint8_t *msix_pending_byte(PCIDevice *dev, int vector)
 {
-    return dev->msix_table_page + MSIX_PAGE_PENDING + vector / 8;
+    return dev->msix_pba + vector / 8;
 }
 
 static int msix_is_pending(PCIDevice *dev, int vector)
@@ -114,7 +114,7 @@ static void msix_clr_pending(PCIDevice *dev, int vector)
 static bool msix_vector_masked(PCIDevice *dev, int vector, bool fmask)
 {
     unsigned offset = vector * PCI_MSIX_ENTRY_SIZE + PCI_MSIX_ENTRY_VECTOR_CTRL;
-    return fmask || dev->msix_table_page[offset] & PCI_MSIX_ENTRY_CTRL_MASKBIT;
+    return fmask || dev->msix_table[offset] & PCI_MSIX_ENTRY_CTRL_MASKBIT;
 }
 
 static bool msix_is_masked(PCIDevice *dev, int vector)
@@ -193,37 +193,47 @@ void msix_write_config(PCIDevice *dev, uint32_t addr,
     }
 }
 
-static uint64_t msix_mmio_read(void *opaque, target_phys_addr_t addr,
-                               unsigned size)
+static uint64_t msix_table_mmio_read(void *opaque, target_phys_addr_t addr,
+                                     unsigned size)
 {
     PCIDevice *dev = opaque;
-    unsigned int offset = addr & (MSIX_PAGE_SIZE - 1) & ~0x3;
-    void *page = dev->msix_table_page;
 
-    return pci_get_long(page + offset);
+    return pci_get_long(dev->msix_table + addr);
 }
 
-static void msix_mmio_write(void *opaque, target_phys_addr_t addr,
-                            uint64_t val, unsigned size)
+static void msix_table_mmio_write(void *opaque, target_phys_addr_t addr,
+                                  uint64_t val, unsigned size)
 {
     PCIDevice *dev = opaque;
-    unsigned int offset = addr & (MSIX_PAGE_SIZE - 1) & ~0x3;
-    int vector = offset / PCI_MSIX_ENTRY_SIZE;
+    int vector = addr / PCI_MSIX_ENTRY_SIZE;
     bool was_masked;
 
-    /* MSI-X page includes a read-only PBA and a writeable Vector Control. */
-    if (vector >= dev->msix_entries_nr) {
-        return;
-    }
-
     was_masked = msix_is_masked(dev, vector);
-    pci_set_long(dev->msix_table_page + offset, val);
+    pci_set_long(dev->msix_table + addr, val);
     msix_handle_mask_update(dev, vector, was_masked);
 }
 
-static const MemoryRegionOps msix_mmio_ops = {
-    .read = msix_mmio_read,
-    .write = msix_mmio_write,
+static const MemoryRegionOps msix_table_mmio_ops = {
+    .read = msix_table_mmio_read,
+    .write = msix_table_mmio_write,
+    /* TODO: MSIX should be LITTLE_ENDIAN. */
+    .endianness = DEVICE_NATIVE_ENDIAN,
+    .valid = {
+        .min_access_size = 4,
+        .max_access_size = 4,
+    },
+};
+
+static uint64_t msix_pba_mmio_read(void *opaque, target_phys_addr_t addr,
+                                   unsigned size)
+{
+    PCIDevice *dev = opaque;
+
+    return pci_get_long(dev->msix_pba + addr);
+}
+
+static const MemoryRegionOps msix_pba_mmio_ops = {
+    .read = msix_pba_mmio_read,
     /* TODO: MSIX should be LITTLE_ENDIAN. */
     .endianness = DEVICE_NATIVE_ENDIAN,
     .valid = {
@@ -236,11 +246,14 @@ static void msix_mmio_setup(PCIDevice *d, MemoryRegion *bar)
 {
     uint8_t *config = d->config + d->msix_cap;
     uint32_t table = pci_get_long(config + PCI_MSIX_TABLE);
-    uint32_t offset = table & ~(MSIX_PAGE_SIZE - 1);
+    uint32_t table_offset = table & ~PCI_MSIX_FLAGS_BIRMASK;
+    uint32_t pba = pci_get_long(config + PCI_MSIX_PBA);
+    uint32_t pba_offset = pba & ~PCI_MSIX_FLAGS_BIRMASK;
     /* TODO: for assigned devices, we'll want to make it possible to map
      * pending bits separately in case they are in a separate bar. */
 
-    memory_region_add_subregion(bar, offset, &d->msix_mmio);
+    memory_region_add_subregion(bar, table_offset, &d->msix_table_mmio);
+    memory_region_add_subregion(bar, pba_offset, &d->msix_pba_mmio);
 }
 
 static void msix_mask_all(struct PCIDevice *dev, unsigned nentries)
@@ -252,7 +265,7 @@ static void msix_mask_all(struct PCIDevice *dev, unsigned nentries)
             vector * PCI_MSIX_ENTRY_SIZE + PCI_MSIX_ENTRY_VECTOR_CTRL;
         bool was_masked = msix_is_masked(dev, vector);
 
-        dev->msix_table_page[offset] |= PCI_MSIX_ENTRY_CTRL_MASKBIT;
+        dev->msix_table[offset] |= PCI_MSIX_ENTRY_CTRL_MASKBIT;
         msix_handle_mask_update(dev, vector, was_masked);
     }
 }
@@ -264,6 +277,7 @@ int msix_init(struct PCIDevice *dev, unsigned short nentries,
               unsigned bar_nr, unsigned bar_size)
 {
     int ret;
+    unsigned table_size, pba_size;
 
     /* Nothing to do if MSI is not supported by interrupt controller */
     if (!msi_supported) {
@@ -272,14 +286,20 @@ int msix_init(struct PCIDevice *dev, unsigned short nentries,
     if (nentries > MSIX_MAX_ENTRIES)
         return -EINVAL;
 
+    table_size = nentries * PCI_MSIX_ENTRY_SIZE;
+    pba_size = QEMU_ALIGN_UP(nentries, 64) / 8;
+
     dev->msix_entry_used = g_malloc0(MSIX_MAX_ENTRIES *
                                         sizeof *dev->msix_entry_used);
 
-    dev->msix_table_page = g_malloc0(MSIX_PAGE_SIZE);
+    dev->msix_table = g_malloc0(table_size);
+    dev->msix_pba = g_malloc0(pba_size);
     msix_mask_all(dev, nentries);
 
-    memory_region_init_io(&dev->msix_mmio, &msix_mmio_ops, dev,
-                          "msix", MSIX_PAGE_SIZE);
+    memory_region_init_io(&dev->msix_table_mmio, &msix_table_mmio_ops, dev,
+                          "msix-table", table_size);
+    memory_region_init_io(&dev->msix_pba_mmio, &msix_pba_mmio_ops, dev,
+                          "msix-pba", pba_size);
 
     dev->msix_entries_nr = nentries;
     ret = msix_add_config(dev, nentries, bar_nr, bar_size);
@@ -292,9 +312,12 @@ int msix_init(struct PCIDevice *dev, unsigned short nentries,
 
 err_config:
     dev->msix_entries_nr = 0;
-    memory_region_destroy(&dev->msix_mmio);
-    g_free(dev->msix_table_page);
-    dev->msix_table_page = NULL;
+    memory_region_destroy(&dev->msix_pba_mmio);
+    g_free(dev->msix_pba);
+    dev->msix_pba = NULL;
+    memory_region_destroy(&dev->msix_table_mmio);
+    g_free(dev->msix_table);
+    dev->msix_table = NULL;
     g_free(dev->msix_entry_used);
     dev->msix_entry_used = NULL;
     return ret;
@@ -359,10 +382,14 @@ int msix_uninit(PCIDevice *dev, MemoryRegion *bar)
     dev->msix_cap = 0;
     msix_free_irq_entries(dev);
     dev->msix_entries_nr = 0;
-    memory_region_del_subregion(bar, &dev->msix_mmio);
-    memory_region_destroy(&dev->msix_mmio);
-    g_free(dev->msix_table_page);
-    dev->msix_table_page = NULL;
+    memory_region_del_subregion(bar, &dev->msix_pba_mmio);
+    memory_region_destroy(&dev->msix_pba_mmio);
+    g_free(dev->msix_pba);
+    dev->msix_pba = NULL;
+    memory_region_del_subregion(bar, &dev->msix_table_mmio);
+    memory_region_destroy(&dev->msix_table_mmio);
+    g_free(dev->msix_table);
+    dev->msix_table = NULL;
     g_free(dev->msix_entry_used);
     dev->msix_entry_used = NULL;
     dev->cap_present &= ~QEMU_PCI_CAP_MSIX;
@@ -385,8 +412,8 @@ void msix_save(PCIDevice *dev, QEMUFile *f)
         return;
     }
 
-    qemu_put_buffer(f, dev->msix_table_page, n * PCI_MSIX_ENTRY_SIZE);
-    qemu_put_buffer(f, dev->msix_table_page + MSIX_PAGE_PENDING, (n + 7) / 8);
+    qemu_put_buffer(f, dev->msix_table, n * PCI_MSIX_ENTRY_SIZE);
+    qemu_put_buffer(f, dev->msix_pba, (n + 7) / 8);
 }
 
 /* Should be called after restoring the config space. */
@@ -400,8 +427,8 @@ void msix_load(PCIDevice *dev, QEMUFile *f)
     }
 
     msix_free_irq_entries(dev);
-    qemu_get_buffer(f, dev->msix_table_page, n * PCI_MSIX_ENTRY_SIZE);
-    qemu_get_buffer(f, dev->msix_table_page + MSIX_PAGE_PENDING, (n + 7) / 8);
+    qemu_get_buffer(f, dev->msix_table, n * PCI_MSIX_ENTRY_SIZE);
+    qemu_get_buffer(f, dev->msix_pba, (n + 7) / 8);
     msix_update_function_masked(dev);
 
     for (vector = 0; vector < n; vector++) {
@@ -448,7 +475,8 @@ void msix_reset(PCIDevice *dev)
     msix_free_irq_entries(dev);
     dev->config[dev->msix_cap + MSIX_CONTROL_OFFSET] &=
 	    ~dev->wmask[dev->msix_cap + MSIX_CONTROL_OFFSET];
-    memset(dev->msix_table_page, 0, MSIX_PAGE_SIZE);
+    memset(dev->msix_table, 0, dev->msix_entries_nr * PCI_MSIX_ENTRY_SIZE);
+    memset(dev->msix_pba, 0, QEMU_ALIGN_UP(dev->msix_entries_nr, 64) / 8);
     msix_mask_all(dev, dev->msix_entries_nr);
 }
 
diff --git a/hw/pci.h b/hw/pci.h
index 7344891..44ae871 100644
--- a/hw/pci.h
+++ b/hw/pci.h
@@ -220,12 +220,14 @@ struct PCIDevice {
     /* MSI-X entries */
     int msix_entries_nr;
 
-    /* Space to store MSIX table */
-    uint8_t *msix_table_page;
+    /* Space to store MSIX table & pending bit array */
+    uint8_t *msix_table;
+    uint8_t *msix_pba;
     /* MemoryRegion container for msix exclusive BAR setup */
     MemoryRegion msix_exclusive_bar;
-    /* MMIO index used to map MSIX table and pending bit entries. */
-    MemoryRegion msix_mmio;
+    /* Memory Regions for MSIX table and pending bit entries. */
+    MemoryRegion msix_table_mmio;
+    MemoryRegion msix_pba_mmio;
     /* Reference-count for entries actually in use by driver. */
     unsigned *msix_entry_used;
     /* MSIX function mask set or MSIX disabled */
commit 2cf62ad74261a9bd90e5b720e726f0404640b16a
Author: Alex Williamson <alex.williamson at redhat.com>
Date:   Thu Jun 14 12:16:28 2012 -0600

    msix: Note endian TODO item
    
    MSIX, like PCI, is little endian.  Specifying native is wrong here,
    but we need to check the rest of the file to determine if it's
    as simple as flipping this macro.
    
    Signed-off-by: Alex Williamson <alex.williamson at redhat.com>
    Signed-off-by: Michael S. Tsirkin <mst at redhat.com>

diff --git a/hw/msix.c b/hw/msix.c
index 50885ac..87d316a 100644
--- a/hw/msix.c
+++ b/hw/msix.c
@@ -224,6 +224,7 @@ static void msix_mmio_write(void *opaque, target_phys_addr_t addr,
 static const MemoryRegionOps msix_mmio_ops = {
     .read = msix_mmio_read,
     .write = msix_mmio_write,
+    /* TODO: MSIX should be LITTLE_ENDIAN. */
     .endianness = DEVICE_NATIVE_ENDIAN,
     .valid = {
         .min_access_size = 4,
commit eebcb0a76a7e8b093740c9bd3db00f5b38e79a33
Author: Alex Williamson <alex.williamson at redhat.com>
Date:   Thu Jun 14 12:16:19 2012 -0600

    msix: Move msix_mmio_read
    
    What's this doing so far from msix_mmio_ops?
    
    Signed-off-by: Alex Williamson <alex.williamson at redhat.com>
    Signed-off-by: Michael S. Tsirkin <mst at redhat.com>

diff --git a/hw/msix.c b/hw/msix.c
index bafea94..50885ac 100644
--- a/hw/msix.c
+++ b/hw/msix.c
@@ -86,16 +86,6 @@ static int msix_add_config(struct PCIDevice *pdev, unsigned short nentries,
     return 0;
 }
 
-static uint64_t msix_mmio_read(void *opaque, target_phys_addr_t addr,
-                               unsigned size)
-{
-    PCIDevice *dev = opaque;
-    unsigned int offset = addr & (MSIX_PAGE_SIZE - 1) & ~0x3;
-    void *page = dev->msix_table_page;
-
-    return pci_get_long(page + offset);
-}
-
 static uint8_t msix_pending_mask(int vector)
 {
     return 1 << (vector % 8);
@@ -203,6 +193,16 @@ void msix_write_config(PCIDevice *dev, uint32_t addr,
     }
 }
 
+static uint64_t msix_mmio_read(void *opaque, target_phys_addr_t addr,
+                               unsigned size)
+{
+    PCIDevice *dev = opaque;
+    unsigned int offset = addr & (MSIX_PAGE_SIZE - 1) & ~0x3;
+    void *page = dev->msix_table_page;
+
+    return pci_get_long(page + offset);
+}
+
 static void msix_mmio_write(void *opaque, target_phys_addr_t addr,
                             uint64_t val, unsigned size)
 {
commit b2357c484d3b3e2afd305b71fb5bc0b0b8d61ca8
Author: Alex Williamson <alex.williamson at redhat.com>
Date:   Thu Jun 14 12:16:10 2012 -0600

    virtio: Convert to msix_init_exclusive_bar() interface
    
    Simple conversion.
    
    Signed-off-by: Alex Williamson <alex.williamson at redhat.com>
    Signed-off-by: Michael S. Tsirkin <mst at redhat.com>

diff --git a/hw/virtio-pci.c b/hw/virtio-pci.c
index 9342eed..3dca37f 100644
--- a/hw/virtio-pci.c
+++ b/hw/virtio-pci.c
@@ -782,13 +782,10 @@ void virtio_init_pci(VirtIOPCIProxy *proxy, VirtIODevice *vdev)
     pci_set_word(config + PCI_SUBSYSTEM_ID, vdev->device_id);
     config[PCI_INTERRUPT_PIN] = 1;
 
-    memory_region_init(&proxy->msix_bar, "virtio-msix", 4096);
-    if (vdev->nvectors && !msix_init(&proxy->pci_dev, vdev->nvectors,
-                                     &proxy->msix_bar, 1, 0)) {
-        pci_register_bar(&proxy->pci_dev, 1, PCI_BASE_ADDRESS_SPACE_MEMORY,
-                         &proxy->msix_bar);
-    } else
+    if (vdev->nvectors &&
+        msix_init_exclusive_bar(&proxy->pci_dev, vdev->nvectors, 1)) {
         vdev->nvectors = 0;
+    }
 
     proxy->pci_dev.config_write = virtio_write_config;
 
@@ -834,12 +831,10 @@ static int virtio_blk_init_pci(PCIDevice *pci_dev)
 static int virtio_exit_pci(PCIDevice *pci_dev)
 {
     VirtIOPCIProxy *proxy = DO_UPCAST(VirtIOPCIProxy, pci_dev, pci_dev);
-    int r;
 
     memory_region_destroy(&proxy->bar);
-    r = msix_uninit(pci_dev, &proxy->msix_bar);
-    memory_region_destroy(&proxy->msix_bar);
-    return r;
+    msix_uninit_exclusive_bar(pci_dev);
+    return 0;
 }
 
 static int virtio_blk_exit_pci(PCIDevice *pci_dev)
diff --git a/hw/virtio-pci.h b/hw/virtio-pci.h
index 91b791b..ac9d522 100644
--- a/hw/virtio-pci.h
+++ b/hw/virtio-pci.h
@@ -34,7 +34,6 @@ typedef struct {
     PCIDevice pci_dev;
     VirtIODevice *vdev;
     MemoryRegion bar;
-    MemoryRegion msix_bar;
     uint32_t flags;
     uint32_t class_code;
     uint32_t nvectors;
commit 1116b5392129a9961335c2b64e63003736e3c2df
Author: Alex Williamson <alex.williamson at redhat.com>
Date:   Thu Jun 14 12:16:01 2012 -0600

    ivshmem: Convert to msix_init_exclusive_bar() interface
    
    Trivial conversion, failed to have an uninit before and after.
    
    Signed-off-by: Alex Williamson <alex.williamson at redhat.com>
    Signed-off-by: Michael S. Tsirkin <mst at redhat.com>

diff --git a/hw/ivshmem.c b/hw/ivshmem.c
index 05559b6..8b49eee 100644
--- a/hw/ivshmem.c
+++ b/hw/ivshmem.c
@@ -70,7 +70,6 @@ typedef struct IVShmemState {
      */
     MemoryRegion bar;
     MemoryRegion ivshmem;
-    MemoryRegion msix_bar;
     uint64_t ivshmem_size; /* size of shared memory region */
     int shm_fd; /* shared memory file descriptor */
 
@@ -563,16 +562,13 @@ static uint64_t ivshmem_get_size(IVShmemState * s) {
 
 static void ivshmem_setup_msi(IVShmemState * s)
 {
-    memory_region_init(&s->msix_bar, "ivshmem-msix", 4096);
-    if (!msix_init(&s->dev, s->vectors, &s->msix_bar, 1, 0)) {
-        pci_register_bar(&s->dev, 1, PCI_BASE_ADDRESS_SPACE_MEMORY,
-                         &s->msix_bar);
-        IVSHMEM_DPRINTF("msix initialized (%d vectors)\n", s->vectors);
-    } else {
+    if (msix_init_exclusive_bar(&s->dev, s->vectors, 1)) {
         IVSHMEM_DPRINTF("msix initialization failed\n");
         exit(1);
     }
 
+    IVSHMEM_DPRINTF("msix initialized (%d vectors)\n", s->vectors);
+
     /* allocate QEMU char devices for receiving interrupts */
     s->eventfd_table = g_malloc0(s->vectors * sizeof(EventfdEntry));
 
commit 53f949254ad2435bfd45cb0dee96f246a0bdd7e3
Author: Alex Williamson <alex.williamson at redhat.com>
Date:   Thu Jun 14 12:15:51 2012 -0600

    msix: Add simple BAR allocation MSIX setup functions
    
    msi_init() takes over a BAR without really specifying or allowing
    specification of how it does so.  Instead, let's split it into
    two interfaces, one fully specified, and one trivially easy.  This
    implements the latter.  msix_init_exclusive_bar() takes over
    allocating and filling a PCI BAR _exclusively_ for the use of MSIX.
    When used, the matching msi_uninit_exclusive_bar() should be used
    to tear it down.
    
    Signed-off-by: Alex Williamson <alex.williamson at redhat.com>
    Signed-off-by: Michael S. Tsirkin <mst at redhat.com>

diff --git a/hw/msix.c b/hw/msix.c
index b64f109..bafea94 100644
--- a/hw/msix.c
+++ b/hw/msix.c
@@ -299,6 +299,45 @@ err_config:
     return ret;
 }
 
+int msix_init_exclusive_bar(PCIDevice *dev, unsigned short nentries,
+                            uint8_t bar_nr)
+{
+    int ret;
+    char *name;
+
+    /*
+     * Migration compatibility dictates that this remains a 4k
+     * BAR with the vector table in the lower half and PBA in
+     * the upper half.  Do not use these elsewhere!
+     */
+#define MSIX_EXCLUSIVE_BAR_SIZE 4096
+#define MSIX_EXCLUSIVE_BAR_PBA_OFFSET (MSIX_EXCLUSIVE_BAR_SIZE / 2)
+
+    if (nentries * PCI_MSIX_ENTRY_SIZE > MSIX_EXCLUSIVE_BAR_PBA_OFFSET) {
+        return -EINVAL;
+    }
+
+    if (asprintf(&name, "%s-msix", dev->name) == -1) {
+        return -ENOMEM;
+    }
+
+    memory_region_init(&dev->msix_exclusive_bar, name, MSIX_EXCLUSIVE_BAR_SIZE);
+
+    free(name);
+
+    ret = msix_init(dev, nentries, &dev->msix_exclusive_bar, bar_nr,
+                    MSIX_EXCLUSIVE_BAR_SIZE);
+    if (ret) {
+        memory_region_destroy(&dev->msix_exclusive_bar);
+        return ret;
+    }
+
+    pci_register_bar(dev, bar_nr, PCI_BASE_ADDRESS_SPACE_MEMORY,
+                     &dev->msix_exclusive_bar);
+
+    return 0;
+}
+
 static void msix_free_irq_entries(PCIDevice *dev)
 {
     int vector;
@@ -329,6 +368,14 @@ int msix_uninit(PCIDevice *dev, MemoryRegion *bar)
     return 0;
 }
 
+void msix_uninit_exclusive_bar(PCIDevice *dev)
+{
+    if (msix_present(dev)) {
+        msix_uninit(dev, &dev->msix_exclusive_bar);
+        memory_region_destroy(&dev->msix_exclusive_bar);
+    }
+}
+
 void msix_save(PCIDevice *dev, QEMUFile *f)
 {
     unsigned n = dev->msix_entries_nr;
diff --git a/hw/msix.h b/hw/msix.h
index 4a17f94..f681bb0 100644
--- a/hw/msix.h
+++ b/hw/msix.h
@@ -7,10 +7,13 @@
 int msix_init(PCIDevice *pdev, unsigned short nentries,
               MemoryRegion *bar,
               unsigned bar_nr, unsigned bar_size);
+int msix_init_exclusive_bar(PCIDevice *dev, unsigned short nentries,
+                            uint8_t bar_nr);
 
 void msix_write_config(PCIDevice *dev, uint32_t address, uint32_t val, int len);
 
 int msix_uninit(PCIDevice *d, MemoryRegion *bar);
+void msix_uninit_exclusive_bar(PCIDevice *dev);
 
 unsigned int msix_nr_vectors_allocated(const PCIDevice *dev);
 
diff --git a/hw/pci.h b/hw/pci.h
index 3d534e7..7344891 100644
--- a/hw/pci.h
+++ b/hw/pci.h
@@ -222,6 +222,8 @@ struct PCIDevice {
 
     /* Space to store MSIX table */
     uint8_t *msix_table_page;
+    /* MemoryRegion container for msix exclusive BAR setup */
+    MemoryRegion msix_exclusive_bar;
     /* MMIO index used to map MSIX table and pending bit entries. */
     MemoryRegion msix_mmio;
     /* Reference-count for entries actually in use by driver. */
commit 118f2c2b48b9758a3a2967868b337eb388d1531b
Author: Alex Williamson <alex.williamson at redhat.com>
Date:   Wed Jun 13 22:52:06 2012 -0600

    msix: fix PCIDevice naming inconsistency
    
    msix.h calls the PCIDevice * parameter "dev" almost everywhere except
    the msix_write_config declaration. Fix the inconsistency.
    
    Signed-off-by: Alex Williamson <alex.williamson at redhat.com>
    Signed-off-by: Michael S. Tsirkin <mst at redhat.com>

diff --git a/hw/msix.h b/hw/msix.h
index e5a488d..4a17f94 100644
--- a/hw/msix.h
+++ b/hw/msix.h
@@ -8,8 +8,7 @@ int msix_init(PCIDevice *pdev, unsigned short nentries,
               MemoryRegion *bar,
               unsigned bar_nr, unsigned bar_size);
 
-void msix_write_config(PCIDevice *pci_dev, uint32_t address,
-                       uint32_t val, int len);
+void msix_write_config(PCIDevice *dev, uint32_t address, uint32_t val, int len);
 
 int msix_uninit(PCIDevice *d, MemoryRegion *bar);
 
commit 393a98924eb00df76231384b86652e1d5f964d67
Author: Jan Kiszka <jan.kiszka at siemens.com>
Date:   Mon Jun 4 16:56:01 2012 +0200

    msix: drop unused msix_bar_size, require valid bar_size
    
    No user in sight for msix_bar_size.
    bar_size for all users is aligned, let's simply
    require this instead of trying to fix up invalid input.
    
    Signed-off-by: Jan Kiszka <jan.kiszka at siemens.com>
    Signed-off-by: Michael S. Tsirkin <mst at redhat.com>

diff --git a/hw/msix.c b/hw/msix.c
index ded3c55..b64f109 100644
--- a/hw/msix.c
+++ b/hw/msix.c
@@ -55,24 +55,17 @@ static int msix_add_config(struct PCIDevice *pdev, unsigned short nentries,
 {
     int config_offset;
     uint8_t *config;
-    uint32_t new_size;
 
     if (nentries < 1 || nentries > PCI_MSIX_FLAGS_QSIZE + 1)
         return -EINVAL;
     if (bar_size > 0x80000000)
         return -ENOSPC;
 
-    /* Add space for MSI-X structures */
-    if (!bar_size) {
-        new_size = MSIX_PAGE_SIZE;
-    } else if (bar_size < MSIX_PAGE_SIZE) {
-        bar_size = MSIX_PAGE_SIZE;
-        new_size = MSIX_PAGE_SIZE * 2;
-    } else {
-        new_size = bar_size * 2;
+    /* Require aligned offset for MSI-X structures */
+    if (bar_size & ~(MSIX_PAGE_SIZE - 1)) {
+        return -EINVAL;
     }
 
-    pdev->msix_bar_size = new_size;
     config_offset = pci_add_capability(pdev, PCI_CAP_ID_MSIX,
                                        0, MSIX_CAP_LENGTH);
     if (config_offset < 0)
@@ -382,13 +375,6 @@ int msix_enabled(PCIDevice *dev)
          MSIX_ENABLE_MASK);
 }
 
-/* Size of bar where MSI-X table resides, or 0 if MSI-X not supported. */
-uint32_t msix_bar_size(PCIDevice *dev)
-{
-    return (dev->cap_present & QEMU_PCI_CAP_MSIX) ?
-        dev->msix_bar_size : 0;
-}
-
 /* Send an MSI-X message */
 void msix_notify(PCIDevice *dev, unsigned vector)
 {
diff --git a/hw/msix.h b/hw/msix.h
index 50aee82..e5a488d 100644
--- a/hw/msix.h
+++ b/hw/msix.h
@@ -21,8 +21,6 @@ void msix_load(PCIDevice *dev, QEMUFile *f);
 int msix_enabled(PCIDevice *dev);
 int msix_present(PCIDevice *dev);
 
-uint32_t msix_bar_size(PCIDevice *dev);
-
 int msix_vector_use(PCIDevice *dev, unsigned vector);
 void msix_vector_unuse(PCIDevice *dev, unsigned vector);
 void msix_unuse_all_vectors(PCIDevice *dev);
diff --git a/hw/pci.h b/hw/pci.h
index c3cacce..3d534e7 100644
--- a/hw/pci.h
+++ b/hw/pci.h
@@ -226,8 +226,6 @@ struct PCIDevice {
     MemoryRegion msix_mmio;
     /* Reference-count for entries actually in use by driver. */
     unsigned *msix_entry_used;
-    /* Region including the MSI-X table */
-    uint32_t msix_bar_size;
     /* MSIX function mask set or MSIX disabled */
     bool msix_function_masked;
     /* Version id needed for VMState */
commit 25e5e4c7e9d5ec3e95c9526d1abaca40ada50ab0
Author: Michael Tokarev <mjt at tls.msk.ru>
Date:   Wed Mar 14 11:18:54 2012 +0400

    rewrite iov_send_recv() and move it to iov.c
    
    Make it much more understandable, add a missing
    iov_cnt argument (number of iovs in the iov), and
    add comments to it.
    
    The new implementation has been extensively tested
    by splitting a large buffer into many small
    randomly-sized chunks, sending it over socket to
    another, slow process and verifying the receiving
    data is the same.
    
    Also add a unit test for iov_send_recv(), sending/
    receiving data between two processes over a socketpair
    using random vectors and random sizes.
    
    Signed-off-by: Michael Tokarev <mjt at tls.msk.ru>

diff --git a/cutils.c b/cutils.c
index cb6f638..e2bc1b8 100644
--- a/cutils.c
+++ b/cutils.c
@@ -375,86 +375,3 @@ int qemu_parse_fd(const char *param)
     }
     return fd;
 }
-
-ssize_t iov_send_recv(int sockfd, struct iovec *iov,
-                      size_t offset, size_t bytes,
-                      bool do_sendv)
-{
-    int iovlen;
-    ssize_t ret;
-    size_t diff;
-    struct iovec *last_iov;
-
-    /* last_iov is inclusive, so count from one.  */
-    iovlen = 1;
-    last_iov = iov;
-    bytes += offset;
-
-    while (last_iov->iov_len < bytes) {
-        bytes -= last_iov->iov_len;
-
-        last_iov++;
-        iovlen++;
-    }
-
-    diff = last_iov->iov_len - bytes;
-    last_iov->iov_len -= diff;
-
-    while (iov->iov_len <= offset) {
-        offset -= iov->iov_len;
-
-        iov++;
-        iovlen--;
-    }
-
-    iov->iov_base = (char *) iov->iov_base + offset;
-    iov->iov_len -= offset;
-
-    {
-#if defined CONFIG_IOVEC && defined CONFIG_POSIX
-        struct msghdr msg;
-        memset(&msg, 0, sizeof(msg));
-        msg.msg_iov = iov;
-        msg.msg_iovlen = iovlen;
-
-        do {
-            if (do_sendv) {
-                ret = sendmsg(sockfd, &msg, 0);
-            } else {
-                ret = recvmsg(sockfd, &msg, 0);
-            }
-        } while (ret == -1 && errno == EINTR);
-#else
-        struct iovec *p = iov;
-        ret = 0;
-        while (iovlen > 0) {
-            int rc;
-            if (do_sendv) {
-                rc = send(sockfd, p->iov_base, p->iov_len, 0);
-            } else {
-                rc = qemu_recv(sockfd, p->iov_base, p->iov_len, 0);
-            }
-            if (rc == -1) {
-                if (errno == EINTR) {
-                    continue;
-                }
-                if (ret == 0) {
-                    ret = -1;
-                }
-                break;
-            }
-            if (rc == 0) {
-                break;
-            }
-            ret += rc;
-            iovlen--, p++;
-        }
-#endif
-    }
-
-    /* Undo the changes above */
-    iov->iov_base = (char *) iov->iov_base - offset;
-    iov->iov_len += offset;
-    last_iov->iov_len += diff;
-    return ret;
-}
diff --git a/iov.c b/iov.c
index 9657d28..7cc08f0 100644
--- a/iov.c
+++ b/iov.c
@@ -18,6 +18,14 @@
 
 #include "iov.h"
 
+#ifdef _WIN32
+# include <windows.h>
+# include <winsock2.h>
+#else
+# include <sys/types.h>
+# include <sys/socket.h>
+#endif
+
 size_t iov_from_buf(struct iovec *iov, unsigned int iov_cnt,
                     size_t offset, const void *buf, size_t bytes)
 {
@@ -87,6 +95,101 @@ size_t iov_size(const struct iovec *iov, const unsigned int iov_cnt)
     return len;
 }
 
+/* helper function for iov_send_recv() */
+static ssize_t
+do_send_recv(int sockfd, struct iovec *iov, unsigned iov_cnt, bool do_send)
+{
+#if defined CONFIG_IOVEC && defined CONFIG_POSIX
+    ssize_t ret;
+    struct msghdr msg;
+    memset(&msg, 0, sizeof(msg));
+    msg.msg_iov = iov;
+    msg.msg_iovlen = iov_cnt;
+    do {
+        ret = do_send
+            ? sendmsg(sockfd, &msg, 0)
+            : recvmsg(sockfd, &msg, 0);
+    } while (ret < 0 && errno == EINTR);
+    return ret;
+#else
+    /* else send piece-by-piece */
+    /*XXX Note: windows has WSASend() and WSARecv() */
+    unsigned i;
+    size_t count = 0;
+    for (i = 0; i < iov_cnt; ++i) {
+        ssize_t r = do_send
+            ? send(sockfd, iov[i].iov_base, iov[i].iov_len, 0)
+            : recv(sockfd, iov[i].iov_base, iov[i].iov_len, 0);
+        if (r > 0) {
+            ret += r;
+        } else if (!r) {
+            break;
+        } else if (errno == EINTR) {
+            continue;
+        } else {
+            /* else it is some "other" error,
+             * only return if there was no data processed. */
+            if (ret == 0) {
+                return -1;
+            }
+            break;
+        }
+    }
+    return count;
+#endif
+}
+
+ssize_t iov_send_recv(int sockfd, struct iovec *iov, unsigned iov_cnt,
+                      size_t offset, size_t bytes,
+                      bool do_send)
+{
+    ssize_t ret;
+    unsigned si, ei;            /* start and end indexes */
+
+    /* Find the start position, skipping `offset' bytes:
+     * first, skip all full-sized vector elements, */
+    for (si = 0; si < iov_cnt && offset >= iov[si].iov_len; ++si) {
+        offset -= iov[si].iov_len;
+    }
+    if (offset) {
+        assert(si < iov_cnt);
+        /* second, skip `offset' bytes from the (now) first element,
+         * undo it on exit */
+        iov[si].iov_base += offset;
+        iov[si].iov_len -= offset;
+    }
+    /* Find the end position skipping `bytes' bytes: */
+    /* first, skip all full-sized elements */
+    for (ei = si; ei < iov_cnt && iov[ei].iov_len <= bytes; ++ei) {
+        bytes -= iov[ei].iov_len;
+    }
+    if (bytes) {
+        /* second, fixup the last element, and remember
+         * the length we've cut from the end of it in `bytes' */
+        size_t tail;
+        assert(ei < iov_cnt);
+        assert(iov[ei].iov_len > bytes);
+        tail = iov[ei].iov_len - bytes;
+        iov[ei].iov_len = bytes;
+        bytes = tail;  /* bytes is now equal to the tail size */
+        ++ei;
+    }
+
+    ret = do_send_recv(sockfd, iov + si, ei - si, do_send);
+
+    /* Undo the changes above */
+    if (offset) {
+        iov[si].iov_base -= offset;
+        iov[si].iov_len += offset;
+    }
+    if (bytes) {
+        iov[ei-1].iov_len += bytes;
+    }
+
+    return ret;
+}
+
+
 void iov_hexdump(const struct iovec *iov, const unsigned int iov_cnt,
                  FILE *fp, const char *prefix, size_t limit)
 {
diff --git a/iov.h b/iov.h
index 9b6a883..381f37a 100644
--- a/iov.h
+++ b/iov.h
@@ -60,7 +60,7 @@ size_t iov_memset(const struct iovec *iov, const unsigned int iov_cnt,
  * `offset' bytes in the beginning of iovec buffer are skipped and
  * next `bytes' bytes are used, which must be within data of iovec.
  *
- *   r = iov_send_recv(sockfd, iov, offset, bytes, true);
+ *   r = iov_send_recv(sockfd, iov, iovcnt, offset, bytes, true);
  *
  * is logically equivalent to
  *
@@ -68,13 +68,16 @@ size_t iov_memset(const struct iovec *iov, const unsigned int iov_cnt,
  *   iov_to_buf(iov, iovcnt, offset, buf, bytes);
  *   r = send(sockfd, buf, bytes, 0);
  *   free(buf);
+ *
+ * For iov_send_recv() _whole_ area being sent or received
+ * should be within the iovec, not only beginning of it.
  */
-ssize_t iov_send_recv(int sockfd, struct iovec *iov,
+ssize_t iov_send_recv(int sockfd, struct iovec *iov, unsigned iov_cnt,
                       size_t offset, size_t bytes, bool do_send);
-#define iov_recv(sockfd, iov, offset, bytes) \
-  iov_send_recv(sockfd, iov, offset, bytes, false)
-#define iov_send(sockfd, iov, offset, bytes) \
-  iov_send_recv(sockfd, iov, offset, bytes, true)
+#define iov_recv(sockfd, iov, iov_cnt, offset, bytes) \
+  iov_send_recv(sockfd, iov, iov_cnt, offset, bytes, false)
+#define iov_send(sockfd, iov, iov_cnt, offset, bytes) \
+  iov_send_recv(sockfd, iov, iov_cnt, offset, bytes, true)
 
 /**
  * Produce a text hexdump of iovec `iov' with `iov_cnt' number of elements
diff --git a/qemu-coroutine-io.c b/qemu-coroutine-io.c
index 6693c78..5734965 100644
--- a/qemu-coroutine-io.c
+++ b/qemu-coroutine-io.c
@@ -34,7 +34,7 @@ qemu_co_sendv_recvv(int sockfd, struct iovec *iov, unsigned iov_cnt,
     size_t done = 0;
     ssize_t ret;
     while (done < bytes) {
-        ret = iov_send_recv(sockfd, iov,
+        ret = iov_send_recv(sockfd, iov, iov_cnt,
                             offset + done, bytes - done, do_send);
         if (ret > 0) {
             done += ret;
diff --git a/tests/test-iov.c b/tests/test-iov.c
index 5f82296..cbe7a89 100644
--- a/tests/test-iov.c
+++ b/tests/test-iov.c
@@ -1,6 +1,7 @@
 #include <glib.h>
 #include "qemu-common.h"
 #include "iov.h"
+#include "qemu_socket.h"
 
 /* create a randomly-sized iovec with random vectors */
 static void iov_random(struct iovec **iovp, unsigned *iov_cntp)
@@ -144,10 +145,116 @@ static void test_to_from_buf(void)
     }
 }
 
+static void test_io(void)
+{
+#ifndef _WIN32
+/* socketpair(PF_UNIX) which does not exist on windows */
+
+    int sv[2];
+    int r;
+    unsigned i, j, k, s, t;
+    fd_set fds;
+    unsigned niov;
+    struct iovec *iov, *siov;
+    unsigned char *buf;
+    size_t sz;
+
+    iov_random(&iov, &niov);
+    sz = iov_size(iov, niov);
+    buf = g_malloc(sz);
+    for (i = 0; i < sz; ++i) {
+        buf[i] = i & 255;
+    }
+    iov_from_buf(iov, niov, 0, buf, sz);
+
+    siov = g_malloc(sizeof(*iov) * niov);
+    memcpy(siov, iov, sizeof(*iov) * niov);
+
+    if (socketpair(PF_UNIX, SOCK_STREAM, 0, sv) < 0) {
+       perror("socketpair");
+       exit(1);
+    }
+
+    FD_ZERO(&fds);
+
+    t = 0;
+    if (fork() == 0) {
+       /* writer */
+
+       close(sv[0]);
+       FD_SET(sv[1], &fds);
+       fcntl(sv[1], F_SETFL, O_RDWR|O_NONBLOCK);
+       r = g_test_rand_int_range(sz / 2, sz);
+       setsockopt(sv[1], SOL_SOCKET, SO_SNDBUF, &r, sizeof(r));
+
+       for (i = 0; i <= sz; ++i) {
+           for (j = i; j <= sz; ++j) {
+               k = i;
+               do {
+                   s = g_test_rand_int_range(0, j - k + 1);
+                   r = iov_send(sv[1], iov, niov, k, s);
+                   g_assert(memcmp(iov, siov, sizeof(*iov)*niov) == 0);
+                   if (r >= 0) {
+                       k += r;
+                       t += r;
+                       usleep(g_test_rand_int_range(0, 30));
+                   } else if (errno == EAGAIN) {
+                       select(sv[1]+1, NULL, &fds, NULL, NULL);
+                       continue;
+                   } else {
+                       perror("send");
+                       exit(1);
+                   }
+               } while(k < j);
+           }
+       }
+       exit(0);
+
+    } else {
+       /* reader & verifier */
+
+       close(sv[1]);
+       FD_SET(sv[0], &fds);
+       fcntl(sv[0], F_SETFL, O_RDWR|O_NONBLOCK);
+       r = g_test_rand_int_range(sz / 2, sz);
+       setsockopt(sv[0], SOL_SOCKET, SO_RCVBUF, &r, sizeof(r));
+       usleep(500000);
+
+       for (i = 0; i <= sz; ++i) {
+           for (j = i; j <= sz; ++j) {
+               k = i;
+               iov_memset(iov, niov, 0, 0xff, -1);
+               do {
+                   s = g_test_rand_int_range(0, j - k + 1);
+                   r = iov_recv(sv[0], iov, niov, k, s);
+                   g_assert(memcmp(iov, siov, sizeof(*iov)*niov) == 0);
+                   if (r > 0) {
+                       k += r;
+                       t += r;
+                   } else if (!r) {
+                       if (s) {
+                           break;
+                       }
+                   } else if (errno == EAGAIN) {
+                       select(sv[0]+1, &fds, NULL, NULL, NULL);
+                       continue;
+                   } else {
+                       perror("recv");
+                       exit(1);
+                   }
+               } while(k < j);
+               test_iov_bytes(iov, niov, i, j - i);
+           }
+        }
+     }
+#endif
+}
+
 int main(int argc, char **argv)
 {
     g_test_init(&argc, &argv, NULL);
     g_test_rand_int();
     g_test_add_func("/basic/iov/from-to-buf", test_to_from_buf);
+    g_test_add_func("/basic/iov/io", test_io);
     return g_test_run();
 }
commit 2fc8ae1dd77fbc55146b602f703add6dc314dea4
Author: Michael Tokarev <mjt at tls.msk.ru>
Date:   Thu Jun 7 20:22:46 2012 +0400

    cleanup qemu_co_sendv(), qemu_co_recvv() and friends
    
    The same as for non-coroutine versions in previous
    patches: rename arguments to be more obvious, change
    type of arguments from int to size_t where appropriate,
    and use common code for send and receive paths (with
    one extra argument) since these are exactly the same.
    Use common iov_send_recv() directly.
    
    qemu_co_sendv(), qemu_co_recvv(), and qemu_co_recv()
    are now trivial #define's merely adding one extra arg.
    
    qemu_co_sendv() and qemu_co_recvv() callers are
    converted to different argument order and extra
    `iov_cnt' argument.
    
    Signed-off-by: Michael Tokarev <mjt at tls.msk.ru>

diff --git a/block/nbd.c b/block/nbd.c
index 1212614..2bce47b 100644
--- a/block/nbd.c
+++ b/block/nbd.c
@@ -196,7 +196,7 @@ static void nbd_restart_write(void *opaque)
 }
 
 static int nbd_co_send_request(BDRVNBDState *s, struct nbd_request *request,
-                               struct iovec *iov, int offset)
+                               QEMUIOVector *qiov, int offset)
 {
     int rc, ret;
 
@@ -205,8 +205,9 @@ static int nbd_co_send_request(BDRVNBDState *s, struct nbd_request *request,
     qemu_aio_set_fd_handler(s->sock, nbd_reply_ready, nbd_restart_write,
                             nbd_have_request, s);
     rc = nbd_send_request(s->sock, request);
-    if (rc >= 0 && iov) {
-        ret = qemu_co_sendv(s->sock, iov, request->len, offset);
+    if (rc >= 0 && qiov) {
+        ret = qemu_co_sendv(s->sock, qiov->iov, qiov->niov,
+                            offset, request->len);
         if (ret != request->len) {
             return -EIO;
         }
@@ -220,7 +221,7 @@ static int nbd_co_send_request(BDRVNBDState *s, struct nbd_request *request,
 
 static void nbd_co_receive_reply(BDRVNBDState *s, struct nbd_request *request,
                                  struct nbd_reply *reply,
-                                 struct iovec *iov, int offset)
+                                 QEMUIOVector *qiov, int offset)
 {
     int ret;
 
@@ -231,8 +232,9 @@ static void nbd_co_receive_reply(BDRVNBDState *s, struct nbd_request *request,
     if (reply->handle != request->handle) {
         reply->error = EIO;
     } else {
-        if (iov && reply->error == 0) {
-            ret = qemu_co_recvv(s->sock, iov, request->len, offset);
+        if (qiov && reply->error == 0) {
+            ret = qemu_co_recvv(s->sock, qiov->iov, qiov->niov,
+                                offset, request->len);
             if (ret != request->len) {
                 reply->error = EIO;
             }
@@ -349,7 +351,7 @@ static int nbd_co_readv_1(BlockDriverState *bs, int64_t sector_num,
     if (ret < 0) {
         reply.error = -ret;
     } else {
-        nbd_co_receive_reply(s, &request, &reply, qiov->iov, offset);
+        nbd_co_receive_reply(s, &request, &reply, qiov, offset);
     }
     nbd_coroutine_end(s, &request);
     return -reply.error;
@@ -374,7 +376,7 @@ static int nbd_co_writev_1(BlockDriverState *bs, int64_t sector_num,
     request.len = nb_sectors * 512;
 
     nbd_coroutine_start(s, &request);
-    ret = nbd_co_send_request(s, &request, qiov->iov, offset);
+    ret = nbd_co_send_request(s, &request, qiov, offset);
     if (ret < 0) {
         reply.error = -ret;
     } else {
diff --git a/block/sheepdog.c b/block/sheepdog.c
index f46ca8f..2c7aece 100644
--- a/block/sheepdog.c
+++ b/block/sheepdog.c
@@ -719,8 +719,8 @@ static void coroutine_fn aio_read_response(void *opaque)
         }
         break;
     case AIOCB_READ_UDATA:
-        ret = qemu_co_recvv(fd, acb->qiov->iov, rsp.data_length,
-                            aio_req->iov_offset);
+        ret = qemu_co_recvv(fd, acb->qiov->iov, acb->qiov->niov,
+                            aio_req->iov_offset, rsp.data_length);
         if (ret < 0) {
             error_report("failed to get the data, %s", strerror(errno));
             goto out;
@@ -992,7 +992,7 @@ static int coroutine_fn add_aio_request(BDRVSheepdogState *s, AIOReq *aio_req,
     }
 
     if (wlen) {
-        ret = qemu_co_sendv(s->fd, iov, wlen, aio_req->iov_offset);
+        ret = qemu_co_sendv(s->fd, iov, niov, aio_req->iov_offset, wlen);
         if (ret < 0) {
             qemu_co_mutex_unlock(&s->lock);
             error_report("failed to send a data, %s", strerror(errno));
diff --git a/qemu-common.h b/qemu-common.h
index 41b8ae7..7139577 100644
--- a/qemu-common.h
+++ b/qemu-common.h
@@ -300,32 +300,29 @@ struct qemu_work_item {
 void qemu_init_vcpu(void *env);
 #endif
 
-/**
- * Sends an iovec (or optionally a part of it) down a socket, yielding
- * when the socket is full.
- */
-int qemu_co_sendv(int sockfd, struct iovec *iov,
-                  int len, int iov_offset);
 
 /**
- * Receives data into an iovec (or optionally into a part of it) from
- * a socket, yielding when there is no data in the socket.
+ * Sends a (part of) iovec down a socket, yielding when the socket is full, or
+ * Receives data into a (part of) iovec from a socket,
+ * yielding when there is no data in the socket.
+ * The same interface as qemu_sendv_recvv(), with added yielding.
+ * XXX should mark these as coroutine_fn
  */
-int qemu_co_recvv(int sockfd, struct iovec *iov,
-                  int len, int iov_offset);
-
+ssize_t qemu_co_sendv_recvv(int sockfd, struct iovec *iov, unsigned iov_cnt,
+                            size_t offset, size_t bytes, bool do_send);
+#define qemu_co_recvv(sockfd, iov, iov_cnt, offset, bytes) \
+  qemu_co_sendv_recvv(sockfd, iov, iov_cnt, offset, bytes, false)
+#define qemu_co_sendv(sockfd, iov, iov_cnt, offset, bytes) \
+  qemu_co_sendv_recvv(sockfd, iov, iov_cnt, offset, bytes, true)
 
 /**
- * Sends a buffer down a socket, yielding when the socket is full.
+ * The same as above, but with just a single buffer
  */
-int qemu_co_send(int sockfd, void *buf, int len);
-
-/**
- * Receives data into a buffer from a socket, yielding when there
- * is no data in the socket.
- */
-int qemu_co_recv(int sockfd, void *buf, int len);
-
+ssize_t qemu_co_send_recv(int sockfd, void *buf, size_t bytes, bool do_send);
+#define qemu_co_recv(sockfd, buf, bytes) \
+  qemu_co_send_recv(sockfd, buf, bytes, false)
+#define qemu_co_send(sockfd, buf, bytes) \
+  qemu_co_send_recv(sockfd, buf, bytes, true)
 
 typedef struct QEMUIOVector {
     struct iovec *iov;
diff --git a/qemu-coroutine-io.c b/qemu-coroutine-io.c
index 0461a9a..6693c78 100644
--- a/qemu-coroutine-io.c
+++ b/qemu-coroutine-io.c
@@ -27,71 +27,39 @@
 #include "qemu-coroutine.h"
 #include "iov.h"
 
-int coroutine_fn qemu_co_recvv(int sockfd, struct iovec *iov,
-                               int len, int iov_offset)
+ssize_t coroutine_fn
+qemu_co_sendv_recvv(int sockfd, struct iovec *iov, unsigned iov_cnt,
+                    size_t offset, size_t bytes, bool do_send)
 {
-    int total = 0;
-    int ret;
-    while (len) {
-        ret = iov_recv(sockfd, iov, iov_offset + total, len);
-        if (ret < 0) {
+    size_t done = 0;
+    ssize_t ret;
+    while (done < bytes) {
+        ret = iov_send_recv(sockfd, iov,
+                            offset + done, bytes - done, do_send);
+        if (ret > 0) {
+            done += ret;
+        } else if (ret < 0) {
             if (errno == EAGAIN) {
                 qemu_coroutine_yield();
-                continue;
-            }
-            if (total == 0) {
-                total = -1;
-            }
-            break;
-        }
-        if (ret == 0) {
-            break;
-        }
-        total += ret, len -= ret;
-    }
-
-    return total;
-}
-
-int coroutine_fn qemu_co_sendv(int sockfd, struct iovec *iov,
-                               int len, int iov_offset)
-{
-    int total = 0;
-    int ret;
-    while (len) {
-        ret = iov_send(sockfd, iov, iov_offset + total, len);
-        if (ret < 0) {
-            if (errno == EAGAIN) {
-                qemu_coroutine_yield();
-                continue;
-            }
-            if (total == 0) {
-                total = -1;
+            } else if (done == 0) {
+                return -1;
+            } else {
+                break;
             }
+        } else if (ret == 0 && !do_send) {
+            /* write (send) should never return 0.
+             * read (recv) returns 0 for end-of-file (-data).
+             * In both cases there's little point retrying,
+             * but we do for write anyway, just in case */
             break;
         }
-        total += ret, len -= ret;
     }
-
-    return total;
+    return done;
 }
 
-int coroutine_fn qemu_co_recv(int sockfd, void *buf, int len)
+ssize_t coroutine_fn
+qemu_co_send_recv(int sockfd, void *buf, size_t bytes, bool do_send)
 {
-    struct iovec iov;
-
-    iov.iov_base = buf;
-    iov.iov_len = len;
-
-    return qemu_co_recvv(sockfd, &iov, len, 0);
-}
-
-int coroutine_fn qemu_co_send(int sockfd, void *buf, int len)
-{
-    struct iovec iov;
-
-    iov.iov_base = buf;
-    iov.iov_len = len;
-
-    return qemu_co_sendv(sockfd, &iov, len, 0);
+    struct iovec iov = { .iov_base = buf, .iov_len = bytes };
+    return qemu_co_sendv_recvv(sockfd, &iov, 1, 0, bytes, do_send);
 }
commit e3e87df4c94319b15017f958e22761aba03c452a
Author: Michael Tokarev <mjt at tls.msk.ru>
Date:   Wed Mar 14 10:56:04 2012 +0400

    export iov_send_recv() and use it in iov_send() and iov_recv()
    
    Rename do_sendv_recvv() to iov_send_recv(), change its last arg
    (do_send) from int to bool, export it in iov.h, and made the two
    callers of it (iov_send() and iov_recv()) to be trivial #defines
    just adding 5th arg.
    
    iov_send_recv() will be used later.
    
    Signed-off-by: Michael Tokarev <mjt at tls.msk.ru>

diff --git a/cutils.c b/cutils.c
index 2ad5fa3..cb6f638 100644
--- a/cutils.c
+++ b/cutils.c
@@ -376,9 +376,9 @@ int qemu_parse_fd(const char *param)
     return fd;
 }
 
-static ssize_t do_sendv_recvv(int sockfd, struct iovec *iov,
-                          size_t offset, size_t bytes,
-                          int do_sendv)
+ssize_t iov_send_recv(int sockfd, struct iovec *iov,
+                      size_t offset, size_t bytes,
+                      bool do_sendv)
 {
     int iovlen;
     ssize_t ret;
@@ -458,14 +458,3 @@ static ssize_t do_sendv_recvv(int sockfd, struct iovec *iov,
     last_iov->iov_len += diff;
     return ret;
 }
-
-ssize_t iov_recv(int sockfd, struct iovec *iov, size_t offset, size_t bytes)
-{
-    return do_sendv_recvv(sockfd, iov, offset, bytes, 0);
-}
-
-ssize_t iov_send(int sockfd, struct iovec *iov, size_t offset, size_t bytes)
-{
-    return do_sendv_recvv(sockfd, iov, offset, bytes, 1);
-}
-
diff --git a/iov.h b/iov.h
index 5aa2f45..9b6a883 100644
--- a/iov.h
+++ b/iov.h
@@ -60,7 +60,7 @@ size_t iov_memset(const struct iovec *iov, const unsigned int iov_cnt,
  * `offset' bytes in the beginning of iovec buffer are skipped and
  * next `bytes' bytes are used, which must be within data of iovec.
  *
- *   r = iov_send(sockfd, iov, offset, bytes);
+ *   r = iov_send_recv(sockfd, iov, offset, bytes, true);
  *
  * is logically equivalent to
  *
@@ -69,8 +69,12 @@ size_t iov_memset(const struct iovec *iov, const unsigned int iov_cnt,
  *   r = send(sockfd, buf, bytes, 0);
  *   free(buf);
  */
-ssize_t iov_recv(int sockfd, struct iovec *iov, size_t offset, size_t bytes);
-ssize_t iov_send(int sockfd, struct iovec *iov, size_t offset, size_t bytes);
+ssize_t iov_send_recv(int sockfd, struct iovec *iov,
+                      size_t offset, size_t bytes, bool do_send);
+#define iov_recv(sockfd, iov, offset, bytes) \
+  iov_send_recv(sockfd, iov, offset, bytes, false)
+#define iov_send(sockfd, iov, offset, bytes) \
+  iov_send_recv(sockfd, iov, offset, bytes, true)
 
 /**
  * Produce a text hexdump of iovec `iov' with `iov_cnt' number of elements
commit 3e80bf9351f8fec9085c46df6da075efd5e71003
Author: Michael Tokarev <mjt at tls.msk.ru>
Date:   Sat Mar 10 17:00:41 2012 +0400

    rename qemu_sendv to iov_send, change proto and move declarations to iov.h
    
    Rename arguments and use size_t for sizes instead of int,
    from
     int
     qemu_sendv(int sockfd, struct iovec *iov,
                int len, int iov_offset)
    to
     ssize_t
     iov_send(int sockfd, struct iovec *iov,
              size_t offset, size_t bytes)
    
    The main motivation was to make it clear that length
    and offset are in _bytes_, not in iov elements: it was
    very confusing before, because all standard functions
    which deals with iovecs expects number of iovs, not
    bytes, even the fact that struct iovec has iov_len and
    iov_ prefix does not help.  With "bytes" and "offset",
    especially since they're now size_t, it is much more
    explicit.  Also change the return type to be ssize_t
    instead of int.
    
    This also changes it to match other iov-related functons,
    but not _quite_: there's still no argument indicating
    where iovec ends, ie, no iov_cnt parameter as used
    in iov_size() and friends.  If will be added in subsequent
    patch/rewrite.
    
    All callers of qemu_sendv() and qemu_recvv() and
    related, like qemu_co_sendv() and qemu_co_recvv(),
    were checked to verify that it is safe to use unsigned
    datatype instead of int.
    
    Note that the order of arguments is changed to: offset
    and bytes (len and iov_offset) are swapped with each
    other.  This is to make them consistent with very similar
    functions from qemu_iovec family, where offset always
    follows qiov, to mean the place in it to start from.
    
    Signed-off-by: Michael Tokarev <mjt at tls.msk.ru>

diff --git a/cutils.c b/cutils.c
index 352bc52..2ad5fa3 100644
--- a/cutils.c
+++ b/cutils.c
@@ -376,43 +376,28 @@ int qemu_parse_fd(const char *param)
     return fd;
 }
 
-/*
- * Send/recv data with iovec buffers
- *
- * This function send/recv data from/to the iovec buffer directly.
- * The first `offset' bytes in the iovec buffer are skipped and next
- * `len' bytes are used.
- *
- * For example,
- *
- *   do_sendv_recvv(sockfd, iov, len, offset, 1);
- *
- * is equal to
- *
- *   char *buf = malloc(size);
- *   iov_to_buf(iov, iovcnt, buf, offset, size);
- *   send(sockfd, buf, size, 0);
- *   free(buf);
- */
-static int do_sendv_recvv(int sockfd, struct iovec *iov, int len, int offset,
+static ssize_t do_sendv_recvv(int sockfd, struct iovec *iov,
+                          size_t offset, size_t bytes,
                           int do_sendv)
 {
-    int ret, diff, iovlen;
+    int iovlen;
+    ssize_t ret;
+    size_t diff;
     struct iovec *last_iov;
 
     /* last_iov is inclusive, so count from one.  */
     iovlen = 1;
     last_iov = iov;
-    len += offset;
+    bytes += offset;
 
-    while (last_iov->iov_len < len) {
-        len -= last_iov->iov_len;
+    while (last_iov->iov_len < bytes) {
+        bytes -= last_iov->iov_len;
 
         last_iov++;
         iovlen++;
     }
 
-    diff = last_iov->iov_len - len;
+    diff = last_iov->iov_len - bytes;
     last_iov->iov_len -= diff;
 
     while (iov->iov_len <= offset) {
@@ -474,13 +459,13 @@ static int do_sendv_recvv(int sockfd, struct iovec *iov, int len, int offset,
     return ret;
 }
 
-int qemu_recvv(int sockfd, struct iovec *iov, int len, int iov_offset)
+ssize_t iov_recv(int sockfd, struct iovec *iov, size_t offset, size_t bytes)
 {
-    return do_sendv_recvv(sockfd, iov, len, iov_offset, 0);
+    return do_sendv_recvv(sockfd, iov, offset, bytes, 0);
 }
 
-int qemu_sendv(int sockfd, struct iovec *iov, int len, int iov_offset)
+ssize_t iov_send(int sockfd, struct iovec *iov, size_t offset, size_t bytes)
 {
-    return do_sendv_recvv(sockfd, iov, len, iov_offset, 1);
+    return do_sendv_recvv(sockfd, iov, offset, bytes, 1);
 }
 
diff --git a/iov.h b/iov.h
index 19ee3b3..5aa2f45 100644
--- a/iov.h
+++ b/iov.h
@@ -54,6 +54,24 @@ size_t iov_to_buf(const struct iovec *iov, const unsigned int iov_cnt,
 size_t iov_memset(const struct iovec *iov, const unsigned int iov_cnt,
                   size_t offset, int fillc, size_t bytes);
 
+/*
+ * Send/recv data from/to iovec buffers directly
+ *
+ * `offset' bytes in the beginning of iovec buffer are skipped and
+ * next `bytes' bytes are used, which must be within data of iovec.
+ *
+ *   r = iov_send(sockfd, iov, offset, bytes);
+ *
+ * is logically equivalent to
+ *
+ *   char *buf = malloc(bytes);
+ *   iov_to_buf(iov, iovcnt, offset, buf, bytes);
+ *   r = send(sockfd, buf, bytes, 0);
+ *   free(buf);
+ */
+ssize_t iov_recv(int sockfd, struct iovec *iov, size_t offset, size_t bytes);
+ssize_t iov_send(int sockfd, struct iovec *iov, size_t offset, size_t bytes);
+
 /**
  * Produce a text hexdump of iovec `iov' with `iov_cnt' number of elements
  * in file `fp', prefixing each line with `prefix' and processing not more
diff --git a/qemu-common.h b/qemu-common.h
index 056e495..41b8ae7 100644
--- a/qemu-common.h
+++ b/qemu-common.h
@@ -205,9 +205,6 @@ int qemu_pipe(int pipefd[2]);
 #define qemu_recv(sockfd, buf, len, flags) recv(sockfd, buf, len, flags)
 #endif
 
-int qemu_recvv(int sockfd, struct iovec *iov, int len, int iov_offset);
-int qemu_sendv(int sockfd, struct iovec *iov, int len, int iov_offset);
-
 /* Error handling.  */
 
 void QEMU_NORETURN hw_error(const char *fmt, ...) GCC_FMT_ATTR(1, 2);
diff --git a/qemu-coroutine-io.c b/qemu-coroutine-io.c
index 40fd514..0461a9a 100644
--- a/qemu-coroutine-io.c
+++ b/qemu-coroutine-io.c
@@ -25,6 +25,7 @@
 #include "qemu-common.h"
 #include "qemu_socket.h"
 #include "qemu-coroutine.h"
+#include "iov.h"
 
 int coroutine_fn qemu_co_recvv(int sockfd, struct iovec *iov,
                                int len, int iov_offset)
@@ -32,7 +33,7 @@ int coroutine_fn qemu_co_recvv(int sockfd, struct iovec *iov,
     int total = 0;
     int ret;
     while (len) {
-        ret = qemu_recvv(sockfd, iov, len, iov_offset + total);
+        ret = iov_recv(sockfd, iov, iov_offset + total, len);
         if (ret < 0) {
             if (errno == EAGAIN) {
                 qemu_coroutine_yield();
@@ -58,7 +59,7 @@ int coroutine_fn qemu_co_sendv(int sockfd, struct iovec *iov,
     int total = 0;
     int ret;
     while (len) {
-        ret = qemu_sendv(sockfd, iov, len, iov_offset + total);
+        ret = iov_send(sockfd, iov, iov_offset + total, len);
         if (ret < 0) {
             if (errno == EAGAIN) {
                 qemu_coroutine_yield();
commit d5e6b1619c516fa1e2ee4d8d20f08fcda4fb67a0
Author: Michael Tokarev <mjt at tls.msk.ru>
Date:   Thu Jun 7 20:21:06 2012 +0400

    change qemu_iovec_to_buf() to match other to,from_buf functions
    
    It now allows specifying offset within qiov to start from and
    amount of bytes to copy.  Actual implementation is just a call
    to iov_to_buf().
    
    Signed-off-by: Michael Tokarev <mjt at tls.msk.ru>

diff --git a/block.c b/block.c
index 5b1a862..63b7ae0 100644
--- a/block.c
+++ b/block.c
@@ -3408,7 +3408,7 @@ static BlockDriverAIOCB *bdrv_aio_rw_vector(BlockDriverState *bs,
     acb->bh = qemu_bh_new(bdrv_aio_bh_cb, acb);
 
     if (is_write) {
-        qemu_iovec_to_buffer(acb->qiov, acb->bounce);
+        qemu_iovec_to_buf(acb->qiov, 0, acb->bounce, qiov->size);
         acb->ret = bs->drv->bdrv_write(bs, sector_num, acb->bounce, nb_sectors);
     } else {
         acb->ret = bs->drv->bdrv_read(bs, sector_num, acb->bounce, nb_sectors);
diff --git a/block/iscsi.c b/block/iscsi.c
index 22888a0..ecb7a22 100644
--- a/block/iscsi.c
+++ b/block/iscsi.c
@@ -240,8 +240,7 @@ iscsi_aio_writev(BlockDriverState *bs, int64_t sector_num,
     /* this will allow us to get rid of 'buf' completely */
     size = nb_sectors * BDRV_SECTOR_SIZE;
     acb->buf = g_malloc(size);
-    qemu_iovec_to_buffer(acb->qiov, acb->buf);
-
+    qemu_iovec_to_buf(acb->qiov, 0, acb->buf, size);
 
     acb->task = malloc(sizeof(struct scsi_task));
     if (acb->task == NULL) {
diff --git a/block/qcow.c b/block/qcow.c
index 7280103..7b5ab87 100644
--- a/block/qcow.c
+++ b/block/qcow.c
@@ -569,7 +569,7 @@ static coroutine_fn int qcow_co_writev(BlockDriverState *bs, int64_t sector_num,
 
     if (qiov->niov > 1) {
         buf = orig_buf = qemu_blockalign(bs, qiov->size);
-        qemu_iovec_to_buffer(qiov, buf);
+        qemu_iovec_to_buf(qiov, 0, buf, qiov->size);
     } else {
         orig_buf = NULL;
         buf = (uint8_t *)qiov->iov->iov_base;
diff --git a/block/qcow2.c b/block/qcow2.c
index 8458d10..1b5b36c 100644
--- a/block/qcow2.c
+++ b/block/qcow2.c
@@ -731,7 +731,7 @@ static coroutine_fn int qcow2_co_writev(BlockDriverState *bs,
 
             assert(hd_qiov.size <=
                    QCOW_MAX_CRYPT_CLUSTERS * s->cluster_size);
-            qemu_iovec_to_buffer(&hd_qiov, cluster_data);
+            qemu_iovec_to_buf(&hd_qiov, 0, cluster_data, hd_qiov.size);
 
             qcow2_encrypt_sectors(s, sector_num, cluster_data,
                 cluster_data, cur_nr_sectors, 1, &s->aes_encrypt_key);
diff --git a/block/rbd.c b/block/rbd.c
index 8bb3252..49a4787 100644
--- a/block/rbd.c
+++ b/block/rbd.c
@@ -674,7 +674,7 @@ static BlockDriverAIOCB *rbd_start_aio(BlockDriverState *bs,
     acb->bh = NULL;
 
     if (cmd == RBD_AIO_WRITE) {
-        qemu_iovec_to_buffer(acb->qiov, acb->bounce);
+        qemu_iovec_to_buf(acb->qiov, 0, acb->bounce, qiov->size);
     }
 
     buf = acb->bounce;
diff --git a/cutils.c b/cutils.c
index 1aeac15..352bc52 100644
--- a/cutils.c
+++ b/cutils.c
@@ -220,15 +220,10 @@ void qemu_iovec_reset(QEMUIOVector *qiov)
     qiov->size = 0;
 }
 
-void qemu_iovec_to_buffer(QEMUIOVector *qiov, void *buf)
+size_t qemu_iovec_to_buf(QEMUIOVector *qiov, size_t offset,
+                         void *buf, size_t bytes)
 {
-    uint8_t *p = (uint8_t *)buf;
-    int i;
-
-    for (i = 0; i < qiov->niov; ++i) {
-        memcpy(p, qiov->iov[i].iov_base, qiov->iov[i].iov_len);
-        p += qiov->iov[i].iov_len;
-    }
+    return iov_to_buf(qiov->iov, qiov->niov, offset, buf, bytes);
 }
 
 size_t qemu_iovec_from_buf(QEMUIOVector *qiov, size_t offset,
diff --git a/qemu-common.h b/qemu-common.h
index cae7bb6..056e495 100644
--- a/qemu-common.h
+++ b/qemu-common.h
@@ -344,7 +344,8 @@ void qemu_iovec_concat(QEMUIOVector *dst,
                        QEMUIOVector *src, size_t soffset, size_t sbytes);
 void qemu_iovec_destroy(QEMUIOVector *qiov);
 void qemu_iovec_reset(QEMUIOVector *qiov);
-void qemu_iovec_to_buffer(QEMUIOVector *qiov, void *buf);
+size_t qemu_iovec_to_buf(QEMUIOVector *qiov, size_t offset,
+                         void *buf, size_t bytes);
 size_t qemu_iovec_from_buf(QEMUIOVector *qiov, size_t offset,
                            const void *buf, size_t bytes);
 size_t qemu_iovec_memset(QEMUIOVector *qiov, size_t offset,
commit 1b093c480a32051cc856b6ab2395d8cbc3ae99da
Author: Michael Tokarev <mjt at tls.msk.ru>
Date:   Mon Mar 12 21:28:06 2012 +0400

    consolidate qemu_iovec_copy() and qemu_iovec_concat() and make them consistent
    
    qemu_iovec_concat() is currently a wrapper for
    qemu_iovec_copy(), use the former (with extra
    "0" arg) in a few places where it is used.
    
    Change skip argument of qemu_iovec_copy() from
    uint64_t to size_t, since size of qiov itself
    is size_t, so there's no way to skip larger
    sizes.  Rename it to soffset, to make it clear
    that the offset is applied to src.
    
    Also change the only usage of uint64_t in
    hw/9pfs/virtio-9p.c, in v9fs_init_qiov_from_pdu() -
    all callers of it actually uses size_t too,
    not uint64_t.
    
    One added restriction: as for all other iovec-related
    functions, soffset must point inside src.
    
    Order of argumens is already good:
     qemu_iovec_memset(QEMUIOVector *qiov, size_t offset,
                       int c, size_t bytes)
    vs:
     qemu_iovec_concat(QEMUIOVector *dst,
                       QEMUIOVector *src,
                       size_t soffset, size_t sbytes)
    (note soffset is after _src_ not dst, since it applies to src;
    for memset it applies to qiov).
    
    Note that in many places where this function is used,
    the previous call is qemu_iovec_reset(), which means
    many callers actually want copy (replacing dst content),
    not concat.  So we may want to add a wrapper like
    qemu_iovec_copy() with the same arguments but which
    calls qemu_iovec_reset() before _concat().
    
    Signed-off-by: Michael Tokarev <mjt at tls.msk.ru>

diff --git a/block.c b/block.c
index e0ef95e..5b1a862 100644
--- a/block.c
+++ b/block.c
@@ -3101,13 +3101,13 @@ static int multiwrite_merge(BlockDriverState *bs, BlockRequest *reqs,
             // Add the first request to the merged one. If the requests are
             // overlapping, drop the last sectors of the first request.
             size = (reqs[i].sector - reqs[outidx].sector) << 9;
-            qemu_iovec_concat(qiov, reqs[outidx].qiov, size);
+            qemu_iovec_concat(qiov, reqs[outidx].qiov, 0, size);
 
             // We should need to add any zeros between the two requests
             assert (reqs[i].sector <= oldreq_last);
 
             // Add the second request
-            qemu_iovec_concat(qiov, reqs[i].qiov, reqs[i].qiov->size);
+            qemu_iovec_concat(qiov, reqs[i].qiov, 0, reqs[i].qiov->size);
 
             reqs[outidx].nb_sectors = qiov->size >> 9;
             reqs[outidx].qiov = qiov;
diff --git a/block/qcow2.c b/block/qcow2.c
index ccc599b..8458d10 100644
--- a/block/qcow2.c
+++ b/block/qcow2.c
@@ -549,7 +549,7 @@ static coroutine_fn int qcow2_co_readv(BlockDriverState *bs, int64_t sector_num,
         index_in_cluster = sector_num & (s->cluster_sectors - 1);
 
         qemu_iovec_reset(&hd_qiov);
-        qemu_iovec_copy(&hd_qiov, qiov, bytes_done,
+        qemu_iovec_concat(&hd_qiov, qiov, bytes_done,
             cur_nr_sectors * 512);
 
         switch (ret) {
@@ -720,7 +720,7 @@ static coroutine_fn int qcow2_co_writev(BlockDriverState *bs,
         assert((cluster_offset & 511) == 0);
 
         qemu_iovec_reset(&hd_qiov);
-        qemu_iovec_copy(&hd_qiov, qiov, bytes_done,
+        qemu_iovec_concat(&hd_qiov, qiov, bytes_done,
             cur_nr_sectors * 512);
 
         if (s->crypt_method) {
diff --git a/block/qed.c b/block/qed.c
index 40bdb53..847417a 100644
--- a/block/qed.c
+++ b/block/qed.c
@@ -1131,7 +1131,7 @@ static void qed_aio_write_alloc(QEDAIOCB *acb, size_t len)
 
     acb->cur_nclusters = qed_bytes_to_clusters(s,
             qed_offset_into_cluster(s, acb->cur_pos) + len);
-    qemu_iovec_copy(&acb->cur_qiov, acb->qiov, acb->qiov_offset, len);
+    qemu_iovec_concat(&acb->cur_qiov, acb->qiov, acb->qiov_offset, len);
 
     if (acb->flags & QED_AIOCB_ZERO) {
         /* Skip ahead if the clusters are already zero */
@@ -1177,7 +1177,7 @@ static void qed_aio_write_inplace(QEDAIOCB *acb, uint64_t offset, size_t len)
 
     /* Calculate the I/O vector */
     acb->cur_cluster = offset;
-    qemu_iovec_copy(&acb->cur_qiov, acb->qiov, acb->qiov_offset, len);
+    qemu_iovec_concat(&acb->cur_qiov, acb->qiov, acb->qiov_offset, len);
 
     /* Do the actual write */
     qed_aio_write_main(acb, 0);
@@ -1247,7 +1247,7 @@ static void qed_aio_read_data(void *opaque, int ret,
         goto err;
     }
 
-    qemu_iovec_copy(&acb->cur_qiov, acb->qiov, acb->qiov_offset, len);
+    qemu_iovec_concat(&acb->cur_qiov, acb->qiov, acb->qiov_offset, len);
 
     /* Handle zero cluster and backing file reads */
     if (ret == QED_CLUSTER_ZERO) {
diff --git a/cutils.c b/cutils.c
index b4dd844..1aeac15 100644
--- a/cutils.c
+++ b/cutils.c
@@ -172,48 +172,34 @@ void qemu_iovec_add(QEMUIOVector *qiov, void *base, size_t len)
 }
 
 /*
- * Copies iovecs from src to the end of dst. It starts copying after skipping
- * the given number of bytes in src and copies until src is completely copied
- * or the total size of the copied iovec reaches size.The size of the last
- * copied iovec is changed in order to fit the specified total size if it isn't
- * a perfect fit already.
+ * Concatenates (partial) iovecs from src to the end of dst.
+ * It starts copying after skipping `soffset' bytes at the
+ * beginning of src and adds individual vectors from src to
+ * dst copies up to `sbytes' bytes total, or up to the end
+ * of src if it comes first.  This way, it is okay to specify
+ * very large value for `sbytes' to indicate "up to the end
+ * of src".
+ * Only vector pointers are processed, not the actual data buffers.
  */
-void qemu_iovec_copy(QEMUIOVector *dst, QEMUIOVector *src, uint64_t skip,
-    size_t size)
+void qemu_iovec_concat(QEMUIOVector *dst,
+                       QEMUIOVector *src, size_t soffset, size_t sbytes)
 {
     int i;
     size_t done;
-    void *iov_base;
-    uint64_t iov_len;
-
+    struct iovec *siov = src->iov;
     assert(dst->nalloc != -1);
-
-    done = 0;
-    for (i = 0; (i < src->niov) && (done != size); i++) {
-        if (skip >= src->iov[i].iov_len) {
-            /* Skip the whole iov */
-            skip -= src->iov[i].iov_len;
-            continue;
+    assert(src->size >= soffset);
+    for (i = 0, done = 0; done < sbytes && i < src->niov; i++) {
+        if (soffset < siov[i].iov_len) {
+            size_t len = MIN(siov[i].iov_len - soffset, sbytes - done);
+            qemu_iovec_add(dst, siov[i].iov_base + soffset, len);
+            done += len;
+            soffset = 0;
         } else {
-            /* Skip only part (or nothing) of the iov */
-            iov_base = (uint8_t*) src->iov[i].iov_base + skip;
-            iov_len = src->iov[i].iov_len - skip;
-            skip = 0;
+            soffset -= siov[i].iov_len;
         }
-
-        if (done + iov_len > size) {
-            qemu_iovec_add(dst, iov_base, size - done);
-            break;
-        } else {
-            qemu_iovec_add(dst, iov_base, iov_len);
-        }
-        done += iov_len;
     }
-}
-
-void qemu_iovec_concat(QEMUIOVector *dst, QEMUIOVector *src, size_t size)
-{
-    qemu_iovec_copy(dst, src, 0, size);
+    /* return done; */
 }
 
 void qemu_iovec_destroy(QEMUIOVector *qiov)
diff --git a/hw/9pfs/virtio-9p.c b/hw/9pfs/virtio-9p.c
index c633fb9..f4a7026 100644
--- a/hw/9pfs/virtio-9p.c
+++ b/hw/9pfs/virtio-9p.c
@@ -1648,7 +1648,7 @@ out:
  * with qemu_iovec_destroy().
  */
 static void v9fs_init_qiov_from_pdu(QEMUIOVector *qiov, V9fsPDU *pdu,
-                                    uint64_t skip, size_t size,
+                                    size_t skip, size_t size,
                                     bool is_write)
 {
     QEMUIOVector elem;
@@ -1665,7 +1665,7 @@ static void v9fs_init_qiov_from_pdu(QEMUIOVector *qiov, V9fsPDU *pdu,
 
     qemu_iovec_init_external(&elem, iov, niov);
     qemu_iovec_init(qiov, niov);
-    qemu_iovec_copy(qiov, &elem, skip, size);
+    qemu_iovec_concat(qiov, &elem, skip, size);
 }
 
 static void v9fs_read(void *opaque)
@@ -1715,7 +1715,7 @@ static void v9fs_read(void *opaque)
         qemu_iovec_init(&qiov, qiov_full.niov);
         do {
             qemu_iovec_reset(&qiov);
-            qemu_iovec_copy(&qiov, &qiov_full, count, qiov_full.size - count);
+            qemu_iovec_concat(&qiov, &qiov_full, count, qiov_full.size - count);
             if (0) {
                 print_sg(qiov.iov, qiov.niov);
             }
@@ -1970,7 +1970,7 @@ static void v9fs_write(void *opaque)
     qemu_iovec_init(&qiov, qiov_full.niov);
     do {
         qemu_iovec_reset(&qiov);
-        qemu_iovec_copy(&qiov, &qiov_full, total, qiov_full.size - total);
+        qemu_iovec_concat(&qiov, &qiov_full, total, qiov_full.size - total);
         if (0) {
             print_sg(qiov.iov, qiov.niov);
         }
diff --git a/qemu-common.h b/qemu-common.h
index 430ec15..cae7bb6 100644
--- a/qemu-common.h
+++ b/qemu-common.h
@@ -340,9 +340,8 @@ typedef struct QEMUIOVector {
 void qemu_iovec_init(QEMUIOVector *qiov, int alloc_hint);
 void qemu_iovec_init_external(QEMUIOVector *qiov, struct iovec *iov, int niov);
 void qemu_iovec_add(QEMUIOVector *qiov, void *base, size_t len);
-void qemu_iovec_copy(QEMUIOVector *dst, QEMUIOVector *src, uint64_t skip,
-    size_t size);
-void qemu_iovec_concat(QEMUIOVector *dst, QEMUIOVector *src, size_t size);
+void qemu_iovec_concat(QEMUIOVector *dst,
+                       QEMUIOVector *src, size_t soffset, size_t sbytes);
 void qemu_iovec_destroy(QEMUIOVector *qiov);
 void qemu_iovec_reset(QEMUIOVector *qiov);
 void qemu_iovec_to_buffer(QEMUIOVector *qiov, void *buf);
commit 03396148bca54c0e81ad8eecb12a136456d14c16
Author: Michael Tokarev <mjt at tls.msk.ru>
Date:   Thu Jun 7 20:17:55 2012 +0400

    allow qemu_iovec_from_buffer() to specify offset from which to start copying
    
    Similar to
     qemu_iovec_memset(QEMUIOVector *qiov, size_t offset,
                       int c, size_t bytes);
    the new prototype is:
     qemu_iovec_from_buf(QEMUIOVector *qiov, size_t offset,
                         const void *buf, size_t bytes);
    
    The processing starts at offset bytes within qiov.
    
    This way, we may copy a bounce buffer directly to
    a middle of qiov.
    
    This is exactly the same function as iov_from_buf() from
    iov.c, so use the existing implementation and rename it
    to qemu_iovec_from_buf() to be shorter and to match the
    utility function.
    
    As with utility implementation, we now assert that the
    offset is inside actual iovec.  Nothing changed for
    current callers, because `offset' parameter is new.
    
    While at it, stop using "bounce-qiov" in block/qcow2.c
    and copy decrypted data directly from cluster_data
    instead of recreating a temp qiov for doing that.
    
    Signed-off-by: Michael Tokarev <mjt at tls.msk.ru>

diff --git a/block.c b/block.c
index 7547051..e0ef95e 100644
--- a/block.c
+++ b/block.c
@@ -1821,8 +1821,8 @@ static int coroutine_fn bdrv_co_do_copy_on_readv(BlockDriverState *bs,
     }
 
     skip_bytes = (sector_num - cluster_sector_num) * BDRV_SECTOR_SIZE;
-    qemu_iovec_from_buffer(qiov, bounce_buffer + skip_bytes,
-                           nb_sectors * BDRV_SECTOR_SIZE);
+    qemu_iovec_from_buf(qiov, 0, bounce_buffer + skip_bytes,
+                        nb_sectors * BDRV_SECTOR_SIZE);
 
 err:
     qemu_vfree(bounce_buffer);
@@ -3382,7 +3382,7 @@ static void bdrv_aio_bh_cb(void *opaque)
     BlockDriverAIOCBSync *acb = opaque;
 
     if (!acb->is_write)
-        qemu_iovec_from_buffer(acb->qiov, acb->bounce, acb->qiov->size);
+        qemu_iovec_from_buf(acb->qiov, 0, acb->bounce, acb->qiov->size);
     qemu_vfree(acb->bounce);
     acb->common.cb(acb->common.opaque, acb->ret);
     qemu_bh_delete(acb->bh);
diff --git a/block/curl.c b/block/curl.c
index bf3680b..e7c3634 100644
--- a/block/curl.c
+++ b/block/curl.c
@@ -140,8 +140,8 @@ static size_t curl_read_cb(void *ptr, size_t size, size_t nmemb, void *opaque)
             continue;
 
         if ((s->buf_off >= acb->end)) {
-            qemu_iovec_from_buffer(acb->qiov, s->orig_buf + acb->start,
-                                   acb->end - acb->start);
+            qemu_iovec_from_buf(acb->qiov, 0, s->orig_buf + acb->start,
+                                acb->end - acb->start);
             acb->common.cb(acb->common.opaque, 0);
             qemu_aio_release(acb);
             s->acb[i] = NULL;
@@ -176,7 +176,7 @@ static int curl_find_buf(BDRVCURLState *s, size_t start, size_t len,
         {
             char *buf = state->orig_buf + (start - state->buf_start);
 
-            qemu_iovec_from_buffer(acb->qiov, buf, len);
+            qemu_iovec_from_buf(acb->qiov, 0, buf, len);
             acb->common.cb(acb->common.opaque, 0);
 
             return FIND_RET_OK;
diff --git a/block/qcow.c b/block/qcow.c
index 35dff49..7280103 100644
--- a/block/qcow.c
+++ b/block/qcow.c
@@ -540,7 +540,7 @@ done:
     qemu_co_mutex_unlock(&s->lock);
 
     if (qiov->niov > 1) {
-        qemu_iovec_from_buffer(qiov, orig_buf, qiov->size);
+        qemu_iovec_from_buf(qiov, 0, orig_buf, qiov->size);
         qemu_vfree(orig_buf);
     }
 
diff --git a/block/qcow2.c b/block/qcow2.c
index fcbf952..ccc599b 100644
--- a/block/qcow2.c
+++ b/block/qcow2.c
@@ -590,7 +590,7 @@ static coroutine_fn int qcow2_co_readv(BlockDriverState *bs, int64_t sector_num,
                 goto fail;
             }
 
-            qemu_iovec_from_buffer(&hd_qiov,
+            qemu_iovec_from_buf(&hd_qiov, 0,
                 s->cluster_cache + index_in_cluster * 512,
                 512 * cur_nr_sectors);
             break;
@@ -630,11 +630,8 @@ static coroutine_fn int qcow2_co_readv(BlockDriverState *bs, int64_t sector_num,
             if (s->crypt_method) {
                 qcow2_encrypt_sectors(s, sector_num,  cluster_data,
                     cluster_data, cur_nr_sectors, 0, &s->aes_decrypt_key);
-                qemu_iovec_reset(&hd_qiov);
-                qemu_iovec_copy(&hd_qiov, qiov, bytes_done,
-                    cur_nr_sectors * 512);
-                qemu_iovec_from_buffer(&hd_qiov, cluster_data,
-                    512 * cur_nr_sectors);
+                qemu_iovec_from_buf(qiov, bytes_done,
+                    cluster_data, 512 * cur_nr_sectors);
             }
             break;
 
diff --git a/block/rbd.c b/block/rbd.c
index 1280d66..8bb3252 100644
--- a/block/rbd.c
+++ b/block/rbd.c
@@ -620,7 +620,7 @@ static void rbd_aio_bh_cb(void *opaque)
     RBDAIOCB *acb = opaque;
 
     if (acb->cmd == RBD_AIO_READ) {
-        qemu_iovec_from_buffer(acb->qiov, acb->bounce, acb->qiov->size);
+        qemu_iovec_from_buf(acb->qiov, 0, acb->bounce, acb->qiov->size);
     }
     qemu_vfree(acb->bounce);
     acb->common.cb(acb->common.opaque, (acb->ret > 0 ? 0 : acb->ret));
diff --git a/cutils.c b/cutils.c
index 0ddf4c7..b4dd844 100644
--- a/cutils.c
+++ b/cutils.c
@@ -245,20 +245,10 @@ void qemu_iovec_to_buffer(QEMUIOVector *qiov, void *buf)
     }
 }
 
-void qemu_iovec_from_buffer(QEMUIOVector *qiov, const void *buf, size_t count)
+size_t qemu_iovec_from_buf(QEMUIOVector *qiov, size_t offset,
+                           const void *buf, size_t bytes)
 {
-    const uint8_t *p = (const uint8_t *)buf;
-    size_t copy;
-    int i;
-
-    for (i = 0; i < qiov->niov && count; ++i) {
-        copy = count;
-        if (copy > qiov->iov[i].iov_len)
-            copy = qiov->iov[i].iov_len;
-        memcpy(qiov->iov[i].iov_base, p, copy);
-        p     += copy;
-        count -= copy;
-    }
+    return iov_from_buf(qiov->iov, qiov->niov, offset, buf, bytes);
 }
 
 size_t qemu_iovec_memset(QEMUIOVector *qiov, size_t offset,
diff --git a/qemu-common.h b/qemu-common.h
index e752d2b..430ec15 100644
--- a/qemu-common.h
+++ b/qemu-common.h
@@ -346,7 +346,8 @@ void qemu_iovec_concat(QEMUIOVector *dst, QEMUIOVector *src, size_t size);
 void qemu_iovec_destroy(QEMUIOVector *qiov);
 void qemu_iovec_reset(QEMUIOVector *qiov);
 void qemu_iovec_to_buffer(QEMUIOVector *qiov, void *buf);
-void qemu_iovec_from_buffer(QEMUIOVector *qiov, const void *buf, size_t count);
+size_t qemu_iovec_from_buf(QEMUIOVector *qiov, size_t offset,
+                           const void *buf, size_t bytes);
 size_t qemu_iovec_memset(QEMUIOVector *qiov, size_t offset,
                          int fillc, size_t bytes);
 
commit 3d9b49254f893f2a3739400e536de25db1cdc5f9
Author: Michael Tokarev <mjt at tls.msk.ru>
Date:   Sat Mar 10 16:54:23 2012 +0400

    consolidate qemu_iovec_memset{,_skip}() into single function and use existing iov_memset()
    
    This patch combines two functions into one, and replaces
    the implementation with already existing iov_memset() from
    iov.c.
    
    The new prototype of qemu_iovec_memset():
      size_t qemu_iovec_memset(qiov, size_t offset, int fillc, size_t bytes)
    It is different from former qemu_iovec_memset_skip(), and
    I want to make other functions to be consistent with it
    too: first how much to skip, second what, and 3rd how many
    of it.  It also returns actual number of bytes filled in,
    which may be less than the requested `bytes' if qiov is
    smaller than offset+bytes, in the same way iov_memset()
    does.
    
    While at it, use utility function iov_memset() from
    iov.h in posix-aio-compat.c, where qiov was used.
    
    Signed-off-by: Michael Tokarev <mjt at tls.msk.ru>

diff --git a/Makefile b/Makefile
index 9b7a85e..017836b 100644
--- a/Makefile
+++ b/Makefile
@@ -154,7 +154,8 @@ qemu-img.o: qemu-img-cmds.h
 qemu-img.o qemu-tool.o qemu-nbd.o qemu-io.o cmd.o qemu-ga.o: $(GENERATED_HEADERS)
 
 tools-obj-y = $(oslib-obj-y) $(trace-obj-y) qemu-tool.o qemu-timer.o \
-	qemu-timer-common.o main-loop.o notify.o iohandler.o cutils.o async.o
+	qemu-timer-common.o main-loop.o notify.o \
+	iohandler.o cutils.o iov.o async.o
 tools-obj-$(CONFIG_POSIX) += compatfd.o
 
 qemu-img$(EXESUF): qemu-img.o $(tools-obj-y) $(block-obj-y)
diff --git a/Makefile.objs b/Makefile.objs
index 70c5c79..f173946 100644
--- a/Makefile.objs
+++ b/Makefile.objs
@@ -42,7 +42,7 @@ coroutine-obj-$(CONFIG_WIN32) += coroutine-win32.o
 #######################################################################
 # block-obj-y is code used by both qemu system emulation and qemu-img
 
-block-obj-y = cutils.o cache-utils.o qemu-option.o module.o async.o
+block-obj-y = cutils.o iov.o cache-utils.o qemu-option.o module.o async.o
 block-obj-y += nbd.o block.o aio.o aes.o qemu-config.o qemu-progress.o qemu-sockets.o
 block-obj-y += $(coroutine-obj-y) $(qobject-obj-y) $(version-obj-y)
 block-obj-$(CONFIG_POSIX) += posix-aio-compat.o
@@ -198,7 +198,7 @@ common-obj-$(CONFIG_XEN_BACKEND) += xen_console.o xenfb.o xen_disk.o xen_nic.o
 user-obj-y =
 user-obj-y += envlist.o path.o
 user-obj-y += tcg-runtime.o host-utils.o
-user-obj-y += cutils.o cache-utils.o
+user-obj-y += cutils.o iov.o cache-utils.o
 user-obj-y += module.o
 user-obj-y += qemu-user.o
 user-obj-y += $(trace-obj-y)
diff --git a/block/qcow2.c b/block/qcow2.c
index c2e49cd..fcbf952 100644
--- a/block/qcow2.c
+++ b/block/qcow2.c
@@ -510,7 +510,7 @@ int qcow2_backing_read1(BlockDriverState *bs, QEMUIOVector *qiov,
     else
         n1 = bs->total_sectors - sector_num;
 
-    qemu_iovec_memset_skip(qiov, 0, 512 * (nb_sectors - n1), 512 * n1);
+    qemu_iovec_memset(qiov, 512 * n1, 0, 512 * (nb_sectors - n1));
 
     return n1;
 }
@@ -571,7 +571,7 @@ static coroutine_fn int qcow2_co_readv(BlockDriverState *bs, int64_t sector_num,
                 }
             } else {
                 /* Note: in this case, no need to wait */
-                qemu_iovec_memset(&hd_qiov, 0, 512 * cur_nr_sectors);
+                qemu_iovec_memset(&hd_qiov, 0, 0, 512 * cur_nr_sectors);
             }
             break;
 
@@ -580,7 +580,7 @@ static coroutine_fn int qcow2_co_readv(BlockDriverState *bs, int64_t sector_num,
                 ret = -EIO;
                 goto fail;
             }
-            qemu_iovec_memset(&hd_qiov, 0, 512 * cur_nr_sectors);
+            qemu_iovec_memset(&hd_qiov, 0, 0, 512 * cur_nr_sectors);
             break;
 
         case QCOW2_CLUSTER_COMPRESSED:
diff --git a/block/qed.c b/block/qed.c
index 30a31f9..40bdb53 100644
--- a/block/qed.c
+++ b/block/qed.c
@@ -736,7 +736,7 @@ static void qed_read_backing_file(BDRVQEDState *s, uint64_t pos,
     /* Zero all sectors if reading beyond the end of the backing file */
     if (pos >= backing_length ||
         pos + qiov->size > backing_length) {
-        qemu_iovec_memset(qiov, 0, qiov->size);
+        qemu_iovec_memset(qiov, 0, 0, qiov->size);
     }
 
     /* Complete now if there are no backing file sectors to read */
@@ -1251,7 +1251,7 @@ static void qed_aio_read_data(void *opaque, int ret,
 
     /* Handle zero cluster and backing file reads */
     if (ret == QED_CLUSTER_ZERO) {
-        qemu_iovec_memset(&acb->cur_qiov, 0, acb->cur_qiov.size);
+        qemu_iovec_memset(&acb->cur_qiov, 0, 0, acb->cur_qiov.size);
         qed_aio_next_io(acb, 0);
         return;
     } else if (ret != QED_CLUSTER_FOUND) {
diff --git a/cutils.c b/cutils.c
index af308cd..0ddf4c7 100644
--- a/cutils.c
+++ b/cutils.c
@@ -26,6 +26,7 @@
 #include <math.h>
 
 #include "qemu_socket.h"
+#include "iov.h"
 
 void pstrcpy(char *buf, int buf_size, const char *str)
 {
@@ -260,47 +261,10 @@ void qemu_iovec_from_buffer(QEMUIOVector *qiov, const void *buf, size_t count)
     }
 }
 
-void qemu_iovec_memset(QEMUIOVector *qiov, int c, size_t count)
+size_t qemu_iovec_memset(QEMUIOVector *qiov, size_t offset,
+                         int fillc, size_t bytes)
 {
-    size_t n;
-    int i;
-
-    for (i = 0; i < qiov->niov && count; ++i) {
-        n = MIN(count, qiov->iov[i].iov_len);
-        memset(qiov->iov[i].iov_base, c, n);
-        count -= n;
-    }
-}
-
-void qemu_iovec_memset_skip(QEMUIOVector *qiov, int c, size_t count,
-                            size_t skip)
-{
-    int i;
-    size_t done;
-    void *iov_base;
-    uint64_t iov_len;
-
-    done = 0;
-    for (i = 0; (i < qiov->niov) && (done != count); i++) {
-        if (skip >= qiov->iov[i].iov_len) {
-            /* Skip the whole iov */
-            skip -= qiov->iov[i].iov_len;
-            continue;
-        } else {
-            /* Skip only part (or nothing) of the iov */
-            iov_base = (uint8_t*) qiov->iov[i].iov_base + skip;
-            iov_len = qiov->iov[i].iov_len - skip;
-            skip = 0;
-        }
-
-        if (done + iov_len > count) {
-            memset(iov_base, c, count - done);
-            break;
-        } else {
-            memset(iov_base, c, iov_len);
-        }
-        done += iov_len;
-    }
+    return iov_memset(qiov->iov, qiov->niov, offset, fillc, bytes);
 }
 
 /*
diff --git a/linux-aio.c b/linux-aio.c
index fa0fbf3..ce9b5d4 100644
--- a/linux-aio.c
+++ b/linux-aio.c
@@ -63,8 +63,8 @@ static void qemu_laio_process_completion(struct qemu_laio_state *s,
         } else if (ret >= 0) {
             /* Short reads mean EOF, pad with zeros. */
             if (laiocb->is_read) {
-                qemu_iovec_memset_skip(laiocb->qiov, 0,
-                    laiocb->qiov->size - ret, ret);
+                qemu_iovec_memset(laiocb->qiov, ret, 0,
+                    laiocb->qiov->size - ret);
             } else {
                 ret = -EINVAL;
             }
diff --git a/posix-aio-compat.c b/posix-aio-compat.c
index 68361f5..96e4daf 100644
--- a/posix-aio-compat.c
+++ b/posix-aio-compat.c
@@ -29,6 +29,7 @@
 #include "qemu-common.h"
 #include "trace.h"
 #include "block_int.h"
+#include "iov.h"
 
 #include "block/raw-posix-aio.h"
 
@@ -351,11 +352,8 @@ static void *aio_thread(void *unused)
             if (ret >= 0 && ret < aiocb->aio_nbytes && aiocb->common.bs->growable) {
                 /* A short read means that we have reached EOF. Pad the buffer
                  * with zeros for bytes after EOF. */
-                QEMUIOVector qiov;
-
-                qemu_iovec_init_external(&qiov, aiocb->aio_iov,
-                                         aiocb->aio_niov);
-                qemu_iovec_memset_skip(&qiov, 0, aiocb->aio_nbytes - ret, ret);
+                iov_memset(aiocb->aio_iov, aiocb->aio_niov, ret,
+                           0, aiocb->aio_nbytes - ret);
 
                 ret = aiocb->aio_nbytes;
             }
diff --git a/qemu-common.h b/qemu-common.h
index 91e0562..e752d2b 100644
--- a/qemu-common.h
+++ b/qemu-common.h
@@ -347,9 +347,8 @@ void qemu_iovec_destroy(QEMUIOVector *qiov);
 void qemu_iovec_reset(QEMUIOVector *qiov);
 void qemu_iovec_to_buffer(QEMUIOVector *qiov, void *buf);
 void qemu_iovec_from_buffer(QEMUIOVector *qiov, const void *buf, size_t count);
-void qemu_iovec_memset(QEMUIOVector *qiov, int c, size_t count);
-void qemu_iovec_memset_skip(QEMUIOVector *qiov, int c, size_t count,
-                            size_t skip);
+size_t qemu_iovec_memset(QEMUIOVector *qiov, size_t offset,
+                         int fillc, size_t bytes);
 
 bool buffer_is_zero(const void *buf, size_t len);
 
commit 2278a69e7020d86a8c73a28474e7709d3e7d5081
Author: Michael Tokarev <mjt at tls.msk.ru>
Date:   Thu Jun 7 20:08:19 2012 +0400

    rewrite iov_* functions
    
    This changes implementations of all iov_*
    functions, completing the previous step.
    
    All iov_* functions now ensure that this offset
    argument is within the iovec (using assertion),
    but lets to specify `bytes' value larger than
    actual length of the iovec - in this case they
    stops at the actual end of iovec.  It is also
    suggested to use convinient `-1' value as `bytes'
    to mean just this -- "up to the end".
    
    There's one very minor semantic change here: new
    requiriment is that `offset' points to inside of
    iovec.  This is checked just at the end of functions
    (assert()), it does not actually need to be enforced,
    but using any of these functions with offset pointing
    past the end of iovec is wrong anyway.
    
    Note: the new code in iov.c uses arithmetic with
    void pointers.  I thought this is not supported
    everywhere and is a GCC extension (indeed, the C
    standard does not define void arithmetic).  However,
    the original code already use void arith in
    iov_from_buf() function:
      (memcpy(..., buf + buf_off,...)
    which apparently works well so far (it is this
    way in qemu 1.0).  So I left it this way and used
    it in other places.
    
    While at it, add a unit-test file test-iov.c,
    to check various corner cases with iov_from_buf(),
    iov_to_buf() and iov_memset().
    
    Signed-off-by: Michael Tokarev <mjt at tls.msk.ru>

diff --git a/iov.c b/iov.c
index bc58cab..9657d28 100644
--- a/iov.c
+++ b/iov.c
@@ -7,6 +7,7 @@
  * Author(s):
  *  Anthony Liguori <aliguori at us.ibm.com>
  *  Amit Shah <amit.shah at redhat.com>
+ *  Michael Tokarev <mjt at tls.msk.ru>
  *
  * This work is licensed under the terms of the GNU GPL, version 2.  See
  * the COPYING file in the top-level directory.
@@ -17,75 +18,61 @@
 
 #include "iov.h"
 
-size_t iov_from_buf(struct iovec *iov, unsigned int iov_cnt, size_t iov_off,
-                    const void *buf, size_t size)
+size_t iov_from_buf(struct iovec *iov, unsigned int iov_cnt,
+                    size_t offset, const void *buf, size_t bytes)
 {
-    size_t iovec_off, buf_off;
+    size_t done;
     unsigned int i;
-
-    iovec_off = 0;
-    buf_off = 0;
-    for (i = 0; i < iov_cnt && size; i++) {
-        if (iov_off < (iovec_off + iov[i].iov_len)) {
-            size_t len = MIN((iovec_off + iov[i].iov_len) - iov_off, size);
-
-            memcpy(iov[i].iov_base + (iov_off - iovec_off), buf + buf_off, len);
-
-            buf_off += len;
-            iov_off += len;
-            size -= len;
+    for (i = 0, done = 0; (offset || done < bytes) && i < iov_cnt; i++) {
+        if (offset < iov[i].iov_len) {
+            size_t len = MIN(iov[i].iov_len - offset, bytes - done);
+            memcpy(iov[i].iov_base + offset, buf + done, len);
+            done += len;
+            offset = 0;
+        } else {
+            offset -= iov[i].iov_len;
         }
-        iovec_off += iov[i].iov_len;
     }
-    return buf_off;
+    assert(offset == 0);
+    return done;
 }
 
-size_t iov_to_buf(const struct iovec *iov, const unsigned int iov_cnt, size_t iov_off,
-                  void *buf, size_t size)
+size_t iov_to_buf(const struct iovec *iov, const unsigned int iov_cnt,
+                  size_t offset, void *buf, size_t bytes)
 {
-    uint8_t *ptr;
-    size_t iovec_off, buf_off;
+    size_t done;
     unsigned int i;
-
-    ptr = buf;
-    iovec_off = 0;
-    buf_off = 0;
-    for (i = 0; i < iov_cnt && size; i++) {
-        if (iov_off < (iovec_off + iov[i].iov_len)) {
-            size_t len = MIN((iovec_off + iov[i].iov_len) - iov_off , size);
-
-            memcpy(ptr + buf_off, iov[i].iov_base + (iov_off - iovec_off), len);
-
-            buf_off += len;
-            iov_off += len;
-            size -= len;
+    for (i = 0, done = 0; (offset || done < bytes) && i < iov_cnt; i++) {
+        if (offset < iov[i].iov_len) {
+            size_t len = MIN(iov[i].iov_len - offset, bytes - done);
+            memcpy(buf + done, iov[i].iov_base + offset, len);
+            done += len;
+            offset = 0;
+        } else {
+            offset -= iov[i].iov_len;
         }
-        iovec_off += iov[i].iov_len;
     }
-    return buf_off;
+    assert(offset == 0);
+    return done;
 }
 
 size_t iov_memset(const struct iovec *iov, const unsigned int iov_cnt,
-                 size_t iov_off, int fillc, size_t size)
+                  size_t offset, int fillc, size_t bytes)
 {
-    size_t iovec_off, buf_off;
+    size_t done;
     unsigned int i;
-
-    iovec_off = 0;
-    buf_off = 0;
-    for (i = 0; i < iov_cnt && size; i++) {
-        if (iov_off < (iovec_off + iov[i].iov_len)) {
-            size_t len = MIN((iovec_off + iov[i].iov_len) - iov_off , size);
-
-            memset(iov[i].iov_base + (iov_off - iovec_off), fillc, len);
-
-            buf_off += len;
-            iov_off += len;
-            size -= len;
+    for (i = 0, done = 0; (offset || done < bytes) && i < iov_cnt; i++) {
+        if (offset < iov[i].iov_len) {
+            size_t len = MIN(iov[i].iov_len - offset, bytes - done);
+            memset(iov[i].iov_base + offset, fillc, len);
+            done += len;
+            offset = 0;
+        } else {
+            offset -= iov[i].iov_len;
         }
-        iovec_off += iov[i].iov_len;
     }
-    return buf_off;
+    assert(offset == 0);
+    return done;
 }
 
 size_t iov_size(const struct iovec *iov, const unsigned int iov_cnt)
diff --git a/iov.h b/iov.h
index 0b4acf4..19ee3b3 100644
--- a/iov.h
+++ b/iov.h
@@ -1,10 +1,11 @@
 /*
- * Helpers for getting linearized buffers from iov / filling buffers into iovs
+ * Helpers for using (partial) iovecs.
  *
  * Copyright (C) 2010 Red Hat, Inc.
  *
  * Author(s):
  *  Amit Shah <amit.shah at redhat.com>
+ *  Michael Tokarev <mjt at tls.msk.ru>
  *
  * This work is licensed under the terms of the GNU GPL, version 2.  See
  * the COPYING file in the top-level directory.
@@ -28,6 +29,12 @@ size_t iov_size(const struct iovec *iov, const unsigned int iov_cnt);
  * only part of data will be copied, up to the end of the iovec.
  * Number of bytes actually copied will be returned, which is
  *  min(bytes, iov_size(iov)-offset)
+ * `Offset' must point to the inside of iovec.
+ * It is okay to use very large value for `bytes' since we're
+ * limited by the size of the iovec anyway, provided that the
+ * buffer pointed to by buf has enough space.  One possible
+ * such "large" value is -1 (sinice size_t is unsigned),
+ * so specifying `-1' as `bytes' means 'up to the end of iovec'.
  */
 size_t iov_from_buf(struct iovec *iov, unsigned int iov_cnt,
                     size_t offset, const void *buf, size_t bytes);
@@ -37,11 +44,12 @@ size_t iov_to_buf(const struct iovec *iov, const unsigned int iov_cnt,
 /**
  * Set data bytes pointed out by iovec `iov' of size `iov_cnt' elements,
  * starting at byte offset `start', to value `fillc', repeating it
- * `bytes' number of times.
+ * `bytes' number of times.  `Offset' must point to the inside of iovec.
  * If `bytes' is large enough, only last bytes portion of iovec,
  * up to the end of it, will be filled with the specified value.
  * Function return actual number of bytes processed, which is
  * min(size, iov_size(iov) - offset).
+ * Again, it is okay to use large value for `bytes' to mean "up to the end".
  */
 size_t iov_memset(const struct iovec *iov, const unsigned int iov_cnt,
                   size_t offset, int fillc, size_t bytes);
diff --git a/tests/Makefile b/tests/Makefile
index ab7f667..7340bc5 100644
--- a/tests/Makefile
+++ b/tests/Makefile
@@ -13,6 +13,7 @@ check-unit-y += tests/test-qmp-commands$(EXESUF)
 check-unit-y += tests/test-string-input-visitor$(EXESUF)
 check-unit-y += tests/test-string-output-visitor$(EXESUF)
 check-unit-y += tests/test-coroutine$(EXESUF)
+check-unit-y += tests/test-iov$(EXESUF)
 
 check-block-$(CONFIG_POSIX) += tests/qemu-iotests-quick.sh
 
@@ -47,6 +48,7 @@ tests/check-qlist$(EXESUF): tests/check-qlist.o qlist.o qint.o $(tools-obj-y)
 tests/check-qfloat$(EXESUF): tests/check-qfloat.o qfloat.o $(tools-obj-y)
 tests/check-qjson$(EXESUF): tests/check-qjson.o $(qobject-obj-y) $(tools-obj-y)
 tests/test-coroutine$(EXESUF): tests/test-coroutine.o $(coroutine-obj-y) $(tools-obj-y)
+tests/test-iov$(EXESUF): tests/test-iov.o iov.o
 
 tests/test-qapi-types.c tests/test-qapi-types.h :\
 $(SRC_PATH)/qapi-schema-test.json $(SRC_PATH)/scripts/qapi-types.py
diff --git a/tests/test-iov.c b/tests/test-iov.c
new file mode 100644
index 0000000..5f82296
--- /dev/null
+++ b/tests/test-iov.c
@@ -0,0 +1,153 @@
+#include <glib.h>
+#include "qemu-common.h"
+#include "iov.h"
+
+/* create a randomly-sized iovec with random vectors */
+static void iov_random(struct iovec **iovp, unsigned *iov_cntp)
+{
+     unsigned niov = g_test_rand_int_range(3,8);
+     struct iovec *iov = g_malloc(niov * sizeof(*iov));
+     unsigned i;
+     for (i = 0; i < niov; ++i) {
+         iov[i].iov_len = g_test_rand_int_range(5,20);
+         iov[i].iov_base = g_malloc(iov[i].iov_len);
+     }
+     *iovp = iov;
+     *iov_cntp = niov;
+}
+
+static void iov_free(struct iovec *iov, unsigned niov)
+{
+    unsigned i;
+    for (i = 0; i < niov; ++i) {
+        g_free(iov[i].iov_base);
+    }
+    g_free(iov);
+}
+
+static void test_iov_bytes(struct iovec *iov, unsigned niov,
+                           size_t offset, size_t bytes)
+{
+    unsigned i;
+    size_t j, o;
+    unsigned char *b;
+    o = 0;
+
+    /* we walk over all elements, */
+    for (i = 0; i < niov; ++i) {
+        b = iov[i].iov_base;
+        /* over each char of each element, */
+        for (j = 0; j < iov[i].iov_len; ++j) {
+            /* counting each of them and
+             * verifying that the ones within [offset,offset+bytes)
+             * range are equal to the position number (o) */
+            if (o >= offset && o < offset + bytes) {
+                g_assert(b[j] == (o & 255));
+            } else {
+                g_assert(b[j] == 0xff);
+            }
+            ++o;
+        }
+    }
+}
+
+static void test_to_from_buf_1(void)
+{
+     unsigned niov;
+     struct iovec *iov;
+     size_t sz;
+     unsigned char *ibuf, *obuf;
+     unsigned i, j, n;
+
+     iov_random(&iov, &niov);
+
+     sz = iov_size(iov, niov);
+
+     ibuf = g_malloc(sz + 8) + 4;
+     memcpy(ibuf-4, "aaaa", 4); memcpy(ibuf + sz, "bbbb", 4);
+     obuf = g_malloc(sz + 8) + 4;
+     memcpy(obuf-4, "xxxx", 4); memcpy(obuf + sz, "yyyy", 4);
+
+     /* fill in ibuf with 0123456... */
+     for (i = 0; i < sz; ++i) {
+         ibuf[i] = i & 255;
+     }
+
+     for (i = 0; i <= sz; ++i) {
+
+         /* Test from/to buf for offset(i) in [0..sz] up to the end of buffer.
+          * For last iteration with offset == sz, the procedure should
+          * skip whole vector and process exactly 0 bytes */
+
+         /* first set bytes [i..sz) to some "random" value */
+         n = iov_memset(iov, niov, 0, 0xff, -1);
+         g_assert(n == sz);
+
+         /* next copy bytes [i..sz) from ibuf to iovec */
+         n = iov_from_buf(iov, niov, i, ibuf + i, -1);
+         g_assert(n == sz - i);
+
+         /* clear part of obuf */
+         memset(obuf + i, 0, sz - i);
+         /* and set this part of obuf to values from iovec */
+         n = iov_to_buf(iov, niov, i, obuf + i, -1);
+         g_assert(n == sz - i);
+
+         /* now compare resulting buffers */
+         g_assert(memcmp(ibuf, obuf, sz) == 0);
+
+         /* test just one char */
+         n = iov_to_buf(iov, niov, i, obuf + i, 1);
+         g_assert(n == (i < sz));
+         if (n) {
+             g_assert(obuf[i] == (i & 255));
+         }
+
+         for (j = i; j <= sz; ++j) {
+             /* now test num of bytes cap up to byte no. j,
+              * with j in [i..sz]. */
+
+             /* clear iovec */
+             n = iov_memset(iov, niov, 0, 0xff, -1);
+             g_assert(n == sz);
+
+             /* copy bytes [i..j) from ibuf to iovec */
+             n = iov_from_buf(iov, niov, i, ibuf + i, j - i);
+             g_assert(n == j - i);
+
+             /* clear part of obuf */
+             memset(obuf + i, 0, j - i);
+
+             /* copy bytes [i..j) from iovec to obuf */
+             n = iov_to_buf(iov, niov, i, obuf + i, j - i);
+             g_assert(n == j - i);
+
+             /* verify result */
+             g_assert(memcmp(ibuf, obuf, sz) == 0);
+
+             /* now actually check if the iovec contains the right data */
+             test_iov_bytes(iov, niov, i, j - i);
+         }
+    }
+    g_assert(!memcmp(ibuf-4, "aaaa", 4) && !memcmp(ibuf+sz, "bbbb", 4));
+    g_free(ibuf-4);
+    g_assert(!memcmp(obuf-4, "xxxx", 4) && !memcmp(obuf+sz, "yyyy", 4));
+    g_free(obuf-4);
+    iov_free(iov, niov);
+}
+
+static void test_to_from_buf(void)
+{
+    int x;
+    for (x = 0; x < 4; ++x) {
+        test_to_from_buf_1();
+    }
+}
+
+int main(int argc, char **argv)
+{
+    g_test_init(&argc, &argv, NULL);
+    g_test_rand_int();
+    g_test_add_func("/basic/iov/from-to-buf", test_to_from_buf);
+    return g_test_run();
+}
commit dcf6f5e15ecee4f593eeacbe0591c1addc004d92
Author: Michael Tokarev <mjt at tls.msk.ru>
Date:   Sun Mar 11 18:05:12 2012 +0400

    change iov_* function prototypes to be more appropriate
    
    Reorder arguments to be more natural, readable and
    consistent with other iov_* functions, and change
    argument names, from:
     iov_from_buf(iov, iov_cnt, buf, iov_off, size)
    to
     iov_from_buf(iov, iov_cnt, offset, buf, bytes)
    
    The result becomes natural English:
    
     copy data to this `iov' vector with `iov_cnt'
     elements starting at byte offset `offset'
     from memory buffer `buf', processing `bytes'
     bytes max.
    
    (Try to read the original prototype this way).
    
    Also change iov_clear() to more general iov_memset()
    (it uses memset() internally anyway).
    
    While at it, add comments to the header file
    describing what the routines actually does.
    
    The patch only renames argumens in the header, but
    keeps old names in the implementation.  The next
    patch will touch actual code to match.
    
    Now, it might look wrong to pay so much attention
    to so small things.  But we've so many badly designed
    interfaces already so the whole thing becomes rather
    confusing or error prone.  One example of this is
    previous commit and small discussion which emerged
    from it, with an outcome that the utility functions
    like these aren't well-understdandable, leading to
    strange usage cases.  That's why I paid quite some
    attention to this set of functions and a few
    others in subsequent patches.
    
    Signed-off-by: Michael Tokarev <mjt at tls.msk.ru>

diff --git a/hw/rtl8139.c b/hw/rtl8139.c
index eb22d04..8128b64 100644
--- a/hw/rtl8139.c
+++ b/hw/rtl8139.c
@@ -1783,7 +1783,7 @@ static void rtl8139_transfer_frame(RTL8139State *s, uint8_t *buf, int size,
         if (iov) {
             buf2_size = iov_size(iov, 3);
             buf2 = g_malloc(buf2_size);
-            iov_to_buf(iov, 3, buf2, 0, buf2_size);
+            iov_to_buf(iov, 3, 0, buf2, buf2_size);
             buf = buf2;
         }
 
diff --git a/hw/usb/core.c b/hw/usb/core.c
index 0e02da7..2641685 100644
--- a/hw/usb/core.c
+++ b/hw/usb/core.c
@@ -522,10 +522,10 @@ void usb_packet_copy(USBPacket *p, void *ptr, size_t bytes)
     switch (p->pid) {
     case USB_TOKEN_SETUP:
     case USB_TOKEN_OUT:
-        iov_to_buf(p->iov.iov, p->iov.niov, ptr, p->result, bytes);
+        iov_to_buf(p->iov.iov, p->iov.niov, p->result, ptr, bytes);
         break;
     case USB_TOKEN_IN:
-        iov_from_buf(p->iov.iov, p->iov.niov, ptr, p->result, bytes);
+        iov_from_buf(p->iov.iov, p->iov.niov, p->result, ptr, bytes);
         break;
     default:
         fprintf(stderr, "%s: invalid pid: %x\n", __func__, p->pid);
@@ -539,7 +539,7 @@ void usb_packet_skip(USBPacket *p, size_t bytes)
     assert(p->result >= 0);
     assert(p->result + bytes <= p->iov.size);
     if (p->pid == USB_TOKEN_IN) {
-        iov_clear(p->iov.iov, p->iov.niov, p->result, bytes);
+        iov_memset(p->iov.iov, p->iov.niov, p->result, 0, bytes);
     }
     p->result += bytes;
 }
diff --git a/hw/virtio-balloon.c b/hw/virtio-balloon.c
index 075ed87..23effa4 100644
--- a/hw/virtio-balloon.c
+++ b/hw/virtio-balloon.c
@@ -77,7 +77,7 @@ static void virtio_balloon_handle_output(VirtIODevice *vdev, VirtQueue *vq)
         size_t offset = 0;
         uint32_t pfn;
 
-        while (iov_to_buf(elem.out_sg, elem.out_num, &pfn, offset, 4) == 4) {
+        while (iov_to_buf(elem.out_sg, elem.out_num, offset, &pfn, 4) == 4) {
             ram_addr_t pa;
             ram_addr_t addr;
 
@@ -118,7 +118,7 @@ static void virtio_balloon_receive_stats(VirtIODevice *vdev, VirtQueue *vq)
      */
     reset_stats(s);
 
-    while (iov_to_buf(elem->out_sg, elem->out_num, &stat, offset, sizeof(stat))
+    while (iov_to_buf(elem->out_sg, elem->out_num, offset, &stat, sizeof(stat))
            == sizeof(stat)) {
         uint16_t tag = tswap16(stat.tag);
         uint64_t val = tswap64(stat.val);
diff --git a/hw/virtio-net.c b/hw/virtio-net.c
index 3f190d4..533aa3d 100644
--- a/hw/virtio-net.c
+++ b/hw/virtio-net.c
@@ -656,8 +656,8 @@ static ssize_t virtio_net_receive(VLANClientState *nc, const uint8_t *buf, size_
         }
 
         /* copy in packet.  ugh */
-        len = iov_from_buf(sg, elem.in_num,
-                           buf + offset, 0, size - offset);
+        len = iov_from_buf(sg, elem.in_num, 0,
+                           buf + offset, size - offset);
         total += len;
         offset += len;
         /* If buffers can't be merged, at this point we
diff --git a/hw/virtio-serial-bus.c b/hw/virtio-serial-bus.c
index 1e477e5..728f218 100644
--- a/hw/virtio-serial-bus.c
+++ b/hw/virtio-serial-bus.c
@@ -106,8 +106,8 @@ static size_t write_to_port(VirtIOSerialPort *port,
             break;
         }
 
-        len = iov_from_buf(elem.in_sg, elem.in_num,
-                           buf + offset, 0, size - offset);
+        len = iov_from_buf(elem.in_sg, elem.in_num, 0,
+                           buf + offset, size - offset);
         offset += len;
 
         virtqueue_push(vq, &elem, len);
@@ -467,7 +467,7 @@ static void control_out(VirtIODevice *vdev, VirtQueue *vq)
             buf = g_malloc(cur_len);
             len = cur_len;
         }
-        iov_to_buf(elem.out_sg, elem.out_num, buf, 0, cur_len);
+        iov_to_buf(elem.out_sg, elem.out_num, 0, buf, cur_len);
 
         handle_control_message(vser, buf, cur_len);
         virtqueue_push(vq, &elem, 0);
diff --git a/iov.c b/iov.c
index 0f96493..bc58cab 100644
--- a/iov.c
+++ b/iov.c
@@ -17,8 +17,8 @@
 
 #include "iov.h"
 
-size_t iov_from_buf(struct iovec *iov, unsigned int iov_cnt,
-                    const void *buf, size_t iov_off, size_t size)
+size_t iov_from_buf(struct iovec *iov, unsigned int iov_cnt, size_t iov_off,
+                    const void *buf, size_t size)
 {
     size_t iovec_off, buf_off;
     unsigned int i;
@@ -40,8 +40,8 @@ size_t iov_from_buf(struct iovec *iov, unsigned int iov_cnt,
     return buf_off;
 }
 
-size_t iov_to_buf(const struct iovec *iov, const unsigned int iov_cnt,
-                  void *buf, size_t iov_off, size_t size)
+size_t iov_to_buf(const struct iovec *iov, const unsigned int iov_cnt, size_t iov_off,
+                  void *buf, size_t size)
 {
     uint8_t *ptr;
     size_t iovec_off, buf_off;
@@ -65,8 +65,8 @@ size_t iov_to_buf(const struct iovec *iov, const unsigned int iov_cnt,
     return buf_off;
 }
 
-size_t iov_clear(const struct iovec *iov, const unsigned int iov_cnt,
-                 size_t iov_off, size_t size)
+size_t iov_memset(const struct iovec *iov, const unsigned int iov_cnt,
+                 size_t iov_off, int fillc, size_t size)
 {
     size_t iovec_off, buf_off;
     unsigned int i;
@@ -77,7 +77,7 @@ size_t iov_clear(const struct iovec *iov, const unsigned int iov_cnt,
         if (iov_off < (iovec_off + iov[i].iov_len)) {
             size_t len = MIN((iovec_off + iov[i].iov_len) - iov_off , size);
 
-            memset(iov[i].iov_base + (iov_off - iovec_off), 0, len);
+            memset(iov[i].iov_base + (iov_off - iovec_off), fillc, len);
 
             buf_off += len;
             iov_off += len;
diff --git a/iov.h b/iov.h
index 94d2f78..0b4acf4 100644
--- a/iov.h
+++ b/iov.h
@@ -12,12 +12,44 @@
 
 #include "qemu-common.h"
 
+/**
+ * count and return data size, in bytes, of an iovec
+ * starting at `iov' of `iov_cnt' number of elements.
+ */
+size_t iov_size(const struct iovec *iov, const unsigned int iov_cnt);
+
+/**
+ * Copy from single continuous buffer to scatter-gather vector of buffers
+ * (iovec) and back like memcpy() between two continuous memory regions.
+ * Data in single continuous buffer starting at address `buf' and
+ * `bytes' bytes long will be copied to/from an iovec `iov' with
+ * `iov_cnt' number of elements, starting at byte position `offset'
+ * within the iovec.  If the iovec does not contain enough space,
+ * only part of data will be copied, up to the end of the iovec.
+ * Number of bytes actually copied will be returned, which is
+ *  min(bytes, iov_size(iov)-offset)
+ */
 size_t iov_from_buf(struct iovec *iov, unsigned int iov_cnt,
-                    const void *buf, size_t iov_off, size_t size);
+                    size_t offset, const void *buf, size_t bytes);
 size_t iov_to_buf(const struct iovec *iov, const unsigned int iov_cnt,
-                  void *buf, size_t iov_off, size_t size);
-size_t iov_size(const struct iovec *iov, const unsigned int iov_cnt);
-size_t iov_clear(const struct iovec *iov, const unsigned int iov_cnt,
-                 size_t iov_off, size_t size);
+                  size_t offset, void *buf, size_t bytes);
+
+/**
+ * Set data bytes pointed out by iovec `iov' of size `iov_cnt' elements,
+ * starting at byte offset `start', to value `fillc', repeating it
+ * `bytes' number of times.
+ * If `bytes' is large enough, only last bytes portion of iovec,
+ * up to the end of it, will be filled with the specified value.
+ * Function return actual number of bytes processed, which is
+ * min(size, iov_size(iov) - offset).
+ */
+size_t iov_memset(const struct iovec *iov, const unsigned int iov_cnt,
+                  size_t offset, int fillc, size_t bytes);
+
+/**
+ * Produce a text hexdump of iovec `iov' with `iov_cnt' number of elements
+ * in file `fp', prefixing each line with `prefix' and processing not more
+ * than `limit' data bytes.
+ */
 void iov_hexdump(const struct iovec *iov, const unsigned int iov_cnt,
                  FILE *fp, const char *prefix, size_t limit);
diff --git a/net.c b/net.c
index 4aa416c..abf0fd0 100644
--- a/net.c
+++ b/net.c
@@ -544,7 +544,7 @@ static ssize_t vc_sendv_compat(VLANClientState *vc, const struct iovec *iov,
     uint8_t buffer[4096];
     size_t offset;
 
-    offset = iov_to_buf(iov, iovcnt, buffer, 0, sizeof(buffer));
+    offset = iov_to_buf(iov, iovcnt, 0, buffer, sizeof(buffer));
 
     return vc->info->receive(vc, buffer, offset);
 }
commit 45270ad8a86a80cca4c59dfa73d9a9ee0688d781
Author: Michael Tokarev <mjt at tls.msk.ru>
Date:   Sun Mar 11 17:52:59 2012 +0400

    virtio-serial-bus: use correct lengths in control_out() message
    
    Original code has one thing to process (cur_len), requests to
    convert from iovec to buf another thing (len which is actually max_len),
    and processes something else (copied).  Whole thing is very difficult
    to understand, even if it does a right thing.  The iov_to_buf()
    conversion in this case will always return cur_len, because it is
    the length of the iovec it was asked to process, and the size we
    asked to convert is the same or larger, and iov_to_buf() will stop
    at reaching either iov or buf.
    
    Make the code saner by doing the only sane thing: dropping `copied'
    which is always the same as `cur_len' but just introduces questions.
    
    Signed-off-by: Michael Tokarev <mjt at tls.msk.ru>

diff --git a/hw/virtio-serial-bus.c b/hw/virtio-serial-bus.c
index 72287d1..1e477e5 100644
--- a/hw/virtio-serial-bus.c
+++ b/hw/virtio-serial-bus.c
@@ -454,7 +454,7 @@ static void control_out(VirtIODevice *vdev, VirtQueue *vq)
     len = 0;
     buf = NULL;
     while (virtqueue_pop(vq, &elem)) {
-        size_t cur_len, copied;
+        size_t cur_len;
 
         cur_len = iov_size(elem.out_sg, elem.out_num);
         /*
@@ -467,9 +467,9 @@ static void control_out(VirtIODevice *vdev, VirtQueue *vq)
             buf = g_malloc(cur_len);
             len = cur_len;
         }
-        copied = iov_to_buf(elem.out_sg, elem.out_num, buf, 0, len);
+        iov_to_buf(elem.out_sg, elem.out_num, buf, 0, cur_len);
 
-        handle_control_message(vser, buf, copied);
+        handle_control_message(vser, buf, cur_len);
         virtqueue_push(vq, &elem, 0);
     }
     g_free(buf);


More information about the Spice-commits mailing list